|
2 | 2 | // strands installs that return to upstream. Usage: fork-schema-check.cjs <base> <head>. |
3 | 3 | // Refused: migrations, schema setup and what they import; shipped source files holding a schema |
4 | 4 | // statement; a PR copy of this check or of .gitattributes that differs from the base's copy; and a |
5 | | -// branch built on an old (since rebased) base. Files are read as git blobs. |
| 5 | +// branch holding commits already on the base (built on an old, since rebased base, or copying its |
| 6 | +// commits). Files are read as git blobs. |
6 | 7 |
|
7 | 8 | const { execFileSync } = require("node:child_process"); |
8 | 9 | const path = require("node:path"); |
@@ -57,7 +58,9 @@ const isShippedSource = (file) => SHIPPED_SOURCE.test(file) && !isTest(file); |
57 | 58 | /** |
58 | 59 | * Files the schema roots import, transitively: relative and package subpath imports, and for a |
59 | 60 | * package root (`@t3tools/contracts`) the files that declare the names imported from it. The |
60 | | - * root's barrel itself is not added, so the rest of the package stays free to change. |
| 61 | + * barrels on the way to a declaring file are guarded too (a barrel edit could re-point a name), |
| 62 | + * but their other re-exports are not followed, so the rest of the package stays free to change. |
| 63 | + * A name that cannot be traced guards the whole barrel and everything it re-exports. |
61 | 64 | * @param {{ files: string[]; has(file: string): boolean; read(file: string): string }} tree |
62 | 65 | * @returns {Set<string>} |
63 | 66 | */ |
@@ -67,14 +70,18 @@ function schemaClosure(tree) { |
67 | 70 | (file) => SCHEMA_ROOTS.some((pattern) => pattern.test(file)) && !isTest(file), |
68 | 71 | ); |
69 | 72 | const closure = new Set(queue); |
| 73 | + const walked = new Set(queue); |
70 | 74 | while (queue.length > 0) { |
71 | 75 | const file = queue.pop(); |
72 | 76 | const text = tree.read(file); |
73 | 77 | const names = importedNames(text); |
74 | 78 | for (const match of text.matchAll(IMPORT_SPECIFIER)) { |
75 | | - for (const target of resolveImport(tree, packages, file, match[1], names.get(match[1]))) { |
76 | | - if (!isTest(target) && !closure.has(target)) { |
| 79 | + const reached = resolveImport(tree, packages, file, match[1], names.get(match[1])); |
| 80 | + for (const target of reached.barrels) if (!isTest(target)) closure.add(target); |
| 81 | + for (const target of reached.files) { |
| 82 | + if (!isTest(target) && !walked.has(target)) { |
77 | 83 | closure.add(target); |
| 84 | + walked.add(target); |
78 | 85 | queue.push(target); |
79 | 86 | } |
80 | 87 | } |
@@ -122,15 +129,21 @@ function importedNames(text) { |
122 | 129 | return names; |
123 | 130 | } |
124 | 131 |
|
125 | | -/** The files an import reaches: one file, or for a package root the files declaring `names`. */ |
| 132 | +/** |
| 133 | + * The files an import reaches: one file, or for a package root the files declaring `names` |
| 134 | + * (`files`, whose own imports matter) and the barrels re-exporting them (`barrels`, guarded only). |
| 135 | + * @returns {{ files: string[]; barrels: string[] }} |
| 136 | + */ |
126 | 137 | function resolveImport(tree, packages, from, specifier, names) { |
| 138 | + const none = { files: [], barrels: [] }; |
| 139 | + const whole = (file) => ({ files: [file], barrels: [] }); |
127 | 140 | if (specifier.startsWith(".")) { |
128 | 141 | const target = resolveFile(tree, path.posix.join(path.posix.dirname(from), specifier)); |
129 | | - return target ? [target] : []; |
| 142 | + return target ? whole(target) : none; |
130 | 143 | } |
131 | 144 | const parts = specifier.match(/^(@[^/]+\/[^/]+)(?:\/(.+))?$/); |
132 | 145 | const pkg = parts && packages.get(parts[1]); |
133 | | - if (!pkg || !pkg.exports) return []; |
| 146 | + if (!pkg || !pkg.exports) return none; |
134 | 147 | const exports = |
135 | 148 | typeof pkg.exports === "string" || "import" in pkg.exports || "default" in pkg.exports |
136 | 149 | ? { ".": pkg.exports } |
@@ -140,36 +153,42 @@ function resolveImport(tree, packages, from, specifier, names) { |
140 | 153 | typeof entry === "string" ? entry : entry && (entry.import ?? entry.default ?? entry.types); |
141 | 154 | const file = |
142 | 155 | typeof target === "string" ? resolveFile(tree, path.posix.join(pkg.dir, target)) : undefined; |
143 | | - if (!file) return []; |
144 | | - if (parts[2] || !names || names.has("*") || names.has("default")) return [file]; |
| 156 | + if (!file) return none; |
| 157 | + if (parts[2] || !names || names.has("*") || names.has("default")) return whole(file); |
145 | 158 | const found = new Set(); |
146 | | - for (const name of names) declaringFiles(tree, packages, file, name, found, new Set()); |
147 | | - return [...found]; |
| 159 | + const barrels = new Set(); |
| 160 | + for (const name of names) { |
| 161 | + // A name no file is seen to declare fails closed: the barrel is walked whole. |
| 162 | + if (!declaringFiles(tree, packages, file, name, found, barrels, new Map())) return whole(file); |
| 163 | + } |
| 164 | + return { files: [...found], barrels: [...barrels] }; |
148 | 165 | } |
149 | 166 |
|
150 | | -/** Follows `export * from` and `export { name } from` until a file declares `name`. */ |
151 | | -function declaringFiles(tree, packages, file, name, found, seen) { |
152 | | - if (seen.has(`${file}\0${name}`)) return; |
153 | | - seen.add(`${file}\0${name}`); |
| 167 | +/** |
| 168 | + * Follows `export * from` and `export { name } from` until a file declares `name`. Adds declaring |
| 169 | + * files to `found` and the re-exporting files on the way to `barrels`. |
| 170 | + * @returns {boolean} whether `name` was traced to a declaring file from `file` |
| 171 | + */ |
| 172 | +function declaringFiles(tree, packages, file, name, found, barrels, seen) { |
| 173 | + const key = `${file}\0${name}`; |
| 174 | + if (seen.has(key)) return seen.get(key); |
| 175 | + seen.set(key, false); |
154 | 176 | const text = tree.read(file); |
155 | | - const word = name.replace(/\$/g, "\\$"); |
156 | | - const declares = new RegExp( |
157 | | - String.raw`\bexport\s+(?:declare\s+)?(?:abstract\s+)?(?:const|let|var|function\*?|class|type|interface|enum|namespace)\s+${word}(?![\w$])`, |
158 | | - ); |
159 | | - const local = [...text.matchAll(/\bexport\s+(?:type\s+)?\{([^}]*)\}(?!\s*from)/g)].some( |
160 | | - (match) => match[1].split(",").some((part) => part.trim().split(/\s+as\s+/).pop() === name), |
161 | | - ); |
162 | | - if (declares.test(text) || local) { |
| 177 | + if (declaresName(text, name)) { |
163 | 178 | found.add(file); |
164 | | - return; |
| 179 | + seen.set(key, true); |
| 180 | + return true; |
165 | 181 | } |
| 182 | + let traced = false; |
166 | 183 | for (const match of text.matchAll( |
167 | 184 | /\bexport\s+(?:type\s+)?(\*(?:\s+as\s+([\w$]+))?|\{[^}]*\})\s*from\s*["']([^"'\n]+)["']/g, |
168 | 185 | )) { |
169 | 186 | const [, clause, namespace, specifier] = match; |
170 | | - const targets = resolveImport(tree, packages, file, specifier, new Set(["*"])); |
| 187 | + const targets = resolveImport(tree, packages, file, specifier, new Set(["*"])).files; |
171 | 188 | if (clause.startsWith("*") && !namespace) { |
172 | | - for (const target of targets) declaringFiles(tree, packages, target, name, found, seen); |
| 189 | + for (const target of targets) { |
| 190 | + if (declaringFiles(tree, packages, target, name, found, barrels, seen)) traced = true; |
| 191 | + } |
173 | 192 | continue; |
174 | 193 | } |
175 | 194 | const exported = namespace |
@@ -183,9 +202,36 @@ function declaringFiles(tree, packages, file, name, found, seen) { |
183 | 202 | if (!exported) continue; |
184 | 203 | for (const target of targets) { |
185 | 204 | if (exported === "*") found.add(target); |
186 | | - else declaringFiles(tree, packages, target, exported, found, seen); |
| 205 | + if (exported === "*" || declaringFiles(tree, packages, target, exported, found, barrels, seen)) { |
| 206 | + traced = true; |
| 207 | + } |
187 | 208 | } |
188 | 209 | } |
| 210 | + if (traced) barrels.add(file); |
| 211 | + seen.set(key, traced); |
| 212 | + return traced; |
| 213 | +} |
| 214 | + |
| 215 | +/** |
| 216 | + * Whether `text` declares and exports `name` itself: a declaration (`export async function`, |
| 217 | + * `export const { name } = ...` and the like), a local `export { [type] x as name }`, or for |
| 218 | + * `default` an `export default`. |
| 219 | + */ |
| 220 | +function declaresName(text, name) { |
| 221 | + const word = name.replace(/\$/g, "\\$"); |
| 222 | + const bound = String.raw`(?<![\w$])${word}(?![\w$])`; |
| 223 | + const declarations = [ |
| 224 | + String.raw`\bexport\s+(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:const|let|var|function\s*\*?|class|type|interface|enum|namespace|module)\s*${bound}`, |
| 225 | + // Destructuring: `export const { a, b: name } = o` or `export const [name] = list`. |
| 226 | + String.raw`\bexport\s+(?:const|let|var)\s*[{[][^=;]*?${bound}[^=;]*?[}\]]\s*(?::[^=;]*)?=`, |
| 227 | + ]; |
| 228 | + if (name === "default") declarations.push(String.raw`\bexport\s+default\b`); |
| 229 | + if (declarations.some((pattern) => new RegExp(pattern).test(text))) return true; |
| 230 | + return [...text.matchAll(/\bexport\s+(?:type\s+)?\{([^}]*)\}(?!\s*from)/g)].some((match) => |
| 231 | + match[1] |
| 232 | + .split(",") |
| 233 | + .some((part) => part.trim().replace(/^type\s+/, "").split(/\s+as\s+/).pop().trim() === name), |
| 234 | + ); |
189 | 235 | } |
190 | 236 |
|
191 | 237 | function resolveFile(tree, file) { |
@@ -195,44 +241,46 @@ function resolveFile(tree, file) { |
195 | 241 | } |
196 | 242 |
|
197 | 243 | /** |
198 | | - * @param {ReadonlyArray<{ path: string; before?: string; after?: string; sameAsBase?: boolean }>} changes |
| 244 | + * @param {ReadonlyArray<{ path: string; before?: string; after?: string; sameAsBase?: boolean; fromOldMain?: boolean }>} changes |
199 | 245 | * one entry per path the branch changes since the merge-base; `before`/`after` are the file |
200 | | - * texts (undefined when absent); `sameAsBase` says the branch's copy equals the base's copy |
| 246 | + * texts (undefined when absent); `sameAsBase` says the branch's copy equals the base's copy; |
| 247 | + * `fromOldMain` says the branch's copy is the one a commit already on main left there |
201 | 248 | * @param {{ closure: ReadonlySet<string>; baseHasCheck: boolean; staleCommits?: number }} context |
202 | 249 | * `staleCommits`: the branch's commits that the base already holds as rebased copies |
203 | 250 | * @returns {string[]} one reason per refused file |
204 | 251 | */ |
205 | 252 | function findSchemaChanges(changes, { closure, baseHasCheck, staleCommits = 0 }) { |
206 | 253 | const reasons = []; |
207 | | - const rebase = |
208 | | - "this branch is based on an old main that has since been rebased; rebase it onto main"; |
209 | 254 | if (staleCommits > 0) { |
210 | 255 | reasons.push( |
211 | | - `${staleCommits} commit(s) of this branch are already on main as rebased copies, so ${rebase}.`, |
| 256 | + `${staleCommits} commit(s) of this branch are already on main (it is based on an old main, ` + |
| 257 | + "or it copies main's commits), so rebase it onto main.", |
212 | 258 | ); |
213 | 259 | } |
| 260 | + const also = staleCommits > 0 ? " (also rebase onto main)" : ""; |
214 | 261 | for (const change of changes) { |
215 | 262 | const file = change.path; |
216 | 263 | const guarded = CHECK_FILES.includes(file) || GITATTRIBUTES.test(file); |
217 | 264 | // The branch carries main's copy (e.g. it branched before main was rebased): nothing to judge. |
218 | 265 | if (guarded && change.sameAsBase) continue; |
219 | | - if (guarded && staleCommits > 0) { |
220 | | - reasons.push(`${file}: differs from main's copy because ${rebase}.`); |
| 266 | + // Main's own older copy, carried by commits already on main: only the rebase is needed. |
| 267 | + if (guarded && staleCommits > 0 && change.fromOldMain) { |
| 268 | + reasons.push(`${file}: differs from main's copy, because this branch needs a rebase onto main.`); |
221 | 269 | continue; |
222 | 270 | } |
223 | 271 | if (CHECK_FILES.includes(file)) { |
224 | 272 | if (baseHasCheck) { |
225 | 273 | reasons.push( |
226 | 274 | `${file}: changes the schema check itself. Only the owner may do that: the check stays ` + |
227 | | - "red, and the owner merges past it.", |
| 275 | + `red, and the owner merges past it${also}.`, |
228 | 276 | ); |
229 | 277 | } |
230 | 278 | continue; |
231 | 279 | } |
232 | 280 | if (GITATTRIBUTES.test(file)) { |
233 | 281 | reasons.push( |
234 | 282 | `${file}: changes how git treats files, which can hide changes from review. Only the ` + |
235 | | - "owner may do that.", |
| 283 | + `owner may do that${also}.`, |
236 | 284 | ); |
237 | 285 | continue; |
238 | 286 | } |
@@ -321,16 +369,20 @@ function blobAt(rev, file) { |
321 | 369 | } |
322 | 370 |
|
323 | 371 | /** |
324 | | - * The branch's commits (merge-base..head) that the base already holds as rebased copies, matched |
325 | | - * by author, author time and subject: a rebase keeps all three. Needs no file contents. |
| 372 | + * The branch's commits (merge-base..head) that the base already holds as copies (rebased or |
| 373 | + * cherry-picked), matched by author, author time and subject: both keep all three. Needs no file |
| 374 | + * contents. Returns the branch-side commit ids. |
326 | 375 | */ |
327 | | -function staleCommitCount(mergeBase, base, head) { |
| 376 | +function staleCommits(mergeBase, base, head) { |
328 | 377 | const ids = (range) => |
329 | | - git(["log", "--no-merges", "--format=%an%x00%ae%x00%at%x00%s", range]) |
| 378 | + git(["log", "--no-merges", "--format=%H%x00%an%x00%ae%x00%at%x00%s", range]) |
330 | 379 | .split("\n") |
331 | | - .filter(Boolean); |
332 | | - const onBase = new Set(ids(`${mergeBase}..${base}`)); |
333 | | - return ids(`${mergeBase}..${head}`).filter((id) => onBase.has(id)).length; |
| 380 | + .filter(Boolean) |
| 381 | + .map((line) => ({ sha: line.slice(0, line.indexOf("\0")), id: line.slice(line.indexOf("\0")) })); |
| 382 | + const onBase = new Set(ids(`${mergeBase}..${base}`).map((commit) => commit.id)); |
| 383 | + return ids(`${mergeBase}..${head}`) |
| 384 | + .filter((commit) => onBase.has(commit.id)) |
| 385 | + .map((commit) => commit.sha); |
334 | 386 | } |
335 | 387 |
|
336 | 388 | function main(argv) { |
@@ -346,11 +398,16 @@ function main(argv) { |
346 | 398 | // Only shipped source is searched for statements, so only its texts are read. |
347 | 399 | const text = (entry, sha) => (sha && isShippedSource(entry.path) ? readBlob(sha) : undefined); |
348 | 400 | const guarded = (file) => CHECK_FILES.includes(file) || GITATTRIBUTES.test(file); |
| 401 | + const stale = staleCommits(mergeBase, base, head); |
| 402 | + // A guarded file's copy that one of those commits left: main's older copy, not a branch edit. |
| 403 | + const fromOldMain = (entry) => |
| 404 | + stale.some((sha) => blobAt(sha, entry.path) === entry.newBlob); |
349 | 405 | const changes = entries.map((entry) => ({ |
350 | 406 | path: entry.path, |
351 | 407 | before: text(entry, entry.oldBlob), |
352 | 408 | after: text(entry, entry.newBlob), |
353 | 409 | sameAsBase: guarded(entry.path) ? blobAt(base, entry.path) === entry.newBlob : undefined, |
| 410 | + fromOldMain: guarded(entry.path) && stale.length > 0 ? fromOldMain(entry) : undefined, |
354 | 411 | })); |
355 | 412 | const closure = new Set([ |
356 | 413 | ...schemaClosure(readTree(mergeBase)), |
@@ -359,7 +416,7 @@ function main(argv) { |
359 | 416 | const reasons = findSchemaChanges(changes, { |
360 | 417 | closure, |
361 | 418 | baseHasCheck: treeHas(base, CHECK_SCRIPT), |
362 | | - staleCommits: staleCommitCount(mergeBase, base, head), |
| 419 | + staleCommits: stale.length, |
363 | 420 | }); |
364 | 421 | if (reasons.length === 0) { |
365 | 422 | console.log(`No database schema changes (${changes.length} changed files checked).`); |
|