Open History to see the last commit
1import type { FileDiffMetadata } from "@pierre/diffs";
2
3import { resolveFileDiffPath } from "~/lib/diffRendering";
4
5export type DiffFileTier = "source" | "test" | "generated";
6
7const GENERATED_FILE_NAMES = new Set([
8 "pnpm-lock.yaml",
9 "yarn.lock",
10 "package-lock.json",
11 "bun.lockb",
12 "Cargo.lock",
13 "go.sum",
14 "composer.lock",
15 "Gemfile.lock",
16]);
17const GENERATED_DIRECTORIES = new Set([
18 "__snapshots__",
19 "__generated__",
20 "dist",
21 "build",
22 "vendor",
23]);
24const TEST_DIRECTORIES = new Set(["__tests__", "tests", "test"]);
25// `.mts` also ends in `.ts`, so longer extensions come first.
26const MODULE_EXTENSIONS = [".mts", ".cts", ".mjs", ".cjs", ".tsx", ".jsx", ".ts", ".js"];
27
28function diffFileTier(path: string): DiffFileTier {
29 const segments = path.split("/");
30 const name = segments.at(-1) ?? "";
31 if (
32 GENERATED_FILE_NAMES.has(name) ||
33 name.endsWith(".snap") ||
34 name.endsWith(".min.js") ||
35 name.endsWith(".min.css") ||
36 /\.generated\./.test(name) ||
37 segments.slice(0, -1).some((segment) => GENERATED_DIRECTORIES.has(segment))
38 ) {
39 return "generated";
40 }
41 if (
42 /\.(?:test|spec)\./.test(name) ||
43 segments.slice(0, -1).some((segment) => TEST_DIRECTORIES.has(segment))
44 ) {
45 return "test";
46 }
47 return "source";
48}
49
50function stripExtension(path: string): string {
51 const dot = path.lastIndexOf(".");
52 const slash = path.lastIndexOf("/");
53 return dot > slash ? path.slice(0, dot) : path;
54}
55
56function baseName(path: string): string {
57 return stripExtension(path.split("/").at(-1) ?? "");
58}
59
60// Import specifiers omit module extensions but keep dotted names such as `b.logic`, so module-map
61// keys strip only the extensions an import could omit.
62function stripModuleExtension(path: string): string {
63 const extension = MODULE_EXTENSIONS.find((candidate) => path.endsWith(candidate));
64 return extension === undefined ? path : path.slice(0, -extension.length);
65}
66
67function moduleName(path: string): string {
68 return stripModuleExtension(path.split("/").at(-1) ?? "");
69}
70
71function resolveRelative(fromPath: string, specifier: string): string {
72 const segments = fromPath.split("/").slice(0, -1);
73 for (const part of specifier.split("/")) {
74 if (part === "." || part === "") continue;
75 if (part === "..") segments.pop();
76 else segments.push(part);
77 }
78 return segments.join("/");
79}
80
81const IMPORT_SPECIFIER = /(?:\bfrom|\bimport|\brequire\s*\()\s*\(?\s*["']([^"']+)["']/g;
82
83function importedPaths(
84 path: string,
85 lines: ReadonlyArray<string>,
86 byModulePath: ReadonlyMap<string, string>,
87 byModuleName: ReadonlyMap<string, string>,
88): ReadonlySet<string> {
89 const imported = new Set<string>();
90 for (const line of lines) {
91 IMPORT_SPECIFIER.lastIndex = 0;
92 let match = IMPORT_SPECIFIER.exec(line);
93 while (match !== null) {
94 // Bundler queries such as `?worker` or `?url` name the same file.
95 const specifier = (match[1] ?? "").replace(/\?.*$/, "");
96 const resolved = stripModuleExtension(
97 specifier.startsWith(".") ? resolveRelative(path, specifier) : specifier,
98 );
99 const target =
100 byModulePath.get(resolved) ??
101 byModulePath.get(`${resolved}/index`) ??
102 byModuleName.get(moduleName(resolved));
103 if (target !== undefined && target !== path) imported.add(target);
104 match = IMPORT_SPECIFIER.exec(line);
105 }
106 }
107 return imported;
108}
109
110function orderByImports(
111 paths: ReadonlyArray<string>,
112 imports: ReadonlyMap<string, ReadonlySet<string>>,
113): Array<string> {
114 const remaining = new Set(paths);
115 const ordered: Array<string> = [];
116 const sorted = [...paths].sort((left, right) => left.localeCompare(right));
117 while (remaining.size > 0) {
118 const candidates = sorted.filter((path) => remaining.has(path));
119 const next =
120 candidates.find((path) =>
121 [...(imports.get(path) ?? [])].every((dependency) => !remaining.has(dependency)),
122 ) ?? candidates[0]!;
123 remaining.delete(next);
124 ordered.push(next);
125 }
126 return ordered;
127}
128
129// `a.logic.test.ts` covers `a.logic.ts` while `a.browser.test.ts` covers `a.ts`, so the longest
130// dotted prefix that names a source file wins.
131function testedSourcePosition(path: string, sourcePositions: ReadonlyMap<string, number>): number {
132 let name = (path.split("/").at(-1) ?? "").replace(/\.(?:test|spec)\..*$/, "");
133 while (true) {
134 const position = sourcePositions.get(name);
135 if (position !== undefined) return position;
136 const dot = name.lastIndexOf(".");
137 if (dot <= 0) return Number.MAX_SAFE_INTEGER;
138 name = name.slice(0, dot);
139 }
140}
141
142export function orderDiffFiles(
143 files: ReadonlyArray<FileDiffMetadata>,
144): ReadonlyArray<FileDiffMetadata> {
145 const byPath = new Map<string, FileDiffMetadata>();
146 for (const file of files) byPath.set(resolveFileDiffPath(file), file);
147 const tiers = new Map<string, DiffFileTier>();
148 for (const path of byPath.keys()) tiers.set(path, diffFileTier(path));
149
150 const sourcePaths = [...byPath.keys()].filter((path) => tiers.get(path) === "source");
151 const byModulePath = new Map<string, string>();
152 const ambiguousModuleNames = new Set<string>();
153 const byModuleName = new Map<string, string>();
154 for (const path of sourcePaths) {
155 byModulePath.set(stripModuleExtension(path), path);
156 const name = moduleName(path);
157 if (byModuleName.has(name)) ambiguousModuleNames.add(name);
158 byModuleName.set(name, path);
159 }
160 for (const name of ambiguousModuleNames) byModuleName.delete(name);
161
162 const imports = new Map<string, ReadonlySet<string>>();
163 for (const path of sourcePaths) {
164 const file = byPath.get(path)!;
165 imports.set(
166 path,
167 importedPaths(
168 path,
169 [...file.additionLines, ...file.deletionLines],
170 byModulePath,
171 byModuleName,
172 ),
173 );
174 }
175 const orderedSource = orderByImports(sourcePaths, imports);
176
177 const sourcePositions = new Map<string, number>();
178 orderedSource.forEach((path, index) => {
179 const base = baseName(path);
180 if (!sourcePositions.has(base)) sourcePositions.set(base, index);
181 });
182 const orderedTests = [...byPath.keys()]
183 .filter((path) => tiers.get(path) === "test")
184 .sort((left, right) => {
185 return (
186 testedSourcePosition(left, sourcePositions) -
187 testedSourcePosition(right, sourcePositions) || left.localeCompare(right)
188 );
189 });
190
191 const orderedGenerated = [...byPath.keys()]
192 .filter((path) => tiers.get(path) === "generated")
193 .sort((left, right) => left.localeCompare(right));
194
195 return [...orderedSource, ...orderedTests, ...orderedGenerated].map((path) => byPath.get(path)!);
196}