-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
90 lines (77 loc) · 1.81 KB
/
cli.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// https://github.com/js2coffee/js2coffee/blob/master/lib/cli.js
/**
* cli:
* minimal command-line helper on top of minimist.
*
* var args = require('../lib/cli')
* .helpfile(__dirname+'/../help.txt')
* .version(require('../package.json').version)
* .args({
* alias: { h: 'help', v: 'version' }
* });
*
* // $ myapp --help
* // $ myapp --version
*/
var cli = (module.exports = {});
var fs = require('fs');
/**
* cmd() : cli.cmd()
* Returns the command name.
*/
cli.cmd = function() {
return require('path').basename(process.argv[1]);
};
/**
* help() : cli.help([help])
* Sets or prints the help text. If `help` is given, sets the help text to that.
* If no arguments are given, the help text is printed.
*/
cli.help = function(str) {
if (str) {
cli._help = str;
return this;
} else {
process.stdout.write((cli._help || '').replace(/\$0/g, cli.cmd()));
return this;
}
};
cli.helpfile = function(fname) {
cli._help = fs.readFileSync(fname, 'utf-8');
return this;
};
/**
* version() : cli.version([ver])
* Sets or prints the version. If `ver` is given, the version is set; if no
* arguments are given, the version is printed.
*/
cli.version = function(ver) {
if (ver) cli._version = ver;
else console.log(cli._version);
return this;
};
/**
* minimist() : cli.minimist({ ... })
* Parses arguments using minimist.
*/
cli.minimist = function(options) {
cli._parseArgs(options);
cli._run();
return cli._args;
};
cli._parseArgs = function(options) {
if (!cli._args)
cli._args = require('minimist')(process.argv.slice(2), options || {});
return cli;
};
cli._run = function() {
var args = this._args;
if (args.help) {
cli.help();
process.exit();
}
if (args.version) {
cli.version();
process.exit();
}
};