Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

cli.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /**
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. var nopt = require('nopt');
  18. var updateNotifier = require('update-notifier');
  19. var pkg = require('../package.json');
  20. var telemetry = require('./telemetry');
  21. var help = require('./help');
  22. const info = require('./info');
  23. var cordova_lib = require('cordova-lib');
  24. var CordovaError = cordova_lib.CordovaError;
  25. var cordova = cordova_lib.cordova;
  26. var events = cordova_lib.events;
  27. var logger = require('cordova-common').CordovaLogger.get();
  28. var cordovaCreate = require('cordova-create');
  29. var Configstore = require('configstore');
  30. var conf = new Configstore(pkg.name + '-config');
  31. var editor = require('editor');
  32. const semver = require('semver');
  33. // process.version is not declared writable or has no setter so storing in const for Jasmine.
  34. const NODE_VERSION = process.version;
  35. // When there is no node version in the deprecation stage, set to null or false.
  36. const NODE_VERSION_REQUIREMENT = false;
  37. const NODE_VERSION_DEPRECATING_RANGE = '<10';
  38. var knownOpts = {
  39. verbose: Boolean,
  40. version: Boolean,
  41. help: Boolean,
  42. silent: Boolean,
  43. experimental: Boolean,
  44. noregistry: Boolean,
  45. nohooks: Array,
  46. shrinkwrap: Boolean,
  47. searchpath: String,
  48. variable: Array,
  49. link: Boolean,
  50. force: Boolean,
  51. 'save-exact': Boolean,
  52. // Flags to be passed to `cordova build/run/emulate`
  53. debug: Boolean,
  54. release: Boolean,
  55. archs: String,
  56. device: Boolean,
  57. emulator: Boolean,
  58. target: String,
  59. noprepare: Boolean,
  60. nobuild: Boolean,
  61. list: Boolean,
  62. buildConfig: String,
  63. template: String,
  64. production: Boolean,
  65. noprod: Boolean
  66. };
  67. var shortHands = {
  68. d: '--verbose',
  69. v: '--version',
  70. h: '--help',
  71. t: '--template'
  72. };
  73. function checkForUpdates () {
  74. try {
  75. // Checks for available update and returns an instance
  76. var notifier = updateNotifier({ pkg: pkg });
  77. if (notifier.update &&
  78. notifier.update.latest !== pkg.version) {
  79. // Notify using the built-in convenience method
  80. notifier.notify();
  81. }
  82. } catch (e) {
  83. // https://issues.apache.org/jira/browse/CB-10062
  84. if (e && e.message && /EACCES/.test(e.message)) {
  85. console.log('Update notifier was not able to access the config file.\n' +
  86. 'You may grant permissions to the file: \'sudo chmod 744 ~/.config/configstore/update-notifier-cordova.json\'');
  87. } else {
  88. throw e;
  89. }
  90. }
  91. }
  92. var shouldCollectTelemetry = false;
  93. module.exports = function (inputArgs) {
  94. // If no inputArgs given, use process.argv.
  95. inputArgs = inputArgs || process.argv;
  96. var cmd = inputArgs[2]; // e.g: inputArgs= 'node cordova run ios'
  97. var subcommand = getSubCommand(inputArgs, cmd);
  98. var isTelemetryCmd = (cmd === 'telemetry');
  99. var isConfigCmd = (cmd === 'config');
  100. // ToDO: Move nopt-based parsing of args up here
  101. if (cmd === '--version' || cmd === '-v') {
  102. cmd = 'version';
  103. } else if (!cmd || cmd === '--help' || cmd === 'h') {
  104. cmd = 'help';
  105. }
  106. // If "get" is called
  107. if (isConfigCmd && inputArgs[3] === 'get') {
  108. if (inputArgs[4]) {
  109. logger.subscribe(events);
  110. conf.get(inputArgs[4]);
  111. if (conf.get(inputArgs[4]) !== undefined) {
  112. events.emit('log', conf.get(inputArgs[4]).toString());
  113. } else {
  114. events.emit('log', 'undefined');
  115. }
  116. }
  117. }
  118. // If "set" is called
  119. if (isConfigCmd && inputArgs[3] === 'set') {
  120. if (inputArgs[5] === undefined) {
  121. conf.set(inputArgs[4], true);
  122. }
  123. if (inputArgs[5]) {
  124. conf.set(inputArgs[4], inputArgs[5]);
  125. }
  126. }
  127. // If "delete" is called
  128. if (isConfigCmd && inputArgs[3] === 'delete') {
  129. if (inputArgs[4]) {
  130. conf.del(inputArgs[4]);
  131. }
  132. }
  133. // If "edit" is called
  134. if (isConfigCmd && inputArgs[3] === 'edit') {
  135. editor(conf.path, function (code, sig) {
  136. logger.warn('Finished editing with code ' + code);
  137. });
  138. }
  139. // If "ls" is called
  140. if (isConfigCmd && (inputArgs[3] === 'ls' || inputArgs[3] === 'list')) {
  141. logger.results(JSON.stringify(conf.all, null, 4));
  142. }
  143. return Promise.resolve().then(function () {
  144. /**
  145. * Skip telemetry prompt if:
  146. * - CI environment variable is present
  147. * - Command is run with `--no-telemetry` flag
  148. * - Command ran is: `cordova telemetry on | off | ...`
  149. */
  150. if (telemetry.isCI(process.env) || telemetry.isNoTelemetryFlag(inputArgs)) {
  151. return Promise.resolve(false);
  152. }
  153. /**
  154. * We shouldn't prompt for telemetry if user issues a command of the form: `cordova telemetry on | off | ...x`
  155. * Also, if the user has already been prompted and made a decision, use his saved answer
  156. */
  157. if (isTelemetryCmd) {
  158. var isOptedIn = telemetry.isOptedIn();
  159. return handleTelemetryCmd(subcommand, isOptedIn);
  160. }
  161. if (telemetry.hasUserOptedInOrOut()) {
  162. return Promise.resolve(telemetry.isOptedIn());
  163. }
  164. /**
  165. * Otherwise, prompt user to opt-in or out
  166. * Note: the prompt is shown for 30 seconds. If no choice is made by that time, User is considered to have opted out.
  167. */
  168. return telemetry.showPrompt();
  169. }).then(function (collectTelemetry) {
  170. shouldCollectTelemetry = collectTelemetry;
  171. if (isTelemetryCmd) {
  172. return Promise.resolve();
  173. }
  174. return cli(inputArgs);
  175. }).then(function () {
  176. if (shouldCollectTelemetry && !isTelemetryCmd) {
  177. telemetry.track(cmd, subcommand, 'successful');
  178. }
  179. }).catch(function (err) {
  180. if (shouldCollectTelemetry && !isTelemetryCmd) {
  181. telemetry.track(cmd, subcommand, 'unsuccessful');
  182. }
  183. throw err;
  184. });
  185. };
  186. function getSubCommand (args, cmd) {
  187. if (['platform', 'platforms', 'plugin', 'plugins', 'telemetry', 'config'].indexOf(cmd) > -1) {
  188. return args[3]; // e.g: args='node cordova platform rm ios', 'node cordova telemetry on'
  189. }
  190. return null;
  191. }
  192. function printHelp (command) {
  193. var result = help([command]);
  194. cordova.emit('results', result);
  195. }
  196. function handleTelemetryCmd (subcommand, isOptedIn) {
  197. if (subcommand !== 'on' && subcommand !== 'off') {
  198. logger.subscribe(events);
  199. printHelp('telemetry');
  200. return;
  201. }
  202. var turnOn = subcommand === 'on';
  203. var cmdSuccess = true;
  204. // turn telemetry on or off
  205. try {
  206. if (turnOn) {
  207. telemetry.turnOn();
  208. console.log('Thanks for opting into telemetry to help us improve cordova.');
  209. } else {
  210. telemetry.turnOff();
  211. console.log('You have been opted out of telemetry. To change this, run: cordova telemetry on.');
  212. }
  213. } catch (ex) {
  214. cmdSuccess = false;
  215. }
  216. // track or not track ?, that is the question
  217. if (!turnOn) {
  218. // Always track telemetry opt-outs (whether user opted out or not!)
  219. telemetry.track('telemetry', 'off', 'via-cordova-telemetry-cmd', cmdSuccess ? 'successful' : 'unsuccessful');
  220. return Promise.resolve();
  221. }
  222. if (isOptedIn) {
  223. telemetry.track('telemetry', 'on', 'via-cordova-telemetry-cmd', cmdSuccess ? 'successful' : 'unsuccessful');
  224. }
  225. return Promise.resolve();
  226. }
  227. function cli (inputArgs) {
  228. checkForUpdates();
  229. var args = nopt(knownOpts, shortHands, inputArgs);
  230. process.on('uncaughtException', function (err) {
  231. if (err.message) {
  232. logger.error(err.message);
  233. } else {
  234. logger.error(err);
  235. }
  236. // Don't send exception details, just send that it happened
  237. if (shouldCollectTelemetry) {
  238. telemetry.track('uncaughtException');
  239. }
  240. process.exit(1);
  241. });
  242. logger.subscribe(events);
  243. if (args.silent) {
  244. logger.setLevel('error');
  245. } else if (args.verbose) { // can't be both silent AND verbose, silent wins
  246. logger.setLevel('verbose');
  247. }
  248. var cliVersion = pkg.version;
  249. var usingPrerelease = !!semver.prerelease(cliVersion);
  250. if (args.version || usingPrerelease) {
  251. var libVersion = require('cordova-lib/package').version;
  252. var toPrint = cliVersion;
  253. if (cliVersion !== libVersion || usingPrerelease) {
  254. toPrint += ' (cordova-lib@' + libVersion + ')';
  255. }
  256. if (args.version) {
  257. logger.results(toPrint);
  258. return Promise.resolve(); // Important! this will return and cease execution
  259. } else { // must be usingPrerelease
  260. // Show a warning and continue
  261. logger.warn('Warning: using prerelease version ' + toPrint);
  262. }
  263. }
  264. let warningPartial = null;
  265. // If the Node.js versions does not meet our requirements or in a deprecation stage, display a warning.
  266. if (
  267. NODE_VERSION_REQUIREMENT &&
  268. !semver.satisfies(NODE_VERSION, NODE_VERSION_REQUIREMENT)
  269. ) {
  270. warningPartial = 'is no longer supported';
  271. } else if (
  272. NODE_VERSION_DEPRECATING_RANGE &&
  273. semver.satisfies(NODE_VERSION, NODE_VERSION_DEPRECATING_RANGE)
  274. ) {
  275. warningPartial = 'has been deprecated';
  276. }
  277. if (warningPartial) {
  278. const upgradeMsg = 'Please upgrade to the latest Node.js version available (LTS version recommended).';
  279. logger.warn(`Warning: Node.js ${NODE_VERSION} ${warningPartial}. ${upgradeMsg}`);
  280. }
  281. // If there were arguments protected from nopt with a double dash, keep
  282. // them in unparsedArgs. For example:
  283. // cordova build ios -- --verbose --whatever
  284. // In this case "--verbose" is not parsed by nopt and args.vergbose will be
  285. // false, the unparsed args after -- are kept in unparsedArgs and can be
  286. // passed downstream to some scripts invoked by Cordova.
  287. var unparsedArgs = [];
  288. var parseStopperIdx = args.argv.original.indexOf('--');
  289. if (parseStopperIdx !== -1) {
  290. unparsedArgs = args.argv.original.slice(parseStopperIdx + 1);
  291. }
  292. // args.argv.remain contains both the undashed args (like platform names)
  293. // and whatever unparsed args that were protected by " -- ".
  294. // "undashed" stores only the undashed args without those after " -- " .
  295. var remain = args.argv.remain;
  296. var undashed = remain.slice(0, remain.length - unparsedArgs.length);
  297. var cmd = undashed[0];
  298. var subcommand;
  299. if (!cmd || cmd === 'help' || args.help) {
  300. if (!args.help && remain[0] === 'help') {
  301. remain.shift();
  302. }
  303. return printHelp(remain);
  304. }
  305. if (cmd === 'info') return info();
  306. // Don't need to do anything with cordova-lib since config was handled above
  307. if (cmd === 'config') return true;
  308. if (cmd === 'create') {
  309. const [, dest, id, name] = undashed;
  310. return cordovaCreate(dest, { id, name, events, template: args.template });
  311. }
  312. if (!Object.prototype.hasOwnProperty.call(cordova, cmd)) {
  313. var msg2 = 'Cordova does not know ' + cmd + '; try `' + cordova_lib.binname +
  314. ' help` for a list of all the available commands.';
  315. throw new CordovaError(msg2);
  316. }
  317. var opts = {
  318. platforms: [],
  319. options: [],
  320. verbose: args.verbose || false,
  321. silent: args.silent || false,
  322. nohooks: args.nohooks || [],
  323. searchpath: args.searchpath
  324. };
  325. var platformCommands = ['emulate', 'build', 'prepare', 'compile', 'run', 'clean'];
  326. if (platformCommands.indexOf(cmd) !== -1) {
  327. // All options without dashes are assumed to be platform names
  328. opts.platforms = undashed.slice(1);
  329. // Pass nopt-parsed args to PlatformApi through opts.options
  330. opts.options = args;
  331. opts.options.argv = unparsedArgs;
  332. if (cmd === 'run' && args.list && cordova.targets) {
  333. return cordova.targets.call(null, opts);
  334. }
  335. return cordova[cmd].call(null, opts);
  336. } else if (cmd === 'requirements') {
  337. // All options without dashes are assumed to be platform names
  338. opts.platforms = undashed.slice(1);
  339. return cordova[cmd].call(null, opts.platforms)
  340. .then(function (platformChecks) {
  341. var someChecksFailed = Object.keys(platformChecks).map(function (platformName) {
  342. events.emit('log', '\nRequirements check results for ' + platformName + ':');
  343. var platformCheck = platformChecks[platformName];
  344. if (platformCheck instanceof CordovaError) {
  345. events.emit('warn', 'Check failed for ' + platformName + ' due to ' + platformCheck);
  346. return true;
  347. }
  348. var someChecksFailed = false;
  349. // platformCheck is expected to be an array of conditions that must be met
  350. // the browser platform currently returns nothing, which was breaking here.
  351. if (platformCheck && platformCheck.forEach) {
  352. platformCheck.forEach(function (checkItem) {
  353. var checkSummary = checkItem.name + ': ' +
  354. (checkItem.installed ? 'installed ' : 'not installed ') +
  355. (checkItem.installed ? checkItem.metadata.version.version || checkItem.metadata.version : '');
  356. events.emit('log', checkSummary);
  357. if (!checkItem.installed) {
  358. someChecksFailed = true;
  359. events.emit('warn', checkItem.metadata.reason);
  360. }
  361. });
  362. }
  363. return someChecksFailed;
  364. }).some(function (isCheckFailedForPlatform) {
  365. return isCheckFailedForPlatform;
  366. });
  367. if (someChecksFailed) {
  368. throw new CordovaError('Some of requirements check failed');
  369. }
  370. });
  371. } else if (cmd === 'serve') {
  372. var port = undashed[1];
  373. return cordova.serve(port);
  374. } else {
  375. // platform/plugins add/rm [target(s)]
  376. subcommand = undashed[1]; // sub-command like "add", "ls", "rm" etc.
  377. var targets = undashed.slice(2); // array of targets, either platforms or plugins
  378. var cli_vars = {};
  379. if (args.variable) {
  380. args.variable.forEach(function (strVar) {
  381. // CB-9171
  382. var keyVal = strVar.split('=');
  383. if (keyVal.length < 2) {
  384. throw new CordovaError('invalid variable format: ' + strVar);
  385. } else {
  386. var key = keyVal.shift().toUpperCase();
  387. var val = keyVal.join('=');
  388. cli_vars[key] = val;
  389. }
  390. });
  391. }
  392. args.save = !args.nosave;
  393. args.production = !args.noprod;
  394. if (args.searchpath === undefined) {
  395. // User explicitly did not pass in searchpath
  396. args.searchpath = conf.get('searchpath');
  397. }
  398. if (args['save-exact'] === undefined) {
  399. // User explicitly did not pass in save-exact
  400. args['save-exact'] = conf.get('save-exact');
  401. }
  402. var download_opts = {
  403. searchpath: args.searchpath,
  404. noregistry: args.noregistry,
  405. nohooks: args.nohooks,
  406. cli_variables: cli_vars,
  407. link: args.link || false,
  408. save: args.save,
  409. save_exact: args['save-exact'] || false,
  410. shrinkwrap: args.shrinkwrap || false,
  411. force: args.force || false,
  412. production: args.production
  413. };
  414. return cordova[cmd](subcommand, targets, download_opts);
  415. }
  416. }