@aspruyt/xfg 8.1.2 → 8.2.0

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.
@@ -8,7 +8,7 @@ export function buildSettingsReport(results) {
8
8
  variables: { create: 0, update: 0, delete: 0 },
9
9
  secrets: { create: 0, update: 0, delete: 0 },
10
10
  collaborators: { create: 0, update: 0, delete: 0 },
11
- environments: { create: 0, update: 0 },
11
+ environments: { create: 0, update: 0, delete: 0 },
12
12
  };
13
13
  for (const result of results) {
14
14
  const repoChanges = {
@@ -1,4 +1,4 @@
1
- export type { PRMergeOptions, RepoPROptions, AiConfig, AiProvider, ResolvedAiConfig, MergeMode, MergeStrategy, BypassActor, BypassMode, StatusCheckConfig, CodeScanningTool, PullRequestRuleParameters, RulesetRule, Ruleset, GitHubRepoSettings, RepoVisibility, SquashMergeCommitTitle, SquashMergeCommitMessage, MergeCommitTitle, MergeCommitMessage, Label, CodeScanningSettings, CodeScanningState, CodeScanningQuerySuite, CodeScanningLanguage, DeploymentBranchPatternType, DeploymentBranchPattern, DeploymentBranchPolicy, EnvironmentConfig, RawEnvironmentConfig, RepoSettings, RawFileConfig, RawRepoFileOverride, RawGroupConfig, SecretConfig, CollaboratorsConfig, RawCollaboratorsConfig, SecretsConfig, RawRootSettings, RawRepoSettings, RawRepoConfig, RawConfig, RawConditionalGroupWhen, RawConditionalGroupConfig, RepoConfig, Config, FileContent, ContentValue, } from "./types.js";
1
+ export type { PRMergeOptions, RepoPROptions, AiConfig, AiProvider, ResolvedAiConfig, MergeMode, MergeStrategy, BypassActor, BypassMode, StatusCheckConfig, CodeScanningTool, PullRequestRuleParameters, RulesetRule, Ruleset, GitHubRepoSettings, RepoVisibility, SquashMergeCommitTitle, SquashMergeCommitMessage, MergeCommitTitle, MergeCommitMessage, Label, CodeScanningSettings, CodeScanningState, CodeScanningQuerySuite, CodeScanningLanguage, DeploymentBranchPatternType, DeploymentBranchPattern, DeploymentBranchPolicy, EnvironmentConfig, EnvironmentsConfig, RawEnvironmentConfig, RepoSettings, RawFileConfig, RawRepoFileOverride, RawGroupConfig, SecretConfig, CollaboratorsConfig, RawCollaboratorsConfig, SecretsConfig, RawRootSettings, RawRepoSettings, RawRepoConfig, RawConfig, RawConditionalGroupWhen, RawConditionalGroupConfig, RepoConfig, Config, FileContent, ContentValue, } from "./types.js";
2
2
  export { RULESET_COMPARABLE_FIELDS } from "./types.js";
3
3
  export { loadRawConfig, loadConfig, normalizeConfig } from "./loader.js";
4
4
  export { convertContentToString } from "./formatter.js";
@@ -106,7 +106,6 @@ function mergeRuleset(name, root, perRepo) {
106
106
  return structuredClone(perRepo ?? {});
107
107
  if (!perRepo)
108
108
  return structuredClone(root);
109
- // Deep merge using the existing merge utility with replace strategy.
110
109
  // deepMerge operates on Record<string, unknown> — the cast is safe because
111
110
  // merging two Ruleset-shaped objects preserves the Ruleset structure.
112
111
  const ctx = createMergeContext("replace", rulesetLocation(name));
@@ -244,9 +243,9 @@ function finalizeEnvironment(env) {
244
243
  if (env.deploymentBranchPolicy) {
245
244
  result.deploymentBranchPolicy = structuredClone(env.deploymentBranchPolicy);
246
245
  }
247
- const secrets = Object.entries(env.secrets ?? {}).filter(([, value]) => value !== false);
248
- if (secrets.length > 0) {
249
- result.secrets = Object.fromEntries(secrets);
246
+ const secrets = dropEntryMapIfEmpty(mergeEntryMapLayer(undefined, env.secrets));
247
+ if (secrets) {
248
+ result.secrets = secrets;
250
249
  }
251
250
  return result;
252
251
  }
@@ -254,31 +253,44 @@ function finalizeEnvironment(env) {
254
253
  function isMergeableEntry(entry) {
255
254
  return entry === false || (typeof entry === "object" && entry !== null);
256
255
  }
257
- // GitHub environment names are case-insensitive; base entries take the overlay's spelling so they merge.
256
+ /** `deleteOrphaned` resolves innermost-wins like the entry maps; `inherit: false` never clears it. */
258
257
  function mergeEnvironmentEntries(base, overlay) {
258
+ const { deleteOrphaned: baseDeleteOrphaned, ...baseEnvs } = base ?? {};
259
+ const { deleteOrphaned: overlayDeleteOrphaned, ...overlayEnvs } = overlay;
259
260
  const overlayNames = new Map();
260
- for (const [name, entry] of Object.entries(overlay)) {
261
+ for (const [name, entry] of Object.entries(overlayEnvs)) {
261
262
  if (name !== "inherit" && isMergeableEntry(entry)) {
262
263
  overlayNames.set(name.toLowerCase(), name);
263
264
  }
264
265
  }
265
266
  const rekeyed = {};
266
- for (const [name, env] of Object.entries(base ?? {})) {
267
+ for (const [name, env] of Object.entries(baseEnvs)) {
267
268
  rekeyed[overlayNames.get(name.toLowerCase()) ?? name] = env;
268
269
  }
269
- return mergeNamedEntries(rekeyed, overlay, mergeEnvironmentLayer);
270
+ const result = mergeNamedEntries(rekeyed, overlayEnvs, mergeEnvironmentLayer);
271
+ const deleteOrphaned = overlayDeleteOrphaned ?? baseDeleteOrphaned;
272
+ if (deleteOrphaned !== undefined) {
273
+ result.deleteOrphaned = deleteOrphaned;
274
+ }
275
+ return result;
270
276
  }
271
277
  function mergeEnvironments(root, perRepo) {
272
278
  if (!root && !perRepo)
273
279
  return undefined;
274
- const merged = mergeEnvironmentEntries(root, perRepo ?? {});
280
+ const { deleteOrphaned, ...merged } = mergeEnvironmentEntries(root, perRepo ?? {});
275
281
  const result = {};
276
282
  for (const [name, env] of Object.entries(merged)) {
277
283
  if (env === false)
278
284
  continue;
279
285
  result[name] = finalizeEnvironment(env);
280
286
  }
281
- return Object.keys(result).length > 0 ? result : undefined;
287
+ if (Object.keys(result).length === 0 && deleteOrphaned !== true) {
288
+ return undefined;
289
+ }
290
+ if (deleteOrphaned !== undefined) {
291
+ result.deleteOrphaned = deleteOrphaned;
292
+ }
293
+ return result;
282
294
  }
283
295
  /**
284
296
  * Merges settings: per-repo settings deep merge with root settings.
@@ -301,18 +301,28 @@ export interface DeploymentBranchPattern {
301
301
  export interface DeploymentBranchPolicy {
302
302
  protectedBranches?: boolean;
303
303
  custom?: DeploymentBranchPattern[];
304
+ /** Delete patterns on GitHub that are not in `custom` */
305
+ deleteOrphaned?: boolean;
304
306
  }
305
307
  export interface EnvironmentConfig {
306
308
  /** Omitted: any branch can deploy */
307
309
  deploymentBranchPolicy?: DeploymentBranchPolicy;
308
310
  /** Environment secrets keyed by name; only `xfg secrets sync` writes them */
309
- secrets?: Record<string, SecretConfig>;
311
+ secrets?: Record<string, SecretConfig> & {
312
+ deleteOrphaned?: boolean;
313
+ };
310
314
  }
311
315
  export interface RawEnvironmentConfig {
312
316
  /** `false` clears an inherited policy so any branch can deploy */
313
317
  deploymentBranchPolicy?: DeploymentBranchPolicy | false;
314
- secrets?: Record<string, SecretConfig | false>;
318
+ secrets?: Record<string, SecretConfig | false> & {
319
+ deleteOrphaned?: boolean;
320
+ };
315
321
  }
322
+ /** Environments keyed by name, plus the `deleteOrphaned` peer key. */
323
+ export type EnvironmentsConfig = Record<string, EnvironmentConfig> & {
324
+ deleteOrphaned?: boolean;
325
+ };
316
326
  export interface CollaboratorsConfig {
317
327
  /** GitHub usernames granted write access (personal repos only) */
318
328
  users?: string[];
@@ -342,7 +352,7 @@ export interface RepoSettings {
342
352
  /** Direct collaborators on personal (user-owned) repos */
343
353
  collaborators?: CollaboratorsConfig;
344
354
  /** GitHub deployment environments keyed by name */
345
- environments?: Record<string, EnvironmentConfig>;
355
+ environments?: EnvironmentsConfig;
346
356
  deleteOrphaned?: boolean;
347
357
  }
348
358
  export type ContentValue = Record<string, unknown> | string | string[];
@@ -408,7 +418,9 @@ export interface RawRootSettings {
408
418
  };
409
419
  secrets?: SecretsConfig;
410
420
  collaborators?: CollaboratorsConfig;
411
- environments?: Record<string, RawEnvironmentConfig | false>;
421
+ environments?: Record<string, RawEnvironmentConfig | false> & {
422
+ deleteOrphaned?: boolean;
423
+ };
412
424
  deleteOrphaned?: boolean;
413
425
  }
414
426
  export interface RawRepoSettings {
@@ -430,6 +442,7 @@ export interface RawRepoSettings {
430
442
  collaborators?: RawCollaboratorsConfig;
431
443
  environments?: Record<string, RawEnvironmentConfig | false> & {
432
444
  inherit?: boolean;
445
+ deleteOrphaned?: boolean;
433
446
  };
434
447
  deleteOrphaned?: boolean;
435
448
  }
@@ -306,7 +306,8 @@ export function hasActionableSettings(settings) {
306
306
  }
307
307
  // An environment holding only secrets still needs `xfg sync` to create it.
308
308
  if (settings.environments &&
309
- Object.entries(settings.environments).some(([name, env]) => name !== "inherit" && isPlainObject(env))) {
309
+ (settings.environments.deleteOrphaned === true ||
310
+ Object.entries(settings.environments).some(([name, env]) => name !== "inherit" && isPlainObject(env)))) {
310
311
  return true;
311
312
  }
312
313
  // Secrets are deliberately absent: `xfg sync` must never process them.
@@ -261,7 +261,11 @@ function validateSettingsCollaborators(settings, context) {
261
261
  }
262
262
  }
263
263
  const ENVIRONMENT_KEYS = new Set(["deploymentBranchPolicy", "secrets"]);
264
- const BRANCH_POLICY_KEYS = new Set(["protectedBranches", "custom"]);
264
+ const BRANCH_POLICY_KEYS = new Set([
265
+ "protectedBranches",
266
+ "custom",
267
+ "deleteOrphaned",
268
+ ]);
265
269
  const BRANCH_PATTERN_KEYS = new Set(["type", "name"]);
266
270
  const ENVIRONMENT_NAME_MAX_LENGTH = 255;
267
271
  function assertKnownKeys(obj, allowed, context) {
@@ -318,15 +322,29 @@ function validateDeploymentBranchPolicy(policy, context, isRoot) {
318
322
  if (hasCustom) {
319
323
  validateBranchPatterns(policy.custom, ctx);
320
324
  }
325
+ if (policy.deleteOrphaned !== undefined) {
326
+ if (typeof policy.deleteOrphaned !== "boolean") {
327
+ throw new ValidationError(`${context}: deploymentBranchPolicy: deleteOrphaned must be a boolean`);
328
+ }
329
+ if (!hasCustom) {
330
+ throw new ValidationError(`${context}: deploymentBranchPolicy: deleteOrphaned only applies to a 'custom' policy`);
331
+ }
332
+ }
321
333
  }
322
334
  function validateEnvironmentSecrets(secrets, context) {
323
335
  if (!isPlainObject(secrets)) {
324
336
  throw new ValidationError(`${context}: secrets must be an object`);
325
337
  }
326
338
  for (const [name, value] of Object.entries(secrets)) {
327
- if (name === "deleteOrphaned" || name === "inherit") {
339
+ if (name === "inherit") {
328
340
  throw new ValidationError(`${context}: '${name}' is not supported in environment secrets`);
329
341
  }
342
+ if (name === "deleteOrphaned") {
343
+ if (typeof value !== "boolean") {
344
+ throw new ValidationError(`${context}: secrets.deleteOrphaned must be a boolean`);
345
+ }
346
+ continue;
347
+ }
330
348
  if (value === false)
331
349
  continue;
332
350
  if (!isPlainObject(value)) {
@@ -342,8 +360,8 @@ function validateSettingsEnvironments(settings, context, rootCtx) {
342
360
  }
343
361
  const seenNames = new Map();
344
362
  for (const [name, env] of Object.entries(settings.environments)) {
345
- if (name === "inherit") {
346
- validateEnvironmentsInherit(env, context);
363
+ if (name === "inherit" || name === "deleteOrphaned") {
364
+ validateEnvironmentsFlag(name, env, context);
347
365
  continue;
348
366
  }
349
367
  validateEnvironmentName(name, context, seenNames);
@@ -352,9 +370,9 @@ function validateSettingsEnvironments(settings, context, rootCtx) {
352
370
  }
353
371
  }
354
372
  }
355
- function validateEnvironmentsInherit(value, context) {
373
+ function validateEnvironmentsFlag(key, value, context) {
356
374
  if (typeof value !== "boolean") {
357
- throw new ValidationError(`${context}: environments.inherit must be a boolean`);
375
+ throw new ValidationError(`${context}: environments.${key} must be a boolean`);
358
376
  }
359
377
  }
360
378
  function validateEnvironmentName(name, context, seenNames) {
@@ -36,6 +36,7 @@ export interface SettingsReport {
36
36
  environments?: {
37
37
  create: number;
38
38
  update: number;
39
+ delete: number;
39
40
  };
40
41
  };
41
42
  }
@@ -140,12 +140,17 @@ const DIFF_SIGN = {
140
140
  function renderEnvironmentLines(entry) {
141
141
  const sign = DIFF_SIGN[entry.action];
142
142
  const lines = [`${sign} environment ${quoted(entry.name)}`];
143
+ if (entry.action === "delete")
144
+ return lines;
143
145
  const policy = formatPolicyLine(entry);
144
146
  if (policy)
145
147
  lines.push(`${sign} ${policy}`);
146
148
  for (const pattern of entry.addedPatterns) {
147
149
  lines.push(`+ ${formatPatternLabel(pattern)}`);
148
150
  }
151
+ for (const pattern of entry.removedPatterns) {
152
+ lines.push(`- ${formatPatternLabel(pattern)}`);
153
+ }
149
154
  return lines;
150
155
  }
151
156
  export function renderRepoSettingsDiffLines(repo, diffLines) {
@@ -1,5 +1,5 @@
1
1
  import type { DeploymentBranchPattern, DeploymentBranchPolicy, EnvironmentConfig } from "../../config/index.js";
2
- import type { GitHubDeploymentBranchPolicy, GitHubEnvironment } from "./types.js";
2
+ import type { ExistingBranchPattern, GitHubDeploymentBranchPolicy, GitHubEnvironment } from "./types.js";
3
3
  export type BranchPolicyKind = "all" | "protected" | "custom";
4
4
  export type EnvironmentAction = "create" | "update" | "unchanged";
5
5
  export interface EnvironmentChange {
@@ -10,13 +10,24 @@ export interface EnvironmentChange {
10
10
  desiredKind: BranchPolicyKind;
11
11
  putPolicy: boolean;
12
12
  missingPatterns: DeploymentBranchPattern[];
13
- unmanagedPatterns: DeploymentBranchPattern[];
13
+ unmanagedPatterns: ExistingBranchPattern[];
14
+ orphanPatterns: ExistingBranchPattern[];
14
15
  /** False when the existing patterns were not read, so missingPatterns may hold some that exist */
15
16
  patternsKnown: boolean;
16
17
  }
18
+ export interface EnvironmentDeletion {
19
+ action: "delete";
20
+ name: string;
21
+ }
22
+ export interface DiffEnvironmentsOptions {
23
+ /** Skip pattern deletions even where the policy sets deleteOrphaned */
24
+ noDelete?: boolean;
25
+ }
17
26
  export declare function currentPolicyKind(policy: GitHubDeploymentBranchPolicy | null): BranchPolicyKind;
18
27
  export declare function desiredPolicyKind(policy: DeploymentBranchPolicy | undefined): BranchPolicyKind;
19
28
  export declare function toGitHubPolicy(kind: BranchPolicyKind): GitHubDeploymentBranchPolicy | null;
20
29
  /** Existing environments whose patterns must be read before diffing. */
21
30
  export declare function needsPatternLookup(desired: Record<string, EnvironmentConfig>, current: GitHubEnvironment[]): string[];
22
- export declare function diffEnvironments(desired: Record<string, EnvironmentConfig>, current: GitHubEnvironment[], currentPatterns: ReadonlyMap<string, DeploymentBranchPattern[]>): EnvironmentChange[];
31
+ export declare function diffEnvironments(desired: Record<string, EnvironmentConfig>, current: GitHubEnvironment[], currentPatterns: ReadonlyMap<string, ExistingBranchPattern[]>, options?: DiffEnvironmentsOptions): EnvironmentChange[];
32
+ /** Environments on GitHub with no config entry, matched ignoring case. */
33
+ export declare function orphanEnvironments(desired: Record<string, EnvironmentConfig>, current: GitHubEnvironment[]): EnvironmentDeletion[];
@@ -40,39 +40,54 @@ export function needsPatternLookup(desired, current) {
40
40
  function patternKey(p) {
41
41
  return `${p.type}\u0000${p.name}`;
42
42
  }
43
- export function diffEnvironments(desired, current, currentPatterns) {
44
- const existing = indexByName(current);
45
- return Object.entries(desired).map(([configName, config]) => {
46
- const desiredKind = desiredPolicyKind(config.deploymentBranchPolicy);
47
- const wanted = config.deploymentBranchPolicy?.custom ?? [];
48
- const env = existing.get(configName.toLowerCase());
49
- if (!env) {
50
- return {
51
- action: "create",
52
- name: configName,
53
- desiredKind,
54
- putPolicy: true,
55
- missingPatterns: [...wanted],
56
- unmanagedPatterns: [],
57
- patternsKnown: true,
58
- };
59
- }
60
- const currentKind = currentPolicyKind(env.deployment_branch_policy);
61
- const putPolicy = currentKind !== desiredKind;
62
- const known = currentPatterns.get(env.name.toLowerCase());
63
- const have = new Set((known ?? []).map(patternKey));
64
- const want = new Set(wanted.map(patternKey));
65
- const missingPatterns = wanted.filter((p) => !have.has(patternKey(p)));
66
- const unmanagedPatterns = (known ?? []).filter((p) => !want.has(patternKey(p)));
43
+ function diffEnvironment(configName, config, env, currentPatterns, noDelete) {
44
+ const desiredKind = desiredPolicyKind(config.deploymentBranchPolicy);
45
+ const wanted = config.deploymentBranchPolicy?.custom ?? [];
46
+ if (!env) {
67
47
  return {
68
- action: putPolicy || missingPatterns.length > 0 ? "update" : "unchanged",
69
- name: env.name,
70
- currentKind,
48
+ action: "create",
49
+ name: configName,
71
50
  desiredKind,
72
- putPolicy,
73
- missingPatterns,
74
- unmanagedPatterns: desiredKind === "custom" ? unmanagedPatterns : [],
75
- patternsKnown: desiredKind !== "custom" || known !== undefined,
51
+ putPolicy: true,
52
+ missingPatterns: [...wanted],
53
+ unmanagedPatterns: [],
54
+ orphanPatterns: [],
55
+ patternsKnown: true,
76
56
  };
77
- });
57
+ }
58
+ const currentKind = currentPolicyKind(env.deployment_branch_policy);
59
+ const putPolicy = currentKind !== desiredKind;
60
+ const known = currentPatterns.get(env.name.toLowerCase());
61
+ const have = new Set((known ?? []).map(patternKey));
62
+ const want = new Set(wanted.map(patternKey));
63
+ const missingPatterns = wanted.filter((p) => !have.has(patternKey(p)));
64
+ const extra = desiredKind === "custom"
65
+ ? (known ?? []).filter((p) => !want.has(patternKey(p)))
66
+ : [];
67
+ const deleteExtra = config.deploymentBranchPolicy?.deleteOrphaned === true && !noDelete;
68
+ const orphanPatterns = deleteExtra ? extra : [];
69
+ return {
70
+ action: putPolicy || missingPatterns.length > 0 || orphanPatterns.length > 0
71
+ ? "update"
72
+ : "unchanged",
73
+ name: env.name,
74
+ currentKind,
75
+ desiredKind,
76
+ putPolicy,
77
+ missingPatterns,
78
+ unmanagedPatterns: deleteExtra ? [] : extra,
79
+ orphanPatterns,
80
+ patternsKnown: desiredKind !== "custom" || known !== undefined,
81
+ };
82
+ }
83
+ export function diffEnvironments(desired, current, currentPatterns, options = {}) {
84
+ const existing = indexByName(current);
85
+ return Object.entries(desired).map(([configName, config]) => diffEnvironment(configName, config, existing.get(configName.toLowerCase()), currentPatterns, options.noDelete ?? false));
86
+ }
87
+ /** Environments on GitHub with no config entry, matched ignoring case. */
88
+ export function orphanEnvironments(desired, current) {
89
+ const wanted = new Set(Object.keys(desired).map((n) => n.toLowerCase()));
90
+ return current
91
+ .filter((env) => !wanted.has(env.name.toLowerCase()))
92
+ .map((env) => ({ action: "delete", name: env.name }));
78
93
  }
@@ -1,17 +1,23 @@
1
1
  import type { DeploymentBranchPattern } from "../../config/index.js";
2
- import type { BranchPolicyKind, EnvironmentChange } from "./diff.js";
3
- export interface EnvironmentsPlanEntry {
2
+ import type { BranchPolicyKind, EnvironmentChange, EnvironmentDeletion } from "./diff.js";
3
+ export interface EnvironmentsUpsertEntry {
4
4
  name: string;
5
5
  action: "create" | "update";
6
6
  /** Set on updates that change the policy kind */
7
7
  currentKind?: BranchPolicyKind;
8
8
  desiredKind: BranchPolicyKind;
9
9
  addedPatterns: DeploymentBranchPattern[];
10
+ removedPatterns: DeploymentBranchPattern[];
10
11
  }
12
+ export interface EnvironmentsDeleteEntry {
13
+ name: string;
14
+ action: "delete";
15
+ }
16
+ export type EnvironmentsPlanEntry = EnvironmentsUpsertEntry | EnvironmentsDeleteEntry;
11
17
  export interface EnvironmentsPlanResult {
12
18
  lines: string[];
13
19
  entries: EnvironmentsPlanEntry[];
14
20
  }
15
- export declare function formatPolicyLine(entry: EnvironmentsPlanEntry): string | null;
21
+ export declare function formatPolicyLine(entry: EnvironmentsUpsertEntry): string | null;
16
22
  export declare function formatPatternLabel(pattern: DeploymentBranchPattern): string;
17
- export declare function formatEnvironmentsPlan(changes: EnvironmentChange[], dryRun: boolean): EnvironmentsPlanResult;
23
+ export declare function formatEnvironmentsPlan(changes: EnvironmentChange[], dryRun: boolean, deletions?: EnvironmentDeletion[]): EnvironmentsPlanResult;
@@ -10,6 +10,10 @@ function toEntry(change) {
10
10
  action: change.action,
11
11
  desiredKind: change.desiredKind,
12
12
  addedPatterns: change.missingPatterns,
13
+ removedPatterns: change.orphanPatterns.map(({ type, name }) => ({
14
+ type,
15
+ name,
16
+ })),
13
17
  };
14
18
  if (change.action === "update" && change.putPolicy) {
15
19
  entry.currentKind = change.currentKind;
@@ -29,6 +33,9 @@ export function formatPatternLabel(pattern) {
29
33
  return `${pattern.type} ${quoted(pattern.name)}`;
30
34
  }
31
35
  function formatEntry(entry) {
36
+ if (entry.action === "delete") {
37
+ return [chalk.red(` - environment ${quoted(entry.name)}`)];
38
+ }
32
39
  const color = entry.action === "create" ? chalk.green : chalk.yellow;
33
40
  const sign = entry.action === "create" ? "+" : "~";
34
41
  const lines = [color(` ${sign} environment ${quoted(entry.name)}`)];
@@ -38,16 +45,23 @@ function formatEntry(entry) {
38
45
  for (const pattern of entry.addedPatterns) {
39
46
  lines.push(chalk.green(` + ${formatPatternLabel(pattern)}`));
40
47
  }
48
+ for (const pattern of entry.removedPatterns) {
49
+ lines.push(chalk.red(` - ${formatPatternLabel(pattern)}`));
50
+ }
41
51
  return lines;
42
52
  }
43
- function actionRank(entry) {
44
- return entry.action === "create" ? 0 : 1;
45
- }
46
- export function formatEnvironmentsPlan(changes, dryRun) {
47
- const entries = changes
48
- .map(toEntry)
49
- .filter((e) => e !== null)
50
- .sort((a, b) => actionRank(a) - actionRank(b));
53
+ const ACTION_RANK = {
54
+ create: 0,
55
+ update: 1,
56
+ delete: 2,
57
+ };
58
+ export function formatEnvironmentsPlan(changes, dryRun, deletions = []) {
59
+ const entries = [
60
+ ...changes
61
+ .map(toEntry)
62
+ .filter((e) => e !== null),
63
+ ...deletions.map(({ name }) => ({ name, action: "delete" })),
64
+ ].sort((a, b) => ACTION_RANK[a.action] - ACTION_RANK[b.action]);
51
65
  const summary = formatActionCountEntry("environment", "environments", countActions(entries), dryRun);
52
66
  if (!summary) {
53
67
  return { lines: [], entries };
@@ -3,7 +3,7 @@ import { type RepoInfo } from "../../repo/index.js";
3
3
  import { type GhApiOptions } from "../../shared/gh-api-utils.js";
4
4
  import type { DeploymentBranchPattern } from "../../config/index.js";
5
5
  import type { GitHubPublicKey, GitHubSecret } from "../secrets/types.js";
6
- import type { GitHubDeploymentBranchPolicy, GitHubEnvironment, IEnvironmentSecretsStrategy, IEnvironmentsStrategy } from "./types.js";
6
+ import type { ExistingBranchPattern, GitHubDeploymentBranchPolicy, GitHubEnvironment, IEnvironmentSecretsStrategy, IEnvironmentsStrategy } from "./types.js";
7
7
  interface GitHubEnvironmentsStrategyOptions {
8
8
  retries?: number;
9
9
  cwd: string;
@@ -14,10 +14,13 @@ export declare class GitHubEnvironmentsStrategy implements IEnvironmentsStrategy
14
14
  private base;
15
15
  list(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubEnvironment[]>;
16
16
  createOrUpdate(repoInfo: RepoInfo, name: string, policy: GitHubDeploymentBranchPolicy | null, options?: GhApiOptions): Promise<void>;
17
- listBranchPolicies(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<DeploymentBranchPattern[]>;
17
+ delete(repoInfo: RepoInfo, name: string, options?: GhApiOptions): Promise<void>;
18
+ listBranchPolicies(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<ExistingBranchPattern[]>;
19
+ deleteBranchPolicy(repoInfo: RepoInfo, environment: string, id: number, options?: GhApiOptions): Promise<void>;
18
20
  createBranchPolicy(repoInfo: RepoInfo, environment: string, pattern: DeploymentBranchPattern, options?: GhApiOptions): Promise<void>;
19
21
  listSecrets(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubSecret[]>;
20
22
  getSecretsPublicKey(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubPublicKey>;
21
23
  upsertSecret(repoInfo: RepoInfo, environment: string, name: string, encryptedValue: string, keyId: string, options?: GhApiOptions): Promise<void>;
24
+ deleteSecret(repoInfo: RepoInfo, environment: string, name: string, options?: GhApiOptions): Promise<void>;
22
25
  }
23
26
  export {};
@@ -28,14 +28,21 @@ export class GitHubEnvironmentsStrategy {
28
28
  options,
29
29
  });
30
30
  }
31
+ async delete(repoInfo, name, options) {
32
+ await this.api.call("DELETE", this.base(repoInfo, name), { options });
33
+ }
31
34
  async listBranchPolicies(repoInfo, environment, options) {
32
35
  const result = await this.api.call("GET", `${this.base(repoInfo, environment)}/deployment-branch-policies?per_page=100`, { options, paginate: true });
33
36
  const response = parseApiJson(result, "deployment branch policies response");
34
37
  return (response.branch_policies ?? []).map((p) => ({
38
+ id: p.id,
35
39
  type: p.type ?? "branch",
36
40
  name: p.name,
37
41
  }));
38
42
  }
43
+ async deleteBranchPolicy(repoInfo, environment, id, options) {
44
+ await this.api.call("DELETE", `${this.base(repoInfo, environment)}/deployment-branch-policies/${id}`, { options });
45
+ }
39
46
  async createBranchPolicy(repoInfo, environment, pattern, options) {
40
47
  await this.api.call("POST", `${this.base(repoInfo, environment)}/deployment-branch-policies`, { payload: { name: pattern.name, type: pattern.type }, options });
41
48
  }
@@ -51,4 +58,7 @@ export class GitHubEnvironmentsStrategy {
51
58
  async upsertSecret(repoInfo, environment, name, encryptedValue, keyId, options) {
52
59
  await this.api.call("PUT", `${this.base(repoInfo, environment)}/secrets/${encodeURIComponent(name)}`, { payload: { encrypted_value: encryptedValue, key_id: keyId }, options });
53
60
  }
61
+ async deleteSecret(repoInfo, environment, name, options) {
62
+ await this.api.call("DELETE", `${this.base(repoInfo, environment)}/secrets/${encodeURIComponent(name)}`, { options });
63
+ }
54
64
  }
@@ -1,5 +1,5 @@
1
- export { type BranchPolicyKind, type EnvironmentChange, type EnvironmentAction, } from "./diff.js";
1
+ export { type BranchPolicyKind, type EnvironmentChange, type EnvironmentAction, type EnvironmentDeletion, } from "./diff.js";
2
2
  export { type EnvironmentsPlanEntry, type EnvironmentsPlanResult, formatPolicyLine, formatPatternLabel, } from "./formatter.js";
3
- export { EnvironmentsProcessor, type IEnvironmentsProcessor, type EnvironmentsProcessorResult, } from "./processor.js";
3
+ export { EnvironmentsProcessor, type IEnvironmentsProcessor, type EnvironmentsProcessorOptions, type EnvironmentsProcessorResult, } from "./processor.js";
4
4
  export { GitHubEnvironmentsStrategy } from "./github-environments-strategy.js";
5
5
  export type { IEnvironmentsStrategy, IEnvironmentSecretsStrategy, GitHubEnvironment, GitHubDeploymentBranchPolicy, } from "./types.js";
@@ -3,7 +3,10 @@ import type { IRepoMetadataProvider, RepoInfo } from "../../repo/index.js";
3
3
  import { type EnvironmentsPlanResult } from "./formatter.js";
4
4
  import type { IEnvironmentsStrategy } from "./types.js";
5
5
  import { type BaseProcessorOptions, type BaseProcessorResult, type ISettingsProcessor, type ChangeCounts } from "../base-processor.js";
6
- export type IEnvironmentsProcessor = ISettingsProcessor<BaseProcessorOptions, EnvironmentsProcessorResult>;
6
+ export type IEnvironmentsProcessor = ISettingsProcessor<EnvironmentsProcessorOptions, EnvironmentsProcessorResult>;
7
+ export interface EnvironmentsProcessorOptions extends BaseProcessorOptions {
8
+ noDelete?: boolean;
9
+ }
7
10
  export interface EnvironmentsProcessorResult extends BaseProcessorResult {
8
11
  changes?: ChangeCounts;
9
12
  planOutput?: EnvironmentsPlanResult;
@@ -13,9 +16,10 @@ export declare class EnvironmentsProcessor implements IEnvironmentsProcessor {
13
16
  private readonly strategy;
14
17
  private readonly metadataProvider;
15
18
  constructor(strategy: IEnvironmentsStrategy, metadataProvider: IRepoMetadataProvider);
16
- process(repoConfig: RepoConfig, repoInfo: RepoInfo, options: BaseProcessorOptions): Promise<EnvironmentsProcessorResult>;
19
+ process(repoConfig: RepoConfig, repoInfo: RepoInfo, options: EnvironmentsProcessorOptions): Promise<EnvironmentsProcessorResult>;
17
20
  private readPatterns;
18
21
  private applySettings;
22
+ private deleteEnvironment;
19
23
  private applyChange;
20
24
  private skipIfNotPublic;
21
25
  }
@@ -1,9 +1,30 @@
1
1
  import { runSequentially } from "../../shared/sequential.js";
2
2
  import { quoted } from "../../shared/string-utils.js";
3
3
  import { toErrorMessage } from "../../shared/type-guards.js";
4
- import { diffEnvironments, needsPatternLookup, toGitHubPolicy, } from "./diff.js";
4
+ import { diffEnvironments, needsPatternLookup, orphanEnvironments, toGitHubPolicy, } from "./diff.js";
5
5
  import { formatEnvironmentsPlan, formatPatternLabel, } from "./formatter.js";
6
6
  import { withGitHubGuards, countActions, buildDryRunResult, buildApplyResult, } from "../base-processor.js";
7
+ function environmentsOf(repoConfig) {
8
+ const { deleteOrphaned, ...entries } = (repoConfig.settings?.environments ??
9
+ {});
10
+ return {
11
+ entries: entries,
12
+ deleteOrphaned: deleteOrphaned === true,
13
+ };
14
+ }
15
+ function isPermissionError(error) {
16
+ return (toErrorMessage(error).includes("HTTP 403") && !isPaidPlanError(error));
17
+ }
18
+ async function deleteAsAdmin(what, run) {
19
+ try {
20
+ await run();
21
+ }
22
+ catch (error) {
23
+ if (!isPermissionError(error))
24
+ throw error;
25
+ throw new Error(`${what} needs the Administration: Read and write permission (repo admin): ${toErrorMessage(error)}`, { cause: error });
26
+ }
27
+ }
7
28
  function unmanagedWarnings(repoName, changes) {
8
29
  return changes.flatMap((c) => c.unmanagedPatterns.map((p) => `${repoName}: environment ${quoted(c.name)} has ${formatPatternLabel(p)} not in config - left in place`));
9
30
  }
@@ -26,7 +47,10 @@ export class EnvironmentsProcessor {
26
47
  }
27
48
  async process(repoConfig, repoInfo, options) {
28
49
  return withGitHubGuards(repoConfig, repoInfo, options, {
29
- hasDesiredSettings: (rc) => Object.keys(rc.settings?.environments ?? {}).length > 0,
50
+ hasDesiredSettings: (rc) => {
51
+ const { entries, deleteOrphaned } = environmentsOf(rc);
52
+ return Object.keys(entries).length > 0 || deleteOrphaned;
53
+ },
30
54
  emptySettingsMessage: "No environments configured",
31
55
  applySettings: (githubRepo, rc, opts, token, repoName) => this.applySettings(githubRepo, rc, opts, token, repoName),
32
56
  });
@@ -40,15 +64,17 @@ export class EnvironmentsProcessor {
40
64
  return patterns;
41
65
  }
42
66
  async applySettings(githubRepo, repoConfig, options, effectiveToken, repoName) {
43
- const desired = repoConfig.settings?.environments ?? {};
67
+ const { entries: desired, deleteOrphaned } = environmentsOf(repoConfig);
68
+ const noDelete = options.noDelete ?? false;
44
69
  const strategyOptions = { token: effectiveToken, host: githubRepo.host };
45
70
  const current = await this.strategy.list(githubRepo, strategyOptions);
46
71
  const patterns = await this.readPatterns(githubRepo, needsPatternLookup(desired, current), strategyOptions);
47
- const changes = diffEnvironments(desired, current, patterns);
48
- const changeCounts = countActions(changes);
72
+ const changes = diffEnvironments(desired, current, patterns, { noDelete });
73
+ const deletions = deleteOrphaned && !noDelete ? orphanEnvironments(desired, current) : [];
74
+ const changeCounts = countActions([...changes, ...deletions]);
49
75
  const warnings = unmanagedWarnings(repoName, changes);
50
76
  if (options.dryRun) {
51
- return buildDryRunResult(repoName, changeCounts, withWarnings({ planOutput: formatEnvironmentsPlan(changes, true) }, warnings));
77
+ return buildDryRunResult(repoName, changeCounts, withWarnings({ planOutput: formatEnvironmentsPlan(changes, true, deletions) }, warnings));
52
78
  }
53
79
  const progress = { writes: 0 };
54
80
  let appliedCount = 0;
@@ -58,13 +84,21 @@ export class EnvironmentsProcessor {
58
84
  await this.applyChange(githubRepo, change, strategyOptions, progress);
59
85
  appliedCount++;
60
86
  });
87
+ await runSequentially(deletions, async (deletion) => {
88
+ await this.deleteEnvironment(githubRepo, deletion, strategyOptions);
89
+ progress.writes++;
90
+ appliedCount++;
91
+ });
61
92
  }
62
93
  catch (error) {
63
94
  if (progress.writes > 0 || !isPaidPlanError(error))
64
95
  throw error;
65
96
  return this.skipIfNotPublic(githubRepo, strategyOptions, repoName, error);
66
97
  }
67
- return buildApplyResult(repoName, changeCounts, appliedCount, withWarnings({ planOutput: formatEnvironmentsPlan(changes, false) }, warnings));
98
+ return buildApplyResult(repoName, changeCounts, appliedCount, withWarnings({ planOutput: formatEnvironmentsPlan(changes, false, deletions) }, warnings));
99
+ }
100
+ async deleteEnvironment(githubRepo, deletion, strategyOptions) {
101
+ await deleteAsAdmin(`deleting environment ${quoted(deletion.name)}`, () => this.strategy.delete(githubRepo, deletion.name, strategyOptions));
68
102
  }
69
103
  async applyChange(githubRepo, change, strategyOptions, progress) {
70
104
  if (change.putPolicy) {
@@ -81,6 +115,11 @@ export class EnvironmentsProcessor {
81
115
  await this.strategy.createBranchPolicy(githubRepo, change.name, pattern, strategyOptions);
82
116
  progress.writes++;
83
117
  });
118
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
119
+ await runSequentially(change.orphanPatterns, async (pattern) => {
120
+ await deleteAsAdmin(`deleting ${formatPatternLabel(pattern)} from environment ${quoted(change.name)}`, () => this.strategy.deleteBranchPolicy(githubRepo, change.name, pattern.id, strategyOptions));
121
+ progress.writes++;
122
+ });
84
123
  }
85
124
  // GitHub can't report the plan up front: listing a free private repo's environments still succeeds.
86
125
  async skipIfNotPublic(githubRepo, strategyOptions, repoName, error) {
@@ -24,15 +24,22 @@ export interface GitHubBranchPoliciesResponse {
24
24
  total_count: number;
25
25
  branch_policies?: GitHubBranchPolicy[];
26
26
  }
27
+ /** A pattern as it exists on GitHub; the id is what DELETE takes. */
28
+ export interface ExistingBranchPattern extends DeploymentBranchPattern {
29
+ id: number;
30
+ }
27
31
  export interface IEnvironmentsStrategy {
28
32
  list(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubEnvironment[]>;
29
33
  createOrUpdate(repoInfo: RepoInfo, name: string, policy: GitHubDeploymentBranchPolicy | null, options?: GhApiOptions): Promise<void>;
30
- listBranchPolicies(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<DeploymentBranchPattern[]>;
34
+ delete(repoInfo: RepoInfo, name: string, options?: GhApiOptions): Promise<void>;
35
+ listBranchPolicies(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<ExistingBranchPattern[]>;
31
36
  createBranchPolicy(repoInfo: RepoInfo, environment: string, pattern: DeploymentBranchPattern, options?: GhApiOptions): Promise<void>;
37
+ deleteBranchPolicy(repoInfo: RepoInfo, environment: string, id: number, options?: GhApiOptions): Promise<void>;
32
38
  }
33
39
  export interface IEnvironmentSecretsStrategy {
34
40
  list(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubEnvironment[]>;
35
41
  listSecrets(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubSecret[]>;
36
42
  getSecretsPublicKey(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubPublicKey>;
37
43
  upsertSecret(repoInfo: RepoInfo, environment: string, name: string, encryptedValue: string, keyId: string, options?: GhApiOptions): Promise<void>;
44
+ deleteSecret(repoInfo: RepoInfo, environment: string, name: string, options?: GhApiOptions): Promise<void>;
38
45
  }
@@ -16,12 +16,22 @@ function hasRepoSecrets(repoConfig) {
16
16
  return Object.keys(entries).length > 0 || deleteOrphaned === true;
17
17
  }
18
18
  function environmentSecretsOf(repoConfig) {
19
- return Object.entries(repoConfig.settings?.environments ?? {})
20
- .map(([name, env]) => [
21
- name,
22
- Object.entries(env.secrets ?? {}),
23
- ])
24
- .filter(([, entries]) => entries.length > 0);
19
+ const { deleteOrphaned: _d, ...environments } = (repoConfig.settings
20
+ ?.environments ?? {});
21
+ return Object.entries(environments)
22
+ .flatMap(([name, env]) => {
23
+ if (typeof env === "boolean")
24
+ return [];
25
+ const { deleteOrphaned, ...entries } = (env.secrets ?? {});
26
+ return [
27
+ {
28
+ name,
29
+ entries: Object.entries(entries).filter((entry) => typeof entry[1] !== "boolean"),
30
+ deleteOrphaned: deleteOrphaned === true,
31
+ },
32
+ ];
33
+ })
34
+ .filter((env) => env.entries.length > 0 || env.deleteOrphaned);
25
35
  }
26
36
  function missingEnvironmentWarning(repoName, env) {
27
37
  return `${repoName}: environment ${quoted(env)} does not exist - its secrets were skipped (environments on private repos need a paid GitHub plan; on a paid plan, run 'xfg sync' first)`;
@@ -78,7 +88,7 @@ export class SecretsProcessor {
78
88
  const repoChanges = secretEntries.length > 0 || deleteOrphaned
79
89
  ? diffSecrets(await this.strategy.list(githubRepo, strategyOptions), secretEntries.map(([name]) => name), deleteOrphaned)
80
90
  : [];
81
- const envGroups = await this.readEnvironments(githubRepo, repoConfig, strategyOptions);
91
+ const envGroups = await this.readEnvironments(githubRepo, repoConfig, strategyOptions, noDelete ?? false);
82
92
  const envChanges = await this.diffEnvironmentSecrets(githubRepo, envGroups, strategyOptions);
83
93
  if (dryRun) {
84
94
  const planned = [...repoChanges, ...envChanges];
@@ -98,7 +108,9 @@ export class SecretsProcessor {
98
108
  ];
99
109
  const extra = gate.warnings.length > 0 ? { warnings: gate.warnings } : {};
100
110
  const repoValues = this.resolve(secretEntries);
101
- const envValues = writableGroups.map((g) => ({
111
+ const envValues = writableGroups
112
+ .filter((g) => g.entries.length > 0)
113
+ .map((g) => ({
102
114
  environment: g.environment,
103
115
  values: this.resolve(g.entries),
104
116
  }));
@@ -142,7 +154,12 @@ export class SecretsProcessor {
142
154
  }
143
155
  async writeChange(githubRepo, change, scopes, strategyOptions) {
144
156
  if (change.action === "delete") {
145
- await this.strategy.delete(githubRepo, change.name, strategyOptions);
157
+ if (change.environment === undefined) {
158
+ await this.strategy.delete(githubRepo, change.name, strategyOptions);
159
+ }
160
+ else {
161
+ await this.environments.strategy.deleteSecret(githubRepo, change.environment, change.name, strategyOptions);
162
+ }
146
163
  return;
147
164
  }
148
165
  const { values, publicKey } = scopes.get(change.environment);
@@ -156,7 +173,8 @@ export class SecretsProcessor {
156
173
  }
157
174
  /** On a public repo a missing environment is an error; elsewhere it may be the plan, so warn and skip. */
158
175
  async gateMissingEnvironments(githubRepo, groups, strategyOptions, repoName) {
159
- const missing = groups.filter((g) => !g.exists);
176
+ // A missing environment has no secrets to delete, so only writes need it.
177
+ const missing = groups.filter((g) => !g.exists && g.entries.length > 0);
160
178
  if (missing.length === 0)
161
179
  return { warnings: [] };
162
180
  const { visibility } = await this.environments.metadataProvider.getMetadata(githubRepo, strategyOptions);
@@ -175,7 +193,7 @@ export class SecretsProcessor {
175
193
  return new Map();
176
194
  return this.envResolver.resolveAll(entries.map(([name, config]) => ({ name, envVar: config.env })));
177
195
  }
178
- async readEnvironments(githubRepo, repoConfig, strategyOptions) {
196
+ async readEnvironments(githubRepo, repoConfig, strategyOptions, noDelete) {
179
197
  const configured = this.environments
180
198
  ? environmentSecretsOf(repoConfig)
181
199
  : [];
@@ -183,12 +201,13 @@ export class SecretsProcessor {
183
201
  return [];
184
202
  const current = await this.environments.strategy.list(githubRepo, strategyOptions);
185
203
  const existing = new Map(current.map((env) => [env.name.toLowerCase(), env.name]));
186
- return configured.map(([name, entries]) => {
204
+ return configured.map(({ name, entries, deleteOrphaned }) => {
187
205
  const actual = existing.get(name.toLowerCase());
188
206
  return {
189
207
  environment: actual ?? name,
190
208
  exists: actual !== undefined,
191
209
  entries,
210
+ deleteOrphaned: deleteOrphaned && !noDelete,
192
211
  };
193
212
  });
194
213
  }
@@ -199,7 +218,7 @@ export class SecretsProcessor {
199
218
  const current = group.exists
200
219
  ? await this.environments.strategy.listSecrets(githubRepo, group.environment, strategyOptions)
201
220
  : [];
202
- changes.push(...diffSecrets(current, group.entries.map(([name]) => name), false).map((change) => ({ ...change, environment: group.environment })));
221
+ changes.push(...diffSecrets(current, group.entries.map(([name]) => name), group.deleteOrphaned).map((change) => ({ ...change, environment: group.environment })));
203
222
  });
204
223
  return changes;
205
224
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aspruyt/xfg",
3
- "version": "8.1.2",
3
+ "version": "8.2.0",
4
4
  "description": "Manage files, settings, and repositories across GitHub, Azure DevOps, and GitLab — declaratively, from a single YAML config",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -11,7 +11,7 @@
11
11
  }
12
12
  },
13
13
  "bin": {
14
- "xfg": "./dist/cli.js"
14
+ "xfg": "dist/cli.js"
15
15
  },
16
16
  "sideEffects": [
17
17
  "./dist/cli.js"