forked from sindresorhus/meow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (74 loc) 路 2.39 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
92
93
94
95
96
import process from 'node:process';
import parseArguments from 'yargs-parser';
import camelCaseKeys from 'camelcase-keys';
import {trimNewlines} from 'trim-newlines';
import redent from 'redent';
import normalizePackageData from 'normalize-package-data';
import {buildOptions} from './options.js';
import {buildParserOptions} from './parser.js';
import {validate, checkUnknownFlags, checkMissingRequiredFlags} from './validate.js';
const buildResult = (options, parserOptions) => {
const {pkg: package_} = options;
const argv = parseArguments(options.argv, parserOptions);
let help = '';
if (options.help) {
help = trimNewlines((options.help || '').replace(/\t+\n*$/, ''));
if (help.includes('\n')) {
help = redent(help, options.helpIndent);
}
help = `\n${help}`;
}
normalizePackageData(package_);
let description = options.description ?? package_.description;
description &&= help ? redent(`\n${description}\n`, options.helpIndent) : `\n${description}`;
help = `${description || ''}${help}\n`;
const showHelp = code => {
console.log(help);
process.exit(typeof code === 'number' ? code : 2);
};
const showVersion = () => {
console.log(typeof options.version === 'string' ? options.version : package_.version);
process.exit(0);
};
if (argv._.length === 0 && options.argv.length === 1) {
if (argv.version === true && options.autoVersion) {
showVersion();
} else if (argv.help === true && options.autoHelp) {
showHelp(0);
}
}
const input = argv._;
delete argv._;
if (!options.allowUnknownFlags) {
checkUnknownFlags(input);
}
const flags = camelCaseKeys(argv, {exclude: ['--', /^\w$/]});
const unnormalizedFlags = {...flags};
validate(flags, options);
for (const flagValue of Object.values(options.flags)) {
if (Array.isArray(flagValue.aliases)) {
for (const alias of flagValue.aliases) {
delete flags[alias];
}
}
delete flags[flagValue.shortFlag];
}
checkMissingRequiredFlags(options.flags, flags, input);
return {
input,
flags,
unnormalizedFlags,
pkg: package_,
help,
showHelp,
showVersion,
};
};
const meow = (helpText, options = {}) => {
const parsedOptions = buildOptions(helpText, options);
const parserOptions = buildParserOptions(parsedOptions);
const result = buildResult(parsedOptions, parserOptions);
process.title = result.pkg.bin ? Object.keys(result.pkg.bin).at(0) : result.pkg.name;
return result;
};
export default meow;