You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The documentation assumes the bundle is installed,
but the only difference between the bundle and modules installation is how functions are imported:
The bundle uses require('shargs/opts'), while require('shargs-opts') is used by modules
(note the use of / vs. -).
Read installing as bundle or modules for more details.
Getting Started
Describe your command and its options:
constopts=[stringPos('question',{desc: 'Ask a question.',required: true}),number('answer',['-a','--answer'],{desc: 'The answer.',defaultValues: [42]}),flag('help',['-h','--help'],{desc: 'Print this help message and exit.'})]constdeepThought=command('deepThought',opts,{desc: 'Ask the Ultimate Question.'})
The deepThought command has three command-line options:
A required string positional argument named question.
An answer number option specified with -a or --answer that should default to 42 if not given.
A help command-line flag given by -h or --help.
You may use the shargs-opts module to get a nice DSL for describing our options.
However, you could have also written them out as objects yourself or could have used a different DSL.
Shargs gives you fine-grained control over how the options are parsed.
By using the shargs-core and shargs-parser modules, we have build the following parser:
splitShortOpts: Short option groups like -cvzf are transformed to -c -v -z -f.
setDefaultValues: Options with default values that were not provided are set.
requireOpts: It is verified that all required options have been given.
cast: Strings are cast to other types, like numbers or booleans.
flagsAsBools: Command-line flags are transformed to booleans.
Note that you did not tell parser how exactly to do those things.
Everything is nice and declarative, and the details are hidden away in the parser stages.
You may use shargs-usage to automatically generate a usage documentation based on a command definition
(e.g. deepThought from before).
The module provides all components generally found in usage documentations, like:
A synopsis, summarizing available options: e.g. deepThought (<question>) [-a|--answer] [-h|--help].
An options list (optsList), describing option details in a tabular format.
Note that shargs-usage is declarative:
You only specify what components our usage documentation should have.
The details on how exactly those components transform command-line options into text is hidden away.
deepThought (<question>) [-a|--answer] [-h|--help]
<question> Ask a question. [required]
-a, --answer=<number> The answer. [default: 42]
-h, --help Print this help message and exit.
Ask the Ultimate Question.
Since writing objects following these interfaces by hand can be tedious,
shargs-opts gives you a simple type-based DSL for defining valid command-line options:
const{command, flag, number, subcommand}=require('shargs/opts')constopts=[subcommand(askOpts)('ask',['ask'],{required: true,desc: 'Ask a question.'}),number('answer',['-a','--answer'],{defaultValues: [42],desc: 'The answer.'}),flag('help',['-h','--help'],{desc: 'Print this help message and exit.'})]constdeepThought=command('deepThought',opts,{desc: 'Deep Thought was created to come up with the Answer to '+'The Ultimate Question of Life, the Universe, and Everything.'})
In the example, using the type functions subcommand, number, flag,
and command guarantees the generation of valid objects.
Note that the values are represented as strings and you may want to cast them.
If you need more values representing 'true' (e.g. 't', 'yes')
or 'false' (e.g. 'F', 'no'),
have a look at broadenBools.
If you want to treat a value as its reverse,
see reverseBools.
If you need flags instead of bools, have a look at the
boolAsFlag and boolsAsFlags
parser stages.
subcommand generates a subcommand option,
while command generates a command positional argument.
Combined, they enable commands to do multiple things like git init, git commit, and git push.
subcommand's and command's opts fields
are arrays of command-line options used to parse their values.
Subcommands may have their own command-specific parsers
or are parsed by command's parser.
command or subcommand values are either terminated by the end of the input
or by --.
flag generates a flag option,
representing command-line options that take no value.
Shargs counts the number of times a flag occurs, so a flag may be amplified by repeating it.
If you don't need counts and prefer numbers or boolean values, have a look at the
flagAsBool, flagAsNumber,
flagsAsBools and flagsAsNumbers
parser stages.
If you need the presence of a flag to imply negativity (e.g. --no-fun),
see complement,
reverse and reverseFlags.
Numbers are represented as strings and you may want to cast them.
If you need flags instead of numbers, have a look at the
numberAsFlag and numbersAsFlags
parser stages.
An opts array can have at most one variadic positional argument
and no other positional arguments (*Pos) may be defined after it.
The closely related array
and arrayPos represent arrays with known lengths, while
command and subcommand are
variadicPos and variadic with opts fields.
A variadic's or variadicPos' values are either terminated by the end of the input
or by --.
You may write out command-line options by hand, or write your own DSLs for creating them, they are just JavaScript objects:
constaskOpts=[{key: 'format',args: ['--format'],types: ['string'],only: ['json','xml'],defaultValues: ['json'],desc: 'Respond either with json or xml.'},{key: 'html',args: ['--no-html'],types: [],reverse: true,desc: 'Remove HTML tags.'},{key: 'help',args: ['-h','--help'],types: [],desc: 'Print this help message and exit.'},{key: 'question',types: ['string'],required: true,desc: 'State your question.'}]
Apart from key, args, types, opts, and values
that we have already seen and that determine an option's type,
command-line option objects may be given any other fields,
that may be used to provide information to parser stages
(e.g. defaultValues, only),
or to provide descriptions for usage documentation generation
(e.g. desc, descArg).
If you write your own parser stages, you may also define your own fields.
args defines argument names for command-line options (e.g. ['-h', '--help']).
Argument names have no restrictions and can be any string.
E.g. ['-h', '--help'] could be used for a help flag
or ['ask'] could be used for a command.
Positional arguments must not have an args field,
as they are not given by argument, but by their position.
contradicts defines what keys an option is incompatible with.
This information is used by the contradictOpts parser stage
to report errors if incompatible options are used together.
Note that contradicts is unidirectional and not transitive
(e.g. if a contradicts b and b contradicts c,
a does not contradict c, and thus a and c are compatible).
Only two keys that each contradict the other key
are mutually exclusive.
defaultValues defines default values for command-line options.
They are used by the setDefaultValues parser stage
that sets the values field if no values are supplied.
The defaultValues' type depends on the command-line option type:
Subcommands takes the same array of options as opts.
Flag options' values have to be a number.
All other options take an array of values,
that must have the same length as their types field.
descArg defines a description for an argument value
(e.g. {descArg: 'format'} would print --format=<format>
instead of --format=<string>).
It is used by the optsList, optsLists,
optsDef, and optsDefs usage functions
and their *With versions.
only, types, and key
are other fields that change the argument value description.
These fields are applied in the following order (highest priority first):
descArg, only, types,
and key.
If descArg is an empty string, no argument value description is displayed.
descDefault overrides the default shield (e.g. [default: 42]) displayed in several usage commands.
It is used by the optsList, optsLists,
optsDef, and optsDefs usage functions
and their *With versions.
If descDefault is an empty string, the default shield is hidden.
implies defines what keys an option must be defined with.
This information is used by the implyOpts parser stage
to report errors if mandatory options are missing.
Note that implies is unidirectional
(e.g. if a implies b and a is present, b must be present as well,
but if b is present, a does not have to be present)
and transitive
(e.g. if a implies b and b implies c,
a also implies c,
and thus if a is present, c must also be present).
Only two keys that each imply the other key
are mutually inclusive.
It is used by the parser function
as a field name for the parsed values in the resulting args object.
Most command-line options should have a unique key to avoid collisions with other options.
However, if two different options describe the same result field, it may make sense to give them a shared key.
See complement for an example.
A key must not be named _.
It is also used by the
optsList, optsLists,
optsDef, optsDefs,
synopses, and synopsis usage functions
and their *With versions to describe argument values (e.g. --format=<format>).
descArg, only,
and types are other fields that change the argument value description.
These fields are applied in the following order (highest priority first):
descArg, only,
types, and key.
It is used by the restrictToOnly parser stage to validate user input.
only may be used to implement enumerations.
It is also used by the optsList, optsLists,
optsDef, and optsDefs usage functions
and their *With versions to describe argument values (e.g. --format=<json|xml>).
descArg, types,
and key are other fields that change the argument value description.
These fields are applied in the following order (highest priority first):
descArg, only, types,
and key.
required defines whether a command-line option has to be present or not.
It is used by the requireOpts stage that reports an error
if a required option does not have values.
A positional argument (*Pos) can only be required,
if all previously defined positional arguments are required as well.
The synopsis, synopses,
optsList, optsLists,
optsDef, and optsDefs usage functions
and their *With versions mark required options.
Certain changes to options are so frequent, that shargs-opts provides decorators for them.
You may think of decorators as recurring patterns that are provided as functions.
complement transforms a bool or flag
option into a complementary option prefixed with a given string
(e.g. --no-html if used on --html).
The complementary option has the same key as the original option,
but reverses its value.
If complement is used,
you most probably want to also use the reverseBools
or reverseFlags parser stage.
In the example, it would return a list of errs if deepThought was invalid.
If the command is valid, the errs list is empty.
verifyCommand is used internally by parserSync and parser, but may be used independently.
The parserSync Function
The parserSync function is shargs' core abstraction.
It generates a command-line parser from a collection of parser stages
and is usually used alongside shargs-parser:
A stages object that takes parser stages
and defines what transformations should be applied in which order.
An optional substages object that defines subcommand-specific opts parser stages.
parserSync has a twin function called parser that does the same, but works asynchronously.
stages
Shargs has seven different processing steps called stages that are applied in a predefined order
and transform argument values (process.argv) via command-line options (opts) to arguments (args):
The argv, opts, and args stages
are the user-facing API to declare a parser's behavior.
The toOps and toArgs stages
define the core behavior of parserSync (and parser)
and shargs defines sensible defaults that should not have to be changed in most use cases.
However, if you do have a use case that needs adjustments to those stages, you may carefully swap them out.
If you read the types from top to bottom, you get a good impression of how parserSync works.
substages
substages define custom opts stages for subcommands.
That means, while most subcommands are parsed using the opts defined in stages,
those whose key matches a key in the substages object are parsed using the opts defined under that key.
Keys may be deeply nested to account for subcommands of subcommands:
E.g. if ask had a subcommand with the questionkey, {ask: {question: [...stages.opts, restrictToOnly]}} would assign custom opts to question.
The _key is special in substages:
It is a wildcard that is used by any subcommand that is not given explicitly by key.
E.g. {ask: {_: [...stages.opts, restrictToOnly]}} and {_: {_: [...stages.opts, restrictToOnly]}} both work for question.
Async Parsers
The parserSync function has an asynchronous alternative called parser.
It is used exactly like parserSync, but also works with stages returning
JavaScript Promises
and returns a Promise itself:
// stages, substages, deepThought, argv are taken from the Getting Started sectionconst{parser}=require('shargs')constasyncParser=parser(stages,substages)constparse=asyncParser(deepThought)const{errs, args}=awaitparse(argv)
In addition to parserSync's parameters,
parser's stages and substages parameters also take parser stages that return Promises:
If you read the stages' field types from top to bottom, you get a good impression of what an asynchronous parser does.
Internally, an asynchronous shargs parser really differs only in one major way from a synchronous parser:
Instead of using function composition, it uses Promise.prototype.then to chain parser stages.
You do not have to write all parser stages yourself.
The shargs-parser library offers a large collection of common parser stages, you can use.
The parser stages presented here are split into checks and stages.
While checks only report errors, stages also transform their argv, opts, or args.
Usually, it makes sense to declare checks before stages.
Allows to omit whitespaces between short arguments and their values.
Passing -a42 would be the same as passing -a 42.
Cannot be used together with splitShortOpts.
Transforms arguments by applying a function f to each argument satisfying a predicate p.
While p's signature is arg => true|false,
f's signature must be (arg, index, argv) => ({errs = [], argv = []}).
Many other argv checks and stages are defined in terms of traverseArgv
and it is of great help for writing custom argv stages.
const{demandASubcommand}=require('shargs/parser')const{flag, number, subcommand}=require('shargs/opts')constopts=[subcommand([])('ask',['ask'],{desc: 'Ask a question.'}),number('answer',['-a','--answer'],{values: ['42'],desc: 'The answer.'}),flag('help',['-h','--help'],{desc: 'Print this help message and exit.'})]demandASubcommand({opts})
Result:
{errs: [{code: 'SubcommandRequired',msg: 'No subcommand found. Please use at least one subcommand!',info: {...}}]}
This is the case, if the option has values, but an option from its implies list has not.
If implies is not a list, it reports a WrongImpliesType error.
Example:
const{implyOpts}=require('shargs/parser')const{number, string}=require('shargs/opts')constopts=[number('answer',['-a']),string('question',['-q'],{implies: ['answer'],values: ['How much is the fish?']})]implyOpts({opts})
Result:
{errs: [{code: 'ImplicationViolated',msg: 'Some given keys that imply...',info: {...}}]}
Corrects spelling mistakes by suggesting existing command-line arguments for all unknown provided arguments.
E.g. if --asnwer was provided, the --answer argument would be suggested.
It checks all restvalues,
assuming they are in the rest category because of spelling mistakes.
It collects all command-line options' args
and computes a distance metric (currently Levenshtein distance) between each arg and each rest.
It reports the results in a DidYouMean error,
suggesting probable args replacements for spelling mistakes.
The options array looks a little bit strange, so an explanation is in order.
The array's index is the cost necessary to transform the unknown option in the arguments, represented as keys.
Because of this, you can conveniently work with the results, e.g. by only using the most probable ones:
'Did you mean: '+(options.slice(0,3).reduce((a,b)=>a.concat(b)).flatMap(Object.keys).join(', '))
If a positional argument is required,
all previously defined positional arguments must be required, as well,
and no other positional arguments can be defined after a variadicPos.
In case of a violation of the second rule, validatePosArgs reports an
InvalidVariadicPositionalArgument error.
{errs: [{code: 'InvalidRequiredPositionalArgument',msg: 'If a positional argument is required, all prev...',info: {...}},{code: 'InvalidVariadicPositionalArgument',msg: 'Only the last positional argument may be variadic.',info: {...}}]}
Reports a FalseOptsRules error
if the opts array does not adhere to the rules predicate.
rules must have the following function signature: opt => true|false.
If rules is not a function, verifyOpts reports a WrongOptsRulesType error.
Example:
const{verifyOpts}=require('shargs/parser')const{string}=require('shargs/opts')constimplies=(p,q)=>!p||qconstrules=opts=>implies(opts.some(_=>_.key==='question'&&_.values),opts.some(_=>_.key==='answer'&&_.values))constopts=[string('question',['--question'],{values: ['How much is the fish?']}),number('answer',['-a'])]verifyOpts(rules)({opts})
Result:
{errs: [{code: 'FalseOptsRules',msg: 'Your opts rules returned false...',info: {...}}]}
Reports an error if an option's
values do not fit its types.
See the values documentations for the exact rules.
If the lengths of values and types do not match,
an InvalidArity error is reported.
If the types field has an invalid value, an InvalidTypes error is reported
and verifyValuesArity reports an InvalidValues error in case of invalid values.
Takes a best guess approach to transform rest values that did not match a command-line option
into new command-line options.
E.g. {values: ['--version']} becomes {key: 'version', types: [], values: [1]} and
[{values: ['--not']}, {values: ['panic']}]
becomes {key: 'not', types: ['string'], args: ['--not'], values: ['panic']}.
Single rest options are interpreted as flags
while two consecutive rest options are interpreted as strings
if the first rest is in short option format
(one minus with a single character, e.g. -n, -a)
or in long option format (two minuses with any more characters, e.g. --name, --answer).
bestGuessArgs is very similar to bestGuessOpts,
but also considers non-consecutive rest values.
Casts string values
into other JavaScript types (e.g. numbers, booleans)
according to the command-line options' types
(e.g. {key: 'answer', types: ['number'], values: ['42']} is transformed to
{key: 'answer', types: ['number'], values: [42]}).
Transforms opts by applying a function f
to each option satisfying a predicate p.
While p's signature is opt => true|false,
f's signature must be (opt, index, opts) => ({errs = [], opts = []}).
Many other opts checks and stages are defined in terms of traverseOpts
and it is of great help for writing custom opts stages.
const{verifyArgs}=require('shargs/parser')construles=args=>(typeofargs.question!=='undefined'&&typeofargs.answer!=='undefined')constargs={question: 'How much is the fish?'}verifyArgs(rules)({args})
Result:
{errs: [{code: 'FalseArgsRules',msg: 'Your args rules returned false...',info: {...}}]}
Introduces new arguments by best guess based on rest field values
(e.g. {_: ['--version']} becomes {version: {type: 'flag', count: 1}}
and {_: ['--not', 'panic']} becomes {not: 'panic'}).
Transforms single rest field values into a flag and two consecutive rest options into a string.
It only assumes rest field values to be strings if the first rest is in short option format
(one minus with a single character, e.g. -h, -v)
or in long option format (two minuses with any more characters, e.g. --help, --verbose).
bestGuessArgs is very similar to bestGuessOpts,
but also considers rest fields that originally did not directly follow each other.
E.g. assuming --help to be a known argument, --not --help panic would produce {not: 'panic'},
although its components were not in tandem.
Example:
const{bestGuessArgs}=require('shargs/parser')constobj={args: {_: ['--answer','42','foo','-h'],command: {_: ['bar','-v','--question','What is answer?','-v']}}}bestGuessArgs(obj)
Casts string args into other JavaScript types
using a best guess approach based on their values (e.g. {answer: '42'} becomes {answer: 42}
and {all: 'true'} becomes {all: true}).
It supports numbers and booleans (e.g. {help: 'true'} becomes {help: true}).
Transforms bool arguments with key in args to a flag object.
E.g., assuming the all key,
{all: true} is transformed to {all: {type: 'flag', count: 1}} and
{all: false} to {all: {type: 'flag', count: -1}}.
Transforms flags with key in args to a bool value.
E.g., assuming the all key,
{all: {type: 'flag', count: 1}} is transformed to {all: true} and
{all: {type: 'flag', count: -1}} to {all: false}.
If its count is greater than 0 it is considered true, otherwise it is considered false.
Transforms flags with key in args to a number using its count.
E.g., assuming the verbose key,
{verbose: {type: 'flag', count: 3}} becomes {verbose: 3}.
Transforms args by flattening them
by recursively merging nested objects into their parent object
(e.g. {ask: {question: '42?'}, answer: 42} becomes {question: '42?', answer: 42}).
A custom merge function may be passed with the following function signature:
(obj1 = {}, obj2 = {}) => {}.
The default merge function (if merge is undefined)
prefers keys from the parent object over keys from nested objects,
but concatenates rest values (_) from both objects
(e.g. {_: ['foo'], answer: 42, ask: {_: ['bar'], answer: 23}} becomes
{_: ['foo', 'bar'], answer: 42}).
Transforms numbers with key in args to flag objects.
The number becomes the flag's count.
E.g. {answer: 42} becomes {answer: {type: 'flag', count: 42}}.
Transforms args by applying functions fs to each key/value pair based on the value's type.
fs supports the following types:
array, boolean, flag, function, null, number, object, string, undefined, and otherwise.
The default behavior for most types is to not change the value, with three notable exceptions:
functions and otherwises key/value pairs are removed from args,
while object's default function applies fs to nested objects.
{flag: ({key, val, errs, args}) => ({errs, args})}
is the signature for fs with fields for each type.
Many other args checks and stages are defined in terms of traverseArgs
and it is of great help for writing custom args stages.
Shargs strictly separates the concerns of parsing command-line arguments and generating usage documentation.
The shargs-usage module specializes on
generating terminal-based usage documentation for --help flags
from command-line options:
shargs-usage lets you define how your usage documentation should look like in a declarative way.
In the example, we tell our docs to start with synopses, have optsLists in the body,
and close with a description.
We separate these three parts with spaces and enclose everything in a usage function.
Note that we did not mention any command-line options, yet:
const{command, flag, number, stringPos}=require('shargs/opts')constopts=[stringPos('question',{desc: 'Ask a question.',required: true}),number('answer',['-a','--answer'],{desc: 'The answer.',defaultValues: [42]}),flag('help',['-h','--help'],{desc: 'Print this help message and exit.'})]constdeepThought=command('deepThought',opts,{desc: 'Deep Thought was created to come up with the Answer to '+'The Ultimate Question of Life, the Universe, and Everything.'})constoptsDocs=docs(deepThought)
optsDocs now knows what to layout (deepThought), and how to layout it (docs).
Finally, we style the different parts (lines and columns) of the documentation:
Now, if we console.log(text), the following text is printed to the console:
deepThought (<question>) [-a|--answer] [-h|--help]
<question> Ask a question. [required]
-a, --answer=<number> The answer. [default: 42]
-h, --help Print this help message and exit.
Deep Thought was created to come up with the Answer to The
Ultimate Question of Life, the Universe, and Everything.
desc takes a command-line option's desc field
and formats it according to a style.
If the description is too long to fit one line, it is split and spread over several lines.
desc is defined as descWith({id: 'line'}).
Example:
Deep Thought should answer the Ultimate
Question
Code:
const{desc, usage}=require('shargs/usage')constopt={opts: [],desc: 'Deep Thought should answer the Ultimate Question'}conststyle={line: [{width: 40}]}usage([desc])(opt)(style)
note takes a string and formats it according to a style,
ignoring its second parameter.
If the string is too long to fit one line, it is split and spread over several lines.
note is defined as noteWith({id: 'line'}).
Example:
Deep Thought was created to come up with
the Answer
Code:
const{note, usage}=require('shargs/usage')conststyle={line: [{width: 40}]}usage([note('Deep Thought was created to come up with the Answer')])()(style)
notes takes a list of strings and formats it
according to a style,
ignoring its second parameter.
If a string is too long to fit one line, it is split and spread over several lines.
notes is defined as notesWith({id: 'line'}).
Example:
Deep Thought was created to come up with
the Answer
to The Ultimate Question.
Code:
const{notes, usage}=require('shargs/usage')conststyle={line: [{width: 40}]}usage([notes(['Deep Thought was created to come up with the Answer','to The Ultimate Question.'])])()(style)
optsLists first layouts its opts and then the opts
of all its subcommands recursively,
using optsLists,
indenting the first column of each optsList layer by four spaces.
optsLists is defined as optsListsWith({id: 'cols', pad: 4}).
Example:
-a, --answer=<number> The answer. [default: 42]
-h, --help Usage docs.
ask Ask questions. [required]
-h Show the usage docs.
<questions>... Questions. [required]
space ignores its first argument and returns a line consisting entirely of spaces,
with a width according to style.
space is defined as spaceWith({id: 'line', lines: 1}).
Example:
Deep Thought was created to come up with
the Answer to The Ultimate Question.
Code:
const{note, space, usage}=require('shargs/usage')conststyle={line: [{width: 40}]}usage([note('Deep Thought was created to come up with'),space,note('the Answer to The Ultimate Question.')])()(style)
synopsis layouts the program's name in the first and its opts
in the second column of a table
and formats it according to its style.
For each opt, the args, descArg, only, required, types,
and key fields are used for a brief overview.
synopsis is defined as synopsisWith({id: 'line'}).
const{synopsis, usage}=require('shargs/usage')const{command, flag}=require('shargs/opts')const{number, variadicPos}=require('shargs/opts')constopts=[number('answer',['-a','--answer'],{desc: 'The answer.',required: true}),flag('help',['-h','--help'],{desc: 'Prints help.'}),flag('version',['--version'],{desc: 'The version.'}),variadicPos('questions')]constdeepThought=command('deepThought',opts)conststyle={line: [{width: 40}]}usage([synopsis])(deepThought)(style)
Usage Combinators
While usage functions taken for themselves are useful,
they really begin to shine if they are combined by usage combinators.
Usage combinators are higher-order usage functions that take other usage functions as parameters,
combine them in various ways, and return a new usage function.
Let's see how usage combinators may be used to implement synopses:
This example uses usage decorators, that are only introduced in the next section.
The implementation of synopses uses two usage combinators:
usage and usageMap.
usage is used to combine two usage functions:
A synopsis of all opts, but subcommands, and the usage function returned by usageMap.
usageMap iterates over all subcommands
and recursively calls synopses on each subcommand's opts.
The recursion stops, if opt's opts has no more subcommands,
since usage functions with empty opts return an empty string.
Combinators are a powerful feature, as they let you build more complex things from smaller parts.
shargs-usage provides the following usage combinators:
usage takes a list of usage functions
that each take an opt, a style and return a string.
It then applies its own opt and style to each function,
and concatenates the resulting strings.
Example:
deepThought [-a|--answer] [-h|--help] [--version]
-a, --answer=<number> The answer.
-h, --help Prints help.
--version Prints version.
Deep Thought was created to come up with the
Answer.
Code:
const{note, optsList, space}=require('shargs/usage')const{synopsis, usage}=require('shargs/usage')const{command, flag, number}=require('shargs/opts')constopts=[number('answer',['-a','--answer'],{desc: 'The answer.'}),flag('help',['-h','--help'],{desc: 'Prints help.'}),flag('version',['--version'],{desc: 'Prints version.'})]constdeepThought=command('deepThought',opts,{desc: 'Deep Thought was created to come up with the Answer.'})conststyle={line: [{width: 50}],cols: [{width: 25},{width: 25}]}usage([synopsis,space,optsList,space,desc])(deepThought)(style)
usageMap takes a function f that takes an option
and returns a layout function.
It maps f over the option's opts
and applies its style to each resulting layout function.
Finally, it concatenates the resulting strings and returns the result.
Example:
-a, --answer
The answer.
-h, --help
Prints help.
--version
Prints version.
When defining layouts, we may want to feature some opts in one place,
and the remaining in a different place of our documentation.
Maybe the subcommands should be presented in a definition list,
while the other options are layed out as a table.
Usage decorators enable these use cases by modifying inputs of usage functions:
optsFilter modifies its opt by applying a filter with the predicate p,
whose function signature must be opt => true|false to its opts.
Many other usage decorators are defined in terms of optsFilter
and it is of great help for writing custom ones.
Example:
const{optsFilter, usage}=require('shargs/usage')const{flag, number, subcommand}=require('shargs/opts')conststyle={cols: [{width: 25},{width: 25}]}constopt={opts: [number('answer',['-a','--answer'],{desc: 'The answer'}),subcommand([])('ask',['ask'],{desc: 'Asks a question'}),flag('version',['--version'],{desc: 'Prints version'})]}usage([optsFilter(({types})=>types!==null)(optsList)])(opt)(style)
Result:
-a, --answer=<number> The answer
ask Asks a question
--version Prints version
optsMap modifies its opt by applying a function f
to each option in opts,
whose function signature must be opt => opt.
Many other usage decorators are defined in terms of optsMap
and it is of great help for writing custom ones.
Example:
const{optsMap, usage}=require('shargs/usage')const{flag, number, subcommand}=require('shargs/opts')conststyle={cols: [{width: 25},{width: 25}]}constopt={opts: [number('answer',['-a','--answer'],{desc: 'The answer'}),subcommand([])('ask',['ask'],{desc: 'Asks a question'}),flag('version',['--version'],{desc: 'Prints version'})]}usage([optsMap(opt=>({...opt,args: opt.args.slice(0,1)}))(optsList)])(opt)(style)
Result:
-a <number> The answer
ask Asks a question
--version Prints version
Usage Decorator Combinators
If many usage decorators are applied to a usage function, things get unwieldy, fast:
In the example, briefSynopsis is decorated three times and the code is not very readable.
Usage decorator combinators facilitate a cleaner code layout:
This version of briefSynopsis is much more readable.
Note, that decorate applies its usage decorators from right to left.
As is apparent from the example, usage decorator combinators are usage decorators, themselves.
shargs-usage has the following usage decorator combinators:
In the example, style provides the details for how many columns a usage documentation text should be wide,
and whether it should have padding.
A style is an object whose values are arrays of style objects, that must have a width key,
and may have padEnd and padStart keys:
constaskOpts=[{key: 'format',args: ['--format'],types: ['string'],only: ['json','xml'],defaultValues: ['json'],desc: 'Respond either with json or xml.'},{key: 'html',args: ['--no-html'],types: [],reverse: true,desc: 'Remove HTML tags.'},{key: 'help',args: ['-h','--help'],types: [],desc: 'Print this help message and exit.'},{key: 'question',types: ['string'],required: true,desc: 'State your question.'}]
const{command, flag, number, subcommand}=require('shargs/opts')constopts=[subcommand(askOpts)('ask',['ask'],{required: true,desc: 'Ask a question.'}),number('answer',['-a','--answer'],{defaultValues: [42],desc: 'The answer.'}),flag('help',['-h','--help'],{desc: 'Print this help message and exit.'})]constdeepThought=command('deepThought',opts,{desc: 'Deep Thought was created to come up with the Answer to '+'The Ultimate Question of Life, the Universe, and Everything.'})
Imagine these snippets were located in their own modules and were imported earlier.
Then, a sample command-line program written with shargs could be:
constargv=process.argv.slice(2)const{errs, args}=parser(deepThought)(argv)if(args.help){consthelp=docs(deepThought)(style)console.log(help)process.exit(0)}if(errs.length>0){errs.forEach(({code, msg})=>console.log(`${code}: ${msg}`))process.exit(1)}console.log(`The answer is: ${args.answer}`)process.exit(0)
First, we skip the first two values of process.argv.
They are node and the file name and can be ignored.
We then parse the remaining argv with our deepThought parser and get two results:
A list of errs, and an args object with parsed argument values.
Based on those two results, we build our program.
If the args.help field is set, we print a help text generated from docs by applying deepThought and style.
Then, we exit with exit code 0.
If we run the program with node ./deepThought --help, the following text is printed:
deepThought [-a|--answer] [-h|--help]
deepThought (ask) [--format] [--no-html] [-h|--help] (<question>)
-a, --answer=<number> The answer. [default: 42]
-h, --help Print this help message and exit.
ask Ask a question. [required]
--format=<json|xml> Respond either with json or xml. [default: json]
--no-html Remove HTML tags.
-h, --help Print this help message and exit.
<question> State your question. [required]
Deep Thought was created to come up with the Answer to The Ultimate Question of
Life, the Universe, and Everything.
If the errs array has errors, we print all errors and exit with exit code 1.
E.g. if we execute node ./deepThought --answer 5, without specifying the required ask subcommand,
the following text appears:
Required option is missing: An option that is marked as required has not been provided.
Otherwise, we print the args.answer.
E.g. if we run it with node ./deepThought ask "What is the meaning of Life, the Universe, and Everything?",
it prints:
The answer is: 42
More In-depth Documentation
Feel free to skip this section if you are new to Shargs.
It introduces more advanced topics:
Since version 0.26.0, shargs may be installed in two different ways:
Either as a bundle (recommended), or individually as modules.
npm install --save shargs # bundle installation (core, opts, parser, and usage)
npm install --save shargs-core # module (in bundle: shargs/core or shargs)
npm install --save shargs-opts # module (in bundle: shargs/opts)
npm install --save shargs-parser # module (in bundle: shargs/parser)
npm install --save shargs-usage # module (in bundle: shargs/usage)
npm install --save shargs-repl # module (not in bundle)
The shargs bundle combines several modules in one distribution with its own version number.
The advantage for the user is that the module versions are guaranteed to be compatible and updates are simpler.
Installing individual modules is more flexible,
e.g. if you want to use a specific set of module versions,
if one module of the bundle is not needed
or if one of the modules is replaced with a different implementation.
It is recommended to start with the bundle installation
and import modules like require('shargs/opts') or import 'shargs/core'.
If you want to switch to a module installation later, you may simply replace your imports with module imports:
E.g. require('shargs-opts') and import 'shargs-core'.
If you are using modules and need to know which versions are compatible,
you may refer to the module versions used by the shargs bundle.
Multiple Subcommands
Shargs supports specifying multiple subcommands.
E.g. you could use both, the ask and designsubcommands in the same command
in the following version of deepThought:
const{command, flag, number, stringPos, subcommand}=require('shargs/opts')constask=subcommand([stringPos('question')])constdesign=subcommand([stringPos('name')])constopts=[ask('ask',['ask'],{desc: 'Ask a question.'}),design('design',['design'],{desc: 'Design a more powerful computer.'}),flag('help',['-h','--help'],{desc: 'Print this help message and exit.'})]constdeepThought=command('deepThought',opts,{desc: 'Ask the Ultimate Question.'})
If you provide both subcommands in your argv, both are parsed:
constargv=['design','Earth','ask','What is the answer to the Ultimate Question?']constparse=parserSync()(deepThought)const{argv, errs}=parse(argv)console.log(argv)/*{ _: [], ask: { _: [], question: 'What is the answer to the Ultimate Question?' }, design: { _: [], name: 'Earth' }}*/
Note that the subcommand order is not preserved.
This is due to the default behavior of fromArgs,
that keeps only the first mention of a subcommand and merges all subcommands into an (unordered) object.
The input to fromArgs is still ordered and has duplicates,
so if your program needs the subcommand order or duplicates,
just write a custom fromArgs stage:
This demonstration implementation of fromArgs is very simple
and lacks some features like e.g. subcommands of subcommands.
Please improve it before using it in your production programs.
Building REPLs with Shargs
🚧 Work in progress: This feature is currently worked on and its API is not yet stable.
Shargs makes writing and using custom checks and stages very simple.
The only thing you have to do is to follow the correct function signatures for your check or stage,
as given in the stages and substages sections.
The following code snippets showcase very simple examples with the correct signatures.
Regardless of whether you implement a check or a stage, the most important thing to remember is:
Always pass on errors!
If you write a custom args stage, have a look at traverseArgs!
Layout Functions
Usage functions that are applied to an opt yield so called layout functions.
If we take a closer look at the signatures of usage and layout functions,
the connection between the two becomes apparent:
Usage functions take an opt and return a layout function.
In shargs-usage, an opt's purpose is to provide the textual contents of layout functions
and the usage functions' only job is to specify how this textual content is extracted from the opt.
The layout functions do the actual work of formatting strings.
Let's have a look at an example:
const{br, defs, layout, table, text}=require('shargs/usage')constaskDocs=layout([table([['deepThought (ask)','[--format] [--no-html] [-h|--help] (<question>)']]),br,defs([['--format=<json|xml> [default: json]','Respond either with json or xml.'],['--no-html','Remove HTML tags.'],['-h, --help','Print this help message and exit.'],['<question> [required]','State your question.']]),br,text('Deep Thought was created to come up with the Answer to '+'The Ultimate Question of Life, the Universe, and Everything.')])
In the example, askDocs is a layout that comprises four different layout functions:
table, br, defs, and text.
Depending on how we style the layout, we get different strings:
If we console.log(string), the following text is printed to the console:
deepThought (ask) [--format] [--no-html] [-h|--help] (<question>)
--format=<json|xml> [default: json]
Respond either with json or xml.
--no-html
Remove HTML tags.
-h, --help
Print this help message and exit.
<question> [required]
State your question.
Deep Thought was created to come up with the Answer to The Ultimate Question of
Life, the Universe, and Everything.
br returns a line filled with spaces,
with a width according to style.
br is defined as brWith({id: 'line', lines: 1}).
Example:
Deep Thought was created to come up with
the Answer
to The Ultimate Question.
Code:
const{br, layout, text}=require('shargs/usage')conststyle={line: [{width: 40}]}layout([text('Deep Thought was created to come up with the Answer'),br,text('to The Ultimate Question.')])(style)
defs takes a list of tuples,
where each entry is a tuple of strings,
with a term at the first and a definition at the second position.
It formats its tuples as a definition list over two lines,
with the term in the first, and the definition in the second line.
If a term or definition extends its line,
it is continued in another line.
defs is defined as defsWith({id: 'line', pad: 4}).
Example:
-a, --answer=<number> [default: 42]
The answer.
-h, --help
Prints help.
--version
Prints version.
line takes a string
and formats it according to a style's width.
If a string exceeds its width, it is cut off, otherwise, the width is filled up with spaces.
It ends with a line break. line is defined as lineWith({id: 'line'}).
Example:
Deep Thought was created to come up with
the Answer
Code:
const{layout, line}=require('shargs/usage')conststyle={line: [{width: 40}]}layout([line('Deep Thought was created to come up with'),line('the Answer')])(style)
lines takes a list of strings
and layouts each string with line.
lines is defined as linesWith({id: 'line'}).
Example:
Deep Thought was created to come up with
the Answer
to The Ultimate Question.
Code:
const{layout, lines}=require('shargs/usage')conststyle={line: [{width: 40}]}layout([lines(['Deep Thought was created to come up with','the Answer','to The Ultimate Question.'])])(style)
text takes a string and formats it according to a style.
If the string exceeds a line, it continues on the next.
text is defined as textWith({id: 'line'}).
Example:
Deep Thought was created to come up with
the Answer
Code:
const{layout, text}=require('shargs/usage')conststyle={line: [{width: 40}]}layout([text('Deep Thought was created to come up with the Answer')])(style)
texts takes a list of strings
and layouts each string with text.
texts is defined as textsWith({id: 'line'}).
Example:
Deep Thought was created to come up with
the Answer
to The Ultimate Question.
Code:
const{layout, texts}=require('shargs/usage')conststyle={line: [{width: 40}]}layout([texts(['Deep Thought was created to come up with the Answer','to The Ultimate Question.'])])(style)
Layout Combinators
Layout combinators are functions that take layout functions as parameters
and return new layout functions.
They are the primary way of building more complex constructs from simpler components.
The following examples demonstrate the use of layout combinators:
layout takes a list of layout functions
that each take a style and return a string.
It then applies its own style to each function,
and concatenates the resulting strings.
Example:
const{layout, line}=require('shargs/usage')conststyle={line: [{width: 40}]}layout([line('Deep Thought was created to come up with'),line('the Answer')])(style)
Result:
Deep Thought was created to come up with
the Answer
layoutMap takes a function f that takes any value
and returns a layout function.
It maps f over the list
and applies its style to each resulting layout function.
Finally, it concatenates the resulting strings and returns the result.
-a, --answer=<number> [default: 42]
The answer.
-h, --help
Prints help.
--version
Prints version.
Layout Decorators
When working with layout functions that take a style as input,
you sometimes want to modify this style just before it is passed to the function,
and only for this function call.
This is what layout decorators are for:
The example shows a sample implementation of defs using the pad layout decorator.
Here, the term, as well as the definition have the same id, texts default id 'line'.
However, we want to add a padding of 4 spaces to the definition.
So we use pad to add 4 spaces to the id at the ['line', 0] path of style.
shargs-usage ships with the following layout decorators:
pad looks up the style object at the path in its style
and modifies it, by adding a number of spaces to its padStart
and subtracting the same number from its width.
It then passes the modified style to its layoutFunction.
stylePath looks up the style object at the path in its style
and modifies it by applying the function f to it.
It then passes the modified style to its layoutFunction.
decorate takes many layout function decorators
and applies them to its layoutFunction from right to left.
Custom Layout Functions
Using your own layout function is straightforward:
Your function only has to have the correct signature and it is ready to be used as a layout function:
It must take a style object and return a string.
The following example showcases the custom table2 layout function that takes columns instead of rows as input:
You may use table2 as a layout function if you apply it to a columns array,
since that returns a function that takes a style argument and returns a string.
This is of course a very simplified example that makes many assumptions that are often not valid
and should not be made in real projects.
Your own function would most probably need much more validations and handling of edge cases.
Custom Usage Functions
Writing and using custom usage functions in shargs is very simple:
You only have to write a function with the correct signature and it can be used as a usage function.
It must take an opt object and a style object and return a string.
The following example shows the custom descs function that displays the options' descriptions:
shargs-core and shargs-parser report errors if a
command-line option's syntax is invalid, or if checks fail.
The following table contains all error codes currently in use and where they are thrown:
If a positional argument is required, all previous positional arguments must be required as well.
The required field must either be undefined, true or false.
A required option has values or defaultValues in the wrong format.
Default values are different depending on the command-line option type:
Commands take objects, flags take counts, and other options take arrays of the correct length.
A config object in this question denotes an object that is used to read in default values from a file or a URI.
Shargs does not include reading and merging config objects because there are other specialized libraries for this task
that are easy to use alongside shargs.
There are several simple ways to combine shargs' args objects with config objects:
If you just want to have default values, you may want to check out the defaultValues options field.
If this does not suffice or you have a different problem, read on.
Say we have read in a config object from somewhere:
constconfig={question: 'How can I use config objects with shargs?',answer: 'Read the FAQ section!'}
And we have run a shargs parser and have obtained the following args object:
constargs={_: [],question: 'What is the meaning of life, the universe, and everything?'}
Then using the config object would just mean merging the two objects:
Of course these example merges are simple cases, because the objects are flat.
In case of subcommands, the args object would have (deeply) nested objects.
Such cases are common and there are specialized libraries for merging deeply nested objects,
like ramda or lodash:
The key field is an apparent difference between shargs and other command-line parsers.
So one might ask, why shargs uses it, while other parsers do not need it.
But as is mostly the case, shargs has good reasons:
Command-line parsers read arguments and assign them to variables that are passed as inputs to programs.
So we are dealing with two different sets of names, here: Names of arguments and names of variables.
Those two sets are connected by a unidirectional mapping, where arguments map to variable names.
If a single argument would only ever map to a single variable, the two could just as well have the same name.
But for more complex mappings, things start to get complex, too:
Say we have two arguments, -v and --version, that can be used interchangeably.
If they would map to two variables, -v and --version,
the program would have to have knowledge about the arguments being interchangeable,
in order to correctly interpret its inputs.
As leaking this knowledge to the program would be undesirable,
parsers usually work around this by assigning the value of one argument to both variables.
But now we are in a situation where we have two dependant variables that always have the same value.
A less verbose solution is just letting both arguments map to the same variable (the key field):
A special situation of two arguments mapping to the same variable is, when the arguments belong to separate options.
This frequently occurs for flag and bool options that have a complement:
In the example, --fun adds 1 to the flag count, while --no-fun adds -1 due to reverse
(assuming the parser has the reverseFlags stage).
But we have other possible mappings yet to explore:
Situations, where one argument maps to two different variable names.
Say we have a --birthday argument and the birthday and age variables.
birthday is a string in date format, while age is a number holding the current age,
transformed by the custom ageAsNumber stage.
This kind of mapping is only possible if the parser's arguments are independent of the program's variables.
So, command-line options have a key field, because:
Separating internal variable names from external argument names is a good practice.
Separating argument and variable names enables functionality that would otherwise not be possible.
Separating arguments and variables makes interpreting variables less verbose for programs.
If you really do not need key fields and wish to use just argument names instead,
it is straight forward to adjust the type function syntax accordingly:
A date is an option that takes exactly one argument, whose type is described as 'date'.
Now we have an option, we may want to write parser stages that work with dates.
How about a stage that transforms dates to their millisecond representation:
This parser stage works alongside the other parser stages.
Note, that a real implementation would test much more edge cases, like dates that occur in arrays.
Can I use comma-separated values to define arrays?
shargs-parser does not include a parser stage
to split comma-separated values into arrays.
But it is easy enough to write a stage yourself:
We are inventing a new option type for this FAQ: commas:
splitCommas may now be used with options of type commas!
So why doesn't shargs-parser support comma-separated values by default?
The reason is that using comma-separated values is just not that common.
And if you nonetheless need comma-separated values, it is simple enough to implement yourself.
Why are --no-* arguments not reversed by the bestGuess* stages?
The reason is because there is no simple way to opt-out of this functionality, once it is employed.
You could add an optOutReverse parameter to each bestGuess* stage, I guess,
but that would clutter the stages' signatures.
So shargs decided to leave interpreting these arguments to the individual programs.
Can I have command-line options with 0..1 values?
An example for such an option would be ternary logics types,
like true, false, unknown,
that could be represented as a mixture of flags
and bools.
Shargs does not support such options out of the box, but you can implement them with some gotchas:
We generally recommend against using options with 0..1 cardinalities in programs.
This is also why shargs does not support it.
A better approach is using an enumeration, implemented with the only options field
and the restrictToOnly parser stage.
If you want to use it anyway, here is how you could do it in shargs:
Flags give you only two cases, the presence of the flag (true if flagsAsBools is used),
and its absence (unknown):
If you provide --fun, the fun variable is set to true, on --no-fun it is set to false,
and providing neither --fun, nor --no-fun would mean unknown.
You could implement the same behavior with an option that takes none or one argument,
by using a combination of variable length arrays,
aka subcommands and a custom command-line options field.
The general idea is to mark a subcommand as threeValued with a field,
and then transform it to a custom type in the opts stage.
subcommandsToThreeValued only transforms subcommands that have the threeValued field.
For each subcommand, it checks, whether the subcommand is not present (unknown),
it is present but has no values (true), or if it is present and has at least one value,
(true if the value is true, false if it is false, otherwise unknown).
Note that this sample implementation is very brittle and should not be used as presented in a program.
Can I use enums?
Yes, you can use enums with a combination of string command-line options,
the only options field,
and the restrictToOnly parser stage:
Can I use keys like 'a.b', indicating object fields?
Some command-line parsers allow arguments of the form --a.b 42,
whose values are stored in nested objects {a: {b: 42}}.
Shargs does not provide this functionality.
However, it is very easy to write your own parser stage for it:
First, let us write a helper function for traversing args objects:
The nestKeys args stage should now nest the values into an object.
The reason why shargs does not include such a stage by default is,
that this is a niche case that can be either implemented after parsing,
or is easy enough to implement yourself.
Why do shargs' functions have several parameter lists?
Many functions have an unusual signature, like text(string)(style)
and the question arises, why it is not text(string, style), instead.
The reason has to do with function composition
and tacit programming:
shargs builds command-line parsers and usage documentation by composing parser
and usage functions with functions it calls combinators.
An exemplary combinator function is layout(functions)(style).
layout takes a list of functions that have a common signature:
They take a style, and return a string.
Next, it takes its own style parameter and feeds it to each function, getting a list of strings.
Then it concatenates all strings together, which results in a string:
What layout basically gives us is a way to provide only one style parameter to a list of functions,
instead of one parameter per function.
But why does layout have to have such a weird signature?
Let us assume we had the following layout2 and text2 functions, instead:
And then we can apply an optimization:
See how we define a function that takes a style and feed it to a function text('First.') that takes a style?
This is redundant, and we can just leave out style altogether:
Now we do not repeat style for every function!
The code is much shorter and is easier to read.
And we can do even better by using a signature like layout.
Because then layout is also a function that takes a style and returns a string,
like text, and can be used inside other layout functions!
And although we have five functions that each take a style parameter, we only have to apply it once.
Shargs employs tacit programming techniques to reduce boilerplate in its DSLs.
A side-effect is that function signatures are weird (the technical term is curried).
Some JavaScript libraries like Ramda and lodash/fp use a technique called auto-currying.
If layout would be auto-curried, it would have the signatures of layout
and layout2 at the same time and you could choose which one to use.
Shargs decided against auto-currying its functions,
since it is simple enough to curry your functions yourself if you wanted:
We are open to, and grateful for, any contributions made by the community.
By contributing to shargs, you agree to abide by the code of conduct.
Please read the contributing guide.