UNPKG

1.77 kBJavaScriptView Raw
1/*
2 * Command helper in terminal
3 * @author: Hsiaoming Yang <lepture@me.com>
4 *
5 */
6
7var color = require('./color')
8
9
10function Command(name, executable, description) {
11 if (!(this instanceof Command)) {
12 return new Command(name, executable, description)
13 }
14 if (typeof name === 'object') {
15 var obj = name
16 this.name = obj.name
17 this.executable = obj.executable || obj.name
18 this.description = obj.description
19 this.version = obj.version
20 this.group = obj.group
21 this.color = obj.color
22 return this
23 }
24
25 this.name = name
26 if (!description) {
27 description = executable
28 executable = name
29 }
30 this.executable = executable
31 this.description = description
32 this.version = undefined
33 this.group = undefined
34 this.color = undefined
35 return this
36}
37
38Command.prototype.executable = function(executable) {
39 this.executable = executable
40}
41
42Command.prototype.description = function(description) {
43 this.description = description
44}
45
46exports.Command = Command
47
48exports.printHelp = function(cmd) {
49 var colorfunc = null
50 if (typeof cmd.color === 'string') {
51 colorfunc = color[cmd.color]
52 } else if (typeof cmd.color === 'function') {
53 colorfunc = cmd.color
54 }
55 var name = cmd.name
56 if (colorfunc) {
57 var name = colorfunc(name)
58 }
59 var text = ' ' + pad(name, 15, cmd.name.length)
60 if (cmd.description.length > 60) {
61 text += cmd.description.slice(0, 58)
62 if (cmd.description.slice(58, 59) !== ' ') {
63 text += '-'
64 }
65 text += '\n'
66 text += Array(21).join(' ')
67 text += cmd.description.slice(58)
68 } else {
69 text += cmd.description
70 }
71 console.log(text)
72}
73
74function pad(str, width, strWidth) {
75 var len = Math.max(0, width - (strWidth || str.length))
76 return str + Array(len + 1).join(' ')
77}