-
Notifications
You must be signed in to change notification settings - Fork 210
Expand file tree
/
Copy pathargv.ts
More file actions
449 lines (362 loc) · 14.9 KB
/
Copy pathargv.ts
File metadata and controls
449 lines (362 loc) · 14.9 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import assert from "node:assert";
import fs from "fs-extra";
import * as dotenv from "dotenv";
import * as path from "node:path";
import camelCase from "camelcase";
import {Utils} from "./utils.js";
import {WriteStreams} from "./write-streams.js";
import chalkBase from "chalk";
import chalk from "chalk-template";
export function splitSemicolonEnvVars (argv: Record<string, any>, arrayKeys: Set<string>, env: Record<string, string | undefined>): void {
for (const [envKey, envValue] of Object.entries(env)) {
if (!envKey.startsWith("GCL_") || envValue == null) continue;
const optionName = camelCase(envKey.slice(4));
if (!arrayKeys.has(optionName)) continue;
const currentVal = argv[optionName];
if (!Array.isArray(currentVal) || currentVal.length !== 1 || currentVal[0] !== envValue) continue;
argv[optionName] = envValue.split(";");
}
}
async function isInGitRepository () {
try {
await Utils.spawn(["git", "rev-parse", "--is-inside-work-tree"]);
return true;
} catch {
return false;
}
}
async function gitRootPath () {
const {stdout} = await Utils.spawn(["git", "rev-parse", "--show-toplevel"]);
return stdout;
}
const GCL_VARIABLE_PREFIX = "GCL_VARIABLE_";
// Removes GCL_VARIABLE_* entries from env (mutates) and returns the removed entries
export function stripGclVariableEnvVars (env: Record<string, string | undefined>): Record<string, string> {
const stripped: Record<string, string> = {};
for (const key of Object.keys(env)) {
if (!key.startsWith(GCL_VARIABLE_PREFIX) || env[key] == null) continue;
if (key.length > GCL_VARIABLE_PREFIX.length) {
stripped[key] = env[key]!;
}
delete env[key];
}
return stripped;
}
// Prepends env vars so CLI --variable (later in array) takes precedence via last-wins
export function injectGclVariableEnvVars (argv: {variable?: string[]; [key: string]: unknown}, gclVars: Record<string, string>): void {
for (const [envKey, envValue] of Object.entries(gclVars)) {
const varName = envKey.slice(GCL_VARIABLE_PREFIX.length);
argv.variable ??= [];
argv.variable.unshift(`${varName}=${envValue}`);
}
}
export class Argv {
static readonly default = {
"variablesFile": ".gitlab-ci-local-variables.yml",
"inputsFile": ".gitlab-ci-local-inputs.yml",
"evaluateRuleChanges": true,
"ignoreSchemaPaths": [] as string[],
"ignorePredefinedVars": [] as string[],
};
map: Map<string, any> = new Map<string, any>();
private readonly writeStreams: WriteStreams | undefined;
private async fallbackCwd (args: any) {
if (args.cwd !== undefined || args.file !== undefined) return;
if (fs.existsSync(`${process.cwd()}/.gitlab-ci.yml`)) return;
if (!(await isInGitRepository())) return;
this.writeStreams?.stderr(chalk`{yellow .gitlab-ci.yml not found in cwd, falling back to git root directory}\n`);
this.map.set("cwd", path.relative(process.cwd(), await gitRootPath()));
}
static async build (args: any, writeStreams?: WriteStreams) {
const argv = new Argv(args, writeStreams);
await argv.fallbackCwd(args);
argv.injectDotenv(`${argv.home}/.gitlab-ci-local/.env`, args);
argv.injectDotenv(`${argv.cwd}/.gitlab-ci-local-env`, args);
if (!argv.shellExecutorNoImage && argv.shellIsolation) {
writeStreams?.stderr(chalk`{black.bgYellowBright WARN } --shell-isolation does not work with --no-shell-executor-no-image\n`);
}
if (argv.defaultImageExplicitlySet && argv.shellIsolation) {
writeStreams?.stderr(chalk`{black.bgYellowBright WARN } --default-image does not work with --shell-isolation=true\n`);
}
if (argv.defaultImageExplicitlySet && argv.shellExecutorNoImage) {
writeStreams?.stderr(chalk`{black.bgYellowBright WARN } --default-image does not work with --shell-executor-no-image=true\n`);
}
if (argv.defaultImageExplicitlySet && argv.forceShellExecutor) {
writeStreams?.stderr(chalk`{black.bgYellowBright WARN } --default-image does not work with --force-shell-executor=true\n`);
}
return argv;
}
private constructor (argv: any, writeStreams?: WriteStreams) {
if (argv.noColor || argv.color === false || (process.env.NO_COLOR ?? "") !== "") {
chalkBase.level = 0;
}
this.writeStreams = writeStreams;
for (const [key, value] of Object.entries(argv)) {
this.map.set(key, value);
}
}
private injectDotenv (potentialDotenvFilepath: string, argv: any) {
if (!fs.existsSync(potentialDotenvFilepath)) return;
const config = dotenv.parse(fs.readFileSync(potentialDotenvFilepath));
for (const [key, value] of Object.entries(config)) {
const argKey = camelCase(key);
// variable is additive — merge dotenv values with CLI values
if (argKey === "variable") {
let currentVal = argv[argKey];
if (currentVal == null) {
currentVal = [];
this.map.set(argKey, currentVal);
}
if (!Array.isArray(currentVal)) {
continue;
}
for (const pair of value.split(" ")) {
currentVal.unshift(pair);
}
} else if (argv[argKey] == null) {
// Work around `dotenv.parse` limitation https://github.com/motdotla/dotenv/issues/51#issuecomment-552559070
if (value === "true") this.map.set(argKey, true);
else if (value === "false") this.map.set(argKey, false);
else if (value === "null") this.map.set(argKey, null);
else if (Number.isFinite(Number(value))) this.map.set(argKey, Number(value));
else this.map.set(argKey, value);
}
}
}
private getStringArray (key: string): string[] {
const val = this.map.get(key) ?? [];
if (Array.isArray(val)) return val;
if (typeof val === "string") return val.split(" ");
return [];
}
get cwd (): string {
let cwd = this.map.get("cwd") ?? ".";
assert(typeof cwd != "object", "--cwd option cannot be an array");
assert(!path.isAbsolute(cwd), "Please use relative path for the --cwd option");
cwd = path.normalize(`${process.cwd()}/${cwd}`);
cwd = cwd.replace(/\/$/, "");
assert(fs.pathExistsSync(cwd), `${cwd} is not a directory`);
return cwd;
}
get variablesFile (): string {
return this.map.get("variablesFile") ?? Argv.default.variablesFile;
}
get inputsFile (): string {
return this.map.get("inputsFile") ?? Argv.default.inputsFile;
}
get evaluateRuleChanges (): boolean {
return this.map.get("evaluateRuleChanges") ?? Argv.default.evaluateRuleChanges;
}
get file (): string {
return this.map.get("file") ?? ".gitlab-ci.yml";
}
get stateDir (): string {
return (this.map.get("stateDir") ?? ".gitlab-ci-local").replace(/\/$/, "");
}
get home (): string {
return (this.map.get("home") ?? process.env.HOME ?? "").replace(/\/$/, "");
}
get volume (): string[] { return this.getStringArray("volume"); }
get network (): string[] { return this.getStringArray("network"); }
get extraHost (): string[] { return this.getStringArray("extraHost"); }
get caFile (): string | null {
return this.map.get("caFile") ?? null;
}
get ignoreSchemaPaths (): string[] {
return this.map.get("ignoreSchemaPaths") ?? Argv.default.ignoreSchemaPaths;
}
get ignorePredefinedVars (): string[] {
const val = this.map.get("ignorePredefinedVars");
if (Array.isArray(val)) return val;
if (typeof val === "string" && val.length > 0) return val.split(",");
return Argv.default.ignorePredefinedVars;
}
get pullPolicy (): string {
return this.map.get("pullPolicy") ?? "if-not-present";
}
get remoteVariables (): string[] { return this.getStringArray("remoteVariables"); }
get variable (): {[key: string]: string} {
const variables: {[key: string]: string} = {};
for (const pair of this.getStringArray("variable")) {
const eqIndex = pair.indexOf("=");
if (eqIndex < 1) continue;
const key = pair.substring(0, eqIndex);
if (/^\w+$/.test(key)) {
variables[key] = pair.substring(eqIndex + 1);
}
}
return variables;
}
get input (): {_global: {[key: string]: any}; _components: {[key: string]: {[key: string]: any}}} {
const val = this.map.get("input");
const _global: {[key: string]: any} = {};
const _components: {[key: string]: {[key: string]: any}} = {};
const pairs = typeof val == "string" ? val.split(" ") : val;
const dangerousKeys = new Set(["__proto__", "constructor", "prototype"]);
(pairs ?? []).forEach((inputPair: string) => {
// Support component-specific syntax: component:key=value or key=value
// Component names may contain word chars, hyphens, and slashes (e.g. templates/deploy)
const exec = /(?:(?<component>[\w\-/]+):)?(?<key>[\w-]+)(=)(?<value>(.|\n|\r)*)/.exec(inputPair);
if (exec?.groups?.key) {
const value = exec?.groups?.value;
const key = exec.groups.key;
const component = exec.groups.component;
// Guard against prototype pollution
if (dangerousKeys.has(key) || dangerousKeys.has(component ?? "")) return;
// Try to parse as JSON for arrays/objects/booleans/numbers
let parsedValue;
try {
parsedValue = JSON.parse(value);
} catch {
parsedValue = value;
}
if (component) {
if (!_components[component]) _components[component] = {};
_components[component][key] = parsedValue;
} else {
_global[key] = parsedValue;
}
}
});
return {_global, _components};
}
get unsetVariables (): string[] {
return this.map.get("unsetVariable") ?? [];
}
get manual (): string[] { return this.getStringArray("manual"); }
get job (): string[] {
return this.map.get("job") ?? [];
}
get autoCompleting (): boolean {
return this.map.get("autoCompleting") ?? false;
}
get cleanup (): boolean {
return this.map.get("cleanup") ?? true;
}
get quiet (): boolean {
return this.map.get("quiet") ?? false;
}
get umask (): boolean {
// TODO: default to false in 5.x.x
return this.map.get("umask") ?? true;
}
get userns (): string | undefined {
return this.map.get("userns");
}
get privileged (): boolean {
return this.map.get("privileged") ?? false;
}
get device (): string[] { return this.getStringArray("device"); }
get ulimit (): string | null {
const ulimit = this.map.get("ulimit");
if (!ulimit) return null;
return ulimit;
}
get shmSize (): string | undefined {
return this.map.get("shmSize");
}
get needs (): boolean {
return this.map.get("needs") ?? false;
}
get onlyNeeds (): boolean {
return this.map.get("onlyNeeds") ?? false;
}
get stage (): string | null {
return this.map.get("stage") ?? null;
}
get completion (): boolean {
return this.map.get("completion") ?? false;
}
get list (): boolean {
return this.map.get("list") ?? false;
}
get listAll (): boolean {
return this.map.get("listAll") ?? false;
}
get listJson (): boolean {
return this.map.get("listJson") ?? false;
}
get listCsv (): boolean {
return this.map.get("listCsv") ?? false;
}
get listCsvAll (): boolean {
return this.map.get("listCsvAll") ?? false;
}
get preview (): boolean {
return this.map.get("preview") ?? false;
}
get validateDependencyChain (): boolean {
return this.map.get("validateDependencyChain") ?? false;
}
get shellIsolation (): boolean {
// TODO: default to true in 5.x.x
return this.map.get("shellIsolation") ?? false;
}
get fetchIncludes (): boolean {
return this.map.get("fetchIncludes") ?? false;
}
get mountCache (): boolean {
return this.map.get("mountCache") ?? false;
}
get artifactsToSource (): boolean {
// TODO: default to false in 5.x.x
return this.map.get("artifactsToSource") ?? true;
}
get showTimestamps (): boolean {
return this.map.get("timestamps") ?? false;
}
get maxJobNamePadding (): number | null {
return this.map.get("maxJobNamePadding") ?? null;
}
get containerMacAddress (): string | null {
return this.map.get("containerMacAddress") ?? null;
}
get containerEmulate (): string | null {
return this.map.get("containerEmulate") ?? null;
}
get gpus (): string | null {
return this.map.get("gpus") ?? null;
}
get concurrency (): number | null {
const concurrency = this.map.get("concurrency");
if (!concurrency) return null;
return Number(concurrency);
}
get containerExecutable (): string {
return this.map.get("containerExecutable") ?? "docker";
}
get jsonSchemaValidation (): boolean {
return this.map.get("jsonSchemaValidation") ?? true;
}
get shellExecutorNoImage (): boolean {
// TODO: default to false in 5.x.x
return this.map.get("shellExecutorNoImage") ?? true;
}
get forceShellExecutor (): boolean {
return this.map.get("forceShellExecutor") ?? false;
}
get defaultImage (): string {
return this.map.get("defaultImage") ?? "docker.io/ruby:3.1";
}
get waitImage (): string {
return this.map.get("waitImage") ?? "docker.io/sumina46/wait-for-it:latest";
}
get waitForServicesTimeout (): number {
return this.map.get("waitForServicesTimeout") ?? 30;
}
get helperImage (): string {
return this.map.get("helperImage") ?? "docker.io/firecow/gitlab-ci-local-util:latest";
}
get defaultImageExplicitlySet (): boolean {
return this.map.get("defaultImage") ?? false;
}
get maximumIncludes (): number {
return this.map.get("maximumIncludes") ?? 150; // https://docs.gitlab.com/ee/administration/settings/continuous_integration.html#maximum-includes
}
get childPipelineDepth (): number {
return this.map.get("childPipelineDepth");
}
get registry (): boolean {
return this.map.get("registry") ?? false;
}
}