1 | var _ = require('lodash');
|
2 |
|
3 |
|
4 |
|
5 | function indent_output(n, name, description) {
|
6 | if (!n) {
|
7 | n = 0;
|
8 | }
|
9 |
|
10 | console.log(
|
11 | _.repeat(' ', n)
|
12 | + name
|
13 | + _.repeat(' ', 32 - n * 4 - name.length)
|
14 | + description
|
15 | );
|
16 | }
|
17 |
|
18 |
|
19 |
|
20 | function help(commands) {
|
21 | _.each(commands, function(command) {
|
22 | indent_output(1, command.name, command.description);
|
23 | _.each(command.options || [], function(option) {
|
24 | var after = [];
|
25 |
|
26 | if (option.defaults !== undefined) after.push("Default is "+option.defaults);
|
27 | if (option.values) after.push("Values are "+option.values.join(", "));
|
28 |
|
29 | if (after.length > 0) after = "("+after.join("; ")+")";
|
30 | else after = "";
|
31 |
|
32 | var optname = '--';
|
33 | if (typeof option.defaults === 'boolean') optname += '[no-]';
|
34 | optname += option.name;
|
35 | indent_output(2, optname, option.description + ' ' + after);
|
36 | });
|
37 | console.log('');
|
38 | });
|
39 | }
|
40 |
|
41 |
|
42 |
|
43 | function exec(commands, command, args, kwargs) {
|
44 | var cmd = _.find(commands, function(_cmd) {
|
45 | return _.first(_cmd.name.split(" ")) == command;
|
46 | });
|
47 |
|
48 |
|
49 | if (!cmd) throw new Error('Command '+command+' doesn\'t exist, run "gitbook help" to list commands.');
|
50 |
|
51 |
|
52 | _.each(cmd.options || [], function(option) {
|
53 | kwargs[option.name] = (kwargs[option.name] === undefined)? option.defaults : kwargs[option.name];
|
54 | if (option.values && !_.includes(option.values, kwargs[option.name])) {
|
55 | throw new Error('Invalid value for option "'+option.name+'"');
|
56 | }
|
57 | });
|
58 |
|
59 | return cmd.exec(args, kwargs);
|
60 | }
|
61 |
|
62 | module.exports = {
|
63 | help: help,
|
64 | exec: exec
|
65 | };
|