node icon indicating copy to clipboard operation
node copied to clipboard

parseArgs with type: "boolean" and default: true does not allow a false value

Open mcollina opened this issue 1 year ago • 4 comments

Consider the following example:

import { parseArgs } from 'node:util'

const options = {
  foo: {
    type: 'boolean',
    short: 'f',
    default: true
  },
};

function parseAndLog (args, options) {
  console.log('---');
  try {
    console.log('args:', args);
    const {
      values,
      positionals,
    } = parseArgs({ args, options });
    console.log(values, positionals);
  } catch (e) {
    console.error(e);
  }
}

parseAndLog(['--foo', 'false'], options);
parseAndLog(['--no-foo'], options);

How can somebody add a flag that can be defaulted as true, but allow a --no flag to set it to false? I imagine that a type: "boolean" setting would add both --flag and --no-flag.

mcollina avatar May 22 '24 08:05 mcollina

I see many node configuration use this bidirectional flag format, I'm willing to implement it in parseArgs

kylo5aby avatar May 22 '24 09:05 kylo5aby

The bidirectional flag format is really common here because it allows to change the default of the flag in a follow-up major.

mcollina avatar May 22 '24 09:05 mcollina

This can be done using the tokens array, though it does require about a dozen lines of boilerplate.

bakkot avatar May 22 '24 21:05 bakkot

In fact, the same example of adding support for negation from the parseArgs repo (linked above) is also used as the example use of tokens in the Node.js documentation:

  • https://nodejs.org/docs/latest/api/util.html#parseargs-tokens

shadowspawn avatar May 24 '24 03:05 shadowspawn

Fixed by https://github.com/nodejs/node/pull/53107, presumably?

bakkot avatar Jul 16 '24 00:07 bakkot

Fixed by https://github.com/nodejs/node/pull/53107, presumably?

I believe that was the intent, so I've closed this

avivkeller avatar Jul 16 '24 21:07 avivkeller