@aspruyt/xfg 8.3.0 → 8.3.2

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.
@@ -2,6 +2,7 @@ import { mkdirSync } from "node:fs";
2
2
  import { loadRawConfig, normalizeConfig, validateSecretsConfig, validateNormalizedConfig, } from "../config/index.js";
3
3
  import { SecretsProcessor, GitHubSecretsStrategy, SodiumEncryptor, } from "../settings/secrets/index.js";
4
4
  import { GitHubEnvironmentsStrategy } from "../settings/environments/index.js";
5
+ import { GitHubLifecycleProvider } from "../lifecycle/index.js";
5
6
  import { GitHubRepoMetadataProvider, parseGitUrl, getRepoDisplayName, } from "../repo/index.js";
6
7
  import { EnvResolver } from "../shared/env-resolver.js";
7
8
  import { ProcessExecutor } from "../shared/command-executor.js";
@@ -26,7 +27,7 @@ function createDefaultProcessor(cwd, retries, tokenProvider) {
26
27
  cwd,
27
28
  retries,
28
29
  }),
29
- });
30
+ }, new GitHubLifecycleProvider({ executor, retries, cwd }));
30
31
  }
31
32
  function hostQualifiedName(repoInfo) {
32
33
  const name = getRepoDisplayName(repoInfo);
@@ -1,3 +1,4 @@
1
1
  export type { IRepoLifecycleManager, LifecycleActionKind } from "./types.js";
2
2
  export { RepoLifecycleManager } from "./repo-lifecycle-manager.js";
3
+ export { GitHubLifecycleProvider } from "./github-lifecycle-provider.js";
3
4
  export { runLifecycleCheck, toCreateRepoSettings, type LifecycleCheckResult, } from "./helpers.js";
@@ -1,2 +1,3 @@
1
1
  export { RepoLifecycleManager } from "./repo-lifecycle-manager.js";
2
+ export { GitHubLifecycleProvider } from "./github-lifecycle-provider.js";
2
3
  export { runLifecycleCheck, toCreateRepoSettings, } from "./helpers.js";
@@ -8,12 +8,10 @@ export interface RepoSettingsChange {
8
8
  oldValue?: unknown;
9
9
  newValue?: unknown;
10
10
  }
11
+ export declare function getCurrentValue(current: CurrentRepoSettings, property: keyof GitHubRepoSettings): unknown;
11
12
  /**
12
13
  * Compares current repository settings with desired settings.
13
14
  * Only compares properties that are explicitly set in desired.
14
15
  */
15
16
  export declare function diffRepoSettings(current: CurrentRepoSettings, desired: GitHubRepoSettings): RepoSettingsChange[];
16
- /**
17
- * Checks if there are any changes to apply.
18
- */
19
17
  export declare function hasRepoSettingsChanges(changes: RepoSettingsChange[]): boolean;
@@ -1,6 +1,3 @@
1
- /**
2
- * Maps config property names (camelCase) to GitHub API property names (snake_case).
3
- */
4
1
  const PROPERTY_MAPPING = {
5
2
  description: "description",
6
3
  hasIssues: "has_issues",
@@ -29,12 +26,8 @@ const PROPERTY_MAPPING = {
29
26
  secretScanningPushProtection: "_secret_scanning_push_protection",
30
27
  privateVulnerabilityReporting: "private_vulnerability_reporting",
31
28
  };
32
- /**
33
- * Gets the current value for a property from GitHub API response.
34
- */
35
- function getCurrentValue(current, property) {
29
+ export function getCurrentValue(current, property) {
36
30
  const apiKey = PROPERTY_MAPPING[property];
37
- // Handle security_and_analysis nested properties
38
31
  if (apiKey === "_secret_scanning") {
39
32
  return current.security_and_analysis?.secret_scanning?.status === "enabled";
40
33
  }
@@ -60,7 +53,6 @@ export function diffRepoSettings(current, desired) {
60
53
  const property = key;
61
54
  const currentValue = getCurrentValue(current, property);
62
55
  if (currentValue === undefined) {
63
- // Property not currently set or unknown
64
56
  changes.push({
65
57
  property,
66
58
  action: "create",
@@ -75,13 +67,9 @@ export function diffRepoSettings(current, desired) {
75
67
  newValue: desiredValue,
76
68
  });
77
69
  }
78
- // unchanged properties are not included
79
70
  }
80
71
  return changes;
81
72
  }
82
- /**
83
- * Checks if there are any changes to apply.
84
- */
85
73
  export function hasRepoSettingsChanges(changes) {
86
74
  return changes.length > 0;
87
75
  }
@@ -1,6 +1,25 @@
1
- import { diffRepoSettings, hasRepoSettingsChanges } from "./diff.js";
1
+ import { diffRepoSettings, getCurrentValue, hasRepoSettingsChanges, } from "./diff.js";
2
2
  import { formatRepoSettingsPlan, } from "./formatter.js";
3
3
  import { withGitHubGuards, buildDryRunResult, buildApplyResult, } from "../base-processor.js";
4
+ // GitHub rejects a commit message setting sent without its title, and vice versa
5
+ const PAIRED_SETTINGS = [
6
+ ["squashMergeCommitTitle", "squashMergeCommitMessage"],
7
+ ["mergeCommitTitle", "mergeCommitMessage"],
8
+ ];
9
+ function withPairedSettings(changed, current) {
10
+ const payload = { ...changed };
11
+ for (const pair of PAIRED_SETTINGS) {
12
+ if (!pair.some((key) => key in changed))
13
+ continue;
14
+ for (const key of pair) {
15
+ const currentValue = getCurrentValue(current, key);
16
+ if (!(key in payload) && currentValue !== undefined) {
17
+ payload[key] = currentValue;
18
+ }
19
+ }
20
+ }
21
+ return payload;
22
+ }
4
23
  export class RepoSettingsProcessor {
5
24
  strategy;
6
25
  metadataProvider;
@@ -25,12 +44,10 @@ export class RepoSettingsProcessor {
25
44
  throw new Error("applySettings called without repo settings");
26
45
  }
27
46
  const strategyOptions = { token: effectiveToken, host: githubRepo.host };
28
- // Fetch current settings and metadata in parallel
29
47
  const [currentSettings, metadata] = await Promise.all([
30
48
  this.strategy.get(githubRepo, strategyOptions),
31
49
  this.metadataProvider.getMetadata(githubRepo, strategyOptions),
32
50
  ]);
33
- // Validate security settings compatibility
34
51
  const securityErrors = this.validateSecuritySettings(desiredSettings, metadata);
35
52
  if (securityErrors.length > 0) {
36
53
  return {
@@ -39,7 +56,6 @@ export class RepoSettingsProcessor {
39
56
  message: `Failed: ${securityErrors.join("; ")}`,
40
57
  };
41
58
  }
42
- // Compute diff
43
59
  const changes = diffRepoSettings(currentSettings, desiredSettings);
44
60
  if (!hasRepoSettingsChanges(changes)) {
45
61
  return {
@@ -49,7 +65,6 @@ export class RepoSettingsProcessor {
49
65
  changes: { create: 0, update: 0, delete: 0, unchanged: 0 },
50
66
  };
51
67
  }
52
- // Validate defaultBranch target exists before attempting to apply
53
68
  const defaultBranchChange = changes.find((c) => c.property === "defaultBranch");
54
69
  if (defaultBranchChange) {
55
70
  const targetBranch = String(defaultBranchChange.newValue);
@@ -65,7 +80,6 @@ export class RepoSettingsProcessor {
65
80
  };
66
81
  }
67
82
  }
68
- // Format plan output
69
83
  const planOutput = formatRepoSettingsPlan(changes);
70
84
  const changeCounts = {
71
85
  create: planOutput.creates,
@@ -79,13 +93,13 @@ export class RepoSettingsProcessor {
79
93
  planOutput,
80
94
  });
81
95
  }
82
- // Apply changes - only send settings that actually changed
96
+ // Send only changed keys: an unchanged allowForking fails on user-owned repos
83
97
  const changedSettings = {};
84
98
  for (const change of changes) {
85
99
  changedSettings[change.property] =
86
100
  change.newValue;
87
101
  }
88
- await this.applyChanges(githubRepo, changedSettings, strategyOptions);
102
+ await this.applyChanges(githubRepo, withPairedSettings(changedSettings, currentSettings), strategyOptions);
89
103
  const appliedCount = Object.keys(changedSettings).length;
90
104
  return buildApplyResult(repoName, changeCounts, appliedCount, {
91
105
  warnings: planOutput.warnings,
@@ -93,23 +107,18 @@ export class RepoSettingsProcessor {
93
107
  });
94
108
  }
95
109
  async applyChanges(repoInfo, settings, options) {
96
- // Extract settings that need separate API calls
97
110
  const { vulnerabilityAlerts, automatedSecurityFixes, privateVulnerabilityReporting, ...mainSettings } = settings;
98
- // Update main settings via PATCH /repos
99
111
  if (Object.keys(mainSettings).length > 0) {
100
112
  await this.strategy.update(repoInfo, mainSettings, options);
101
113
  }
102
- // Handle vulnerability alerts (separate endpoint)
103
- // Must be done before automated security fixes
114
+ // Must run before automated security fixes
104
115
  if (vulnerabilityAlerts !== undefined) {
105
116
  await this.strategy.updateVulnerabilityAlerts(repoInfo, vulnerabilityAlerts, options);
106
117
  }
107
- // Handle private vulnerability reporting (separate endpoint)
108
118
  if (privateVulnerabilityReporting !== undefined) {
109
119
  await this.strategy.updatePrivateVulnerabilityReporting(repoInfo, privateVulnerabilityReporting, options);
110
120
  }
111
- // Handle automated security fixes (separate endpoint)
112
- // Done last to ensure vulnerability alerts have been fully processed
121
+ // Last, so vulnerability alerts are fully processed first
113
122
  if (automatedSecurityFixes !== undefined) {
114
123
  await this.strategy.updateAutomatedSecurityFixes(repoInfo, automatedSecurityFixes, options);
115
124
  }
@@ -4,4 +4,4 @@ export { formatSecretsPlan, formatSecretLabel, type SecretsPlanEntry, type Secre
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";
7
- export type { ISecretsStrategy, GitHubSecret, GitHubPublicKey, } from "./types.js";
7
+ export type { ISecretsStrategy, GitHubSecret, GitHubPublicKey, IRepoExistenceChecker, } from "./types.js";
@@ -1,6 +1,6 @@
1
1
  import type { IRepoMetadataProvider, RepoInfo } from "../../repo/index.js";
2
2
  import type { RepoConfig } from "../../config/index.js";
3
- import type { ISecretsStrategy } from "./types.js";
3
+ import type { ISecretsStrategy, IRepoExistenceChecker } from "./types.js";
4
4
  import type { IEnvironmentSecretsStrategy } from "../environments/types.js";
5
5
  import type { ISecretEncryptor } from "./encryption.js";
6
6
  import type { IEnvResolver } from "../../shared/env-resolver.js";
@@ -28,7 +28,8 @@ export declare class SecretsProcessor implements ISecretsProcessor {
28
28
  private readonly envResolver;
29
29
  private readonly tokenProvider?;
30
30
  private readonly environments?;
31
- constructor(strategy: ISecretsStrategy, encryptor: ISecretEncryptor, envResolver: IEnvResolver, tokenProvider?: IGitHubTokenProvider | undefined, environments?: EnvironmentSecretsDependencies | undefined);
31
+ private readonly repoExistence?;
32
+ constructor(strategy: ISecretsStrategy, encryptor: ISecretEncryptor, envResolver: IEnvResolver, tokenProvider?: IGitHubTokenProvider | undefined, environments?: EnvironmentSecretsDependencies | undefined, repoExistence?: IRepoExistenceChecker | undefined);
32
33
  private hasDesiredSecrets;
33
34
  process(repoConfig: RepoConfig, repoInfo: RepoInfo, options: SecretsProcessorOptions): Promise<SecretsProcessorResult>;
34
35
  private applySettings;
@@ -42,12 +42,14 @@ export class SecretsProcessor {
42
42
  envResolver;
43
43
  tokenProvider;
44
44
  environments;
45
- constructor(strategy, encryptor, envResolver, tokenProvider, environments) {
45
+ repoExistence;
46
+ constructor(strategy, encryptor, envResolver, tokenProvider, environments, repoExistence) {
46
47
  this.strategy = strategy;
47
48
  this.encryptor = encryptor;
48
49
  this.envResolver = envResolver;
49
50
  this.tokenProvider = tokenProvider;
50
51
  this.environments = environments;
52
+ this.repoExistence = repoExistence;
51
53
  }
52
54
  hasDesiredSecrets(repoConfig) {
53
55
  return (hasRepoSecrets(repoConfig) ||
@@ -80,15 +82,22 @@ export class SecretsProcessor {
80
82
  token = resolved.token;
81
83
  }
82
84
  const { dryRun, noDelete } = options;
85
+ const repoMissing = dryRun === true &&
86
+ this.repoExistence !== undefined &&
87
+ !(await this.repoExistence.exists({ repo: githubRepo, token }));
83
88
  const secrets = (repoConfig.settings?.secrets ?? {});
84
89
  const configDeleteOrphaned = secrets.deleteOrphaned === true;
85
90
  const deleteOrphaned = configDeleteOrphaned && !(noDelete ?? false);
86
91
  const secretEntries = secretEntriesOf(repoConfig).filter((entry) => typeof entry[1] !== "boolean");
87
92
  const strategyOptions = { token, host: githubRepo.host };
88
- const repoChanges = secretEntries.length > 0 || deleteOrphaned
89
- ? diffSecrets(await this.strategy.list(githubRepo, strategyOptions), secretEntries.map(([name]) => name), deleteOrphaned)
93
+ const managesRepoSecrets = secretEntries.length > 0 || deleteOrphaned;
94
+ const currentRepoSecrets = managesRepoSecrets && !repoMissing
95
+ ? await this.strategy.list(githubRepo, strategyOptions)
90
96
  : [];
91
- const envGroups = await this.readEnvironments(githubRepo, repoConfig, strategyOptions, noDelete ?? false);
97
+ const repoChanges = managesRepoSecrets
98
+ ? diffSecrets(currentRepoSecrets, secretEntries.map(([name]) => name), deleteOrphaned)
99
+ : [];
100
+ const envGroups = await this.readEnvironments(githubRepo, repoConfig, strategyOptions, noDelete ?? false, repoMissing);
92
101
  const envChanges = await this.diffEnvironmentSecrets(githubRepo, envGroups, strategyOptions);
93
102
  if (dryRun) {
94
103
  const planned = [...repoChanges, ...envChanges];
@@ -193,13 +202,15 @@ export class SecretsProcessor {
193
202
  return new Map();
194
203
  return this.envResolver.resolveAll(entries.map(([name, config]) => ({ name, envVar: config.env })));
195
204
  }
196
- async readEnvironments(githubRepo, repoConfig, strategyOptions, noDelete) {
205
+ async readEnvironments(githubRepo, repoConfig, strategyOptions, noDelete, repoMissing) {
197
206
  const configured = this.environments
198
207
  ? environmentSecretsOf(repoConfig)
199
208
  : [];
200
209
  if (configured.length === 0)
201
210
  return [];
202
- const current = await this.environments.strategy.list(githubRepo, strategyOptions);
211
+ const current = repoMissing
212
+ ? []
213
+ : await this.environments.strategy.list(githubRepo, strategyOptions);
203
214
  const existing = new Map(current.map((env) => [env.name.toLowerCase(), env.name]));
204
215
  return configured.map(({ name, entries, deleteOrphaned }) => {
205
216
  const actual = existing.get(name.toLowerCase());
@@ -19,3 +19,10 @@ export interface ISecretsStrategy {
19
19
  upsert(repoInfo: RepoInfo, name: string, encryptedValue: string, keyId: string, options?: GhApiOptions): Promise<void>;
20
20
  delete(repoInfo: RepoInfo, name: string, options?: GhApiOptions): Promise<void>;
21
21
  }
22
+ /** `xfg sync` creates a missing repo, so a plan reads its current state as empty. */
23
+ export interface IRepoExistenceChecker {
24
+ exists(params: {
25
+ repo: RepoInfo;
26
+ token?: string;
27
+ }): Promise<boolean>;
28
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aspruyt/xfg",
3
- "version": "8.3.0",
3
+ "version": "8.3.2",
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",