@futurelastic/colab-handbook 1.18.0-rc.9 → 1.19.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/audit/audit.mjs +31 -0
- package/package.json +1 -1
- package/tools/colab +167 -23
- package/tools/lib/adopt.js +5 -1
- package/tools/lib/ci-forgejo.js +130 -0
- package/tools/lib/migration-paths.js +83 -3
- package/tools/lib/release-cut.js +97 -6
- package/tools/lib/release-finalize.js +26 -3
- package/tools/lib/stale-base.js +14 -4
- package/tools/lib/tracker-fake.js +5 -0
- package/tools/lib/tracker-github.js +6 -0
- package/tools/lib/tracker-scenarios.json +32 -1
- package/tools/lib/tracker.js +117 -6
package/audit/audit.mjs
CHANGED
|
@@ -269,6 +269,9 @@ function parseScalarValue(raw) {
|
|
|
269
269
|
const NESTED_MAP_KEYS = new Set(["release", "owner", "gate", "thresholds", "contention"]); // owner: #394 · gate: #410 · thresholds: #560 · contention: #630
|
|
270
270
|
// The one map whose pairs may hold an INLINE list (`coupled: [a, b]`) — still one level, still no block list (#630).
|
|
271
271
|
const LIST_IN_MAP_KEYS = new Set(["contention"]);
|
|
272
|
+
// A key whose empty value may open EITHER a block list or a one-level map: `migrations:` is a list of
|
|
273
|
+
// paths, or the `none: <reason>` block (#672). The two line shapes cannot be mistaken for each other.
|
|
274
|
+
const LIST_OR_MAP_KEYS = new Set(["migrations"]);
|
|
272
275
|
|
|
273
276
|
function parseFlatYaml(text) {
|
|
274
277
|
const out = {};
|
|
@@ -340,6 +343,7 @@ function parseFlatYaml(text) {
|
|
|
340
343
|
if (trimmed === "") {
|
|
341
344
|
if (NESTED_MAP_KEYS.has(key)) mapKey = key;
|
|
342
345
|
else listKey = key;
|
|
346
|
+
if (LIST_OR_MAP_KEYS.has(key)) mapKey = key;
|
|
343
347
|
}
|
|
344
348
|
});
|
|
345
349
|
return { data: out, problems };
|
|
@@ -893,6 +897,16 @@ function makeSource(target) {
|
|
|
893
897
|
return [];
|
|
894
898
|
}
|
|
895
899
|
},
|
|
900
|
+
// #676: the tracked files at HEAD under the given declared `migrations:` entries (pathspec-
|
|
901
|
+
// limited, never the whole tree). null = git could not list — the check then says nothing.
|
|
902
|
+
filesAtHeadUnder: (paths) => {
|
|
903
|
+
try {
|
|
904
|
+
const out = execFileSync("git", ["-C", root, "ls-tree", "-r", "--name-only", "HEAD", "--", ...paths], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 });
|
|
905
|
+
return out.split("\n").map((s) => s.trim()).filter(Boolean);
|
|
906
|
+
} catch {
|
|
907
|
+
return null;
|
|
908
|
+
}
|
|
909
|
+
},
|
|
896
910
|
// Every path under a directory named `migrations` (#383's undeclared-layout check). null =
|
|
897
911
|
// git could not list — the check then says nothing rather than reporting a clean tree.
|
|
898
912
|
migrationDirFiles: () => {
|
|
@@ -924,6 +938,8 @@ function makeSource(target) {
|
|
|
924
938
|
// Same cost argument as markdownFiles: a recursive tree listing per repo per sweep. null = not
|
|
925
939
|
// enumerated, so #383's undeclared-migration-layout check is local-only, silently.
|
|
926
940
|
migrationDirFiles: () => null,
|
|
941
|
+
// Same cost argument: the declared-path existence check (#676) is local-only too.
|
|
942
|
+
filesAtHeadUnder: () => null,
|
|
927
943
|
tags: () => listRemoteTags(target.slug),
|
|
928
944
|
metadata: () => readRemoteMetadata(target.slug),
|
|
929
945
|
// The duration report (#137) needs a per-commit walk over historical blobs
|
|
@@ -1426,6 +1442,21 @@ function auditRepoInner(target, ctx) {
|
|
|
1426
1442
|
migCfg.problems.forEach((p) => fail(p));
|
|
1427
1443
|
migCfg.notes.forEach((p) => warn(p));
|
|
1428
1444
|
const migFiles = src.migrationDirFiles();
|
|
1445
|
+
// #672's guard, where the declaration is read: `migrations: none` beside a Laravel or Prisma
|
|
1446
|
+
// migrations directory is a contradiction, and every later cut refuses it too (release-cut.js
|
|
1447
|
+
// schemaVerdict, release-finalize.js migrationGrantVerdict). Local-only, like the rule below.
|
|
1448
|
+
if (migFiles && migCfg.none) {
|
|
1449
|
+
const dirsOf = migFiles.map((f) => f.split("/").slice(0, -1).map((_, i, a) => a.slice(0, i + 1).join("/"))).flat();
|
|
1450
|
+
const why = migrationPaths.noneContradiction(migCfg.none, migrationPaths.defaultLayoutDirs([...new Set(dirsOf)]));
|
|
1451
|
+
if (why) fail(`migrations: ${why}`);
|
|
1452
|
+
}
|
|
1453
|
+
// #676: a declared path that names nothing at HEAD is not a layout — release cut/finalize no
|
|
1454
|
+
// longer count it as one, and here it fails where the declaration is read, so the typo is found
|
|
1455
|
+
// before a release refuses on it. Local-only, like the rules around it.
|
|
1456
|
+
if (migCfg.paths.length && src.filesAtHeadUnder) {
|
|
1457
|
+
const presence = migrationPaths.declaredPresence(migCfg.paths, src.filesAtHeadUnder(migCfg.paths));
|
|
1458
|
+
if (presence && presence.missing.length) fail(`migrations: ${migrationPaths.missingNote(presence.missing, "HEAD")}`);
|
|
1459
|
+
}
|
|
1429
1460
|
if (migFiles) {
|
|
1430
1461
|
const undeclared = migrationPaths.undeclaredMigrationDirs(migFiles, migCfg.paths);
|
|
1431
1462
|
if (undeclared.length) {
|
package/package.json
CHANGED
package/tools/colab
CHANGED
|
@@ -231,15 +231,44 @@ function findClaim(st, num, repoAbs) {
|
|
|
231
231
|
}
|
|
232
232
|
|
|
233
233
|
function isGhUsable(repoAbs) {
|
|
234
|
+
// #678: a remote whose forge the engine map names (Forgejo) is never served by gh — even on a host
|
|
235
|
+
// where gh is installed and authenticated for GitHub, a call would go to the wrong forge. Every
|
|
236
|
+
// gh-keyed row (issue evidence, labels, PR close, grants) then behaves as "no tracker here"; the CI
|
|
237
|
+
// rows read the forge through forgeCi below instead.
|
|
238
|
+
if (forgeEngine(repoAbs).engine !== 'github') return false;
|
|
234
239
|
return git.ghAvailable() && !!git.remoteUrl(repoAbs);
|
|
235
240
|
}
|
|
236
241
|
|
|
242
|
+
/**
|
|
243
|
+
* #367's forge-visibility read, or null on a forge gh does not serve (#678) — null is "could not
|
|
244
|
+
* read", which tools/lib/machine-trailer.js fails closed on. Never sends `gh repo view` at a forge slug.
|
|
245
|
+
*/
|
|
246
|
+
function repoVisibility(repoAbs) {
|
|
247
|
+
return forgeEngine(repoAbs).engine === 'github' ? git.ghRepoVisibility(repoAbs) : null;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** #678: the repo's forge engine (tools/lib/tracker.js engineFor) — github unless the machine config's `forges` names the host. */
|
|
251
|
+
function forgeEngine(repoAbs) {
|
|
252
|
+
return tracker.engineFor(repoAbs);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* #678: the CI reader for a repo whose remote is a non-GitHub forge the engine map names, or null on
|
|
257
|
+
* GitHub (the gh-based reads stay exactly as they were there). The forge's CI is read through the
|
|
258
|
+
* tracker contract's `ciVerdict` — commit statuses on Forgejo (tools/lib/ci-forgejo.js).
|
|
259
|
+
*/
|
|
260
|
+
function forgeCi(repoAbs) {
|
|
261
|
+
return forgeEngine(repoAbs).engine === 'github' ? null : tracker.ciFor(repoAbs);
|
|
262
|
+
}
|
|
263
|
+
|
|
237
264
|
/**
|
|
238
265
|
* #344: the honest half of every "gh not usable" message — WHICH of isGhUsable's conditions failed.
|
|
239
266
|
* The old fixed text "(no auth / no origin)" blamed both at once, and pointed an operator whose
|
|
240
267
|
* active credential was fine at auth. Only meaningful when isGhUsable() is false.
|
|
241
268
|
*/
|
|
242
269
|
function ghUnusableWhy(repoAbs) {
|
|
270
|
+
const eng = forgeEngine(repoAbs);
|
|
271
|
+
if (eng.engine !== 'github') return `the remote is a ${eng.engine} forge (${eng.host}, machine config \`forges\`) — gh does not serve it; the adopter's own tracker owns issue writes there (#678)`;
|
|
243
272
|
const s = git.ghState();
|
|
244
273
|
if (!s.ok && s.reason === 'missing') return 'gh is not installed';
|
|
245
274
|
if (!s.ok && s.reason === 'rate-limited') { // #516
|
|
@@ -281,7 +310,7 @@ const { liveClaimComments, tieBreakVerdict } = claimComments; // the format itse
|
|
|
281
310
|
const commentHostCache = new Map();
|
|
282
311
|
function commentHostDecision(repoAbs) {
|
|
283
312
|
if (commentHostCache.has(repoAbs)) return commentHostCache.get(repoAbs);
|
|
284
|
-
const d = machineTrailer.mayNameHost({ visibility:
|
|
313
|
+
const d = machineTrailer.mayNameHost({ visibility: repoVisibility(repoAbs), room: projectDoc(repoAbs).room });
|
|
285
314
|
commentHostCache.set(repoAbs, d);
|
|
286
315
|
return d;
|
|
287
316
|
}
|
|
@@ -1486,18 +1515,34 @@ function measureCandidateConditions(repoAbs, { sha, lastFinal, at, readRuns, iss
|
|
|
1486
1515
|
// matched (migration-paths.js isMigrationPath)? Without one and with nothing declared, the check
|
|
1487
1516
|
// read nothing: "not checked", never a ✓. null = the tree could not be read, never "absent".
|
|
1488
1517
|
const layoutR = git.git(['ls-tree', '-r', '-d', '--name-only', sha], repoAbs);
|
|
1489
|
-
const
|
|
1518
|
+
const layoutDirs = layoutR.ok ? migrationPaths.defaultLayoutDirs(layoutR.stdout.split('\n')) : null;
|
|
1519
|
+
const layout = layoutDirs ? layoutDirs.length > 0 : null;
|
|
1520
|
+
// #672: `migrations: none` counts only as committed AT THE CANDIDATE — never the disk copy, which on
|
|
1521
|
+
// a finalize is trunk's head, not what ships — and only where nothing declares a layout (a declared
|
|
1522
|
+
// path anywhere wins: the gate then sees more, never less). The default-layout guard is the verdicts'.
|
|
1523
|
+
const noneAt = declared.length ? null : migrationPaths.parseMigrationPaths(projectDocAt(repoAbs, sha)).none;
|
|
1524
|
+
const none = noneAt ? { ...noneAt, dirs: layoutDirs || [] } : null;
|
|
1525
|
+
// #676: a declared path is a layout only where it names something AT THE CANDIDATE — a misspelled or
|
|
1526
|
+
// stale entry used to open the grant gate having read nothing. null = the tree could not be listed.
|
|
1527
|
+
let presence = { present: [], missing: [] };
|
|
1528
|
+
if (declared.length) {
|
|
1529
|
+
// Pathspec-limited: only what sits under a declared entry is listed, never the whole tree.
|
|
1530
|
+
const filesR = git.git(['ls-tree', '-r', '--name-only', sha, '--', ...declared], repoAbs, { maxBuffer: 64 * 1024 * 1024 });
|
|
1531
|
+
presence = migrationPaths.declaredPresence(declared, filesR.ok ? filesR.stdout.split('\n').filter(Boolean) : null);
|
|
1532
|
+
}
|
|
1533
|
+
const missing = presence ? presence.missing : [];
|
|
1490
1534
|
const schema = changes === null
|
|
1491
1535
|
? { ok: false, unread: true, detail: 'git diff failed — schema changes cannot be read' }
|
|
1492
|
-
: releaseCut.schemaVerdict(changes, lastFinal || 'the first commit', declared, layout);
|
|
1536
|
+
: releaseCut.schemaVerdict(changes, lastFinal || 'the first commit', declared, presence ? layout : null, none, presence ? missing : null);
|
|
1493
1537
|
// #441: every migration file since the last final, destructive or not — an operator-granted
|
|
1494
1538
|
// automatic final refuses an ungranted one (release-finalize.js migrationGrantVerdict).
|
|
1495
1539
|
const migrations = changes === null ? null : changes.filter((c) => releaseCut.isMigrationPath(c.path, declared)).map((c) => c.path);
|
|
1496
|
-
// #671: could a migration have been seen at all? A declared prefix is a layout
|
|
1497
|
-
// default-layout reading above (null = unread, never
|
|
1498
|
-
// without one, so its empty list never reads "nothing read"
|
|
1499
|
-
|
|
1500
|
-
|
|
1540
|
+
// #671: could a migration have been seen at all? A declared prefix is a layout — #676: only one that
|
|
1541
|
+
// exists at the candidate; otherwise the default-layout reading above (null = unread, never
|
|
1542
|
+
// "absent"). The grant gate fails closed without one, so its empty list never reads "nothing read"
|
|
1543
|
+
// as "nothing changed". An unlistable tree with a declaration is unread, never a layout.
|
|
1544
|
+
const migrationLayout = !presence ? null : presence.present.length ? true : layout;
|
|
1545
|
+
return { ci, suite, schema, switches, issues, migrations, migrationLayout, migrationsNone: none, migrationsMissing: missing };
|
|
1501
1546
|
}
|
|
1502
1547
|
|
|
1503
1548
|
/**
|
|
@@ -1635,7 +1680,7 @@ function finalTags(repoAbs, onlyTags = null) {
|
|
|
1635
1680
|
* since the newest final. The version is computed here only to find that tracking issue; decide()
|
|
1636
1681
|
* computes it again from the same inputs, so the two cannot disagree.
|
|
1637
1682
|
*/
|
|
1638
|
-
function measureFastRoute(repoAbs, { policy, remote, issues, lastFinal, tags, auto, migrationPaths: paths, migrationLayout = null, remoteTags = null }) {
|
|
1683
|
+
function measureFastRoute(repoAbs, { policy, remote, issues, lastFinal, tags, auto, migrationPaths: paths, migrationLayout = null, migrationsNone = null, migrationsMissing = [], remoteTags = null }) {
|
|
1639
1684
|
const grantDecl = policy.effective.finalGrant;
|
|
1640
1685
|
const trust = trustAt(repoAbs, `${remote}/main`);
|
|
1641
1686
|
const finalGrant = isGhUsable(repoAbs)
|
|
@@ -1655,7 +1700,7 @@ function measureFastRoute(repoAbs, { policy, remote, issues, lastFinal, tags, au
|
|
|
1655
1700
|
: { ok: false, reason: 'no tracking issue yet to carry a grant' };
|
|
1656
1701
|
if (grant && grant.ok) grant = { ...grant, issue: tracking.number };
|
|
1657
1702
|
}
|
|
1658
|
-
const migrations = { ...releaseFinalize.migrationGrantVerdict({ paths, grant, since: lastFinal, layout: migrationLayout }), paths: paths || null };
|
|
1703
|
+
const migrations = { ...releaseFinalize.migrationGrantVerdict({ paths, grant, since: lastFinal, layout: migrationLayout, none: migrationsNone, missing: migrationsMissing }), paths: paths || null };
|
|
1659
1704
|
const spacing = releaseCut.spacingVerdict({ finals: finalTags(repoAbs, remoteTags), spacingHours: policy.effective.finalSpacingHours, now: new Date().toISOString() });
|
|
1660
1705
|
return { finalGrant, holds, migrations, spacing, tracking };
|
|
1661
1706
|
}
|
|
@@ -1748,7 +1793,7 @@ function cmdReleaseCut(argv) {
|
|
|
1748
1793
|
const tags = lines(git.git(['tag', '--list'], repoAbs)).filter(onRemote);
|
|
1749
1794
|
const tagsAtSha = lines(git.git(['tag', '--points-at', sha], repoAbs)).filter(onRemote);
|
|
1750
1795
|
|
|
1751
|
-
const { ci, suite, schema, switches, issues, migrations: migrationPathsSince, migrationLayout } = measureCandidateConditions(repoAbs, {
|
|
1796
|
+
const { ci, suite, schema, switches, issues, migrations: migrationPathsSince, migrationLayout, migrationsNone, migrationsMissing } = measureCandidateConditions(repoAbs, {
|
|
1752
1797
|
sha, lastFinal, at, readRuns: () => releaseCut.withoutOwnWorkflow(git.ghRunsForCommit(repoAbs, 'main', sha)), // #425
|
|
1753
1798
|
verifying: verifyingPolicy(repoAbs), // #624: the ship gate's rule for which runs may veto
|
|
1754
1799
|
});
|
|
@@ -1764,7 +1809,7 @@ function cmdReleaseCut(argv) {
|
|
|
1764
1809
|
// #446: route deploy-tag-fast — the grant, the human veto, the migration gate and the spacing are
|
|
1765
1810
|
// measured only there, so every candidate route's run is what it was.
|
|
1766
1811
|
const fast = releaseCut.isFastRoute(policy) && !policy.findings.length;
|
|
1767
|
-
const fastFacts = fast ? measureFastRoute(repoAbs, { policy, remote, issues, lastFinal, tags, auto, migrationPaths: migrationPathsSince, migrationLayout, remoteTags }) : {};
|
|
1812
|
+
const fastFacts = fast ? measureFastRoute(repoAbs, { policy, remote, issues, lastFinal, tags, auto, migrationPaths: migrationPathsSince, migrationLayout, migrationsNone, migrationsMissing, remoteTags }) : {};
|
|
1768
1813
|
if (fast && auto) auto.spacing = fastFacts.spacing;
|
|
1769
1814
|
// #590: route library-fast — a final with nothing deployed. The release-hold veto is its one extra
|
|
1770
1815
|
// read; a hand cut also needs MIGRATION.md for a manifest-declared major (--auto reads it already).
|
|
@@ -2251,7 +2296,7 @@ function cmdReleaseFinalize(argv) {
|
|
|
2251
2296
|
const mg = tracking && tracking.number
|
|
2252
2297
|
? migrationGrant.evaluateIssue(rec, cand.version, tracking.number, labels.MIGRATION_GRANT_LABEL, { trust })
|
|
2253
2298
|
: { ok: false, reason: 'no tracking issue yet to carry a grant' };
|
|
2254
|
-
migrations = releaseFinalize.migrationGrantVerdict({ paths: conditions.migrations, grant: mg, since: releaseTag.latestReleaseTag(repoAbs, { ref: cand.sha, onlyTags: remoteTags }), layout: conditions.migrationLayout });
|
|
2299
|
+
migrations = releaseFinalize.migrationGrantVerdict({ paths: conditions.migrations, grant: mg, since: releaseTag.latestReleaseTag(repoAbs, { ref: cand.sha, onlyTags: remoteTags }), layout: conditions.migrationLayout, none: conditions.migrationsNone, missing: conditions.migrationsMissing });
|
|
2255
2300
|
}
|
|
2256
2301
|
const verdict = releaseFinalize.decide({
|
|
2257
2302
|
policy, selection: sel, tracking, supersededHeld, period, trunk, regressions,
|
|
@@ -3934,6 +3979,8 @@ change. Nothing else can produce a grant — no --force on ship, no project.yml
|
|
|
3934
3979
|
from an issue's content, age or park count. A human act on the issue is the whole answer.
|
|
3935
3980
|
|
|
3936
3981
|
colab migration-grant <N> --branch <branch> grant #N an exemption, bound to <branch>
|
|
3982
|
+
colab migration-grant <N> --branch vX.Y.Z on a release tracking issue: bound to that version
|
|
3983
|
+
(#677 — the command a release hand-off prints)
|
|
3937
3984
|
colab migration-grant <N> --revoke revoke #N's grant (idempotent — safe if none exists)
|
|
3938
3985
|
colab migration-grant --list [--json] list every issue with a live grant right now
|
|
3939
3986
|
|
|
@@ -3959,6 +4006,13 @@ Revoking removes the label FIRST (the gate is restored the same minute) and post
|
|
|
3959
4006
|
grantor — any revoke comment cancels every live grant on that issue, because a safety gate should
|
|
3960
4007
|
fail toward "closed" if either half only partially lands.
|
|
3961
4008
|
|
|
4009
|
+
A RELEASE VERSION (#677). --branch must name a ref (a local branch or origin's copy) — with one
|
|
4010
|
+
exception: a human grant naming a final version \`vX.Y.Z\` that is not a ref, on the issue whose body
|
|
4011
|
+
starts with that version's tracking marker (\`<!-- colab:release version=vX.Y.Z -->\`). That is the
|
|
4012
|
+
grant a release hand-off asks for (\`colab release cut --auto\` on deploy-tag-fast, and a deploy-tag
|
|
4013
|
+
candidate): the version becomes a tag only after the grant, and the release gate reads the grant
|
|
4014
|
+
against the version. Any other version — a typo, or one #N does not track — is refused, nothing posted.
|
|
4015
|
+
|
|
3962
4016
|
There is deliberately no local-only fallback: without a usable \`gh\`, every subcommand here REFUSES
|
|
3963
4017
|
rather than write (or read) something invisible to the machine \`ship\` might later run on.
|
|
3964
4018
|
|
|
@@ -4048,7 +4102,15 @@ function cmdMigrationGrant(argv) {
|
|
|
4048
4102
|
if (!opts.revoke && !opts.branch) {
|
|
4049
4103
|
throw new UserError('--branch <branch> is required — a grant is bound to one branch, never inferred from the current checkout');
|
|
4050
4104
|
}
|
|
4051
|
-
|
|
4105
|
+
// #677: a release version is the one binding name that is not a ref when it is granted — on route
|
|
4106
|
+
// deploy-tag-fast (and a deploy-tag candidate) the grant is what lets `vX.Y.Z` be tagged at all,
|
|
4107
|
+
// and the release gate compares the grant against the computed version, never a ref. So a human
|
|
4108
|
+
// grant naming a canonical final version is deferred here to cmdMigrationGrantCreate, which accepts
|
|
4109
|
+
// it only when #N's tracking marker names exactly that version: a typo is still refused, just one
|
|
4110
|
+
// step later (it needs the tracker). Any other name — and a reviewer grant, which binds a pushed
|
|
4111
|
+
// HEAD — keeps the ref check below, unchanged.
|
|
4112
|
+
if (!opts.revoke) opts.versionBinding = migrationGrantVersionBinding(repoAbs, opts);
|
|
4113
|
+
if (!opts.revoke && !opts.versionBinding && !git.branchExists(repoAbs, opts.branch)) {
|
|
4052
4114
|
throw new UserError(`branch "${opts.branch}" does not resolve to a ref (locally or on origin) — refusing to bind a grant to a name nothing exists at`);
|
|
4053
4115
|
}
|
|
4054
4116
|
// #397: the role, and for a reviewer grant its whole record — all answerable locally, so all
|
|
@@ -4069,6 +4131,19 @@ function cmdMigrationGrant(argv) {
|
|
|
4069
4131
|
return opts.revoke ? cmdMigrationGrantRevoke(repoAbs, num) : cmdMigrationGrantCreate(repoAbs, num, opts);
|
|
4070
4132
|
}
|
|
4071
4133
|
|
|
4134
|
+
/**
|
|
4135
|
+
* #677: true when this grant binds a release VERSION rather than a branch — a human grant whose
|
|
4136
|
+
* --branch is a canonical final version (`vX.Y.Z`, never an `-rc.N`) that resolves to no ref here.
|
|
4137
|
+
* Local only, so it runs before the gh gate; cmdMigrationGrantCreate then holds it to the issue's
|
|
4138
|
+
* tracking marker (`<!-- colab:release version=vX.Y.Z -->`). A ref of that name wins: the grant is
|
|
4139
|
+
* an ordinary branch grant and nothing about it changes.
|
|
4140
|
+
*/
|
|
4141
|
+
function migrationGrantVersionBinding(repoAbs, opts) {
|
|
4142
|
+
if (opts.role !== undefined && String(opts.role) !== 'human') return false;
|
|
4143
|
+
if (!releaseCut.parseVersion(opts.branch)) return false;
|
|
4144
|
+
return !git.branchExists(repoAbs, opts.branch);
|
|
4145
|
+
}
|
|
4146
|
+
|
|
4072
4147
|
/**
|
|
4073
4148
|
* #397: resolve the grant's role and, for a reviewer grant, build and check its review record.
|
|
4074
4149
|
* Returns null for a human grant (the unchanged path). Throws UserError on anything a reviewer
|
|
@@ -4189,15 +4264,23 @@ function cmdMigrationGrantCreate(repoAbs, num, opts) {
|
|
|
4189
4264
|
if (!opts.branch) {
|
|
4190
4265
|
throw new UserError('--branch <branch> is required — a grant is bound to one branch, never inferred from the current checkout');
|
|
4191
4266
|
}
|
|
4192
|
-
if (!git.branchExists(repoAbs, opts.branch)) {
|
|
4267
|
+
if (!opts.versionBinding && !git.branchExists(repoAbs, opts.branch)) {
|
|
4193
4268
|
throw new UserError(`branch "${opts.branch}" does not resolve to a ref (locally or on origin) — refusing to bind a grant to a name nothing exists at`);
|
|
4194
4269
|
}
|
|
4195
4270
|
|
|
4196
|
-
const info = git.ghIssueView(repoAbs, num, ['state', 'labels']);
|
|
4271
|
+
const info = git.ghIssueView(repoAbs, num, opts.versionBinding ? ['state', 'labels', 'body'] : ['state', 'labels']);
|
|
4197
4272
|
if (!info) throw new UserError(`could not read #${num} from the tracker — refusing to write a grant blind`);
|
|
4198
4273
|
if (info.state !== 'OPEN') {
|
|
4199
4274
|
throw new UserError(`#${num} is ${info.state} — a grant expires the instant its issue closes, so granting a closed one would do nothing (CONVENTIONS.md §5, Migration exemption)`);
|
|
4200
4275
|
}
|
|
4276
|
+
// #677: a version-bound grant stands on the tracking marker in place of a ref — the name must be
|
|
4277
|
+
// exactly the version #N tracks, so a typo still binds nothing.
|
|
4278
|
+
if (opts.versionBinding) {
|
|
4279
|
+
const tracked = releaseFinalize.parseReleaseMarker(info.body);
|
|
4280
|
+
if (tracked !== opts.branch) {
|
|
4281
|
+
throw new UserError(`"${opts.branch}" is not a ref, and #${num} ${tracked ? `tracks ${tracked}, not ${opts.branch}` : 'carries no release tracking marker (<!-- colab:release version=vX.Y.Z -->)'} — a version is granted only on its own tracking issue; nothing was posted. Re-run with the version #${num} tracks, or the branch the migration is on: COLAB_HUMAN=1 colab migration-grant ${num} --branch ${tracked || '<branch>'}`);
|
|
4282
|
+
}
|
|
4283
|
+
}
|
|
4201
4284
|
|
|
4202
4285
|
const present = git.ghListLabels(repoAbs);
|
|
4203
4286
|
if (present && !present.includes(labels.MIGRATION_GRANT_LABEL)) {
|
|
@@ -4237,8 +4320,13 @@ function cmdMigrationGrantCreate(repoAbs, num, opts) {
|
|
|
4237
4320
|
print(` Revoke any time: colab migration-grant ${num} --revoke`);
|
|
4238
4321
|
return 0;
|
|
4239
4322
|
}
|
|
4240
|
-
|
|
4241
|
-
|
|
4323
|
+
if (opts.versionBinding) {
|
|
4324
|
+
print(`Granted #${num} in ${shortRepo(repoAbs)} a migration exemption for release ${opts.branch}.`);
|
|
4325
|
+
print(` This covers ONLY that version's final, and expires the moment #${num} closes. The next green release run tags it.`);
|
|
4326
|
+
} else {
|
|
4327
|
+
print(`Granted #${num} in ${shortRepo(repoAbs)} a migration exemption for branch "${opts.branch}".`);
|
|
4328
|
+
print(` This covers ONLY this branch, and expires the moment #${num} closes.`);
|
|
4329
|
+
}
|
|
4242
4330
|
print(` Revoke any time: colab migration-grant ${num} --revoke`);
|
|
4243
4331
|
// Deliberately no pushEvent — see HELP_SHIP's JSON note: no receiver-agreed kind exists for
|
|
4244
4332
|
// this yet, and both markers are already visible on the tracker from any machine.
|
|
@@ -9391,7 +9479,7 @@ async function cmdAdopt(argv) {
|
|
|
9391
9479
|
// the forge reads private, or reads nothing and the room (this run's answer, else the one on
|
|
9392
9480
|
// record) is private. Otherwise the comment keeps its date and drops the host.
|
|
9393
9481
|
const provenanceHost = machineTrailer.mayNameHost({
|
|
9394
|
-
visibility:
|
|
9482
|
+
visibility: repoVisibility(repoAbs),
|
|
9395
9483
|
room: answers.room ? answers.room.values.room : cfg.room,
|
|
9396
9484
|
}).include ? HOST : null;
|
|
9397
9485
|
const meta = (a) => (a.mode === 'interactive'
|
|
@@ -11720,6 +11808,9 @@ function descriptorHolds(doc) {
|
|
|
11720
11808
|
function shipCiCheck(repoAbs, gh, target, trunk, grantThunk, cureThunk, branch = null) {
|
|
11721
11809
|
const name = `${target === trunk ? 'trunk' : 'line'} CI green`;
|
|
11722
11810
|
const r = readCiVerdict(repoAbs, gh, target, trunk);
|
|
11811
|
+
// #678: on a forge the engine map names, the verdict is final — the #482 no-workflow door counts
|
|
11812
|
+
// `.github/workflows` and reads the branch through gh, neither of which describes a forge's CI.
|
|
11813
|
+
if (forgeCi(repoAbs)) return { name, ...r.verdict, grantVerdict: null, cureVerdict: null };
|
|
11723
11814
|
const nw = noWorkflowTrunkDoor(repoAbs, r, target, trunk, branch);
|
|
11724
11815
|
if (nw) return { name, ...nw, grantVerdict: null, cureVerdict: null };
|
|
11725
11816
|
if (r.final) return { name, ...r.verdict, grantVerdict: null, cureVerdict: null };
|
|
@@ -11815,6 +11906,8 @@ function trunkWorkflowFiles(repoAbs, sha) {
|
|
|
11815
11906
|
* branch past a red trunk, it does not make the trunk green, and the red still needs an owner.
|
|
11816
11907
|
*/
|
|
11817
11908
|
function readCiVerdict(repoAbs, gh, target, trunk) {
|
|
11909
|
+
const fc = forgeCi(repoAbs);
|
|
11910
|
+
if (fc) return readForgeCiVerdict(repoAbs, fc, target, trunk);
|
|
11818
11911
|
if (!gh) return { run: null, final: true, verdict: { ok: false, class: SELF_CLEARING, detail: `gh not usable (${ghUnusableWhy(repoAbs)}) — cannot confirm CI` } };
|
|
11819
11912
|
// #503: only runs that VERIFY the code count — a post-CI release/deploy run at the same sha is set
|
|
11820
11913
|
// aside and named, never a red and never a reason to wait (tools/lib/verify-runs.js).
|
|
@@ -11869,6 +11962,45 @@ function readCiVerdict(repoAbs, gh, target, trunk) {
|
|
|
11869
11962
|
return { run, verdict, final: verdict.ok || verdict.class !== HUMAN_GATED };
|
|
11870
11963
|
}
|
|
11871
11964
|
|
|
11965
|
+
/**
|
|
11966
|
+
* #678: readCiVerdict on a non-GitHub forge — the target's remote head (plain git), its verdict
|
|
11967
|
+
* through the tracker contract's `ciVerdict` (commit statuses on Forgejo), classified by the same
|
|
11968
|
+
* classifyCiRun every GitHub read goes through. Kept: the line→trunk fallback and the #413 empty-read
|
|
11969
|
+
* grace (both git-side). Not offered: the GitHub-only doors — the by-commit re-read (#413), the
|
|
11970
|
+
* docs-only tip (#606), the batch substitute (#373), the tree-green citation (#493) — and, by
|
|
11971
|
+
* returning `final: true`, the ci-grant and cure exemptions, which live on the tracker (frozen on a
|
|
11972
|
+
* forge, #604/#608). A failed read is SELF_CLEARING and never green.
|
|
11973
|
+
*/
|
|
11974
|
+
function readForgeCiVerdict(repoAbs, fc, target, trunk) {
|
|
11975
|
+
const engine = fc.kind || 'forge';
|
|
11976
|
+
const remote = git.remoteInfo(repoAbs).name || 'origin';
|
|
11977
|
+
const headOf = (b) => {
|
|
11978
|
+
const ls = git.git(['ls-remote', remote, `refs/heads/${b}`], repoAbs);
|
|
11979
|
+
return ls.ok ? ((ls.stdout.split('\n')[0] || '').split('\t')[0].trim() || null) : null;
|
|
11980
|
+
};
|
|
11981
|
+
const unread = (detail) => ({ run: null, final: true, verdict: { ok: false, class: SELF_CLEARING, detail } });
|
|
11982
|
+
let sha = headOf(target);
|
|
11983
|
+
if (!sha) return unread(`${target} not readable on the remote — cannot confirm CI (${engine})`);
|
|
11984
|
+
let run = fc.ciVerdict(sha, { branch: target });
|
|
11985
|
+
let via = target;
|
|
11986
|
+
if (run && run.status === 'none' && target !== trunk) {
|
|
11987
|
+
const tSha = headOf(trunk);
|
|
11988
|
+
const tRun = tSha ? fc.ciVerdict(tSha, { branch: trunk }) : null;
|
|
11989
|
+
if (tRun) { run = tRun; sha = tSha; via = `${trunk} (line "${target}" has no runs — ungated, advisory)`; }
|
|
11990
|
+
}
|
|
11991
|
+
if (!run) return unread(`${engine} commit-status read failed for ${target}@${shortSha(sha)} — cannot confirm CI`);
|
|
11992
|
+
const at = `${via}@${shortSha(run.sha || sha)} (${engine} commit status)`;
|
|
11993
|
+
let verdict = classifyCiRun(repoAbs, run, at);
|
|
11994
|
+
if (run.status === 'none' && target === trunk) {
|
|
11995
|
+
const fresh = ciVerdict.emptyReadVerdict(git.commitTimeMs(repoAbs, run.sha), { graceSec: ciProfileFor(repoAbs).th.emptyReadGraceSec });
|
|
11996
|
+
if (fresh.fresh) {
|
|
11997
|
+
verdict = { ok: false, class: SELF_CLEARING,
|
|
11998
|
+
detail: `no commit status yet for ${at} — committed ${fresh.minutes.toFixed(1)}m ago, inside the ${Math.round(fresh.graceMinutes * 10) / 10}m grace; retry later` };
|
|
11999
|
+
}
|
|
12000
|
+
}
|
|
12001
|
+
return { run, verdict, final: true };
|
|
12002
|
+
}
|
|
12003
|
+
|
|
11872
12004
|
/**
|
|
11873
12005
|
* #493: a green trunk read whose suite was SKIPPED because the CI guard found a green run of the
|
|
11874
12006
|
* same workflow at an identical tree — name the run it relied on. The run's `success` is already
|
|
@@ -12139,9 +12271,14 @@ function shipStaleBaseCheck(repoAbs, gh, base, branch) {
|
|
|
12139
12271
|
// stale verdict there grades nothing, so it must not block the close.
|
|
12140
12272
|
if (contains === false && git.git(['diff', '--quiet', `${baseTip}...${headSha}`], repoAbs).code === 0) contains = 'no-change';
|
|
12141
12273
|
}
|
|
12142
|
-
|
|
12274
|
+
// #678: on a forge the engine map names, the branch head's verdict comes through the same CI method
|
|
12275
|
+
// the trunk-CI row reads (commit statuses on Forgejo) — never keyed on the gh flag, so a stale or red
|
|
12276
|
+
// branch head cannot pass here as `unread` while the CI row passes on the forge's statuses.
|
|
12277
|
+
const fc = forgeCi(repoAbs);
|
|
12278
|
+
if (headSha && fc) run = fc.ciVerdict(headSha, { branch });
|
|
12279
|
+
else if (headSha && gh) run = git.ghRunForCommit(repoAbs, branch, headSha);
|
|
12143
12280
|
// #606: `run`/`headSha` are additive — the docs-only row reads whether that run finished red.
|
|
12144
|
-
return { ...staleBase.staleBaseVerdict({ headSha, run, baseTip, contains, behind, base,
|
|
12281
|
+
return { ...staleBase.staleBaseVerdict({ headSha, run, baseTip, contains, behind, base, ciReadable: !!(fc || gh) }), run, headSha };
|
|
12145
12282
|
}
|
|
12146
12283
|
|
|
12147
12284
|
/**
|
|
@@ -13708,7 +13845,7 @@ function shipMachineTrailerDecision(repoAbs, doc) {
|
|
|
13708
13845
|
if (shipMachineTrailerCache.has(repoAbs)) return shipMachineTrailerCache.get(repoAbs);
|
|
13709
13846
|
const d = machineTrailer.decide({
|
|
13710
13847
|
label: branchName.machineLabel(HOST),
|
|
13711
|
-
visibility:
|
|
13848
|
+
visibility: repoVisibility(repoAbs),
|
|
13712
13849
|
room: doc && doc.room,
|
|
13713
13850
|
});
|
|
13714
13851
|
shipMachineTrailerCache.set(repoAbs, d);
|
|
@@ -14670,7 +14807,7 @@ function cmdShip(argv) {
|
|
|
14670
14807
|
// never silently ride the same exemption twice.
|
|
14671
14808
|
let ciGrantForTrailer = null; // #105: set below when B1 shipped UNDER a grant — read at commit-message time
|
|
14672
14809
|
let ciCureForTrailer = null; // #281: set below when B1 shipped UNDER the cure rule — read at commit-message time
|
|
14673
|
-
if (gh) {
|
|
14810
|
+
if (gh || forgeCi(repoAbs)) { // #678: a forge's CI is re-read at B1 exactly as GitHub's is
|
|
14674
14811
|
const measureB1 = () => shipCiCheck(repoAbs, gh, target, trunk,
|
|
14675
14812
|
(redSha) => shipCiGrants(repoAbs, gh, sess.issues, sess.branch, trunk, redSha),
|
|
14676
14813
|
(redSha) => shipCiCure(repoAbs, gh, target, trunk, redSha, sess.branch), sess.branch);
|
|
@@ -15165,6 +15302,13 @@ function shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, re
|
|
|
15165
15302
|
const disposition = shippedBranch.shippedBranchDisposition({ closeIssues, refsIssues, deleteBranch: opts.deleteBranch, keepBranch: opts.keepBranch || (!!sess.handoff && !opts.deleteBranch) });
|
|
15166
15303
|
handleShippedBranch(repoAbs, target, sess.branch, { disposition, worktreeKept, integration });
|
|
15167
15304
|
|
|
15305
|
+
// #678: on a forge the engine map names, the tracker writes below (🚢 evidence, group-label and
|
|
15306
|
+
// container teardown) are frozen surfaces (#604/#608) — skipped, and said once, never a failure.
|
|
15307
|
+
if (!gh) {
|
|
15308
|
+
const eng = forgeEngine(repoAbs);
|
|
15309
|
+
const what = sess.issues.length ? `closing #${sess.issues.join(', #')} with evidence and releasing the claim` : 'issue writes';
|
|
15310
|
+
if (eng.engine !== 'github') print(`B4: tracker writes skipped — ${eng.host} is a ${eng.engine} forge; ${what} there is the adopter's own tracker's job (#678)`);
|
|
15311
|
+
}
|
|
15168
15312
|
// ---- (g/h) B4 verify + post summary per issue ----
|
|
15169
15313
|
const groupLabelsCarried = new Set(); // union across every issue this branch carried — for (i) below
|
|
15170
15314
|
const closedByShip = []; // the issues this ship actually closed — for (i2) below (#371)
|
package/tools/lib/adopt.js
CHANGED
|
@@ -280,7 +280,7 @@ function detectMigrationCandidates(cfg, trackedFiles) {
|
|
|
280
280
|
if ([...dirs].some((d) => dir.startsWith(d))) continue;
|
|
281
281
|
dirs.add(dir);
|
|
282
282
|
}
|
|
283
|
-
return { declared: parsed.declared ? declared : null, candidates: [...dirs].sort() };
|
|
283
|
+
return { declared: parsed.declared ? declared : null, none: parsed.none, candidates: [...dirs].sort() };
|
|
284
284
|
}
|
|
285
285
|
|
|
286
286
|
const MIGRATION_CANDIDATES_SHOWN = 6;
|
|
@@ -288,6 +288,10 @@ const MIGRATION_CANDIDATES_SHOWN = 6;
|
|
|
288
288
|
/** The step-2 remainder line about `migrations:` — adopt never asks it, so it always reports it. */
|
|
289
289
|
function migrationsStepText(m) {
|
|
290
290
|
const tail = 'project.schema.md `migrations`; `colab adopt` does not ask it, step 2';
|
|
291
|
+
if (m && m.none) {
|
|
292
|
+
const extra = m.candidates.length ? ` — but these look like migrations, check: ${listShort(m.candidates)}` : '';
|
|
293
|
+
return `\`migrations: none\` declared (${m.none.reason})${extra} — ${tail}`;
|
|
294
|
+
}
|
|
291
295
|
if (m && m.declared && m.declared.length) {
|
|
292
296
|
const extra = m.candidates.length ? ` — still uncovered, check: ${listShort(m.candidates)}` : '';
|
|
293
297
|
return `\`migrations:\` declared (${m.declared.join(', ')})${extra} — ${tail}`;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* tools/lib/ci-forgejo.js — the CI half of the tracker contract on a Forgejo (or Gitea) forge
|
|
4
|
+
* (#678). The owner's ruling on #678 was "landing only": on a Forgejo remote the CLI reads CI so
|
|
5
|
+
* `colab ship` can land code, and writes nothing to the forge's issue tracker (claims, readiness,
|
|
6
|
+
* holds and close-with-evidence stay frozen per #604/#608 — the adopter's own tracker layer owns
|
|
7
|
+
* them there). So this module implements `tracker.CI_METHODS` only: `ciVerdict`.
|
|
8
|
+
*
|
|
9
|
+
* The read: the commit's COMBINED status, `GET {api}/repos/{owner}/{repo}/commits/{sha}/status`,
|
|
10
|
+
* which already holds the newest status per context. Each status becomes one row in the shape
|
|
11
|
+
* tools/lib/git.js summarizes for GitHub runs (`context` is the workflow name), and the verdict is
|
|
12
|
+
* `git.summarizeRunsForCommit` over those rows — the same all-quantifier rule, so a forge cannot
|
|
13
|
+
* read green where GitHub would read red:
|
|
14
|
+
* pending -> status in_progress (not finished: not green yet)
|
|
15
|
+
* success -> completed / success
|
|
16
|
+
* failure | error | warning | ? -> completed / <state> (only success counts — the allowlist rule)
|
|
17
|
+
* No statuses at all -> `status: 'none'`. Any failed read (HTTP error, timeout, bad JSON, a 404
|
|
18
|
+
* for a commit the forge does not have) -> null, which every caller reads as "could not read",
|
|
19
|
+
* never as "none". `databaseId` is always null: a forge status has no run whose jobs `gh run view`
|
|
20
|
+
* could list, so nothing downstream ever reaches for gh with it.
|
|
21
|
+
*
|
|
22
|
+
* The token: read from the environment variable the engine map names (default FORGEJO_TOKEN),
|
|
23
|
+
* inside the child process that makes the request — never on an argument list, never logged. No
|
|
24
|
+
* token is not an error: a public repo's statuses read anonymously; a private one answers 404/401,
|
|
25
|
+
* which is null.
|
|
26
|
+
*
|
|
27
|
+
* Synchronous like the rest of the CLI: the request runs in a child `node` (global fetch, Node >= 18)
|
|
28
|
+
* through spawnSync. `withFetcher` is the test seam.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
const { spawnSync } = require('child_process');
|
|
32
|
+
|
|
33
|
+
const PAGE_LIMIT = 50; // Forgejo's default maximum page size
|
|
34
|
+
const MAX_PAGES = 10;
|
|
35
|
+
const TIMEOUT_MS = 30000;
|
|
36
|
+
|
|
37
|
+
let _fetcher = null; // test seam only — see withFetcher
|
|
38
|
+
|
|
39
|
+
// The child: GET argv[1] with the token from the env var COLAB_FORGE_TOKEN_ENV names; print
|
|
40
|
+
// {status, body} as JSON on stdout. Network failures print {status: 0, error}.
|
|
41
|
+
const CHILD = `
|
|
42
|
+
const [url] = process.argv.slice(1);
|
|
43
|
+
const name = process.env.COLAB_FORGE_TOKEN_ENV;
|
|
44
|
+
const token = name ? process.env[name] : '';
|
|
45
|
+
const headers = { accept: 'application/json' };
|
|
46
|
+
if (token) headers.authorization = 'token ' + token;
|
|
47
|
+
fetch(url, { headers, signal: AbortSignal.timeout(${TIMEOUT_MS - 2000}) })
|
|
48
|
+
.then(async (r) => process.stdout.write(JSON.stringify({ status: r.status, body: await r.text() })))
|
|
49
|
+
.catch((e) => process.stdout.write(JSON.stringify({ status: 0, error: String(e && e.message || e) })));
|
|
50
|
+
`;
|
|
51
|
+
|
|
52
|
+
/** GET `url` → `{ status, body }` (status 0 = the request never completed). Never throws. */
|
|
53
|
+
function httpGet(url, tokenEnv) {
|
|
54
|
+
if (_fetcher) return _fetcher(url, { tokenEnv });
|
|
55
|
+
const r = spawnSync(process.execPath, ['-e', CHILD, url], {
|
|
56
|
+
encoding: 'utf8', timeout: TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024,
|
|
57
|
+
env: { ...process.env, COLAB_FORGE_TOKEN_ENV: tokenEnv || '' },
|
|
58
|
+
});
|
|
59
|
+
if (r.error || r.status !== 0) return { status: 0, body: '' };
|
|
60
|
+
try { const o = JSON.parse(r.stdout || '{}'); return { status: Number(o.status) || 0, body: o.body || '' }; } catch (_) { return { status: 0, body: '' }; }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Run `fn` with every HTTP read answered by `fetcher(url, { tokenEnv })` → `{status, body}`. */
|
|
64
|
+
function withFetcher(fetcher, fn) {
|
|
65
|
+
const prev = _fetcher;
|
|
66
|
+
_fetcher = fetcher;
|
|
67
|
+
try { return fn(); } finally { _fetcher = prev; }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** One commit status → one run row in tools/lib/git.js's shape. Pure. */
|
|
71
|
+
function statusRow(sha, st) {
|
|
72
|
+
const state = String((st && st.status) || (st && st.state) || '').toLowerCase();
|
|
73
|
+
const done = state !== 'pending' && state !== '';
|
|
74
|
+
return {
|
|
75
|
+
headSha: sha,
|
|
76
|
+
workflowName: (st && st.context) || null,
|
|
77
|
+
status: done ? 'completed' : 'in_progress',
|
|
78
|
+
conclusion: done ? state : '',
|
|
79
|
+
createdAt: (st && (st.updated_at || st.created_at)) || null,
|
|
80
|
+
databaseId: null,
|
|
81
|
+
url: (st && st.target_url) || null,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The status rows for `sha` from a sequence of combined-status pages, or null when any page failed. Pure. */
|
|
86
|
+
function rowsFromPages(sha, pages) {
|
|
87
|
+
const rows = [];
|
|
88
|
+
for (const p of pages) {
|
|
89
|
+
if (!p || !Array.isArray(p.statuses)) return null;
|
|
90
|
+
for (const st of p.statuses) rows.push(statusRow(sha, st));
|
|
91
|
+
}
|
|
92
|
+
return rows;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function create(repoAbs, eng) {
|
|
96
|
+
const base = `${eng.api}/repos/${encodeURIComponent(eng.owner)}/${encodeURIComponent(eng.repo)}`;
|
|
97
|
+
return {
|
|
98
|
+
kind: 'forgejo',
|
|
99
|
+
repo: repoAbs,
|
|
100
|
+
engine: eng,
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The CI verdict at `sha` (tracker contract, #678). `branch` is accepted and ignored: a commit
|
|
104
|
+
* status belongs to the commit, whatever ref carries it.
|
|
105
|
+
*/
|
|
106
|
+
ciVerdict: (sha) => {
|
|
107
|
+
const full = /^[0-9a-f]{40}$/i.test(String(sha || '')) ? String(sha).toLowerCase() : require('./git').fullSha(repoAbs, sha);
|
|
108
|
+
if (!full) return null;
|
|
109
|
+
const pages = [];
|
|
110
|
+
let seen = 0;
|
|
111
|
+
for (let page = 1; page <= MAX_PAGES; page++) {
|
|
112
|
+
const r = httpGet(`${base}/commits/${full}/status?page=${page}&limit=${PAGE_LIMIT}`, eng.tokenEnv);
|
|
113
|
+
if (r.status !== 200) return null;
|
|
114
|
+
let j;
|
|
115
|
+
try { j = JSON.parse(r.body); } catch (_) { return null; }
|
|
116
|
+
if (!j || typeof j !== 'object') return null;
|
|
117
|
+
pages.push(j);
|
|
118
|
+
const n = Array.isArray(j.statuses) ? j.statuses.length : 0;
|
|
119
|
+
seen += n;
|
|
120
|
+
const total = Number(j.total_count);
|
|
121
|
+
if (n < PAGE_LIMIT || (Number.isFinite(total) && seen >= total)) break;
|
|
122
|
+
if (page === MAX_PAGES) return null; // more statuses than we read: never a partial verdict
|
|
123
|
+
}
|
|
124
|
+
const rows = rowsFromPages(full, pages);
|
|
125
|
+
return rows === null ? null : require('./git').summarizeRunsForCommit(rows, full);
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
module.exports = { create, withFetcher, statusRow, rowsFromPages, PAGE_LIMIT };
|
|
@@ -76,30 +76,57 @@ function entryCovers(p, f) {
|
|
|
76
76
|
* lenient in the direction that makes the gate STRICTER (it still sees
|
|
77
77
|
* the path the author obviously meant); the audit fails the shape.
|
|
78
78
|
*
|
|
79
|
+
* - a `none:` block → #672: the repo has no schema migrations, and `none:`'s value says why:
|
|
80
|
+
* migrations:
|
|
81
|
+
* none: every record lives behind another service's API
|
|
82
|
+
* `none` is then `{ reason }` and `paths` is []. A block, not a scalar plus a
|
|
83
|
+
* sibling key, because the reason is part of the declaration and must not
|
|
84
|
+
* drift from it (and tools/lib/yaml.js reads no flow maps). Without a reason —
|
|
85
|
+
* a bare `migrations: none`, an empty `none:`, a `none` list entry — it is a
|
|
86
|
+
* problem and `none` stays null: the grant gate keeps failing closed (#671).
|
|
87
|
+
* Whether a default layout contradicts it is the caller's to measure, at the
|
|
88
|
+
* commit (`noneContradiction`).
|
|
89
|
+
*
|
|
79
90
|
* `paths` never includes the defaults — `isMigrationPath` always applies those itself. An entry
|
|
80
91
|
* keeps its trailing `/` as written (#673): `a/b/` is a directory, `a/b` a file or a directory.
|
|
81
92
|
*/
|
|
82
93
|
function parseMigrationPaths(doc) {
|
|
83
94
|
const has = !!doc && Object.prototype.hasOwnProperty.call(doc, 'migrations');
|
|
84
95
|
if (!has || doc.migrations === null || doc.migrations === undefined) {
|
|
85
|
-
return { declared: false, paths: [], problems: [], notes: [], reason: 'migrations absent — defaults only' };
|
|
96
|
+
return { declared: false, paths: [], none: null, problems: [], notes: [], reason: 'migrations absent — defaults only' };
|
|
86
97
|
}
|
|
87
98
|
const v = doc.migrations;
|
|
88
99
|
const problems = [];
|
|
89
100
|
const notes = [];
|
|
101
|
+
const NONE_FORM = 'write it as a block naming why — `migrations:` then, indented, `none: <why this repo has no schema migrations>`';
|
|
102
|
+
if (v && typeof v === 'object' && !Array.isArray(v)) {
|
|
103
|
+
const keys = Object.keys(v);
|
|
104
|
+
if (keys.length !== 1 || keys[0] !== 'none') {
|
|
105
|
+
return { declared: true, paths: [], none: null, problems: [`migrations is a block with ${keys.map((k) => `\`${k}\``).join(', ') || 'no key'} — the only block form is \`none: <reason>\` (#672); a layout is a list (e.g. [backend/migrations/])`], notes, reason: 'migrations malformed — defaults only' };
|
|
106
|
+
}
|
|
107
|
+
const why = typeof v.none === 'string' ? v.none.trim() : '';
|
|
108
|
+
if (!why) return { declared: true, paths: [], none: null, problems: [`migrations: none has no reason — ${NONE_FORM}; until it has one, it declares nothing`], notes, reason: 'migrations: none without a reason — defaults only' };
|
|
109
|
+
return { declared: true, paths: [], none: { reason: why }, problems, notes, reason: `migrations: none — ${why}` };
|
|
110
|
+
}
|
|
111
|
+
if (typeof v === 'string' && v.trim().toLowerCase() === 'none') {
|
|
112
|
+
return { declared: true, paths: [], none: null, problems: [`migrations: none needs its reason — ${NONE_FORM}; until it has one, it declares nothing`], notes, reason: 'migrations: none without a reason — defaults only' };
|
|
113
|
+
}
|
|
90
114
|
let entries;
|
|
91
115
|
if (Array.isArray(v)) entries = v;
|
|
92
116
|
else if (typeof v === 'string' && v.trim() !== '') {
|
|
93
117
|
entries = [v];
|
|
94
118
|
problems.push(`migrations is a bare string ${JSON.stringify(v)}, expected a list (e.g. [${v.trim()}])`);
|
|
95
119
|
} else {
|
|
96
|
-
return { declared: true, paths: [], problems: [`migrations is ${JSON.stringify(v)}, expected a list of repo-relative prefixes (e.g. [backend/migrations/])`], notes, reason: 'migrations malformed — defaults only' };
|
|
120
|
+
return { declared: true, paths: [], none: null, problems: [`migrations is ${JSON.stringify(v)}, expected a list of repo-relative prefixes (e.g. [backend/migrations/])`], notes, reason: 'migrations malformed — defaults only' };
|
|
97
121
|
}
|
|
98
122
|
if (Array.isArray(v) && v.length === 0) {
|
|
99
123
|
notes.push('migrations is an empty list — omit the key for the defaults alone');
|
|
100
124
|
}
|
|
101
125
|
const paths = [];
|
|
102
126
|
for (const raw of entries) {
|
|
127
|
+
// #672: `none` inside a list would be a path named `none` — and any declared path reads as a
|
|
128
|
+
// layout, so it would wave the fail-closed grant gate through. Refused, never kept as a path.
|
|
129
|
+
if (typeof raw === 'string' && raw.trim().toLowerCase() === 'none') { problems.push(`migrations: "none" in a list is not a path — to declare no schema migrations, ${NONE_FORM}`); continue; }
|
|
103
130
|
const r = normalizeEntry(raw);
|
|
104
131
|
if (r.problem) { problems.push(`migrations: ${r.problem}`); continue; }
|
|
105
132
|
if (DEFAULT_MIGRATION_PATHS.includes(dirForm(r.path))) {
|
|
@@ -109,7 +136,33 @@ function parseMigrationPaths(doc) {
|
|
|
109
136
|
if (paths.some((q) => dirForm(q) === dirForm(r.path))) { notes.push(`migrations: "${r.path}" is declared twice`); continue; }
|
|
110
137
|
paths.push(r.path);
|
|
111
138
|
}
|
|
112
|
-
return { declared: true, paths, problems, notes, reason: paths.length ? `migrations: [${paths.join(', ')}] + defaults` : 'defaults only' };
|
|
139
|
+
return { declared: true, paths, none: null, problems, notes, reason: paths.length ? `migrations: [${paths.join(', ')}] + defaults` : 'defaults only' };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* #672's guard: a `migrations: none` contradicted by the tree. `none` is parseMigrationPaths().none;
|
|
144
|
+
* `defaultDirs` the default-layout directories found at the commit (`database/migrations/`,
|
|
145
|
+
* `prisma/migrations/`, anywhere), or null when the tree could not be read. Returns a refusal detail,
|
|
146
|
+
* or null when `none` stands (or there is no `none`). An unread tree is not "absent": the caller
|
|
147
|
+
* fails closed on it the way it already does — this answers only "does a layout exist".
|
|
148
|
+
*/
|
|
149
|
+
function noneContradiction(none, defaultDirs) {
|
|
150
|
+
if (!none || !defaultDirs || !defaultDirs.length) return null;
|
|
151
|
+
const dirs = defaultDirs.slice(0, 3).join(', ') + (defaultDirs.length > 3 ? ` (+${defaultDirs.length - 3} more)` : '');
|
|
152
|
+
return `the repo declares \`migrations: none\` (${none.reason}) but ${dirs} exists at the commit — a repo that can have migrations is never waved through: remove the \`none:\` block (the default layout is read without it), or remove the directory`;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The default-layout directories in a `git ls-tree -r -d --name-only` listing (#670, #672), outermost match per path. */
|
|
156
|
+
function defaultLayoutDirs(dirs) {
|
|
157
|
+
const out = [];
|
|
158
|
+
for (const d of dirs || []) {
|
|
159
|
+
if (!d) continue;
|
|
160
|
+
const dd = `${d}/`;
|
|
161
|
+
for (const def of DEFAULT_MIGRATION_PATHS) {
|
|
162
|
+
if ((dd === def || dd.endsWith(`/${def}`)) && !out.includes(dd)) out.push(dd);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return out;
|
|
113
166
|
}
|
|
114
167
|
|
|
115
168
|
/** Union of several docs' declared prefixes (trunk's + the branch's) — the gate sees every one. */
|
|
@@ -119,6 +172,32 @@ function unionPaths(...docs) {
|
|
|
119
172
|
return out;
|
|
120
173
|
}
|
|
121
174
|
|
|
175
|
+
/**
|
|
176
|
+
* #676: which declared entries name something at a commit. `files` is that commit's tracked-file list
|
|
177
|
+
* (`git ls-tree -r --name-only <sha>`), or null when it could not be read. A directory entry exists
|
|
178
|
+
* when a tracked file sits under it, a no-slash entry when it is that file or a directory holding one
|
|
179
|
+
* (entryCovers, the same rule the gate matches by). Returns `{ present, missing }` in declared order,
|
|
180
|
+
* or null for an unread tree — never "everything missing", which would be a guess.
|
|
181
|
+
*
|
|
182
|
+
* Before this a declared path counted as a layout whether or not it existed, so a misspelled or stale
|
|
183
|
+
* entry opened the migration-grant gate having read nothing. Only `present` is a layout; `missing` is
|
|
184
|
+
* named wherever the gate reports, and a gate with nothing else to read fails closed.
|
|
185
|
+
*/
|
|
186
|
+
function declaredPresence(declared, files) {
|
|
187
|
+
if (!Array.isArray(files)) return null;
|
|
188
|
+
const present = [];
|
|
189
|
+
const missing = [];
|
|
190
|
+
for (const p of declared || []) (files.some((f) => entryCovers(p, f)) ? present : missing).push(p);
|
|
191
|
+
return { present, missing };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** `missing` (declaredPresence) as the one sentence every gate appends — empty when none is missing. */
|
|
195
|
+
function missingNote(missing, where = 'the candidate') {
|
|
196
|
+
if (!missing || !missing.length) return '';
|
|
197
|
+
const list = missing.join(', ');
|
|
198
|
+
return `declared \`migrations:\` ${missing.length === 1 ? 'path' : 'paths'} ${list} ${missing.length === 1 ? 'does' : 'do'} not exist at ${where}, so nothing was read there — fix or remove ${missing.length === 1 ? 'the entry' : 'the entries'} in .github/project.yml (a misspelled or stale path is not a layout, #676)`;
|
|
199
|
+
}
|
|
200
|
+
|
|
122
201
|
/** Is `file` (repo-relative, `/`-separated) a migration under the defaults or a declared prefix? */
|
|
123
202
|
function isMigrationPath(file, declared) {
|
|
124
203
|
const f = String(file || '');
|
|
@@ -162,4 +241,5 @@ function undeclaredMigrationDirs(files, declared) {
|
|
|
162
241
|
|
|
163
242
|
module.exports = {
|
|
164
243
|
DEFAULT_MIGRATION_PATHS, parseMigrationPaths, unionPaths, isMigrationPath, isDeclaredFile, undeclaredMigrationDirs,
|
|
244
|
+
noneContradiction, defaultLayoutDirs, declaredPresence, missingNote,
|
|
165
245
|
};
|
package/tools/lib/release-cut.js
CHANGED
|
@@ -845,6 +845,65 @@ function laravelUpBody(text) {
|
|
|
845
845
|
return down === -1 ? text.slice(up) : text.slice(up, up + down);
|
|
846
846
|
}
|
|
847
847
|
|
|
848
|
+
// #674: Laravel Blueprint methods that ADD a column. An allowlist, so it fails closed: a statement
|
|
849
|
+
// whose first call is not on it (`unique('x')`, `index('x')`, a macro) never counts as adding `x`.
|
|
850
|
+
const LARAVEL_COLUMN_TYPES = new Set(('bigIncrements bigInteger binary boolean char dateTimeTz dateTime date ' +
|
|
851
|
+
'decimal double enum float foreignId foreignIdFor foreignUlid foreignUuid geography geometry id increments ' +
|
|
852
|
+
'integer ipAddress json jsonb longText macAddress mediumIncrements mediumInteger mediumText morphs ' +
|
|
853
|
+
'nullableMorphs nullableTimestamps nullableUlidMorphs nullableUuidMorphs rememberToken set smallIncrements ' +
|
|
854
|
+
'smallInteger softDeletesTz softDeletes string text timeTz time timestampTz timestamp timestampsTz timestamps ' +
|
|
855
|
+
'tinyIncrements tinyInteger tinyText unsignedBigInteger unsignedDecimal unsignedInteger unsignedMediumInteger ' +
|
|
856
|
+
'unsignedSmallInteger unsignedTinyInteger ulidMorphs uuidMorphs ulid uuid vector year').split(' '));
|
|
857
|
+
const LARAVEL_SCHEMA_TABLE = /Schema\s*::\s*(?:connection\s*\([^)]*\)\s*->\s*)?(?:create|table)\s*\(\s*['"]([^'"]+)['"]/g;
|
|
858
|
+
|
|
859
|
+
/**
|
|
860
|
+
* #674: the columns one Laravel `up()` body adds and changes, in source order —
|
|
861
|
+
* [{ kind: 'add'|'change', table, column, index }], `index` = the `->change(` offset for a change.
|
|
862
|
+
* A statement is `;`-delimited; its column is the first `$var->type('name'` in it, with `type` on
|
|
863
|
+
* the allowlist above; its table is the last `Schema::create|table('<table>'` before it. A statement
|
|
864
|
+
* with no table or no readable column is not listed — so a `->change()` in it stays destructive.
|
|
865
|
+
*/
|
|
866
|
+
function laravelColumnEvents(up) {
|
|
867
|
+
const tables = [...up.matchAll(LARAVEL_SCHEMA_TABLE)].map((m) => ({ at: m.index, table: m[1] }));
|
|
868
|
+
const tableAt = (pos) => { let t = null; for (const s of tables) { if (s.at < pos) t = s.table; else break; } return t; };
|
|
869
|
+
const events = [];
|
|
870
|
+
let start = 0;
|
|
871
|
+
for (const stmt of up.split(';')) {
|
|
872
|
+
const col = /\$\w+\s*->\s*(\w+)\s*\(\s*['"]([^'"]+)['"]/.exec(stmt);
|
|
873
|
+
const table = col && tableAt(start + col.index);
|
|
874
|
+
if (col && table && LARAVEL_COLUMN_TYPES.has(col[1])) {
|
|
875
|
+
const ch = /->\s*change\s*\(/.exec(stmt);
|
|
876
|
+
events.push(ch ? { kind: 'change', table, column: col[2], index: start + ch.index } : { kind: 'add', table, column: col[2] });
|
|
877
|
+
}
|
|
878
|
+
start += stmt.length + 1;
|
|
879
|
+
}
|
|
880
|
+
return events;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* #674: the first destructive call in a Laravel `up()` — the RegExp match — or null. A `->change()` on
|
|
885
|
+
* a column this release itself added — earlier in the same file, or in an ADDED migration that runs
|
|
886
|
+
* before it (`addedBefore`, a Set of `table.column`) — rewrites nothing the last final shipped, so it is
|
|
887
|
+
* not destructive: add nullable, backfill, then tighten the same column `->nullable(false)->change()`
|
|
888
|
+
* is the ordinary safe shape. A change on any other column still is.
|
|
889
|
+
*/
|
|
890
|
+
function laravelDestructive(up, addedBefore) {
|
|
891
|
+
const events = laravelColumnEvents(up);
|
|
892
|
+
const fresh = new Set(addedBefore || []);
|
|
893
|
+
const exempt = new Set();
|
|
894
|
+
for (const e of events) {
|
|
895
|
+
const key = `${e.table}.${e.column}`;
|
|
896
|
+
if (e.kind === 'add') fresh.add(key);
|
|
897
|
+
else if (fresh.has(key)) exempt.add(e.index);
|
|
898
|
+
}
|
|
899
|
+
const re = new RegExp(LARAVEL_DESTRUCTIVE.source, 'g');
|
|
900
|
+
for (const m of up.matchAll(re)) {
|
|
901
|
+
if (/->\s*change/.test(m[0]) && exempt.has(m.index)) continue;
|
|
902
|
+
return m;
|
|
903
|
+
}
|
|
904
|
+
return null;
|
|
905
|
+
}
|
|
906
|
+
|
|
848
907
|
/**
|
|
849
908
|
* `changes` is [{ status, path, content }] for every changed path since the last final tag —
|
|
850
909
|
* `status` is git's --name-status letter (A/M/D/R…), `content` the file at the candidate commit
|
|
@@ -866,9 +925,28 @@ function laravelUpBody(text) {
|
|
|
866
925
|
* is destructive (a destructive read file is still ✗).
|
|
867
926
|
* `layout` = does `database/migrations/` or `prisma/migrations/` exist in the tree at the candidate:
|
|
868
927
|
* true / false / null (the tree could not be read — never "absent"). Undefined = a caller that does
|
|
869
|
-
* not measure it, read as today: present.
|
|
928
|
+
* not measure it, read as today: present. `none` (#672) = the candidate's `migrations: none` block
|
|
929
|
+
* (`{ reason, dirs? }`), or absent.
|
|
930
|
+
*
|
|
931
|
+
* #676: `missing` = the declared entries that do not exist at the candidate (migration-paths.js
|
|
932
|
+
* declaredPresence). They still classify a change (a file deleted under one is still read — the gate
|
|
933
|
+
* sees more, never less), but they are not a layout and not in the ✓'s scope: with nothing else to
|
|
934
|
+
* read the verdict is NOT CHECKED naming them, and beside a real layout every detail names them.
|
|
935
|
+
* `missing` null = the tree could not be listed (pass `layout` null with it): unread, never a ✓.
|
|
936
|
+
* Undefined = a caller that does not measure it, read as before: every declared path present.
|
|
870
937
|
*/
|
|
871
|
-
function schemaVerdict(changes, since, declared, layout) {
|
|
938
|
+
function schemaVerdict(changes, since, declared, layout, none, missing) {
|
|
939
|
+
const v = schemaVerdictCore(changes, since, declared, layout, none, missing);
|
|
940
|
+
const note = v.missingNamed ? '' : migrationPaths.missingNote(missing);
|
|
941
|
+
const { missingNamed, ...out } = v;
|
|
942
|
+
return note ? { ...out, detail: `${out.detail} — ${note}` } : out;
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
function schemaVerdictCore(changes, since, declared, layout, none, missing) {
|
|
946
|
+
// #672: the candidate's `migrations: none` block. Contradicted by a default layout → refused on every
|
|
947
|
+
// cut, whatever changed; otherwise, with nothing changed, "not checked" naming the declaration —
|
|
948
|
+
// never a ✓ (nothing was read), never the "declare a layout" advice (the repo already answered).
|
|
949
|
+
if (none && layout === true) return { ok: false, detail: migrationPaths.noneContradiction(none, none.dirs && none.dirs.length ? none.dirs : ['a Laravel database/migrations/ or Prisma prisma/migrations/ directory']) };
|
|
872
950
|
const inPaths = (changes || []).filter((c) => isMigrationPath(c.path, declared));
|
|
873
951
|
// #673: a declared schema FILE (an inline schema the server applies itself) is read by the lines
|
|
874
952
|
// its change added — never "unread", and an edit is never "an existing migration was rewritten".
|
|
@@ -883,24 +961,37 @@ function schemaVerdict(changes, since, declared, layout) {
|
|
|
883
961
|
const unread = (declared && declared.length)
|
|
884
962
|
? history.filter((c) => !/\.(php|sql)$/.test(c.path) && !migrationPaths.isMigrationPath(c.path, []))
|
|
885
963
|
: [];
|
|
886
|
-
|
|
887
|
-
const
|
|
964
|
+
// `missing` null = the candidate's tree could not be listed: no declared path is known to exist.
|
|
965
|
+
const present = missing === null ? [] : (declared || []).filter((p) => !(missing || []).includes(p));
|
|
966
|
+
const scope = `Laravel database/migrations + Prisma prisma/migrations${present.length ? ` + declared ${present.join(', ')} (php/sql only; a declared file: the SQL it added)` : ''} — other layouts are not read`;
|
|
967
|
+
const hasDeclared = present.length > 0;
|
|
888
968
|
const notChecked = (why) => ({ ok: true, checked: false, detail: `not checked — ${why}` });
|
|
889
969
|
const unreadWhy = () => `${unread.length} declared migration file(s) changed since ${since} in a format this check does not read (php/sql only) — a human reads them before the final: ${unread.map((c) => c.path).join(', ')}`;
|
|
890
|
-
const howToDeclare = 'a repo whose migrations live elsewhere declares their directory as `migrations:` in .github/project.yml (project.schema.md `migrations`); a repo with no
|
|
970
|
+
const howToDeclare = 'a repo whose migrations live elsewhere declares their directory as `migrations:` in .github/project.yml (project.schema.md `migrations`); a repo with no schema migrations declares `migrations:` then `none: <why>` (#672)';
|
|
891
971
|
if (!migrations.length && !schemaFiles.length) {
|
|
892
972
|
if (unread.length) return notChecked(unreadWhy());
|
|
973
|
+
if (none && layout === false) return notChecked(`the repo declares \`migrations: none\` (${none.reason}) and no Laravel or Prisma migrations directory exists at the candidate, so there is no schema to read`);
|
|
974
|
+
if (!hasDeclared && layout === false && missing && missing.length) {
|
|
975
|
+
return { ...notChecked(`the declared \`migrations:\` ${missing.length === 1 ? 'path' : 'paths'} ${missing.join(', ')} ${missing.length === 1 ? 'does' : 'do'} not exist at the candidate and there is no Laravel database/migrations/ or Prisma prisma/migrations/ directory, so no migration was read — fix the path (a misspelled or stale entry is not a layout, #676), or ${howToDeclare}`), missingNamed: true };
|
|
976
|
+
}
|
|
893
977
|
if (!hasDeclared && layout === false) return notChecked(`no Laravel database/migrations/ or Prisma prisma/migrations/ directory at the candidate and no \`migrations:\` declared, so no migration was read — ${howToDeclare}`);
|
|
894
978
|
if (!hasDeclared && layout === null) return notChecked(`the tree at the candidate could not be read for a migration layout, so no migration was read — ${howToDeclare}`);
|
|
895
979
|
return { ok: true, detail: `no migration file changed since ${since} (${scope})` };
|
|
896
980
|
}
|
|
897
981
|
const findings = [];
|
|
982
|
+
// #674: columns added by every ADDED Laravel migration, keyed by run order (Laravel runs by file
|
|
983
|
+
// name), so a `->change()` on a column an earlier added migration created is read as this release's.
|
|
984
|
+
const base = (p) => p.slice(p.lastIndexOf('/') + 1);
|
|
985
|
+
const laravelAdds = migrations
|
|
986
|
+
.filter((c) => String(c.status || '').charAt(0) === 'A' && c.path.endsWith('.php'))
|
|
987
|
+
.map((c) => ({ name: base(c.path), adds: laravelColumnEvents(laravelUpBody(String(c.content || ''))).filter((e) => e.kind === 'add').map((e) => `${e.table}.${e.column}`) }));
|
|
988
|
+
const addedBefore = (p) => laravelAdds.filter((a) => a.name < base(p)).flatMap((a) => a.adds);
|
|
898
989
|
for (const c of migrations) {
|
|
899
990
|
const st = String(c.status || '').charAt(0);
|
|
900
991
|
if (st !== 'A') { findings.push(`${c.path}: ${st === 'D' ? 'deleted' : st === 'R' ? 'renamed' : 'edited'} — an existing migration was rewritten`); continue; }
|
|
901
992
|
const text = String(c.content || '');
|
|
902
993
|
if (c.path.endsWith('.php')) {
|
|
903
|
-
const m =
|
|
994
|
+
const m = laravelDestructive(laravelUpBody(text), addedBefore(c.path));
|
|
904
995
|
if (m) findings.push(`${c.path}: \`${m[0].trim()}\` in up()`);
|
|
905
996
|
} else {
|
|
906
997
|
if (SQL_DOWN_FILE.test(c.path)) continue;
|
|
@@ -61,6 +61,7 @@
|
|
|
61
61
|
*/
|
|
62
62
|
|
|
63
63
|
const releaseTag = require('./release-tag');
|
|
64
|
+
const migrationPaths = require('./migration-paths');
|
|
64
65
|
|
|
65
66
|
// The tracking marker and the event marker are wire format: codec/release.js (#498, epic #496),
|
|
66
67
|
// re-exported below under the names this module always had. VERSION_RE is the codec's, so a
|
|
@@ -564,17 +565,39 @@ function regressionVerdict(edges, { periodStart }) {
|
|
|
564
565
|
* true = a `migrations:` prefix is declared or a default layout (Laravel database/migrations/,
|
|
565
566
|
* Prisma prisma/migrations/) exists in the tree; false = neither, so an empty `paths` is "nothing
|
|
566
567
|
* read", not "nothing changed"; null/absent = the tree could not be read. An empty `paths` passes
|
|
567
|
-
* only with a layout
|
|
568
|
+
* only with a layout — or (#672) with `none`: the candidate's committed `migrations: none` block
|
|
569
|
+
* (`{ reason, dirs? }` — `dirs` the default-layout directories found, for the refusal), honoured only where no default layout exists (`layout` false). With a layout there
|
|
570
|
+
* (`layout` true) the declaration is a contradiction and the gate refuses, migrations changed or not:
|
|
571
|
+
* a repo that can have migrations is never waved through; an unread tree still fails closed.
|
|
572
|
+
* #676: `layout` true comes from a declared path only when it EXISTS at the candidate
|
|
573
|
+
* (migration-paths.js declaredPresence); `missing` lists the declared paths that do not. Every detail
|
|
574
|
+
* names them, and with nothing else to read the refusal says so — a misspelled or stale path is not
|
|
575
|
+
* a layout. Missing beside a real layout is reported, never refused: the gate reads what exists.
|
|
576
|
+
* Returns { ok, detail } (+ unread: true when something could not be read).
|
|
568
577
|
*/
|
|
569
|
-
function migrationGrantVerdict(
|
|
578
|
+
function migrationGrantVerdict(args) {
|
|
579
|
+
const { missingNamed, ...v } = migrationGrantVerdictCore(args);
|
|
580
|
+
const note = missingNamed ? '' : migrationPaths.missingNote(args.missing);
|
|
581
|
+
return note ? { ...v, detail: `${v.detail} — ${note}` } : v;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function migrationGrantVerdictCore({ paths, grant, since, layout, none, missing }) {
|
|
570
585
|
if (paths === null || paths === undefined) return { ok: false, unread: true, detail: 'the migration files since the last final could not be read — an unread migration is not an absent one' };
|
|
586
|
+
if (none) {
|
|
587
|
+
if (layout === true) return { ok: false, detail: `${migrationPaths.noneContradiction(none, none.dirs && none.dirs.length ? none.dirs : ['a Laravel database/migrations/ or Prisma prisma/migrations/ directory'])} — then the usual migration grant applies (COLAB_HUMAN=1 colab migration-grant <tracking issue> --branch <version>)` };
|
|
588
|
+
if (layout === false && !paths.length) return { ok: true, detail: `no schema migrations to read since ${since || 'the first commit'}: the repo declares \`migrations: none\` (${none.reason}), and no Laravel or Prisma migrations directory exists at the candidate` };
|
|
589
|
+
}
|
|
571
590
|
if (!paths.length) {
|
|
572
591
|
// #671: fail closed where nothing could have been seen — an automatically deployed final never
|
|
573
592
|
// reads "nothing read" as "nothing changed". The way out is named in the detail, never implied —
|
|
574
593
|
// route-neutral: release finalize prints its own human command, and route deploy-tag-fast has none.
|
|
575
594
|
// #673: a schema applied inline by the server's own code is declarable too — as the FILE — and the
|
|
576
595
|
// detail names the grant command that clears its next change, so no one reaches for a raw tag.
|
|
577
|
-
const wayOut = 'declare where the schema lives as `migrations:` in .github/project.yml (project.schema.md `migrations`) — a migration directory (`migrations: [backend/migrations/]`) or, for a schema the server applies inline, the file itself (`migrations: [server/db.ts]`); a change under it then clears the usual way (COLAB_HUMAN=1 colab migration-grant <tracking issue> --branch <version>).
|
|
596
|
+
const wayOut = 'declare where the schema lives as `migrations:` in .github/project.yml (project.schema.md `migrations`) — a migration directory (`migrations: [backend/migrations/]`) or, for a schema the server applies inline, the file itself (`migrations: [server/db.ts]`); a change under it then clears the usual way (COLAB_HUMAN=1 colab migration-grant <tracking issue> --branch <version>). A repo with no schema migrations at all declares that instead, with its reason (`migrations:` then `none: <why>`, #672). Until then the final is a human act, not the grant\'s';
|
|
597
|
+
if (layout === false && missing && missing.length) {
|
|
598
|
+
// #676: declared, but nothing it names is there — the same "cannot see" as an undeclared repo.
|
|
599
|
+
return { ok: false, missingNamed: true, detail: `no migration was read since ${since || 'the first commit'}: the declared \`migrations:\` ${missing.length === 1 ? 'path' : 'paths'} ${missing.join(', ')} ${missing.length === 1 ? 'does' : 'do'} not exist at the candidate and there is no Laravel database/migrations/ or Prisma prisma/migrations/ directory, so a migration would be invisible — fix the path (a misspelled or stale entry is not a layout, #676), or ${wayOut}` };
|
|
600
|
+
}
|
|
578
601
|
if (layout === false) return { ok: false, detail: `no migration was read since ${since || 'the first commit'}: no \`migrations:\` declared and no Laravel database/migrations/ or Prisma prisma/migrations/ directory at the candidate, so a migration elsewhere would be invisible — ${wayOut}` };
|
|
579
602
|
if (layout !== true) return { ok: false, unread: true, detail: `the tree at the candidate could not be read for a migration layout, so an empty migration list since ${since || 'the first commit'} is not evidence that none changed — ${wayOut}` };
|
|
580
603
|
return { ok: true, detail: `no migration file changed since ${since || 'the first commit'}` };
|
package/tools/lib/stale-base.js
CHANGED
|
@@ -27,18 +27,28 @@
|
|
|
27
27
|
* 'no-change' = it is not, but the head lands no change (evidence-close)
|
|
28
28
|
* @param {number|null} a.behind - commits on the base the head lacks (display only)
|
|
29
29
|
* @param {string} a.base - the base's name, for the detail line
|
|
30
|
-
* @param {boolean} a.
|
|
30
|
+
* @param {boolean} a.ciReadable - false = no CI read exists on this host: gh not usable and the
|
|
31
|
+
* remote's engine is not one the CLI reads CI from (#678). The old
|
|
32
|
+
* name `ghUsable` is still accepted.
|
|
31
33
|
* @returns {{ok:boolean, verdict:string, selfClearing:boolean, detail:string}}
|
|
32
34
|
*/
|
|
33
35
|
function staleBaseVerdict(a) {
|
|
34
36
|
const short = (s) => (s ? String(s).slice(0, 7) : '?');
|
|
37
|
+
const ciReadable = a.ciReadable !== undefined ? a.ciReadable : a.ghUsable;
|
|
35
38
|
if (!a.headSha) {
|
|
36
39
|
return { ok: true, verdict: 'no-run', selfClearing: false,
|
|
37
40
|
detail: 'branch not on the remote — no branch run exists to be stale (B2a reads the trunk run at the squash)' };
|
|
38
41
|
}
|
|
39
|
-
if (!
|
|
40
|
-
//
|
|
41
|
-
|
|
42
|
+
if (!ciReadable) {
|
|
43
|
+
// #678: this used to pass ("the CI row above already refuses"). Once the CI row reads a forge
|
|
44
|
+
// other than GitHub, that is no longer true, and a pass here would let a stale branch land on an
|
|
45
|
+
// unread verdict. Unread refuses — except a head that lands nothing, which grades nothing (#90).
|
|
46
|
+
if (a.contains === 'no-change') {
|
|
47
|
+
return { ok: true, verdict: 'no-change', selfClearing: false,
|
|
48
|
+
detail: `the head introduces no change against ${a.base} — nothing lands, so nothing is graded (evidence-close, #90)` };
|
|
49
|
+
}
|
|
50
|
+
return { ok: false, verdict: 'unread', selfClearing: false,
|
|
51
|
+
detail: `no CI read on this host (gh not usable, and the remote's forge is not one colab reads CI from) — the branch run at ${short(a.headSha)} is unread, and an unread verdict never passes (#678)` };
|
|
42
52
|
}
|
|
43
53
|
if (a.run === null || a.run === undefined) {
|
|
44
54
|
return { ok: false, verdict: 'unread', selfClearing: true,
|
|
@@ -178,6 +178,11 @@ function create(repoAbs, given = {}) {
|
|
|
178
178
|
.filter((r) => r.headBranch === branch && (!commit || r.headSha === commit))
|
|
179
179
|
.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
180
180
|
.slice(0, limit).map((r) => pick(r, fields))),
|
|
181
|
+
// #678: the same summary the real adapters return, over the seeded runs at `sha` (on `branch` when named).
|
|
182
|
+
ciVerdict: (sha, { branch = null } = {}) => {
|
|
183
|
+
if (offline) return null;
|
|
184
|
+
return require('./git').summarizeRunsForCommit(clone(runs.filter((r) => r.headSha === sha && (!branch || r.headBranch === branch))), sha);
|
|
185
|
+
},
|
|
181
186
|
|
|
182
187
|
releaseView: (tag) => {
|
|
183
188
|
if (offline) return result(false);
|
|
@@ -154,6 +154,12 @@ function create(repoAbs) {
|
|
|
154
154
|
runList: ({ branch, commit, limit, fields }) => withData(exec(
|
|
155
155
|
['run', 'list', '--branch', branch, ...(commit ? ['--commit', commit] : []), '-L', String(limit),
|
|
156
156
|
'--json', fields.join(',')], at)),
|
|
157
|
+
// #678: the one-summary CI verdict at `sha` — the exact reads ship made before the contract had
|
|
158
|
+
// it: by branch when one is named (ghRunForCommit), by commit otherwise (ghRunForCommitAnyRef).
|
|
159
|
+
ciVerdict: (sha, { branch = null, verifying = null } = {}) => {
|
|
160
|
+
const opts = verifying ? { verifying } : {};
|
|
161
|
+
return branch ? git().ghRunForCommit(repoAbs, branch, sha, undefined, opts) : git().ghRunForCommitAnyRef(repoAbs, sha, undefined, opts);
|
|
162
|
+
},
|
|
157
163
|
|
|
158
164
|
// --- releases ----------------------------------------------------------------------------
|
|
159
165
|
releaseView: (tag) => exec(['release', 'view', tag, '--json', 'tagName'], at),
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"labels": "the label names defined on the repo, in the order labelList returns them.",
|
|
18
18
|
"issues": "[{number, title, body, state: OPEN|CLOSED, stateReason, labels: [name], assignees: [login], comments: [{author, body}], events: [{event: \"labeled\", label, actor}]}] — `events` is the label timeline claimHolder reads; the claimer is the actor of the LATEST labeled in-progress event.",
|
|
19
19
|
"prs": "[{number, head, base, title, body, state: OPEN|CLOSED|MERGED, author}] — issues and pull requests share ONE number sequence, as on GitHub.",
|
|
20
|
-
"runs": "[{headBranch, headSha, status, conclusion, event, workflowName, createdAt}] — CI runs; runList returns them newest first by createdAt.",
|
|
20
|
+
"runs": "[{headBranch, headSha, status, conclusion, event, workflowName, createdAt, databaseId}] — CI runs; runList returns them newest first by createdAt; ciVerdict (#678) summarizes the ones at one sha.",
|
|
21
21
|
"releases": "[{tag, prerelease}]"
|
|
22
22
|
},
|
|
23
23
|
"scenarios": [
|
|
@@ -201,6 +201,37 @@
|
|
|
201
201
|
{ "call": "runList", "args": [{ "branch": "main", "limit": 5, "fields": ["headSha"] }], "expect": { "ok": false, "data": null } },
|
|
202
202
|
{ "call": "prForBranch", "args": ["feat/x-1"], "expect": { "error": { "$type": "string" } } }
|
|
203
203
|
]
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
"id": "ci-verdict",
|
|
207
|
+
"description": "ciVerdict reads every CI result at one commit as ONE verdict (#678): green only when every workflow at the sha finished and succeeded; one failed workflow makes it red; an unfinished one reads as still running; no result at all is status none with runCount 0 — never null, which is reserved for a read that failed.",
|
|
208
|
+
"given": {
|
|
209
|
+
"login": "alice",
|
|
210
|
+
"runs": [
|
|
211
|
+
{"headBranch": "main", "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "status": "completed", "conclusion": "success", "event": "push", "workflowName": "CI", "createdAt": "2026-11-01T10:00:00Z", "databaseId": 101},
|
|
212
|
+
{"headBranch": "main", "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "status": "completed", "conclusion": "success", "event": "push", "workflowName": "Lint", "createdAt": "2026-11-01T10:00:05Z", "databaseId": 102},
|
|
213
|
+
{"headBranch": "main", "headSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "status": "completed", "conclusion": "failure", "event": "push", "workflowName": "CI", "createdAt": "2026-11-01T11:00:00Z", "databaseId": 103},
|
|
214
|
+
{"headBranch": "main", "headSha": "dddddddddddddddddddddddddddddddddddddddd", "status": "in_progress", "conclusion": "", "event": "push", "workflowName": "CI", "createdAt": "2026-11-01T12:00:00Z", "databaseId": 104}
|
|
215
|
+
]
|
|
216
|
+
},
|
|
217
|
+
"steps": [
|
|
218
|
+
{ "call": "ciVerdict", "args": ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", { "branch": "main" }],
|
|
219
|
+
"expect": {"status": "completed", "conclusion": "success", "sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "runCount": 2} },
|
|
220
|
+
{ "call": "ciVerdict", "args": ["bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", { "branch": "main" }],
|
|
221
|
+
"expect": {"status": "completed", "conclusion": "failure", "sha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"} },
|
|
222
|
+
{ "call": "ciVerdict", "args": ["dddddddddddddddddddddddddddddddddddddddd", { "branch": "main" }],
|
|
223
|
+
"expect": {"status": "in_progress", "sha": "dddddddddddddddddddddddddddddddddddddddd"} },
|
|
224
|
+
{ "call": "ciVerdict", "args": ["cccccccccccccccccccccccccccccccccccccccc", { "branch": "main" }],
|
|
225
|
+
"expect": {"status": "none", "sha": "cccccccccccccccccccccccccccccccccccccccc", "runCount": 0} }
|
|
226
|
+
]
|
|
227
|
+
},
|
|
228
|
+
{
|
|
229
|
+
"id": "ci-verdict-unreadable",
|
|
230
|
+
"description": "A CI read that cannot reach the tracker returns null — could not read, never a `none` verdict a caller would take for unwired CI.",
|
|
231
|
+
"given": { "login": "alice", "offline": true },
|
|
232
|
+
"steps": [
|
|
233
|
+
{ "call": "ciVerdict", "args": ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", { "branch": "main" }], "expect": null }
|
|
234
|
+
]
|
|
204
235
|
}
|
|
205
236
|
]
|
|
206
237
|
}
|
package/tools/lib/tracker.js
CHANGED
|
@@ -15,9 +15,16 @@
|
|
|
15
15
|
* "could not read" and never "none"; the read helpers keep their existing null-on-failure
|
|
16
16
|
* contract.
|
|
17
17
|
*
|
|
18
|
+
* CI verdict (#678): `ciVerdict(sha, { branch })` answers "is this sha green" as ONE summary —
|
|
19
|
+
* `{ status, conclusion, sha, createdAt, databaseId, runCount, … }` (tools/lib/git.js
|
|
20
|
+
* `summarizeRunsForCommit`'s shape, the one ship's CI rows and the docs-only row already read), or
|
|
21
|
+
* null when the read failed. `status: 'none'` is "no run at this sha", never "could not read". A
|
|
22
|
+
* forge that only lands code (no issue tracker the CLI writes to) implements just `CI_METHODS`:
|
|
23
|
+
* tools/lib/ci-forgejo.js, Forgejo commit statuses. Which engine a repo gets is `engineFor` below.
|
|
24
|
+
*
|
|
18
25
|
* Deliberately NOT in the contract yet (#501 left it so: no scenario needs them, and each would
|
|
19
|
-
* pin a GitHub-only shape into a spec other trackers must satisfy): the CI-run
|
|
20
|
-
*
|
|
26
|
+
* pin a GitHub-only shape into a spec other trackers must satisfy): the raw CI-run lists and REST
|
|
27
|
+
* probes behind `ciVerdict`, label create/delete/edit, raw `issue edit` flags and raw `api`
|
|
21
28
|
* access. They still reach `gh` only through the adapter's `exec`.
|
|
22
29
|
*/
|
|
23
30
|
|
|
@@ -38,13 +45,21 @@ const METHODS = Object.freeze([
|
|
|
38
45
|
{ name: 'prList', kind: 'read', returns: 'result + data: pr[] | null' },
|
|
39
46
|
{ name: 'prEdit', kind: 'write', returns: 'result' },
|
|
40
47
|
{ name: 'runList', kind: 'read', returns: 'result + data: run[] | null' },
|
|
48
|
+
{ name: 'ciVerdict', kind: 'read', returns: 'run summary | null' },
|
|
41
49
|
{ name: 'releaseView', kind: 'read', returns: 'result' },
|
|
42
50
|
{ name: 'releaseCreate', kind: 'write', returns: 'result' },
|
|
43
51
|
].map(Object.freeze));
|
|
44
52
|
|
|
45
|
-
/**
|
|
46
|
-
|
|
47
|
-
|
|
53
|
+
/** The methods a CI-only engine implements (#678): a forge the CLI lands code on but never writes issues to. */
|
|
54
|
+
const CI_METHODS = Object.freeze(['ciVerdict']);
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Throw, naming every contract method `impl` lacks. Returns `impl` when it is complete.
|
|
58
|
+
* `names` narrows the check to a subset (CI_METHODS for a CI-only engine); default: the whole contract.
|
|
59
|
+
*/
|
|
60
|
+
function assertImplements(impl, label = 'tracker', names = null) {
|
|
61
|
+
const want = names ? METHODS.filter((m) => names.includes(m.name)) : METHODS;
|
|
62
|
+
const missing = want.filter((m) => !impl || typeof impl[m.name] !== 'function').map((m) => m.name);
|
|
48
63
|
if (missing.length) throw new Error(`${label} does not implement the tracker contract: missing ${missing.join(', ')}`);
|
|
49
64
|
return impl;
|
|
50
65
|
}
|
|
@@ -61,4 +76,100 @@ function forRepo(repoAbs, { kind = 'github' } = {}) {
|
|
|
61
76
|
return impl;
|
|
62
77
|
}
|
|
63
78
|
|
|
64
|
-
|
|
79
|
+
// ---------------------------------------------------------------------------------------------
|
|
80
|
+
// Engine choice by remote host (#678)
|
|
81
|
+
// ---------------------------------------------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
/** Engines the map may name. `github` is the default for every host the map does not name. */
|
|
84
|
+
const ENGINES = Object.freeze(['github', 'forgejo']);
|
|
85
|
+
const DEFAULT_TOKEN_ENV = 'FORGEJO_TOKEN';
|
|
86
|
+
|
|
87
|
+
/** `{ host, owner, repo }` for a remote URL (https, ssh://, scp-like), or null. Pure. */
|
|
88
|
+
function parseRemoteUrl(url) {
|
|
89
|
+
const s = String(url || '').trim();
|
|
90
|
+
let m = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(?:(.+)\/)?([^/]+)\/([^/]+?)(?:\.git)?\/*$/i.exec(s);
|
|
91
|
+
if (m) return { host: m[1].toLowerCase(), owner: m[3], repo: m[4] };
|
|
92
|
+
m = /^(?:[^@/\s]+@)?([^:/\s]+):(?:(.+)\/)?([^/]+)\/([^/]+?)(?:\.git)?\/*$/.exec(s);
|
|
93
|
+
if (m) return { host: m[1].toLowerCase(), owner: m[3], repo: m[4] };
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The engine for one remote URL, from a parsed machine config. Pure.
|
|
99
|
+
*
|
|
100
|
+
* The map is `forges` in the machine config (`$COLAB_HOME/config.json`, never a tracked file):
|
|
101
|
+
* { "forges": { "<host>": { "engine": "forgejo", "api": "https://<host>/api/v1", "tokenEnv": "FORGEJO_TOKEN" } } }
|
|
102
|
+
* `api` defaults to `https://<host>/api/v1`, `tokenEnv` to FORGEJO_TOKEN. A host the map does not
|
|
103
|
+
* name, a URL that does not parse, and a missing config all read `github` — today's behaviour.
|
|
104
|
+
* An entry naming an engine this CLI does not know is `invalid` (and reads github), never a guess.
|
|
105
|
+
*
|
|
106
|
+
* Returns `{ engine, host, owner, repo, api, tokenEnv, source: 'default'|'map'|'invalid', why }`.
|
|
107
|
+
*/
|
|
108
|
+
function engineFromConfig(url, cfg) {
|
|
109
|
+
const p = parseRemoteUrl(url);
|
|
110
|
+
const base = { engine: 'github', host: p ? p.host : null, owner: p ? p.owner : null, repo: p ? p.repo : null,
|
|
111
|
+
api: null, tokenEnv: null, source: 'default', why: '' };
|
|
112
|
+
if (!p) return base;
|
|
113
|
+
const forges = cfg && typeof cfg === 'object' && cfg.forges && typeof cfg.forges === 'object' ? cfg.forges : null;
|
|
114
|
+
const ent = forges ? (forges[p.host] ?? Object.entries(forges).find(([k]) => k.toLowerCase() === p.host)?.[1]) : undefined;
|
|
115
|
+
if (ent === undefined || ent === null) return base;
|
|
116
|
+
const engine = typeof ent === 'string' ? ent : (ent && typeof ent === 'object' ? ent.engine : null);
|
|
117
|
+
if (!ENGINES.includes(engine)) {
|
|
118
|
+
return { ...base, source: 'invalid', why: `forges["${p.host}"] in the machine config names engine ${JSON.stringify(engine)} (known: ${ENGINES.join(', ')}) — read as github` };
|
|
119
|
+
}
|
|
120
|
+
if (engine === 'github') return { ...base, source: 'map' };
|
|
121
|
+
const o = typeof ent === 'object' ? ent : {};
|
|
122
|
+
const api = String(o.api || `https://${p.host}/api/v1`).replace(/\/+$/, '');
|
|
123
|
+
const tokenEnv = typeof o.tokenEnv === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(o.tokenEnv) ? o.tokenEnv : DEFAULT_TOKEN_ENV;
|
|
124
|
+
return { ...base, engine, api, tokenEnv, source: 'map' };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The machine config, parsed; `{}` when absent or unreadable (the engine then reads github). */
|
|
128
|
+
function readMachineConfig(configFile) {
|
|
129
|
+
try { return JSON.parse(require('fs').readFileSync(configFile || require('./state').CONFIG_FILE, 'utf8')) || {}; } catch (_) { return {}; }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const _engineCache = new Map();
|
|
133
|
+
function _resetEngineCache() { _engineCache.clear(); }
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The engine for one repo: its resolved remote's CONFIGURED url (not `git remote get-url`, which
|
|
137
|
+
* expands `url.<x>.insteadOf` — that rewrites how git reaches the remote, never which forge it is;
|
|
138
|
+
* the same read tracker-github's pinnedRepo makes) looked up in the machine config's `forges`.
|
|
139
|
+
* Never throws. Cached per resolved repo path for the life of the process.
|
|
140
|
+
*/
|
|
141
|
+
function engineFor(repoAbs, { configFile = null } = {}) {
|
|
142
|
+
const key = require('path').resolve(repoAbs || process.cwd());
|
|
143
|
+
if (!configFile && _engineCache.has(key)) return _engineCache.get(key);
|
|
144
|
+
let url = null;
|
|
145
|
+
try {
|
|
146
|
+
const g = require('./git');
|
|
147
|
+
const { name } = g.remoteInfo(key);
|
|
148
|
+
const u = name ? g.git(['config', '--get', `remote.${name}.url`], key) : null;
|
|
149
|
+
url = u && u.ok ? u.stdout : null;
|
|
150
|
+
} catch (_) { url = null; }
|
|
151
|
+
const eng = engineFromConfig(url, readMachineConfig(configFile));
|
|
152
|
+
if (!configFile) _engineCache.set(key, eng);
|
|
153
|
+
return eng;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const CI_KINDS = { forgejo: () => require('./ci-forgejo') };
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The CI reader for one repo, or null when its engine is GitHub — the caller keeps its existing,
|
|
160
|
+
* gh-based reads there, which `ciVerdict` on the GitHub tracker wraps one-for-one. Non-null only
|
|
161
|
+
* for an engine the map names (#678).
|
|
162
|
+
*/
|
|
163
|
+
function ciFor(repoAbs, opts = {}) {
|
|
164
|
+
const eng = engineFor(repoAbs, opts);
|
|
165
|
+
const load = CI_KINDS[eng.engine];
|
|
166
|
+
if (!load) return null;
|
|
167
|
+
const impl = load().create(repoAbs, eng);
|
|
168
|
+
if (!_checked.has(`ci:${eng.engine}`)) { assertImplements(impl, `CI engine "${eng.engine}"`, CI_METHODS); _checked.add(`ci:${eng.engine}`); }
|
|
169
|
+
return impl;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
module.exports = {
|
|
173
|
+
METHODS, CI_METHODS, ENGINES, assertImplements, forRepo,
|
|
174
|
+
parseRemoteUrl, engineFromConfig, engineFor, ciFor, _resetEngineCache,
|
|
175
|
+
};
|