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