UNPKG

1.98 kBJavaScriptView Raw
1var _ = require('lodash');
2
3// Helper function for print help
4// indented output by spaces
5function 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// Print help for a list of commands
19// It prints the command and its description, then all the options
20function 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// Execute a command from a list
42// with a specific set of args/kwargs
43function exec(commands, command, args, kwargs) {
44 var cmd = _.find(commands, function(_cmd) {
45 return _.first(_cmd.name.split(" ")) == command;
46 });
47
48 // Command not found
49 if (!cmd) throw new Error('Command '+command+' doesn\'t exist, run "gitbook help" to list commands.');
50
51 // Apply defaults
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
62module.exports = {
63 help: help,
64 exec: exec
65};