@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.
Files changed (45) hide show
  1. package/dist/cli/secrets-command.js +12 -2
  2. package/dist/cli/settings-factories.d.ts +2 -1
  3. package/dist/cli/settings-factories.js +7 -1
  4. package/dist/cli/settings-report-builder.d.ts +6 -1
  5. package/dist/cli/settings-report-builder.js +7 -1
  6. package/dist/cli/settings-runner.js +24 -15
  7. package/dist/cli/types.d.ts +4 -2
  8. package/dist/config/index.d.ts +1 -1
  9. package/dist/config/merge.d.ts +9 -5
  10. package/dist/config/merge.js +148 -67
  11. package/dist/config/normalizer.js +87 -18
  12. package/dist/config/types.d.ts +28 -0
  13. package/dist/config/validator.js +17 -3
  14. package/dist/config/validators/ruleset-validator.js +6 -5
  15. package/dist/config/validators/shared.js +123 -0
  16. package/dist/lifecycle/github-lifecycle-provider.d.ts +1 -1
  17. package/dist/lifecycle/github-lifecycle-provider.js +54 -37
  18. package/dist/output/settings-report.d.ts +6 -1
  19. package/dist/output/settings-report.js +31 -9
  20. package/dist/settings/environments/diff.d.ts +22 -0
  21. package/dist/settings/environments/diff.js +78 -0
  22. package/dist/settings/environments/formatter.d.ts +17 -0
  23. package/dist/settings/environments/formatter.js +62 -0
  24. package/dist/settings/environments/github-environments-strategy.d.ts +23 -0
  25. package/dist/settings/environments/github-environments-strategy.js +54 -0
  26. package/dist/settings/environments/index.d.ts +5 -0
  27. package/dist/settings/environments/index.js +3 -0
  28. package/dist/settings/environments/processor.d.ts +21 -0
  29. package/dist/settings/environments/processor.js +100 -0
  30. package/dist/settings/environments/types.d.ts +38 -0
  31. package/dist/settings/environments/types.js +1 -0
  32. package/dist/settings/index.d.ts +1 -0
  33. package/dist/settings/index.js +1 -0
  34. package/dist/settings/secrets/diff.d.ts +2 -0
  35. package/dist/settings/secrets/formatter.d.ts +4 -0
  36. package/dist/settings/secrets/formatter.js +17 -4
  37. package/dist/settings/secrets/index.d.ts +2 -2
  38. package/dist/settings/secrets/index.js +1 -1
  39. package/dist/settings/secrets/processor.d.ts +16 -2
  40. package/dist/settings/secrets/processor.js +132 -28
  41. package/dist/shared/retry-utils.d.ts +3 -2
  42. package/dist/shared/retry-utils.js +3 -2
  43. package/dist/shared/sequential.d.ts +2 -0
  44. package/dist/shared/sequential.js +4 -0
  45. package/package.json +2 -2
@@ -1,4 +1,6 @@
1
1
  import chalk from "chalk";
2
+ import { formatSecretLabel } from "../settings/secrets/formatter.js";
3
+ import { formatPatternLabel, formatPolicyLine, } from "../settings/environments/formatter.js";
2
4
  import { STEP_SUMMARY_MAX_BYTES, writeGitHubStepSummary, } from "./github-summary.js";
3
5
  import { fitSummary, summaryHeader } from "./summary-budget.js";
4
6
  import { formatScalarValue, quoted } from "../shared/string-utils.js";
@@ -10,6 +12,7 @@ export function hasRepoSettingsChanges(repo) {
10
12
  (repo.variables ?? []).length > 0 ||
11
13
  (repo.secrets ?? []).length > 0 ||
12
14
  (repo.collaborators ?? []).length > 0 ||
15
+ (repo.environments ?? []).length > 0 ||
13
16
  !!repo.error);
14
17
  }
15
18
  function renderRulesetConfig(config, startDepth, formatLine) {
@@ -71,6 +74,11 @@ const SETTINGS_CATEGORIES = [
71
74
  plural: "collaborators",
72
75
  totals: (t) => t.collaborators,
73
76
  },
77
+ {
78
+ noun: "environment",
79
+ plural: "environments",
80
+ totals: (t) => t.environments,
81
+ },
74
82
  ];
