-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathgetCliOptions.ts
More file actions
179 lines (164 loc) · 5.25 KB
/
getCliOptions.ts
File metadata and controls
179 lines (164 loc) · 5.25 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
import parser from 'yargs-parser';
import { CliOptions } from '../types/BeachballOptions';
import { getDefaultRemoteBranch, findProjectRoot } from 'workspace-tools';
import { env } from '../env';
// For camelCased options, yargs will automatically accept them with-dashes too.
const arrayOptions = ['disallowedChangeTypes', 'package', 'scope'] as const;
const booleanOptions = [
'all',
'bump',
'bumpDeps',
'bumpPeerDeps',
'commit',
'disallowDeletedChangeFiles',
'fetch',
'forceVersions',
'gitTags',
'help',
'keepChangeFiles',
'new',
'publish',
'push',
'verbose',
'version',
'yes',
] as const;
const numberOptions = ['depth', 'gitTimeout', 'retries', 'timeout'] as const;
const stringOptions = [
'access',
'authType',
'branch',
'canaryName',
'changehint',
'configPath',
'dependentChangeType',
'fromRef',
'message',
'prereleasePrefix',
'registry',
'tag',
'token',
'type',
] as const;
type AtLeastOne<T> = [T, ...T[]];
/** Type hack to verify that an array includes all keys of a type */
const allKeysOfType =
<T extends string>() =>
<L extends AtLeastOne<T>>(
...x: L extends any ? (Exclude<T, L[number]> extends never ? L : Exclude<T, L[number]>[]) : never
) =>
x;
// Verify that all the known CLI options have types specified, to ensure correct parsing.
//
// NOTE: If a prop is missing, this will have a somewhat misleading error:
// Argument of type '"disallowedChangeTypes"' is not assignable to parameter of type '"tag" | "version"'
//
// To fix, add the missing names after "parameter of type" ("tag" and "version" in this example)
// to the appropriate array above.
const knownOptions = allKeysOfType<keyof CliOptions>()(
...arrayOptions,
...booleanOptions,
...numberOptions,
...stringOptions,
// these options are filled in below, not respected from the command line
'path',
'command'
);
const parserOptions: parser.Options = {
configuration: {
'boolean-negation': true,
'camel-case-expansion': true,
'dot-notation': false,
'duplicate-arguments-array': true,
'flatten-duplicate-arrays': true,
'greedy-arrays': true, // for now; we might want to change this to false in the future
'parse-numbers': true,
'parse-positional-numbers': false,
'short-option-groups': false,
'strip-aliased': true,
'strip-dashed': true,
},
// spread to get rid of readonly...
array: [...arrayOptions],
boolean: [...booleanOptions],
number: [...numberOptions],
string: [...stringOptions],
alias: {
authType: ['a'],
branch: ['b'],
configPath: ['c', 'config'],
forceVersions: ['force'],
fromRef: ['since'],
help: ['h', '?'],
message: ['m'],
package: ['p'],
registry: ['r'],
tag: ['t'],
token: ['n'],
version: ['v'],
yes: ['y'],
},
};
let cachedCliOptions: CliOptions;
export function getCliOptions(argv: string[], disableCache?: boolean): CliOptions {
// Special case caching to process.argv which should be immutable
if (argv === process.argv) {
if (disableCache || env.beachballDisableCache || !cachedCliOptions) {
cachedCliOptions = getCliOptionsUncached(process.argv);
}
return cachedCliOptions;
} else {
return getCliOptionsUncached(argv);
}
}
function getCliOptionsUncached(argv: string[]): CliOptions {
// Be careful not to mutate the input argv
const trimmedArgv = argv.slice(2);
const args = parser(trimmedArgv, parserOptions);
const { _: positionalArgs, ...options } = args;
let cwd: string;
try {
cwd = findProjectRoot(process.cwd());
} catch (err) {
cwd = process.cwd();
}
if (positionalArgs.length > 1) {
throw new Error(`Only one positional argument (the command) is allowed. Received: ${positionalArgs.join(' ')}`);
}
const cliOptions = {
...(options as CliOptions),
command: positionalArgs.length ? String(positionalArgs[0]) : 'change',
path: cwd,
};
if (args.branch) {
// TODO: This logic assumes the first segment of any branch name with a slash must be the remote,
// which is not necessarily accurate. Ideally we should check if a remote with that name exists,
// and if not, perform the default remote lookup.
cliOptions.branch =
args.branch.indexOf('/') > -1
? args.branch
: getDefaultRemoteBranch({ branch: args.branch, verbose: args.verbose, cwd });
}
if (cliOptions.command === 'canary') {
cliOptions.tag = cliOptions.canaryName || 'canary';
}
for (const key of Object.keys(cliOptions) as (keyof CliOptions)[]) {
const value = cliOptions[key];
if (value === undefined) {
delete cliOptions[key];
} else if (typeof value === 'number' && isNaN(value)) {
throw new Error(`Non-numeric value passed for numeric option "${key}"`);
} else if (knownOptions.includes(key)) {
if (Array.isArray(value) && !arrayOptions.includes(key as any)) {
throw new Error(`Option "${key}" only accepts a single value. Received: ${value.join(' ')}`);
}
} else if (value === 'true') {
// For unknown arguments like --foo=true or --bar=false, yargs will handle the value as a string.
// Convert it to a boolean to avoid subtle bugs.
(cliOptions as any)[key] = true;
} else if (value === 'false') {
(cliOptions as any)[key] = false;
}
}
return cliOptions;
}