blob: d7ab879b8fb76b047b877ca4b08f70d427765936 [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2var path = require('path');
3var minimist = require('minimist');
4var objectAssign = require('object-assign');
5var camelcaseKeys = require('camelcase-keys');
6var decamelize = require('decamelize');
7var mapObj = require('map-obj');
8var trimNewlines = require('trim-newlines');
9var redent = require('redent');
10var readPkgUp = require('read-pkg-up');
11var loudRejection = require('loud-rejection');
12var normalizePackageData = require('normalize-package-data');
13
14// get the uncached parent
15delete require.cache[__filename];
16var parentDir = path.dirname(module.parent.filename);
17
18module.exports = function (opts, minimistOpts) {
19 loudRejection();
20
21 if (Array.isArray(opts) || typeof opts === 'string') {
22 opts = {help: opts};
23 }
24
25 opts = objectAssign({
26 pkg: readPkgUp.sync({
27 cwd: parentDir,
28 normalize: false
29 }).pkg,
30 argv: process.argv.slice(2)
31 }, opts);
32
33 minimistOpts = objectAssign({}, minimistOpts);
34
35 minimistOpts.default = mapObj(minimistOpts.default || {}, function (key, value) {
36 return [decamelize(key, '-'), value];
37 });
38
39 if (Array.isArray(opts.help)) {
40 opts.help = opts.help.join('\n');
41 }
42
43 var pkg = typeof opts.pkg === 'string' ? require(path.join(parentDir, opts.pkg)) : opts.pkg;
44 var argv = minimist(opts.argv, minimistOpts);
45 var help = redent(trimNewlines(opts.help || ''), 2);
46
47 normalizePackageData(pkg);
48
49 process.title = pkg.bin ? Object.keys(pkg.bin)[0] : pkg.name;
50
51 var description = opts.description;
52 if (!description && description !== false) {
53 description = pkg.description;
54 }
55
56 help = (description ? '\n ' + description + '\n' : '') + (help ? '\n' + help : '\n');
57
58 var showHelp = function (code) {
59 console.log(help);
60 process.exit(code || 0);
61 };
62
63 if (argv.version && opts.version !== false) {
64 console.log(typeof opts.version === 'string' ? opts.version : pkg.version);
65 process.exit();
66 }
67
68 if (argv.help && opts.help !== false) {
69 showHelp();
70 }
71
72 var _ = argv._;
73 delete argv._;
74
75 return {
76 input: _,
77 flags: camelcaseKeys(argv),
78 pkg: pkg,
79 help: help,
80 showHelp: showHelp
81 };
82};