-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusage.js
More file actions
75 lines (72 loc) · 2.08 KB
/
usage.js
File metadata and controls
75 lines (72 loc) · 2.08 KB
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
const {basename} = require('path');
/**
* Formats a usage string from parsed options.
*/
module.exports = function usage({optDesc, error, command}) {
let {arg0} = optDesc;
console.assert(arg0);
let s = '';
if (error === true) {
// parsing needed to show usage without an error
} else if (error) {
if (!error.startsWith('error:')) s += 'error: ';
s += error + '\n';
}
s += `usage: ${basename(arg0)}`;
if (command) {
optDesc = command.optDesc;
s += " " + command.name;
}
let hasOptions = Object.keys(optDesc.options).length > 0;
if (hasOptions) s += " [options]";
let positionalSynopsis = '';
for (let {name, rest, required, synopsis} of optDesc.positional) {
name = camelToKebabCase(name);
if (rest) name += '...';
if (!required) name = "[" + name + "]";
s += " " + name;
if (synopsis) {
positionalSynopsis += ` ${name} ${synopsis}\n`;
}
}
s += "\n\n";
if (optDesc.synopsis) {
s += optDesc.synopsis + "\n\n";
}
if (positionalSynopsis) {
s += `args:\n${positionalSynopsis}\n\n`;
}
if (hasOptions) {
s += "options:\n";
for (let [key, {name, alias, hasArg, synopsis}] of Object.entries(optDesc.options)) {
if (key !== name) continue;
name = camelToKebabCase(name);
s += ' ';
if (alias) {
alias = camelToKebabCase(alias);
if (alias.length > name.length) [alias, name] = [name, alias];
if (alias.length > 1) alias = '-' + alias;
s += `-${alias}, `;
}
if (name.length > 1) name = '-' + name;
s += `-${name}${hasArg?'=<value>':''}`;
if (synopsis) s += ` ${synopsis}`;
s += '\n';
}
s += "\n";
}
if (optDesc.commands) {
s += "commands:\n";
for (let {name, optDesc: commandOptDesc} of Object.values(optDesc.commands)) {
s += ` ${name}`;
if (commandOptDesc.synopsis) s += ` ${commandOptDesc.synopsis}`;
s += '\n';
}
s += "\n";
}
return s;
}
function camelToKebabCase(str) {
if (!str || str.length < 3) return str;
return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}