CoolFace
Apppublic

Umama-at-Bluchip/Quick-UI

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
README.md414 linesDownload Raw Back to parseargs
1<!-- omit in toc -->2# parseArgs3 4[![Coverage][coverage-image]][coverage-url]5 6Polyfill of `util.parseArgs()`7 8## `util.parseArgs([config])`9 10<!-- YAML11added: v18.3.012changes:13  - version: REPLACEME14    pr-url: https://github.com/nodejs/node/pull/4345915    description: add support for returning detailed parse information16                 using `tokens` in input `config` and returned properties.17-->18 19> Stability: 1 - Experimental20 21* `config` {Object} Used to provide arguments for parsing and to configure22  the parser. `config` supports the following properties:23  * `args` {string\[]} array of argument strings. **Default:** `process.argv`24    with `execPath` and `filename` removed.25  * `options` {Object} Used to describe arguments known to the parser.26    Keys of `options` are the long names of options and values are an27    {Object} accepting the following properties:28    * `type` {string} Type of argument, which must be either `boolean` or `string`.29    * `multiple` {boolean} Whether this option can be provided multiple30      times. If `true`, all values will be collected in an array. If31      `false`, values for the option are last-wins. **Default:** `false`.32    * `short` {string} A single character alias for the option.33    * `default` {string | boolean | string\[] | boolean\[]} The default option34      value when it is not set by args. It must be of the same type as the35      the `type` property. When `multiple` is `true`, it must be an array.36  * `strict` {boolean} Should an error be thrown when unknown arguments37    are encountered, or when arguments are passed that do not match the38    `type` configured in `options`.39    **Default:** `true`.40  * `allowPositionals` {boolean} Whether this command accepts positional41    arguments.42    **Default:** `false` if `strict` is `true`, otherwise `true`.43  * `tokens` {boolean} Return the parsed tokens. This is useful for extending44    the built-in behavior, from adding additional checks through to reprocessing45    the tokens in different ways.46    **Default:** `false`.47 48* Returns: {Object} The parsed command line arguments:49  * `values` {Object} A mapping of parsed option names with their {string}50    or {boolean} values.51  * `positionals` {string\[]} Positional arguments.52  * `tokens` {Object\[] | undefined} See [parseArgs tokens](#parseargs-tokens)53    section. Only returned if `config` includes `tokens: true`.54 55Provides a higher level API for command-line argument parsing than interacting56with `process.argv` directly. Takes a specification for the expected arguments57and returns a structured object with the parsed options and positionals.58 59```mjs60import { parseArgs } from 'node:util';61const args = ['-f', '--bar', 'b'];62const options = {63  foo: {64    type: 'boolean',65    short: 'f'66  },67  bar: {68    type: 'string'69  }70};71const {72  values,73  positionals74} = parseArgs({ args, options });75console.log(values, positionals);76// Prints: [Object: null prototype] { foo: true, bar: 'b' } []77```78 79```cjs80const { parseArgs } = require('node:util');81const args = ['-f', '--bar', 'b'];82const options = {83  foo: {84    type: 'boolean',85    short: 'f'86  },87  bar: {88    type: 'string'89  }90};91const {92  values,93  positionals94} = parseArgs({ args, options });95console.log(values, positionals);96// Prints: [Object: null prototype] { foo: true, bar: 'b' } []97```98 99`util.parseArgs` is experimental and behavior may change. Join the100conversation in [pkgjs/parseargs][] to contribute to the design.101 102### `parseArgs` `tokens`103 104Detailed parse information is available for adding custom behaviours by105specifying `tokens: true` in the configuration.106The returned tokens have properties describing:107 108* all tokens109  * `kind` {string} One of 'option', 'positional', or 'option-terminator'.110  * `index` {number} Index of element in `args` containing token. So the111    source argument for a token is `args[token.index]`.112* option tokens113  * `name` {string} Long name of option.114  * `rawName` {string} How option used in args, like `-f` of `--foo`.115  * `value` {string | undefined} Option value specified in args.116    Undefined for boolean options.117  * `inlineValue` {boolean | undefined} Whether option value specified inline,118    like `--foo=bar`.119* positional tokens120  * `value` {string} The value of the positional argument in args (i.e. `args[index]`).121* option-terminator token122 123The returned tokens are in the order encountered in the input args. Options124that appear more than once in args produce a token for each use. Short option125groups like `-xy` expand to a token for each option. So `-xxx` produces126three tokens.127 128For example to use the returned tokens to add support for a negated option129like `--no-color`, the tokens can be reprocessed to change the value stored130for the negated option.131 132```mjs133import { parseArgs } from 'node:util';134 135const options = {136  'color': { type: 'boolean' },137  'no-color': { type: 'boolean' },138  'logfile': { type: 'string' },139  'no-logfile': { type: 'boolean' },140};141const { values, tokens } = parseArgs({ options, tokens: true });142 143// Reprocess the option tokens and overwrite the returned values.144tokens145  .filter((token) => token.kind === 'option')146  .forEach((token) => {147    if (token.name.startsWith('no-')) {148      // Store foo:false for --no-foo149      const positiveName = token.name.slice(3);150      values[positiveName] = false;151      delete values[token.name];152    } else {153      // Resave value so last one wins if both --foo and --no-foo.154      values[token.name] = token.value ?? true;155    }156  });157 158const color = values.color;159const logfile = values.logfile ?? 'default.log';160 161console.log({ logfile, color });162```163 164```cjs165const { parseArgs } = require('node:util');166 167const options = {168  'color': { type: 'boolean' },169  'no-color': { type: 'boolean' },170  'logfile': { type: 'string' },171  'no-logfile': { type: 'boolean' },172};173const { values, tokens } = parseArgs({ options, tokens: true });174 175// Reprocess the option tokens and overwrite the returned values.176tokens177  .filter((token) => token.kind === 'option')178  .forEach((token) => {179    if (token.name.startsWith('no-')) {180      // Store foo:false for --no-foo181      const positiveName = token.name.slice(3);182      values[positiveName] = false;183      delete values[token.name];184    } else {185      // Resave value so last one wins if both --foo and --no-foo.186      values[token.name] = token.value ?? true;187    }188  });189 190const color = values.color;191const logfile = values.logfile ?? 'default.log';192 193console.log({ logfile, color });194```195 196Example usage showing negated options, and when an option is used197multiple ways then last one wins.198 199```console200$ node negate.js201{ logfile: 'default.log', color: undefined }202$ node negate.js --no-logfile --no-color203{ logfile: false, color: false }204$ node negate.js --logfile=test.log --color205{ logfile: 'test.log', color: true }206$ node negate.js --no-logfile --logfile=test.log --color --no-color207{ logfile: 'test.log', color: false }208```209 210-----211 212<!-- omit in toc -->213## Table of Contents214- [`util.parseArgs([config])`](#utilparseargsconfig)215- [Scope](#scope)216- [Version Matchups](#version-matchups)217- [๐Ÿš€ Getting Started](#-getting-started)218- [๐Ÿ™Œ Contributing](#-contributing)219- [๐Ÿ’ก `process.mainArgs` Proposal](#-processmainargs-proposal)220  - [Implementation:](#implementation)221- [๐Ÿ“ƒ Examples](#-examples)222- [F.A.Qs](#faqs)223- [Links & Resources](#links--resources)224 225-----226 227## Scope228 229It is already possible to build great arg parsing modules on top of what Node.js provides; the prickly API is abstracted away by these modules. Thus, process.parseArgs() is not necessarily intended for library authors; it is intended for developers of simple CLI tools, ad-hoc scripts, deployed Node.js applications, and learning materials.230 231It is exceedingly difficult to provide an API which would both be friendly to these Node.js users while being extensible enough for libraries to build upon. We chose to prioritize these use cases because these are currently not well-served by Node.js' API.232 233----234 235## Version Matchups236 237| Node.js | @pkgjs/parseArgs |238| -- | -- |239| [v18.3.0](https://nodejs.org/docs/latest-v18.x/api/util.html#utilparseargsconfig) | [v0.9.1](https://github.com/pkgjs/parseargs/tree/v0.9.1#utilparseargsconfig) |240| [v16.17.0](https://nodejs.org/dist/latest-v16.x/docs/api/util.html#utilparseargsconfig), [v18.7.0](https://nodejs.org/docs/latest-v18.x/api/util.html#utilparseargsconfig) | [0.10.0](https://github.com/pkgjs/parseargs/tree/v0.10.0#utilparseargsconfig) |241 242----243 244## ๐Ÿš€ Getting Started245 2461. **Install dependencies.**247 248   ```bash249   npm install250   ```251 2522. **Open the index.js file and start editing!**253 2543. **Test your code by calling parseArgs through our test file**255 256   ```bash257   npm test258   ```259 260----261 262## ๐Ÿ™Œ Contributing263 264Any person who wants to contribute to the initiative is welcome! Please first read the [Contributing Guide](CONTRIBUTING.md)265 266Additionally, reading the [`Examples w/ Output`](#-examples-w-output) section of this document will be the best way to familiarize yourself with the target expected behavior for parseArgs() once it is fully implemented.267 268This package was implemented using [tape](https://www.npmjs.com/package/tape) as its test harness.269 270----271 272## ๐Ÿ’ก `process.mainArgs` Proposal273 274> Note: This can be moved forward independently of the `util.parseArgs()` proposal/work.275 276### Implementation:277 278```javascript279process.mainArgs = process.argv.slice(process._exec ? 1 : 2)280```281 282----283 284## ๐Ÿ“ƒ Examples285 286```js287const { parseArgs } = require('@pkgjs/parseargs');288```289 290```js291const { parseArgs } = require('@pkgjs/parseargs');292// specify the options that may be used293const options = {294  foo: { type: 'string'},295  bar: { type: 'boolean' },296};297const args = ['--foo=a', '--bar'];298const { values, positionals } = parseArgs({ args, options });299// values = { foo: 'a', bar: true }300// positionals = []301```302 303```js304const { parseArgs } = require('@pkgjs/parseargs');305// type:string & multiple306const options = {307  foo: {308    type: 'string',309    multiple: true,310  },311};312const args = ['--foo=a', '--foo', 'b'];313const { values, positionals } = parseArgs({ args, options });314// values = { foo: [ 'a', 'b' ] }315// positionals = []316```317 318```js319const { parseArgs } = require('@pkgjs/parseargs');320// shorts321const options = {322  foo: {323    short: 'f',324    type: 'boolean'325  },326};327const args = ['-f', 'b'];328const { values, positionals } = parseArgs({ args, options, allowPositionals: true });329// values = { foo: true }330// positionals = ['b']331```332 333```js334const { parseArgs } = require('@pkgjs/parseargs');335// unconfigured336const options = {};337const args = ['-f', '--foo=a', '--bar', 'b'];338const { values, positionals } = parseArgs({ strict: false, args, options, allowPositionals: true });339// values = { f: true, foo: 'a', bar: true }340// positionals = ['b']341```342 343----344 345## F.A.Qs346 347- Is `cmd --foo=bar baz` the same as `cmd baz --foo=bar`?348  - yes349- Does the parser execute a function?350  - no351- Does the parser execute one of several functions, depending on input?352  - no353- Can subcommands take options that are distinct from the main command?354  - no355- Does it output generated help when no options match?356  - no357- Does it generated short usage?  Like: `usage: ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]`358  - no (no usage/help at all)359- Does the user provide the long usage text?  For each option?  For the whole command?360  - no361- Do subcommands (if implemented) have their own usage output?362  - no363- Does usage print if the user runs `cmd --help`?364  - no365- Does it set `process.exitCode`?366  - no367- Does usage print to stderr or stdout?368  - N/A369- Does it check types?  (Say, specify that an option is a boolean, number, etc.)370  - no371- Can an option have more than one type?  (string or false, for example)372  - no373- Can the user define a type?  (Say, `type: path` to call `path.resolve()` on the argument.)374  - no375- Does a `--foo=0o22` mean 0, 22, 18, or "0o22"?376  - `"0o22"`377- Does it coerce types?378  - no379- Does `--no-foo` coerce to `--foo=false`?  For all options?  Only boolean options?380  - no, it sets `{values:{'no-foo': true}}`381- Is `--foo` the same as `--foo=true`?  Only for known booleans?  Only at the end?382  - no, they are not the same. There is no special handling of `true` as a value so it is just another string.383- Does it read environment variables?  Ie, is `FOO=1 cmd` the same as `cmd --foo=1`?384  - no385- Do unknown arguments raise an error?  Are they parsed?  Are they treated as positional arguments?386  - no, they are parsed, not treated as positionals387- Does `--` signal the end of options?388  - yes389- Is `--` included as a positional?390  - no391- Is `program -- foo` the same as `program foo`?392  - yes, both store `{positionals:['foo']}`393- Does the API specify whether a `--` was present/relevant?394  - no395- Is `-bar` the same as `--bar`?396  - no, `-bar` is a short option or options, with expansion logic that follows the397    [Utility Syntax Guidelines in POSIX.1-2017](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html). `-bar` expands to `-b`, `-a`, `-r`.398- Is `---foo` the same as `--foo`?399  - no400  - the first is a long option named `'-foo'`401  - the second is a long option named `'foo'`402- Is `-` a positional? ie, `bash some-test.sh | tap -`403  - yes404 405## Links & Resources406 407* [Initial Tooling Issue](https://github.com/nodejs/tooling/issues/19)408* [Initial Proposal](https://github.com/nodejs/node/pull/35015)409* [parseArgs Proposal](https://github.com/nodejs/node/pull/42675)410 411[coverage-image]: https://img.shields.io/nycrc/pkgjs/parseargs412[coverage-url]: https://github.com/pkgjs/parseargs/blob/main/.nycrc413[pkgjs/parseargs]: https://github.com/pkgjs/parseargs414