@aspruyt/xfg 8.0.0 → 8.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/secrets-command.js +12 -2
- package/dist/cli/settings-factories.d.ts +2 -1
- package/dist/cli/settings-factories.js +7 -1
- package/dist/cli/settings-report-builder.d.ts +6 -1
- package/dist/cli/settings-report-builder.js +7 -1
- package/dist/cli/settings-runner.js +24 -15
- package/dist/cli/types.d.ts +4 -2
- package/dist/config/index.d.ts +1 -1
- package/dist/config/merge.d.ts +9 -5
- package/dist/config/merge.js +148 -67
- package/dist/config/normalizer.js +87 -18
- package/dist/config/types.d.ts +28 -0
- package/dist/config/validator.js +17 -3
- package/dist/config/validators/ruleset-validator.js +6 -5
- package/dist/config/validators/shared.js +123 -0
- package/dist/lifecycle/github-lifecycle-provider.d.ts +1 -1
- package/dist/lifecycle/github-lifecycle-provider.js +54 -37
- package/dist/output/settings-report.d.ts +6 -1
- package/dist/output/settings-report.js +31 -9
- package/dist/settings/environments/diff.d.ts +22 -0
- package/dist/settings/environments/diff.js +78 -0
- package/dist/settings/environments/formatter.d.ts +17 -0
- package/dist/settings/environments/formatter.js +62 -0
- package/dist/settings/environments/github-environments-strategy.d.ts +23 -0
- package/dist/settings/environments/github-environments-strategy.js +54 -0
- package/dist/settings/environments/index.d.ts +5 -0
- package/dist/settings/environments/index.js +3 -0
- package/dist/settings/environments/processor.d.ts +21 -0
- package/dist/settings/environments/processor.js +100 -0
- package/dist/settings/environments/types.d.ts +38 -0
- package/dist/settings/environments/types.js +1 -0
- package/dist/settings/index.d.ts +1 -0
- package/dist/settings/index.js +1 -0
- package/dist/settings/secrets/diff.d.ts +2 -0
- package/dist/settings/secrets/formatter.d.ts +4 -0
- package/dist/settings/secrets/formatter.js +17 -4
- package/dist/settings/secrets/index.d.ts +2 -2
- package/dist/settings/secrets/index.js +1 -1
- package/dist/settings/secrets/processor.d.ts +16 -2
- package/dist/settings/secrets/processor.js +132 -28
- package/dist/shared/retry-utils.d.ts +3 -2
- package/dist/shared/retry-utils.js +3 -2
- package/dist/shared/sequential.d.ts +2 -0
- package/dist/shared/sequential.js +4 -0
- package/package.json +2 -2
|
@@ -5,11 +5,11 @@ import { expandRepoGroups } from "./extends-resolver.js";
|
|
|
5
5
|
* Clone content, stripping merge directives from object content.
|
|
6
6
|
* Text content is cloned as-is since it has no merge directives.
|
|
7
7
|
*/
|
|
8
|
-
function cloneContent(content) {
|
|
8
|
+
function cloneContent(content, fileName) {
|
|
9
9
|
if (isTextContent(content)) {
|
|
10
10
|
return structuredClone(content);
|
|
11
11
|
}
|
|
12
|
-
return stripMergeDirectives(structuredClone(content));
|
|
12
|
+
return stripMergeDirectives(structuredClone(content), fileName);
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
15
|
* Resolve the final content for a file by applying override/inherit/merge rules.
|
|
@@ -17,32 +17,34 @@ function cloneContent(content) {
|
|
|
17
17
|
* Returns null when the file should be empty (e.g. override with no content,
|
|
18
18
|
* or root file with no content and no repo override).
|
|
19
19
|
*/
|
|
20
|
-
function resolveFileContent(rootContent, repoOverride, mergeStrategy) {
|
|
20
|
+
function resolveFileContent(fileName, rootContent, repoOverride, mergeStrategy) {
|
|
21
21
|
if (repoOverride?.override) {
|
|
22
22
|
return repoOverride.content !== undefined
|
|
23
|
-
? cloneContent(repoOverride.content)
|
|
23
|
+
? cloneContent(repoOverride.content, fileName)
|
|
24
24
|
: null;
|
|
25
25
|
}
|
|
26
26
|
if (rootContent === undefined) {
|
|
27
|
-
return repoOverride?.content
|
|
27
|
+
return repoOverride?.content
|
|
28
|
+
? cloneContent(repoOverride.content, fileName)
|
|
29
|
+
: null;
|
|
28
30
|
}
|
|
29
31
|
if (!repoOverride?.content) {
|
|
30
32
|
return structuredClone(rootContent);
|
|
31
33
|
}
|
|
32
|
-
return mergeContentPair(rootContent, repoOverride.content, mergeStrategy);
|
|
34
|
+
return mergeContentPair(fileName, rootContent, repoOverride.content, mergeStrategy);
|
|
33
35
|
}
|
|
34
36
|
/**
|
|
35
37
|
* Merge two content values using the appropriate strategy.
|
|
36
38
|
* Handles text+text, object+object, and type mismatch cases.
|
|
37
39
|
*/
|
|
38
|
-
function mergeContentPair(base, overlay, strategy) {
|
|
40
|
+
function mergeContentPair(fileName, base, overlay, strategy) {
|
|
39
41
|
if (isTextContent(base) && isTextContent(overlay)) {
|
|
40
42
|
return mergeTextContent(base, overlay, strategy);
|
|
41
43
|
}
|
|
42
44
|
if (!isTextContent(base) && !isTextContent(overlay)) {
|
|
43
|
-
const ctx = createMergeContext(strategy);
|
|
45
|
+
const ctx = createMergeContext(strategy, fileName);
|
|
44
46
|
const merged = deepMerge(structuredClone(base), overlay, ctx);
|
|
45
|
-
return stripMergeDirectives(merged);
|
|
47
|
+
return stripMergeDirectives(merged, fileName);
|
|
46
48
|
}
|
|
47
49
|
return overlay;
|
|
48
50
|
}
|
|
@@ -93,10 +95,13 @@ function normalizeAiOption(prOptions) {
|
|
|
93
95
|
return { ...rest, ai: { ...ai, provider: ai.provider ?? "anthropic" } };
|
|
94
96
|
return Object.keys(rest).length > 0 ? rest : undefined;
|
|
95
97
|
}
|
|
98
|
+
function rulesetLocation(name) {
|
|
99
|
+
return `ruleset '${name}'`;
|
|
100
|
+
}
|
|
96
101
|
/**
|
|
97
102
|
* Deep merges two rulesets: per-repo values override root values.
|
|
98
103
|
*/
|
|
99
|
-
function mergeRuleset(root, perRepo) {
|
|
104
|
+
function mergeRuleset(name, root, perRepo) {
|
|
100
105
|
if (!root)
|
|
101
106
|
return structuredClone(perRepo ?? {});
|
|
102
107
|
if (!perRepo)
|
|
@@ -104,7 +109,7 @@ function mergeRuleset(root, perRepo) {
|
|
|
104
109
|
// Deep merge using the existing merge utility with replace strategy.
|
|
105
110
|
// deepMerge operates on Record<string, unknown> — the cast is safe because
|
|
106
111
|
// merging two Ruleset-shaped objects preserves the Ruleset structure.
|
|
107
|
-
const ctx = createMergeContext("replace");
|
|
112
|
+
const ctx = createMergeContext("replace", rulesetLocation(name));
|
|
108
113
|
return deepMerge(structuredClone(root), perRepo, ctx);
|
|
109
114
|
}
|
|
110
115
|
function mergeLabels(rootLabels, repoLabels) {
|
|
@@ -218,6 +223,63 @@ function dropCollaboratorsIfEmpty(merged) {
|
|
|
218
223
|
return undefined;
|
|
219
224
|
return merged;
|
|
220
225
|
}
|
|
226
|
+
/**
|
|
227
|
+
* Merges one environment layer over another: a set `deploymentBranchPolicy`
|
|
228
|
+
* replaces the inherited one whole, and secrets merge like repo secrets.
|
|
229
|
+
*/
|
|
230
|
+
function mergeEnvironmentLayer(base, overlay) {
|
|
231
|
+
const inherited = base === false ? undefined : base;
|
|
232
|
+
const result = {};
|
|
233
|
+
const policy = overlay.deploymentBranchPolicy ?? inherited?.deploymentBranchPolicy;
|
|
234
|
+
if (policy !== undefined) {
|
|
235
|
+
result.deploymentBranchPolicy = structuredClone(policy);
|
|
236
|
+
}
|
|
237
|
+
if (inherited?.secrets || overlay.secrets) {
|
|
238
|
+
result.secrets = mergeEntryMapLayer(inherited?.secrets, overlay.secrets);
|
|
239
|
+
}
|
|
240
|
+
return result;
|
|
241
|
+
}
|
|
242
|
+
function finalizeEnvironment(env) {
|
|
243
|
+
const result = {};
|
|
244
|
+
if (env.deploymentBranchPolicy) {
|
|
245
|
+
result.deploymentBranchPolicy = structuredClone(env.deploymentBranchPolicy);
|
|
246
|
+
}
|
|
247
|
+
const secrets = Object.entries(env.secrets ?? {}).filter(([, value]) => value !== false);
|
|
248
|
+
if (secrets.length > 0) {
|
|
249
|
+
result.secrets = Object.fromEntries(secrets);
|
|
250
|
+
}
|
|
251
|
+
return result;
|
|
252
|
+
}
|
|
253
|
+
// Matches the entries mergeNamedEntries acts on; anything else is ignored there.
|
|
254
|
+
function isMergeableEntry(entry) {
|
|
255
|
+
return entry === false || (typeof entry === "object" && entry !== null);
|
|
256
|
+
}
|
|
257
|
+
// GitHub environment names are case-insensitive; base entries take the overlay's spelling so they merge.
|
|
258
|
+
function mergeEnvironmentEntries(base, overlay) {
|
|
259
|
+
const overlayNames = new Map();
|
|
260
|
+
for (const [name, entry] of Object.entries(overlay)) {
|
|
261
|
+
if (name !== "inherit" && isMergeableEntry(entry)) {
|
|
262
|
+
overlayNames.set(name.toLowerCase(), name);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
const rekeyed = {};
|
|
266
|
+
for (const [name, env] of Object.entries(base ?? {})) {
|
|
267
|
+
rekeyed[overlayNames.get(name.toLowerCase()) ?? name] = env;
|
|
268
|
+
}
|
|
269
|
+
return mergeNamedEntries(rekeyed, overlay, mergeEnvironmentLayer);
|
|
270
|
+
}
|
|
271
|
+
function mergeEnvironments(root, perRepo) {
|
|
272
|
+
if (!root && !perRepo)
|
|
273
|
+
return undefined;
|
|
274
|
+
const merged = mergeEnvironmentEntries(root, perRepo ?? {});
|
|
275
|
+
const result = {};
|
|
276
|
+
for (const [name, env] of Object.entries(merged)) {
|
|
277
|
+
if (env === false)
|
|
278
|
+
continue;
|
|
279
|
+
result[name] = finalizeEnvironment(env);
|
|
280
|
+
}
|
|
281
|
+
return Object.keys(result).length > 0 ? result : undefined;
|
|
282
|
+
}
|
|
221
283
|
/**
|
|
222
284
|
* Merges settings: per-repo settings deep merge with root settings.
|
|
223
285
|
* Returns undefined if no settings are defined.
|
|
@@ -244,8 +306,8 @@ export function mergeSettings(root, perRepo) {
|
|
|
244
306
|
if (!inheritRulesets && !repoRuleset && rootRuleset) {
|
|
245
307
|
continue;
|
|
246
308
|
}
|
|
247
|
-
const merged = mergeRuleset(rootRuleset, repoRuleset);
|
|
248
|
-
result.rulesets[name] = stripMergeDirectives(merged);
|
|
309
|
+
const merged = mergeRuleset(name, rootRuleset, repoRuleset);
|
|
310
|
+
result.rulesets[name] = stripMergeDirectives(merged, rulesetLocation(name));
|
|
249
311
|
}
|
|
250
312
|
if (Object.keys(result.rulesets).length === 0) {
|
|
251
313
|
delete result.rulesets;
|
|
@@ -312,6 +374,10 @@ export function mergeSettings(root, perRepo) {
|
|
|
312
374
|
result.collaborators = merged;
|
|
313
375
|
}
|
|
314
376
|
}
|
|
377
|
+
const mergedEnvironments = mergeEnvironments(root?.environments, perRepo?.environments);
|
|
378
|
+
if (mergedEnvironments) {
|
|
379
|
+
result.environments = mergedEnvironments;
|
|
380
|
+
}
|
|
315
381
|
return Object.keys(result).length > 0 ? result : undefined;
|
|
316
382
|
}
|
|
317
383
|
/**
|
|
@@ -340,7 +406,7 @@ function applyFileLayer(accumulated, layerFiles) {
|
|
|
340
406
|
mergedContent = overlay.content ?? existing.content;
|
|
341
407
|
}
|
|
342
408
|
else {
|
|
343
|
-
mergedContent = mergeContentPair(existing.content, overlay.content, existing.mergeStrategy ?? "replace");
|
|
409
|
+
mergedContent = mergeContentPair(fileName, existing.content, overlay.content, existing.mergeStrategy ?? "replace");
|
|
344
410
|
}
|
|
345
411
|
const { override: _override, ...restFileConfig } = fileConfig;
|
|
346
412
|
accumulated[fileName] = {
|
|
@@ -400,7 +466,7 @@ function mergeNamedEntries(base, overlay, merge) {
|
|
|
400
466
|
}
|
|
401
467
|
else if (typeof entry === "object" && entry !== null) {
|
|
402
468
|
const existing = result[name];
|
|
403
|
-
result[name] = merge(existing, entry);
|
|
469
|
+
result[name] = merge(existing, entry, name);
|
|
404
470
|
}
|
|
405
471
|
}
|
|
406
472
|
return result;
|
|
@@ -418,8 +484,8 @@ function mergeRawSettings(base, overlay) {
|
|
|
418
484
|
return structuredClone(base);
|
|
419
485
|
const result = base ? structuredClone(base) : {};
|
|
420
486
|
if (overlay.rulesets) {
|
|
421
|
-
result.rulesets = mergeNamedEntries(result.rulesets, overlay.rulesets, (existing, entry) => existing && typeof existing === "object"
|
|
422
|
-
? mergeRuleset(existing, entry)
|
|
487
|
+
result.rulesets = mergeNamedEntries(result.rulesets, overlay.rulesets, (existing, entry, name) => existing && typeof existing === "object"
|
|
488
|
+
? mergeRuleset(name, existing, entry)
|
|
423
489
|
: structuredClone(entry));
|
|
424
490
|
}
|
|
425
491
|
if (overlay.repo !== undefined) {
|
|
@@ -456,6 +522,9 @@ function mergeRawSettings(base, overlay) {
|
|
|
456
522
|
if (overlay.collaborators) {
|
|
457
523
|
result.collaborators = mergeCollaboratorsLayer(result.collaborators, overlay.collaborators);
|
|
458
524
|
}
|
|
525
|
+
if (overlay.environments) {
|
|
526
|
+
result.environments = mergeEnvironmentEntries(result.environments, overlay.environments);
|
|
527
|
+
}
|
|
459
528
|
if (overlay.deleteOrphaned !== undefined) {
|
|
460
529
|
result.deleteOrphaned = overlay.deleteOrphaned;
|
|
461
530
|
}
|
|
@@ -524,7 +593,7 @@ function resolveFileEntry(fileName, fileConfig, repoOverride, inheritFiles, glob
|
|
|
524
593
|
if (!inheritFiles && !repoOverride)
|
|
525
594
|
return null;
|
|
526
595
|
const fileStrategy = fileConfig.mergeStrategy ?? "replace";
|
|
527
|
-
let mergedContent = resolveFileContent(fileConfig.content, repoOverride, fileStrategy);
|
|
596
|
+
let mergedContent = resolveFileContent(fileName, fileConfig.content, repoOverride, fileStrategy);
|
|
528
597
|
if (mergedContent !== null) {
|
|
529
598
|
mergedContent = interpolateContent(mergedContent, { strict: true, env });
|
|
530
599
|
}
|
package/dist/config/types.d.ts
CHANGED
|
@@ -291,6 +291,28 @@ export interface SecretConfig {
|
|
|
291
291
|
export type SecretsConfig = Record<string, SecretConfig | boolean> & {
|
|
292
292
|
deleteOrphaned?: boolean;
|
|
293
293
|
};
|
|
294
|
+
export type DeploymentBranchPatternType = "branch" | "tag";
|
|
295
|
+
export interface DeploymentBranchPattern {
|
|
296
|
+
type: DeploymentBranchPatternType;
|
|
297
|
+
/** fnmatch-style name pattern, e.g. `main` or `v*.*.*` */
|
|
298
|
+
name: string;
|
|
299
|
+
}
|
|
300
|
+
/** Exactly one of `protectedBranches: true` or a non-empty `custom` list. */
|
|
301
|
+
export interface DeploymentBranchPolicy {
|
|
302
|
+
protectedBranches?: boolean;
|
|
303
|
+
custom?: DeploymentBranchPattern[];
|
|
304
|
+
}
|
|
305
|
+
export interface EnvironmentConfig {
|
|
306
|
+
/** Omitted: any branch can deploy */
|
|
307
|
+
deploymentBranchPolicy?: DeploymentBranchPolicy;
|
|
308
|
+
/** Environment secrets keyed by name; only `xfg secrets sync` writes them */
|
|
309
|
+
secrets?: Record<string, SecretConfig>;
|
|
310
|
+
}
|
|
311
|
+
export interface RawEnvironmentConfig {
|
|
312
|
+
/** `false` clears an inherited policy so any branch can deploy */
|
|
313
|
+
deploymentBranchPolicy?: DeploymentBranchPolicy | false;
|
|
314
|
+
secrets?: Record<string, SecretConfig | false>;
|
|
315
|
+
}
|
|
294
316
|
export interface CollaboratorsConfig {
|
|
295
317
|
/** GitHub usernames granted write access (personal repos only) */
|
|
296
318
|
users?: string[];
|
|
@@ -319,6 +341,8 @@ export interface RepoSettings {
|
|
|
319
341
|
};
|
|
320
342
|
/** Direct collaborators on personal (user-owned) repos */
|
|
321
343
|
collaborators?: CollaboratorsConfig;
|
|
344
|
+
/** GitHub deployment environments keyed by name */
|
|
345
|
+
environments?: Record<string, EnvironmentConfig>;
|
|
322
346
|
deleteOrphaned?: boolean;
|
|
323
347
|
}
|
|
324
348
|
export type ContentValue = Record<string, unknown> | string | string[];
|
|
@@ -384,6 +408,7 @@ export interface RawRootSettings {
|
|
|
384
408
|
};
|
|
385
409
|
secrets?: SecretsConfig;
|
|
386
410
|
collaborators?: CollaboratorsConfig;
|
|
411
|
+
environments?: Record<string, RawEnvironmentConfig | false>;
|
|
387
412
|
deleteOrphaned?: boolean;
|
|
388
413
|
}
|
|
389
414
|
export interface RawRepoSettings {
|
|
@@ -403,6 +428,9 @@ export interface RawRepoSettings {
|
|
|
403
428
|
inherit?: boolean;
|
|
404
429
|
};
|
|
405
430
|
collaborators?: RawCollaboratorsConfig;
|
|
431
|
+
environments?: Record<string, RawEnvironmentConfig | false> & {
|
|
432
|
+
inherit?: boolean;
|
|
433
|
+
};
|
|
406
434
|
deleteOrphaned?: boolean;
|
|
407
435
|
}
|
|
408
436
|
export interface RawRepoConfig {
|
package/dist/config/validator.js
CHANGED
|
@@ -75,6 +75,10 @@ function validateRootSettings(config) {
|
|
|
75
75
|
"inherit" in config.settings.collaborators) {
|
|
76
76
|
throw new ValidationError("'inherit' is not allowed in root-level collaborators (nothing to inherit from)");
|
|
77
77
|
}
|
|
78
|
+
if (config.settings.environments &&
|
|
79
|
+
"inherit" in config.settings.environments) {
|
|
80
|
+
throw new ValidationError("'inherit' is not allowed in root-level environments (nothing to inherit from)");
|
|
81
|
+
}
|
|
78
82
|
}
|
|
79
83
|
function validateGithubHosts(config) {
|
|
80
84
|
if (config.githubHosts === undefined)
|
|
@@ -300,6 +304,11 @@ export function hasActionableSettings(settings) {
|
|
|
300
304
|
settings.collaborators.deleteOrphaned === true)) {
|
|
301
305
|
return true;
|
|
302
306
|
}
|
|
307
|
+
// An environment holding only secrets still needs `xfg sync` to create it.
|
|
308
|
+
if (settings.environments &&
|
|
309
|
+
Object.entries(settings.environments).some(([name, env]) => name !== "inherit" && isPlainObject(env))) {
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
303
312
|
// Secrets are deliberately absent: `xfg sync` must never process them.
|
|
304
313
|
// A secrets-only config leaves `xfg sync` with nothing to do.
|
|
305
314
|
return false;
|
|
@@ -358,8 +367,13 @@ function validateSecretsLayer(secrets) {
|
|
|
358
367
|
}
|
|
359
368
|
export function validateSecretsConfig(config) {
|
|
360
369
|
for (const settings of collectAllSettings(config)) {
|
|
361
|
-
if (
|
|
362
|
-
|
|
363
|
-
|
|
370
|
+
if (settings?.secrets) {
|
|
371
|
+
validateSecretsLayer(settings.secrets);
|
|
372
|
+
}
|
|
373
|
+
for (const [name, env] of Object.entries(settings?.environments ?? {})) {
|
|
374
|
+
if (name === "inherit" || !isPlainObject(env) || !env.secrets)
|
|
375
|
+
continue;
|
|
376
|
+
validateSecretsLayer(env.secrets);
|
|
377
|
+
}
|
|
364
378
|
}
|
|
365
379
|
}
|
|
@@ -66,17 +66,18 @@ const VALID_RULE_TYPES = validValues([
|
|
|
66
66
|
]);
|
|
67
67
|
// Intentionally duplicated from merge.ts — validator should not depend on merge internals
|
|
68
68
|
const VALID_MERGE_STRATEGIES = ["replace", "append", "prepend", "merge"];
|
|
69
|
+
const DIRECTIVE_KEYS = new Set(["$arrayMerge", "$values", "$matchBy"]);
|
|
69
70
|
/**
|
|
70
|
-
* Checks if a value is an $arrayMerge directive:
|
|
71
|
+
* Checks if a value is an $arrayMerge directive:
|
|
72
|
+
* { $arrayMerge: strategy, $values: [...], $matchBy?: key }
|
|
71
73
|
*/
|
|
72
74
|
function isArrayMergeDirective(value) {
|
|
73
75
|
if (!isPlainObject(value))
|
|
74
76
|
return false;
|
|
75
|
-
|
|
76
|
-
return (keys.length === 2 &&
|
|
77
|
-
keys.every((k) => k === "$arrayMerge" || k === "$values") &&
|
|
77
|
+
return (Object.keys(value).every((k) => DIRECTIVE_KEYS.has(k)) &&
|
|
78
78
|
VALID_MERGE_STRATEGIES.includes(value.$arrayMerge) &&
|
|
79
|
-
Array.isArray(value.$values)
|
|
79
|
+
Array.isArray(value.$values) &&
|
|
80
|
+
(value.$matchBy === undefined || typeof value.$matchBy === "string"));
|
|
80
81
|
}
|
|
81
82
|
/**
|
|
82
83
|
* Extracts the $values array from a directive, or returns the value as-is if it's already an array.
|
|
@@ -260,6 +260,128 @@ function validateSettingsCollaborators(settings, context) {
|
|
|
260
260
|
}
|
|
261
261
|
}
|
|
262
262
|
}
|
|
263
|
+
const ENVIRONMENT_KEYS = new Set(["deploymentBranchPolicy", "secrets"]);
|
|
264
|
+
const BRANCH_POLICY_KEYS = new Set(["protectedBranches", "custom"]);
|
|
265
|
+
const BRANCH_PATTERN_KEYS = new Set(["type", "name"]);
|
|
266
|
+
const ENVIRONMENT_NAME_MAX_LENGTH = 255;
|
|
267
|
+
function assertKnownKeys(obj, allowed, context) {
|
|
268
|
+
for (const key of Object.keys(obj)) {
|
|
269
|
+
if (!allowed.has(key)) {
|
|
270
|
+
throw new ValidationError(`${context}: unknown key '${key}'`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function validateBranchPatterns(custom, context) {
|
|
275
|
+
if (!Array.isArray(custom) || custom.length === 0) {
|
|
276
|
+
throw new ValidationError(`${context}: custom must be a non-empty array`);
|
|
277
|
+
}
|
|
278
|
+
const seen = new Set();
|
|
279
|
+
custom.forEach((pattern, i) => {
|
|
280
|
+
const ctx = `${context}: custom[${i}]`;
|
|
281
|
+
if (!isPlainObject(pattern)) {
|
|
282
|
+
throw new ValidationError(`${ctx} must be an object`);
|
|
283
|
+
}
|
|
284
|
+
assertKnownKeys(pattern, BRANCH_PATTERN_KEYS, ctx);
|
|
285
|
+
if (pattern.type !== "branch" && pattern.type !== "tag") {
|
|
286
|
+
throw new ValidationError(`${ctx}.type must be 'branch' or 'tag'`);
|
|
287
|
+
}
|
|
288
|
+
if (typeof pattern.name !== "string" || pattern.name.trim() === "") {
|
|
289
|
+
throw new ValidationError(`${ctx}.name must be a non-empty string`);
|
|
290
|
+
}
|
|
291
|
+
const key = `${pattern.type}\u0000${pattern.name}`;
|
|
292
|
+
if (seen.has(key)) {
|
|
293
|
+
throw new ValidationError(`${context}: duplicate pattern ${pattern.type} '${pattern.name}'`);
|
|
294
|
+
}
|
|
295
|
+
seen.add(key);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
function validateDeploymentBranchPolicy(policy, context, isRoot) {
|
|
299
|
+
const ctx = `${context} deploymentBranchPolicy`;
|
|
300
|
+
if (policy === false) {
|
|
301
|
+
if (isRoot) {
|
|
302
|
+
throw new ValidationError(`${context}: deploymentBranchPolicy: false is not valid at root level. Omit it to let any branch deploy.`);
|
|
303
|
+
}
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (!isPlainObject(policy)) {
|
|
307
|
+
throw new ValidationError(`${ctx} must be an object`);
|
|
308
|
+
}
|
|
309
|
+
assertKnownKeys(policy, BRANCH_POLICY_KEYS, `${context}: deploymentBranchPolicy`);
|
|
310
|
+
const hasProtected = policy.protectedBranches !== undefined;
|
|
311
|
+
const hasCustom = policy.custom !== undefined;
|
|
312
|
+
if (hasProtected === hasCustom) {
|
|
313
|
+
throw new ValidationError(`${ctx} needs exactly one of 'protectedBranches: true' or 'custom'`);
|
|
314
|
+
}
|
|
315
|
+
if (hasProtected && policy.protectedBranches !== true) {
|
|
316
|
+
throw new ValidationError(`${ctx}: protectedBranches must be true. Omit deploymentBranchPolicy to let any branch deploy.`);
|
|
317
|
+
}
|
|
318
|
+
if (hasCustom) {
|
|
319
|
+
validateBranchPatterns(policy.custom, ctx);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function validateEnvironmentSecrets(secrets, context) {
|
|
323
|
+
if (!isPlainObject(secrets)) {
|
|
324
|
+
throw new ValidationError(`${context}: secrets must be an object`);
|
|
325
|
+
}
|
|
326
|
+
for (const [name, value] of Object.entries(secrets)) {
|
|
327
|
+
if (name === "deleteOrphaned" || name === "inherit") {
|
|
328
|
+
throw new ValidationError(`${context}: '${name}' is not supported in environment secrets`);
|
|
329
|
+
}
|
|
330
|
+
if (value === false)
|
|
331
|
+
continue;
|
|
332
|
+
if (!isPlainObject(value)) {
|
|
333
|
+
throw new ValidationError(`${context}: secret '${name}' must be an object with an 'env' field, or false to opt out`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
function validateSettingsEnvironments(settings, context, rootCtx) {
|
|
338
|
+
if (settings.environments === undefined)
|
|
339
|
+
return;
|
|
340
|
+
if (!isPlainObject(settings.environments)) {
|
|
341
|
+
throw new ValidationError(`${context}: environments must be an object`);
|
|
342
|
+
}
|
|
343
|
+
const seenNames = new Map();
|
|
344
|
+
for (const [name, env] of Object.entries(settings.environments)) {
|
|
345
|
+
if (name === "inherit") {
|
|
346
|
+
validateEnvironmentsInherit(env, context);
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
validateEnvironmentName(name, context, seenNames);
|
|
350
|
+
if (env !== false) {
|
|
351
|
+
validateEnvironmentEntry(env, `${context}: environment '${name}'`, !rootCtx);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
function validateEnvironmentsInherit(value, context) {
|
|
356
|
+
if (typeof value !== "boolean") {
|
|
357
|
+
throw new ValidationError(`${context}: environments.inherit must be a boolean`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function validateEnvironmentName(name, context, seenNames) {
|
|
361
|
+
if (name.trim() === "") {
|
|
362
|
+
throw new ValidationError(`${context}: environment name must not be blank`);
|
|
363
|
+
}
|
|
364
|
+
if (name.length > ENVIRONMENT_NAME_MAX_LENGTH) {
|
|
365
|
+
throw new ValidationError(`${context}: environment name '${name.slice(0, 40)}...' exceeds ${ENVIRONMENT_NAME_MAX_LENGTH} characters`);
|
|
366
|
+
}
|
|
367
|
+
const firstSpelling = seenNames.get(name.toLowerCase());
|
|
368
|
+
if (firstSpelling !== undefined) {
|
|
369
|
+
throw new ValidationError(`${context}: environment '${name}' duplicates '${firstSpelling}'; GitHub environment names ignore case`);
|
|
370
|
+
}
|
|
371
|
+
seenNames.set(name.toLowerCase(), name);
|
|
372
|
+
}
|
|
373
|
+
function validateEnvironmentEntry(env, envCtx, isRoot) {
|
|
374
|
+
if (!isPlainObject(env)) {
|
|
375
|
+
throw new ValidationError(`${envCtx} must be an object, or false to opt out`);
|
|
376
|
+
}
|
|
377
|
+
assertKnownKeys(env, ENVIRONMENT_KEYS, envCtx);
|
|
378
|
+
if (env.deploymentBranchPolicy !== undefined) {
|
|
379
|
+
validateDeploymentBranchPolicy(env.deploymentBranchPolicy, envCtx, isRoot);
|
|
380
|
+
}
|
|
381
|
+
if (env.secrets !== undefined) {
|
|
382
|
+
validateEnvironmentSecrets(env.secrets, envCtx);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
263
385
|
export function validateSettings(settings, context, rootCtx) {
|
|
264
386
|
if (!isPlainObject(settings)) {
|
|
265
387
|
throw new ValidationError(`${context}: settings must be an object`);
|
|
@@ -271,6 +393,7 @@ export function validateSettings(settings, context, rootCtx) {
|
|
|
271
393
|
validateSettingsCodeScanning(settings, context, rootCtx);
|
|
272
394
|
validateSettingsSecrets(settings, context);
|
|
273
395
|
validateSettingsCollaborators(settings, context);
|
|
396
|
+
validateSettingsEnvironments(settings, context, rootCtx);
|
|
274
397
|
}
|
|
275
398
|
export function enrichSettingsContext(rootCtx, settings) {
|
|
276
399
|
if (!settings)
|
|
@@ -30,7 +30,7 @@ export declare class GitHubLifecycleProvider implements IRepoLifecycleProvider {
|
|
|
30
30
|
*/
|
|
31
31
|
private isOrganization;
|
|
32
32
|
private assertGitHub;
|
|
33
|
-
private
|
|
33
|
+
private execRepoCreatingCommand;
|
|
34
34
|
private buildGhApiPrefix;
|
|
35
35
|
exists(params: LifecycleExistsParams): Promise<boolean>;
|
|
36
36
|
create(params: LifecycleCreateParams): Promise<void>;
|
|
@@ -11,14 +11,17 @@ const REPO_NOT_FOUND_PATTERNS = [
|
|
|
11
11
|
"Not Found",
|
|
12
12
|
"404",
|
|
13
13
|
];
|
|
14
|
+
function errorText(error) {
|
|
15
|
+
return (toErrorMessage(error) +
|
|
16
|
+
((error instanceof Error
|
|
17
|
+
? error.stderr
|
|
18
|
+
: undefined) ?? ""));
|
|
19
|
+
}
|
|
14
20
|
/**
|
|
15
21
|
* Check if an error indicates repo not found (vs network/auth error).
|
|
16
22
|
*/
|
|
17
23
|
function isRepoNotFoundError(error) {
|
|
18
|
-
const message =
|
|
19
|
-
((error instanceof Error
|
|
20
|
-
? error.stderr
|
|
21
|
-
: undefined) ?? "");
|
|
24
|
+
const message = errorText(error);
|
|
22
25
|
return REPO_NOT_FOUND_PATTERNS.some((pattern) => message.includes(pattern));
|
|
23
26
|
}
|
|
24
27
|
/**
|
|
@@ -41,13 +44,32 @@ const POST_CREATE_PERMANENT_PATTERNS = [
|
|
|
41
44
|
* Interval between fork readiness checks (2 seconds).
|
|
42
45
|
*/
|
|
43
46
|
const FORK_POLL_INTERVAL_MS = 2_000;
|
|
47
|
+
const CREATE_REPO_APP_PERMISSIONS = "Repository creation: Read and write";
|
|
48
|
+
const FORK_REPO_APP_PERMISSIONS = "Repository creation: Read and write, Administration: Read and write and Contents: Read, and be installed on the target account with access to all repositories and on the upstream account with access to the upstream repository";
|
|
49
|
+
const APP_PERMISSION_DENIED_PATTERNS = [
|
|
50
|
+
/\bHTTP\s*403\b/,
|
|
51
|
+
/not\s*accessible\s*by\s*integration/i,
|
|
52
|
+
];
|
|
53
|
+
const GITHUB_RATE_LIMIT_PATTERNS = [
|
|
54
|
+
/API rate limit/i,
|
|
55
|
+
/secondary rate limit/i,
|
|
56
|
+
/abuse detection/i,
|
|
57
|
+
/too many requests/i,
|
|
58
|
+
/\b429\b/,
|
|
59
|
+
];
|
|
44
60
|
function isInstallationToken(token) {
|
|
45
61
|
return token?.startsWith("ghs_") ?? false;
|
|
46
62
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
63
|
+
// GitHub reports a missing App permission on POST /user/repos as "403 Rate Limit Exceeded".
|
|
64
|
+
function isAppPermissionDenied(error) {
|
|
65
|
+
const text = errorText(error);
|
|
66
|
+
return (APP_PERMISSION_DENIED_PATTERNS.some((p) => p.test(text)) &&
|
|
67
|
+
!GITHUB_RATE_LIMIT_PATTERNS.some((p) => p.test(text)));
|
|
68
|
+
}
|
|
69
|
+
function appPermissionDeniedError(action, requiredPermissions, error) {
|
|
70
|
+
return new LifecycleError(`GitHub refused the App installation token while ${action}: ${toErrorMessage(error)}. ` +
|
|
71
|
+
`The GitHub App needs ${requiredPermissions}. ` +
|
|
72
|
+
`After changing App permissions, approve them on the installation.`, { cause: error });
|
|
51
73
|
}
|
|
52
74
|
function buildRepoCreateArgs(args, settings) {
|
|
53
75
|
if (settings?.visibility === "public") {
|
|
@@ -121,21 +143,22 @@ export class GitHubLifecycleProvider {
|
|
|
121
143
|
assertGitHub(repoInfo) {
|
|
122
144
|
assertGitHubRepo(repoInfo, "GitHubLifecycleProvider");
|
|
123
145
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
if (!isInstallationToken(token))
|
|
128
|
-
return;
|
|
129
|
-
let isOrg;
|
|
146
|
+
async execRepoCreatingCommand(args, token, permission, retryOptions = {}) {
|
|
147
|
+
const appPermissionDenied = (error) => isInstallationToken(token) && isAppPermissionDenied(error);
|
|
148
|
+
const tokenEnv = buildTokenEnv(token);
|
|
130
149
|
try {
|
|
131
|
-
|
|
150
|
+
return await withRetry(() => this.executor.exec("gh", args, this.cwd, { env: tokenEnv }), {
|
|
151
|
+
retries: this.retries,
|
|
152
|
+
...retryOptions,
|
|
153
|
+
abortOn: appPermissionDenied,
|
|
154
|
+
});
|
|
132
155
|
}
|
|
133
156
|
catch (error) {
|
|
134
|
-
|
|
135
|
-
|
|
157
|
+
if (appPermissionDenied(error)) {
|
|
158
|
+
throw appPermissionDeniedError(permission.action, permission.required, error);
|
|
159
|
+
}
|
|
160
|
+
throw error;
|
|
136
161
|
}
|
|
137
|
-
if (!isOrg)
|
|
138
|
-
throw personalAccountInstallationTokenError(repoInfo);
|
|
139
162
|
}
|
|
140
163
|
buildGhApiPrefix(repoInfo, token) {
|
|
141
164
|
const tokenEnv = buildTokenEnv(token);
|
|
@@ -167,19 +190,15 @@ export class GitHubLifecycleProvider {
|
|
|
167
190
|
async create(params) {
|
|
168
191
|
const { repo: repoInfo, settings, token } = params;
|
|
169
192
|
this.assertGitHub(repoInfo);
|
|
170
|
-
|
|
171
|
-
const
|
|
172
|
-
const args = [
|
|
173
|
-
"repo",
|
|
174
|
-
"create",
|
|
175
|
-
`${repoInfo.owner}/${repoInfo.repo}`,
|
|
176
|
-
];
|
|
193
|
+
const repoSlug = `${repoInfo.owner}/${repoInfo.repo}`;
|
|
194
|
+
const args = ["repo", "create", repoSlug];
|
|
177
195
|
buildRepoCreateArgs(args, settings);
|
|
178
196
|
// Add --add-readme to establish the default branch via an initial commit.
|
|
179
197
|
// This avoids empty repos where HEAD doesn't resolve.
|
|
180
198
|
args.push("--add-readme");
|
|
181
|
-
await
|
|
182
|
-
|
|
199
|
+
await this.execRepoCreatingCommand(args, token, {
|
|
200
|
+
action: `creating ${repoSlug}`,
|
|
201
|
+
required: CREATE_REPO_APP_PERMISSIONS,
|
|
183
202
|
});
|
|
184
203
|
if (settings?.defaultBranch) {
|
|
185
204
|
const { tokenEnv: branchTokenEnv, baseArgs, apiPath, } = this.buildGhApiPrefix(repoInfo, token);
|
|
@@ -208,17 +227,14 @@ export class GitHubLifecycleProvider {
|
|
|
208
227
|
`The upstream and target owners must be different.`);
|
|
209
228
|
}
|
|
210
229
|
const isOrg = await this.isOrganization(target.owner, target, token);
|
|
211
|
-
if (!isOrg && isInstallationToken(token)) {
|
|
212
|
-
throw personalAccountInstallationTokenError(target);
|
|
213
|
-
}
|
|
214
|
-
const tokenEnv = buildTokenEnv(token);
|
|
215
230
|
const forkArgs = ["repo", "fork", `${upstream.owner}/${upstream.repo}`];
|
|
216
231
|
if (isOrg) {
|
|
217
232
|
forkArgs.push("--org", target.owner);
|
|
218
233
|
}
|
|
219
234
|
forkArgs.push("--fork-name", target.repo, "--clone=false");
|
|
220
|
-
await
|
|
221
|
-
|
|
235
|
+
await this.execRepoCreatingCommand(forkArgs, token, {
|
|
236
|
+
action: `forking ${upstream.owner}/${upstream.repo} to ${target.owner}/${target.repo}`,
|
|
237
|
+
required: FORK_REPO_APP_PERMISSIONS,
|
|
222
238
|
});
|
|
223
239
|
// GitHub forks are async - wait for the fork to be ready for git operations
|
|
224
240
|
await this.waitForForkReady(target, {
|
|
@@ -280,7 +296,6 @@ export class GitHubLifecycleProvider {
|
|
|
280
296
|
async receiveMigration(params) {
|
|
281
297
|
const { repo: repoInfo, sourceDir, settings, token } = params;
|
|
282
298
|
this.assertGitHub(repoInfo);
|
|
283
|
-
await this.assertTokenCanCreateRepo(repoInfo, token);
|
|
284
299
|
await this.removeOriginRemote(sourceDir);
|
|
285
300
|
await this.cleanNonStandardRefs(sourceDir);
|
|
286
301
|
await this.renameMirrorDefaultBranch(sourceDir, settings?.defaultBranch);
|
|
@@ -335,8 +350,10 @@ export class GitHubLifecycleProvider {
|
|
|
335
350
|
const createArgs = ["repo", "create", repoSlug];
|
|
336
351
|
buildRepoCreateArgs(createArgs, settings);
|
|
337
352
|
try {
|
|
338
|
-
await
|
|
339
|
-
|
|
353
|
+
await this.execRepoCreatingCommand(createArgs, token, {
|
|
354
|
+
action: `creating ${repoSlug}`,
|
|
355
|
+
required: CREATE_REPO_APP_PERMISSIONS,
|
|
356
|
+
}, {
|
|
340
357
|
permanentErrorPatterns: POST_CREATE_PERMANENT_PATTERNS,
|
|
341
358
|
log: this.log
|
|
342
359
|
? { info: (m) => this.log.info(m) }
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PropertyDiff, ActiveAction, SecretsPlanEntry } from "../settings/index.js";
|
|
1
|
+
import type { PropertyDiff, ActiveAction, SecretsPlanEntry, EnvironmentsPlanEntry } from "../settings/index.js";
|
|
2
2
|
import type { Ruleset, Label } from "../config/index.js";
|
|
3
3
|
import type { DebugLog } from "../shared/logger.js";
|
|
4
4
|
export interface SettingsReport {
|
|
@@ -33,6 +33,10 @@ export interface SettingsReport {
|
|
|
33
33
|
update: number;
|
|
34
34
|
delete: number;
|
|
35
35
|
};
|
|
36
|
+
environments?: {
|
|
37
|
+
create: number;
|
|
38
|
+
update: number;
|
|
39
|
+
};
|
|
36
40
|
};
|
|
37
41
|
}
|
|
38
42
|
export interface RepoChanges {
|
|
@@ -51,6 +55,7 @@ export interface RepoChanges {
|
|
|
51
55
|
name: string;
|
|
52
56
|
action: "create" | "delete";
|
|
53
57
|
}[];
|
|
58
|
+
environments?: EnvironmentsPlanEntry[];
|
|
54
59
|
error?: string;
|
|
55
60
|
}
|
|
56
61
|
export declare function hasRepoSettingsChanges(repo: RepoChanges): boolean;
|