-
Notifications
You must be signed in to change notification settings - Fork 344
Expand file tree
/
Copy pathcli.js
More file actions
362 lines (317 loc) · 12.6 KB
/
cli.js
File metadata and controls
362 lines (317 loc) · 12.6 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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
const nopt = require('nopt');
const pkg = require('../package.json');
const help = require('./help');
const info = require('./info');
const cordova_lib = require('cordova-lib');
const CordovaError = cordova_lib.CordovaError;
const cordova = cordova_lib.cordova;
const events = cordova_lib.events;
const logger = require('cordova-common').CordovaLogger.get();
const cordovaCreate = require('cordova-create');
const Configstore = require('configstore');
const conf = new Configstore(pkg.name + '-config');
const editor = require('editor');
const semver = require('semver');
// process.version is not declared writable or has no setter so storing in const for Jasmine.
const NODE_VERSION = process.version;
// When there is no node version in the deprecation stage, set to null or false.
const NODE_VERSION_REQUIREMENT = false;
const NODE_VERSION_DEPRECATING_RANGE = '<10';
const knownOpts = {
verbose: Boolean,
version: Boolean,
help: Boolean,
silent: Boolean,
experimental: Boolean,
noregistry: Boolean,
nohooks: Array,
shrinkwrap: Boolean,
searchpath: String,
variable: Array,
link: Boolean,
force: Boolean,
'save-exact': Boolean,
// Flags to be passed to `cordova build/run/emulate`
debug: Boolean,
release: Boolean,
archs: String,
device: Boolean,
emulator: Boolean,
target: String,
noprepare: Boolean,
nobuild: Boolean,
list: Boolean,
buildConfig: String,
template: String,
production: Boolean,
noprod: Boolean
};
const shortHands = {
d: '--verbose',
v: '--version',
h: '--help',
t: '--template'
};
module.exports = function (inputArgs) {
// If no inputArgs given, use process.argv.
inputArgs = inputArgs || process.argv;
let cmd = inputArgs[2]; // e.g: inputArgs= 'node cordova run ios'
const isConfigCmd = (cmd === 'config');
// ToDO: Move nopt-based parsing of args up here
if (cmd === '--version' || cmd === '-v') {
cmd = 'version';
} else if (!cmd || cmd === '--help' || cmd === 'h') {
cmd = 'help';
}
// If "get" is called
if (isConfigCmd && inputArgs[3] === 'get') {
if (inputArgs[4]) {
logger.subscribe(events);
conf.get(inputArgs[4]);
if (conf.get(inputArgs[4]) !== undefined) {
events.emit('log', conf.get(inputArgs[4]).toString());
} else {
events.emit('log', 'undefined');
}
}
}
// If "set" is called
if (isConfigCmd && inputArgs[3] === 'set') {
if (inputArgs[5] === undefined) {
conf.set(inputArgs[4], true);
}
if (inputArgs[5]) {
conf.set(inputArgs[4], inputArgs[5]);
}
}
// If "delete" is called
if (isConfigCmd && inputArgs[3] === 'delete') {
if (inputArgs[4]) {
conf.delete(inputArgs[4]);
}
}
// If "edit" is called
if (isConfigCmd && inputArgs[3] === 'edit') {
editor(conf.path, function (code, sig) {
logger.warn('Finished editing with code ' + code);
});
}
// If "ls" is called
if (isConfigCmd && (inputArgs[3] === 'ls' || inputArgs[3] === 'list')) {
logger.results(JSON.stringify(conf.all, null, 4));
}
return Promise.resolve().then(function () {
return cli(inputArgs);
});
};
function printHelp (command) {
const result = help([command]);
cordova.emit('results', result);
return result;
}
function cli (inputArgs) {
const args = nopt(knownOpts, shortHands, inputArgs);
process.on('uncaughtException', function (err) {
if (err.message) {
logger.error(err.message);
} else {
logger.error(err);
}
process.exit(1);
});
process.on('unhandledRejection', function (reason) {
const msg = reason instanceof Error ? reason.message : String(reason);
logger.error(msg);
if (reason instanceof Error) {
events.emit('verbose', reason.stack);
}
process.exit(1);
});
logger.subscribe(events);
if (args.silent) {
logger.setLevel('error');
} else if (args.verbose) { // can't be both silent AND verbose, silent wins
logger.setLevel('verbose');
}
const cliVersion = pkg.version;
const usingPrerelease = !!semver.prerelease(cliVersion);
if (args.version || usingPrerelease) {
const libVersion = require('cordova-lib/package').version;
let toPrint = cliVersion;
if (cliVersion !== libVersion || usingPrerelease) {
toPrint += ' (cordova-lib@' + libVersion + ')';
}
if (args.version) {
logger.results(toPrint);
return Promise.resolve(); // Important! this will return and cease execution
} else { // must be usingPrerelease
// Show a warning and continue
logger.warn('Warning: using prerelease version ' + toPrint);
}
}
let warningPartial = null;
// If the Node.js versions does not meet our requirements or in a deprecation stage, display a warning.
if (
NODE_VERSION_REQUIREMENT &&
!semver.satisfies(NODE_VERSION, NODE_VERSION_REQUIREMENT)
) {
warningPartial = 'is no longer supported';
} else if (
NODE_VERSION_DEPRECATING_RANGE &&
semver.satisfies(NODE_VERSION, NODE_VERSION_DEPRECATING_RANGE)
) {
warningPartial = 'has been deprecated';
}
if (warningPartial) {
const upgradeMsg = 'Please upgrade to the latest Node.js version available (LTS version recommended).';
logger.warn(`Warning: Node.js ${NODE_VERSION} ${warningPartial}. ${upgradeMsg}`);
}
// If there were arguments protected from nopt with a double dash, keep
// them in unparsedArgs. For example:
// cordova build ios -- --verbose --whatever
// In this case "--verbose" is not parsed by nopt and args.vergbose will be
// false, the unparsed args after -- are kept in unparsedArgs and can be
// passed downstream to some scripts invoked by Cordova.
let unparsedArgs = [];
const parseStopperIdx = args.argv.original.indexOf('--');
if (parseStopperIdx !== -1) {
unparsedArgs = args.argv.original.slice(parseStopperIdx + 1);
}
// args.argv.remain contains both the undashed args (like platform names)
// and whatever unparsed args that were protected by " -- ".
// "undashed" stores only the undashed args without those after " -- " .
const remain = args.argv.remain;
const undashed = remain.slice(0, remain.length - unparsedArgs.length);
const cmd = undashed[0];
let subcommand;
if (!cmd || cmd === 'help' || args.help) {
if (!args.help && remain[0] === 'help') {
remain.shift();
}
return printHelp(remain);
}
if (cmd === 'info') return info();
// Don't need to do anything with cordova-lib since config was handled above
if (cmd === 'config') return true;
if (cmd === 'create') {
const [, dest, id, name] = undashed;
return cordovaCreate(dest, { id, name, events, template: args.template });
}
if (!Object.prototype.hasOwnProperty.call(cordova, cmd)) {
const msg2 = 'Cordova does not know ' + cmd + '; try `' + cordova_lib.binname +
' help` for a list of all the available commands.';
throw new CordovaError(msg2);
}
const opts = {
platforms: [],
options: [],
verbose: args.verbose || false,
silent: args.silent || false,
nohooks: args.nohooks || [],
searchpath: args.searchpath
};
const platformCommands = ['emulate', 'build', 'prepare', 'compile', 'run', 'clean'];
if (platformCommands.indexOf(cmd) !== -1) {
// All options without dashes are assumed to be platform names
opts.platforms = undashed.slice(1);
// Pass nopt-parsed args to PlatformApi through opts.options
opts.options = args;
opts.options.argv = unparsedArgs;
return cordova[cmd].call(null, opts);
} else if (cmd === 'requirements') {
// All options without dashes are assumed to be platform names
opts.platforms = undashed.slice(1);
return cordova[cmd].call(null, opts.platforms)
.then(function (platformChecks) {
const someChecksFailed = Object.keys(platformChecks).map(function (platformName) {
events.emit('log', '\nRequirements check results for ' + platformName + ':');
const platformCheck = platformChecks[platformName];
if (platformCheck instanceof CordovaError) {
events.emit('warn', 'Check failed for ' + platformName + ' due to ' + platformCheck);
return true;
}
let someChecksFailed = false;
// platformCheck is expected to be an array of conditions that must be met
// the browser platform currently returns nothing, which was breaking here.
if (platformCheck && platformCheck.forEach) {
platformCheck.forEach(function (checkItem) {
const checkSummary = checkItem.name + ': ' +
(checkItem.installed ? 'installed ' : 'not installed ') +
(checkItem.installed ? checkItem.metadata.version.version || checkItem.metadata.version : '');
events.emit('log', checkSummary);
if (!checkItem.installed) {
someChecksFailed = true;
events.emit('warn', checkItem.metadata.reason);
}
});
}
return someChecksFailed;
}).some(function (isCheckFailedForPlatform) {
return isCheckFailedForPlatform;
});
if (someChecksFailed) {
throw new CordovaError('Some of requirements check failed');
}
});
} else if (cmd === 'serve') {
const port = undashed[1];
return cordova.serve(port);
} else {
// platform/plugins add/rm [target(s)]
subcommand = undashed[1]; // sub-command like "add", "ls", "rm" etc.
const targets = undashed.slice(2); // array of targets, either platforms or plugins
const cli_vars = {};
if (args.variable) {
args.variable.forEach(function (strVar) {
// CB-9171
const keyVal = strVar.split('=');
if (keyVal.length < 2) {
throw new CordovaError('invalid variable format: ' + strVar);
} else {
const key = keyVal.shift().toUpperCase();
const val = keyVal.join('=');
cli_vars[key] = val;
}
});
}
args.save = !args.nosave;
args.production = !args.noprod;
if (args.searchpath === undefined) {
// User explicitly did not pass in searchpath
args.searchpath = conf.get('searchpath');
}
if (args['save-exact'] === undefined) {
// User explicitly did not pass in save-exact
args['save-exact'] = conf.get('save-exact');
}
const download_opts = {
searchpath: args.searchpath,
noregistry: args.noregistry,
nohooks: args.nohooks,
cli_variables: cli_vars,
link: args.link || false,
save: args.save,
save_exact: args['save-exact'] || false,
shrinkwrap: args.shrinkwrap || false,
force: args.force || false,
production: args.production
};
return cordova[cmd](subcommand, targets, download_opts);
}
}