Coder Social home page Coder Social logo

minimist-lite's Introduction

minimist-lite npm bundle size package dependency count Known Vulnerabilities

parse argument options

This module is the guts of optimist's argument parser without all the fanciful decoration.


The original minimist repo have been picked up by devs and is now available again under the original name:

https://github.com/minimistjs/minimist

Please use that package instead of this, as minimist-lite will only get security updates in the future, no further development is to be expected!

more info here: #27


Installation

With npm do:

npm install minimist-lite

With yarn do:

yarn add minimist-lite

License

MIT License. See LICENSE for details.

Examples

See example/parse.js:

var argv = require('minimist-lite')(process.argv.slice(2));

console.log(argv);

Running node example/parse.js with arguments shows how they are parsed by minimist:

No arguments

With no arguments minimist returns an object with a single key "_" (underscore) with a value of an empty array:

$ node example/parse.js
{ _: [] }

Arguments without dashes

Using arguments with no dashes adds them to the "_" array in the object returned by minimist:

$ node example/parse.js abc def
{ _: [ 'abc', 'def' ] }

Single-letter options

A single dash starts a single-letter option that are boolean by default:

$ node example/parse.js -a -b -c
{ _: [], a: true, b: true, c: true }

Single-letter options can be joined together:

$ node example/parse.js -abc
{ _: [], a: true, b: true, c: true }

When a single-letter option is followed by a value with no dashes, the option gets that value in the returned object instead of a boolean value:

$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }

Numeric values can be joined with single-letter options:

$ node example/parse.js -a 1 -b2
{ _: [], a: 1, b: 2 }

Multi-letter options

Multi-letter options start with double dashes and they are boolean by default:

$ node example/parse.js --abc --def
{ _: [], abc: true, def: true }

Values can follow multi-letter options after a space or equal sign:

$ node example/parse.js --abc 1 --def=2
{ _: [], abc: 1, def: 2 }

--no- prefix handling

Options with the prefix --no- will be treated as a flag that has the value false by default:

$ node example/parse.js --no-abc
{ _: [], abc: false }

$ node example/parse.js --no-abc true
{ _: ['true'], abc: false }

Mixed styles

All of those styles can be used together:

$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop --hoo:haa foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
  x: 3,
  y: 4,
  n: 5,
  a: true,
  b: true,
  c: true,
  hoo: [haa],
  beep: 'boop' }

The default parsing of the arguments can be changed by using the second argument to the parsing method, see below.

Repeated options

If an option is provided more than once, the returned object value for that option will be an array (rather than a boolean or a string):

$ node example/parse.js --foo=bar --foo=baz
{ _: [], foo: [ 'bar', 'baz' ] }

Methods

Minimist exports a single method:

var parseArgs = require('minimist-lite');

var argv = parseArgs(args, opts={})

Return an argument object argv populated with the array arguments from args.

argv._ contains all the arguments that didn't have an option associated with them, or an empty array if there were no such arguments.

Numeric-looking arguments will be returned as numbers unless opts.string or opts.boolean is set for that argument name.

Any arguments after '--' will not be parsed and will end up in argv._.

Options

options can be:

  • opts.string - a string or array of strings with argument names to always treat as strings

  • opts.array - a string or array of strings argument names to always treat as array values

  • opts.boolean - a boolean, string or array of strings to always treat as booleans. if true will treat all double hyphenated arguments without equal signs as boolean (e.g. affects --foo, not -f or --foo=bar)

  • opts.alias - an object mapping string names to strings or arrays of string argument names to use as aliases

  • opts.default - an object mapping string argument names to default values

  • opts.stopEarly - when true, populate argv._ with everything after the first non-option

  • opts['--'] - when true, populate argv._ with everything before the -- and argv['--'] with everything after the --. Here's an example:

    > require('./')('one two three -- four five --six'.split(' '), { '--': true })
    { _: [ 'one', 'two', 'three' ],
      '--': [ 'four', 'five', '--six' ] }
    

    Note that with opts['--'] set, parsing for arguments still stops after the --.

  • opts.unknown - a function which is invoked with a command line parameter not defined in the opts configuration object. If the function returns false, the unknown option is not added to argv.

minimist-lite's People

Contributors

bogusfocused avatar caitp avatar coleste avatar dependabot[bot] avatar dominictarr avatar jdiamond avatar jeffbski avatar joaomoreno avatar lydell avatar m1kc avatar max-mapper avatar meszaros-lajos-gyorgy avatar micalevisk avatar okdistribute avatar sanjosolutions avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

minimist-lite's Issues

BUG: function unknown called for non-options

Original issue by @johndeighan at https://github.com/substack/minimist/issues/161

