@teambit/ci 1.0.485 → 1.0.487
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/ci.docs.mdx +344 -83
- package/commands/sync.cmd.ts +77 -0
- package/dist/ci.docs.mdx +344 -83
- package/dist/ci.main.runtime.d.ts +67 -6
- package/dist/ci.main.runtime.js +152 -25
- package/dist/ci.main.runtime.js.map +1 -1
- package/dist/commands/sync.cmd.d.ts +34 -0
- package/dist/commands/sync.cmd.js +57 -0
- package/dist/commands/sync.cmd.js.map +1 -0
- package/dist/git.d.ts +11 -1
- package/dist/git.js +11 -1
- package/dist/git.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +26 -1
- package/dist/index.js.map +1 -1
- package/dist/{preview-1785858957533.js → preview-1785883495880.js} +1 -1
- package/dist/sync/git-host-provider.d.ts +47 -0
- package/dist/sync/git-host-provider.js +54 -0
- package/dist/sync/git-host-provider.js.map +1 -0
- package/dist/sync/git-host-provider.spec.d.ts +1 -0
- package/dist/sync/git-host-provider.spec.js +171 -0
- package/dist/sync/git-host-provider.spec.js.map +1 -0
- package/dist/sync/git-ops.d.ts +171 -0
- package/dist/sync/git-ops.js +354 -0
- package/dist/sync/git-ops.js.map +1 -0
- package/dist/sync/git-ops.spec.d.ts +1 -0
- package/dist/sync/git-ops.spec.js +476 -0
- package/dist/sync/git-ops.spec.js.map +1 -0
- package/dist/sync/github-client.d.ts +79 -0
- package/dist/sync/github-client.js +198 -0
- package/dist/sync/github-client.js.map +1 -0
- package/dist/sync/github-client.spec.d.ts +1 -0
- package/dist/sync/github-client.spec.js +205 -0
- package/dist/sync/github-client.spec.js.map +1 -0
- package/dist/sync/init-scaffold.d.ts +40 -0
- package/dist/sync/init-scaffold.js +326 -0
- package/dist/sync/init-scaffold.js.map +1 -0
- package/dist/sync/init-scaffold.spec.d.ts +1 -0
- package/dist/sync/init-scaffold.spec.js +169 -0
- package/dist/sync/init-scaffold.spec.js.map +1 -0
- package/dist/sync/lane-sync-executor.d.ts +256 -0
- package/dist/sync/lane-sync-executor.js +1249 -0
- package/dist/sync/lane-sync-executor.js.map +1 -0
- package/dist/sync/lane-sync-executor.spec.d.ts +1 -0
- package/dist/sync/lane-sync-executor.spec.js +416 -0
- package/dist/sync/lane-sync-executor.spec.js.map +1 -0
- package/dist/sync/main-sync-executor.d.ts +62 -0
- package/dist/sync/main-sync-executor.js +305 -0
- package/dist/sync/main-sync-executor.js.map +1 -0
- package/dist/sync/sync-config.d.ts +83 -0
- package/dist/sync/sync-config.js +187 -0
- package/dist/sync/sync-config.js.map +1 -0
- package/dist/sync/sync-config.spec.d.ts +1 -0
- package/dist/sync/sync-config.spec.js +254 -0
- package/dist/sync/sync-config.spec.js.map +1 -0
- package/dist/sync/sync-orchestrator.d.ts +76 -0
- package/dist/sync/sync-orchestrator.js +396 -0
- package/dist/sync/sync-orchestrator.js.map +1 -0
- package/dist/sync/sync-orchestrator.spec.d.ts +1 -0
- package/dist/sync/sync-orchestrator.spec.js +155 -0
- package/dist/sync/sync-orchestrator.spec.js.map +1 -0
- package/dist/sync/sync-planner.d.ts +60 -0
- package/dist/sync/sync-planner.js +114 -0
- package/dist/sync/sync-planner.js.map +1 -0
- package/dist/sync/sync-planner.spec.d.ts +1 -0
- package/dist/sync/sync-planner.spec.js +210 -0
- package/dist/sync/sync-planner.spec.js.map +1 -0
- package/dist/sync/sync-state.d.ts +94 -0
- package/dist/sync/sync-state.js +178 -0
- package/dist/sync/sync-state.js.map +1 -0
- package/dist/sync/sync-state.spec.d.ts +1 -0
- package/dist/sync/sync-state.spec.js +271 -0
- package/dist/sync/sync-state.spec.js.map +1 -0
- package/dist/sync/workspace-lane.d.ts +13 -0
- package/dist/sync/workspace-lane.js +27 -0
- package/dist/sync/workspace-lane.js.map +1 -0
- package/package.json +20 -15
- package/sync/git-host-provider.spec.ts +197 -0
- package/sync/git-host-provider.ts +89 -0
- package/sync/git-ops.spec.ts +506 -0
- package/sync/git-ops.ts +334 -0
- package/sync/github-client.spec.ts +174 -0
- package/sync/github-client.ts +209 -0
- package/sync/init-scaffold.spec.ts +142 -0
- package/sync/init-scaffold.ts +340 -0
- package/sync/lane-sync-executor.spec.ts +389 -0
- package/sync/lane-sync-executor.ts +1363 -0
- package/sync/main-sync-executor.ts +321 -0
- package/sync/sync-config.spec.ts +283 -0
- package/sync/sync-config.ts +214 -0
- package/sync/sync-orchestrator.spec.ts +120 -0
- package/sync/sync-orchestrator.ts +386 -0
- package/sync/sync-planner.spec.ts +126 -0
- package/sync/sync-planner.ts +99 -0
- package/sync/sync-state.spec.ts +263 -0
- package/sync/sync-state.ts +176 -0
- package/sync/workspace-lane.ts +20 -0
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { formatTitle, formatWarningSummary } from '@teambit/cli';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { BitError } from '@teambit/bit-error';
|
|
4
|
+
import type { Logger } from '@teambit/logger';
|
|
5
|
+
import type { Workspace } from '@teambit/workspace';
|
|
6
|
+
import type { LanesMain } from '@teambit/lanes';
|
|
7
|
+
import type { CheckoutMain } from '@teambit/checkout';
|
|
8
|
+
import { CiAspect } from '../ci.aspect';
|
|
9
|
+
import type { CiMain, CiWorkspaceConfig } from '../ci.main.runtime';
|
|
10
|
+
import { git } from '../git';
|
|
11
|
+
import type { CiSyncConfig } from './sync-config';
|
|
12
|
+
import {
|
|
13
|
+
branchToLaneName,
|
|
14
|
+
laneNameToBranch,
|
|
15
|
+
parseLaneTarget,
|
|
16
|
+
resolveSyncConfig,
|
|
17
|
+
shouldSyncLane,
|
|
18
|
+
syncableLaneNameForBranch,
|
|
19
|
+
} from './sync-config';
|
|
20
|
+
import { HALT_SUMMARY_PREFIX, REFUSED_SUMMARY_PREFIX, LaneSyncExecutor } from './lane-sync-executor';
|
|
21
|
+
import { MainSyncExecutor } from './main-sync-executor';
|
|
22
|
+
import { selectGitHostProvider } from './git-host-provider';
|
|
23
|
+
import { gitRepoRoot, isNonContentPath, listRemoteBranches } from './git-ops';
|
|
24
|
+
import { deriveOwnerRepo, renderInitChecklist, scaffoldWorkflowFiles } from './init-scaffold';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Refuse a `--dry-run` whose plan would be computed by force-checking-out branches over uncommitted
|
|
28
|
+
* work: the main-scope drift is a diff, so the tree IS written before the dry-run return. A dry run
|
|
29
|
+
* promises to write nothing, so it may not discard either — with a clean tree the write-then-restore
|
|
30
|
+
* loses nothing.
|
|
31
|
+
*/
|
|
32
|
+
export function assertCleanForDryRun(dirtyFiles: string[]): void {
|
|
33
|
+
if (!dirtyFiles.length) return;
|
|
34
|
+
const named = `${dirtyFiles.slice(0, 10).join(', ')}${dirtyFiles.length > 10 ? ', …' : ''}`;
|
|
35
|
+
throw new BitError(
|
|
36
|
+
`bit ci sync --dry-run refuses to run: the working tree has ${dirtyFiles.length} uncommitted change(s), ` +
|
|
37
|
+
`and computing the plan force-checkouts branches and removes untracked files, which would discard ` +
|
|
38
|
+
`them. Commit or stash them first: ${named}`
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Everything the sync orchestration needs from `CiMain`, passed explicitly. */
|
|
43
|
+
export type SyncOrchestratorDeps = {
|
|
44
|
+
ci: CiMain;
|
|
45
|
+
workspace: Workspace;
|
|
46
|
+
logger: Logger;
|
|
47
|
+
lanes: LanesMain;
|
|
48
|
+
checkout: CheckoutMain;
|
|
49
|
+
config: CiWorkspaceConfig;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Routing and aggregation for `bit ci sync`: decides which targets a run visits and how their
|
|
54
|
+
* summaries combine. What reconciling a target means lives in the two executors, both stateless and
|
|
55
|
+
* idempotent, so the trigger only ever decides when the reconciler runs.
|
|
56
|
+
*/
|
|
57
|
+
export class SyncOrchestrator {
|
|
58
|
+
constructor(private deps: SyncOrchestratorDeps) {}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* `bit ci sync` — reconcile Bit lanes and the main scope with git branches and pull requests.
|
|
62
|
+
* Returns the per-target summary lines; throws the joined summary after the loop when any target
|
|
63
|
+
* halted or was refused, so CI exits non-zero while every other target was still attempted. A skip
|
|
64
|
+
* is neither — it reports itself and leaves the run green.
|
|
65
|
+
*/
|
|
66
|
+
async sync(
|
|
67
|
+
opts: { lane?: string; branch?: string; all?: boolean; main?: boolean; dryRun?: boolean; init?: boolean } = {}
|
|
68
|
+
): Promise<string> {
|
|
69
|
+
if (opts.init) {
|
|
70
|
+
if (opts.lane || opts.branch || opts.all || opts.main || opts.dryRun) {
|
|
71
|
+
throw new BitError(
|
|
72
|
+
'bit ci sync --init cannot be combined with a lane argument, --branch, --all, --main or ' +
|
|
73
|
+
'--dry-run: it only scaffolds onboarding files (workflows + workspace.jsonc config) and exits ' +
|
|
74
|
+
'— it never reconciles'
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
return this.syncInit();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Refuse contradictory flag combinations rather than silently letting one target win.
|
|
81
|
+
const narrower = opts.lane
|
|
82
|
+
? `a lane argument ("${opts.lane}")`
|
|
83
|
+
: (opts.branch && `--branch ("${opts.branch}")`) || (opts.main && '--main') || undefined;
|
|
84
|
+
if (opts.all && narrower) {
|
|
85
|
+
throw new BitError(
|
|
86
|
+
`--all cannot be combined with ${narrower}: --all reconciles every mapped lane plus the main ` +
|
|
87
|
+
`scope, and is what runs when no target is given`
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// A lane argument, `--branch` and `--main` each select the single target; any two contradict.
|
|
92
|
+
const selectors = [
|
|
93
|
+
opts.lane && `a lane argument ("${opts.lane}")`,
|
|
94
|
+
opts.branch && `--branch ("${opts.branch}")`,
|
|
95
|
+
opts.main && '--main',
|
|
96
|
+
].filter((selector): selector is string => Boolean(selector));
|
|
97
|
+
if (selectors.length > 1) {
|
|
98
|
+
const winner = opts.main ? '--main' : `--branch ("${opts.branch}")`;
|
|
99
|
+
throw new BitError(
|
|
100
|
+
`${selectors[0]} cannot be combined with ${selectors.slice(1).join(' or with ')}: each selects ` +
|
|
101
|
+
`the single target this run reconciles, and only ${winner} would have run — the rest would be ` +
|
|
102
|
+
`silently dropped, leaving a run that reports success while a target you named was never visited`
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const cfg = resolveSyncConfig(this.deps.config.sync);
|
|
107
|
+
const defaultScope = this.deps.workspace.defaultScope;
|
|
108
|
+
const defaultBranch = await this.deps.ci.getDefaultBranchName();
|
|
109
|
+
const mainLaneName = this.deps.lanes.getDefaultLaneId().name;
|
|
110
|
+
|
|
111
|
+
// The executors force-checkout branches and remove untracked files; warn up front, naming the
|
|
112
|
+
// files at stake, before an interactive run discards anything.
|
|
113
|
+
const statusAtStart = await git.status().catch(() => undefined);
|
|
114
|
+
const dirtyFiles = (statusAtStart?.files ?? []).map((file) => file.path).filter((file) => !isNonContentPath(file));
|
|
115
|
+
if (opts.dryRun) assertCleanForDryRun(dirtyFiles);
|
|
116
|
+
if (dirtyFiles.length) {
|
|
117
|
+
this.deps.logger.consoleWarning(
|
|
118
|
+
`the working tree has ${dirtyFiles.length} uncommitted change(s). "bit ci sync" force-checkouts branches ` +
|
|
119
|
+
`and removes untracked files (except .bit/ and node_modules/), so these will be discarded: ` +
|
|
120
|
+
`${dirtyFiles.slice(0, 10).join(', ')}${dirtyFiles.length > 10 ? ', …' : ''}`
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const remoteUrl = await git.remote(['get-url', 'origin']).catch(() => undefined);
|
|
125
|
+
const { provider: gitHost, reason: noGitHostReason } = selectGitHostProvider(
|
|
126
|
+
this.deps.ci.listGitHostProviders(),
|
|
127
|
+
typeof remoteUrl === 'string' ? remoteUrl.trim() : undefined
|
|
128
|
+
);
|
|
129
|
+
if (gitHost) this.deps.logger.debug(`bit ci sync: using the "${gitHost.name}" git host provider`);
|
|
130
|
+
// Warn once, up front — the executors' per-action lines can only say PRs were skipped, not why.
|
|
131
|
+
else if (noGitHostReason) this.deps.logger.consoleWarning(noGitHostReason);
|
|
132
|
+
|
|
133
|
+
const laneSync = new LaneSyncExecutor({
|
|
134
|
+
lanes: this.deps.lanes,
|
|
135
|
+
ci: this.deps.ci,
|
|
136
|
+
logger: this.deps.logger,
|
|
137
|
+
gitHost,
|
|
138
|
+
cfg,
|
|
139
|
+
defaultScope,
|
|
140
|
+
});
|
|
141
|
+
const mainSync = new MainSyncExecutor({
|
|
142
|
+
checkout: this.deps.checkout,
|
|
143
|
+
lanes: this.deps.lanes,
|
|
144
|
+
ci: this.deps.ci,
|
|
145
|
+
logger: this.deps.logger,
|
|
146
|
+
gitHost,
|
|
147
|
+
cfg,
|
|
148
|
+
defaultBranch,
|
|
149
|
+
defaultScope,
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
if (opts.main) {
|
|
153
|
+
return this.summarizeSync([await mainSync.syncMain({ dryRun: opts.dryRun })]);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (opts.branch) {
|
|
157
|
+
const branch = opts.branch;
|
|
158
|
+
// Under the default `branchPrefix: ''` these two would resolve to the bogus lanes "main" /
|
|
159
|
+
// "bit-sync/main"; both are reconciled by the main-scope path, never as lanes.
|
|
160
|
+
if (branch === defaultBranch) {
|
|
161
|
+
return `branch ${branch} is the default branch — reconcile it with "bit ci sync --main"; nothing to do`;
|
|
162
|
+
}
|
|
163
|
+
if (branch === cfg.mainSyncBranch) {
|
|
164
|
+
return `branch ${branch} is the main sync branch maintained by this command; nothing to do`;
|
|
165
|
+
}
|
|
166
|
+
const laneName = syncableLaneNameForBranch(branch, cfg);
|
|
167
|
+
if (!laneName) return `branch ${branch} does not map to a valid lane name; nothing to do`;
|
|
168
|
+
const skipReason = this.laneNotSyncableReason(laneName, cfg, mainLaneName, defaultBranch);
|
|
169
|
+
if (skipReason) return `${skipReason} (branch ${branch})`;
|
|
170
|
+
// A branch name carries no scope, so this path can only resolve the lane against `defaultScope`;
|
|
171
|
+
// resolving a foreign-hosted lane to the wrong scope is safe (no-op, never a deletion).
|
|
172
|
+
return this.summarizeSync([
|
|
173
|
+
await laneSync.syncLane({ hostScope: defaultScope, name: laneName }, { dryRun: opts.dryRun }),
|
|
174
|
+
]);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (opts.lane) {
|
|
178
|
+
// Every guard below is asked about the NAME: "main" is not a lane whichever scope hosts it, and
|
|
179
|
+
// the `lanes` patterns match lane names, not lane ids.
|
|
180
|
+
const target = parseLaneTarget(opts.lane, defaultScope);
|
|
181
|
+
const skipReason = this.laneNotSyncableReason(target.name, cfg, mainLaneName, defaultBranch);
|
|
182
|
+
if (skipReason) return skipReason;
|
|
183
|
+
return this.summarizeSync([await laneSync.syncLane(target, { dryRun: opts.dryRun, explicitTarget: true })]);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// `--all` (also the no-arguments default): every mapped lane, then the main scope. Sequential on
|
|
187
|
+
// purpose — the lanes share one workspace and one git checkout.
|
|
188
|
+
const lines: string[] = [];
|
|
189
|
+
const { lanes: lanesToSync, errors } = await this.listLanesToSync(cfg, mainLaneName, defaultBranch);
|
|
190
|
+
lines.push(...errors);
|
|
191
|
+
this.deps.logger.console(
|
|
192
|
+
formatTitle(
|
|
193
|
+
`Reconciling ${lanesToSync.length} mapped lane(s) of ${defaultScope}` +
|
|
194
|
+
`${lanesToSync.length ? `: ${lanesToSync.join(', ')}` : ''}`
|
|
195
|
+
)
|
|
196
|
+
);
|
|
197
|
+
for (const laneName of lanesToSync) {
|
|
198
|
+
// Every enumerated target is hosted on `defaultScope` by construction; foreign-hosted lanes are
|
|
199
|
+
// explicit-target only.
|
|
200
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
201
|
+
lines.push(await laneSync.syncLane({ hostScope: defaultScope, name: laneName }, { dryRun: opts.dryRun }));
|
|
202
|
+
}
|
|
203
|
+
lines.push(await mainSync.syncMain({ dryRun: opts.dryRun }));
|
|
204
|
+
return this.summarizeSync(lines);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* `bit ci sync --init` — one-command onboarding: scaffolds the two workflow files, adds the sync
|
|
209
|
+
* config block to workspace.jsonc if missing, and prints the manual-steps checklist. Safe to
|
|
210
|
+
* re-run: existing files are skipped, an existing config block is left alone; it never reconciles.
|
|
211
|
+
*/
|
|
212
|
+
private async syncInit(): Promise<string> {
|
|
213
|
+
const defaultBranch = await this.deps.ci.getDefaultBranchName();
|
|
214
|
+
|
|
215
|
+
// Workflows belong to the repository, not the workspace: GitHub only discovers them at
|
|
216
|
+
// `<repo-root>/.github/workflows`, and a bit workspace may be a subdirectory.
|
|
217
|
+
const repoRoot = await gitRepoRoot();
|
|
218
|
+
const scaffoldRoot = repoRoot ?? this.deps.workspace.path;
|
|
219
|
+
if (!repoRoot) {
|
|
220
|
+
this.deps.logger.consoleWarning(
|
|
221
|
+
`could not resolve the git repository root ("git rev-parse --show-toplevel" failed — is this a git ` +
|
|
222
|
+
`repository?). Writing the workflow files under the workspace instead: ${scaffoldRoot}. If that is ` +
|
|
223
|
+
`not the repository root, GitHub will not discover them — move .github/workflows there by hand.`
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const fileOutcomes = scaffoldWorkflowFiles(scaffoldRoot, defaultBranch);
|
|
228
|
+
// Report the path relative to where the user is standing, not to the workspace.
|
|
229
|
+
const displayPath = (relativePath: string) => {
|
|
230
|
+
const abs = path.join(scaffoldRoot, relativePath);
|
|
231
|
+
const fromCwd = path.relative(process.cwd(), abs);
|
|
232
|
+
return fromCwd && !fromCwd.startsWith('..') ? fromCwd : abs;
|
|
233
|
+
};
|
|
234
|
+
const fileLines = fileOutcomes.map((outcome) =>
|
|
235
|
+
outcome.status === 'written'
|
|
236
|
+
? `wrote ${displayPath(outcome.relativePath)} (default branch: ${defaultBranch})`
|
|
237
|
+
: `skipped ${displayPath(outcome.relativePath)} (already exists — bit ci sync --init never overwrites)`
|
|
238
|
+
);
|
|
239
|
+
|
|
240
|
+
const configAdded = await this.ensureSyncConfigBlock();
|
|
241
|
+
const configLine = configAdded
|
|
242
|
+
? 'added "teambit.git/ci": { "sync": {} } to workspace.jsonc'
|
|
243
|
+
: 'workspace.jsonc already configures "teambit.git/ci".sync — left untouched';
|
|
244
|
+
|
|
245
|
+
const remoteUrl = await git.remote(['get-url', 'origin']).catch(() => undefined);
|
|
246
|
+
const ownerRepo = deriveOwnerRepo(typeof remoteUrl === 'string' ? remoteUrl.trim() : undefined);
|
|
247
|
+
|
|
248
|
+
const summary = ['bit ci sync --init', ...fileLines, configLine, renderInitChecklist(ownerRepo)].join('\n');
|
|
249
|
+
this.deps.logger.console(summary);
|
|
250
|
+
return summary;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Add `"sync": {}` under `"teambit.git/ci"` in workspace.jsonc if that key isn't there yet; returns
|
|
255
|
+
* whether it wrote. The comment-preserving `WorkspaceConfig` API merges into existing
|
|
256
|
+
* `teambit.git/ci` config rather than clobbering it.
|
|
257
|
+
*/
|
|
258
|
+
private async ensureSyncConfigBlock(): Promise<boolean> {
|
|
259
|
+
const wsConfig = this.deps.workspace.getWorkspaceConfig();
|
|
260
|
+
const existing = wsConfig.extension(CiAspect.id, true) as CiWorkspaceConfig | undefined;
|
|
261
|
+
if (existing?.sync) return false;
|
|
262
|
+
wsConfig.setExtension(CiAspect.id, { sync: {} }, { mergeIntoExisting: true, ignoreVersion: true });
|
|
263
|
+
await wsConfig.write({ reasonForChange: 'bit ci sync --init: add the sync config block' });
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Why this lane name must not be handed to the lane executor, or undefined when it's syncable. The
|
|
269
|
+
* mapped branch is checked too — the lane path must never write the two branches the main-scope
|
|
270
|
+
* path owns.
|
|
271
|
+
*/
|
|
272
|
+
private laneNotSyncableReason(
|
|
273
|
+
laneName: string,
|
|
274
|
+
cfg: Required<CiSyncConfig>,
|
|
275
|
+
mainLaneName: string,
|
|
276
|
+
defaultBranch: string
|
|
277
|
+
): string | undefined {
|
|
278
|
+
if (laneName === mainLaneName) {
|
|
279
|
+
return `"${mainLaneName}" is not a lane — reconcile the main scope with "bit ci sync --main"; nothing to do`;
|
|
280
|
+
}
|
|
281
|
+
const branch = laneNameToBranch(laneName, cfg);
|
|
282
|
+
if (branch === defaultBranch) {
|
|
283
|
+
return (
|
|
284
|
+
`lane ${laneName} maps to the default branch ${branch} — reconcile it with "bit ci sync --main"; ` +
|
|
285
|
+
`nothing to do`
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
if (branch === cfg.mainSyncBranch) {
|
|
289
|
+
return `lane ${laneName} maps to ${branch}, the main sync branch maintained by this command; nothing to do`;
|
|
290
|
+
}
|
|
291
|
+
if (!shouldSyncLane(laneName, cfg)) {
|
|
292
|
+
return `lane ${laneName} is not matched by the sync config (lanes: ${JSON.stringify(cfg.lanes)}); nothing to do`;
|
|
293
|
+
}
|
|
294
|
+
return undefined;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* The lane names to reconcile on an `--all` run (sorted), plus one HALTED line per enumeration
|
|
299
|
+
* failure. The list is the union of the remote's lanes AND the lane-mapped branches on `origin` —
|
|
300
|
+
* a lane deleted on bit.cloud is gone from the first source, and only the branch side can make
|
|
301
|
+
* `close-pr` fire for it. An enumeration failure is reported rather than thrown, so the half that
|
|
302
|
+
* did enumerate is still reconciled while the run exits non-zero.
|
|
303
|
+
*/
|
|
304
|
+
private async listLanesToSync(
|
|
305
|
+
cfg: Required<CiSyncConfig>,
|
|
306
|
+
mainLaneName: string,
|
|
307
|
+
defaultBranch: string
|
|
308
|
+
): Promise<{ lanes: string[]; errors: string[] }> {
|
|
309
|
+
if (!cfg.lanes.length) {
|
|
310
|
+
this.deps.logger.console(
|
|
311
|
+
formatWarningSummary('sync.lanes is empty — lane mirroring is disabled, reconciling the main scope only')
|
|
312
|
+
);
|
|
313
|
+
return { lanes: [], errors: [] };
|
|
314
|
+
}
|
|
315
|
+
const errors: string[] = [];
|
|
316
|
+
const names = new Set<string>();
|
|
317
|
+
const remote = this.deps.workspace.defaultScope;
|
|
318
|
+
|
|
319
|
+
try {
|
|
320
|
+
const lanes = await this.deps.lanes.getLanes({ remote });
|
|
321
|
+
lanes.forEach((lane) => {
|
|
322
|
+
const name = lane.id?.name ?? lane.name;
|
|
323
|
+
if (name) names.add(name);
|
|
324
|
+
});
|
|
325
|
+
} catch (e: any) {
|
|
326
|
+
const msg = e?.toString() ?? '';
|
|
327
|
+
// A scope with no lanes at all: the remote answers "not found" rather than an empty list.
|
|
328
|
+
if (msg.includes('was not found') || msg.includes('not found')) {
|
|
329
|
+
this.deps.logger.console(
|
|
330
|
+
formatWarningSummary(`No lanes found on ${remote} — reconciling lane-mapped branches and the main scope only`)
|
|
331
|
+
);
|
|
332
|
+
} else {
|
|
333
|
+
errors.push(`${HALT_SUMMARY_PREFIX} lanes -> could not list the lanes of ${remote}: ${msg}`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
try {
|
|
338
|
+
for (const branch of await listRemoteBranches()) {
|
|
339
|
+
// Reconciled by the main-scope path, never as lanes — under the default `branchPrefix: ''`
|
|
340
|
+
// they would otherwise resolve to the bogus lanes "main" / "bit-sync/main".
|
|
341
|
+
if (branch === defaultBranch || branch === cfg.mainSyncBranch) continue;
|
|
342
|
+
// Ordinary developer branches are skipped at debug level, never as a summary line.
|
|
343
|
+
const laneName = syncableLaneNameForBranch(branch, cfg);
|
|
344
|
+
if (!laneName) {
|
|
345
|
+
this.deps.logger.debug(
|
|
346
|
+
`bit ci sync: branch "${branch}" does not map to a name any lane could have ` +
|
|
347
|
+
`(mapped to "${branchToLaneName(branch, cfg) ?? '<not lane-mapped>'}") — skipping it`
|
|
348
|
+
);
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
names.add(laneName);
|
|
352
|
+
}
|
|
353
|
+
} catch (e: any) {
|
|
354
|
+
errors.push(
|
|
355
|
+
`${HALT_SUMMARY_PREFIX} lanes -> could not list the branches of "origin", so a lane deleted on ` +
|
|
356
|
+
`bit.cloud may have kept an orphan branch and an open PR: ${e?.message || e}`
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const lanes = [...names]
|
|
361
|
+
.filter((name) => name !== mainLaneName)
|
|
362
|
+
.filter((name) => shouldSyncLane(name, cfg))
|
|
363
|
+
.sort();
|
|
364
|
+
return { lanes, errors };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Join the per-target summary lines, and turn any halt into a non-zero exit — the executors never
|
|
369
|
+
* throw, so this is the single place "needs a human" becomes visible to CI. `BitError` rather than
|
|
370
|
+
* `Error`: bit reports a plain `Error` as an internal failure (stack trace, Sentry FATAL).
|
|
371
|
+
*/
|
|
372
|
+
private summarizeSync(lines: string[]): string {
|
|
373
|
+
const summary = lines.join('\n');
|
|
374
|
+
const halted = lines.filter((line) => line.startsWith(HALT_SUMMARY_PREFIX));
|
|
375
|
+
if (halted.length) {
|
|
376
|
+
throw new BitError(`bit ci sync could not reconcile ${halted.length} target(s):\n${summary}`);
|
|
377
|
+
}
|
|
378
|
+
// A refusal is not a halt: the repository is healthy, the reconciler simply will not do what was
|
|
379
|
+
// asked — exit non-zero saying that, rather than reporting a sync conflict.
|
|
380
|
+
const refusals = lines.filter((line) => line.startsWith(REFUSED_SUMMARY_PREFIX));
|
|
381
|
+
if (refusals.length) {
|
|
382
|
+
throw new BitError(refusals.map((line) => line.slice(REFUSED_SUMMARY_PREFIX.length).trim()).join('\n'));
|
|
383
|
+
}
|
|
384
|
+
return summary;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { expect } from 'chai';
|
|
2
|
+
import type { LaneOwnershipEvidence, LaneSyncAction, LaneSyncInput } from './sync-planner';
|
|
3
|
+
import { planLaneSync } from './sync-planner';
|
|
4
|
+
|
|
5
|
+
const base: LaneSyncInput = {
|
|
6
|
+
laneHead: 'L1',
|
|
7
|
+
branchExists: true,
|
|
8
|
+
lastSyncedHead: 'L1',
|
|
9
|
+
hasDevCommits: false,
|
|
10
|
+
tipIsSyncCommit: true,
|
|
11
|
+
conflictLabelPresent: false,
|
|
12
|
+
ownership: 'own-live',
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** the "lane deleted remotely, branch still there" shape — the only path that reads `ownership` */
|
|
16
|
+
const laneGone = (ownership: LaneOwnershipEvidence) => ({ laneHead: undefined, ownership });
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The decision table. `action` (exact) is required on every row that decides a branch deletion: under
|
|
20
|
+
* the defaults an ordinary developer branch reaches the planner in the same shape as a deleted lane's
|
|
21
|
+
* branch, so `deleteBranch` and the keep reason are part of the contract, not incidental output.
|
|
22
|
+
*/
|
|
23
|
+
const table: Array<{
|
|
24
|
+
name: string;
|
|
25
|
+
input: Partial<LaneSyncInput>;
|
|
26
|
+
type: LaneSyncAction['type'];
|
|
27
|
+
action?: LaneSyncAction;
|
|
28
|
+
reason?: string;
|
|
29
|
+
}> = [
|
|
30
|
+
{ name: 'converged -> noop', input: {}, type: 'noop', reason: 'converged' },
|
|
31
|
+
{
|
|
32
|
+
name: 'conflict label present -> noop until resolved',
|
|
33
|
+
input: { laneHead: 'L2', conflictLabelPresent: true },
|
|
34
|
+
type: 'noop',
|
|
35
|
+
},
|
|
36
|
+
{ name: 'lane gone + no branch -> noop', input: { laneHead: undefined, branchExists: false }, type: 'noop' },
|
|
37
|
+
|
|
38
|
+
{
|
|
39
|
+
name: "own-live, no dev commits, OUR tip (the branch is exactly the lane's mirror) -> close-pr AND delete",
|
|
40
|
+
input: laneGone('own-live'),
|
|
41
|
+
type: 'close-pr',
|
|
42
|
+
action: { type: 'close-pr', deleteBranch: true },
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
// A developer who commits their own `.bitmap` write looks own-live with nothing above the state
|
|
46
|
+
// commit; the marker is what separates our mirror from their branch.
|
|
47
|
+
name: 'own-live, no dev commits, a tip WE DID NOT WRITE -> close-pr but KEEP the branch',
|
|
48
|
+
input: { ...laneGone('own-live'), tipIsSyncCommit: false },
|
|
49
|
+
type: 'close-pr',
|
|
50
|
+
action: { type: 'close-pr', deleteBranch: false, keepReason: 'tip-not-a-sync-commit' },
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
name: 'own-live WITH dev commits (never-exported work above the state commit) -> KEEP the branch',
|
|
54
|
+
input: { ...laneGone('own-live'), hasDevCommits: true },
|
|
55
|
+
type: 'close-pr',
|
|
56
|
+
action: { type: 'close-pr', deleteBranch: false, keepReason: 'unmerged-commits' },
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
// "tip-not-a-sync-commit" would send the reader after the wrong thing when there is real work.
|
|
60
|
+
name: 'own-live with dev commits AND a foreign tip -> keeps, naming the commits as the reason',
|
|
61
|
+
input: { ...laneGone('own-live'), hasDevCommits: true, tipIsSyncCommit: false },
|
|
62
|
+
type: 'close-pr',
|
|
63
|
+
action: { type: 'close-pr', deleteBranch: false, keepReason: 'unmerged-commits' },
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
name: 'own-merged (branch tip already in the default branch) -> close-pr AND delete',
|
|
67
|
+
input: laneGone('own-merged'),
|
|
68
|
+
type: 'close-pr',
|
|
69
|
+
action: { type: 'close-pr', deleteBranch: true },
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
// Reachability alone proves deleting loses nothing, so no marker conjunction applies here.
|
|
73
|
+
name: 'own-merged deletes even with a foreign tip and dev commits',
|
|
74
|
+
input: { ...laneGone('own-merged'), tipIsSyncCommit: false, hasDevCommits: true },
|
|
75
|
+
type: 'close-pr',
|
|
76
|
+
action: { type: 'close-pr', deleteBranch: true },
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
name: 'own-superseded (PR merged, then more commits pushed) -> close-pr but KEEP the branch',
|
|
80
|
+
input: laneGone('own-superseded'),
|
|
81
|
+
type: 'close-pr',
|
|
82
|
+
action: { type: 'close-pr', deleteBranch: false, keepReason: 'unmerged-commits' },
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
name: 'inherited-or-none -> noop, and never close-pr',
|
|
86
|
+
input: laneGone('inherited-or-none'),
|
|
87
|
+
type: 'noop',
|
|
88
|
+
reason: 'maps to no lane and has no sync history',
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
name: 'inherited-or-none with the branch carrying its own dev commits -> still noop',
|
|
92
|
+
input: { ...laneGone('inherited-or-none'), lastSyncedHead: undefined, hasDevCommits: true },
|
|
93
|
+
type: 'noop',
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
// The adopt paths need no claim: nothing on them can delete a branch.
|
|
97
|
+
{
|
|
98
|
+
name: 'no branch yet -> import-lane',
|
|
99
|
+
input: { branchExists: false, lastSyncedHead: undefined, ownership: 'inherited-or-none' },
|
|
100
|
+
type: 'import-lane',
|
|
101
|
+
},
|
|
102
|
+
{ name: 'lane moved, branch untouched -> import-lane', input: { laneHead: 'L2' }, type: 'import-lane' },
|
|
103
|
+
{ name: 'dev commits, lane unchanged -> export-branch', input: { hasDevCommits: true }, type: 'export-branch' },
|
|
104
|
+
{ name: 'both moved -> merge-diverged', input: { laneHead: 'L2', hasDevCommits: true }, type: 'merge-diverged' },
|
|
105
|
+
{
|
|
106
|
+
name: 'existing branch, never synced, no dev commits, lane EXISTS -> import-lane (adopt branch)',
|
|
107
|
+
input: { lastSyncedHead: undefined, ownership: 'inherited-or-none' },
|
|
108
|
+
type: 'import-lane',
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
name: 'existing branch, never synced, has dev commits, lane EXISTS -> halt (ambiguous)',
|
|
112
|
+
input: { lastSyncedHead: undefined, ownership: 'inherited-or-none', hasDevCommits: true },
|
|
113
|
+
type: 'halt',
|
|
114
|
+
},
|
|
115
|
+
];
|
|
116
|
+
|
|
117
|
+
describe('planLaneSync', () => {
|
|
118
|
+
table.forEach(({ name, input, type, action, reason }) => {
|
|
119
|
+
it(name, () => {
|
|
120
|
+
const result = planLaneSync({ ...base, ...input });
|
|
121
|
+
expect(result.type, name).to.equal(type);
|
|
122
|
+
if (action) expect(result).to.deep.equal(action);
|
|
123
|
+
if (reason) expect((result as { reason?: string }).reason).to.contain(reason);
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
});
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How much of a claim this lane/branch pair has on `origin/<branch>` — the only thing that licenses
|
|
3
|
+
* retiring it, because `close-pr` deletes the branch. Under the default config every branch name maps
|
|
4
|
+
* to a same-named lane, and branches cut after a merged sync PR inherit its `.bitmap`, so "looks
|
|
5
|
+
* bit-managed" is not enough. Evidence = attribution (the branch's `.bitmap` lane pointer) plus
|
|
6
|
+
* reachability of the state commit / tip from the default branch:
|
|
7
|
+
*
|
|
8
|
+
* - `own-live` — names this lane; state commit not in the default branch (real, unmerged lane branch).
|
|
9
|
+
* - `own-merged` — names this lane; branch tip already in the default branch (deleting loses nothing).
|
|
10
|
+
* - `own-superseded` — state commit merged but tip not: close the PR, KEEP the branch.
|
|
11
|
+
* - `inherited-or-none` — no pointer, another lane's, or unreadable: not ours, touch nothing.
|
|
12
|
+
*/
|
|
13
|
+
export type LaneOwnershipEvidence = 'own-live' | 'own-merged' | 'own-superseded' | 'inherited-or-none';
|
|
14
|
+
|
|
15
|
+
export type LaneSyncInput = {
|
|
16
|
+
/** fingerprint of the lane's component heads on bit.cloud; undefined when the lane is gone */
|
|
17
|
+
laneHead?: string;
|
|
18
|
+
branchExists: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* The lane-component fingerprint as the branch's committed `.bitmap` records it; undefined when the
|
|
21
|
+
* branch holds no state for this lane. Equality with `laneHead` is the definition of converged.
|
|
22
|
+
*/
|
|
23
|
+
lastSyncedHead?: string;
|
|
24
|
+
/** whether the branch carries commits on top of the commit that last wrote its `.bitmap` */
|
|
25
|
+
hasDevCommits: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Whether the reconciler itself wrote the tip commit. The one exception to "markers are annotations":
|
|
28
|
+
* consulted only on the branch-deletion path, and only ever to WITHHOLD a deletion. Must be computed
|
|
29
|
+
* with `isSyncAuthoredMessage`, not the loop guard's substring match.
|
|
30
|
+
*/
|
|
31
|
+
tipIsSyncCommit: boolean;
|
|
32
|
+
conflictLabelPresent: boolean;
|
|
33
|
+
/** @see LaneOwnershipEvidence — consulted only on the "lane is gone" path. */
|
|
34
|
+
ownership: LaneOwnershipEvidence;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Why a `close-pr` is keeping the branch rather than deleting it. `tip-advanced-during-run` is the one
|
|
39
|
+
* the planner never emits: it is discovered when the executor re-reads the branch just before deleting.
|
|
40
|
+
*/
|
|
41
|
+
export type BranchKeepReason = 'unmerged-commits' | 'tip-not-a-sync-commit' | 'tip-advanced-during-run';
|
|
42
|
+
|
|
43
|
+
export type LaneSyncAction =
|
|
44
|
+
| { type: 'noop'; reason: string }
|
|
45
|
+
| { type: 'import-lane' }
|
|
46
|
+
| { type: 'export-branch' }
|
|
47
|
+
| { type: 'merge-diverged' }
|
|
48
|
+
// Two variants rather than an optional `keepReason` so the type enforces that a keep always says why.
|
|
49
|
+
| { type: 'close-pr'; deleteBranch: true }
|
|
50
|
+
| { type: 'close-pr'; deleteBranch: false; keepReason: BranchKeepReason }
|
|
51
|
+
| { type: 'halt'; reason: string };
|
|
52
|
+
|
|
53
|
+
export function planLaneSync(input: LaneSyncInput): LaneSyncAction {
|
|
54
|
+
const { laneHead, branchExists, lastSyncedHead, hasDevCommits, conflictLabelPresent, ownership } = input;
|
|
55
|
+
const { tipIsSyncCommit } = input;
|
|
56
|
+
if (conflictLabelPresent) {
|
|
57
|
+
return { type: 'noop', reason: 'PR is labeled bit-sync-conflict; resolve and remove the label to resume' };
|
|
58
|
+
}
|
|
59
|
+
if (!laneHead) {
|
|
60
|
+
if (!branchExists) return { type: 'noop', reason: 'lane and branch both absent' };
|
|
61
|
+
switch (ownership) {
|
|
62
|
+
case 'own-live':
|
|
63
|
+
// DELETION NEEDS BOTH HALVES: `.bitmap` attribution alone is not enough — a developer who commits
|
|
64
|
+
// their own `.bitmap` write (bit create / unexported snap / deps set) looks exactly like
|
|
65
|
+
// "own-live, nothing above the state commit". The marker can only withhold a deletion, never
|
|
66
|
+
// authorize one; a false keep is harmless, a false delete destroys the only copy of the work.
|
|
67
|
+
if (!hasDevCommits && tipIsSyncCommit) return { type: 'close-pr', deleteBranch: true };
|
|
68
|
+
return {
|
|
69
|
+
type: 'close-pr',
|
|
70
|
+
deleteBranch: false,
|
|
71
|
+
keepReason: hasDevCommits ? 'unmerged-commits' : 'tip-not-a-sync-commit',
|
|
72
|
+
};
|
|
73
|
+
case 'own-merged':
|
|
74
|
+
// No marker conjunction needed: the tip being an ancestor of the default branch is unforgeable
|
|
75
|
+
// proof that deleting loses nothing.
|
|
76
|
+
return { type: 'close-pr', deleteBranch: true };
|
|
77
|
+
case 'own-superseded':
|
|
78
|
+
// Those commits are in no other ref.
|
|
79
|
+
return { type: 'close-pr', deleteBranch: false, keepReason: 'unmerged-commits' };
|
|
80
|
+
default:
|
|
81
|
+
return { type: 'noop', reason: 'branch maps to no lane and has no sync history of its own; ignoring' };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (!branchExists) return { type: 'import-lane' };
|
|
85
|
+
if (!lastSyncedHead) {
|
|
86
|
+
if (hasDevCommits) {
|
|
87
|
+
return {
|
|
88
|
+
type: 'halt',
|
|
89
|
+
reason: 'branch has commits but its .bitmap records no state for this lane; cannot tell which side is newer',
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
return { type: 'import-lane' };
|
|
93
|
+
}
|
|
94
|
+
const laneMoved = laneHead !== lastSyncedHead;
|
|
95
|
+
if (laneMoved && hasDevCommits) return { type: 'merge-diverged' };
|
|
96
|
+
if (laneMoved) return { type: 'import-lane' };
|
|
97
|
+
if (hasDevCommits) return { type: 'export-branch' };
|
|
98
|
+
return { type: 'noop', reason: 'converged' };
|
|
99
|
+
}
|