Skip to content

Commit

Permalink
fix: enforce undefined or - for stdin only flags
Browse files Browse the repository at this point in the history
  • Loading branch information
mdonnalley committed Feb 2, 2024
1 parent 7b58e1b commit 472b934
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/parser/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ export class Parser<
public async parse(): Promise<ParserOutput<TFlags, BFlags, TArgs>> {
this._debugInput()

// eslint-disable-next-line complexity
const parseFlag = async (arg: string): Promise<boolean> => {
const {isLong, name} = this.findFlag(arg)
if (!name) {
Expand Down Expand Up @@ -169,6 +170,12 @@ export class Parser<
this.currentFlag = flag
let input = isLong || arg.length < 3 ? this.argv.shift() : arg.slice(arg[2] === '=' ? 3 : 2)

if (flag.allowStdin === 'only' && input !== '-' && input !== undefined) {
throw new CLIError(
`Flag --${name} can only be read from stdin. The value must be "-" or not provided at all.`,
)
}

if ((flag.allowStdin && input === '-') || flag.allowStdin === 'only') {
const stdin = await readStdin()
if (stdin) {
Expand Down
20 changes: 20 additions & 0 deletions test/parser/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1919,4 +1919,24 @@ describe('allowStdin', () => {
expect(out.flags.myflag).to.equals(stdinValue)
expect(out.raw[0].input).to.equal('x')
})

it('should throw if allowStdin is "only" but value is not "-" or undefined', async () => {
sandbox.stub(parser, 'readStdin').returns(stdinPromise)
try {
await parse(['--myflag', 'INVALID'], {
flags: {
myflag: Flags.string({allowStdin: 'only'}),
},
})
expect.fail('Should have thrown an error')
} catch (error) {
if (error instanceof CLIError) {
expect(error.message).to.equal(
'Flag --myflag can only be read from stdin. The value must be "-" or not provided at all.',
)
} else {
expect.fail('Should have thrown a CLIError')
}
}
})
})

0 comments on commit 472b934

Please sign in to comment.