vercel / arg

Simple argument parsing
https://npmjs.com/arg
MIT License
1.23k stars 54 forks source link

Flags with optional values #61

Open JuanM04 opened 2 years ago

JuanM04 commented 2 years ago

Is there a way to have optional flag values? Something like the following:

const arg = require('arg');

const args = arg({
    '--port': Number, // --port <number>
    '--host': String.optional, // --host [string]
});

Given --port 5432 --host localhost it should return { _: [], port: 5432, host: 'localhost' }, given --port 5432 --host it should return something like { _: [], port: 5432, host: true }, and given --port 5432 it should return { _: [], port: 5432 },

cspotcode commented 1 year ago

I'd like this for ts-node to emulate the behavior of node's -p flag. node -p 123 is equivalent to node -pe 123

psychobolt commented 10 months ago

Workaround is to pass the permissive flag and use a string type, then find the arg value manually:

// cmd.js
const defaultSince = 'origin/main';

const { _ = [], ..args } = arg({
  '--since': defaultSince
}, { permissive: true });

console.log(_);

const sinceIndex = _.indexOf('--since');
if (sinceIndex > -1) {
  console.log(_[sinceIndex + 1]);
}
node cmd.js --since develop

# [ '--since', 'develop' ]
# develop