75
83
  export function formatSettingsCountEntries(totals, dryRun) {
76
84
  return SETTINGS_CATEGORIES.flatMap(({ noun, plural, totals: pick }) => {
@@ -124,6 +132,22 @@ function formatValuePlain(val) {
124
132
  function formatRulesetConfigPlain(config) {
125
133
  return renderRulesetConfig(config, 1, (depth, text) => `+${" ".repeat(depth)}${text.substring(1)}`);
126
134
  }
135
+ const DIFF_SIGN = {
136
+ create: "+",
137
+ update: "!",
138
+ delete: "-",
139
+ };
140
+ function renderEnvironmentLines(entry) {
141
+ const sign = DIFF_SIGN[entry.action];
142
+ const lines = [`${sign} environment ${quoted(entry.name)}`];
143
+ const policy = formatPolicyLine(entry);
144
+ if (policy)
145
+ lines.push(`${sign} ${policy}`);
146
+ for (const pattern of entry.addedPatterns) {
147
+ lines.push(`+ ${formatPatternLabel(pattern)}`);
148
+ }
149
+ return lines;
150
+ }
127
151
  export function renderRepoSettingsDiffLines(repo, diffLines) {
128
152
  const startLength = diffLines.length;
129
153
  for (const setting of repo.settings) {
@@ -229,15 +253,7 @@ export function renderRepoSettingsDiffLines(repo, diffLines) {
229
253
  }
230
254
  // Names only: secret values are write-only and must never reach output.
231
255
  for (const secret of repo.secrets ?? []) {
232
- if (secret.action === "create") {
233
- diffLines.push(`+ secret ${quoted(secret.name)}`);
234
- }
235
- else if (secret.action === "update") {
236
- diffLines.push(`! secret ${quoted(secret.name)} (update, value write-only)`);
237
- }
238
- else {
239
- diffLines.push(`- secret ${quoted(secret.name)}`);
240
- }
256
+ diffLines.push(`${DIFF_SIGN[secret.action]} ${formatSecretLabel(secret)}`);
241
257
  }
242
258
  if ((repo.collaborators ?? []).length > 0 && diffLines.length > startLength) {
243
259
  diffLines.push("");
@@ -246,6 +262,12 @@ export function renderRepoSettingsDiffLines(repo, diffLines) {
246
262
  const sign = collaborator.action === "create" ? "+" : "-";
247
263
  diffLines.push(`${sign} collaborator ${quoted(collaborator.name)}`);
248
264
  }
265
+ if ((repo.environments ?? []).length > 0 && diffLines.length > startLength) {
266
+ diffLines.push("");
267
+ }
268
+ for (const environment of repo.environments ?? []) {
269
+ diffLines.push(...renderEnvironmentLines(environment));
270
+ }
249
271
  if (repo.error) {
250
272
  diffLines.push(`- Error: ${repo.error}`);
251
273
  }
@@ -0,0 +1,22 @@
1
+ import type { DeploymentBranchPattern, DeploymentBranchPolicy, EnvironmentConfig } from "../../config/index.js";
2
+ import type { GitHubDeploymentBranchPolicy, GitHubEnvironment } from "./types.js";
3
+ export type BranchPolicyKind = "all" | "protected" | "custom";
4
+ export type EnvironmentAction = "create" | "update" | "unchanged";
5
+ export interface EnvironmentChange {
6
+ action: EnvironmentAction;
7
+ /** GitHub's spelling when the environment exists, else the config key */
8
+ name: string;
9
+ currentKind?: BranchPolicyKind;
10
+ desiredKind: BranchPolicyKind;
11
+ putPolicy: boolean;
12
+ missingPatterns: DeploymentBranchPattern[];
13
+ unmanagedPatterns: DeploymentBranchPattern[];
14
+ /** False when the existing patterns were not read, so missingPatterns may hold some that exist */
15
+ patternsKnown: boolean;
16
+ }
17
+ export declare function currentPolicyKind(policy: GitHubDeploymentBranchPolicy | null): BranchPolicyKind;
18
+ export declare function desiredPolicyKind(policy: DeploymentBranchPolicy | undefined): BranchPolicyKind;
19
+ export declare function toGitHubPolicy(kind: BranchPolicyKind): GitHubDeploymentBranchPolicy | null;
20
+ /** Existing environments whose patterns must be read before diffing. */
21
+ 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[];
@@ -0,0 +1,78 @@
1
+ export function currentPolicyKind(policy) {
2
+ if (policy?.custom_branch_policies)
3
+ return "custom";
4
+ if (policy?.protected_branches)
5
+ return "protected";
6
+ return "all";
7
+ }
8
+ export function desiredPolicyKind(policy) {
9
+ if (policy?.custom)
10
+ return "custom";
11
+ if (policy?.protectedBranches)
12
+ return "protected";
13
+ return "all";
14
+ }
15
+ export function toGitHubPolicy(kind) {
16
+ if (kind === "all")
17
+ return null;
18
+ return {
19
+ protected_branches: kind === "protected",
20
+ custom_branch_policies: kind === "custom",
21
+ };
22
+ }
23
+ function indexByName(current) {
24
+ return new Map(current.map((env) => [env.name.toLowerCase(), env]));
25
+ }
26
+ /** Existing environments whose patterns must be read before diffing. */
27
+ export function needsPatternLookup(desired, current) {
28
+ const existing = indexByName(current);
29
+ const names = [];
30
+ for (const [name, config] of Object.entries(desired)) {
31
+ const env = existing.get(name.toLowerCase());
32
+ if (env &&
33
+ currentPolicyKind(env.deployment_branch_policy) === "custom" &&
34
+ desiredPolicyKind(config.deploymentBranchPolicy) === "custom") {
35
+ names.push(env.name);
36
+ }
37
+ }
38
+ return names;
39
+ }
40
+ function patternKey(p) {
41
+ return `${p.type}\u0000${p.name}`;
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)));
67
+ return {
68
+ action: putPolicy || missingPatterns.length > 0 ? "update" : "unchanged",
69
+ name: env.name,
70
+ currentKind,
71
+ desiredKind,
72
+ putPolicy,
73
+ missingPatterns,
74
+ unmanagedPatterns: desiredKind === "custom" ? unmanagedPatterns : [],
75
+ patternsKnown: desiredKind !== "custom" || known !== undefined,
76
+ };
77
+ });
78
+ }
@@ -0,0 +1,17 @@
1
+ import type { DeploymentBranchPattern } from "../../config/index.js";
2
+ import type { BranchPolicyKind, EnvironmentChange } from "./diff.js";
3
+ export interface EnvironmentsPlanEntry {
4
+ name: string;
5
+ action: "create" | "update";
6
+ /** Set on updates that change the policy kind */
7
+ currentKind?: BranchPolicyKind;
8
+ desiredKind: BranchPolicyKind;
9
+ addedPatterns: DeploymentBranchPattern[];
10
+ }
11
+ export interface EnvironmentsPlanResult {
12
+ lines: string[];
13
+ entries: EnvironmentsPlanEntry[];
14
+ }
15
+ export declare function formatPolicyLine(entry: EnvironmentsPlanEntry): string | null;
16
+ export declare function formatPatternLabel(pattern: DeploymentBranchPattern): string;
17
+ export declare function formatEnvironmentsPlan(changes: EnvironmentChange[], dryRun: boolean): EnvironmentsPlanResult;
@@ -0,0 +1,62 @@
1
+ import chalk from "chalk";
2
+ import { quoted } from "../../shared/string-utils.js";
3
+ import { countActions } from "../base-processor.js";
4
+ import { formatActionCountEntry } from "../../shared/count-format.js";
5
+ function toEntry(change) {
6
+ if (change.action === "unchanged")
7
+ return null;
8
+ const entry = {
9
+ name: change.name,
10
+ action: change.action,
11
+ desiredKind: change.desiredKind,
12
+ addedPatterns: change.missingPatterns,
13
+ };
14
+ if (change.action === "update" && change.putPolicy) {
15
+ entry.currentKind = change.currentKind;
16
+ }
17
+ return entry;
18
+ }
19
+ export function formatPolicyLine(entry) {
20
+ if (entry.action === "create") {
21
+ return `deployment branches: ${entry.desiredKind}`;
22
+ }
23
+ if (entry.currentKind !== undefined) {
24
+ return `deployment branches: ${entry.currentKind} → ${entry.desiredKind}`;
25
+ }
26
+ return null;
27
+ }
28
+ export function formatPatternLabel(pattern) {
29
+ return `${pattern.type} ${quoted(pattern.name)}`;
30
+ }
31
+ function formatEntry(entry) {
32
+ const color = entry.action === "create" ? chalk.green : chalk.yellow;
33
+ const sign = entry.action === "create" ? "+" : "~";
34
+ const lines = [color(` ${sign} environment ${quoted(entry.name)}`)];
35
+ const policy = formatPolicyLine(entry);
36
+ if (policy)
37
+ lines.push(` ${policy}`);
38
+ for (const pattern of entry.addedPatterns) {
39
+ lines.push(chalk.green(` + ${formatPatternLabel(pattern)}`));
40
+ }
41
+ return lines;
42
+ }
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));
51
+ const summary = formatActionCountEntry("environment", "environments", countActions(entries), dryRun);
52
+ if (!summary) {
53
+ return { lines: [], entries };
54
+ }
55
+ return {
56
+ lines: [
57
+ ...entries.flatMap(formatEntry),
58
+ ` ${dryRun ? "Plan" : "Applied"}: ${summary}`,
59
+ ],
60
+ entries,
61
+ };
62
+ }
@@ -0,0 +1,23 @@
1
+ import type { ICommandExecutor } from "../../shared/command-executor.js";
2
+ import { type RepoInfo } from "../../repo/index.js";
3
+ import { type GhApiOptions } from "../../shared/gh-api-utils.js";
4
+ import type { DeploymentBranchPattern } from "../../config/index.js";
5
+ import type { GitHubPublicKey, GitHubSecret } from "../secrets/types.js";
6
+ import type { GitHubDeploymentBranchPolicy, GitHubEnvironment, IEnvironmentSecretsStrategy, IEnvironmentsStrategy } from "./types.js";
7
+ interface GitHubEnvironmentsStrategyOptions {
8
+ retries?: number;
9
+ cwd: string;
10
+ }
11
+ export declare class GitHubEnvironmentsStrategy implements IEnvironmentsStrategy, IEnvironmentSecretsStrategy {
12
+ private readonly api;
13
+ constructor(executor: ICommandExecutor, options: GitHubEnvironmentsStrategyOptions);
14
+ private base;
15
+ list(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubEnvironment[]>;
16
+ createOrUpdate(repoInfo: RepoInfo, name: string, policy: GitHubDeploymentBranchPolicy | null, options?: GhApiOptions): Promise<void>;
17
+ listBranchPolicies(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<DeploymentBranchPattern[]>;
18
+ createBranchPolicy(repoInfo: RepoInfo, environment: string, pattern: DeploymentBranchPattern, options?: GhApiOptions): Promise<void>;
19
+ listSecrets(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubSecret[]>;
20
+ getSecretsPublicKey(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubPublicKey>;
21
+ upsertSecret(repoInfo: RepoInfo, environment: string, name: string, encryptedValue: string, keyId: string, options?: GhApiOptions): Promise<void>;
22
+ }
23
+ export {};
@@ -0,0 +1,54 @@
1
+ import { assertGitHubRepo } from "../../repo/index.js";
2
+ import { GhApiClient } from "../../shared/gh-api-utils.js";
3
+ import { parseApiJson } from "../../shared/json-utils.js";
4
+ const LABEL = "GitHub Environments strategy";
5
+ export class GitHubEnvironmentsStrategy {
6
+ api;
7
+ constructor(executor, options) {
8
+ this.api = new GhApiClient(executor, options.retries ?? 3, options.cwd);
9
+ }
10
+ base(repoInfo, environment) {
11
+ assertGitHubRepo(repoInfo, LABEL);
12
+ const root = `/repos/${repoInfo.owner}/${repoInfo.repo}/environments`;
13
+ return environment === undefined
14
+ ? root
15
+ : `${root}/${encodeURIComponent(environment)}`;
16
+ }
17
+ async list(repoInfo, options) {
18
+ const result = await this.api.call("GET", `${this.base(repoInfo)}?per_page=100`, { options, paginate: true });
19
+ const response = parseApiJson(result, "environments response");
20
+ return (response.environments ?? []).map((env) => ({
21
+ name: env.name,
22
+ deployment_branch_policy: env.deployment_branch_policy ?? null,
23
+ }));
24
+ }
25
+ async createOrUpdate(repoInfo, name, policy, options) {
26
+ await this.api.call("PUT", this.base(repoInfo, name), {
27
+ payload: { deployment_branch_policy: policy },
28
+ options,
29
+ });
30
+ }
31
+ async listBranchPolicies(repoInfo, environment, options) {
32
+ const result = await this.api.call("GET", `${this.base(repoInfo, environment)}/deployment-branch-policies?per_page=100`, { options, paginate: true });
33
+ const response = parseApiJson(result, "deployment branch policies response");
34
+ return (response.branch_policies ?? []).map((p) => ({
35
+ type: p.type ?? "branch",
36
+ name: p.name,
37
+ }));
38
+ }
39
+ async createBranchPolicy(repoInfo, environment, pattern, options) {
40
+ await this.api.call("POST", `${this.base(repoInfo, environment)}/deployment-branch-policies`, { payload: { name: pattern.name, type: pattern.type }, options });
41
+ }
42
+ async listSecrets(repoInfo, environment, options) {
43
+ const result = await this.api.call("GET", `${this.base(repoInfo, environment)}/secrets?per_page=100`, { options, paginate: true });
44
+ const response = parseApiJson(result, "environment secrets response");
45
+ return response.secrets ?? [];
46
+ }
47
+ async getSecretsPublicKey(repoInfo, environment, options) {
48
+ const result = await this.api.call("GET", `${this.base(repoInfo, environment)}/secrets/public-key`, { options });
49
+ return parseApiJson(result, "environment public key response");
50
+ }
51
+ async upsertSecret(repoInfo, environment, name, encryptedValue, keyId, options) {
52
+ await this.api.call("PUT", `${this.base(repoInfo, environment)}/secrets/${encodeURIComponent(name)}`, { payload: { encrypted_value: encryptedValue, key_id: keyId }, options });
53
+ }
54
+ }
@@ -0,0 +1,5 @@
1
+ export { type BranchPolicyKind, type EnvironmentChange, type EnvironmentAction, } from "./diff.js";
2
+ export { type EnvironmentsPlanEntry, type EnvironmentsPlanResult, formatPolicyLine, formatPatternLabel, } from "./formatter.js";
3
+ export { EnvironmentsProcessor, type IEnvironmentsProcessor, type EnvironmentsProcessorResult, } from "./processor.js";
4
+ export { GitHubEnvironmentsStrategy } from "./github-environments-strategy.js";
5
+ export type { IEnvironmentsStrategy, IEnvironmentSecretsStrategy, GitHubEnvironment, GitHubDeploymentBranchPolicy, } from "./types.js";
@@ -0,0 +1,3 @@
1
+ export { formatPolicyLine, formatPatternLabel, } from "./formatter.js";
2
+ export { EnvironmentsProcessor, } from "./processor.js";
3
+ export { GitHubEnvironmentsStrategy } from "./github-environments-strategy.js";
@@ -0,0 +1,21 @@
1
+ import type { RepoConfig } from "../../config/index.js";
2
+ import type { IRepoMetadataProvider, RepoInfo } from "../../repo/index.js";
3
+ import { type EnvironmentsPlanResult } from "./formatter.js";
4
+ import type { IEnvironmentsStrategy } from "./types.js";
5
+ import { type BaseProcessorOptions, type BaseProcessorResult, type ISettingsProcessor, type ChangeCounts } from "../base-processor.js";
6
+ export type IEnvironmentsProcessor = ISettingsProcessor<BaseProcessorOptions, EnvironmentsProcessorResult>;
7
+ export interface EnvironmentsProcessorResult extends BaseProcessorResult {
8
+ changes?: ChangeCounts;
9
+ planOutput?: EnvironmentsPlanResult;
10
+ warnings?: string[];
11
+ }
12
+ export declare class EnvironmentsProcessor implements IEnvironmentsProcessor {
13
+ private readonly strategy;
14
+ private readonly metadataProvider;
15
+ constructor(strategy: IEnvironmentsStrategy, metadataProvider: IRepoMetadataProvider);
16
+ process(repoConfig: RepoConfig, repoInfo: RepoInfo, options: BaseProcessorOptions): Promise<EnvironmentsProcessorResult>;
17
+ private readPatterns;
18
+ private applySettings;
19
+ private applyChange;
20
+ private skipIfNotPublic;
21
+ }
@@ -0,0 +1,100 @@
1
+ import { runSequentially } from "../../shared/sequential.js";
2
+ import { quoted } from "../../shared/string-utils.js";
3
+ import { toErrorMessage } from "../../shared/type-guards.js";
4
+ import { diffEnvironments, needsPatternLookup, toGitHubPolicy, } from "./diff.js";
5
+ import { formatEnvironmentsPlan, formatPatternLabel, } from "./formatter.js";
6
+ import { withGitHubGuards, countActions, buildDryRunResult, buildApplyResult, } from "../base-processor.js";
7
+ function unmanagedWarnings(repoName, changes) {
8
+ return changes.flatMap((c) => c.unmanagedPatterns.map((p) => `${repoName}: environment ${quoted(c.name)} has ${formatPatternLabel(p)} not in config - left in place`));
9
+ }
10
+ // GitHub's plan-gate replies: 422 for environment protection rules, 403 for other plan-gated features.
11
+ function isPaidPlanError(error) {
12
+ const message = toErrorMessage(error);
13
+ return ((message.includes("HTTP 422") && /billing plan/i.test(message)) ||
14
+ (message.includes("HTTP 403") &&
15
+ message.includes("Upgrade to GitHub Pro or make this repository public")));
16
+ }
17
+ function withWarnings(extra, warnings) {
18
+ return warnings.length > 0 ? { ...extra, warnings } : extra;
19
+ }
20
+ export class EnvironmentsProcessor {
21
+ strategy;
22
+ metadataProvider;
23
+ constructor(strategy, metadataProvider) {
24
+ this.strategy = strategy;
25
+ this.metadataProvider = metadataProvider;
26
+ }
27
+ async process(repoConfig, repoInfo, options) {
28
+ return withGitHubGuards(repoConfig, repoInfo, options, {
29
+ hasDesiredSettings: (rc) => Object.keys(rc.settings?.environments ?? {}).length > 0,
30
+ emptySettingsMessage: "No environments configured",
31
+ applySettings: (githubRepo, rc, opts, token, repoName) => this.applySettings(githubRepo, rc, opts, token, repoName),
32
+ });
33
+ }
34
+ async readPatterns(githubRepo, names, strategyOptions) {
35
+ const patterns = new Map();
36
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
37
+ await runSequentially(names, async (name) => {
38
+ patterns.set(name.toLowerCase(), await this.strategy.listBranchPolicies(githubRepo, name, strategyOptions));
39
+ });
40
+ return patterns;
41
+ }
42
+ async applySettings(githubRepo, repoConfig, options, effectiveToken, repoName) {
43
+ const desired = repoConfig.settings?.environments ?? {};
44
+ const strategyOptions = { token: effectiveToken, host: githubRepo.host };
45
+ const current = await this.strategy.list(githubRepo, strategyOptions);
46
+ const patterns = await this.readPatterns(githubRepo, needsPatternLookup(desired, current), strategyOptions);
47
+ const changes = diffEnvironments(desired, current, patterns);
48
+ const changeCounts = countActions(changes);
49
+ const warnings = unmanagedWarnings(repoName, changes);
50
+ if (options.dryRun) {
51
+ return buildDryRunResult(repoName, changeCounts, withWarnings({ planOutput: formatEnvironmentsPlan(changes, true) }, warnings));
52
+ }
53
+ const progress = { writes: 0 };
54
+ let appliedCount = 0;
55
+ try {
56
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
57
+ await runSequentially(changes.filter((c) => c.action !== "unchanged"), async (change) => {
58
+ await this.applyChange(githubRepo, change, strategyOptions, progress);
59
+ appliedCount++;
60
+ });
61
+ }
62
+ catch (error) {
63
+ if (progress.writes > 0 || !isPaidPlanError(error))
64
+ throw error;
65
+ return this.skipIfNotPublic(githubRepo, strategyOptions, repoName, error);
66
+ }
67
+ return buildApplyResult(repoName, changeCounts, appliedCount, withWarnings({ planOutput: formatEnvironmentsPlan(changes, false) }, warnings));
68
+ }
69
+ async applyChange(githubRepo, change, strategyOptions, progress) {
70
+ if (change.putPolicy) {
71
+ await this.strategy.createOrUpdate(githubRepo, change.name, toGitHubPolicy(change.desiredKind), strategyOptions);
72
+ progress.writes++;
73
+ }
74
+ let missing = change.missingPatterns;
75
+ if (!change.patternsKnown) {
76
+ const existing = await this.strategy.listBranchPolicies(githubRepo, change.name, strategyOptions);
77
+ missing = missing.filter((p) => !existing.some((e) => e.type === p.type && e.name === p.name));
78
+ }
79
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
80
+ await runSequentially(missing, async (pattern) => {
81
+ await this.strategy.createBranchPolicy(githubRepo, change.name, pattern, strategyOptions);
82
+ progress.writes++;
83
+ });
84
+ }
85
+ // GitHub can't report the plan up front: listing a free private repo's environments still succeeds.
86
+ async skipIfNotPublic(githubRepo, strategyOptions, repoName, error) {
87
+ const metadata = await this.metadataProvider.getMetadata(githubRepo, strategyOptions);
88
+ if (metadata.visibility === "public")
89
+ throw error;
90
+ return {
91
+ success: true,
92
+ repoName,
93
+ message: "Skipped: environments need a paid plan on private repos",
94
+ skipped: true,
95
+ warnings: [
96
+ `${repoName}: environments on private repos need a paid GitHub plan (Pro, Team or Enterprise) - skipped (${toErrorMessage(error)})`,
97
+ ],
98
+ };
99
+ }
100
+ }
@@ -0,0 +1,38 @@
1
+ import type { RepoInfo } from "../../repo/index.js";
2
+ import type { GhApiOptions } from "../../shared/gh-api-utils.js";
3
+ import type { DeploymentBranchPattern } from "../../config/index.js";
4
+ import type { GitHubPublicKey, GitHubSecret } from "../secrets/types.js";
5
+ export interface GitHubDeploymentBranchPolicy {
6
+ protected_branches: boolean;
7
+ custom_branch_policies: boolean;
8
+ }
9
+ export interface GitHubEnvironment {
10
+ name: string;
11
+ /** null: any branch can deploy */
12
+ deployment_branch_policy: GitHubDeploymentBranchPolicy | null;
13
+ }
14
+ export interface GitHubEnvironmentsListResponse {
15
+ total_count: number;
16
+ environments?: GitHubEnvironment[];
17
+ }
18
+ export interface GitHubBranchPolicy {
19
+ id: number;
20
+ name: string;
21
+ type?: "branch" | "tag";
22
+ }
23
+ export interface GitHubBranchPoliciesResponse {
24
+ total_count: number;
25
+ branch_policies?: GitHubBranchPolicy[];
26
+ }
27
+ export interface IEnvironmentsStrategy {
28
+ list(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubEnvironment[]>;
29
+ createOrUpdate(repoInfo: RepoInfo, name: string, policy: GitHubDeploymentBranchPolicy | null, options?: GhApiOptions): Promise<void>;
30
+ listBranchPolicies(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<DeploymentBranchPattern[]>;
31
+ createBranchPolicy(repoInfo: RepoInfo, environment: string, pattern: DeploymentBranchPattern, options?: GhApiOptions): Promise<void>;
32
+ }
33
+ export interface IEnvironmentSecretsStrategy {
34
+ list(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubEnvironment[]>;
35
+ listSecrets(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubSecret[]>;
36
+ getSecretsPublicKey(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubPublicKey>;
37
+ upsertSecret(repoInfo: RepoInfo, environment: string, name: string, encryptedValue: string, keyId: string, options?: GhApiOptions): Promise<void>;
38
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -5,4 +5,5 @@ export { type LabelsPlanEntry, LabelsProcessor, type ILabelsProcessor, GitHubLab
5
5
  export { type CodeScanningPlanEntry, CodeScanningProcessor, type ICodeScanningProcessor, GitHubCodeScanningStrategy, } from "./code-scanning/index.js";
6
6
  export { type VariablesPlanEntry, VariablesProcessor, type IVariablesProcessor, GitHubVariablesStrategy, } from "./variables/index.js";
7
7
  export { type CollaboratorsPlanEntry, CollaboratorsProcessor, type ICollaboratorsProcessor, GitHubCollaboratorsStrategy, } from "./collaborators/index.js";
8
+ export { type EnvironmentsPlanEntry, type EnvironmentsProcessorResult, EnvironmentsProcessor, type IEnvironmentsProcessor, type IEnvironmentSecretsStrategy, GitHubEnvironmentsStrategy, } from "./environments/index.js";
8
9
  export { SecretsProcessor, type SecretsPlanEntry, type ISecretsProcessor, type SecretsProcessorOptions, type SecretsProcessorResult, GitHubSecretsStrategy, SodiumEncryptor, type ISecretEncryptor, } from "./secrets/index.js";
@@ -5,5 +5,6 @@ export { LabelsProcessor, GitHubLabelsStrategy, } from "./labels/index.js";
5
5
  export { CodeScanningProcessor, GitHubCodeScanningStrategy, } from "./code-scanning/index.js";
6
6
  export { VariablesProcessor, GitHubVariablesStrategy, } from "./variables/index.js";
7
7
  export { CollaboratorsProcessor, GitHubCollaboratorsStrategy, } from "./collaborators/index.js";
8
+ export { EnvironmentsProcessor, GitHubEnvironmentsStrategy, } from "./environments/index.js";
8
9
  // Secrets — not wired into `xfg sync`; driven by `xfg secrets sync` only.
9
10
  export { SecretsProcessor, GitHubSecretsStrategy, SodiumEncryptor, } from "./secrets/index.js";
@@ -4,6 +4,8 @@ export type SecretAction = SettingsAction;
4
4
  export interface SecretChange {
5
5
  action: SecretAction;
6
6
  name: string;
7
+ /** Set for environment secrets */
8
+ environment?: string;
7
9
  }
8
10
  /**
9
11
  * Diffs remote secrets against the desired name set.
@@ -3,9 +3,13 @@ import { type ActiveAction } from "../base-processor.js";
3
3
  export interface SecretsPlanEntry {
4
4
  name: string;
5
5
  action: ActiveAction;
6
+ /** Set for environment secrets */
7
+ environment?: string;
6
8
  }
7
9
  export interface SecretsPlanResult {
8
10
  lines: string[];
9
11
  entries: SecretsPlanEntry[];
10
12
  }
13
+ /** `secret "X"` plus its notes, e.g. `secret "X" (environment "release", update, value write-only)`. */
14
+ export declare function formatSecretLabel(entry: SecretsPlanEntry): string;
11
15
  export declare function formatSecretsPlan(changes: SecretChange[], dryRun: boolean): SecretsPlanResult;
@@ -7,21 +7,34 @@ const ACTION_ORDER = {
7
7
  update: 1,
8
8
  delete: 2,
9
9
  };
10
+ /** `secret "X"` plus its notes, e.g. `secret "X" (environment "release", update, value write-only)`. */
11
+ export function formatSecretLabel(entry) {
12
+ const notes = [];
13
+ if (entry.environment !== undefined) {
14
+ notes.push(`environment ${quoted(entry.environment)}`);
15
+ }
16
+ if (entry.action === "update")
17
+ notes.push("update", "value write-only");
18
+ const suffix = notes.length > 0 ? ` (${notes.join(", ")})` : "";
19
+ return `secret ${quoted(entry.name)}${suffix}`;
20
+ }
10
21
  // Names only: this formatter must never receive or print a secret value.
11
22
  function formatEntry(entry) {
12
23
  switch (entry.action) {
13
24
  case "create":
14
- return chalk.green(` + secret ${quoted(entry.name)}`);
25
+ return chalk.green(` + ${formatSecretLabel(entry)}`);
15
26
  case "update":
16
- return chalk.yellow(` ~ secret ${quoted(entry.name)} (update, value write-only)`);
27
+ return chalk.yellow(` ~ ${formatSecretLabel(entry)}`);
17
28
  case "delete":
18
- return chalk.red(` - secret ${quoted(entry.name)}`);
29
+ return chalk.red(` - ${formatSecretLabel(entry)}`);
19
30
  }
20
31
  }
21
32
  export function formatSecretsPlan(changes, dryRun) {
22
33
  const entries = changes
23
34
  .filter(isActiveAction)
24
- .map((c) => ({ name: c.name, action: c.action }))
35
+ .map((c) => c.environment === undefined
36
+ ? { name: c.name, action: c.action }
37
+ : { name: c.name, action: c.action, environment: c.environment })
25
38
  .sort((a, b) => ACTION_ORDER[a.action] - ACTION_ORDER[b.action]);
26
39
  const summary = formatActionCountEntry("secret", "secrets", countActions(entries), dryRun);
27
40
  if (!summary) {
@@ -1,6 +1,6 @@
1
1
  export { SecretsProcessor } from "./processor.js";
2
- export type { ISecretsProcessor, SecretsProcessorOptions, SecretsProcessorResult, } from "./processor.js";
3
- export { formatSecretsPlan, type SecretsPlanEntry, type SecretsPlanResult, } from "./formatter.js";
2
+ export type { EnvironmentSecretsDependencies, ISecretsProcessor, SecretsProcessorOptions, SecretsProcessorResult, } from "./processor.js";
3
+ export { formatSecretsPlan, formatSecretLabel, type SecretsPlanEntry, type SecretsPlanResult, } from "./formatter.js";
4
4
  export { diffSecrets, type SecretAction, type SecretChange } from "./diff.js";
5
5
  export { GitHubSecretsStrategy } from "./github-secrets-strategy.js";
6
6
  export { SodiumEncryptor, type ISecretEncryptor } from "./encryption.js";
@@ -1,5 +1,5 @@
1
1
  export { SecretsProcessor } from "./processor.js";
2
- export { formatSecretsPlan, } from "./formatter.js";
2
+ export { formatSecretsPlan, formatSecretLabel, } from "./formatter.js";
3
3
  export { diffSecrets } from "./diff.js";
4
4
  export { GitHubSecretsStrategy } from "./github-secrets-strategy.js";
5
5
  export { SodiumEncryptor } from "./encryption.js";