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

pullRequestFileOrder.logic.ts

182 lines6.0 KB

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";
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;
54​
55function baseName(path: string): string {
56 return stripExtension(path.split("/").at(-1) ?? "");
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("/");
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 // Module-map keys omit extensions, which can differ from disk.
87 const extension = MODULE_EXTENSIONS.find((candidate) => withExtension.endsWith(candidate));
88 const resolved =
89 extension === undefined ? withExtension : withExtension.slice(0, -extension.length);
90 const target =
91 byModulePath.get(resolved) ??
92 byModulePath.get(`${resolved}/index`) ??
93 byBaseName.get(baseName(resolved));
94 if (target !== undefined && target !== path) imported.add(target);
95 match = IMPORT_SPECIFIER.exec(line);
96 }
97 }
98 return imported;
100​
101function orderByImports(
102 paths: ReadonlyArray<string>,
103 imports: ReadonlyMap<string, ReadonlySet<string>>,
104): Array<string> {
105 const remaining = new Set(paths);
106 const ordered: Array<string> = [];
107 const sorted = [...paths].sort((left, right) => left.localeCompare(right));
108 while (remaining.size > 0) {
109 const candidates = sorted.filter((path) => remaining.has(path));
110 const next =
111 candidates.find((path) =>
112 [...(imports.get(path) ?? [])].every((dependency) => !remaining.has(dependency)),
113 ) ?? candidates[0]!;
114 remaining.delete(next);
115 ordered.push(next);
116 }
117 return ordered;
119​
120// `a.logic.test.ts` covers `a.logic.ts` while `a.browser.test.ts` covers `a.ts`, so the longest
121// dotted prefix that names a source file wins.
122function testedSourcePosition(path: string, sourcePositions: ReadonlyMap<string, number>): number {
123 let name = (path.split("/").at(-1) ?? "").replace(/\.(?:test|spec)\..*$/, "");
124 while (true) {
125 const position = sourcePositions.get(name);
126 if (position !== undefined) return position;
127 const dot = name.lastIndexOf(".");
128 if (dot <= 0) return Number.MAX_SAFE_INTEGER;
129 name = name.slice(0, dot);
130 }
132​
133export function orderDiffFiles(
134 files: ReadonlyArray<FileDiffMetadata>,
135): ReadonlyArray<FileDiffMetadata> {
136 const byPath = new Map<string, FileDiffMetadata>();
137 for (const file of files) byPath.set(resolveFileDiffPath(file), file);
138 const tiers = new Map<string, DiffFileTier>();
139 for (const path of byPath.keys()) tiers.set(path, diffFileTier(path));
140​
141 const sourcePaths = [...byPath.keys()].filter((path) => tiers.get(path) === "source");
142 const byModulePath = new Map<string, string>();
143 const ambiguousBaseNames = new Set<string>();
144 const byBaseName = new Map<string, string>();
145 for (const path of sourcePaths) {
146 byModulePath.set(stripExtension(path), path);
147 const base = baseName(path);
148 if (byBaseName.has(base)) ambiguousBaseNames.add(base);
149 byBaseName.set(base, path);
150 }
151 for (const base of ambiguousBaseNames) byBaseName.delete(base);
152​
153 const imports = new Map<string, ReadonlySet<string>>();
154 for (const path of sourcePaths) {
155 const file = byPath.get(path)!;
156 imports.set(
157 path,
158 importedPaths(path, [...file.additionLines, ...file.deletionLines], byModulePath, byBaseName),
159 );
160 }
161 const orderedSource = orderByImports(sourcePaths, imports);
162​
163 const sourcePositions = new Map<string, number>();
164 orderedSource.forEach((path, index) => {
165 const base = baseName(path);
166 if (!sourcePositions.has(base)) sourcePositions.set(base, index);
167 });
168 const orderedTests = [...byPath.keys()]
169 .filter((path) => tiers.get(path) === "test")
170 .sort((left, right) => {
171 return (
172 testedSourcePosition(left, sourcePositions) -
173 testedSourcePosition(right, sourcePositions) || left.localeCompare(right)
174 );
175 });
176​
177 const orderedGenerated = [...byPath.keys()]
178 .filter((path) => tiers.get(path) === "generated")
179 .sort((left, right) => left.localeCompare(right));
180​
181 return [...orderedSource, ...orderedTests, ...orderedGenerated].map((path) => byPath.get(path)!);