@aspruyt/xfg 7.3.0 → 7.4.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.
- 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 +15 -0
- package/dist/cli/settings-runner.js +12 -0
- package/dist/cli/types.d.ts +4 -2
- package/dist/config/index.d.ts +1 -1
- package/dist/config/normalizer.js +32 -3
- package/dist/config/types.d.ts +13 -0
- package/dist/config/validator.js +9 -0
- package/dist/config/validators/shared.js +33 -0
- package/dist/lifecycle/github-lifecycle-provider.d.ts +1 -0
- package/dist/lifecycle/github-lifecycle-provider.js +30 -14
- package/dist/output/settings-report.d.ts +9 -0
- package/dist/output/settings-report.js +13 -0
- package/dist/settings/collaborators/diff.d.ts +17 -0
- package/dist/settings/collaborators/diff.js +64 -0
- package/dist/settings/collaborators/formatter.d.ts +14 -0
- package/dist/settings/collaborators/formatter.js +41 -0
- package/dist/settings/collaborators/github-collaborators-strategy.d.ts +18 -0
- package/dist/settings/collaborators/github-collaborators-strategy.js +43 -0
- package/dist/settings/collaborators/index.d.ts +4 -0
- package/dist/settings/collaborators/index.js +2 -0
- package/dist/settings/collaborators/processor.d.ts +21 -0
- package/dist/settings/collaborators/processor.js +77 -0
- package/dist/settings/collaborators/types.d.ts +19 -0
- package/dist/settings/collaborators/types.js +1 -0
- package/dist/settings/index.d.ts +1 -0
- package/dist/settings/index.js +1 -0
- package/package.json +3 -2
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import type { ProcessExecutor } from "../shared/command-executor.js";
|
|
2
|
-
import type { RulesetProcessorFactory, RepoSettingsProcessorFactory, LabelsProcessorFactory, CodeScanningProcessorFactory, VariablesProcessorFactory, SettingsProcessorFactories } from "./types.js";
|
|
2
|
+
import type { RulesetProcessorFactory, RepoSettingsProcessorFactory, LabelsProcessorFactory, CodeScanningProcessorFactory, VariablesProcessorFactory, CollaboratorsProcessorFactory, SettingsProcessorFactories } from "./types.js";
|
|
3
3
|
export declare function createDefaultRulesetProcessorFactory(executor: ProcessExecutor): RulesetProcessorFactory;
|
|
4
4
|
export declare function createDefaultRepoSettingsProcessorFactory(executor: ProcessExecutor): RepoSettingsProcessorFactory;
|
|
5
5
|
export declare function createDefaultLabelsProcessorFactory(executor: ProcessExecutor): LabelsProcessorFactory;
|
|
6
6
|
export declare function createDefaultCodeScanningProcessorFactory(executor: ProcessExecutor): CodeScanningProcessorFactory;
|
|
7
7
|
export declare function createDefaultVariablesProcessorFactory(executor: ProcessExecutor): VariablesProcessorFactory;
|
|
8
|
+
export declare function createDefaultCollaboratorsProcessorFactory(executor: ProcessExecutor): CollaboratorsProcessorFactory;
|
|
8
9
|
export declare function createDefaultFactories(executor: ProcessExecutor, overrides?: Partial<SettingsProcessorFactories>): SettingsProcessorFactories;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { RulesetProcessor, RepoSettingsProcessor, LabelsProcessor, CodeScanningProcessor, VariablesProcessor, GitHubRulesetStrategy, GitHubRepoSettingsStrategy, GitHubLabelsStrategy, GitHubCodeScanningStrategy, GitHubVariablesStrategy, } from "../settings/index.js";
|
|
1
|
+
import { RulesetProcessor, RepoSettingsProcessor, LabelsProcessor, CodeScanningProcessor, VariablesProcessor, CollaboratorsProcessor, GitHubRulesetStrategy, GitHubRepoSettingsStrategy, GitHubLabelsStrategy, GitHubCodeScanningStrategy, GitHubVariablesStrategy, GitHubCollaboratorsStrategy, } from "../settings/index.js";
|
|
2
2
|
import { GitHubRepoMetadataProvider } from "../repo/index.js";
|
|
3
3
|
export function createDefaultRulesetProcessorFactory(executor) {
|
|
4
4
|
const cwd = process.cwd();
|
|
@@ -20,6 +20,10 @@ export function createDefaultVariablesProcessorFactory(executor) {
|
|
|
20
20
|
const cwd = process.cwd();
|
|
21
21
|
return () => new VariablesProcessor(new GitHubVariablesStrategy(executor, { cwd }));
|
|
22
22
|
}
|
|
23
|
+
export function createDefaultCollaboratorsProcessorFactory(executor) {
|
|
24
|
+
const cwd = process.cwd();
|
|
25
|
+
return () => new CollaboratorsProcessor(new GitHubCollaboratorsStrategy(executor, { cwd }), new GitHubRepoMetadataProvider(executor, { cwd }));
|
|
26
|
+
}
|
|
23
27
|
export function createDefaultFactories(executor, overrides) {
|
|
24
28
|
return {
|
|
25
29
|
rulesets: overrides?.rulesets ?? createDefaultRulesetProcessorFactory(executor),
|
|
@@ -28,5 +32,7 @@ export function createDefaultFactories(executor, overrides) {
|
|
|
28
32
|
codeScanning: overrides?.codeScanning ??
|
|
29
33
|
createDefaultCodeScanningProcessorFactory(executor),
|
|
30
34
|
variables: overrides?.variables ?? createDefaultVariablesProcessorFactory(executor),
|
|
35
|
+
collaborators: overrides?.collaborators ??
|
|
36
|
+
createDefaultCollaboratorsProcessorFactory(executor),
|
|
31
37
|
};
|
|
32
38
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SettingsReport } from "../output/index.js";
|
|
2
|
-
import { type RepoSettingsPlanEntry, type RulesetPlanEntry, type LabelsPlanEntry, type CodeScanningPlanEntry, type VariablesPlanEntry, type SecretsPlanEntry } from "../settings/index.js";
|
|
2
|
+
import { type RepoSettingsPlanEntry, type RulesetPlanEntry, type LabelsPlanEntry, type CodeScanningPlanEntry, type VariablesPlanEntry, type CollaboratorsPlanEntry, type SecretsPlanEntry } from "../settings/index.js";
|
|
3
3
|
export interface ProcessorResults {
|
|
4
4
|
repoName: string;
|
|
5
5
|
settingsResult?: {
|
|
@@ -27,6 +27,11 @@ export interface ProcessorResults {
|
|
|
27
27
|
entries?: VariablesPlanEntry[];
|
|
28
28
|
};
|
|
29
29
|
};
|
|
30
|
+
collaboratorsResult?: {
|
|
31
|
+
planOutput?: {
|
|
32
|
+
entries?: CollaboratorsPlanEntry[];
|
|
33
|
+
};
|
|
34
|
+
};
|
|
30
35
|
secretsResult?: {
|
|
31
36
|
planOutput?: {
|
|
32
37
|
entries?: SecretsPlanEntry[];
|
|
@@ -7,6 +7,7 @@ export function buildSettingsReport(results) {
|
|
|
7
7
|
labels: { create: 0, update: 0, delete: 0 },
|
|
8
8
|
variables: { create: 0, update: 0, delete: 0 },
|
|
9
9
|
secrets: { create: 0, update: 0, delete: 0 },
|
|
10
|
+
collaborators: { create: 0, update: 0, delete: 0 },
|
|
10
11
|
};
|
|
11
12
|
for (const result of results) {
|
|
12
13
|
const repoChanges = {
|
|
@@ -16,6 +17,7 @@ export function buildSettingsReport(results) {
|
|
|
16
17
|
labels: [],
|
|
17
18
|
variables: [],
|
|
18
19
|
secrets: [],
|
|
20
|
+
collaborators: [],
|
|
19
21
|
};
|
|
20
22
|
if (result.settingsResult?.planOutput?.entries) {
|
|
21
23
|
for (const entry of result.settingsResult.planOutput.entries) {
|
|
@@ -104,6 +106,19 @@ export function buildSettingsReport(results) {
|
|
|
104
106
|
totals.secrets.update += counts.update;
|
|
105
107
|
totals.secrets.delete += counts.delete;
|
|
106
108
|
}
|
|
109
|
+
if (result.collaboratorsResult?.planOutput?.entries) {
|
|
110
|
+
for (const entry of result.collaboratorsResult.planOutput.entries) {
|
|
111
|
+
if (entry.action === "unchanged")
|
|
112
|
+
continue;
|
|
113
|
+
repoChanges.collaborators.push({
|
|
114
|
+
name: entry.name,
|
|
115
|
+
action: entry.action,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
const counts = countActions(repoChanges.collaborators);
|
|
119
|
+
totals.collaborators.create += counts.create;
|
|
120
|
+
totals.collaborators.delete += counts.delete;
|
|
121
|
+
}
|
|
107
122
|
if (result.error) {
|
|
108
123
|
repoChanges.error = result.error;
|
|
109
124
|
}
|
|
@@ -16,6 +16,11 @@ function logSettingsResult(logger, result, label, repoNumber, repoName, settings
|
|
|
16
16
|
else if (!result.skipped && result.success) {
|
|
17
17
|
logger.success(repoNumber, repoName, `${label}: ${result.message}`);
|
|
18
18
|
}
|
|
19
|
+
else if (result.skipped) {
|
|
20
|
+
for (const warning of result.warnings ?? []) {
|
|
21
|
+
logger.warn(warning);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
19
24
|
if (!result.success && !result.skipped) {
|
|
20
25
|
logger.error(repoNumber, repoName, `${label}: ${result.message}`);
|
|
21
26
|
settingsCollector.appendError(repoName, result.message);
|
|
@@ -72,6 +77,13 @@ function buildSettingsDescriptors(ctx) {
|
|
|
72
77
|
e.variablesResult = r;
|
|
73
78
|
}),
|
|
74
79
|
},
|
|
80
|
+
{
|
|
81
|
+
key: "collaborators",
|
|
82
|
+
label: "Collaborators",
|
|
83
|
+
run: () => runAndStoreResult(factories.collaborators, repoConfig, repoInfo, sharedOpts, repoName, settingsCollector, (e, r) => {
|
|
84
|
+
e.collaboratorsResult = r;
|
|
85
|
+
}),
|
|
86
|
+
},
|
|
75
87
|
];
|
|
76
88
|
}
|
|
77
89
|
export async function applyRepoSettings(ctx) {
|
package/dist/cli/types.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { MergeMode, MergeStrategy, RepoConfig } from "../config/index.js";
|
|
2
2
|
import type { IRepoLifecycleManager } from "../lifecycle/index.js";
|
|
3
3
|
import type { IRepositoryProcessor, FileChangeDetail } from "../sync/index.js";
|
|
4
|
-
import type { ISettingsProcessor, IRulesetProcessor, IRepoSettingsProcessor, ILabelsProcessor, ICodeScanningProcessor, IVariablesProcessor, BaseProcessorResult } from "../settings/index.js";
|
|
4
|
+
import type { ISettingsProcessor, IRulesetProcessor, IRepoSettingsProcessor, ILabelsProcessor, ICodeScanningProcessor, IVariablesProcessor, ICollaboratorsProcessor, BaseProcessorResult } from "../settings/index.js";
|
|
5
5
|
import type { RepoInfo } from "../repo/index.js";
|
|
6
6
|
import type { ResultsCollector } from "./results-collector.js";
|
|
7
7
|
import type { Logger } from "../shared/logger.js";
|
|
@@ -12,13 +12,15 @@ export type RepoSettingsProcessorFactory = SettingsProcessorFactory<IRepoSetting
|
|
|
12
12
|
export type LabelsProcessorFactory = SettingsProcessorFactory<ILabelsProcessor>;
|
|
13
13
|
export type CodeScanningProcessorFactory = SettingsProcessorFactory<ICodeScanningProcessor>;
|
|
14
14
|
export type VariablesProcessorFactory = SettingsProcessorFactory<IVariablesProcessor>;
|
|
15
|
-
export type
|
|
15
|
+
export type CollaboratorsProcessorFactory = SettingsProcessorFactory<ICollaboratorsProcessor>;
|
|
16
|
+
export type SettingsKind = "rulesets" | "labels" | "repo" | "codeScanning" | "variables" | "collaborators";
|
|
16
17
|
export interface SettingsProcessorFactories {
|
|
17
18
|
rulesets: RulesetProcessorFactory;
|
|
18
19
|
labels: LabelsProcessorFactory;
|
|
19
20
|
repo: RepoSettingsProcessorFactory;
|
|
20
21
|
codeScanning: CodeScanningProcessorFactory;
|
|
21
22
|
variables: VariablesProcessorFactory;
|
|
23
|
+
collaborators: CollaboratorsProcessorFactory;
|
|
22
24
|
}
|
|
23
25
|
/**
|
|
24
26
|
* Dependencies for the sync command (dependency injection).
|
package/dist/config/index.d.ts
CHANGED
|
@@ -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, RepoSettings, RawFileConfig, RawRepoFileOverride, RawGroupConfig, SecretConfig, 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, 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";
|
|
@@ -195,6 +195,29 @@ function dropEntryMapIfEmpty(merged) {
|
|
|
195
195
|
return undefined;
|
|
196
196
|
return merged;
|
|
197
197
|
}
|
|
198
|
+
/**
|
|
199
|
+
* Merges collaborator layers: users union (case-insensitive, first spelling wins),
|
|
200
|
+
* `inherit: false` drops base users but never clears an inherited deleteOrphaned.
|
|
201
|
+
*/
|
|
202
|
+
function mergeCollaboratorsLayer(base, overlay) {
|
|
203
|
+
const inheritedUsers = overlay?.inherit === false ? [] : (base?.users ?? []);
|
|
204
|
+
const seen = new Set();
|
|
205
|
+
const users = [];
|
|
206
|
+
for (const user of [...inheritedUsers, ...(overlay?.users ?? [])]) {
|
|
207
|
+
const key = user.toLowerCase();
|
|
208
|
+
if (seen.has(key))
|
|
209
|
+
continue;
|
|
210
|
+
seen.add(key);
|
|
211
|
+
users.push(user);
|
|
212
|
+
}
|
|
213
|
+
const deleteOrphaned = overlay?.deleteOrphaned ?? base?.deleteOrphaned;
|
|
214
|
+
return deleteOrphaned === undefined ? { users } : { users, deleteOrphaned };
|
|
215
|
+
}
|
|
216
|
+
function dropCollaboratorsIfEmpty(merged) {
|
|
217
|
+
if ((merged.users ?? []).length === 0 && merged.deleteOrphaned === undefined)
|
|
218
|
+
return undefined;
|
|
219
|
+
return merged;
|
|
220
|
+
}
|
|
198
221
|
/**
|
|
199
222
|
* Merges settings: per-repo settings deep merge with root settings.
|
|
200
223
|
* Returns undefined if no settings are defined.
|
|
@@ -234,8 +257,6 @@ export function mergeSettings(root, perRepo) {
|
|
|
234
257
|
if (deleteOrphaned !== undefined) {
|
|
235
258
|
result.deleteOrphaned = deleteOrphaned;
|
|
236
259
|
}
|
|
237
|
-
// Merge repo settings: per-repo overrides root (shallow merge)
|
|
238
|
-
// repo: false means opt out of all root repo settings
|
|
239
260
|
if (perRepo?.repo === false) {
|
|
240
261
|
// Opt-out: don't include any repo settings
|
|
241
262
|
}
|
|
@@ -285,6 +306,12 @@ export function mergeSettings(root, perRepo) {
|
|
|
285
306
|
result.secrets = merged;
|
|
286
307
|
}
|
|
287
308
|
}
|
|
309
|
+
if (root?.collaborators || perRepo?.collaborators) {
|
|
310
|
+
const merged = dropCollaboratorsIfEmpty(mergeCollaboratorsLayer(root?.collaborators, perRepo?.collaborators));
|
|
311
|
+
if (merged) {
|
|
312
|
+
result.collaborators = merged;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
288
315
|
return Object.keys(result).length > 0 ? result : undefined;
|
|
289
316
|
}
|
|
290
317
|
/**
|
|
@@ -412,7 +439,6 @@ function mergeRawSettings(base, overlay) {
|
|
|
412
439
|
...entry,
|
|
413
440
|
}));
|
|
414
441
|
}
|
|
415
|
-
// Merge code scanning: overlay fully replaces base (same semantics as mergeSettings)
|
|
416
442
|
if (overlay.codeScanning !== undefined) {
|
|
417
443
|
if (overlay.codeScanning === false) {
|
|
418
444
|
result.codeScanning = false;
|
|
@@ -427,6 +453,9 @@ function mergeRawSettings(base, overlay) {
|
|
|
427
453
|
if (overlay.secrets) {
|
|
428
454
|
result.secrets = mergeEntryMapLayer(result.secrets, overlay.secrets);
|
|
429
455
|
}
|
|
456
|
+
if (overlay.collaborators) {
|
|
457
|
+
result.collaborators = mergeCollaboratorsLayer(result.collaborators, overlay.collaborators);
|
|
458
|
+
}
|
|
430
459
|
if (overlay.deleteOrphaned !== undefined) {
|
|
431
460
|
result.deleteOrphaned = overlay.deleteOrphaned;
|
|
432
461
|
}
|
package/dist/config/types.d.ts
CHANGED
|
@@ -291,6 +291,15 @@ export interface SecretConfig {
|
|
|
291
291
|
export type SecretsConfig = Record<string, SecretConfig | boolean> & {
|
|
292
292
|
deleteOrphaned?: boolean;
|
|
293
293
|
};
|
|
294
|
+
export interface CollaboratorsConfig {
|
|
295
|
+
/** GitHub usernames granted write access (personal repos only) */
|
|
296
|
+
users?: string[];
|
|
297
|
+
/** Remove users xfg added (tracked in .xfg.json) once they leave the config */
|
|
298
|
+
deleteOrphaned?: boolean;
|
|
299
|
+
}
|
|
300
|
+
export interface RawCollaboratorsConfig extends CollaboratorsConfig {
|
|
301
|
+
inherit?: boolean;
|
|
302
|
+
}
|
|
294
303
|
export interface RepoSettings {
|
|
295
304
|
/** GitHub rulesets keyed by name */
|
|
296
305
|
rulesets?: Record<string, Ruleset>;
|
|
@@ -308,6 +317,8 @@ export interface RepoSettings {
|
|
|
308
317
|
secrets?: Record<string, SecretConfig> & {
|
|
309
318
|
deleteOrphaned?: boolean;
|
|
310
319
|
};
|
|
320
|
+
/** Direct collaborators on personal (user-owned) repos */
|
|
321
|
+
collaborators?: CollaboratorsConfig;
|
|
311
322
|
deleteOrphaned?: boolean;
|
|
312
323
|
}
|
|
313
324
|
export type ContentValue = Record<string, unknown> | string | string[];
|
|
@@ -372,6 +383,7 @@ export interface RawRootSettings {
|
|
|
372
383
|
deleteOrphaned?: boolean;
|
|
373
384
|
};
|
|
374
385
|
secrets?: SecretsConfig;
|
|
386
|
+
collaborators?: CollaboratorsConfig;
|
|
375
387
|
deleteOrphaned?: boolean;
|
|
376
388
|
}
|
|
377
389
|
export interface RawRepoSettings {
|
|
@@ -390,6 +402,7 @@ export interface RawRepoSettings {
|
|
|
390
402
|
secrets?: SecretsConfig & {
|
|
391
403
|
inherit?: boolean;
|
|
392
404
|
};
|
|
405
|
+
collaborators?: RawCollaboratorsConfig;
|
|
393
406
|
deleteOrphaned?: boolean;
|
|
394
407
|
}
|
|
395
408
|
export interface RawRepoConfig {
|
package/dist/config/validator.js
CHANGED
|
@@ -69,6 +69,10 @@ function validateRootSettings(config) {
|
|
|
69
69
|
if (config.settings.secrets && "inherit" in config.settings.secrets) {
|
|
70
70
|
throw new ValidationError("'inherit' is not allowed in root-level secrets (nothing to inherit from)");
|
|
71
71
|
}
|
|
72
|
+
if (config.settings.collaborators &&
|
|
73
|
+
"inherit" in config.settings.collaborators) {
|
|
74
|
+
throw new ValidationError("'inherit' is not allowed in root-level collaborators (nothing to inherit from)");
|
|
75
|
+
}
|
|
72
76
|
}
|
|
73
77
|
function validateGithubHosts(config) {
|
|
74
78
|
if (config.githubHosts === undefined)
|
|
@@ -286,6 +290,11 @@ export function hasActionableSettings(settings) {
|
|
|
286
290
|
return true;
|
|
287
291
|
}
|
|
288
292
|
}
|
|
293
|
+
if (settings.collaborators &&
|
|
294
|
+
((settings.collaborators.users ?? []).length > 0 ||
|
|
295
|
+
settings.collaborators.deleteOrphaned === true)) {
|
|
296
|
+
return true;
|
|
297
|
+
}
|
|
289
298
|
// Secrets are deliberately absent: `xfg sync` must never process them.
|
|
290
299
|
// A secrets-only config leaves `xfg sync` with nothing to do.
|
|
291
300
|
return false;
|
|
@@ -228,6 +228,38 @@ function validateSettingsSecrets(settings, context) {
|
|
|
228
228
|
}
|
|
229
229
|
}
|
|
230
230
|
}
|
|
231
|
+
const GITHUB_USERNAME_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;
|
|
232
|
+
const COLLABORATORS_KEYS = new Set(["users", "deleteOrphaned", "inherit"]);
|
|
233
|
+
function validateSettingsCollaborators(settings, context) {
|
|
234
|
+
if (settings.collaborators === undefined)
|
|
235
|
+
return;
|
|
236
|
+
if (!isPlainObject(settings.collaborators)) {
|
|
237
|
+
throw new ValidationError(`${context}: collaborators must be an object`);
|
|
238
|
+
}
|
|
239
|
+
const collaborators = settings.collaborators;
|
|
240
|
+
for (const key of Object.keys(collaborators)) {
|
|
241
|
+
if (!COLLABORATORS_KEYS.has(key)) {
|
|
242
|
+
throw new ValidationError(`${context}: collaborators: unknown key '${key}'`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
for (const key of ["deleteOrphaned", "inherit"]) {
|
|
246
|
+
const value = collaborators[key];
|
|
247
|
+
if (value !== undefined && typeof value !== "boolean") {
|
|
248
|
+
throw new ValidationError(`${context}: collaborators.${key} must be a boolean`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const users = collaborators.users;
|
|
252
|
+
if (users === undefined)
|
|
253
|
+
return;
|
|
254
|
+
if (!Array.isArray(users)) {
|
|
255
|
+
throw new ValidationError(`${context}: collaborators.users must be an array of GitHub usernames`);
|
|
256
|
+
}
|
|
257
|
+
for (const user of users) {
|
|
258
|
+
if (typeof user !== "string" || !GITHUB_USERNAME_PATTERN.test(user)) {
|
|
259
|
+
throw new ValidationError(`${context}: collaborators.users entry '${String(user)}' is not a valid GitHub username`);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
231
263
|
export function validateSettings(settings, context, rootCtx) {
|
|
232
264
|
if (!isPlainObject(settings)) {
|
|
233
265
|
throw new ValidationError(`${context}: settings must be an object`);
|
|
@@ -238,6 +270,7 @@ export function validateSettings(settings, context, rootCtx) {
|
|
|
238
270
|
validateSettingsRepo(settings, context, rootCtx);
|
|
239
271
|
validateSettingsCodeScanning(settings, context, rootCtx);
|
|
240
272
|
validateSettingsSecrets(settings, context);
|
|
273
|
+
validateSettingsCollaborators(settings, context);
|
|
241
274
|
}
|
|
242
275
|
export function enrichSettingsContext(rootCtx, settings) {
|
|
243
276
|
if (!settings)
|
|
@@ -30,6 +30,7 @@ export declare class GitHubLifecycleProvider implements IRepoLifecycleProvider {
|
|
|
30
30
|
*/
|
|
31
31
|
private isOrganization;
|
|
32
32
|
private assertGitHub;
|
|
33
|
+
private assertTokenCanCreateRepo;
|
|
33
34
|
private buildGhApiPrefix;
|
|
34
35
|
exists(params: LifecycleExistsParams): Promise<boolean>;
|
|
35
36
|
create(params: LifecycleCreateParams): Promise<void>;
|
|
@@ -41,6 +41,14 @@ const POST_CREATE_PERMANENT_PATTERNS = [
|
|
|
41
41
|
* Interval between fork readiness checks (2 seconds).
|
|
42
42
|
*/
|
|
43
43
|
const FORK_POLL_INTERVAL_MS = 2_000;
|
|
44
|
+
function isInstallationToken(token) {
|
|
45
|
+
return token?.startsWith("ghs_") ?? false;
|
|
46
|
+
}
|
|
47
|
+
function personalAccountInstallationTokenError(repoInfo) {
|
|
48
|
+
return new LifecycleError(`An installation token (GitHub App or Actions GITHUB_TOKEN) cannot create repositories for personal account '${repoInfo.owner}'. ` +
|
|
49
|
+
`Create ${repoInfo.owner}/${repoInfo.repo} first, or run lifecycle with a personal access token. ` +
|
|
50
|
+
`Installation tokens can only create repositories in organizations.`);
|
|
51
|
+
}
|
|
44
52
|
function buildRepoCreateArgs(args, settings) {
|
|
45
53
|
if (settings?.visibility === "public") {
|
|
46
54
|
args.push("--public");
|
|
@@ -102,11 +110,10 @@ export class GitHubLifecycleProvider {
|
|
|
102
110
|
if (isPermanentError(error)) {
|
|
103
111
|
throw error;
|
|
104
112
|
}
|
|
105
|
-
// This may cause fork to fail with a misleading error for personal accounts.
|
|
106
113
|
const errMsg = toErrorMessage(error);
|
|
107
114
|
this.log?.debug(`Could not determine if '${owner}' is an organization, defaulting to org behavior: ${errMsg}`);
|
|
108
115
|
this.log?.warn(`Could not verify if '${owner}' is an organization or user account. ` +
|
|
109
|
-
`If
|
|
116
|
+
`If the operation fails, check your authentication (gh auth status) and ensure the ` +
|
|
110
117
|
`target owner is correct.`);
|
|
111
118
|
return true;
|
|
112
119
|
}
|
|
@@ -114,6 +121,22 @@ export class GitHubLifecycleProvider {
|
|
|
114
121
|
assertGitHub(repoInfo) {
|
|
115
122
|
assertGitHubRepo(repoInfo, "GitHubLifecycleProvider");
|
|
116
123
|
}
|
|
124
|
+
// GitHub refuses installation tokens on POST /user/repos with a misleading
|
|
125
|
+
// "403 Rate Limit Exceeded", which withRetry treats as transient.
|
|
126
|
+
async assertTokenCanCreateRepo(repoInfo, token) {
|
|
127
|
+
if (!isInstallationToken(token))
|
|
128
|
+
return;
|
|
129
|
+
let isOrg;
|
|
130
|
+
try {
|
|
131
|
+
isOrg = await this.isOrganization(repoInfo.owner, repoInfo, token);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
this.log?.debug(`Skipping installation token owner check for '${repoInfo.owner}': ${toErrorMessage(error)}`);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (!isOrg)
|
|
138
|
+
throw personalAccountInstallationTokenError(repoInfo);
|
|
139
|
+
}
|
|
117
140
|
buildGhApiPrefix(repoInfo, token) {
|
|
118
141
|
const tokenEnv = buildTokenEnv(token);
|
|
119
142
|
const hostnameArgs = buildHostnameArgs(repoInfo);
|
|
@@ -135,17 +158,16 @@ export class GitHubLifecycleProvider {
|
|
|
135
158
|
return true;
|
|
136
159
|
}
|
|
137
160
|
catch (error) {
|
|
138
|
-
// Distinguish "repo not found" from actual errors
|
|
139
161
|
if (isRepoNotFoundError(error)) {
|
|
140
162
|
return false;
|
|
141
163
|
}
|
|
142
|
-
// Re-throw network/auth errors
|
|
143
164
|
throw error;
|
|
144
165
|
}
|
|
145
166
|
}
|
|
146
167
|
async create(params) {
|
|
147
168
|
const { repo: repoInfo, settings, token } = params;
|
|
148
169
|
this.assertGitHub(repoInfo);
|
|
170
|
+
await this.assertTokenCanCreateRepo(repoInfo, token);
|
|
149
171
|
const tokenEnv = buildTokenEnv(token);
|
|
150
172
|
const args = [
|
|
151
173
|
"repo",
|
|
@@ -159,10 +181,8 @@ export class GitHubLifecycleProvider {
|
|
|
159
181
|
await withRetry(() => this.executor.exec("gh", args, this.cwd, { env: tokenEnv }), {
|
|
160
182
|
retries: this.retries,
|
|
161
183
|
});
|
|
162
|
-
// Rename default branch if requested and it differs from what GitHub created.
|
|
163
184
|
if (settings?.defaultBranch) {
|
|
164
185
|
const { tokenEnv: branchTokenEnv, baseArgs, apiPath, } = this.buildGhApiPrefix(repoInfo, token);
|
|
165
|
-
// Detect the actual default branch name
|
|
166
186
|
const actualBranch = (await withRetry(() => this.executor.exec("gh", [...baseArgs, apiPath, "--jq", ".default_branch"], this.cwd, { env: branchTokenEnv }), {
|
|
167
187
|
retries: this.retries,
|
|
168
188
|
permanentErrorPatterns: POST_CREATE_PERMANENT_PATTERNS,
|
|
@@ -183,17 +203,15 @@ export class GitHubLifecycleProvider {
|
|
|
183
203
|
const { upstream, target, settings, token } = params;
|
|
184
204
|
this.assertGitHub(upstream);
|
|
185
205
|
this.assertGitHub(target);
|
|
186
|
-
// Guard: cannot fork a repo to the same owner
|
|
187
206
|
if (upstream.owner.toLowerCase() === target.owner.toLowerCase()) {
|
|
188
207
|
throw new LifecycleError(`Cannot fork ${upstream.owner}/${upstream.repo} to the same owner '${target.owner}'. ` +
|
|
189
208
|
`The upstream and target owners must be different.`);
|
|
190
209
|
}
|
|
191
|
-
// Determine if target owner is an organization or user
|
|
192
210
|
const isOrg = await this.isOrganization(target.owner, target, token);
|
|
211
|
+
if (!isOrg && isInstallationToken(token)) {
|
|
212
|
+
throw personalAccountInstallationTokenError(target);
|
|
213
|
+
}
|
|
193
214
|
const tokenEnv = buildTokenEnv(token);
|
|
194
|
-
// Build fork command
|
|
195
|
-
// For orgs: gh repo fork <upstream> --org <target-org> --fork-name <name> --clone=false
|
|
196
|
-
// For users: gh repo fork <upstream> --fork-name <name> --clone=false
|
|
197
215
|
const forkArgs = ["repo", "fork", `${upstream.owner}/${upstream.repo}`];
|
|
198
216
|
if (isOrg) {
|
|
199
217
|
forkArgs.push("--org", target.owner);
|
|
@@ -208,7 +226,6 @@ export class GitHubLifecycleProvider {
|
|
|
208
226
|
pollMs: this.forkPollIntervalMs,
|
|
209
227
|
token,
|
|
210
228
|
});
|
|
211
|
-
// Apply settings after fork (visibility, description, etc.)
|
|
212
229
|
if (settings?.visibility || settings?.description) {
|
|
213
230
|
await this.applyRepoSettings(target, settings, token);
|
|
214
231
|
}
|
|
@@ -263,6 +280,7 @@ export class GitHubLifecycleProvider {
|
|
|
263
280
|
async receiveMigration(params) {
|
|
264
281
|
const { repo: repoInfo, sourceDir, settings, token } = params;
|
|
265
282
|
this.assertGitHub(repoInfo);
|
|
283
|
+
await this.assertTokenCanCreateRepo(repoInfo, token);
|
|
266
284
|
await this.removeOriginRemote(sourceDir);
|
|
267
285
|
await this.cleanNonStandardRefs(sourceDir);
|
|
268
286
|
await this.renameMirrorDefaultBranch(sourceDir, settings?.defaultBranch);
|
|
@@ -378,13 +396,11 @@ export class GitHubLifecycleProvider {
|
|
|
378
396
|
*/
|
|
379
397
|
async deleteReadme(repoInfo, token) {
|
|
380
398
|
const { tokenEnv, baseArgs, apiPath } = this.buildGhApiPrefix(repoInfo, token);
|
|
381
|
-
// Get the SHA of the README.md created by --add-readme
|
|
382
399
|
const fileInfo = await withRetry(() => this.executor.exec("gh", [...baseArgs, `${apiPath}/contents/README.md`, "--jq", ".sha"], this.cwd, { env: tokenEnv }), {
|
|
383
400
|
retries: this.retries,
|
|
384
401
|
permanentErrorPatterns: POST_CREATE_PERMANENT_PATTERNS,
|
|
385
402
|
});
|
|
386
403
|
const sha = fileInfo.trim();
|
|
387
|
-
// Delete the README.md to leave the repo clean
|
|
388
404
|
await withRetry(() => this.executor.exec("gh", [
|
|
389
405
|
...baseArgs,
|
|
390
406
|
`${apiPath}/contents/README.md`,
|
|
@@ -28,6 +28,11 @@ export interface SettingsReport {
|
|
|
28
28
|
update: number;
|
|
29
29
|
delete: number;
|
|
30
30
|
};
|
|
31
|
+
collaborators?: {
|
|
32
|
+
create: number;
|
|
33
|
+
update: number;
|
|
34
|
+
delete: number;
|
|
35
|
+
};
|
|
31
36
|
};
|
|
32
37
|
}
|
|
33
38
|
export interface RepoChanges {
|
|
@@ -42,6 +47,10 @@ export interface RepoChanges {
|
|
|
42
47
|
newValue?: string;
|
|
43
48
|
}[];
|
|
44
49
|
secrets?: SecretsPlanEntry[];
|
|
50
|
+
collaborators?: {
|
|
51
|
+
name: string;
|
|
52
|
+
action: "create" | "delete";
|
|
53
|
+
}[];
|
|
45
54
|
error?: string;
|
|
46
55
|
}
|
|
47
56
|
export declare function hasRepoSettingsChanges(repo: RepoChanges): boolean;
|
|
@@ -9,6 +9,7 @@ export function hasRepoSettingsChanges(repo) {
|
|
|
9
9
|
repo.labels.length > 0 ||
|
|
10
10
|
(repo.variables ?? []).length > 0 ||
|
|
11
11
|
(repo.secrets ?? []).length > 0 ||
|
|
12
|
+
(repo.collaborators ?? []).length > 0 ||
|
|
12
13
|
!!repo.error);
|
|
13
14
|
}
|
|
14
15
|
function renderRulesetConfig(config, startDepth, formatLine) {
|
|
@@ -65,6 +66,11 @@ const SETTINGS_CATEGORIES = [
|
|
|
65
66
|
{ noun: "label", plural: "labels", totals: (t) => t.labels },
|
|
66
67
|
{ noun: "variable", plural: "variables", totals: (t) => t.variables },
|
|
67
68
|
{ noun: "secret", plural: "secrets", totals: (t) => t.secrets },
|
|
69
|
+
{
|
|
70
|
+
noun: "collaborator",
|
|
71
|
+
plural: "collaborators",
|
|
72
|
+
totals: (t) => t.collaborators,
|
|
73
|
+
},
|
|
68
74
|
];
|
|
69
75
|
export function formatSettingsCountEntries(totals, dryRun) {
|
|
70
76
|
return SETTINGS_CATEGORIES.flatMap(({ noun, plural, totals: pick }) => {
|
|
@@ -233,6 +239,13 @@ export function renderRepoSettingsDiffLines(repo, diffLines) {
|
|
|
233
239
|
diffLines.push(`- secret ${quoted(secret.name)}`);
|
|
234
240
|
}
|
|
235
241
|
}
|
|
242
|
+
if ((repo.collaborators ?? []).length > 0 && diffLines.length > startLength) {
|
|
243
|
+
diffLines.push("");
|
|
244
|
+
}
|
|
245
|
+
for (const collaborator of repo.collaborators ?? []) {
|
|
246
|
+
const sign = collaborator.action === "create" ? "+" : "-";
|
|
247
|
+
diffLines.push(`${sign} collaborator ${quoted(collaborator.name)}`);
|
|
248
|
+
}
|
|
236
249
|
if (repo.error) {
|
|
237
250
|
diffLines.push(`- Error: ${repo.error}`);
|
|
238
251
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { GitHubCollaborator, GitHubRepoInvitation } from "./types.js";
|
|
2
|
+
import type { SettingsAction } from "../base-processor.js";
|
|
3
|
+
export type CollaboratorAction = Exclude<SettingsAction, "update">;
|
|
4
|
+
export interface CollaboratorChange {
|
|
5
|
+
action: CollaboratorAction;
|
|
6
|
+
username: string;
|
|
7
|
+
pending?: boolean;
|
|
8
|
+
invitationId?: number;
|
|
9
|
+
}
|
|
10
|
+
export interface CollaboratorsDiffInput {
|
|
11
|
+
owner: string;
|
|
12
|
+
collaborators: GitHubCollaborator[];
|
|
13
|
+
invitations: GitHubRepoInvitation[];
|
|
14
|
+
desired: string[];
|
|
15
|
+
deleteOrphaned: boolean;
|
|
16
|
+
}
|
|
17
|
+
export declare function diffCollaborators(input: CollaboratorsDiffInput): CollaboratorChange[];
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export function diffCollaborators(input) {
|
|
2
|
+
const owner = input.owner.toLowerCase();
|
|
3
|
+
const collaborators = new Map(input.collaborators.map((c) => [c.login.toLowerCase(), c]));
|
|
4
|
+
const invitations = new Map();
|
|
5
|
+
for (const inv of input.invitations) {
|
|
6
|
+
if (inv.invitee) {
|
|
7
|
+
invitations.set(inv.invitee.login.toLowerCase(), {
|
|
8
|
+
id: inv.id,
|
|
9
|
+
login: inv.invitee.login,
|
|
10
|
+
expired: inv.expired === true,
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const desired = new Set(input.desired.map((u) => u.toLowerCase()));
|
|
15
|
+
const changes = [];
|
|
16
|
+
if (input.deleteOrphaned) {
|
|
17
|
+
for (const [key, collaborator] of collaborators) {
|
|
18
|
+
if (desired.has(key) || key === owner)
|
|
19
|
+
continue;
|
|
20
|
+
changes.push({ action: "delete", username: collaborator.login });
|
|
21
|
+
}
|
|
22
|
+
for (const [key, invitation] of invitations) {
|
|
23
|
+
if (desired.has(key) || collaborators.has(key))
|
|
24
|
+
continue;
|
|
25
|
+
changes.push({
|
|
26
|
+
action: "delete",
|
|
27
|
+
username: invitation.login,
|
|
28
|
+
pending: true,
|
|
29
|
+
invitationId: invitation.id,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const unchanged = [];
|
|
34
|
+
for (const user of input.desired) {
|
|
35
|
+
const key = user.toLowerCase();
|
|
36
|
+
const collaborator = collaborators.get(key);
|
|
37
|
+
const invitation = invitations.get(key);
|
|
38
|
+
if (collaborator) {
|
|
39
|
+
unchanged.push({ action: "unchanged", username: collaborator.login });
|
|
40
|
+
}
|
|
41
|
+
else if (invitation && !invitation.expired) {
|
|
42
|
+
unchanged.push({
|
|
43
|
+
action: "unchanged",
|
|
44
|
+
username: invitation.login,
|
|
45
|
+
pending: true,
|
|
46
|
+
invitationId: invitation.id,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
else if (key === owner) {
|
|
50
|
+
unchanged.push({ action: "unchanged", username: user });
|
|
51
|
+
}
|
|
52
|
+
else if (invitation) {
|
|
53
|
+
changes.push({
|
|
54
|
+
action: "create",
|
|
55
|
+
username: user,
|
|
56
|
+
invitationId: invitation.id,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
changes.push({ action: "create", username: user });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return [...changes, ...unchanged];
|
|
64
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { CollaboratorChange, CollaboratorAction } from "./diff.js";
|
|
2
|
+
export interface CollaboratorsPlanEntry {
|
|
3
|
+
name: string;
|
|
4
|
+
action: CollaboratorAction;
|
|
5
|
+
pending?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export interface CollaboratorsPlanResult {
|
|
8
|
+
lines: string[];
|
|
9
|
+
creates: number;
|
|
10
|
+
deletes: number;
|
|
11
|
+
unchanged: number;
|
|
12
|
+
entries: CollaboratorsPlanEntry[];
|
|
13
|
+
}
|
|
14
|
+
export declare function formatCollaboratorsPlan(changes: CollaboratorChange[]): CollaboratorsPlanResult;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import { quoted } from "../../shared/string-utils.js";
|
|
3
|
+
import { countActions } from "../base-processor.js";
|
|
4
|
+
export function formatCollaboratorsPlan(changes) {
|
|
5
|
+
const lines = [];
|
|
6
|
+
const entries = changes.map((c) => c.pending
|
|
7
|
+
? { name: c.username, action: c.action, pending: true }
|
|
8
|
+
: { name: c.username, action: c.action });
|
|
9
|
+
const { create: creates, delete: deletes, unchanged } = countActions(changes);
|
|
10
|
+
const creating = changes.filter((c) => c.action === "create");
|
|
11
|
+
const deleting = changes.filter((c) => c.action === "delete");
|
|
12
|
+
const pending = changes.filter((c) => c.action === "unchanged" && c.pending);
|
|
13
|
+
if (creating.length > 0) {
|
|
14
|
+
lines.push(chalk.bold(" Invite:"));
|
|
15
|
+
for (const c of creating) {
|
|
16
|
+
lines.push(chalk.green(` + collaborator ${quoted(c.username)} (invite)`));
|
|
17
|
+
}
|
|
18
|
+
lines.push("");
|
|
19
|
+
}
|
|
20
|
+
if (deleting.length > 0) {
|
|
21
|
+
lines.push(chalk.bold(" Remove:"));
|
|
22
|
+
for (const c of deleting) {
|
|
23
|
+
const suffix = c.pending ? " (cancel invite)" : "";
|
|
24
|
+
lines.push(chalk.red(` - collaborator ${quoted(c.username)}${suffix}`));
|
|
25
|
+
}
|
|
26
|
+
lines.push("");
|
|
27
|
+
}
|
|
28
|
+
for (const c of pending) {
|
|
29
|
+
lines.push(chalk.dim(` collaborator ${quoted(c.username)}: invite pending`));
|
|
30
|
+
}
|
|
31
|
+
const total = creates + deletes;
|
|
32
|
+
if (total > 0) {
|
|
33
|
+
const parts = [];
|
|
34
|
+
if (creates > 0)
|
|
35
|
+
parts.push(`${creates} to invite`);
|
|
36
|
+
if (deletes > 0)
|
|
37
|
+
parts.push(`${deletes} to remove`);
|
|
38
|
+
lines.push(` Plan: ${total} collaborators (${parts.join(", ")})`);
|
|
39
|
+
}
|
|
40
|
+
return { lines, creates, deletes, unchanged, entries };
|
|
41
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
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 { ICollaboratorsStrategy, GitHubCollaborator, GitHubRepoInvitation } from "./types.js";
|
|
5
|
+
interface GitHubCollaboratorsStrategyOptions {
|
|
6
|
+
retries?: number;
|
|
7
|
+
cwd: string;
|
|
8
|
+
}
|
|
9
|
+
export declare class GitHubCollaboratorsStrategy implements ICollaboratorsStrategy {
|
|
10
|
+
private api;
|
|
11
|
+
constructor(executor: ICommandExecutor, options: GitHubCollaboratorsStrategyOptions);
|
|
12
|
+
listCollaborators(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubCollaborator[]>;
|
|
13
|
+
listInvitations(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubRepoInvitation[]>;
|
|
14
|
+
add(repoInfo: RepoInfo, username: string, options?: GhApiOptions): Promise<void>;
|
|
15
|
+
remove(repoInfo: RepoInfo, username: string, options?: GhApiOptions): Promise<void>;
|
|
16
|
+
cancelInvitation(repoInfo: RepoInfo, invitationId: number, options?: GhApiOptions): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,43 @@
|
|
|
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 CONTEXT = "GitHub Collaborators strategy";
|
|
5
|
+
export class GitHubCollaboratorsStrategy {
|
|
6
|
+
api;
|
|
7
|
+
constructor(executor, options) {
|
|
8
|
+
this.api = new GhApiClient(executor, options.retries ?? 3, options.cwd);
|
|
9
|
+
}
|
|
10
|
+
async listCollaborators(repoInfo, options) {
|
|
11
|
+
assertGitHubRepo(repoInfo, CONTEXT);
|
|
12
|
+
const endpoint = `/repos/${repoInfo.owner}/${repoInfo.repo}/collaborators?affiliation=direct`;
|
|
13
|
+
const result = await this.api.call("GET", endpoint, {
|
|
14
|
+
options,
|
|
15
|
+
paginate: true,
|
|
16
|
+
});
|
|
17
|
+
return parseApiJson(result, "collaborators response");
|
|
18
|
+
}
|
|
19
|
+
async listInvitations(repoInfo, options) {
|
|
20
|
+
assertGitHubRepo(repoInfo, CONTEXT);
|
|
21
|
+
const endpoint = `/repos/${repoInfo.owner}/${repoInfo.repo}/invitations`;
|
|
22
|
+
const result = await this.api.call("GET", endpoint, {
|
|
23
|
+
options,
|
|
24
|
+
paginate: true,
|
|
25
|
+
});
|
|
26
|
+
return parseApiJson(result, "invitations response");
|
|
27
|
+
}
|
|
28
|
+
async add(repoInfo, username, options) {
|
|
29
|
+
assertGitHubRepo(repoInfo, CONTEXT);
|
|
30
|
+
const endpoint = `/repos/${repoInfo.owner}/${repoInfo.repo}/collaborators/${encodeURIComponent(username)}`;
|
|
31
|
+
await this.api.call("PUT", endpoint, { options });
|
|
32
|
+
}
|
|
33
|
+
async remove(repoInfo, username, options) {
|
|
34
|
+
assertGitHubRepo(repoInfo, CONTEXT);
|
|
35
|
+
const endpoint = `/repos/${repoInfo.owner}/${repoInfo.repo}/collaborators/${encodeURIComponent(username)}`;
|
|
36
|
+
await this.api.call("DELETE", endpoint, { options });
|
|
37
|
+
}
|
|
38
|
+
async cancelInvitation(repoInfo, invitationId, options) {
|
|
39
|
+
assertGitHubRepo(repoInfo, CONTEXT);
|
|
40
|
+
const endpoint = `/repos/${repoInfo.owner}/${repoInfo.repo}/invitations/${invitationId}`;
|
|
41
|
+
await this.api.call("DELETE", endpoint, { options });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { type CollaboratorChange, type CollaboratorAction } from "./diff.js";
|
|
2
|
+
export { type CollaboratorsPlanEntry } from "./formatter.js";
|
|
3
|
+
export { CollaboratorsProcessor, type ICollaboratorsProcessor, } from "./processor.js";
|
|
4
|
+
export { GitHubCollaboratorsStrategy } from "./github-collaborators-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 CollaboratorsPlanResult } from "./formatter.js";
|
|
4
|
+
import type { ICollaboratorsStrategy } from "./types.js";
|
|
5
|
+
import { type BaseProcessorOptions, type BaseProcessorResult, type ISettingsProcessor, type ChangeCounts } from "../base-processor.js";
|
|
6
|
+
export type ICollaboratorsProcessor = ISettingsProcessor<CollaboratorsProcessorOptions, CollaboratorsProcessorResult>;
|
|
7
|
+
export interface CollaboratorsProcessorOptions extends BaseProcessorOptions {
|
|
8
|
+
noDelete?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface CollaboratorsProcessorResult extends BaseProcessorResult {
|
|
11
|
+
changes?: ChangeCounts;
|
|
12
|
+
planOutput?: CollaboratorsPlanResult;
|
|
13
|
+
warnings?: string[];
|
|
14
|
+
}
|
|
15
|
+
export declare class CollaboratorsProcessor implements ICollaboratorsProcessor {
|
|
16
|
+
private readonly strategy;
|
|
17
|
+
private readonly metadataProvider;
|
|
18
|
+
constructor(strategy: ICollaboratorsStrategy, metadataProvider: IRepoMetadataProvider);
|
|
19
|
+
process(repoConfig: RepoConfig, repoInfo: RepoInfo, options: CollaboratorsProcessorOptions): Promise<CollaboratorsProcessorResult>;
|
|
20
|
+
private applySettings;
|
|
21
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { diffCollaborators } from "./diff.js";
|
|
2
|
+
import { formatCollaboratorsPlan, } from "./formatter.js";
|
|
3
|
+
import { withGitHubGuards, countActions, buildDryRunResult, buildApplyResult, } from "../base-processor.js";
|
|
4
|
+
export class CollaboratorsProcessor {
|
|
5
|
+
strategy;
|
|
6
|
+
metadataProvider;
|
|
7
|
+
constructor(strategy, metadataProvider) {
|
|
8
|
+
this.strategy = strategy;
|
|
9
|
+
this.metadataProvider = metadataProvider;
|
|
10
|
+
}
|
|
11
|
+
async process(repoConfig, repoInfo, options) {
|
|
12
|
+
return withGitHubGuards(repoConfig, repoInfo, options, {
|
|
13
|
+
hasDesiredSettings: (rc) => {
|
|
14
|
+
const c = rc.settings?.collaborators;
|
|
15
|
+
return (c?.users ?? []).length > 0 || c?.deleteOrphaned === true;
|
|
16
|
+
},
|
|
17
|
+
emptySettingsMessage: "No collaborators configured",
|
|
18
|
+
applySettings: (githubRepo, rc, opts, token, repoName) => this.applySettings(githubRepo, rc, opts, token, repoName),
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
async applySettings(githubRepo, repoConfig, options, effectiveToken, repoName) {
|
|
22
|
+
const { dryRun, noDelete } = options;
|
|
23
|
+
const desired = repoConfig.settings?.collaborators ?? {};
|
|
24
|
+
const strategyOptions = { token: effectiveToken, host: githubRepo.host };
|
|
25
|
+
const metadata = await this.metadataProvider.getMetadata(githubRepo, strategyOptions);
|
|
26
|
+
if (metadata.ownerType !== "User") {
|
|
27
|
+
return {
|
|
28
|
+
success: true,
|
|
29
|
+
repoName,
|
|
30
|
+
message: "Skipped: collaborators only apply to personal repos",
|
|
31
|
+
skipped: true,
|
|
32
|
+
warnings: [
|
|
33
|
+
`${repoName}: collaborators only apply to personal repos (owner is an organization) - skipped`,
|
|
34
|
+
],
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
const deleteOrphaned = desired.deleteOrphaned === true && !noDelete;
|
|
38
|
+
const [collaborators, invitations] = await Promise.all([
|
|
39
|
+
this.strategy.listCollaborators(githubRepo, strategyOptions),
|
|
40
|
+
this.strategy.listInvitations(githubRepo, strategyOptions),
|
|
41
|
+
]);
|
|
42
|
+
const changes = diffCollaborators({
|
|
43
|
+
owner: githubRepo.owner,
|
|
44
|
+
collaborators,
|
|
45
|
+
invitations,
|
|
46
|
+
desired: desired.users ?? [],
|
|
47
|
+
deleteOrphaned,
|
|
48
|
+
});
|
|
49
|
+
const changeCounts = countActions(changes);
|
|
50
|
+
const planOutput = formatCollaboratorsPlan(changes);
|
|
51
|
+
if (dryRun) {
|
|
52
|
+
return buildDryRunResult(repoName, changeCounts, { planOutput });
|
|
53
|
+
}
|
|
54
|
+
let appliedCount = 0;
|
|
55
|
+
for (const change of changes) {
|
|
56
|
+
if (change.action === "create") {
|
|
57
|
+
if (change.invitationId !== undefined) {
|
|
58
|
+
await this.strategy.cancelInvitation(githubRepo, change.invitationId, strategyOptions);
|
|
59
|
+
}
|
|
60
|
+
await this.strategy.add(githubRepo, change.username, strategyOptions);
|
|
61
|
+
appliedCount++;
|
|
62
|
+
}
|
|
63
|
+
else if (change.action === "delete") {
|
|
64
|
+
if (change.pending && change.invitationId !== undefined) {
|
|
65
|
+
await this.strategy.cancelInvitation(githubRepo, change.invitationId, strategyOptions);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
await this.strategy.remove(githubRepo, change.username, strategyOptions);
|
|
69
|
+
}
|
|
70
|
+
appliedCount++;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return buildApplyResult(repoName, changeCounts, appliedCount, {
|
|
74
|
+
planOutput,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { RepoInfo } from "../../repo/index.js";
|
|
2
|
+
import type { GhApiOptions } from "../../shared/gh-api-utils.js";
|
|
3
|
+
export interface GitHubCollaborator {
|
|
4
|
+
login: string;
|
|
5
|
+
}
|
|
6
|
+
export interface GitHubRepoInvitation {
|
|
7
|
+
id: number;
|
|
8
|
+
invitee: {
|
|
9
|
+
login: string;
|
|
10
|
+
} | null;
|
|
11
|
+
expired?: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface ICollaboratorsStrategy {
|
|
14
|
+
listCollaborators(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubCollaborator[]>;
|
|
15
|
+
listInvitations(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubRepoInvitation[]>;
|
|
16
|
+
add(repoInfo: RepoInfo, username: string, options?: GhApiOptions): Promise<void>;
|
|
17
|
+
remove(repoInfo: RepoInfo, username: string, options?: GhApiOptions): Promise<void>;
|
|
18
|
+
cancelInvitation(repoInfo: RepoInfo, invitationId: number, options?: GhApiOptions): Promise<void>;
|
|
19
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/settings/index.d.ts
CHANGED
|
@@ -4,4 +4,5 @@ export { RepoSettingsProcessor, type IRepoSettingsProcessor, type RepoSettingsPl
|
|
|
4
4
|
export { type LabelsPlanEntry, LabelsProcessor, type ILabelsProcessor, GitHubLabelsStrategy, } from "./labels/index.js";
|
|
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
|
+
export { type CollaboratorsPlanEntry, CollaboratorsProcessor, type ICollaboratorsProcessor, GitHubCollaboratorsStrategy, } from "./collaborators/index.js";
|
|
7
8
|
export { SecretsProcessor, type SecretsPlanEntry, type ISecretsProcessor, type SecretsProcessorOptions, type SecretsProcessorResult, GitHubSecretsStrategy, SodiumEncryptor, type ISecretEncryptor, } from "./secrets/index.js";
|
package/dist/settings/index.js
CHANGED
|
@@ -4,5 +4,6 @@ export { RepoSettingsProcessor, GitHubRepoSettingsStrategy, } from "./repo-setti
|
|
|
4
4
|
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
|
+
export { CollaboratorsProcessor, GitHubCollaboratorsStrategy, } from "./collaborators/index.js";
|
|
7
8
|
// Secrets — not wired into `xfg sync`; driven by `xfg secrets sync` only.
|
|
8
9
|
export { SecretsProcessor, GitHubSecretsStrategy, SodiumEncryptor, } from "./secrets/index.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aspruyt/xfg",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.4.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",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"docs:generate": "tsx scripts/docs/generate-docs.ts",
|
|
39
39
|
"docs:check": "tsx scripts/docs/generate-docs.ts --check",
|
|
40
40
|
"test": "node --import tsx scripts/run-tests.js",
|
|
41
|
-
"test:coverage": "c8 --check-coverage --lines 95 --reporter=text --reporter=lcov --all --src=src --exclude='test/**/*.test.ts' --exclude='scripts/**' --exclude='src/vcs/types.ts' --exclude='src/settings/rulesets/types.ts' --exclude='src/settings/repo-settings/types.ts' --exclude='src/settings/labels/types.ts' --exclude='src/**/index.ts' --exclude='test/mocks/**' --exclude='src/sync/types.ts' --exclude='src/lifecycle/types.ts' --exclude='src/cli/program.ts' --exclude='src/repo/types.ts' --exclude='src/settings/secrets/types.ts' --exclude='src/settings/code-scanning/types.ts' --exclude='src/settings/variables/types.ts' --exclude='src/ai/types.ts' --exclude='src/cli/types.ts' --exclude='src/cli.ts' --exclude='src/index.ts' npm test",
|
|
41
|
+
"test:coverage": "c8 --check-coverage --lines 95 --reporter=text --reporter=lcov --all --src=src --exclude='test/**/*.test.ts' --exclude='scripts/**' --exclude='src/vcs/types.ts' --exclude='src/settings/rulesets/types.ts' --exclude='src/settings/repo-settings/types.ts' --exclude='src/settings/labels/types.ts' --exclude='src/**/index.ts' --exclude='test/mocks/**' --exclude='src/sync/types.ts' --exclude='src/lifecycle/types.ts' --exclude='src/cli/program.ts' --exclude='src/repo/types.ts' --exclude='src/settings/secrets/types.ts' --exclude='src/settings/code-scanning/types.ts' --exclude='src/settings/variables/types.ts' --exclude='src/settings/collaborators/types.ts' --exclude='src/ai/types.ts' --exclude='src/cli/types.ts' --exclude='src/cli.ts' --exclude='src/index.ts' npm test",
|
|
42
42
|
"test:integration:github": "npm run build && node --import tsx --test test/integration/github.test.ts",
|
|
43
43
|
"test:integration:ado": "npm run build && node --import tsx --test test/integration/ado.test.ts",
|
|
44
44
|
"test:integration:gitlab": "npm run build && node --import tsx --test test/integration/gitlab.test.ts",
|
|
@@ -47,6 +47,7 @@
|
|
|
47
47
|
"test:integration:github-rulesets": "npm run build && node --import tsx --test test/integration/github-rulesets.test.ts",
|
|
48
48
|
"test:integration:github-secrets": "npm run build && node --import tsx --test test/integration/github-secrets.test.ts",
|
|
49
49
|
"test:integration:github-variables": "npm run build && node --import tsx --test test/integration/github-variables.test.ts",
|
|
50
|
+
"test:integration:github-collaborators": "npm run build && node --import tsx --test test/integration/github-collaborators.test.ts",
|
|
50
51
|
"test:integration:github-repo-settings": "npm run build && node --import tsx --test test/integration/github-repo-settings.test.ts",
|
|
51
52
|
"test:integration:github-labels": "npm run build && node --import tsx --test test/integration/github-labels.test.ts",
|
|
52
53
|
"test:integration:github-code-scanning": "npm run build && node --import tsx --test test/integration/github-code-scanning.test.ts",
|