Socket
Socket
Sign inDemoInstall

command-line-args

Package Overview
Dependencies
Maintainers
1
Versions
74
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

command-line-args - npm Package Compare versions

Comparing version 1.0.0-3 to 1.1.0-0

example/alias.js

27

bin/cli.js
#!/usr/bin/env node
"use strict";
var cliArgs = require("../");
var os = require("os");
var fs = require("fs");
var path = require("path");
var ansi = require("ansi-escape-sequences");
var tmpPath = path.join(os.tmpDir(), Date.now() + "-cla.js");
process.stdin
.pipe(fs.createWriteStream(tmpPath))
.on("close", parseCla);
function parseCla(){
var cliOptions = require(tmpPath);
fs.unlinkSync(tmpPath);
var cli = cliArgs(cliOptions);
try {
console.log(cli.parse());
} catch(err){
halt(err.message);
}
}
function halt(msg){
console.error(ansi.format(msg, "red"));
process.exit(1);
}

38

lib/command-line-args.js

@@ -17,11 +17,15 @@ "use strict";

/**
@param {module:command-line-args.argDefType}
@param {string[]}
@returns {object}
@class
@param {module:definition[]}
@alias module:command-line-args
*/
function CliArgs(definitions, argv){
if (!(this instanceof CliArgs)) return new CliArgs(definitions, argv);
function CliArgs(definitions){
if (!(this instanceof CliArgs)) return new CliArgs(definitions);
this.definitions = new Definitions(definitions);
}
/**
@param [argv] {string[]} - parses `process.argv` by default, unless you pass this
@returns {object}
*/
CliArgs.prototype.parse = function(argv){

@@ -38,8 +42,2 @@ var self = this;

/* validate input */
var invalidMessage = this.definitions.validate(argv);
if (invalidMessage){
throw Error(invalidMessage);
}
/* expand getopt-style combined options */

@@ -57,2 +55,8 @@ var combinedArg = option.combined;

/* validate input */
var invalidMessage = this.definitions.validate(argv);
if (invalidMessage){
throw Error(invalidMessage);
}
/* create output initialised with default values */

@@ -88,3 +92,2 @@ var output = this.definitions.createOutput();

_all: output,
_none: {}
};

@@ -94,4 +97,4 @@

a.arrayify(def.group).forEach(function(groupName){
grouped[groupName] = grouped[groupName] || {};
if (t.isDefined(output[def.name])){
grouped[groupName] = grouped[groupName] || {};
grouped[groupName][def.name] = output[def.name];

@@ -104,2 +107,3 @@ }

if (t.isDefined(output[def.name])){
if (!grouped._none) grouped._none = {};
grouped._none[def.name] = output[def.name];

@@ -114,2 +118,6 @@ }

/**
@param [options] {module:usage-options}
@returns {string}
*/
CliArgs.prototype.getUsage = function(options){

@@ -119,6 +127,2 @@ return cliUsage(this.definitions.val(), options);

CliArgs.prototype.setUsage = function(usageGenerator){
cliUsage = usageGenerator;
};
function outputSet(output, property, value){

@@ -125,0 +129,0 @@ if (Array.isArray(output[property])){

@@ -25,7 +25,2 @@ "use strict";

/**
@type {string}
*/
this.description = definition.description;
/**
a single character

@@ -52,10 +47,10 @@ @type {string}

/**
@type {boolean}
@type {*}
*/
this.required = definition.required;
this.defaultValue = definition.defaultValue;
/**
@type {boolean}
@type {string}
*/
this.value = definition.value;
this.description = definition.description;
}

@@ -62,0 +57,0 @@

@@ -9,2 +9,3 @@ "use strict";

@module definitions
@private
*/

@@ -52,3 +53,3 @@ module.exports = Definitions;

this.forEach(function(def){
if (def.value) output[def.name] = def.value;
if (def.defaultValue) output[def.name] = def.defaultValue;
});

@@ -55,0 +56,0 @@ return output;

@@ -5,2 +5,3 @@ "use strict";

@module option
@private
*/

@@ -7,0 +8,0 @@

{
"name": "command-line-args",
"version": "1.0.0-3",
"description": "Command-line parser, usage text producer",
"version": "1.1.0-0",
"description": "A library to collect command-line args and generate a usage guide.",
"repository": "https://github.com/75lb/command-line-args.git",
"main": "lib/command-line-args",
"cla": "bin.cli.js",
"bin": "bin/cli.js",
"scripts": {
"test": "tape test/*.js",
"docs": "jsdoc2md -t jsdoc2md/README.hbs lib/*.js > README.md; echo"
"docs": "jsdoc2md -t jsdoc2md/README.hbs lib/*.js node_modules/command-line-usage/lib/usage-options.js > README.md; echo"
},

@@ -21,3 +21,4 @@ "keywords": [

"cli",
"command"
"command",
"line"
],

@@ -28,5 +29,7 @@ "author": "Lloyd Brookes",

"jsdoc-to-markdown": "^1.1.1",
"tape": "^4"
"tape": "^4",
"test-value": "^1.0.0"
},
"dependencies": {
"ansi-escape-sequences": "^2.1.1",
"array-tools": "^2",

@@ -33,0 +36,0 @@ "command-line-usage": "^1",

@@ -7,15 +7,236 @@ [![view on npm](http://img.shields.io/npm/v/command-line-args.svg)](https://www.npmjs.org/package/command-line-args)

# command-line-args
Collect command-line options, generate a usage guide..
A library to collect command-line args and generate a usage guide.
- Support most option notation styles
- long options (`--find lib.js`)
- short options (`-f lib.js`)
- getopt-style combinations (`-xvf lib.js`)
- option=val style (`--find=lib.js`)
- Customisable usage guide generator
- Modular - define reusage option sets.
- Split options into groups, for apps with a large set of options.
- Fine control over validation, type
## Synopsis
First, create a command-line-args instance passing the option definitions your app accepts.
```js
var cliArgs = require("command-line-args");
var cli = cliArgs([
{
name: "help", description: "Display this usage guide.",
alias: "h", type: Boolean
},
{
name: "files", description: "The input files to process",
alias: "f", type: String, multiple: true, defaultOption: true
},
{
name: "timeout", description: "Timeout value in ms",
alias: "t", type: Number,
}
]);
```
Now, the `cli` instance above has two main operations - `.parse()` and `.getUsage()`.
So if your app was run with a command like this:
```sh
$ my-app -vt 1000 lib/*.js
```
..then `cli.parse()` would return the command-line options and values in a stucture like this:
```js
{
files: [
"lib/command-line-args.js",
"lib/definition.js",
"lib/definitions.js",
"lib/option.js"
],
verbose: true,
timeout: 1000
}
```
and `cli.getUsage(options)` would return:
```
a typical app
Generates something useful
Usage
$ cat input.json | my-app [<options>]
$ my-app <files>
Main options
This group contains the most important options.
-h, --help Display this usage guide.
-f, --files <string[]> The input files to process
-t, --timeout <number> Timeout value in ms
Project home: https://github.com/me/my-app
```
## Option definitions
Options are defined as an array of Definition objects. You can walk through all these files yourself by piping each example into the test harness.
### Name
The only required definition property is `name`, so the simplest working example is
```js
[
{ name: "file" },
{ name: "verbose" },
{ name: "depth"}
]
```
In this case, the value of each option will be either a Boolean or string.
#### Examples
| # | Command line args | parse output |
| --- | -------------------- | ------------ |
| 1 | `--file` | `{ file: true }` |
| 2 | `--file lib.js --verbose` | `{ file: "lib.js", verbose: true }` |
| 3 | `--verbose very` | `{ verbose: "very" }` |
| 4 | `--depth 2` | `{ depth: "2" }` |
### Type
Take control and be more specific about type..
```js
var fs = require("fs");
function FileDetails(filename){
if (!(this instanceof FileDetails)) return new FileDetails(filename);
this.filename = filename;
this.exists = fs.existsSync(filename);
}
module.exports = [
{ name: "file", type: FileDetails },
{ name: "depth", type: Number }
];
```
| # | Command line args| parse output |
| --- | ----------------- | ------------ |
| 5 | `--file asdf.txt` | `{ file: { filename: 'asdf.txt', exists: false } }` |
in 1, main was passed but is set to null (not true, as before) meaning "no value was specified".
| # | Command line args | parse output |
| --- | ----------------- | ------------ |
| 6 | `--depth` | `{ depth: null }` |
| 6 | `--depth 2` | `{ depth: 2 }` |
### Alias
Short option names.
```js
[
{ name: "hot", alias: "h", type: Boolean },
{ name: "discount", alias: "d", type: Boolean },
{ name: "courses", alias: "c" , type: Number }
]
```
| # | Command line | parse output |
| --- | ------------ | ------------ |
| 7 | `-hcd` | `{ hot: true, courses: null, discount: true }` |
| 7 | `-hdc 3` | `{ hot: true, discount: true, courses: 3 }` |
### Multiple option values
```js
module.exports = [
{ name: "files", type: String, multiple: true }
];
```
| # | Command line | parse output |
| --- | ------------ | ------------ |
| 8 | `--files one.js two.js` | `{ files: [ 'one.js', 'two.js' ] }` |
| 9 | `--files one.js --files two.js` | `{ files: [ 'one.js', 'two.js' ] }` |
| 10 | `--files *` | `{ files: [ 'one.js', 'two.js' ] }` |
### Default option
```js
module.exports = [
{ name: "files", type: String, multiple: true, defaultOption: true }
];
```
| # | Command line | parse output |
| --- | ------------ | ------------ |
| 11 | `--files one.js two.js` | `{ files: [ 'one.js', 'two.js' ] }` |
| 11 | `one.js two.js` | `{ files: [ 'one.js', 'two.js' ] }` |
| 12 | `*` | `{ files: [ 'one.js', 'two.js' ] }` |
### Default option value
```js
module.exports = [
{ name: "files", type: String, multiple: true, defaultValue: [ "one.js" ] },
{ name: "max", type: Number, defaultValue: 3 }
];
```
| # | Command line | parse output |
| --- | ------------ | ------------ |
| 13 | | `{ files: [ 'one.js' ], max: 3 }` |
| 14 | `--files two.js` | `{ files: [ 'one.js', 'two.js' ], max: 3 }` |
| 15 | `--max 4` | `{ files: [ 'one.js' ], max: 4 }` |
### Group
When your app has a large amount of options it makes sense to organise them in groups. For example, you may want to delegate the `video`and `audio` options to separate 3rd party libraries.
```js
module.exports = [
{ name: "verbose", group: "standard" },
{ name: "help", group: [ "standard", "main" ] },
{ name: "compress", group: [ "server", "main" ] },
{ name: "static", group: "server" },
{ name: "debug" }
];
```
| # | Command line | parse output |
| --- | ------------ | ------------ |
| 13 | `--verbose` | `{ _all: { verbose: true }, standard: { verbose: true } }` |
| 14 | `--debug` | `{ _all: { debug: true }, _none: { debug: true } }` |
| 15 | `--verbose --debug --compress` | `{ _all: { verbose: true, debug: true, compress: true }, standard: { verbose: true }, server: { compress: true }, main: { compress: true }, _none: { debug: true } }` |
| 15 | `--compress` | `{ _all: { compress: true }, server: { compress: true }, main: { compress: true } }` |
### Validate
Validation is out of scope for this library, which collects values only. Validate using another module or some code of your own. This example uses [test-value](https://github.com/75lb/test-value).
```js
var cliArgs = require("../");
var testValue = require("test-value");
var fs = require("fs");
var cli = cliArgs([
{ name: "help", type: Boolean },
{ name: "files", type: String, multiple: true, defaultOption: true },
{ name: "log-level", type: String }
]);
var options = cli.parse();
var usageForm = {};
usageForm.main = {
files: function(files){
return files && files.every(fs.existsSync);
},
"log-level": [ "info", "warn", "error", undefined ]
};
usageForm.help = {
help: true
};
var valid = testValue(options, [ usageForm.main, usageForm.help ]);
if (!valid){
// exit here
}
```
## Install
### as a library
```sh

@@ -25,3 +246,21 @@ $ npm install command-line-args --save

### as a command-line tool
```sh
$ npm install -g command-line-args
```
If you install globally you get the `command-line-args` test-harness. You test by piping in a module exporting an option definitions array,
All the following examples can be sampled by installing the command-line-args test harness (install globally). Usage:
```sh
$ cat example/one.js | command-line-args --main
{ main: true }
$ cat example/one.js | command-line-args --main --dessert
{ main: true, dessert: true }
```
# API Reference

@@ -34,18 +273,40 @@ ## Modules

<dd></dd>
<dt><a href="#module_definitions">definitions</a></dt>
<dt><a href="#module_usage-options">usage-options</a></dt>
<dd></dd>
<dt><a href="#module_option">option</a></dt>
<dd></dd>
</dl>
<a name="module_command-line-args"></a>
## command-line-args
* [command-line-args](#module_command-line-args)
* [CliArgs](#exp_module_command-line-args--CliArgs) ⏏
* [new CliArgs(definitions)](#new_module_command-line-args--CliArgs_new)
* [.parse([argv])](#module_command-line-args--CliArgs+parse) ⇒ <code>object</code>
* [.getUsage([options])](#module_command-line-args--CliArgs+getUsage) ⇒ <code>string</code>
<a name="exp_module_command-line-args--CliArgs"></a>
### CliArgs(definitions, argv) ⇒ <code>object</code> ⏏
**Kind**: Exported function
### CliArgs ⏏
**Kind**: Exported class
<a name="new_module_command-line-args--CliArgs_new"></a>
#### new CliArgs(definitions)
| Param | Type |
| --- | --- |
| definitions | <code>module:command-line-args.argDefType</code> |
| argv | <code>Array.&lt;string&gt;</code> |
| definitions | <code>[Array.&lt;definition&gt;](#module_definition)</code> |
<a name="module_command-line-args--CliArgs+parse"></a>
#### cliArgs.parse([argv]) ⇒ <code>object</code>
**Kind**: instance method of <code>[CliArgs](#exp_module_command-line-args--CliArgs)</code>
| Param | Type | Description |
| --- | --- | --- |
| [argv] | <code>Array.&lt;string&gt;</code> | parses `process.argv` by default, unless you pass this |
<a name="module_command-line-args--CliArgs+getUsage"></a>
#### cliArgs.getUsage([options]) ⇒ <code>string</code>
**Kind**: instance method of <code>[CliArgs](#exp_module_command-line-args--CliArgs)</code>
| Param | Type |
| --- | --- |
| [options] | <code>[usage-options](#module_usage-options)</code> |
<a name="module_definition"></a>

@@ -58,3 +319,2 @@ ## definition

* [.type](#module_definition--Definition+type) : <code>function</code>
* [.description](#module_definition--Definition+description) : <code>string</code>
* [.alias](#module_definition--Definition+alias) : <code>string</code>

@@ -64,3 +324,4 @@ * [.multiple](#module_definition--Definition+multiple) : <code>boolean</code>

* [.group](#module_definition--Definition+group) : <code>string</code> &#124; <code>Array.&lt;string&gt;</code>
* [.value](#module_definition--Definition+value) : <code>boolean</code>
* [.defaultValue](#module_definition--Definition+defaultValue) : <code>\*</code>
* [.description](#module_definition--Definition+description) : <code>string</code>

@@ -78,5 +339,2 @@ <a name="exp_module_definition--Definition"></a>

**Kind**: instance property of <code>[Definition](#exp_module_definition--Definition)</code>
<a name="module_definition--Definition+description"></a>
#### definition.description : <code>string</code>
**Kind**: instance property of <code>[Definition](#exp_module_definition--Definition)</code>
<a name="module_definition--Definition+alias"></a>

@@ -96,11 +354,110 @@ #### definition.alias : <code>string</code>

**Kind**: instance property of <code>[Definition](#exp_module_definition--Definition)</code>
<a name="module_definition--Definition+value"></a>
#### definition.value : <code>boolean</code>
<a name="module_definition--Definition+defaultValue"></a>
#### definition.defaultValue : <code>\*</code>
**Kind**: instance property of <code>[Definition](#exp_module_definition--Definition)</code>
<a name="module_definitions"></a>
## definitions
<a name="module_option"></a>
## option
<a name="module_definition--Definition+description"></a>
#### definition.description : <code>string</code>
**Kind**: instance property of <code>[Definition](#exp_module_definition--Definition)</code>
<a name="module_usage-options"></a>
## usage-options
* [usage-options](#module_usage-options)
* [UsageOptions](#exp_module_usage-options--UsageOptions) ⏏
* _instance_
* [.title](#module_usage-options--UsageOptions+title) : <code>string</code> &#124; <code>[textObject](#module_usage-options--UsageOptions..textObject)</code>
* [.description](#module_usage-options--UsageOptions+description) : <code>string</code> &#124; <code>[textObject](#module_usage-options--UsageOptions..textObject)</code>
* [.usage](#module_usage-options--UsageOptions+usage) : <code>object</code>
* [.groups](#module_usage-options--UsageOptions+groups) : <code>object</code>
* [.footer](#module_usage-options--UsageOptions+footer) : <code>string</code> &#124; <code>[textObject](#module_usage-options--UsageOptions..textObject)</code>
* [.hide](#module_usage-options--UsageOptions+hide) : <code>string</code> &#124; <code>Array.&lt;string&gt;</code>
* _inner_
* [~textObject](#module_usage-options--UsageOptions..textObject)
<a name="exp_module_usage-options--UsageOptions"></a>
### UsageOptions ⏏
The class describes all valid options for the `getUsage` function. Inline formatting can be used within any text string supplied using valid [ansi-escape-sequences formatting syntax](https://github.com/75lb/ansi-escape-sequences#module_ansi-escape-sequences.format).
**Kind**: Exported class
<a name="module_usage-options--UsageOptions+title"></a>
#### options.title : <code>string</code> &#124; <code>[textObject](#module_usage-options--UsageOptions..textObject)</code>
The title line at the top of the usage, typically the name of the app. By default it is underlined but this formatting can be overridden by passing a [textObject](#module_usage-options--UsageOptions..textObject).
**Kind**: instance property of <code>[UsageOptions](#exp_module_usage-options--UsageOptions)</code>
**Example**
```js
{
title: {
text: "my-app",
format: [ "bold", "underline" ]
}
}
```
<a name="module_usage-options--UsageOptions+description"></a>
#### options.description : <code>string</code> &#124; <code>[textObject](#module_usage-options--UsageOptions..textObject)</code>
A description to go underneath the title. For example, some words about what the app is for.
**Kind**: instance property of <code>[UsageOptions](#exp_module_usage-options--UsageOptions)</code>
<a name="module_usage-options--UsageOptions+usage"></a>
#### options.usage : <code>object</code>
An array of strings highlighting the main usage forms of the app.
**Kind**: instance property of <code>[UsageOptions](#exp_module_usage-options--UsageOptions)</code>
**Properties**
| Name | Type | Default |
| --- | --- | --- |
| title | <code>string</code> &#124; <code>[textObject](#module_usage-options--UsageOptions..textObject)</code> | <code>&quot;Usage&quot;</code> |
| format | <code>string</code> &#124; <code>Array.&lt;string&gt;</code> | |
**Example**
```js
{
usage: {
title: "Synopsis",
forms: [
"$ my-app <options> <files>",
"$ my-app [-cvh]"
]
}
}
```
<a name="module_usage-options--UsageOptions+groups"></a>
#### options.groups : <code>object</code>
Specify which groups to display in the output by supplying an object of key/value pairs, where the key is the name of the group to include and the value is a string or textObject. If the value is a string it is used as the group title. Alternatively supply an object containing a `title` and `description` string.
**Kind**: instance property of <code>[UsageOptions](#exp_module_usage-options--UsageOptions)</code>
**Example**
```js
{
main: {
title: "Main options",
description: "This group contains the most important options."
},
misc: "Miscellaneous"
}
```
<a name="module_usage-options--UsageOptions+footer"></a>
#### options.footer : <code>string</code> &#124; <code>[textObject](#module_usage-options--UsageOptions..textObject)</code>
Displayed at the foot of the usage output.
**Kind**: instance property of <code>[UsageOptions](#exp_module_usage-options--UsageOptions)</code>
<a name="module_usage-options--UsageOptions+hide"></a>
#### options.hide : <code>string</code> &#124; <code>Array.&lt;string&gt;</code>
If you want to hide certain options from the output, specify their names here.
**Kind**: instance property of <code>[UsageOptions](#exp_module_usage-options--UsageOptions)</code>
<a name="module_usage-options--UsageOptions..textObject"></a>
#### options~textObject
Contains text and formatting information.
**Kind**: inner typedef of <code>[UsageOptions](#exp_module_usage-options--UsageOptions)</code>
**Properties**
| Name | Type | Description |
| --- | --- | --- |
| text | <code>string</code> | |
| format | <code>string</code> &#124; <code>Array.&lt;string&gt;</code> | one or more ansi style names from [this list](https://github.com/75lb/ansi-escape-sequences#module_ansi-escape-sequences.style). |
* * *
&copy; 2015 Lloyd Brookes \<75pound@gmail.com\>. Documented by [jsdoc-to-markdown](https://github.com/75lb/jsdoc-to-markdown).

@@ -5,17 +5,17 @@ var test = require("tape");

test("default value", function(t){
t.deepEqual(cliArgs([ { name: "one" }, { name: "two", value: "two" } ]).parse([ "--one", "1" ]), {
t.deepEqual(cliArgs([ { name: "one" }, { name: "two", defaultValue: "two" } ]).parse([ "--one", "1" ]), {
one: "1",
two: "two"
});
t.deepEqual(cliArgs([{ name: "two", value: "two" }]).parse([]), {
t.deepEqual(cliArgs([{ name: "two", defaultValue: "two" }]).parse([]), {
two: "two"
});
t.deepEqual(cliArgs([{ name: "two", value: "two" }]).parse([ "--two", "zwei" ]), {
t.deepEqual(cliArgs([{ name: "two", defaultValue: "two" }]).parse([ "--two", "zwei" ]), {
two: "zwei"
});
t.deepEqual(cliArgs([{ name: "two", multiple: true, value: ["two", "zwei"] }]).parse([ ]), {
t.deepEqual(cliArgs([{ name: "two", multiple: true, defaultValue: ["two", "zwei"] }]).parse([ ]), {
two: [ "two", "zwei" ]
});
t.deepEqual(
cliArgs([{ name: "two", multiple: true, value: ["two", "zwei"] }]).parse([ "--two", "duo" ]),
cliArgs([{ name: "two", multiple: true, defaultValue: ["two", "zwei"] }]).parse([ "--two", "duo" ]),
{ two: [ "two", "zwei", "duo" ] }

@@ -22,0 +22,0 @@ );

@@ -19,1 +19,9 @@ var test = require("tape");

});
test("getOpts: non-existent options", function(t){
var argv = [ "-sdf" ];
t.throws(function(){
cliArgs(optionDefinitions).parse(argv);
}, /invalid/i);
t.end();
});

@@ -20,3 +20,2 @@ var test = require("tape");

},
_none: {},
_all: {

@@ -23,0 +22,0 @@ one: "1",

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc