-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcmdline.js
289 lines (254 loc) · 8.7 KB
/
cmdline.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
'use strict';
const path = require('path'),
dashdash = require('dashdash');
module.exports = { parseCommandLine };
const globalOpts = [
{
names: ['unwrap-prop', 'u'],
abbr: 'u',
helpArg: 'KEY',
type: 'string',
help: 'Operate only against the given property of the loaded data.'
},
{
names: ['auto-unwrap', 'a'],
type: 'bool',
help: 'Attempt to intelligently extract a useful property of the loaded data to run against. Specify --no-auto-unwrap to turn off auto-unwrapping even if it is enabled in your config file.'
},
{
name: 'no-auto-unwrap',
hidden: true,
type: 'bool'
},
{
names: ['config-file', 'c'],
helpArg: 'FILE',
help: 'Load the given config file. The default is the JUTIL_CONFIG_PATH environmental variable or ~/.jutil/config. Specify --no-config-file to use the default configuration.',
type: 'string'
},
{
name: 'no-config-file',
hidden: true,
type: 'bool'
},
{
names: ['verbose', 'v'],
type: 'bool',
help: 'Be verbose about things (e.g. module loading).'
},
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
}
];
const fileOpts = [
{
names: ['file', 'f'],
helpArg: 'FILE',
help: 'Load data from the given file instead of reading from stdin.',
type: 'string'
}
];
dashdash.addOptionType({
name: 'colorOptions',
takesArg: true,
helpArg: 'OPTION',
parseArg(option, optStr, arg) {
const validOptions = ['off', 'force', 'auto', 'auto+pager'];
if(validOptions.indexOf(arg) == -1) {
throw new Error('argument for ' + optStr + ' is not valid');
}
return arg;
}
});
const objectOutputOpts = [
{
names: ['pretty-print', 'p'],
type: 'bool',
help: 'Pretty-print the output. Specify --no-pretty-print or -P to disable pretty printing even if it is enabled by your config file or smart output.'
},
{
names: ["no-pretty-print", "P"],
hidden: true,
type: 'bool'
},
{
names: ['sort-keys', 's'],
type: 'bool',
help: 'Sort keys in the output. Specify --no-sort-keys to disable key sorting even if it is enabled in your config file.'
},
{
name: 'no-sort-keys',
hidden: true,
type: 'bool'
},
{
name: 'color',
type: 'colorOptions',
help: 'JSON colorizing options. Specify "off" to never colorize, "force" to always colorize, "auto" to colorize when printing to a TTY, or "auto+pager" to colorize when printing to a TTY or the pager.'
}
];
const smartOutputOpts = [
{
names: ['disable-smart', 'S'],
type: 'bool',
help: 'Don\'t pretty-print or autopage even if stdout is a terminal. Specify --no-disable-smart to enable smart output even if it is disabled in your config file.'
},
{
name: 'no-disable-smart',
hidden: true,
type: 'bool'
},
{
// This is for testing purposes where stdout isn't a TTY but we want to do smart stuff anyway
name: 'force-smart',
hidden: true,
type: 'bool'
}
];
const sandboxOpts = [
{
names: ['module-dir', 'M'],
helpArg: 'DIR',
type: 'arrayOfString',
help: 'Add the given directory as a module path. Any .js files in the directory will be loaded before executing. Specify --no-module-dir to disable directory loading even if it is enabled in your config file.'
},
{
name: 'no-module-dir',
hidden: true,
type: 'bool'
},
{
names: ['module', 'm'],
helpArg: 'FILE',
type: 'arrayOfString',
help: 'Load the given JavaScript file before executing. You may repeat this option.'
}
];
const withClauseOpts = [
{
names: ['disable-with', 'W'],
type: 'bool',
help: 'Don\'t wrap the script to execute in a "with" clause. Specify --no-disable-with to enable a "with" clause even if it is disabled in your config file.'
},
{
name: 'no-disable-with',
hidden: true,
type: 'bool'
}
];
function parseCommandLine(commandFactories, runCommand)
{
let { args, subcommand } = getArgsAndSubcommand(commandFactories),
commandDesc = commandFactories[subcommand]();
assembleCommandOptions(commandDesc);
let parser = dashdash.createParser({ options: commandDesc.options }),
opts;
try {
opts = parser.parse(args, 0); // 0 is the index in the array at which to start parsing. It defaults to 2, but we already removed stuff at the front.
}
catch(exc) {
console.error('Error: ' + exc.message + '\n');
showHelp(subcommand, commandDesc, parser);
process.exit(1);
}
if(opts.help) {
showHelp(subcommand, commandDesc, parser);
process.exit(0);
}
let minPositionalArguments = commandDesc.minPositionalArguments || 0,
maxPositionalArguments = commandDesc.maxPositionalArguments || 0;
// Special case min specified but not max to mean "at least min, but an unlimited max"
if(minPositionalArguments > 0 && maxPositionalArguments === 0) {
maxPositionalArguments = Number.MAX_SAFE_INTEGER;
}
try {
if(opts._args.length < minPositionalArguments) {
throw new Error('Expected at least ' + minPositionalArguments + ' argument(s), but got ' + opts._args.length);
}
else if(opts._args.length > maxPositionalArguments) {
throw new Error('Expected at most ' + maxPositionalArguments + ' argument(s), but got ' + opts._args.length);
}
}
catch(exc) {
console.error('Error: ' + exc.message + '\n');
showHelp(subcommand, commandDesc, parser);
process.exit(1);
}
runCommand(commandDesc, opts);
}
function getArgsAndSubcommand(commandFactories)
{
let defaultCommand = 'script',
args = process.argv.slice(2), // remove 'node' and script name
scriptName = path.basename(process.argv[1], '.js'),
firstArg = args[0],
subcommand;
// If we weren't invoked as 'jutil', we were called 'j<command name>',
// which we massage into the first argument.
/* istanbul ignore else */
if(scriptName != 'jutil') {
subcommand = scriptName.substr(1);
}
else if(!firstArg || !commandFactories.hasOwnProperty(firstArg))
{
// Otherwise, add in the default command 'script', if appropriate:
// no first arg -> default
// first arg is not a command name -> default
subcommand = defaultCommand;
}
else {
// This will never happen unless we're run as "jutil.js <something-not-real>", which
// won't happen after being installed with npm.
subcommand = args.shift();
}
return { args, subcommand };
}
function assembleCommandOptions(commandDesc)
{
// Gather all the options for this command into commandDesc.options
if(commandDesc.options === undefined) {
commandDesc.options = [];
}
else {
commandDesc.options.unshift({ group: 'Tool Options' });
}
commandDesc.options.push({ group: 'General Options' });
pushAll(globalOpts, commandDesc.options);
// This one is on by default, so consider omission to be truthy
if(commandDesc.hasFileOption === undefined || commandDesc.hasFileOption) {
pushAll(fileOpts, commandDesc.options);
}
if(commandDesc.outputsObject || commandDesc.hasSmartOutput) {
commandDesc.options.push({ group: 'Output Options' });
}
if(commandDesc.outputsObject) {
commandDesc.hasSmartOutput = true; // outputsObject implies hasSmartOutput
pushAll(objectOutputOpts, commandDesc.options);
}
if(commandDesc.hasSmartOutput) {
pushAll(smartOutputOpts, commandDesc.options);
}
if(commandDesc.needsSandbox || commandDesc.hasWithClauseOpt) {
commandDesc.options.push({ group: 'Sandbox Options' });
}
if(commandDesc.needsSandbox) {
pushAll(sandboxOpts, commandDesc.options);
}
if(commandDesc.hasWithClauseOpt) {
pushAll(withClauseOpts, commandDesc.options);
}
}
function showHelp(subcommand, commandDesc, parser)
{
/* istanbul ignore next */
let width = process.stdout.isTTY ? process.stdout.getWindowSize()[0] : 80,
optionsHelp = parser.help({ maxCol: width, indent: 2, headingIndent: 0 }),
helpString = 'Usage: jutil ' + subcommand + ' [options] ' + commandDesc.usageString + '\n\n' + commandDesc.help + '\n\n' + optionsHelp;
process.stderr.write(helpString);
}
function pushAll(values, dest)
{
dest.push.apply(dest, values);
}