Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

flags without argument ('empty flags') are hard to use as boolean flag #604

Open
scarf005 opened this issue Jun 6, 2023 · 3 comments
Open

Comments

@scarf005
Copy link
Contributor

scarf005 commented Jun 6, 2023

Summary

  • option("--empty-flag", "boolean switch") may cause surprising behavior with default value.
  • while there's negatable flag, it may be preferable to not provide one for conciseness.

case 1: empty flag cannot be used as boolean

const boolToStr = (b: boolean) => b ? "true" : "false"

const test1 = await new Command()
  .option("--bool-value", "boolean switch")
  .action(({ boolValue }) => console.log(boolToStr(boolValue))) // type error
  .parse(["--bool-value"])
// boolValue: true | undefined

case 2: default option causes footgun behavior (always evaluates to false)

const { options } = await new Command()
  .option("--bool-value", "boolean switch", { default: false })
  .parse(["--bool-value"])
// boolValue: boolean

however, boolValue always evaluates to false regardless of whether flag is provided.

const { options } = await new Command()
  .option("--bool-value", "boolean switch", { value: (x) => !!x, default: false })
  .parse(Deno.args)

console.log({ options })

similarly, default property completely overrides value mapper.

case 3: default value can be only used for action params

const test3 = await new Command()
  .option("--bool-value", "boolean switch")
  .action(({ boolValue = false }) => console.log(boolValue))
// boolValue: boolean

Possible Solutions?

  • document the behavior
  • making default: false overridable for empty flags
@c4spar
Copy link
Owner

c4spar commented Jun 6, 2023

case 1: empty flag cannot be used as boolean

Yeah, i noticed this as well. Maybe we should set the default value by default to false for boolean flags with no or with optional value.

case 2: default option causes footgun behavior (always evaluates to false)

This was a bug and is already fixed. Will be available in the next release.

@scarf005
Copy link
Contributor Author

scarf005 commented Jun 6, 2023

that's good to know. would i make a PR for case 1?

@c4spar
Copy link
Owner

c4spar commented Jun 9, 2023

I think if we adjust the boolean type to always be a boolean, we should also adjust collectible options to always be an array.
Feel free to open a PR, but the typings for the command module are a bit complex. Let me know if you need help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants