Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

diffFileOrder.ts

358 lines11.8 KB

1interface OrderableDiffFile {
2 readonly additionLines: ReadonlyArray<string>;
3 readonly deletionLines: ReadonlyArray<string>;
4}
5​
6type DiffFileTier = "source" | "test" | "generated";
7​
8const GENERATED_FILE_NAMES = new Set([
9 "pnpm-lock.yaml",
10 "yarn.lock",
11 "package-lock.json",
12 "npm-shrinkwrap.json",
13 "bun.lock",
14 "bun.lockb",
15 "deno.lock",
16 "Cargo.lock",
17 "go.sum",
18 "gradle.lockfile",
19 "composer.lock",
20 "Gemfile.lock",
21 "packages.lock.json",
22 "Pipfile.lock",
23 "poetry.lock",
24 "uv.lock",
25 "flake.lock",
26 "Podfile.lock",
27 "pubspec.lock",
28 "mix.lock",
29]);
30const GENERATED_DIRECTORIES = new Set([
31 "__snapshots__",
32 "__generated__",
33 "dist",
34 "build",
35 "vendor",
36]);
37const TEST_DIRECTORIES = new Set(["__tests__", "tests", "test"]);
38// `.mts` also ends in `.ts`, so longer extensions come first.
39const MODULE_EXTENSIONS = [".mts", ".cts", ".mjs", ".cjs", ".tsx", ".jsx", ".ts", ".js"];
40​
41function diffFileTier(path: string): DiffFileTier {
42 const segments = path.split("/");
43 const name = segments.at(-1) ?? "";
44 if (
45 GENERATED_FILE_NAMES.has(name) ||
46 name.endsWith(".snap") ||
47 name.endsWith(".min.js") ||
48 name.endsWith(".min.css") ||
49 /\.generated\./.test(name) ||
50 segments.slice(0, -1).some((segment) => GENERATED_DIRECTORIES.has(segment))
51 ) {
52 return "generated";
53 }
54 if (
55 /\.(?:test|spec)\./.test(name) ||
56 segments.slice(0, -1).some((segment) => TEST_DIRECTORIES.has(segment))
57 ) {
58 return "test";
59 }
60 return "source";
62​
63function stripExtension(path: string): string {
64 const dot = path.lastIndexOf(".");
65 const slash = path.lastIndexOf("/");
66 return dot > slash ? path.slice(0, dot) : path;
68​
69function baseName(path: string): string {
70 return stripExtension(path.split("/").at(-1) ?? "");
72​
73// Import specifiers omit module extensions but keep dotted names such as `b.logic`, so module-map
74// keys strip only the extensions an import could omit.
75function stripModuleExtension(path: string): string {
76 const extension = MODULE_EXTENSIONS.find((candidate) => path.endsWith(candidate));
77 return extension === undefined ? path : path.slice(0, -extension.length);
79​
80function moduleName(path: string): string {
81 return stripModuleExtension(path.split("/").at(-1) ?? "");
83​
84function resolveRelative(fromPath: string, specifier: string): string | null {
85 const segments = fromPath.split("/").slice(0, -1);
86 for (const part of specifier.split("/")) {
87 if (part === "." || part === "") continue;
88 if (part === "..") {
89 if (segments.length === 0) return null;
90 segments.pop();
91 } else {
92 segments.push(part);
93 }
94 }
95 return segments.join("/");
97​
98const IMPORT_SPECIFIER = /(?:\bfrom|\bimport|\brequire\s*\()\s*\(?\s*["']([^"']+)["']/g;
99​
100function importedPaths(
101 path: string,
102 lines: ReadonlyArray<string>,
103 exactPaths: ReadonlySet<string>,
104 byModulePath: ReadonlyMap<string, string>,
105 byModuleName: ReadonlyMap<string, string>,
106): ReadonlySet<string> {
107 const imported = new Set<string>();
108 for (const line of lines) {
109 for (const match of line.matchAll(IMPORT_SPECIFIER)) {
110 // Bundler queries such as `?worker` or `?url` name the same file.
111 const specifier = (match[1] ?? "").replace(/\?.*$/, "");
112 const isRelative = specifier.startsWith(".");
113 const resolvedPath = isRelative ? resolveRelative(path, specifier) : specifier;
114 if (specifier === "" || resolvedPath === null) continue;
115 const resolved = stripModuleExtension(resolvedPath);
116 // `.` or `..` that lands on the repository root can only mean its index file.
117 const target =
118 resolvedPath === ""
119 ? byModulePath.get("index")
120 : ((exactPaths.has(resolvedPath) ? resolvedPath : undefined) ??
121 byModulePath.get(resolved) ??
122 byModulePath.get(`${resolved}/index`) ??
123 (isRelative ? undefined : byModuleName.get(moduleName(resolved))));
124 if (target !== undefined && target !== path) imported.add(target);
125 }
126 }
127 return imported;
129​
130function pushMinHeap(heap: Array<number>, value: number): void {
131 heap.push(value);
132 let child = heap.length - 1;
133 while (child > 0) {
134 const parent = (child - 1) >> 1;
135 const parentValue = heap[parent]!;
136 if (parentValue <= value) break;
137 heap[child] = parentValue;
138 child = parent;
139 }
140 heap[child] = value;
142​
143function popMinHeap(heap: Array<number>): number {
144 const root = heap[0]!;
145 const last = heap.pop()!;
146 if (heap.length === 0) return root;
147 let parent = 0;
148 const half = heap.length >> 1;
149 while (parent < half) {
150 let child = (parent << 1) + 1;
151 let childValue = heap[child]!;
152 const right = child + 1;
153 if (right < heap.length && heap[right]! < childValue) {
154 child = right;
155 childValue = heap[right]!;
156 }
157 if (last <= childValue) break;
158 heap[parent] = childValue;
159 parent = child;
160 }
161 heap[parent] = last;
162 return root;
164​
165function orderByImports(
166 paths: ReadonlyArray<string>,
167 imports: ReadonlyMap<string, ReadonlySet<string>>,
168): Array<string> {
169 const sorted = [...paths].sort((left, right) => left.localeCompare(right));
170 const count = sorted.length;
171 const indexByPath = new Map<string, number>();
172 for (let index = 0; index < count; index++) {
173 indexByPath.set(sorted[index]!, index);
174 }
175​
176 const inDegree = new Int32Array(count);
177 const emitted = new Uint8Array(count);
178 const dependents: Array<Array<number>> = Array.from({ length: count }, () => []);
179 for (let index = 0; index < count; index++) {
180 const dependencies = imports.get(sorted[index]!);
181 if (dependencies === undefined) continue;
182 for (const dependency of dependencies) {
183 const dependencyIndex = indexByPath.get(dependency);
184 if (dependencyIndex === undefined) continue;
185 inDegree[index] = inDegree[index]! + 1;
186 dependents[dependencyIndex]!.push(index);
187 }
188 }
189​
190 const ready: Array<number> = [];
191 for (let index = 0; index < count; index++) {
192 if (inDegree[index] === 0) ready.push(index);
193 }
194​
195 const ordered: Array<string> = [];
196 let nextRemaining = 0;
197 for (let step = 0; step < count; step++) {
198 let nextIndex: number;
199 if (ready.length > 0) {
200 nextIndex = popMinHeap(ready);
201 } else {
202 while (emitted[nextRemaining] === 1) nextRemaining++;
203 nextIndex = nextRemaining++;
204 }
205 emitted[nextIndex] = 1;
206 ordered.push(sorted[nextIndex]!);
207​
208 for (const dependent of dependents[nextIndex]!) {
209 if (emitted[dependent] === 1) continue;
210 const remainingDependencies = inDegree[dependent]! - 1;
211 inDegree[dependent] = remainingDependencies;
212 if (remainingDependencies === 0) pushMinHeap(ready, dependent);
213 }
214 }
215 return ordered;
217​
218// `a.logic.test.ts` covers `a.logic.ts` while `a.browser.test.ts` covers `a.ts`, so the longest
219// dotted prefix that names a source file wins, and a source beside the test wins over a same-named
220// one in another folder.
221function testedSourcePosition(
222 path: string,
223 sourcePositions: ReadonlyMap<string, number>,
224 pathPositions: ReadonlyMap<string, number>,
225): number {
226 const directory = path.slice(0, path.lastIndexOf("/") + 1);
227 const name = (path.split("/").at(-1) ?? "").replace(/\.(?:test|spec)\..*$/, "");
228 return (
229 longestPrefixPosition(name, (prefix) => pathPositions.get(directory + prefix)) ??
230 longestPrefixPosition(name, (prefix) => sourcePositions.get(prefix)) ??
231 Number.MAX_SAFE_INTEGER
232 );
234​
235function longestPrefixPosition(
236 name: string,
237 positionOf: (prefix: string) => number | undefined,
238): number | undefined {
239 for (let prefix = name; ;) {
240 const position = positionOf(prefix);
241 if (position !== undefined) return position;
242 const dot = prefix.lastIndexOf(".");
243 if (dot <= 0) return undefined;
244 prefix = prefix.slice(0, dot);
245 }
247​
248function orderByImportsAndTier<F extends OrderableDiffFile>(
249 files: ReadonlyArray<F>,
250 pathOf: (file: F) => string,
251): ReadonlyArray<F> {
252 // A type change (file to symlink) is a delete and an add under one path; keep both.
253 const byPath = new Map<string, F[]>();
254 for (const file of files) {
255 const path = pathOf(file);
256 byPath.set(path, [...(byPath.get(path) ?? []), file]);
257 }
258 const tiers = new Map<string, DiffFileTier>();
259 for (const path of byPath.keys()) tiers.set(path, diffFileTier(path));
260​
261 const sourcePaths = [...byPath.keys()].filter((path) => tiers.get(path) === "source");
262 const exactPaths = new Set(sourcePaths);
263 const byModulePath = new Map<string, string>();
264 const ambiguousModuleNames = new Set<string>();
265 const byModuleName = new Map<string, string>();
266 for (const path of sourcePaths) {
267 byModulePath.set(stripModuleExtension(path), path);
268 const name = moduleName(path);
269 if (byModuleName.has(name)) ambiguousModuleNames.add(name);
270 byModuleName.set(name, path);
271 }
272 for (const name of ambiguousModuleNames) byModuleName.delete(name);
273​
274 const imports = new Map<string, ReadonlySet<string>>();
275 for (const path of sourcePaths) {
276 const lines = byPath
277 .get(path)!
278 .flatMap((file) => [...file.additionLines, ...file.deletionLines]);
279 imports.set(path, importedPaths(path, lines, exactPaths, byModulePath, byModuleName));
280 }
281 const orderedSource = orderByImports(sourcePaths, imports);
282​
283 const sourcePositions = new Map<string, number>();
284 const pathPositions = new Map<string, number>();
285 orderedSource.forEach((path, index) => {
286 const base = baseName(path);
287 if (!sourcePositions.has(base)) sourcePositions.set(base, index);
288 pathPositions.set(stripExtension(path), index);
289 });
290 const orderedTests = [...byPath.keys()]
291 .filter((path) => tiers.get(path) === "test")
292 .sort((left, right) => {
293 return (
294 testedSourcePosition(left, sourcePositions, pathPositions) -
295 testedSourcePosition(right, sourcePositions, pathPositions) || left.localeCompare(right)
296 );
297 });
298​
299 const orderedGenerated = [...byPath.keys()]
300 .filter((path) => tiers.get(path) === "generated")
301 .sort((left, right) => left.localeCompare(right));
302​
303 return [...orderedSource, ...orderedTests, ...orderedGenerated].flatMap((path) =>
304 byPath.get(path)!,
305 );
307​
308/** Where each file, and each directory (with a trailing slash), first appears in `paths`. */
309export function diffFileTreePositions(paths: ReadonlyArray<string>): ReadonlyMap<string, number> {
310 const positions = new Map<string, number>();
311 paths.forEach((path, index) => {
312 positions.set(path, index);
313 let directory = "";
314 for (const segment of path.split("/").slice(0, -1)) {
315 directory += `${segment}/`;
316 if (!positions.has(directory)) positions.set(directory, index);
317 }
318 });
319 return positions;
321​
322function orderLikeTree<F>(files: ReadonlyArray<F>, pathOf: (file: F) => string): ReadonlyArray<F> {
323 const paths = files.map(pathOf);
324 const positions = diffFileTreePositions(paths);
325 const keys = paths.map((path) => {
326 const key: number[] = [];
327 let directory = "";
328 for (const segment of path.split("/").slice(0, -1)) {
329 directory += `${segment}/`;
330 key.push(positions.get(directory)!);
331 }
332 key.push(positions.get(path)!);
333 return key;
334 });
335 return files
336 .map((file, index) => ({ file, key: keys[index]! }))
337 .sort((left, right) => {
338 const length = Math.min(left.key.length, right.key.length);
339 for (let index = 0; index < length; index++) {
340 const difference = left.key[index]! - right.key[index]!;
341 if (difference !== 0) return difference;
342 }
343 return left.key.length - right.key.length;
344 })
345 .map(({ file }) => file);
347​
348/**
349 * Review order shared by every client: dependencies before dependents, tests after their source,
350 * generated files last, then regrouped so each directory stays contiguous and a file tree built
351 * from `diffFileTreePositions` lists files in the same order.
352 */
353export function orderDiffFilesForReview<F extends OrderableDiffFile>(
354 files: ReadonlyArray<F>,
355 pathOf: (file: F) => string,
356): ReadonlyArray<F> {
357 return orderLikeTree(orderByImportsAndTier(files, pathOf), pathOf);