Skip to content

Commit

Permalink
Merge pull request #380 from oclif/sm/dont-parse-default
Browse files Browse the repository at this point in the history
fix: parsing the default is wrong types
  • Loading branch information
mshanemc committed Feb 28, 2022
2 parents 6375945 + 4a8fc76 commit ad5b108
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 6 deletions.
8 changes: 2 additions & 6 deletions src/parser/parse.ts
Expand Up @@ -208,12 +208,8 @@ export class Parser<T extends ParserInput, TFlags extends OutputFlags<T['flags']
if (!(k in flags) && flag.default !== undefined) {
this.metaData.flags[k] = {setFromDefault: true}
// eslint-disable-next-line no-await-in-loop
const defaultValue = (typeof flag.default === 'function' ? await flag.default({options: flag, flags, ...this.context}) : flag.default) as string
const parsedValue = flag.type === 'option' && flag.parse ?
// eslint-disable-next-line no-await-in-loop
await flag.parse(defaultValue, this.context) :
defaultValue
flags[k] = parsedValue
const defaultValue = (typeof flag.default === 'function' ? await flag.default({options: flag, flags, ...this.context}) : flag.default)
flags[k] = defaultValue
}
}

Expand Down
49 changes: 49 additions & 0 deletions test/parser/parse.test.ts
Expand Up @@ -436,6 +436,55 @@ See more help with --help`)
expect(out.argv).to.deep.equal([100])
})

it('parse with a default does not parse default', async () => {
const out = await parse([], {
flags: {foo: flags.string({parse: async input => input.toUpperCase(), default: 'baz'})},
})
expect(out.flags).to.deep.include({foo: 'baz'})
})

describe('parse with a default/value of another type (class)', async () => {
class TestClass {
public prop: string;
constructor(input: string) {
this.prop = input
}
}
it('uses default via value', async () => {
const out = await parse([], {
flags: {
foo: flags.build<TestClass>({
parse: async input => new TestClass(input),
default: new TestClass('baz'),
})(),
},
})
expect(out.flags.foo?.prop).to.equal('baz')
})
it('uses default via function', async () => {
const out = await parse([], {
flags: {
foo: flags.build<TestClass>({
parse: async input => new TestClass(input),
default: async () => new TestClass('baz'),
})(),
},
})
expect(out.flags.foo?.prop).to.equal('baz')
})
it('uses parser when value provided', async () => {
const out = await parse(['--foo=bar'], {
flags: {
foo: flags.build<TestClass>({
parse: async input => new TestClass(input),
default: new TestClass('baz'),
})(),
},
})
expect(out.flags.foo?.prop).to.equal('bar')
})
})

// it('gets arg/flag in context', async () => {
// const out = await parse({
// args: [{ name: 'num', parse: (_, ctx) => ctx.arg.name!.toUpperCase() }],
Expand Down

0 comments on commit ad5b108

Please sign in to comment.