Commit 0ae470fd authored by Rosanny Sihombing's avatar Rosanny Sihombing
Browse files

Merge branch 'MLAB-670' into 'testing'

Update required modules

See merge request !162
parents cad730bf d27c335f
Pipeline #6650 passed with stage
in 4 seconds
import type { GenMapping } from '@jridgewell/gen-mapping';
import type { DecodedSourceMap, EncodedSourceMap, Options } from './types';
/**
* A SourceMap v3 compatible sourcemap, which only includes fields that were
* provided to it.
*/
export default class SourceMap {
file?: string | null;
mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];
sourceRoot?: string;
names: string[];
sources: (string | null)[];
sourcesContent?: (string | null)[];
version: 3;
constructor(map: GenMapping, options: Options);
toString(): string;
}
import type { SourceMapInput } from '@jridgewell/trace-mapping';
export type { SourceMapSegment, DecodedSourceMap, EncodedSourceMap, } from '@jridgewell/trace-mapping';
export type { SourceMapInput };
export declare type LoaderContext = {
readonly importer: string;
readonly depth: number;
source: string;
content: string | null | undefined;
};
export declare type SourceMapLoader = (file: string, ctx: LoaderContext) => SourceMapInput | null | undefined | void;
export declare type Options = {
excludeContent?: boolean;
decodedMappings?: boolean;
};
{
"name": "@ampproject/remapping",
"version": "2.2.0",
"description": "Remap sequential sourcemaps through transformations to point at the original source code",
"keywords": [
"source",
"map",
"remap"
],
"main": "dist/remapping.umd.js",
"module": "dist/remapping.mjs",
"typings": "dist/types/remapping.d.ts",
"files": [
"dist"
],
"author": "Justin Ridgewell <jridgewell@google.com>",
"repository": {
"type": "git",
"url": "git+https://github.com/ampproject/remapping.git"
},
"license": "Apache-2.0",
"engines": {
"node": ">=6.0.0"
},
"scripts": {
"build": "run-s -n build:*",
"build:rollup": "rollup -c rollup.config.js",
"build:ts": "tsc --project tsconfig.build.json",
"lint": "run-s -n lint:*",
"lint:prettier": "npm run test:lint:prettier -- --write",
"lint:ts": "npm run test:lint:ts -- --fix",
"prebuild": "rm -rf dist",
"prepublishOnly": "npm run preversion",
"preversion": "run-s test build",
"test": "run-s -n test:lint test:only",
"test:debug": "node --inspect-brk node_modules/.bin/jest --runInBand",
"test:lint": "run-s -n test:lint:*",
"test:lint:prettier": "prettier --check '{src,test}/**/*.ts'",
"test:lint:ts": "eslint '{src,test}/**/*.ts'",
"test:only": "jest --coverage",
"test:watch": "jest --coverage --watch"
},
"devDependencies": {
"@rollup/plugin-typescript": "8.3.2",
"@types/jest": "27.4.1",
"@typescript-eslint/eslint-plugin": "5.20.0",
"@typescript-eslint/parser": "5.20.0",
"eslint": "8.14.0",
"eslint-config-prettier": "8.5.0",
"jest": "27.5.1",
"jest-config": "27.5.1",
"npm-run-all": "4.1.5",
"prettier": "2.6.2",
"rollup": "2.70.2",
"ts-jest": "27.1.4",
"tslib": "2.4.0",
"typescript": "4.6.3"
},
"dependencies": {
"@jridgewell/gen-mapping": "^0.1.0",
"@jridgewell/trace-mapping": "^0.3.9"
}
}
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @babel/cli
> Babel command line.
See our website [@babel/cli](https://babeljs.io/docs/en/babel-cli) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20cli%22+is%3Aopen) associated with this package.
## Install
Using npm:
```sh
npm install --save-dev @babel/cli
```
or using yarn:
```sh
yarn add @babel/cli --dev
```
#!/usr/bin/env node
require("../lib/babel-external-helpers");
#!/usr/bin/env node
require("../lib/babel");
throw new Error("Use the `@babel/core` package instead of `@babel/cli`.");
"use strict";
function _commander() {
const data = require("commander");
_commander = function () {
return data;
};
return data;
}
function _core() {
const data = require("@babel/core");
_core = function () {
return data;
};
return data;
}
function collect(value, previousValue) {
if (typeof value !== "string") return previousValue;
const values = value.split(",");
if (previousValue) {
previousValue.push(...values);
return previousValue;
}
return values;
}
_commander().option("-l, --whitelist [whitelist]", "Whitelist of helpers to ONLY include", collect);
_commander().option("-t, --output-type [type]", "Type of output (global|umd|var)", "global");
_commander().usage("[options]");
_commander().parse(process.argv);
console.log((0, _core().buildExternalHelpers)(_commander().whitelist, _commander().outputType));
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
function _slash() {
const data = require("slash");
_slash = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _fs() {
const data = require("fs");
_fs = function () {
return data;
};
return data;
}
var util = require("./util");
var watcher = require("./watcher");
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
const FILE_TYPE = Object.freeze({
NON_COMPILABLE: "NON_COMPILABLE",
COMPILED: "COMPILED",
IGNORED: "IGNORED",
ERR_COMPILATION: "ERR_COMPILATION"
});
function outputFileSync(filePath, data) {
(((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "10.12") ? _fs().mkdirSync : require("make-dir").sync)(_path().dirname(filePath), {
recursive: true
});
_fs().writeFileSync(filePath, data);
}
function _default(_x) {
return _ref.apply(this, arguments);
}
function _ref() {
_ref = _asyncToGenerator(function* ({
cliOptions,
babelOptions
}) {
function write(_x2, _x3) {
return _write.apply(this, arguments);
}
function _write() {
_write = _asyncToGenerator(function* (src, base) {
let relative = _path().relative(base, src);
if (!util.isCompilableExtension(relative, cliOptions.extensions)) {
return FILE_TYPE.NON_COMPILABLE;
}
relative = util.withExtension(relative, cliOptions.keepFileExtension ? _path().extname(relative) : cliOptions.outFileExtension);
const dest = getDest(relative, base);
try {
const res = yield util.compile(src, Object.assign({}, babelOptions, {
sourceFileName: _slash()(_path().relative(dest + "/..", src))
}));
if (!res) return FILE_TYPE.IGNORED;
if (res.map && babelOptions.sourceMaps && babelOptions.sourceMaps !== "inline") {
const mapLoc = dest + ".map";
res.code = util.addSourceMappingUrl(res.code, mapLoc);
res.map.file = _path().basename(relative);
outputFileSync(mapLoc, JSON.stringify(res.map));
}
outputFileSync(dest, res.code);
util.chmod(src, dest);
if (cliOptions.verbose) {
console.log(_path().relative(process.cwd(), src) + " -> " + dest);
}
return FILE_TYPE.COMPILED;
} catch (err) {
if (cliOptions.watch) {
console.error(err);
return FILE_TYPE.ERR_COMPILATION;
}
throw err;
}
});
return _write.apply(this, arguments);
}
function getDest(filename, base) {
if (cliOptions.relative) {
return _path().join(base, cliOptions.outDir, filename);
}
return _path().join(cliOptions.outDir, filename);
}
function handleFile(_x4, _x5) {
return _handleFile.apply(this, arguments);
}
function _handleFile() {
_handleFile = _asyncToGenerator(function* (src, base) {
const written = yield write(src, base);
if (cliOptions.copyFiles && written === FILE_TYPE.NON_COMPILABLE || cliOptions.copyIgnored && written === FILE_TYPE.IGNORED) {
const filename = _path().relative(base, src);
const dest = getDest(filename, base);
outputFileSync(dest, _fs().readFileSync(src));
util.chmod(src, dest);
}
return written === FILE_TYPE.COMPILED;
});
return _handleFile.apply(this, arguments);
}
function handle(_x6) {
return _handle.apply(this, arguments);
}
function _handle() {
_handle = _asyncToGenerator(function* (filenameOrDir) {
if (!_fs().existsSync(filenameOrDir)) return 0;
const stat = _fs().statSync(filenameOrDir);
if (stat.isDirectory()) {
const dirname = filenameOrDir;
let count = 0;
const files = util.readdir(dirname, cliOptions.includeDotfiles);
for (const filename of files) {
const src = _path().join(dirname, filename);
const written = yield handleFile(src, dirname);
if (written) count += 1;
}
return count;
} else {
const filename = filenameOrDir;
const written = yield handleFile(filename, _path().dirname(filename));
return written ? 1 : 0;
}
});
return _handle.apply(this, arguments);
}
let compiledFiles = 0;
let startTime = null;
const logSuccess = util.debounce(function () {
if (startTime === null) {
return;
}
const diff = process.hrtime(startTime);
console.log(`Successfully compiled ${compiledFiles} ${compiledFiles !== 1 ? "files" : "file"} with Babel (${diff[0] * 1e3 + Math.round(diff[1] / 1e6)}ms).`);
compiledFiles = 0;
startTime = null;
}, 100);
if (cliOptions.watch) watcher.enable({
enableGlobbing: true
});
if (!cliOptions.skipInitialBuild) {
if (cliOptions.deleteDirOnStart) {
util.deleteDir(cliOptions.outDir);
}
(((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "10.12") ? _fs().mkdirSync : require("make-dir").sync)(cliOptions.outDir, {
recursive: true
});
startTime = process.hrtime();
for (const filename of cliOptions.filenames) {
compiledFiles += yield handle(filename);
}
if (!cliOptions.quiet) {
logSuccess();
logSuccess.flush();
}
}
if (cliOptions.watch) {
let processing = 0;
const {
filenames
} = cliOptions;
let getBase;
if (filenames.length === 1) {
const base = filenames[0];
const absoluteBase = _path().resolve(base);
getBase = filename => {
return filename === absoluteBase ? _path().dirname(base) : base;
};
} else {
const filenameToBaseMap = new Map(filenames.map(filename => {
const absoluteFilename = _path().resolve(filename);
return [absoluteFilename, _path().dirname(filename)];
}));
const absoluteFilenames = new Map(filenames.map(filename => {
const absoluteFilename = _path().resolve(filename);
return [absoluteFilename, filename];
}));
const {
sep
} = _path();
getBase = filename => {
const base = filenameToBaseMap.get(filename);
if (base !== undefined) {
return base;
}
for (const [absoluteFilenameOrDir, relative] of absoluteFilenames) {
if (filename.startsWith(absoluteFilenameOrDir + sep)) {
filenameToBaseMap.set(filename, relative);
return relative;
}
}
return "";
};
}
filenames.forEach(filenameOrDir => {
watcher.watch(filenameOrDir);
});
watcher.onFilesChange(_asyncToGenerator(function* (filenames) {
processing++;
if (startTime === null) startTime = process.hrtime();
try {
const written = yield Promise.all(filenames.map(filename => handleFile(filename, getBase(filename))));
compiledFiles += written.filter(Boolean).length;
} catch (err) {
console.error(err);
}
processing--;
if (processing === 0 && !cliOptions.quiet) logSuccess();
}));
}
});
return _ref.apply(this, arguments);
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
function _convertSourceMap() {
const data = require("convert-source-map");
_convertSourceMap = function () {
return data;
};
return data;
}
function _traceMapping() {
const data = require("@jridgewell/trace-mapping");
_traceMapping = function () {
return data;
};
return data;
}
function _slash() {
const data = require("slash");
_slash = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _fs() {
const data = require("fs");
_fs = function () {
return data;
};
return data;
}
var util = require("./util");
var watcher = require("./watcher");
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _default(_x) {
return _ref.apply(this, arguments);
}
function _ref() {
_ref = _asyncToGenerator(function* ({
cliOptions,
babelOptions
}) {
function buildResult(fileResults) {
const mapSections = [];
let code = "";
let offset = 0;
for (const result of fileResults) {
if (!result) continue;
mapSections.push({
offset: {
line: offset,
column: 0
},
map: result.map || emptyMap()
});
code += result.code + "\n";
offset += countNewlines(result.code) + 1;
}
const map = new (_traceMapping().AnyMap)({
version: 3,
file: cliOptions.sourceMapTarget || _path().basename(cliOptions.outFile || "") || "stdout",
sections: mapSections
});
map.sourceRoot = babelOptions.sourceRoot;
if (babelOptions.sourceMaps === "inline" || !cliOptions.outFile && babelOptions.sourceMaps) {
code += "\n" + _convertSourceMap().fromObject((0, _traceMapping().encodedMap)(map)).toComment();
}
return {
map: map,
code: code
};
}
function countNewlines(code) {
let count = 0;
let index = -1;
while ((index = code.indexOf("\n", index + 1)) !== -1) {
count++;
}
return count;
}
function emptyMap() {
return {
version: 3,
names: [],
sources: [],
mappings: []
};
}
function output(fileResults) {
const result = buildResult(fileResults);
if (cliOptions.outFile) {
(((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "10.12") ? _fs().mkdirSync : require("make-dir").sync)(_path().dirname(cliOptions.outFile), {
recursive: true
});
if (babelOptions.sourceMaps && babelOptions.sourceMaps !== "inline") {
const mapLoc = cliOptions.outFile + ".map";
result.code = util.addSourceMappingUrl(result.code, mapLoc);
_fs().writeFileSync(mapLoc, JSON.stringify((0, _traceMapping().encodedMap)(result.map)));
}
_fs().writeFileSync(cliOptions.outFile, result.code);
} else {
process.stdout.write(result.code + "\n");
}
}
function readStdin() {
return new Promise((resolve, reject) => {
let code = "";
process.stdin.setEncoding("utf8");
process.stdin.on("readable", function () {
const chunk = process.stdin.read();
if (chunk !== null) code += chunk;
});
process.stdin.on("end", function () {
resolve(code);
});
process.stdin.on("error", reject);
});
}
function stdin() {
return _stdin.apply(this, arguments);
}
function _stdin() {
_stdin = _asyncToGenerator(function* () {
const code = yield readStdin();
const res = yield util.transformRepl(cliOptions.filename, code, Object.assign({}, babelOptions, {
sourceFileName: "stdin"
}));
output([res]);
});
return _stdin.apply(this, arguments);
}
function walk(_x2) {
return _walk.apply(this, arguments);
}
function _walk() {
_walk = _asyncToGenerator(function* (filenames) {
const _filenames = [];
filenames.forEach(function (filename) {
if (!_fs().existsSync(filename)) return;
const stat = _fs().statSync(filename);
if (stat.isDirectory()) {
const dirname = filename;
util.readdirForCompilable(filename, cliOptions.includeDotfiles, cliOptions.extensions).forEach(function (filename) {
_filenames.push(_path().join(dirname, filename));
});
} else {
_filenames.push(filename);
}
});
const results = yield Promise.all(_filenames.map(_asyncToGenerator(function* (filename) {
let sourceFilename = filename;
if (cliOptions.outFile) {
sourceFilename = _path().relative(_path().dirname(cliOptions.outFile), sourceFilename);
}
sourceFilename = _slash()(sourceFilename);
try {
return yield util.compile(filename, Object.assign({}, babelOptions, {
sourceFileName: sourceFilename,
sourceMaps: babelOptions.sourceMaps === "inline" ? true : babelOptions.sourceMaps
}));
} catch (err) {
if (!cliOptions.watch) {
throw err;
}
console.error(err);
return null;
}
})));
output(results);
});
return _walk.apply(this, arguments);
}
function files(_x3) {
return _files.apply(this, arguments);
}
function _files() {
_files = _asyncToGenerator(function* (filenames) {
if (cliOptions.watch) {
watcher.enable({
enableGlobbing: false
});
}
if (!cliOptions.skipInitialBuild) {
yield walk(filenames);
}
if (cliOptions.watch) {
filenames.forEach(watcher.watch);
watcher.onFilesChange((changes, event, cause) => {
const actionableChange = changes.some(filename => util.isCompilableExtension(filename, cliOptions.extensions) || filenames.includes(filename));
if (!actionableChange) return;
if (cliOptions.verbose) {
console.log(`${event} ${cause}`);
}
walk(filenames).catch(err => {
console.error(err);
});
});
}
});
return _files.apply(this, arguments);
}
if (cliOptions.filenames.length) {
yield files(cliOptions.filenames);
} else {
yield stdin();
}
});
return _ref.apply(this, arguments);
}
\ No newline at end of file
#!/usr/bin/env node
"use strict";
var _options = require("./options");
var _dir = require("./dir");
var _file = require("./file");
const opts = (0, _options.default)(process.argv);
if (opts) {
const fn = opts.cliOptions.outDir ? _dir.default : _file.default;
fn(opts).catch(err => {
console.error(err);
process.exitCode = 1;
});
} else {
process.exitCode = 2;
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = parseArgv;
function _fs() {
const data = require("fs");
_fs = function () {
return data;
};
return data;
}
function _commander() {
const data = require("commander");
_commander = function () {
return data;
};
return data;
}
function _core() {
const data = require("@babel/core");
_core = function () {
return data;
};
return data;
}
function _glob() {
const data = require("glob");
_glob = function () {
return data;
};
return data;
}
_commander().option("-f, --filename [filename]", "The filename to use when reading from stdin. This will be used in source-maps, errors etc.");
_commander().option("--presets [list]", "A comma-separated list of preset names.", collect);
_commander().option("--plugins [list]", "A comma-separated list of plugin names.", collect);
_commander().option("--config-file [path]", "Path to a .babelrc file to use.");
_commander().option("--env-name [name]", "The name of the 'env' to use when loading configs and plugins. " + "Defaults to the value of BABEL_ENV, or else NODE_ENV, or else 'development'.");
_commander().option("--root-mode [mode]", "The project-root resolution mode. " + "One of 'root' (the default), 'upward', or 'upward-optional'.");
_commander().option("--source-type [script|module]", "");
_commander().option("--no-babelrc", "Whether or not to look up .babelrc and .babelignore files.");
_commander().option("--ignore [list]", "List of glob paths to **not** compile.", collect);
_commander().option("--only [list]", "List of glob paths to **only** compile.", collect);
_commander().option("--no-highlight-code", "Enable or disable ANSI syntax highlighting of code frames. (on by default)");
_commander().option("--no-comments", "Write comments to generated output. (true by default)");
_commander().option("--retain-lines", "Retain line numbers. This will result in really ugly code.");
_commander().option("--compact [true|false|auto]", "Do not include superfluous whitespace characters and line terminators.", booleanify);
_commander().option("--minified", "Save as many bytes when printing. (false by default)");
_commander().option("--auxiliary-comment-before [string]", "Print a comment before any injected non-user code.");
_commander().option("--auxiliary-comment-after [string]", "Print a comment after any injected non-user code.");
_commander().option("-s, --source-maps [true|false|inline|both]", "", booleanify);
_commander().option("--source-map-target [string]", "Set `file` on returned source map.");
_commander().option("--source-file-name [string]", "Set `sources[0]` on returned source map.");
_commander().option("--source-root [filename]", "The root from which all sources are relative.");
{
_commander().option("--module-root [filename]", "Optional prefix for the AMD module formatter that will be prepended to the filename on module definitions.");
_commander().option("-M, --module-ids", "Insert an explicit id for modules.");
_commander().option("--module-id [string]", "Specify a custom name for module ids.");
}
_commander().option("-x, --extensions [extensions]", "List of extensions to compile when a directory has been the input. [" + _core().DEFAULT_EXTENSIONS.join() + "]", collect);
_commander().option("--keep-file-extension", "Preserve the file extensions of the input files.");
_commander().option("-w, --watch", "Recompile files on changes.");
_commander().option("--skip-initial-build", "Do not compile files before watching.");
_commander().option("-o, --out-file [out]", "Compile all input files into a single file.");
_commander().option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory.");
_commander().option("--relative", "Compile into an output directory relative to input directory or file. Requires --out-dir [out]");
_commander().option("-D, --copy-files", "When compiling a directory copy over non-compilable files.");
_commander().option("--include-dotfiles", "Include dotfiles when compiling and copying non-compilable files.");
_commander().option("--no-copy-ignored", "Exclude ignored files when copying non-compilable files.");
_commander().option("--verbose", "Log everything. This option conflicts with --quiet");
_commander().option("--quiet", "Don't log anything. This option conflicts with --verbose");
_commander().option("--delete-dir-on-start", "Delete the out directory before compilation.");
_commander().option("--out-file-extension [string]", "Use a specific extension for the output files");
_commander().version("7.18.6" + " (@babel/core " + _core().version + ")");
_commander().usage("[options] <files ...>");
_commander().action(() => {});
function parseArgv(args) {
_commander().parse(args);
const errors = [];
let filenames = _commander().args.reduce(function (globbed, input) {
let files = _glob().sync(input);
if (!files.length) files = [input];
globbed.push(...files);
return globbed;
}, []);
filenames = Array.from(new Set(filenames));
filenames.forEach(function (filename) {
if (!_fs().existsSync(filename)) {
errors.push(filename + " does not exist");
}
});
if (_commander().outDir && !filenames.length) {
errors.push("--out-dir requires filenames");
}
if (_commander().outFile && _commander().outDir) {
errors.push("--out-file and --out-dir cannot be used together");
}
if (_commander().relative && !_commander().outDir) {
errors.push("--relative requires --out-dir usage");
}
if (_commander().watch) {
if (!_commander().outFile && !_commander().outDir) {
errors.push("--watch requires --out-file or --out-dir");
}
if (!filenames.length) {
errors.push("--watch requires filenames");
}
}
if (_commander().skipInitialBuild && !_commander().watch) {
errors.push("--skip-initial-build requires --watch");
}
if (_commander().deleteDirOnStart && !_commander().outDir) {
errors.push("--delete-dir-on-start requires --out-dir");
}
if (_commander().verbose && _commander().quiet) {
errors.push("--verbose and --quiet cannot be used together");
}
if (!_commander().outDir && filenames.length === 0 && typeof _commander().filename !== "string" && _commander().babelrc !== false) {
errors.push("stdin compilation requires either -f/--filename [filename] or --no-babelrc");
}
if (_commander().keepFileExtension && _commander().outFileExtension) {
errors.push("--out-file-extension cannot be used with --keep-file-extension");
}
if (errors.length) {
console.error("babel:");
errors.forEach(function (e) {
console.error(" " + e);
});
return null;
}
const opts = _commander().opts();
const babelOptions = {
presets: opts.presets,
plugins: opts.plugins,
rootMode: opts.rootMode,
configFile: opts.configFile,
envName: opts.envName,
sourceType: opts.sourceType,
ignore: opts.ignore,
only: opts.only,
retainLines: opts.retainLines,
compact: opts.compact,
minified: opts.minified,
auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
sourceMaps: opts.sourceMaps,
sourceFileName: opts.sourceFileName,
sourceRoot: opts.sourceRoot,
babelrc: opts.babelrc === true ? undefined : opts.babelrc,
highlightCode: opts.highlightCode === true ? undefined : opts.highlightCode,
comments: opts.comments === true ? undefined : opts.comments
};
{
Object.assign(babelOptions, {
moduleRoot: opts.moduleRoot,
moduleIds: opts.moduleIds,
moduleId: opts.moduleId
});
}
for (const key of Object.keys(babelOptions)) {
if (babelOptions[key] === undefined) {
delete babelOptions[key];
}
}
return {
babelOptions,
cliOptions: {
filename: opts.filename,
filenames,
extensions: opts.extensions,
keepFileExtension: opts.keepFileExtension,
outFileExtension: opts.outFileExtension,
watch: opts.watch,
skipInitialBuild: opts.skipInitialBuild,
outFile: opts.outFile,
outDir: opts.outDir,
relative: opts.relative,
copyFiles: opts.copyFiles,
copyIgnored: opts.copyFiles && opts.copyIgnored,
includeDotfiles: opts.includeDotfiles,
verbose: opts.verbose,
quiet: opts.quiet,
deleteDirOnStart: opts.deleteDirOnStart,
sourceMapTarget: opts.sourceMapTarget
}
};
}
function booleanify(val) {
if (val === "true" || val == 1) {
return true;
}
if (val === "false" || val == 0 || !val) {
return false;
}
return val;
}
function collect(value, previousValue) {
if (typeof value !== "string") return previousValue;
const values = value.split(",");
if (previousValue) {
previousValue.push(...values);
return previousValue;
}
return values;
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.addSourceMappingUrl = addSourceMappingUrl;
exports.chmod = chmod;
exports.compile = compile;
exports.debounce = debounce;
exports.deleteDir = deleteDir;
exports.isCompilableExtension = isCompilableExtension;
exports.readdir = readdir;
exports.readdirForCompilable = readdirForCompilable;
exports.transformRepl = transformRepl;
exports.withExtension = withExtension;
function _fsReaddirRecursive() {
const data = require("fs-readdir-recursive");
_fsReaddirRecursive = function () {
return data;
};
return data;
}
function babel() {
const data = require("@babel/core");
babel = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _fs() {
const data = require("fs");
_fs = function () {
return data;
};
return data;
}
var watcher = require("./watcher");
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function chmod(src, dest) {
try {
_fs().chmodSync(dest, _fs().statSync(src).mode);
} catch (err) {
console.warn(`Cannot change permissions of ${dest}`);
}
}
function readdir(dirname, includeDotfiles, filter) {
return _fsReaddirRecursive()(dirname, (filename, _index, currentDirectory) => {
const stat = _fs().statSync(_path().join(currentDirectory, filename));
if (stat.isDirectory()) return true;
return (includeDotfiles || filename[0] !== ".") && (!filter || filter(filename));
});
}
function readdirForCompilable(dirname, includeDotfiles, altExts) {
return readdir(dirname, includeDotfiles, function (filename) {
return isCompilableExtension(filename, altExts);
});
}
function isCompilableExtension(filename, altExts) {
const exts = altExts || babel().DEFAULT_EXTENSIONS;
const ext = _path().extname(filename);
return exts.includes(ext);
}
function addSourceMappingUrl(code, loc) {
return code + "\n//# sourceMappingURL=" + _path().basename(loc);
}
const CALLER = {
name: "@babel/cli"
};
function transformRepl(filename, code, opts) {
opts = Object.assign({}, opts, {
caller: CALLER,
filename
});
return new Promise((resolve, reject) => {
babel().transform(code, opts, (err, result) => {
if (err) reject(err);else resolve(result);
});
});
}
function compile(_x, _x2) {
return _compile.apply(this, arguments);
}
function _compile() {
_compile = _asyncToGenerator(function* (filename, opts) {
opts = Object.assign({}, opts, {
caller: CALLER
});
const result = yield new Promise((resolve, reject) => {
babel().transformFile(filename, opts, (err, result) => {
if (err) reject(err);else resolve(result);
});
});
if (result) {
{
if (!result.externalDependencies) return result;
}
watcher.updateExternalDependencies(filename, result.externalDependencies);
}
return result;
});
return _compile.apply(this, arguments);
}
function deleteDir(path) {
if (_fs().existsSync(path)) {
_fs().readdirSync(path).forEach(function (file) {
const curPath = path + "/" + file;
if (_fs().lstatSync(curPath).isDirectory()) {
deleteDir(curPath);
} else {
_fs().unlinkSync(curPath);
}
});
_fs().rmdirSync(path);
}
}
process.on("uncaughtException", function (err) {
console.error(err);
process.exitCode = 1;
});
function withExtension(filename, ext = ".js") {
const newBasename = _path().basename(filename, _path().extname(filename)) + ext;
return _path().join(_path().dirname(filename), newBasename);
}
function debounce(fn, time) {
let timer;
function debounced() {
clearTimeout(timer);
timer = setTimeout(fn, time);
}
debounced.flush = () => {
clearTimeout(timer);
fn();
};
return debounced;
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.enable = enable;
exports.onFilesChange = onFilesChange;
exports.updateExternalDependencies = updateExternalDependencies;
exports.watch = watch;
function _module() {
const data = require("module");
_module = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
const fileToDeps = new Map();
const depToFiles = new Map();
let isWatchMode = false;
let watcher;
function enable({
enableGlobbing
}) {
isWatchMode = true;
const {
FSWatcher
} = requireChokidar();
watcher = new FSWatcher({
disableGlobbing: !enableGlobbing,
persistent: true,
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 50,
pollInterval: 10
}
});
watcher.on("unlink", unwatchFile);
}
function watch(filename) {
if (!isWatchMode) {
throw new Error("Internal Babel error: .watch called when not in watch mode.");
}
watcher.add(_path().resolve(filename));
}
function onFilesChange(callback) {
if (!isWatchMode) {
throw new Error("Internal Babel error: .onFilesChange called when not in watch mode.");
}
watcher.on("all", (event, filename) => {
var _depToFiles$get;
if (event !== "change" && event !== "add") return;
const absoluteFile = _path().resolve(filename);
callback([absoluteFile, ...((_depToFiles$get = depToFiles.get(absoluteFile)) != null ? _depToFiles$get : [])], event, absoluteFile);
});
}
function updateExternalDependencies(filename, dependencies) {
if (!isWatchMode) return;
const absFilename = _path().resolve(filename);
const absDependencies = new Set(Array.from(dependencies, dep => _path().resolve(dep)));
if (fileToDeps.has(absFilename)) {
for (const dep of fileToDeps.get(absFilename)) {
if (!absDependencies.has(dep)) {
removeFileDependency(absFilename, dep);
}
}
}
for (const dep of absDependencies) {
if (!depToFiles.has(dep)) {
depToFiles.set(dep, new Set());
watcher.add(dep);
}
depToFiles.get(dep).add(absFilename);
}
fileToDeps.set(absFilename, absDependencies);
}
function removeFileDependency(filename, dep) {
depToFiles.get(dep).delete(filename);
if (depToFiles.get(dep).size === 0) {
depToFiles.delete(dep);
watcher.unwatch(dep);
}
}
function unwatchFile(filename) {
if (!fileToDeps.has(filename)) return;
for (const dep of fileToDeps.get(filename)) {
removeFileDependency(filename, dep);
}
fileToDeps.delete(filename);
}
function requireChokidar() {
try {
return parseInt(process.versions.node) >= 8 ? require("chokidar") : require("@nicolo-ribaudo/chokidar-2");
} catch (err) {
console.error("The optional dependency chokidar failed to install and is required for " + "--watch. Chokidar is likely not supported on your platform.");
throw err;
}
}
\ No newline at end of file
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). (Format adopted after v3.0.0.)
<!-- markdownlint-disable MD024 -->
## [4.1.1] (2020-02-02)
### Fixed
* TypeScript definition for `.action()` should include Promise for async ([#1157])
## [4.1.0] (2020-01-06)
### Added
* two routines to change how option values are handled, and eliminate name clashes with command properties ([#933] [#1102])
* see storeOptionsAsProperties and passCommandToAction in README
* `.parseAsync` to use instead of `.parse` if supply async action handlers ([#806] [#1118])
### Fixed
* Remove trailing blanks from wrapped help text ([#1096])
### Changed
* update dependencies
* extend security coverage for Commander 2.x to 2020-02-03
* improvements to README
* improvements to TypeScript definition documentation
* move old versions out of main CHANGELOG
* removed explicit use of `ts-node` in tests
## [4.0.1] (2019-11-12)
### Fixed
* display help when requested, even if there are missing required options ([#1091])
## [4.0.0] (2019-11-02)
### Added
* automatically wrap and indent help descriptions for options and commands ([#1051])
* `.exitOverride()` allows override of calls to `process.exit` for additional error handling and to keep program running ([#1040])
* support for declaring required options with `.requiredOptions()` ([#1071])
* GitHub Actions support ([#1027])
* translation links in README
### Changed
* dev: switch tests from Sinon+Should to Jest with major rewrite of tests ([#1035])
* call default subcommand even when there are unknown options ([#1047])
* *Breaking* Commander is only officially supported on Node 8 and above, and requires Node 6 ([#1053])
### Fixed
* *Breaking* keep command object out of program.args when action handler called ([#1048])
* also, action handler now passed array of unknown arguments
* complain about unknown options when program argument supplied and action handler ([#1049])
* this changes parameters to `command:*` event to include unknown arguments
* removed deprecated `customFds` option from call to `child_process.spawn` ([#1052])
* rework TypeScript declarations to bring all types into imported namespace ([#1081])
### Migration Tips
#### Testing for no arguments
If you were previously using code like:
```js
if (!program.args.length) ...
```
a partial replacement is:
```js
if (program.rawArgs.length < 3) ...
```
## [4.0.0-1] Prerelease (2019-10-08)
(Released in 4.0.0)
## [4.0.0-0] Prerelease (2019-10-01)
(Released in 4.0.0)
## [2.20.1] (2019-09-29)
### Fixed
* Improve tracking of executable subcommands.
### Changed
* update development dependencies
## [3.0.2] (2019-09-27)
### Fixed
* Improve tracking of executable subcommands.
### Changed
* update development dependencies
## [3.0.1] (2019-08-30)
### Added
* .name and .usage to README ([#1010])
* Table of Contents to README ([#1010])
* TypeScript definition for `executableFile` in CommandOptions ([#1028])
### Changed
* consistently use `const` rather than `var` in README ([#1026])
### Fixed
* help for sub commands with custom executableFile ([#1018])
## [3.0.0] / 2019-08-08
* Add option to specify executable file name ([#999])
* e.g. `.command('clone', 'clone description', { executableFile: 'myClone' })`
* Change docs for `.command` to contrast action handler vs git-style executable. ([#938] [#990])
* **Breaking** Change TypeScript to use overloaded function for `.command`. ([#938] [#990])
* Change to use straight quotes around strings in error messages (like 'this' instead of `this') ([#915])
* Add TypeScript "reference types" for node ([#974])
* Add support for hyphen as an option argument in subcommands ([#697])
* Add support for a short option flag and its value to be concatenated for action handler subcommands ([#599])
* e.g. `-p 80` can also be supplied as `-p80`
* Add executable arguments to spawn in win32, for git-style executables ([#611])
* e.g. `node --harmony myCommand.js clone`
* Add parent command as prefix of subcommand in help ([#980])
* Add optional custom description to `.version` ([#963])
* e.g. `program.version('0.0.1', '-v, --vers', 'output the current version')`
* Add `.helpOption(flags, description)` routine to customise help flags and description ([#963])
* e.g. `.helpOption('-e, --HELP', 'read more information')`
* Fix behavior of --no-* options ([#795])
* can now define both `--foo` and `--no-foo`
* **Breaking** custom event listeners: `--no-foo` on cli now emits `option:no-foo` (previously `option:foo`)
* **Breaking** default value: defining `--no-foo` after defining `--foo` leaves the default value unchanged (previously set it to false)
* allow boolean default value, such as from environment ([#987])
* Increment inspector port for spawned subcommands ([#991])
* e.g. `node --inspect myCommand.js clone`
### Migration Tips
The custom event for a negated option like `--no-foo` is `option:no-foo` (previously `option:foo`).
```js
program
.option('--no-foo')
.on('option:no-foo', () => {
console.log('removing foo');
});
```
When using TypeScript, adding a command does not allow an explicit `undefined` for an unwanted executable description (e.g
for a command with an action handler).
```js
program
.command('action1', undefined, { noHelp: true }) // No longer valid
.command('action2', { noHelp: true }) // Correct
```
## 3.0.0-0 Prerelease / 2019-07-28
(Released as 3.0.0)
## 2.20.0 / 2019-04-02
* fix: resolve symbolic links completely when hunting for subcommands (#935)
* Update index.d.ts (#930)
* Update Readme.md (#924)
* Remove --save option as it isn't required anymore (#918)
* Add link to the license file (#900)
* Added example of receiving args from options (#858)
* Added missing semicolon (#882)
* Add extension to .eslintrc (#876)
## 2.19.0 / 2018-10-02
* Removed newline after Options and Commands headers (#864)
* Bugfix - Error output (#862)
* Fix to change default value to string (#856)
## 2.18.0 / 2018-09-07
* Standardize help output (#853)
* chmod 644 travis.yml (#851)
* add support for execute typescript subcommand via ts-node (#849)
## 2.17.1 / 2018-08-07
* Fix bug in command emit (#844)
## 2.17.0 / 2018-08-03
* fixed newline output after help information (#833)
* Fix to emit the action even without command (#778)
* npm update (#823)
## 2.16.0 / 2018-06-29
* Remove Makefile and `test/run` (#821)
* Make 'npm test' run on Windows (#820)
* Add badge to display install size (#807)
* chore: cache node_modules (#814)
* chore: remove Node.js 4 (EOL), add Node.js 10 (#813)
* fixed typo in readme (#812)
* Fix types (#804)
* Update eslint to resolve vulnerabilities in lodash (#799)
* updated readme with custom event listeners. (#791)
* fix tests (#794)
## 2.15.0 / 2018-03-07
* Update downloads badge to point to graph of downloads over time instead of duplicating link to npm
* Arguments description
## 2.14.1 / 2018-02-07
* Fix typing of help function
## 2.14.0 / 2018-02-05
* only register the option:version event once
* Fixes issue #727: Passing empty string for option on command is set to undefined
* enable eqeqeq rule
* resolves #754 add linter configuration to project
* resolves #560 respect custom name for version option
* document how to override the version flag
* document using options per command
## 2.13.0 / 2018-01-09
* Do not print default for --no-
* remove trailing spaces in command help
* Update CI's Node.js to LTS and latest version
* typedefs: Command and Option types added to commander namespace
## 2.12.2 / 2017-11-28
* fix: typings are not shipped
## 2.12.1 / 2017-11-23
* Move @types/node to dev dependency
## 2.12.0 / 2017-11-22
* add attributeName() method to Option objects
* Documentation updated for options with --no prefix
* typings: `outputHelp` takes a string as the first parameter
* typings: use overloads
* feat(typings): update to match js api
* Print default value in option help
* Fix translation error
* Fail when using same command and alias (#491)
* feat(typings): add help callback
* fix bug when description is add after command with options (#662)
* Format js code
* Rename History.md to CHANGELOG.md (#668)
* feat(typings): add typings to support TypeScript (#646)
* use current node
## 2.11.0 / 2017-07-03
* Fix help section order and padding (#652)
* feature: support for signals to subcommands (#632)
* Fixed #37, --help should not display first (#447)
* Fix translation errors. (#570)
* Add package-lock.json
* Remove engines
* Upgrade package version
* Prefix events to prevent conflicts between commands and options (#494)
* Removing dependency on graceful-readlink
* Support setting name in #name function and make it chainable
* Add .vscode directory to .gitignore (Visual Studio Code metadata)
* Updated link to ruby commander in readme files
## 2.10.0 / 2017-06-19
* Update .travis.yml. drop support for older node.js versions.
* Fix require arguments in README.md
* On SemVer you do not start from 0.0.1
* Add missing semi colon in readme
* Add save param to npm install
* node v6 travis test
* Update Readme_zh-CN.md
* Allow literal '--' to be passed-through as an argument
* Test subcommand alias help
* link build badge to master branch
* Support the alias of Git style sub-command
* added keyword commander for better search result on npm
* Fix Sub-Subcommands
* test node.js stable
* Fixes TypeError when a command has an option called `--description`
* Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets.
* Add chinese Readme file
## 2.9.0 / 2015-10-13
* Add option `isDefault` to set default subcommand #415 @Qix-
* Add callback to allow filtering or post-processing of help text #434 @djulien
* Fix `undefined` text in help information close #414 #416 @zhiyelee
## 2.8.1 / 2015-04-22
* Back out `support multiline description` Close #396 #397
## 2.8.0 / 2015-04-07
* Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee
* Fix bug in Git-style sub-commands #372 @zhiyelee
* Allow commands to be hidden from help #383 @tonylukasavage
* When git-style sub-commands are in use, yet none are called, display help #382 @claylo
* Add ability to specify arguments syntax for top-level command #258 @rrthomas
* Support multiline descriptions #208 @zxqfox
## 2.7.1 / 2015-03-11
* Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367.
## 2.7.0 / 2015-03-09
* Fix git-style bug when installed globally. Close #335 #349 @zhiyelee
* Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage
* Add support for camelCase on `opts()`. Close #353 @nkzawa
* Add node.js 0.12 and io.js to travis.yml
* Allow RegEx options. #337 @palanik
* Fixes exit code when sub-command failing. Close #260 #332 @pirelenito
* git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee
## 2.6.0 / 2014-12-30
* added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee
* Add application description to the help msg. Close #112 @dalssoft
## 2.5.1 / 2014-12-15
* fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee
## 2.5.0 / 2014-10-24
* add support for variadic arguments. Closes #277 @whitlockjc
## 2.4.0 / 2014-10-17
* fixed a bug on executing the coercion function of subcommands option. Closes #270
* added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage
* added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage
* fixed a bug on subcommand name. Closes #248 @jonathandelgado
* fixed function normalize doesn’t honor option terminator. Closes #216 @abbr
## 2.3.0 / 2014-07-16
* add command alias'. Closes PR #210
* fix: Typos. Closes #99
* fix: Unused fs module. Closes #217
## 2.2.0 / 2014-03-29
* add passing of previous option value
* fix: support subcommands on windows. Closes #142
* Now the defaultValue passed as the second argument of the coercion function.
## 2.1.0 / 2013-11-21
* add: allow cflag style option params, unit test, fixes #174
## 2.0.0 / 2013-07-18
* remove input methods (.prompt, .confirm, etc)
## Older versions
* [1.x](./changelogs/CHANGELOG-1.md)
* [0.x](./changelogs/CHANGELOG-0.md)
[#599]: https://github.com/tj/commander.js/issues/599
[#611]: https://github.com/tj/commander.js/issues/611
[#697]: https://github.com/tj/commander.js/issues/697
[#795]: https://github.com/tj/commander.js/issues/795
[#806]: https://github.com/tj/commander.js/issues/806
[#915]: https://github.com/tj/commander.js/issues/915
[#938]: https://github.com/tj/commander.js/issues/938
[#963]: https://github.com/tj/commander.js/issues/963
[#974]: https://github.com/tj/commander.js/issues/974
[#980]: https://github.com/tj/commander.js/issues/980
[#987]: https://github.com/tj/commander.js/issues/987
[#990]: https://github.com/tj/commander.js/issues/990
[#991]: https://github.com/tj/commander.js/issues/991
[#993]: https://github.com/tj/commander.js/issues/993
[#999]: https://github.com/tj/commander.js/issues/999
[#1010]: https://github.com/tj/commander.js/pull/1010
[#1018]: https://github.com/tj/commander.js/pull/1018
[#1026]: https://github.com/tj/commander.js/pull/1026
[#1027]: https://github.com/tj/commander.js/pull/1027
[#1028]: https://github.com/tj/commander.js/pull/1028
[#1035]: https://github.com/tj/commander.js/pull/1035
[#1040]: https://github.com/tj/commander.js/pull/1040
[#1047]: https://github.com/tj/commander.js/pull/1047
[#1048]: https://github.com/tj/commander.js/pull/1048
[#1049]: https://github.com/tj/commander.js/pull/1049
[#1051]: https://github.com/tj/commander.js/pull/1051
[#1052]: https://github.com/tj/commander.js/pull/1052
[#1053]: https://github.com/tj/commander.js/pull/1053
[#1071]: https://github.com/tj/commander.js/pull/1071
[#1081]: https://github.com/tj/commander.js/pull/1081
[#1091]: https://github.com/tj/commander.js/pull/1091
[#1096]: https://github.com/tj/commander.js/pull/1096
[#1102]: https://github.com/tj/commander.js/pull/1102
[#1118]: https://github.com/tj/commander.js/pull/1118
[#1157]: https://github.com/tj/commander.js/pull/1157
[Unreleased]: https://github.com/tj/commander.js/compare/master...develop
[4.1.1]: https://github.com/tj/commander.js/compare/v4.0.0..v4.1.1
[4.1.0]: https://github.com/tj/commander.js/compare/v4.0.1..v4.1.0
[4.0.1]: https://github.com/tj/commander.js/compare/v4.0.0..v4.0.1
[4.0.0]: https://github.com/tj/commander.js/compare/v3.0.2..v4.0.0
[4.0.0-1]: https://github.com/tj/commander.js/compare/v4.0.0-0..v4.0.0-1
[4.0.0-0]: https://github.com/tj/commander.js/compare/v3.0.2...v4.0.0-0
[3.0.2]: https://github.com/tj/commander.js/compare/v3.0.1...v3.0.2
[3.0.1]: https://github.com/tj/commander.js/compare/v3.0.0...v3.0.1
[3.0.0]: https://github.com/tj/commander.js/compare/v2.20.1...v3.0.0
[2.20.1]: https://github.com/tj/commander.js/compare/v2.20.0...v2.20.1
# Commander.js
[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
Read this in other languages: English | [简体中文](./Readme_zh-CN.md)
- [Commander.js](#commanderjs)
- [Installation](#installation)
- [Declaring program variable](#declaring-program-variable)
- [Options](#options)
- [Common option types, boolean and value](#common-option-types-boolean-and-value)
- [Default option value](#default-option-value)
- [Other option types, negatable boolean and flag|value](#other-option-types-negatable-boolean-and-flagvalue)
- [Custom option processing](#custom-option-processing)
- [Required option](#required-option)
- [Version option](#version-option)
- [Commands](#commands)
- [Specify the argument syntax](#specify-the-argument-syntax)
- [Action handler (sub)commands](#action-handler-subcommands)
- [Git-style executable (sub)commands](#git-style-executable-subcommands)
- [Automated --help](#automated---help)
- [Custom help](#custom-help)
- [.usage and .name](#usage-and-name)
- [.outputHelp(cb)](#outputhelpcb)
- [.helpOption(flags, description)](#helpoptionflags-description)
- [.help(cb)](#helpcb)
- [Custom event listeners](#custom-event-listeners)
- [Bits and pieces](#bits-and-pieces)
- [Avoiding option name clashes](#avoiding-option-name-clashes)
- [TypeScript](#typescript)
- [Node options such as --harmony](#node-options-such-as---harmony)
- [Node debugging](#node-debugging)
- [Override exit handling](#override-exit-handling)
- [Examples](#examples)
- [License](#license)
- [Support](#support)
- [Commander for enterprise](#commander-for-enterprise)
## Installation
```bash
npm install commander
```
## Declaring _program_ variable
Commander exports a global object which is convenient for quick programs.
This is used in the examples in this README for brevity.
```js
const program = require('commander');
program.version('0.0.1');
```
For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
```js
const commander = require('commander');
const program = new commander.Command();
program.version('0.0.1');
```
## Options
Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space.
The options can be accessed as properties on the Command object. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. Multiple short flags may be combined as a single arg, for example `-abc` is equivalent to `-a -b -c`.
See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes).
### Common option types, boolean and value
The two most used option types are a boolean flag, and an option which takes a value (declared using angle brackets). Both are `undefined` unless specified on command line.
```js
const program = require('commander');
program
.option('-d, --debug', 'output extra debugging')
.option('-s, --small', 'small pizza size')
.option('-p, --pizza-type <type>', 'flavour of pizza');
program.parse(process.argv);
if (program.debug) console.log(program.opts());
console.log('pizza details:');
if (program.small) console.log('- small pizza size');
if (program.pizzaType) console.log(`- ${program.pizzaType}`);
```
```bash
$ pizza-options -d
{ debug: true, small: undefined, pizzaType: undefined }
pizza details:
$ pizza-options -p
error: option '-p, --pizza-type <type>' argument missing
$ pizza-options -ds -p vegetarian
{ debug: true, small: true, pizzaType: 'vegetarian' }
pizza details:
- small pizza size
- vegetarian
$ pizza-options --pizza-type=cheese
pizza details:
- cheese
```
`program.parse(arguments)` processes the arguments, leaving any args not consumed by the options as the `program.args` array.
### Default option value
You can specify a default value for an option which takes a value.
```js
const program = require('commander');
program
.option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');
program.parse(process.argv);
console.log(`cheese: ${program.cheese}`);
```
```bash
$ pizza-options
cheese: blue
$ pizza-options --cheese stilton
cheese: stilton
```
### Other option types, negatable boolean and flag|value
You can specify a boolean option long name with a leading `no-` to set the option value to false when used.
Defined alone this also makes the option true by default.
If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
otherwise be. You can specify a default boolean value for a boolean flag and it can be overridden on command line.
```js
const program = require('commander');
program
.option('--no-sauce', 'Remove sauce')
.option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
.option('--no-cheese', 'plain with no cheese')
.parse(process.argv);
const sauceStr = program.sauce ? 'sauce' : 'no sauce';
const cheeseStr = (program.cheese === false) ? 'no cheese' : `${program.cheese} cheese`;
console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
```
```bash
$ pizza-options
You ordered a pizza with sauce and mozzarella cheese
$ pizza-options --sauce
error: unknown option '--sauce'
$ pizza-options --cheese=blue
You ordered a pizza with sauce and blue cheese
$ pizza-options --no-sauce --no-cheese
You ordered a pizza with no sauce and no cheese
```
You can specify an option which functions as a flag but may also take a value (declared using square brackets).
```js
const program = require('commander');
program
.option('-c, --cheese [type]', 'Add cheese with optional type');
program.parse(process.argv);
if (program.cheese === undefined) console.log('no cheese');
else if (program.cheese === true) console.log('add cheese');
else console.log(`add cheese type ${program.cheese}`);
```
```bash
$ pizza-options
no cheese
$ pizza-options --cheese
add cheese
$ pizza-options --cheese mozzarella
add cheese type mozzarella
```
### Custom option processing
You may specify a function to do custom processing of option values. The callback function receives two parameters, the user specified value and the
previous value for the option. It returns the new value for the option.
This allows you to coerce the option value to the desired type, or accumulate values, or do entirely custom processing.
You can optionally specify the default/starting value for the option after the function.
```js
const program = require('commander');
function myParseInt(value, dummyPrevious) {
// parseInt takes a string and an optional radix
return parseInt(value);
}
function increaseVerbosity(dummyValue, previous) {
return previous + 1;
}
function collect(value, previous) {
return previous.concat([value]);
}
function commaSeparatedList(value, dummyPrevious) {
return value.split(',');
}
program
.option('-f, --float <number>', 'float argument', parseFloat)
.option('-i, --integer <number>', 'integer argument', myParseInt)
.option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
.option('-c, --collect <value>', 'repeatable value', collect, [])
.option('-l, --list <items>', 'comma separated list', commaSeparatedList)
;
program.parse(process.argv);
if (program.float !== undefined) console.log(`float: ${program.float}`);
if (program.integer !== undefined) console.log(`integer: ${program.integer}`);
if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);
if (program.collect.length > 0) console.log(program.collect);
if (program.list !== undefined) console.log(program.list);
```
```bash
$ custom -f 1e2
float: 100
$ custom --integer 2
integer: 2
$ custom -v -v -v
verbose: 3
$ custom -c a -c b -c c
[ 'a', 'b', 'c' ]
$ custom --list x,y,z
[ 'x', 'y', 'z' ]
```
### Required option
You may specify a required (mandatory) option using `.requiredOption`. The option must be specified on the command line, or by having a default value. The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing.
```js
const program = require('commander');
program
.requiredOption('-c, --cheese <type>', 'pizza must have cheese');
program.parse(process.argv);
```
```
$ pizza
error: required option '-c, --cheese <type>' not specified
```
### Version option
The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.
```js
program.version('0.0.1');
```
```bash
$ ./examples/pizza -V
0.0.1
```
You may change the flags and description by passing additional parameters to the `version` method, using
the same syntax for flags as the `option` method. The version flags can be named anything, but a long name is required.
```js
program.version('0.0.1', '-v, --vers', 'output the current version');
```
## Commands
You can specify (sub)commands for your top-level command using `.command`. There are two ways these can be implemented: using an action handler attached to the command, or as a separate executable file (described in more detail later). In the first parameter to `.command` you specify the command name and any command arguments. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.
For example:
```js
// Command implemented using action handler (description is supplied separately to `.command`)
// Returns new command for configuring.
program
.command('clone <source> [destination]')
.description('clone a repository into a newly created directory')
.action((source, destination) => {
console.log('clone command called');
});
// Command implemented using separate executable file (description is second parameter to `.command`)
// Returns top-level command for adding more commands.
program
.command('start <service>', 'start named service')
.command('stop [service]', 'stop named service, or all if no name supplied');
```
### Specify the argument syntax
You use `.arguments` to specify the arguments for the top-level command, and for subcommands they are included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required input. Square brackets (e.g. `[optional]`) indicate optional input.
```js
const program = require('commander');
program
.version('0.1.0')
.arguments('<cmd> [env]')
.action(function (cmd, env) {
cmdValue = cmd;
envValue = env;
});
program.parse(process.argv);
if (typeof cmdValue === 'undefined') {
console.error('no command given!');
process.exit(1);
}
console.log('command:', cmdValue);
console.log('environment:', envValue || "no environment given");
```
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
append `...` to the argument name. For example:
```js
const program = require('commander');
program
.version('0.1.0')
.command('rmdir <dir> [otherDirs...]')
.action(function (dir, otherDirs) {
console.log('rmdir %s', dir);
if (otherDirs) {
otherDirs.forEach(function (oDir) {
console.log('rmdir %s', oDir);
});
}
});
program.parse(process.argv);
```
The variadic argument is passed to the action handler as an array. (And this also applies to `program.args`.)
### Action handler (sub)commands
You can add options to a command that uses an action handler.
The action handler gets passed a parameter for each argument you declared, and one additional argument which is the
command object itself. This command argument has the values for the command-specific options added as properties.
```js
const program = require('commander');
program
.command('rm <dir>')
.option('-r, --recursive', 'Remove recursively')
.action(function (dir, cmdObj) {
console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : ''))
})
program.parse(process.argv)
```
You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
```js
async function run() { /* code goes here */ }
async function main() {
program
.command('run')
.action(run);
await program.parseAsync(process.argv);
}
```
A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.
Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output.
### Git-style executable (sub)commands
When `.command()` is invoked with a description argument, this tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.
Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`.
You can specify a custom name with the `executableFile` configuration option.
You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
```js
// file: ./examples/pm
const program = require('commander');
program
.version('0.1.0')
.command('install [name]', 'install one or more packages')
.command('search [query]', 'search with optional query')
.command('update', 'update installed packages', {executableFile: 'myUpdateSubCommand'})
.command('list', 'list packages installed', {isDefault: true})
.parse(process.argv);
```
Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.
Specifying a name with `executableFile` will override the default constructed name.
If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
## Automated --help
The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
```bash
$ ./examples/pizza --help
Usage: pizza [options]
An application for pizzas ordering
Options:
-V, --version output the version number
-p, --peppers Add peppers
-P, --pineapple Add pineapple
-b, --bbq Add bbq sauce
-c, --cheese <type> Add the specified type of cheese (default: "marble")
-C, --no-cheese You do not want any cheese
-h, --help output usage information
```
### Custom help
You can display arbitrary `-h, --help` information
by listening for "--help". Commander will automatically
exit once you are done so that the remainder of your program
does not execute causing undesired behaviors, for example
in the following executable "stuff" will not output when
`--help` is used.
```js
#!/usr/bin/env node
const program = require('commander');
program
.version('0.1.0')
.option('-f, --foo', 'enable some foo')
.option('-b, --bar', 'enable some bar')
.option('-B, --baz', 'enable some baz');
// must be before .parse() since
// node's emit() is immediate
program.on('--help', function(){
console.log('')
console.log('Examples:');
console.log(' $ custom-help --help');
console.log(' $ custom-help -h');
});
program.parse(process.argv);
console.log('stuff');
```
Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
```Text
Usage: custom-help [options]
Options:
-h, --help output usage information
-V, --version output the version number
-f, --foo enable some foo
-b, --bar enable some bar
-B, --baz enable some baz
Examples:
$ custom-help --help
$ custom-help -h
```
### .usage and .name
These allow you to customise the usage description in the first line of the help. The name is otherwise
deduced from the (full) program arguments. Given:
```js
program
.name("my-command")
.usage("[global options] command")
```
The help will start with:
```Text
Usage: my-command [global options] command
```
### .outputHelp(cb)
Output help information without exiting.
Optional callback cb allows post-processing of help text before it is displayed.
If you want to display help by default (e.g. if no command was provided), you can use something like:
```js
const program = require('commander');
const colors = require('colors');
program
.version('0.1.0')
.command('getstream [url]', 'get stream URL')
.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp(make_red);
}
function make_red(txt) {
return colors.red(txt); //display the help text in red on the console
}
```
### .helpOption(flags, description)
Override the default help flags and description.
```js
program
.helpOption('-e, --HELP', 'read more information');
```
### .help(cb)
Output help information and exit immediately.
Optional callback cb allows post-processing of help text before it is displayed.
## Custom event listeners
You can execute custom actions by listening to command and option events.
```js
program.on('option:verbose', function () {
process.env.VERBOSE = this.verbose;
});
// error on unknown commands
program.on('command:*', function () {
console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
process.exit(1);
});
```
## Bits and pieces
### Avoiding option name clashes
The original and default behaviour is that the option values are stored
as properties on the program, and the action handler is passed a
command object with the options values stored as properties.
This is very convenient to code, but the downside is possible clashes with
existing properties of Command.
There are two new routines to change the behaviour, and the default behaviour may change in the future:
- `storeOptionsAsProperties`: whether to store option values as properties on command object, or store separately (specify false) and access using `.opts()`
- `passCommandToAction`: whether to pass command to action handler,
or just the options (specify false)
```js
// file: ./examples/storeOptionsAsProperties.action.js
program
.storeOptionsAsProperties(false)
.passCommandToAction(false);
program
.name('my-program-name')
.option('-n,--name <name>');
program
.command('show')
.option('-a,--action <action>')
.action((options) => {
console.log(options.action);
});
program.parse(process.argv);
const programOptions = program.opts();
console.log(programOptions.name);
```
### TypeScript
The Commander package includes its TypeScript Definition file, but also requires the node types which you need to install yourself. e.g.
```bash
npm install commander
npm install --save-dev @types/node
```
If you use `ts-node` and git-style sub-commands written as `.ts` files, you need to call your program through node to get the sub-commands called correctly. e.g.
```bash
node -r ts-node/register pm.ts
```
### Node options such as `--harmony`
You can enable `--harmony` option in two ways:
- Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. (Note Windows does not support this pattern.)
- Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.
### Node debugging
If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) git-style executable (sub)commands using `node --inspect` et al,
the inspector port is incremented by 1 for the spawned subcommand.
### Override exit handling
By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override
this behaviour and optionally supply a callback. The default override throws a `CommanderError`.
The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help
is not affected by the override which is called after the display.
``` js
program.exitOverride();
try {
program.parse(process.argv);
} catch (err) {
// custom processing...
}
```
## Examples
```js
const program = require('commander');
program
.version('0.1.0')
.option('-C, --chdir <path>', 'change the working directory')
.option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
.option('-T, --no-tests', 'ignore test hook');
program
.command('setup [env]')
.description('run setup commands for all envs')
.option("-s, --setup_mode [mode]", "Which setup mode to use")
.action(function(env, options){
const mode = options.setup_mode || "normal";
env = env || 'all';
console.log('setup for %s env(s) with %s mode', env, mode);
});
program
.command('exec <cmd>')
.alias('ex')
.description('execute the given remote cmd')
.option("-e, --exec_mode <mode>", "Which exec mode to use")
.action(function(cmd, options){
console.log('exec "%s" using %s mode', cmd, options.exec_mode);
}).on('--help', function() {
console.log('');
console.log('Examples:');
console.log('');
console.log(' $ deploy exec sequential');
console.log(' $ deploy exec async');
});
program
.command('*')
.action(function(env){
console.log('deploying "%s"', env);
});
program.parse(process.argv);
```
More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
## License
[MIT](https://github.com/tj/commander.js/blob/master/LICENSE)
## Support
Commander 4.x is supported on Node 8 and above, and is likely to work with Node 6 but not tested.
(For versions of Node below Node 6, use Commander 3.x or 2.x.)
The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.
### Commander for enterprise
Available as part of the Tidelift Subscription
The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter;
var spawn = require('child_process').spawn;
var path = require('path');
var dirname = path.dirname;
var basename = path.basename;
var fs = require('fs');
/**
* Inherit `Command` from `EventEmitter.prototype`.
*/
require('util').inherits(Command, EventEmitter);
/**
* Expose the root command.
*/
exports = module.exports = new Command();
/**
* Expose `Command`.
*/
exports.Command = Command;
/**
* Expose `Option`.
*/
exports.Option = Option;
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {String} flags
* @param {String} description
* @api public
*/
function Option(flags, description) {
this.flags = flags;
this.required = flags.indexOf('<') >= 0; // A value must be supplied when the option is specified.
this.optional = flags.indexOf('[') >= 0; // A value is optional when the option is specified.
this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
this.negate = flags.indexOf('-no-') !== -1;
flags = flags.split(/[ ,|]+/);
if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();
this.long = flags.shift();
this.description = description || '';
}
/**
* Return option name.
*
* @return {String}
* @api private
*/
Option.prototype.name = function() {
return this.long.replace(/^--/, '');
};
/**
* Return option name, in a camelcase format that can be used
* as a object attribute key.
*
* @return {String}
* @api private
*/
Option.prototype.attributeName = function() {
return camelcase(this.name().replace(/^no-/, ''));
};
/**
* Check if `arg` matches the short or long flag.
*
* @param {String} arg
* @return {Boolean}
* @api private
*/
Option.prototype.is = function(arg) {
return this.short === arg || this.long === arg;
};
/**
* CommanderError class
* @class
*/
class CommanderError extends Error {
/**
* Constructs the CommanderError class
* @param {Number} exitCode suggested exit code which could be used with process.exit
* @param {String} code an id string representing the error
* @param {String} message human-readable description of the error
* @constructor
*/
constructor(exitCode, code, message) {
super(message);
// properly capture stack trace in Node.js
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.code = code;
this.exitCode = exitCode;
}
}
exports.CommanderError = CommanderError;
/**
* Initialize a new `Command`.
*
* @param {String} [name]
* @api public
*/
function Command(name) {
this.commands = [];
this.options = [];
this._execs = new Set();
this._allowUnknownOption = false;
this._args = [];
this._name = name || '';
this._optionValues = {};
this._storeOptionsAsProperties = true; // backwards compatible by default
this._passCommandToAction = true; // backwards compatible by default
this._actionResults = [];
this._helpFlags = '-h, --help';
this._helpDescription = 'output usage information';
this._helpShortFlag = '-h';
this._helpLongFlag = '--help';
}
/**
* Define a command.
*
* There are two styles of command: pay attention to where to put the description.
*
* Examples:
*
* // Command implemented using action handler (description is supplied separately to `.command`)
* program
* .command('clone <source> [destination]')
* .description('clone a repository into a newly created directory')
* .action((source, destination) => {
* console.log('clone command called');
* });
*
* // Command implemented using separate executable file (description is second parameter to `.command`)
* program
* .command('start <service>', 'start named service')
* .command('stop [service]', 'stop named service, or all if no name supplied');
*
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
* @param {Object} [execOpts] - configuration options (for executable)
* @return {Command} returns new command for action handler, or top-level command for executable command
* @api public
*/
Command.prototype.command = function(nameAndArgs, actionOptsOrExecDesc, execOpts) {
var desc = actionOptsOrExecDesc;
var opts = execOpts;
if (typeof desc === 'object' && desc !== null) {
opts = desc;
desc = null;
}
opts = opts || {};
var args = nameAndArgs.split(/ +/);
var cmd = new Command(args.shift());
if (desc) {
cmd.description(desc);
this.executables = true;
this._execs.add(cmd._name);
if (opts.isDefault) this.defaultExecutable = cmd._name;
}
cmd._noHelp = !!opts.noHelp;
cmd._helpFlags = this._helpFlags;
cmd._helpDescription = this._helpDescription;
cmd._helpShortFlag = this._helpShortFlag;
cmd._helpLongFlag = this._helpLongFlag;
cmd._exitCallback = this._exitCallback;
cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;
cmd._passCommandToAction = this._passCommandToAction;
cmd._executableFile = opts.executableFile; // Custom name for executable file
this.commands.push(cmd);
cmd.parseExpectedArgs(args);
cmd.parent = this;
if (desc) return this;
return cmd;
};
/**
* Define argument syntax for the top-level command.
*
* @api public
*/
Command.prototype.arguments = function(desc) {
return this.parseExpectedArgs(desc.split(/ +/));
};
/**
* Add an implicit `help [cmd]` subcommand
* which invokes `--help` for the given command.
*
* @api private
*/
Command.prototype.addImplicitHelpCommand = function() {
this.command('help [cmd]', 'display help for [cmd]');
};
/**
* Parse expected `args`.
*
* For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
*
* @param {Array} args
* @return {Command} for chaining
* @api public
*/
Command.prototype.parseExpectedArgs = function(args) {
if (!args.length) return;
var self = this;
args.forEach(function(arg) {
var argDetails = {
required: false,
name: '',
variadic: false
};
switch (arg[0]) {
case '<':
argDetails.required = true;
argDetails.name = arg.slice(1, -1);
break;
case '[':
argDetails.name = arg.slice(1, -1);
break;
}
if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
argDetails.variadic = true;
argDetails.name = argDetails.name.slice(0, -3);
}
if (argDetails.name) {
self._args.push(argDetails);
}
});
return this;
};
/**
* Register callback to use as replacement for calling process.exit.
*
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
* @return {Command} for chaining
* @api public
*/
Command.prototype.exitOverride = function(fn) {
if (fn) {
this._exitCallback = fn;
} else {
this._exitCallback = function(err) {
if (err.code !== 'commander.executeSubCommandAsync') {
throw err;
} else {
// Async callback from spawn events, not useful to throw.
}
};
}
return this;
};
/**
* Call process.exit, and _exitCallback if defined.
*
* @param {Number} exitCode exit code for using with process.exit
* @param {String} code an id string representing the error
* @param {String} message human-readable description of the error
* @return never
* @api private
*/
Command.prototype._exit = function(exitCode, code, message) {
if (this._exitCallback) {
this._exitCallback(new CommanderError(exitCode, code, message));
// Expecting this line is not reached.
}
process.exit(exitCode);
};
/**
* Register callback `fn` for the command.
*
* Examples:
*
* program
* .command('help')
* .description('display verbose help')
* .action(function() {
* // output help here
* });
*
* @param {Function} fn
* @return {Command} for chaining
* @api public
*/
Command.prototype.action = function(fn) {
var self = this;
var listener = function(args, unknown) {
// Parse any so-far unknown options
args = args || [];
unknown = unknown || [];
var parsed = self.parseOptions(unknown);
// Output help if necessary
outputHelpIfRequested(self, parsed.unknown);
self._checkForMissingMandatoryOptions();
// If there are still any unknown options, then we simply
// die, unless someone asked for help, in which case we give it
// to them, and then we die.
if (parsed.unknown.length > 0) {
self.unknownOption(parsed.unknown[0]);
}
// Leftover arguments need to be pushed back. Fixes issue #56
if (parsed.args.length) args = parsed.args.concat(args);
self._args.forEach(function(arg, i) {
if (arg.required && args[i] == null) {
self.missingArgument(arg.name);
} else if (arg.variadic) {
if (i !== self._args.length - 1) {
self.variadicArgNotLast(arg.name);
}
args[i] = args.splice(i);
}
});
// The .action callback takes an extra parameter which is the command itself.
var expectedArgsCount = self._args.length;
var actionArgs = args.slice(0, expectedArgsCount);
if (self._passCommandToAction) {
actionArgs[expectedArgsCount] = self;
} else {
actionArgs[expectedArgsCount] = self.opts();
}
// Add the extra arguments so available too.
if (args.length > expectedArgsCount) {
actionArgs.push(args.slice(expectedArgsCount));
}
const actionResult = fn.apply(self, actionArgs);
// Remember result in case it is async. Assume parseAsync getting called on root.
let rootCommand = self;
while (rootCommand.parent) {
rootCommand = rootCommand.parent;
}
rootCommand._actionResults.push(actionResult);
};
var parent = this.parent || this;
var name = parent === this ? '*' : this._name;
parent.on('command:' + name, listener);
if (this._alias) parent.on('command:' + this._alias, listener);
return this;
};
/**
* Internal implementation shared by .option() and .requiredOption()
*
* @param {Object} config
* @param {String} flags
* @param {String} description
* @param {Function|*} [fn] - custom option processing function or default vaue
* @param {*} [defaultValue]
* @return {Command} for chaining
* @api private
*/
Command.prototype._optionEx = function(config, flags, description, fn, defaultValue) {
var self = this,
option = new Option(flags, description),
oname = option.name(),
name = option.attributeName();
option.mandatory = !!config.mandatory;
// default as 3rd arg
if (typeof fn !== 'function') {
if (fn instanceof RegExp) {
// This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing.
// No longer documented in README, but still present for backwards compatibility.
var regex = fn;
fn = function(val, def) {
var m = regex.exec(val);
return m ? m[0] : def;
};
} else {
defaultValue = fn;
fn = null;
}
}
// preassign default value for --no-*, [optional], <required>, or plain flag if boolean value
if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {
// when --no-foo we make sure default is true, unless a --foo option is already defined
if (option.negate) {
const positiveLongFlag = option.long.replace(/^--no-/, '--');
defaultValue = self.optionFor(positiveLongFlag) ? self._getOptionValue(name) : true;
}
// preassign only if we have a default
if (defaultValue !== undefined) {
self._setOptionValue(name, defaultValue);
option.defaultValue = defaultValue;
}
}
// register the option
this.options.push(option);
// when it's passed assign the value
// and conditionally invoke the callback
this.on('option:' + oname, function(val) {
// coercion
if (val !== null && fn) {
val = fn(val, self._getOptionValue(name) === undefined ? defaultValue : self._getOptionValue(name));
}
// unassigned or boolean value
if (typeof self._getOptionValue(name) === 'boolean' || typeof self._getOptionValue(name) === 'undefined') {
// if no value, negate false, and we have a default, then use it!
if (val == null) {
self._setOptionValue(name, option.negate
? false
: defaultValue || true);
} else {
self._setOptionValue(name, val);
}
} else if (val !== null) {
// reassign
self._setOptionValue(name, option.negate ? false : val);
}
});
return this;
};
/**
* Define option with `flags`, `description` and optional
* coercion `fn`.
*
* The `flags` string should contain both the short and long flags,
* separated by comma, a pipe or space. The following are all valid
* all will output this way when `--help` is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* Examples:
*
* // simple boolean defaulting to undefined
* program.option('-p, --pepper', 'add pepper');
*
* program.pepper
* // => undefined
*
* --pepper
* program.pepper
* // => true
*
* // simple boolean defaulting to true (unless non-negated option is also defined)
* program.option('-C, --no-cheese', 'remove cheese');
*
* program.cheese
* // => true
*
* --no-cheese
* program.cheese
* // => false
*
* // required argument
* program.option('-C, --chdir <path>', 'change the working directory');
*
* --chdir /tmp
* program.chdir
* // => "/tmp"
*
* // optional argument
* program.option('-c, --cheese [type]', 'add cheese [marble]');
*
* @param {String} flags
* @param {String} description
* @param {Function|*} [fn] - custom option processing function or default vaue
* @param {*} [defaultValue]
* @return {Command} for chaining
* @api public
*/
Command.prototype.option = function(flags, description, fn, defaultValue) {
return this._optionEx({}, flags, description, fn, defaultValue);
};
/*
* Add a required option which must have a value after parsing. This usually means
* the option must be specified on the command line. (Otherwise the same as .option().)
*
* The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.
*
* @param {String} flags
* @param {String} description
* @param {Function|*} [fn] - custom option processing function or default vaue
* @param {*} [defaultValue]
* @return {Command} for chaining
* @api public
*/
Command.prototype.requiredOption = function(flags, description, fn, defaultValue) {
return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
};
/**
* Allow unknown options on the command line.
*
* @param {Boolean} arg if `true` or omitted, no error will be thrown
* for unknown options.
* @api public
*/
Command.prototype.allowUnknownOption = function(arg) {
this._allowUnknownOption = arguments.length === 0 || arg;
return this;
};
/**
* Whether to store option values as properties on command object,
* or store separately (specify false). In both cases the option values can be accessed using .opts().
*
* @param {boolean} value
* @return {Command} Command for chaining
* @api public
*/
Command.prototype.storeOptionsAsProperties = function(value) {
this._storeOptionsAsProperties = (value === undefined) || value;
if (this.options.length) {
// This is for programmer, not end user.
console.error('Commander usage error: call storeOptionsAsProperties before adding options');
}
return this;
};
/**
* Whether to pass command to action handler,
* or just the options (specify false).
*
* @param {boolean} value
* @return {Command} Command for chaining
* @api public
*/
Command.prototype.passCommandToAction = function(value) {
this._passCommandToAction = (value === undefined) || value;
return this;
};
/**
* Store option value
*
* @param {String} key
* @param {Object} value
* @api private
*/
Command.prototype._setOptionValue = function(key, value) {
if (this._storeOptionsAsProperties) {
this[key] = value;
} else {
this._optionValues[key] = value;
}
};
/**
* Retrieve option value
*
* @param {String} key
* @return {Object} value
* @api private
*/
Command.prototype._getOptionValue = function(key) {
if (this._storeOptionsAsProperties) {
return this[key];
}
return this._optionValues[key];
};
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* @param {Array} argv
* @return {Command} for chaining
* @api public
*/
Command.prototype.parse = function(argv) {
// implicit help
if (this.executables) this.addImplicitHelpCommand();
// store raw args
this.rawArgs = argv;
// guess name
this._name = this._name || basename(argv[1], '.js');
// github-style sub-commands with no sub-command
if (this.executables && argv.length < 3 && !this.defaultExecutable) {
// this user needs help
argv.push(this._helpLongFlag);
}
// process argv
var normalized = this.normalize(argv.slice(2));
var parsed = this.parseOptions(normalized);
var args = this.args = parsed.args;
var result = this.parseArgs(this.args, parsed.unknown);
if (args[0] === 'help' && args.length === 1) this.help();
// Note for future: we could return early if we found an action handler in parseArgs, as none of following code needed?
// <cmd> --help
if (args[0] === 'help') {
args[0] = args[1];
args[1] = this._helpLongFlag;
} else {
// If calling through to executable subcommand we could check for help flags before failing,
// but a somewhat unlikely case since program options not passed to executable subcommands.
// Wait for reports to see if check needed and what usage pattern is.
this._checkForMissingMandatoryOptions();
}
// executable sub-commands
// (Debugging note for future: args[0] is not right if an action has been called)
var name = result.args[0];
var subCommand = null;
// Look for subcommand
if (name) {
subCommand = this.commands.find(function(command) {
return command._name === name;
});
}
// Look for alias
if (!subCommand && name) {
subCommand = this.commands.find(function(command) {
return command.alias() === name;
});
if (subCommand) {
name = subCommand._name;
args[0] = name;
}
}
// Look for default subcommand
if (!subCommand && this.defaultExecutable) {
name = this.defaultExecutable;
args.unshift(name);
subCommand = this.commands.find(function(command) {
return command._name === name;
});
}
if (this._execs.has(name)) {
return this.executeSubCommand(argv, args, parsed.unknown, subCommand ? subCommand._executableFile : undefined);
}
return result;
};
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
*
* @param {Array} argv
* @return {Promise}
* @api public
*/
Command.prototype.parseAsync = function(argv) {
this.parse(argv);
return Promise.all(this._actionResults);
};
/**
* Execute a sub-command executable.
*
* @param {Array} argv
* @param {Array} args
* @param {Array} unknown
* @param {String} executableFile
* @api private
*/
Command.prototype.executeSubCommand = function(argv, args, unknown, executableFile) {
args = args.concat(unknown);
if (!args.length) this.help();
var isExplicitJS = false; // Whether to use node to launch "executable"
// executable
var pm = argv[1];
// name of the subcommand, like `pm-install`
var bin = basename(pm, path.extname(pm)) + '-' + args[0];
if (executableFile != null) {
bin = executableFile;
// Check for same extensions as we scan for below so get consistent launch behaviour.
var executableExt = path.extname(executableFile);
isExplicitJS = executableExt === '.js' || executableExt === '.ts' || executableExt === '.mjs';
}
// In case of globally installed, get the base dir where executable
// subcommand file should be located at
var baseDir;
var resolvedLink = fs.realpathSync(pm);
baseDir = dirname(resolvedLink);
// prefer local `./<bin>` to bin in the $PATH
var localBin = path.join(baseDir, bin);
// whether bin file is a js script with explicit `.js` or `.ts` extension
if (exists(localBin + '.js')) {
bin = localBin + '.js';
isExplicitJS = true;
} else if (exists(localBin + '.ts')) {
bin = localBin + '.ts';
isExplicitJS = true;
} else if (exists(localBin + '.mjs')) {
bin = localBin + '.mjs';
isExplicitJS = true;
} else if (exists(localBin)) {
bin = localBin;
}
args = args.slice(1);
var proc;
if (process.platform !== 'win32') {
if (isExplicitJS) {
args.unshift(bin);
// add executable arguments to spawn
args = incrementNodeInspectorPort(process.execArgv).concat(args);
proc = spawn(process.argv[0], args, { stdio: 'inherit' });
} else {
proc = spawn(bin, args, { stdio: 'inherit' });
}
} else {
args.unshift(bin);
// add executable arguments to spawn
args = incrementNodeInspectorPort(process.execArgv).concat(args);
proc = spawn(process.execPath, args, { stdio: 'inherit' });
}
var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
signals.forEach(function(signal) {
process.on(signal, function() {
if (proc.killed === false && proc.exitCode === null) {
proc.kill(signal);
}
});
});
// By default terminate process when spawned process terminates.
// Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!
const exitCallback = this._exitCallback;
if (!exitCallback) {
proc.on('close', process.exit.bind(process));
} else {
proc.on('close', () => {
exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));
});
}
proc.on('error', function(err) {
if (err.code === 'ENOENT') {
console.error('error: %s(1) does not exist, try --help', bin);
} else if (err.code === 'EACCES') {
console.error('error: %s(1) not executable. try chmod or run with root', bin);
}
if (!exitCallback) {
process.exit(1);
} else {
const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
wrappedError.nestedError = err;
exitCallback(wrappedError);
}
});
// Store the reference to the child process
this.runningCommand = proc;
};
/**
* Normalize `args`, splitting joined short flags. For example
* the arg "-abc" is equivalent to "-a -b -c".
* This also normalizes equal sign and splits "--abc=def" into "--abc def".
*
* @param {Array} args
* @return {Array}
* @api private
*/
Command.prototype.normalize = function(args) {
var ret = [],
arg,
lastOpt,
index,
short,
opt;
for (var i = 0, len = args.length; i < len; ++i) {
arg = args[i];
if (i > 0) {
lastOpt = this.optionFor(args[i - 1]);
}
if (arg === '--') {
// Honor option terminator
ret = ret.concat(args.slice(i));
break;
} else if (lastOpt && lastOpt.required) {
ret.push(arg);
} else if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
short = arg.slice(0, 2);
opt = this.optionFor(short);
if (opt && (opt.required || opt.optional)) {
ret.push(short);
ret.push(arg.slice(2));
} else {
arg.slice(1).split('').forEach(function(c) {
ret.push('-' + c);
});
}
} else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {
ret.push(arg.slice(0, index), arg.slice(index + 1));
} else {
ret.push(arg);
}
}
return ret;
};
/**
* Parse command `args`.
*
* When listener(s) are available those
* callbacks are invoked, otherwise the "*"
* event is emitted and those actions are invoked.
*
* @param {Array} args
* @return {Command} for chaining
* @api private
*/
Command.prototype.parseArgs = function(args, unknown) {
var name;
if (args.length) {
name = args[0];
if (this.listeners('command:' + name).length) {
this.emit('command:' + args.shift(), args, unknown);
} else {
this.emit('command:*', args, unknown);
}
} else {
outputHelpIfRequested(this, unknown);
// If there were no args and we have unknown options,
// then they are extraneous and we need to error.
if (unknown.length > 0 && !this.defaultExecutable) {
this.unknownOption(unknown[0]);
}
if (this.commands.length === 0 &&
this._args.filter(function(a) { return a.required; }).length === 0) {
this.emit('command:*');
}
}
return this;
};
/**
* Return an option matching `arg` if any.
*
* @param {String} arg
* @return {Option}
* @api private
*/
Command.prototype.optionFor = function(arg) {
for (var i = 0, len = this.options.length; i < len; ++i) {
if (this.options[i].is(arg)) {
return this.options[i];
}
}
};
/**
* Display an error message if a mandatory option does not have a value.
*
* @api private
*/
Command.prototype._checkForMissingMandatoryOptions = function() {
// Walk up hierarchy so can call from action handler after checking for displaying help.
for (var cmd = this; cmd; cmd = cmd.parent) {
cmd.options.forEach((anOption) => {
if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {
cmd.missingMandatoryOptionValue(anOption);
}
});
}
};
/**
* Parse options from `argv` returning `argv`
* void of these options.
*
* @param {Array} argv
* @return {{args: Array, unknown: Array}}
* @api public
*/
Command.prototype.parseOptions = function(argv) {
var args = [],
len = argv.length,
literal,
option,
arg;
var unknownOptions = [];
// parse options
for (var i = 0; i < len; ++i) {
arg = argv[i];
// literal args after --
if (literal) {
args.push(arg);
continue;
}
if (arg === '--') {
literal = true;
continue;
}
// find matching Option
option = this.optionFor(arg);
// option is defined
if (option) {
// requires arg
if (option.required) {
arg = argv[++i];
if (arg == null) return this.optionMissingArgument(option);
this.emit('option:' + option.name(), arg);
// optional arg
} else if (option.optional) {
arg = argv[i + 1];
if (arg == null || (arg[0] === '-' && arg !== '-')) {
arg = null;
} else {
++i;
}
this.emit('option:' + option.name(), arg);
// flag
} else {
this.emit('option:' + option.name());
}
continue;
}
// looks like an option
if (arg.length > 1 && arg[0] === '-') {
unknownOptions.push(arg);
// If the next argument looks like it might be
// an argument for this option, we pass it on.
// If it isn't, then it'll simply be ignored
if ((i + 1) < argv.length && (argv[i + 1][0] !== '-' || argv[i + 1] === '-')) {
unknownOptions.push(argv[++i]);
}
continue;
}
// arg
args.push(arg);
}
return { args: args, unknown: unknownOptions };
};
/**
* Return an object containing options as key-value pairs
*
* @return {Object}
* @api public
*/
Command.prototype.opts = function() {
if (this._storeOptionsAsProperties) {
// Preserve original behaviour so backwards compatible when still using properties
var result = {},
len = this.options.length;
for (var i = 0; i < len; i++) {
var key = this.options[i].attributeName();
result[key] = key === this._versionOptionName ? this._version : this[key];
}
return result;
}
return this._optionValues;
};
/**
* Argument `name` is missing.
*
* @param {String} name
* @api private
*/
Command.prototype.missingArgument = function(name) {
const message = `error: missing required argument '${name}'`;
console.error(message);
this._exit(1, 'commander.missingArgument', message);
};
/**
* `Option` is missing an argument, but received `flag` or nothing.
*
* @param {Option} option
* @param {String} [flag]
* @api private
*/
Command.prototype.optionMissingArgument = function(option, flag) {
let message;
if (flag) {
message = `error: option '${option.flags}' argument missing, got '${flag}'`;
} else {
message = `error: option '${option.flags}' argument missing`;
}
console.error(message);
this._exit(1, 'commander.optionMissingArgument', message);
};
/**
* `Option` does not have a value, and is a mandatory option.
*
* @param {Option} option
* @api private
*/
Command.prototype.missingMandatoryOptionValue = function(option) {
const message = `error: required option '${option.flags}' not specified`;
console.error(message);
this._exit(1, 'commander.missingMandatoryOptionValue', message);
};
/**
* Unknown option `flag`.
*
* @param {String} flag
* @api private
*/
Command.prototype.unknownOption = function(flag) {
if (this._allowUnknownOption) return;
const message = `error: unknown option '${flag}'`;
console.error(message);
this._exit(1, 'commander.unknownOption', message);
};
/**
* Variadic argument with `name` is not the last argument as required.
*
* @param {String} name
* @api private
*/
Command.prototype.variadicArgNotLast = function(name) {
const message = `error: variadic arguments must be last '${name}'`;
console.error(message);
this._exit(1, 'commander.variadicArgNotLast', message);
};
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* You can optionally supply the flags and description to override the defaults.
*
* @param {String} str
* @param {String} [flags]
* @param {String} [description]
* @return {Command} for chaining
* @api public
*/
Command.prototype.version = function(str, flags, description) {
if (arguments.length === 0) return this._version;
this._version = str;
flags = flags || '-V, --version';
description = description || 'output the version number';
var versionOption = new Option(flags, description);
this._versionOptionName = versionOption.long.substr(2) || 'version';
this.options.push(versionOption);
var self = this;
this.on('option:' + this._versionOptionName, function() {
process.stdout.write(str + '\n');
self._exit(0, 'commander.version', str);
});
return this;
};
/**
* Set the description to `str`.
*
* @param {String} str
* @param {Object} [argsDescription]
* @return {String|Command}
* @api public
*/
Command.prototype.description = function(str, argsDescription) {
if (arguments.length === 0) return this._description;
this._description = str;
this._argsDescription = argsDescription;
return this;
};
/**
* Set an alias for the command
*
* @param {String} alias
* @return {String|Command}
* @api public
*/
Command.prototype.alias = function(alias) {
var command = this;
if (this.commands.length !== 0) {
command = this.commands[this.commands.length - 1];
}
if (arguments.length === 0) return command._alias;
if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
command._alias = alias;
return this;
};
/**
* Set / get the command usage `str`.
*
* @param {String} [str]
* @return {String|Command}
* @api public
*/
Command.prototype.usage = function(str) {
var args = this._args.map(function(arg) {
return humanReadableArgName(arg);
});
var usage = '[options]' +
(this.commands.length ? ' [command]' : '') +
(this._args.length ? ' ' + args.join(' ') : '');
if (arguments.length === 0) return this._usage || usage;
this._usage = str;
return this;
};
/**
* Get or set the name of the command
*
* @param {String} [str]
* @return {String|Command}
* @api public
*/
Command.prototype.name = function(str) {
if (arguments.length === 0) return this._name;
this._name = str;
return this;
};
/**
* Return prepared commands.
*
* @return {Array}
* @api private
*/
Command.prototype.prepareCommands = function() {
return this.commands.filter(function(cmd) {
return !cmd._noHelp;
}).map(function(cmd) {
var args = cmd._args.map(function(arg) {
return humanReadableArgName(arg);
}).join(' ');
return [
cmd._name +
(cmd._alias ? '|' + cmd._alias : '') +
(cmd.options.length ? ' [options]' : '') +
(args ? ' ' + args : ''),
cmd._description
];
});
};
/**
* Return the largest command length.
*
* @return {Number}
* @api private
*/
Command.prototype.largestCommandLength = function() {
var commands = this.prepareCommands();
return commands.reduce(function(max, command) {
return Math.max(max, command[0].length);
}, 0);
};
/**
* Return the largest option length.
*
* @return {Number}
* @api private
*/
Command.prototype.largestOptionLength = function() {
var options = [].slice.call(this.options);
options.push({
flags: this._helpFlags
});
return options.reduce(function(max, option) {
return Math.max(max, option.flags.length);
}, 0);
};
/**
* Return the largest arg length.
*
* @return {Number}
* @api private
*/
Command.prototype.largestArgLength = function() {
return this._args.reduce(function(max, arg) {
return Math.max(max, arg.name.length);
}, 0);
};
/**
* Return the pad width.
*
* @return {Number}
* @api private
*/
Command.prototype.padWidth = function() {
var width = this.largestOptionLength();
if (this._argsDescription && this._args.length) {
if (this.largestArgLength() > width) {
width = this.largestArgLength();
}
}
if (this.commands && this.commands.length) {
if (this.largestCommandLength() > width) {
width = this.largestCommandLength();
}
}
return width;
};
/**
* Return help for options.
*
* @return {String}
* @api private
*/
Command.prototype.optionHelp = function() {
var width = this.padWidth();
var columns = process.stdout.columns || 80;
var descriptionWidth = columns - width - 4;
// Append the help information
return this.options.map(function(option) {
const fullDesc = option.description +
((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');
return pad(option.flags, width) + ' ' + optionalWrap(fullDesc, descriptionWidth, width + 2);
}).concat([pad(this._helpFlags, width) + ' ' + optionalWrap(this._helpDescription, descriptionWidth, width + 2)])
.join('\n');
};
/**
* Return command help documentation.
*
* @return {String}
* @api private
*/
Command.prototype.commandHelp = function() {
if (!this.commands.length) return '';
var commands = this.prepareCommands();
var width = this.padWidth();
var columns = process.stdout.columns || 80;
var descriptionWidth = columns - width - 4;
return [
'Commands:',
commands.map(function(cmd) {
var desc = cmd[1] ? ' ' + cmd[1] : '';
return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2);
}).join('\n').replace(/^/gm, ' '),
''
].join('\n');
};
/**
* Return program help documentation.
*
* @return {String}
* @api private
*/
Command.prototype.helpInformation = function() {
var desc = [];
if (this._description) {
desc = [
this._description,
''
];
var argsDescription = this._argsDescription;
if (argsDescription && this._args.length) {
var width = this.padWidth();
var columns = process.stdout.columns || 80;
var descriptionWidth = columns - width - 5;
desc.push('Arguments:');
desc.push('');
this._args.forEach(function(arg) {
desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name], descriptionWidth, width + 4));
});
desc.push('');
}
}
var cmdName = this._name;
if (this._alias) {
cmdName = cmdName + '|' + this._alias;
}
var parentCmdNames = '';
for (var parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {
parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;
}
var usage = [
'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(),
''
];
var cmds = [];
var commandHelp = this.commandHelp();
if (commandHelp) cmds = [commandHelp];
var options = [
'Options:',
'' + this.optionHelp().replace(/^/gm, ' '),
''
];
return usage
.concat(desc)
.concat(options)
.concat(cmds)
.join('\n');
};
/**
* Output help information for this command.
*
* When listener(s) are available for the helpLongFlag
* those callbacks are invoked.
*
* @api public
*/
Command.prototype.outputHelp = function(cb) {
if (!cb) {
cb = function(passthru) {
return passthru;
};
}
const cbOutput = cb(this.helpInformation());
if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) {
throw new Error('outputHelp callback must return a string or a Buffer');
}
process.stdout.write(cbOutput);
this.emit(this._helpLongFlag);
};
/**
* You can pass in flags and a description to override the help
* flags and help description for your command.
*
* @param {String} [flags]
* @param {String} [description]
* @return {Command}
* @api public
*/
Command.prototype.helpOption = function(flags, description) {
this._helpFlags = flags || this._helpFlags;
this._helpDescription = description || this._helpDescription;
var splitFlags = this._helpFlags.split(/[ ,|]+/);
if (splitFlags.length > 1) this._helpShortFlag = splitFlags.shift();
this._helpLongFlag = splitFlags.shift();
return this;
};
/**
* Output help information and exit.
*
* @param {Function} [cb]
* @api public
*/
Command.prototype.help = function(cb) {
this.outputHelp(cb);
// exitCode: preserving original behaviour which was calling process.exit()
// message: do not have all displayed text available so only passing placeholder.
this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)');
};
/**
* Camel-case the given `flag`
*
* @param {String} flag
* @return {String}
* @api private
*/
function camelcase(flag) {
return flag.split('-').reduce(function(str, word) {
return str + word[0].toUpperCase() + word.slice(1);
});
}
/**
* Pad `str` to `width`.
*
* @param {String} str
* @param {Number} width
* @return {String}
* @api private
*/
function pad(str, width) {
var len = Math.max(0, width - str.length);
return str + Array(len + 1).join(' ');
}
/**
* Wraps the given string with line breaks at the specified width while breaking
* words and indenting every but the first line on the left.
*
* @param {String} str
* @param {Number} width
* @param {Number} indent
* @return {String}
* @api private
*/
function wrap(str, width, indent) {
var regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');
var lines = str.match(regex) || [];
return lines.map(function(line, i) {
if (line.slice(-1) === '\n') {
line = line.slice(0, line.length - 1);
}
return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight();
}).join('\n');
}
/**
* Optionally wrap the given str to a max width of width characters per line
* while indenting with indent spaces. Do not wrap if insufficient width or
* string is manually formatted.
*
* @param {String} str
* @param {Number} width
* @param {Number} indent
* @return {String}
* @api private
*/
function optionalWrap(str, width, indent) {
// Detect manually wrapped and indented strings by searching for line breaks
// followed by multiple spaces/tabs.
if (str.match(/[\n]\s+/)) return str;
// Do not wrap to narrow columns (or can end up with a word per line).
const minWidth = 40;
if (width < minWidth) return str;
return wrap(str, width, indent);
}
/**
* Output help information if help flags specified
*
* @param {Command} cmd - command to output help for
* @param {Array} options - array of options to search for -h or --help
* @api private
*/
function outputHelpIfRequested(cmd, options) {
options = options || [];
for (var i = 0; i < options.length; i++) {
if (options[i] === cmd._helpLongFlag || options[i] === cmd._helpShortFlag) {
cmd.outputHelp();
// (Do not have all displayed text available so only passing placeholder.)
cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');
}
}
}
/**
* Takes an argument and returns its human readable equivalent for help usage.
*
* @param {Object} arg
* @return {String}
* @api private
*/
function humanReadableArgName(arg) {
var nameOutput = arg.name + (arg.variadic === true ? '...' : '');
return arg.required
? '<' + nameOutput + '>'
: '[' + nameOutput + ']';
}
// for versions before node v0.8 when there weren't `fs.existsSync`
function exists(file) {
try {
if (fs.statSync(file).isFile()) {
return true;
}
} catch (e) {
return false;
}
}
/**
* Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
*
* @param {string[]} args - array of arguments from node.execArgv
* @returns {string[]}
* @api private
*/
function incrementNodeInspectorPort(args) {
// Testing for these options:
// --inspect[=[host:]port]
// --inspect-brk[=[host:]port]
// --inspect-port=[host:]port
return args.map((arg) => {
var result = arg;
if (arg.indexOf('--inspect') === 0) {
var debugOption;
var debugHost = '127.0.0.1';
var debugPort = '9229';
var match;
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
// e.g. --inspect
debugOption = match[1];
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
debugOption = match[1];
if (/^\d+$/.test(match[3])) {
// e.g. --inspect=1234
debugPort = match[3];
} else {
// e.g. --inspect=localhost
debugHost = match[3];
}
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
// e.g. --inspect=localhost:1234
debugOption = match[1];
debugHost = match[3];
debugPort = match[4];
}
if (debugOption && debugPort !== '0') {
result = `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
}
}
return result;
});
}
{
"name": "commander",
"version": "4.1.1",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"commander",
"command",
"option",
"parser"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/tj/commander.js.git"
},
"scripts": {
"lint": "eslint index.js \"tests/**/*.js\"",
"test": "jest && npm run test-typings",
"test-typings": "tsc -p tsconfig.json"
},
"main": "index",
"files": [
"index.js",
"typings/index.d.ts"
],
"dependencies": {},
"devDependencies": {
"@types/jest": "^24.0.23",
"@types/node": "^12.12.11",
"eslint": "^6.7.0",
"eslint-plugin-jest": "^22.21.0",
"jest": "^24.8.0",
"standard": "^14.3.1",
"typescript": "^3.7.2"
},
"typings": "typings/index.d.ts",
"engines": {
"node": ">= 6"
}
}
// Type definitions for commander
// Original definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
///<reference types="node" />
declare namespace commander {
interface CommanderError extends Error {
code: string;
exitCode: number;
message: string;
nestedError?: string;
}
type CommanderErrorConstructor = { new (exitCode: number, code: string, message: string): CommanderError };
interface Option {
flags: string;
required: boolean; // A value must be supplied when the option is specified.
optional: boolean; // A value is optional when the option is specified.
mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.
bool: boolean;
short?: string;
long: string;
description: string;
}
type OptionConstructor = { new (flags: string, description?: string): Option };
interface Command extends NodeJS.EventEmitter {
[key: string]: any; // options as properties
args: string[];
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* You can optionally supply the flags and description to override the defaults.
*/
version(str: string, flags?: string, description?: string): Command;
/**
* Define a command, implemented using an action handler.
*
* @remarks
* The command description is supplied using `.description`, not as a parameter to `.command`.
*
* @example
* ```ts
* program
* .command('clone <source> [destination]')
* .description('clone a repository into a newly created directory')
* .action((source, destination) => {
* console.log('clone command called');
* });
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param opts - configuration options
* @returns new command
*/
command(nameAndArgs: string, opts?: CommandOptions): Command;
/**
* Define a command, implemented in a separate executable file.
*
* @remarks
* The command description is supplied as the second parameter to `.command`.
*
* @example
* ```ts
* program
* .command('start <service>', 'start named service')
* .command('stop [service]', 'stop named serice, or all if no name supplied');
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param description - description of executable command
* @param opts - configuration options
* @returns top level command for chaining more command definitions
*/
command(nameAndArgs: string, description: string, opts?: commander.CommandOptions): Command;
/**
* Define argument syntax for the top-level command.
*
* @returns Command for chaining
*/
arguments(desc: string): Command;
/**
* Parse expected `args`.
*
* For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
*
* @returns Command for chaining
*/
parseExpectedArgs(args: string[]): Command;
/**
* Register callback to use as replacement for calling process.exit.
*/
exitOverride(callback?: (err: CommanderError) => never|void): Command;
/**
* Register callback `fn` for the command.
*
* @example
* program
* .command('help')
* .description('display verbose help')
* .action(function() {
* // output help here
* });
*
* @returns Command for chaining
*/
action(fn: (...args: any[]) => void | Promise<void>): Command;
/**
* Define option with `flags`, `description` and optional
* coercion `fn`.
*
* The `flags` string should contain both the short and long flags,
* separated by comma, a pipe or space. The following are all valid
* all will output this way when `--help` is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* @example
* // simple boolean defaulting to false
* program.option('-p, --pepper', 'add pepper');
*
* --pepper
* program.pepper
* // => Boolean
*
* // simple boolean defaulting to true
* program.option('-C, --no-cheese', 'remove cheese');
*
* program.cheese
* // => true
*
* --no-cheese
* program.cheese
* // => false
*
* // required argument
* program.option('-C, --chdir <path>', 'change the working directory');
*
* --chdir /tmp
* program.chdir
* // => "/tmp"
*
* // optional argument
* program.option('-c, --cheese [type]', 'add cheese [marble]');
*
* @returns Command for chaining
*/
option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command;
option(flags: string, description?: string, defaultValue?: any): Command;
/**
* Define a required option, which must have a value after parsing. This usually means
* the option must be specified on the command line. (Otherwise the same as .option().)
*
* The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.
*/
requiredOption(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command;
requiredOption(flags: string, description?: string, defaultValue?: any): Command;
/**
* Whether to store option values as properties on command object,
* or store separately (specify false). In both cases the option values can be accessed using .opts().
*
* @return Command for chaining
*/
storeOptionsAsProperties(value?: boolean): Command;
/**
* Whether to pass command to action handler,
* or just the options (specify false).
*
* @return Command for chaining
*/
passCommandToAction(value?: boolean): Command;
/**
* Allow unknown options on the command line.
*
* @param [arg] if `true` or omitted, no error will be thrown for unknown options.
* @returns Command for chaining
*/
allowUnknownOption(arg?: boolean): Command;
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* @returns Command for chaining
*/
parse(argv: string[]): Command;
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
*
* @returns Promise
*/
parseAsync(argv: string[]): Promise<any>;
/**
* Parse options from `argv` returning `argv` void of these options.
*/
parseOptions(argv: string[]): commander.ParseOptionsResult;
/**
* Return an object containing options as key-value pairs
*/
opts(): { [key: string]: any };
/**
* Set the description.
*
* @returns Command for chaining
*/
description(str: string, argsDescription?: {[argName: string]: string}): Command;
/**
* Get the description.
*/
description(): string;
/**
* Set an alias for the command.
*
* @returns Command for chaining
*/
alias(alias: string): Command;
/**
* Get alias for the command.
*/
alias(): string;
/**
* Set the command usage.
*
* @returns Command for chaining
*/
usage(str: string): Command;
/**
* Get the command usage.
*/
usage(): string;
/**
* Set the name of the command.
*
* @returns Command for chaining
*/
name(str: string): Command;
/**
* Get the name of the command.
*/
name(): string;
/**
* Output help information for this command.
*
* When listener(s) are available for the helpLongFlag
* those callbacks are invoked.
*/
outputHelp(cb?: (str: string) => string): void;
/**
* You can pass in flags and a description to override the help
* flags and help description for your command.
*/
helpOption(flags?: string, description?: string): Command;
/**
* Output help information and exit.
*/
help(cb?: (str: string) => string): never;
}
type CommandConstructor = { new (name?: string): Command };
interface CommandOptions {
noHelp?: boolean;
isDefault?: boolean;
executableFile?: string;
}
interface ParseOptionsResult {
args: string[];
unknown: string[];
}
interface CommanderStatic extends Command {
Command: CommandConstructor;
Option: OptionConstructor;
CommanderError:CommanderErrorConstructor;
}
}
declare const commander: commander.CommanderStatic;
export = commander;
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment