adding mermaid packages

This commit is contained in:
shiva108
2026-01-23 15:09:56 +01:00
parent 91dccbba6f
commit 2ec4191721
9491 changed files with 1062059 additions and 1 deletions
+19
View File
@@ -0,0 +1,19 @@
{
"rules": {
"indent": [ 2, 4 ],
"quotes": [ 2, "single" ],
"linebreak-style": [ 2, "unix" ],
"semi": [ 2, "always" ],
"no-unused-vars": [ 2, {
"vars": "all",
"args": "none"
} ],
"spaced-comment": [ 2, "always" ]
},
"env": {
"node": true,
"mocha": true,
"browser": true
},
"extends": "eslint:recommended"
}
+30
View File
@@ -0,0 +1,30 @@
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
# Deployed apps should consider commenting this line out:
# see https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git
node_modules
# vim swapfile
*.swp
.tmp
+4
View File
@@ -0,0 +1,4 @@
sudo: false
language: node_js
node_js:
- "lts/*"
+91
View File
@@ -0,0 +1,91 @@
# gitbook-cli
[![NPM version](https://badge.fury.io/js/gitbook-cli.svg)](http://badge.fury.io/js/gitbook-cli)
[![Linux Build Status](https://travis-ci.org/GitbookIO/gitbook-cli.png?branch=master)](https://travis-ci.org/GitbookIO/gitbook-cli)
[![Windows Build status](https://ci.appveyor.com/api/projects/status/gddbj0602joc4wah?svg=true)](https://ci.appveyor.com/project/GitBook/gitbook-cli)
> The GitBook command line interface.
Install this globally and you'll have access to the gitbook command anywhere on your system.
```
$ npm install -g gitbook-cli
```
**Note:** The purpose of the gitbook command is to load and run the version of GitBook you have specified in your book (or the latest one), irrespective of its version. The GitBook CLI only support versions `>=2.0.0` of GitBook.
`gitbook-cli` store GitBook's versions into `~/.gitbook`, you can set the `GITBOOK_DIR` environment variable to use another directory.
## How to install it?
```
$ npm install -g gitbook-cli
```
## How to use it?
### Run GitBook
Run command `gitbook build`, `gitbook serve` (read [GitBook documentation](https://github.com/GitbookIO/gitbook/blob/master/docs/setup.md) for details).
List all available commands using:
```
$ gitbook help
```
#### Specify a specific version
By default, GitBook CLI will read the gitbook version to use from the book configuration, but you can force a specific version using `--gitbook` option:
```
$ gitbook build ./mybook --gitbook=2.0.1
```
and list available commands in this version using:
```
$ gitbook help --gitbook=2.0.1
```
#### Manage versions
List installed versions:
```
$ gitbook ls
```
List available versions on NPM:
```
$ gitbook ls-remote
```
Install a specific version:
```
$ gitbook fetch 2.1.0
# or a pre-release
$ gitbook fetch beta
```
Update to the latest version
```
$ gitbook update
```
Uninstall a specific version
```
$ gitbook uninstall 2.0.1
```
Use a local folder as a GitBook version (for developement)
```
$ gitbook alias ./mygitbook latest
```
+26
View File
@@ -0,0 +1,26 @@
# Fix line endings in Windows. (runs before repo cloning)
init:
- git config --global core.autocrlf input
# Test against these versions of Node.js.
environment:
matrix:
- nodejs_version: "6.10.3"
# Install scripts. (runs after repo cloning)
install:
# Get the latest stable version of Node.js or io.js
- ps: Install-Product node $env:nodejs_version
# install modules
- npm install
# Post-install test scripts.
test_script:
# Output useful info for debugging.
- node --version
- npm --version
# run tests
- npm test
# Don't actually build.
build: off
Generated Vendored Executable
+198
View File
@@ -0,0 +1,198 @@
#! /usr/bin/env node
var Q = require('q');
var _ = require('lodash');
var path = require('path');
var program = require('commander');
var parsedArgv = require('optimist').argv;
var color = require('bash-color');
var pkg = require('../package.json');
var manager = require('../lib');
var tags = require('../lib/tags');
var commands = require('../lib/commands');
// Which book is concerned?
var bookRoot = parsedArgv._[1] || process.cwd();
function runPromise(p) {
return p
.then(function() {
process.exit(0);
}, function(err) {
console.log('');
console.log(color.red(err.toString()));
if (program.debug || process.env.DEBUG) console.log(err.stack || '');
process.exit(1);
});
}
function printGitbookVersion(v) {
var actualVersion = (v.name != v.version)? ' ('+v.version+')' : '';
return v.name + actualVersion;
}
// Init gitbook-cli
manager.init();
program
.option('-v, --gitbook [version]', 'specify GitBook version to use')
.option('-d, --debug', 'enable verbose error')
.option('-V, --version', 'Display running versions of gitbook and gitbook-cli', function() {
console.log('CLI version:', pkg.version);
runPromise(
manager.ensure(bookRoot, program.gitbook)
.then(function(v) {
console.log('GitBook version:', printGitbookVersion(v));
process.exit(0);
})
);
});
program
.command('ls')
.description('List versions installed locally')
.action(function(){
var versions = manager.versions();
if (versions.length > 0) {
console.log('GitBook Versions Installed:');
console.log('');
_.each(versions,function(v, i) {
var text = v.name;
if (v.name != v.version) text += ' [' + v.version + ']';
if (v.link) text = text + ' (alias of ' + v.link + ')';
console.log(' ', i == 0? '*' : ' ', text);
});
console.log('');
console.log('Run "gitbook update" to update to the latest version.');
} else {
console.log('There is no versions installed');
console.log('You can install the latest version using: "gitbook fetch"');
}
});
program
.command('current')
.description('Display currently activated version')
.action(function(){
runPromise(
manager.ensure(bookRoot, program.gitbook)
.then(function(v) {
console.log('GitBook version is', printGitbookVersion(v));
})
);
});
program
.command('ls-remote')
.description('List remote versions available for install')
.action(function(){
runPromise(
manager.available()
.then(function(available) {
console.log('Available GitBook Versions:');
console.log('');
console.log(' ', available.versions.join(', '));
console.log('');
console.log('Tags:');
console.log('');
_.each(available.tags, function(version, tagName) {
console.log(' ', tagName, ':', version);
});
console.log('');
})
);
});
program
.command('fetch [version]')
.description('Download and install a <version>')
.action(function(version){
version = version || '*';
runPromise(
manager.install(version)
.then(function(installedVersion) {
console.log('');
console.log(color.green('GitBook '+installedVersion+' has been installed'));
})
);
});
program
.command('alias [folder] [version]')
.description('Set an alias named <version> pointing to <folder>')
.action(function(folder, version) {
folder = path.resolve(folder || process.cwd());
version = version || 'latest';
runPromise(
manager.link(version, folder)
.then(function() {
console.log(color.green('GitBook '+version+' point to '+folder));
})
);
});
program
.command('uninstall [version]')
.description('Uninstall a version')
.action(function(version){
runPromise(
manager.uninstall(version)
.then(function() {
console.log(color.green('GitBook '+version+' has been uninstalled.'));
})
);
});
program
.command('update [tag]')
.description('Update to the latest version of GitBook')
.action(function(tag){
runPromise(
manager.update(tag)
.then(function(version) {
if (!version) {
console.log('No update found!');
} else {
console.log('');
console.log(color.green('GitBook has been updated to '+version));
}
})
);
});
program
.command('help')
.description('List commands for GitBook')
.action(function(){
runPromise(
manager.ensureAndLoad(bookRoot, program.gitbook)
.get('commands')
.then(commands.help)
);
});
program
.command('*')
.description('run a command with a specific gitbook version')
.action(function(commandName){
var args = parsedArgv._.slice(1);
var kwargs = _.omit(parsedArgv, '$0', '_');
runPromise(
manager.ensureAndLoad(bookRoot, program.gitbook)
.then(function(gitbook) {
return commands.exec(gitbook.commands, commandName, args, kwargs);
})
);
});
// Parse and fallback to help if no args
if(_.isEmpty(program.parse(process.argv).args) && process.argv.length === 2) {
program.help();
}
+65
View File
@@ -0,0 +1,65 @@
var _ = require('lodash');
// Helper function for print help
// indented output by spaces
function indent_output(n, name, description) {
if (!n) {
n = 0;
}
console.log(
_.repeat(' ', n)
+ name
+ _.repeat(' ', 32 - n * 4 - name.length)
+ description
);
}
// Print help for a list of commands
// It prints the command and its description, then all the options
function help(commands) {
_.each(commands, function(command) {
indent_output(1, command.name, command.description);
_.each(command.options || [], function(option) {
var after = [];
if (option.defaults !== undefined) after.push("Default is "+option.defaults);
if (option.values) after.push("Values are "+option.values.join(", "));
if (after.length > 0) after = "("+after.join("; ")+")";
else after = "";
var optname = '--';
if (typeof option.defaults === 'boolean') optname += '[no-]';
optname += option.name;
indent_output(2, optname, option.description + ' ' + after);
});
console.log('');
});
}
// Execute a command from a list
// with a specific set of args/kwargs
function exec(commands, command, args, kwargs) {
var cmd = _.find(commands, function(_cmd) {
return _.first(_cmd.name.split(" ")) == command;
});
// Command not found
if (!cmd) throw new Error('Command '+command+' doesn\'t exist, run "gitbook help" to list commands.');
// Apply defaults
_.each(cmd.options || [], function(option) {
kwargs[option.name] = (kwargs[option.name] === undefined)? option.defaults : kwargs[option.name];
if (option.values && !_.includes(option.values, kwargs[option.name])) {
throw new Error('Invalid value for option "'+option.name+'"');
}
});
return cmd.exec(args, kwargs);
}
module.exports = {
help: help,
exec: exec
};
+41
View File
@@ -0,0 +1,41 @@
var path = require('path');
var fs = require('fs-extra');
var color = require('bash-color');
var userHome = require('user-home');
var CONFIG_ROOT = process.env.GITBOOK_DIR;
if (!CONFIG_ROOT) {
if (!userHome) {
console.log(color.red('HOME or GITBOOK_DIR needs to be defined'));
process.exit(1);
}
CONFIG_ROOT = path.resolve(userHome, '.gitbook');
}
var VERSIONS_ROOT = path.resolve(CONFIG_ROOT, 'versions');
// Init and prepare configuration for gitbook-cli
// It creates the required folder
function init() {
fs.mkdirsSync(CONFIG_ROOT);
fs.mkdirsSync(VERSIONS_ROOT);
}
// Replace root folder to use
function setRoot(root) {
CONFIG_ROOT = path.resolve(root);
VERSIONS_ROOT = path.resolve(CONFIG_ROOT, 'versions');
module.exports.ROOT = CONFIG_ROOT;
module.exports.VERSIONS_ROOT = VERSIONS_ROOT;
}
module.exports = {
init: init,
setRoot: setRoot,
GITBOOK_VERSION: '>1.x.x',
ROOT: CONFIG_ROOT,
VERSIONS_ROOT: VERSIONS_ROOT
};
+121
View File
@@ -0,0 +1,121 @@
var Q = require('q');
var _ = require('lodash');
var path = require('path');
var config = require('./config');
var local = require('./local');
var registry = require('./registry');
var tags = require('./tags');
// Return book version (string) required by a book
function bookVersion(bookRoot) {
var version;
try {
var bookJson = require(path.resolve(bookRoot, 'book'));
version = bookJson.gitbook;
} catch (e) {
if (e.code != 'MODULE_NOT_FOUND') throw e;
}
return version || '*';
}
// Ensure that a version exists
// or install it
function ensureVersion(bookRoot, version, opts) {
opts = _.defaults(opts || {}, {
install: true
});
return Q()
// If not defined, load version required from book.json
.then(function() {
if (version) return version;
return bookVersion(bookRoot);
})
// Resolve version locally
.then(function(_version) {
version = _version;
return local.resolve(version)
// Install if needed
.fail(function(err) {
if (!opts.install) throw err;
return registry.install(version)
.then(function() {
return ensureVersion(bookRoot, version, {
install: false
});
});
});
});
}
// Get version in a book
function getVersion(bookRoot, version) {
return ensureVersion(bookRoot, version, {
install: false
});
}
// Ensure a version exists (or install it)
// Then load it and returns the gitbook instance
function ensureAndLoad(bookRoot, version, opts) {
return ensureVersion(bookRoot, version, opts)
.then(function(version) {
return local.load(version);
});
}
// Update current version
// -> Check that a newer version exists
// -> Install it
// -> Remove previous version
function updateVersion(tag) {
tag = tag || 'latest';
return getVersion(null, {
install: false
})
.fail(function(err) {
return Q(null);
})
.then(function(currentV) {
return registry.versions()
.then(function(result) {
var remoteVersion = result.tags[tag];
if (!remoteVersion) throw new Error('Tag doesn\'t exist: '+tag);
if (currentV && tags.sort(remoteVersion, currentV.version) >= 0) return null;
return registry.install(remoteVersion)
.then(function() {
if (!currentV) return;
return local.remove(currentV.tag);
})
.thenResolve(remoteVersion);
});
});
}
module.exports = {
init: config.init,
setRoot: config.setRoot,
load: local.load,
get: getVersion,
getBookVersion: bookVersion,
ensure: ensureVersion,
ensureAndLoad: ensureAndLoad,
uninstall: local.remove,
link: local.link,
versions: local.versions,
update: updateVersion,
install: registry.install,
available: registry.versions
};
+129
View File
@@ -0,0 +1,129 @@
var Q = require('q');
var fs = require('fs-extra');
var path = require('path');
var _ = require('lodash');
var npmi = require('npmi');
var npm = require('npm');
var tmp = require('tmp');
var color = require('bash-color');
var parsedArgv = require('optimist').argv;
var config = require('./config');
var tags = require('./tags');
// Return a list of all available versions on this system
function listVersions() {
var folders = fs.readdirSync(config.VERSIONS_ROOT);
var latest = null;
return _.chain(folders)
.map(function(tag) {
// Verison matches requirements?
if (!tags.isValid(tag)) return null;
// Read package.json to determine version
var versionFolder = path.resolve(config.VERSIONS_ROOT, tag);
var stat = fs.lstatSync(versionFolder);
var pkg;
try {
pkg = require(path.resolve(versionFolder, 'package.json'));
} catch(e) {
return null;
}
// Is it gitbook?
if (pkg.name != 'gitbook') return null;
return {
// The name associated in the folder
name: tag,
// The real absolute version
version: pkg.version,
// Location of this version
path: versionFolder,
// Location if it's a symlink
link: stat.isSymbolicLink()? fs.readlinkSync(versionFolder) : null,
// Type of release, latest, beta, etc ?
tag: tags.getTag(pkg.version)
};
})
.compact()
// Sort by the version
.sort(function(a, b) {
return tags.sort(a.version, b.version);
})
.value();
}
// Return path to a specific version
function versionRoot(version) {
return path.resolve(config.VERSIONS_ROOT, version);
}
// Resolve a version using a condition
function resolveVersion(condition) {
var versions = listVersions();
var version = _.chain(versions)
.find(function(v) {
return tags.satisfies(v.name, condition);
})
.value();
if (!version) return Q.reject(new Error('No version match: '+condition));
return Q(version);
}
// Remove an installed version of gitbook
function removeVersion(version) {
if (!version) return Q.reject(new Error('No version specified'));
var outputFolder = versionRoot(version);
return Q.nfcall(fs.lstat.bind(fs), outputFolder)
.then(function(stat) {
if (stat.isSymbolicLink()) {
return Q.nfcall(fs.unlink.bind(fs), outputFolder);
}
return Q.nfcall(fs.remove.bind(fs), outputFolder);
});
}
// Load a gitbook version
function loadVersion(version) {
return Q(_.isString(version)? resolveVersion(version) : version)
.then(function(resolved) {
var gitbook;
try {
gitbook = require(resolved.path);
} catch (err) {
console.log(color.red('Error loading version '+resolved.tag+': '+(err.stack || err.message || err)));
return null;
}
if (!gitbook) throw new Error('GitBook Version '+resolved.tag+' is corrupted');
return gitbook;
});
}
// Link a folder to a tag
function linkVersion(name, folder) {
if (!name) return Q.reject(new Error('Require a name to represent this GitBook version'));
if (!folder) return Q.reject(new Error('Require a folder'));
var outputFolder = versionRoot(name);
return Q.nfcall(fs.symlink.bind(fs), folder, outputFolder);
}
module.exports = {
load: loadVersion,
resolve: resolveVersion,
versions: listVersions,
remove: removeVersion,
link: linkVersion
};
+110
View File
@@ -0,0 +1,110 @@
var Q = require('q');
var fs = require('fs-extra');
var npmi = require('npmi');
var npm = require('npm');
var tmp = require('tmp');
var _ = require('lodash');
var path = require('path');
var tags = require('./tags');
var config = require('./config');
// Initialize NPM before usage
var initNPM = _.memoize(function() {
return Q.nfcall(npm.load, {
silent: true,
loglevel: 'silent'
});
});
// Return a list of versions available in the registry (npm)
function availableVersions() {
return initNPM()
.then(function() {
return Q.nfcall(npm.commands.view, ['gitbook', 'versions', 'dist-tags'], true);
})
.then(function(result) {
result = _.chain(result).values().first().value();
result = {
versions: _.chain(result.versions)
.filter(function(v) {
return tags.isValid(v);
})
.sort(tags.sort)
.value(),
tags: _.chain(result['dist-tags'])
.omit(function(tagVersion, tagName) {
return !tags.isValid(tagVersion);
})
.value()
};
if (result.versions.length == 0) throw new Error('No valid version on the NPM registry');
return result;
});
}
// Resolve a version name or tag to an installable absolute version
function resolveVersion(version) {
var _version = version;
return availableVersions()
.then(function(available) {
// Resolve if tag
if (available.tags[version]) version = available.tags[version];
version = _.find(available.versions, function(v) {
return tags.satisfies(v, version, {
// Tag is resolved from npm dist-tags
acceptTagCondition: false
});
});
// Check version
if (!version) throw new Error('Invalid version or tag "'+_version+'", see available using "gitbook ls-remote"');
return version;
});
}
// Install a specific version of gitbook
function installVersion(version, forceInstall) {
return resolveVersion(version)
.then(function(_version) {
version = _version;
return Q.nfcall(tmp.dir.bind(tmp));
})
.spread(function(tmpDir) {
var options = {
name: 'gitbook',
version: version,
path: tmpDir,
forceInstall: !!forceInstall,
npmLoad: {
loglevel: 'silent',
loaded: false,
prefix: tmpDir
}
};
console.log('Installing GitBook', version);
return Q.nfcall(npmi.bind(npmi), options).thenResolve(tmpDir);
})
.then(function(tmpDir) {
var gitbookRoot = path.resolve(tmpDir, 'node_modules/gitbook');
var packageJson = fs.readJsonSync(path.resolve(gitbookRoot, 'package.json'));
var version = packageJson.version;
var outputFolder = path.resolve(config.VERSIONS_ROOT, version);
if (!tags.isValid(version)) throw 'Invalid GitBook version, should satisfies '+config.GITBOOK_VERSION;
// Copy to the install folder
return Q.nfcall(fs.copy.bind(fs), gitbookRoot, outputFolder)
.thenResolve(version);
});
}
module.exports = {
versions: availableVersions,
resolve: resolveVersion,
install: installVersion
};
+81
View File
@@ -0,0 +1,81 @@
var _ = require('lodash');
var semver = require('semver');
var config = require('./config');
var ALLOWED_TAGS = ['latest', 'pre', 'beta', 'alpha'];
// Returns true if a version is a tag
function isTag(version) {
return _.includes(ALLOWED_TAGS, version);
}
// Return true if a version matches gitbook-cli's requirements
function isValid(version) {
if (isTag(version)) return true;
var versionWithoutPre = version.replace(/\-(\S+)/g, '');
try {
return semver.satisfies(versionWithoutPre, config.GITBOOK_VERSION);
} catch(e) {
return false;
}
}
// Extract prerelease tag from a version
function getTag(version) {
if (isTag(version)) return version;
var v = semver.parse(version);
return v.prerelease[0] || 'latest';
}
// Sort versions (tale prerelease tags in consideration)
function sortTags(a, b) {
if (isTag(a) && isTag(b)) {
var indexA = ALLOWED_TAGS.indexOf(a);
var indexB = ALLOWED_TAGS.indexOf(b);
if (indexA > indexB) return -1;
if (indexB > indexA) return 1;
return 0;
}
if (isTag(a)) return -1;
if (isTag(b)) return 1;
if (semver.gt(a, b)) {
return -1;
}
if (semver.lt(a, b)) {
return 1;
}
return 0;
}
// Returns true if a version satisfies a condition
function satisfies(version, condition, opts) {
opts = _.defaults(opts || {}, {
acceptTagCondition: true
});
if (isTag(version)) {
return (condition == '*' || version == condition);
}
// Condition is a tag ('beta', 'latest')
if (opts.acceptTagCondition) {
var tag = getTag(version);
if (tag == condition) return true;
}
return semver.satisfies(version, condition);
}
module.exports = {
isTag: isTag,
isValid: isValid,
sort: sortTags,
satisfies: satisfies,
getTag: getTag
};
+298
View File
@@ -0,0 +1,298 @@
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 doesnt 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)
1.3.2 / 2013-07-18
==================
* add support for sub-commands to co-exist with the original command
1.3.1 / 2013-07-18
==================
* add quick .runningCommand hack so you can opt-out of other logic when running a sub command
1.3.0 / 2013-07-09
==================
* add EACCES error handling
* fix sub-command --help
1.2.0 / 2013-06-13
==================
* allow "-" hyphen as an option argument
* support for RegExp coercion
1.1.1 / 2012-11-20
==================
* add more sub-command padding
* fix .usage() when args are present. Closes #106
1.1.0 / 2012-11-16
==================
* add git-style executable subcommand support. Closes #94
1.0.5 / 2012-10-09
==================
* fix `--name` clobbering. Closes #92
* fix examples/help. Closes #89
1.0.4 / 2012-09-03
==================
* add `outputHelp()` method.
1.0.3 / 2012-08-30
==================
* remove invalid .version() defaulting
1.0.2 / 2012-08-24
==================
* add `--foo=bar` support [arv]
* fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus]
1.0.1 / 2012-08-03
==================
* fix issue #56
* fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode())
1.0.0 / 2012-07-05
==================
* add support for optional option descriptions
* add defaulting of `.version()` to package.json's version
0.6.1 / 2012-06-01
==================
* Added: append (yes or no) on confirmation
* Added: allow node.js v0.7.x
0.6.0 / 2012-04-10
==================
* Added `.prompt(obj, callback)` support. Closes #49
* Added default support to .choose(). Closes #41
* Fixed the choice example
0.5.1 / 2011-12-20
==================
* Fixed `password()` for recent nodes. Closes #36
0.5.0 / 2011-12-04
==================
* Added sub-command option support [itay]
0.4.3 / 2011-12-04
==================
* Fixed custom help ordering. Closes #32
0.4.2 / 2011-11-24
==================
* Added travis support
* Fixed: line-buffered input automatically trimmed. Closes #31
0.4.1 / 2011-11-18
==================
* Removed listening for "close" on --help
0.4.0 / 2011-11-15
==================
* Added support for `--`. Closes #24
0.3.3 / 2011-11-14
==================
* Fixed: wait for close event when writing help info [Jerry Hamlet]
0.3.2 / 2011-11-01
==================
* Fixed long flag definitions with values [felixge]
0.3.1 / 2011-10-31
==================
* Changed `--version` short flag to `-V` from `-v`
* Changed `.version()` so it's configurable [felixge]
0.3.0 / 2011-10-31
==================
* Added support for long flags only. Closes #18
0.2.1 / 2011-10-24
==================
* "node": ">= 0.4.x < 0.7.0". Closes #20
0.2.0 / 2011-09-26
==================
* Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs]
0.1.0 / 2011-08-24
==================
* Added support for custom `--help` output
0.0.5 / 2011-08-18
==================
* Changed: when the user enters nothing prompt for password again
* Fixed issue with passwords beginning with numbers [NuckChorris]
0.0.4 / 2011-08-15
==================
* Fixed `Commander#args`
0.0.3 / 2011-08-15
==================
* Added default option value support
0.0.2 / 2011-08-15
==================
* Added mask support to `Command#password(str[, mask], fn)`
* Added `Command#password(str, fn)`
0.0.1 / 2010-01-03
==================
* Initial release
+22
View File
@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
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.
+351
View File
@@ -0,0 +1,351 @@
# 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://www.npmjs.org/package/commander)
[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
[API documentation](http://tj.github.com/commander.js/)
## Installation
$ npm install commander --save
## Option parsing
Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq-sauce', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbqSauce) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
```
Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.
## Coercion
```js
function range(val) {
return val.split('..').map(Number);
}
function list(val) {
return val.split(',');
}
function collect(val, memo) {
memo.push(val);
return memo;
}
function increaseVerbosity(v, total) {
return total + 1;
}
program
.version('0.1.0')
.usage('[options] <file ...>')
.option('-i, --integer <n>', 'An integer argument', parseInt)
.option('-f, --float <n>', 'A float argument', parseFloat)
.option('-r, --range <a>..<b>', 'A range', range)
.option('-l, --list <items>', 'A list', list)
.option('-o, --optional [value]', 'An optional value')
.option('-c, --collect [value]', 'A repeatable value', collect, [])
.option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
.parse(process.argv);
console.log(' int: %j', program.integer);
console.log(' float: %j', program.float);
console.log(' optional: %j', program.optional);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
console.log(' collect: %j', program.collect);
console.log(' verbosity: %j', program.verbose);
console.log(' args: %j', program.args);
```
## Regular Expression
```js
program
.version('0.1.0')
.option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
.option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
.parse(process.argv);
console.log(' size: %j', program.size);
console.log(' drink: %j', program.drink);
```
## Variadic arguments
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
append `...` to the argument name. Here is an example:
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var 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);
```
An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
to your action as demonstrated above.
## Specify the argument syntax
```js
#!/usr/bin/env node
var 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");
```
Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.
## Git-style sub-commands
```js
// file: ./examples/pm
var program = require('commander');
program
.version('0.1.0')
.command('install [name]', 'install one or more packages')
.command('search [query]', 'search with optional query')
.command('list', 'list packages installed', {isDefault: true})
.parse(process.argv);
```
When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.
The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.
Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the option from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.
If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
### `--harmony`
You can enable `--harmony` option in two ways:
* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version dont 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.
## 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:
```
$ ./examples/pizza --help
Usage: pizza [options]
An application for pizzas ordering
Options:
-h, --help output usage information
-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 [marble]
-C, --no-cheese You do not want any cheese
```
## 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 behaviours, for example
in the following executable "stuff" will not output when
`--help` is used.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var 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(' Examples:');
console.log('');
console.log(' $ custom-help --help');
console.log(' $ custom-help -h');
console.log('');
});
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:
```
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
```
## .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
var program = require('commander');
var 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
}
```
## .help(cb)
Output help information and exit immediately.
Optional callback cb allows post-processing of help text before it is displayed.
## Examples
```js
var 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){
var 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(' Examples:');
console.log();
console.log(' $ deploy exec sequential');
console.log(' $ deploy exec async');
console.log();
});
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
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
{
"name": "commander",
"version": "2.11.0",
"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"
},
"devDependencies": {
"should": "^11.2.1",
"sinon": "^2.3.5"
},
"scripts": {
"test": "make test"
},
"main": "index",
"files": [
"index.js"
],
"dependencies": {}
}
+50
View File
@@ -0,0 +1,50 @@
{
"name": "gitbook-cli",
"version": "2.3.2",
"homepage": "https://www.gitbook.com",
"description": "CLI to generate books and documentation using gitbook",
"main": "bin/gitbook.js",
"dependencies": {
"q": "1.5.0",
"lodash": "4.17.4",
"semver": "5.3.0",
"npmi": "1.0.1",
"tmp": "0.0.31",
"commander": "2.11.0",
"optimist": "0.6.1",
"fs-extra": "3.0.1",
"bash-color": "0.0.4",
"npm": "5.1.0",
"user-home": "2.0.0"
},
"devDependencies": {
"mocha": "3.4.2",
"should": "11.2.1",
"gitbook": "2.5.0-beta.1"
},
"scripts": {
"test": "mocha --reporter spec --recursive --bail"
},
"repository": {
"type": "git",
"url": "https://github.com/GitbookIO/gitbook-cli.git"
},
"author": "FriendCode Inc. <contact@gitbook.com>",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/GitbookIO/gitbook-cli/issues"
},
"bin": {
"gitbook": "./bin/gitbook.js"
},
"contributors": [
{
"name": "Aaron O'Mullan",
"email": "aaron@gitbook.com"
},
{
"name": "Samy Pessé",
"email": "samy@gitbook.com"
}
]
}
+11
View File
@@ -0,0 +1,11 @@
var path = require('path');
var fs = require('fs-extra');
var manager = require('../lib');
// Use tmp folder for testing
before(function() {
var gitbookFolder = path.resolve(__dirname, '../.tmp');
fs.removeSync(gitbookFolder);
manager.setRoot(gitbookFolder);
manager.init();
});
+3
View File
@@ -0,0 +1,3 @@
{
"gitbook": "3.0.0-pre.2"
}
+38
View File
@@ -0,0 +1,38 @@
var should = require('should');
var tags = require('../lib/tags');
describe('Tags', function() {
describe('.isValid()', function() {
it('should return true for version >= 2.0.0', function() {
tags.isValid('2.0.0').should.be.ok()
});
it('should return true for pre-releases', function() {
tags.isValid('2.0.0-beta.0').should.be.ok()
});
});
describe('.satisfies()', function() {
it('should return true for tag and *', function() {
tags.satisfies('pre', '*').should.be.ok()
});
});
describe('.sort()', function() {
it('should sort tags first', function() {
tags.sort('pre', '1.0.0').should.equal(-1);
tags.sort('beta', '1.0.0').should.equal(-1);
tags.sort('alpha', '1.0.0').should.equal(-1);
});
it('should sort tags correctly', function() {
tags.sort('alpha', 'pre').should.equal(-1);
tags.sort('alpha', 'beta').should.equal(-1);
});
it('should sort pre versions first', function() {
tags.sort('1.0.0-pre.1', '0.0.9').should.equal(-1);
tags.sort('1.0.0-pre.1', '1.0.0').should.equal(1);
});
});
});
+133
View File
@@ -0,0 +1,133 @@
var path = require('path');
var should = require('should');
var manager = require('../lib');
describe('Versions', function() {
this.timeout(100000);
describe('.available()', function() {
var result;
before(function() {
return manager.available()
.then(function(versions) {
result = versions;
});
});
it('should correctly return a list of versions', function() {
result.should.have.properties('versions');
result.versions.should.be.an.Array();
});
it('should correctly return a map of tags', function() {
result.should.have.properties('tags');
result.tags.should.have.properties('latest');
});
});
describe('.install()', function() {
var result;
before(function() {
return manager.install('2.0.0')
.then(function(version) {
result = version;
});
});
it('should correctly return the installed version', function() {
result.should.be.a.String();
result.should.equal('2.0.0');
});
});
describe('.ensure()', function() {
it('should correctly return installed version', function() {
return manager.ensure(__dirname)
.then(function(v) {
v.should.have.properties('version', 'path');
v.version.should.equal('2.0.0');
});
});
it('should correctly install version specified', function() {
return manager.ensure(path.resolve(__dirname, 'fixtures/book1'))
.then(function(v) {
v.should.have.properties('version', 'path');
v.version.should.equal('3.0.0-pre.2');
});
});
});
describe('.list()', function() {
var result;
before(function() {
result = manager.versions();
});
it('should correctly return the installed version', function() {
result.should.be.an.Array();
result.should.have.lengthOf(2);
result[0].should.have.properties('name', 'tag', 'version', 'path');
result[0].version.should.equal('3.0.0-pre.2');
result[1].should.have.properties('name', 'tag', 'version', 'path');
result[1].version.should.equal('2.0.0');
});
});
describe('.link()', function() {
var localGitbook = path.resolve(__dirname, '../node_modules/gitbook');
before(function() {
return manager.link('latest', localGitbook);
});
it('should correctly list latest version', function() {
var result = manager.versions();
result.should.have.lengthOf(3);
result[1].should.have.properties('version', 'path');
result[1].tag.should.equal('beta');
result[1].name.should.equal('latest');
result[1].link.should.equal(localGitbook);
});
it('should correctly return latest version as default one', function() {
return manager.get(__dirname)
.then(function(version) {
version.name.should.equal('latest');
});
});
});
describe('.ensureAndLoad()', function() {
it('should correctly return gitbook instance', function() {
return manager.ensureAndLoad(__dirname)
.then(function(gitbook) {
gitbook.should.be.an.Object();
gitbook.should.have.properties('commands');
gitbook.commands.should.be.an.Array();
});
});
});
describe('.uninstall()', function() {
it('should correctly remove a specific version', function() {
return manager.uninstall('2.0.0')
.then(function() {
var result = manager.versions();
result.should.have.lengthOf(2);
});
});
it('should correctly remove a version by tag', function() {
return manager.uninstall('latest')
.then(function() {
var result = manager.versions();
result.should.have.lengthOf(1);
});
});
});
});