when I pass this to parseArgs() (using 'import parseArgs from 'minimist';' in an ES6 module'):

[ 'test/TopMenuShort.starbucks' ]

For example, my command line is node myscript.js test/TopMenuShort.starbucks, my "unknown" function is called, and this is output (though I've realized that this line is printed by my "unknown" function):

Unknown option: -test/TopMenuShort.starbucks

But the return value from parseArgs() is correct:

{
  _: [ 'test/TopMenuShort.starbucks' ],
  c: false,
  j: false,
  s: false,
  h: false,
  d: false
}

My work around is to simply return true from my "unknown" function, but that still has the problem that I can't just print the "unknown option" error message. I'm pretty sure that the function should only be called for unknown options, not for non-options on the command line.

Add option to disable numeric conversion for arguments

Original issue by @whitlockjc at https://github.com/substack/minimist/issues/36

const argv = require('minimist-lite')(process.argv.slice(2))
console.dir(argv)

If I invoke my command using my-command 2.3, I end up with something like this:

{ _: [ 2.3 ] }

I realize if this was an option I could use opts.string to tell minimist to treat my option as a string but looks like there's no way to achieve the same for argument.

What I expect instead:

{ _: [ '2.3' ] }

New Feature : Allow for array in flag options

Would be really usefull if options could take a list of values
currently if I need to pass a list of value for a given option I have to repeat the flag :

bin -a fr -a be -a us
# will return { ..... a: ['fr', 'be', 'us'] }

What if we could parse :

bin -a fr,be,us
# and return { ..... a: ['fr', 'be', 'us'] }

of course there will be a debate on the separator, which should be an option.
This behavior could be trigger with the array option, if a separator option is provided.

just check this :

"a,z,e,r,t".split(undefined) // Array [ "a,z,e,r,t" ]
"a,z,e,r,t".split(',') // Array(5) [ "a", "z", "e", "r", "t" ]

Anybody interested in this ?

Proposal: Adding option for longer arguments names

So I thought if we'd be able to add support for longer names (currently it supports only "one letter" arguments). I have small issue because I'd like to add longer arguments. Like

const argvs = require("minimist")(process.argv.slice(2));

console.log(argvs)

if (argvs.th || argvs.templateHelp) {
    templateHelp();
}

if (argvs.h || argvs.help) {
    help();
}

So when I call node index.js -th  this will call for templateHelp() function, not the help() one (because it divides arguments into argvs: { _: [], t: true, h: true })

Automate publishing on NPM registry using GitHub Actions. And add CI workflow

Currently only you (I guess) can release new versions of this package.

We could use GitHub actions to automatically publish new versions to NPM registry after some event on this repo.

My proposal: publish on new releases on this repo.
An example of an workflow that publish the package on new Git Tags (that could be easily adapted): https://github.com/micalevisk/nestjs-swagger-api-http-response-decorators/blob/main/.github/workflows/publish-on-new-tag.yml

You just need to add a secret called NPM_TOKEN with your NPM access token into this repo.


Also, to make thinks more safer, we can add another CI workflow that will be triggered on every PR that change some code. It will ran automated tests & coverage report. So we'll make sure that only good PRs are merged to the main branch.


To implement this, I need to know a bit more about how is the current workflow from changing the code til release a new version.

Auto converting hex values to numbers

Original issue by @dimabru at https://github.com/substack/minimist/issues/149

Hex parameters get auto-converted to numbers.
This results in a loss of information and change of values since hex values often exceed max int.

example:
input args --a 0xffffffffffffffffffff

code:
console.log(process.argv.slice(2));
let args = minimist(process.argv.slice(2));
console.log(args['a']);
console.log(args['a'].toString(16));

console output:
image

100000000000000000000 is clearly !== 0xffffffffffffffffffff

TypeScript Definitions Not Included in Package

Hey all!

Thanks for forking minimist, it's nice to see work being done on an abandoned project once more. I pulled this project into my application and noticed TypeScript was complaining saying Could not find a declaration file for module 'minimist-lite'. I saw that you have an index.d.ts in the repo and looked in the package itself to investigate. To my surprise, I saw that the d.ts wasn't included with the packaged module (see the attached screenshot for details)

Screen Shot 2022-01-23 at 2 36 58 PM

As a workaround I've created an empty minimist-lite.d.ts with the contents declare module 'minimist-lite';, but I know this isn't a sustainable route to take moving forward

Release 2.2.0

@micalevisk whad do you think, is the current master ready to be released or is there anything else we can add? We could start creating version labels and add those to the individual tickets. I'll set up github projects page and we can add ideas there as well.

patch high vunerability on transitive development dependency

npm audit report

cached-path-relative  <1.1.0
Severity: high
Prototype Pollution in cached-path-relative - https://github.com/advisories/GHSA-wg6g-ppvx-927h
fix available via `npm audit fix`
node_modules/cached-path-relative

1 high severity vulnerability
[email protected] /tmp/minimist-lite
└─┬ [email protected]
  └─┬ [email protected]
    ├── [email protected]
    └─┬ [email protected]
      └── [email protected] deduped

solution

npm audit fix

will touch the lock file.

Seems parse error for this case

Original issue by @poppinlp at https://github.com/substack/minimist/issues/154

I've run the code like node index.js -a="aaa=bbb" --a2="aaa=bbb"
And here are the output for process.argv, minimist parsed result and yargs-parser parsed result:

origin argv [
  'blabla/.nvm/versions/node/v14.7.0/bin/node',
  'blabla not important',
  '-a=aaa=bbb',
  '--a2=aaa=bbb'
]
minimist { _: [], a: 'aaa', a2: 'aaa=bbb' }
yargs parser { _: [], a: 'aaa=bbb', a2: 'aaa=bbb' }

You could see, for -a, minimist seems to get the wrong result.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.