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

diffFileOrder.ts

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