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"]);
25const MODULE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
26
27function diffFileTier(path: string): DiffFileTier {
28 const segments = path.split("/");
29 const name = segments.at(-1) ?? "";
30 if (
31 GENERATED_FILE_NAMES.has(name) ||
32 name.endsWith(".snap") ||
33 name.endsWith(".min.js") ||
34 name.endsWith(".min.css") ||
35 /\.generated\./.test(name) ||
36 segments.slice(0, -1).some((segment) => GENERATED_DIRECTORIES.has(segment))
37 ) {
38 return "generated";
39 }
40 if (
41 /\.(?:test|spec)\./.test(name) ||
42 segments.slice(0, -1).some((segment) => TEST_DIRECTORIES.has(segment))
43 ) {
44 return "test";
45 }
46 return "source";
47}
48
49function stripExtension(path: string): string {
50 const dot = path.lastIndexOf(".");
51 const slash = path.lastIndexOf("/");
52 return dot > slash ? path.slice(0, dot) : path;
53}
54
55function baseName(path: string): string {
56 return stripExtension(path.split("/").at(-1) ?? "");
57}
58
59function resolveRelative(fromPath: string, specifier: string): string {
60 const segments = fromPath.split("/").slice(0, -1);
61 for (const part of specifier.split("/")) {
62 if (part === "." || part === "") continue;
63 if (part === "..") segments.pop();
64 else segments.push(part);
65 }
66 return segments.join("/");
67}
68
69const IMPORT_SPECIFIER = /(?:\bfrom|\bimport|\brequire\s*\()\s*\(?\s*["']([^"']+)["']/g;
70
71function importedPaths(
72 path: string,
73 lines: ReadonlyArray<string>,
74 byModulePath: ReadonlyMap<string, string>,
75 byBaseName: ReadonlyMap<string, string>,
76): ReadonlySet<string> {
77 const imported = new Set<string>();
78 for (const line of lines) {
79 IMPORT_SPECIFIER.lastIndex = 0;
80 let match = IMPORT_SPECIFIER.exec(line);
81 while (match !== null) {
82 const specifier = match[1] ?? "";
83 const withExtension = specifier.startsWith(".")
84 ? resolveRelative(path, specifier)
85 : specifier;
86 // A specifier may name the extension the module map dropped, and it need not be the one on
87 // disk: TypeScript's own imports point at the `.js` beside a `.ts`.
88 const extension = MODULE_EXTENSIONS.find((candidate) => withExtension.endsWith(candidate));
89 const resolved =
90 extension === undefined ? withExtension : withExtension.slice(0, -extension.length);
91 const target =
92 byModulePath.get(resolved) ??
93 byModulePath.get(`${resolved}/index`) ??
94 byBaseName.get(baseName(resolved));
95 if (target !== undefined && target !== path) imported.add(target);
96 match = IMPORT_SPECIFIER.exec(line);
97 }
98 }
99 return imported;
100}
101
102function orderByImports(
103 paths: ReadonlyArray<string>,
104 imports: ReadonlyMap<string, ReadonlySet<string>>,
105): Array<string> {
106 const remaining = new Set(paths);
107 const ordered: Array<string> = [];
108 const sorted = [...paths].sort((left, right) => left.localeCompare(right));
109 while (remaining.size > 0) {
110 const candidates = sorted.filter((path) => remaining.has(path));
111 const next =
112 candidates.find((path) =>
113 [...(imports.get(path) ?? [])].every((dependency) => !remaining.has(dependency)),
114 ) ?? candidates[0]!;
115 remaining.delete(next);
116 ordered.push(next);
117 }
118 return ordered;
119}
120
121function testedBaseName(path: string): string {
122 return (path.split("/").at(-1) ?? "").replace(/\.(?:test|spec)\..*$/, "").replace(/\.[^.]+$/, "");
123}
124
125export function orderDiffFiles(
126 files: ReadonlyArray<FileDiffMetadata>,
127): ReadonlyArray<FileDiffMetadata> {
128 const byPath = new Map<string, FileDiffMetadata>();
129 for (const file of files) byPath.set(resolveFileDiffPath(file), file);
130 const tiers = new Map<string, DiffFileTier>();
131 for (const path of byPath.keys()) tiers.set(path, diffFileTier(path));
132
133 const sourcePaths = [...byPath.keys()].filter((path) => tiers.get(path) === "source");
134 const byModulePath = new Map<string, string>();
135 const ambiguousBaseNames = new Set<string>();
136 const byBaseName = new Map<string, string>();
137 for (const path of sourcePaths) {
138 byModulePath.set(stripExtension(path), path);
139 const base = baseName(path);
140 if (byBaseName.has(base)) ambiguousBaseNames.add(base);
141 byBaseName.set(base, path);
142 }
143 for (const base of ambiguousBaseNames) byBaseName.delete(base);
144
145 const imports = new Map<string, ReadonlySet<string>>();
146 for (const path of sourcePaths) {
147 const file = byPath.get(path)!;
148 imports.set(
149 path,
150 importedPaths(path, [...file.additionLines, ...file.deletionLines], byModulePath, byBaseName),
151 );
152 }
153 const orderedSource = orderByImports(sourcePaths, imports);
154
155 const sourcePositions = new Map<string, number>();
156 orderedSource.forEach((path, index) => {
157 const base = baseName(path);
158 if (!sourcePositions.has(base)) sourcePositions.set(base, index);
159 });
160 const orderedTests = [...byPath.keys()]
161 .filter((path) => tiers.get(path) === "test")
162 .sort((left, right) => {
163 const leftPosition = sourcePositions.get(testedBaseName(left)) ?? Number.MAX_SAFE_INTEGER;
164 const rightPosition = sourcePositions.get(testedBaseName(right)) ?? Number.MAX_SAFE_INTEGER;
165 return leftPosition - rightPosition || left.localeCompare(right);
166 });
167
168 const orderedGenerated = [...byPath.keys()]
169 .filter((path) => tiers.get(path) === "generated")
170 .sort((left, right) => left.localeCompare(right));
171
172 return [...orderedSource, ...orderedTests, ...orderedGenerated].map((path) => byPath.get(path)!);
173}