const Command = require('common-bin');class CloneCommand extends Command { constructor(rawArgv) { super(rawArgv); this.options = { depth: { type: 'number', description: 'Create a shallow clone with a history truncated to the specified number of commits', }, }; } async run({ argv }) { console.log('git clone %s to %s with depth %d', argv._[0], argv._[1], argv.depth); } get description() { return 'Clone a repository into a new directory';
Run result
$ my-git clone gh://node-modules/common-bin dist --depth=1git clone gh://node-modules/common-bin to dist with depth 1
Concept
Command
Define the main logic of command
Method:
async start() - start your program, only use once in your bin file.
async run(context)
should implement this to provide command handler, will exec when not found sub command.
Support generator / async function / normal function which return promise.
context is { cwd, env, argv, rawArgv }
cwd - process.cwd()
env - clone env object from process.env
argv - argv parse result by yargs, { _: [ 'start' ], '$0': '/usr/local/bin/common-bin', baseDir: 'simple'}
rawArgv - the raw argv, [ "--baseDir=simple" ]
load(fullPath) - register the entire directory to commands
add(name, target) - register special command with command name, target could be full path of file or Class.
alias(alias, name) - register a command with an existing command
showHelp() - print usage message to console.
options= - a setter, shortcut for yargs.options
usage= - a setter, shortcut for yargs.usage
Properties:
description - {String} a getter, only show this description when it's a sub command in help console
helper - {Object} helper instance
yargs - {Object} yargs instance for advanced custom usage
options - {Object} a setter, set yargs' options
version - {String} customize version, can be defined as a getter to support lazy load.
parserOptions - {Object} control context parse rule.
execArgv - {Boolean} whether extract execArgv to context.execArgv
removeAlias - {Boolean} whether remove alias key from argv
removeCamelCase - {Boolean} whether remove camel case key from argv
$ # exec below will print usage for auto bash completion$ my-git completion$ # exec below will mount auto completion to your bash$ my-git completion >> ~/.bashrc
Migrating from v1 to v3
bin
run method is not longer exist.
// 1.xconst run = require('common-bin').run;run(require('../lib/my_program'));// 3.x// require a main Commandconst Command = require('..');new Command().start();
Program
Program is just a Command sub class, you can call it Main Command now.
addCommand() is replace with add().
Recommand to use load() to load the whole command directory.