forked from sindresorhus/meow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (72 loc) · 2.25 KB
/
index.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
'use strict';
const path = require('path');
const minimist = require('minimist');
const camelcaseKeys = require('camelcase-keys');
const decamelizeKeys = require('decamelize-keys');
const trimNewlines = require('trim-newlines');
const redent = require('redent');
const readPkgUp = require('read-pkg-up');
const loudRejection = require('loud-rejection');
const normalizePackageData = require('normalize-package-data');
// Prevent caching of this module so module.parent is always accurate
delete require.cache[__filename];
const parentDir = path.dirname(module.parent.filename);
module.exports = (opts, minimistOpts) => {
loudRejection();
if (Array.isArray(opts) || typeof opts === 'string') {
opts = {
help: opts
};
}
opts = Object.assign({
pkg: readPkgUp.sync({
cwd: parentDir,
normalize: false
}).pkg,
argv: process.argv.slice(2),
inferType: false
}, opts);
minimistOpts = Object.assign({
string: ['_']
}, minimistOpts);
minimistOpts.default = decamelizeKeys(minimistOpts.default || {}, '-');
const index = minimistOpts.string.indexOf('_');
if (opts.inferType === false && index === -1) {
minimistOpts.string.push('_');
} else if (opts.inferType === true && index !== -1) {
minimistOpts.string.splice(index, 1);
}
const pkg = opts.pkg;
const argv = minimist(opts.argv, minimistOpts);
let help = redent(trimNewlines((opts.help || '').replace(/\t+\n*$/, '')), 2);
normalizePackageData(pkg);
process.title = pkg.bin ? Object.keys(pkg.bin)[0] : pkg.name;
let description = opts.description;
if (!description && description !== false) {
description = pkg.description;
}
help = (description ? `\n ${description}\n` : '') + (help ? `\n${help}\n` : '\n');
const showHelp = code => {
console.log(help);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(typeof code === 'number' ? code : 2);
};
if (argv.version && opts.version !== false) {
console.log(typeof opts.version === 'string' ? opts.version : pkg.version);
// eslint-disable-next-line unicorn/no-process-exit
process.exit();
}
if (argv.help && opts.help !== false) {
showHelp(0);
}
const input = argv._;
delete argv._;
const flags = camelcaseKeys(argv, {exclude: ['--', /^\w$/]});
return {
input,
flags,
pkg,
help,
showHelp
};
};