@ryuugg/stanza 0.3.3 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -5
- package/package.json +19 -11
- package/src/launcher +102 -8
- package/src/cli.ts +0 -684
- package/src/compile/darwin-arm64.ts +0 -3
- package/src/compile/darwin-x64.ts +0 -3
- package/src/compile/linux-arm64-musl.ts +0 -3
- package/src/compile/linux-arm64.ts +0 -3
- package/src/compile/linux-x64-musl.ts +0 -3
- package/src/compile/linux-x64.ts +0 -3
- package/src/compiled.ts +0 -9
- package/src/depth.ts +0 -372
- package/src/directories.ts +0 -77
- package/src/engine/attach.ts +0 -62
- package/src/engine/directives.ts +0 -157
- package/src/engine/doc.ts +0 -93
- package/src/engine/edits.ts +0 -79
- package/src/engine/explain.ts +0 -337
- package/src/engine/gaps.ts +0 -361
- package/src/engine/hunks.ts +0 -319
- package/src/engine/index.ts +0 -273
- package/src/engine/model.ts +0 -103
- package/src/engine/rules.ts +0 -104
- package/src/engine/types.ts +0 -38
- package/src/files.ts +0 -1186
- package/src/format.ts +0 -159
- package/src/gitignore.ts +0 -280
- package/src/hook.ts +0 -380
- package/src/languages/index.ts +0 -34
- package/src/languages/javascript/ast.ts +0 -261
- package/src/languages/javascript/braces.ts +0 -374
- package/src/languages/javascript/config/biome.ts +0 -112
- package/src/languages/javascript/config/eslint.ts +0 -128
- package/src/languages/javascript/config/evaluate.ts +0 -278
- package/src/languages/javascript/config/find.ts +0 -105
- package/src/languages/javascript/config/glob.ts +0 -149
- package/src/languages/javascript/config/index.ts +0 -48
- package/src/languages/javascript/config/layers.ts +0 -468
- package/src/languages/javascript/config/module.ts +0 -327
- package/src/languages/javascript/config/oxlint.ts +0 -170
- package/src/languages/javascript/config/width.ts +0 -723
- package/src/languages/javascript/deserializers.ts +0 -17
- package/src/languages/javascript/embedded.ts +0 -7
- package/src/languages/javascript/entry.ts +0 -42
- package/src/languages/javascript/facts.ts +0 -294
- package/src/languages/javascript/index.ts +0 -20
- package/src/languages/javascript/lists.ts +0 -64
- package/src/languages/javascript/oracle.ts +0 -191
- package/src/languages/javascript/oxc-raw.d.ts +0 -31
- package/src/languages/javascript/parse.ts +0 -131
- package/src/languages/javascript/raw.ts +0 -95
- package/src/languages/javascript/scan.ts +0 -68
- package/src/languages/language.ts +0 -109
- package/src/native-file.d.ts +0 -4
- package/src/pool.ts +0 -473
- package/src/start.ts +0 -49
- package/src/step.ts +0 -113
- package/src/usage.ts +0 -35
- package/src/worker.ts +0 -5
package/src/files.ts
DELETED
|
@@ -1,1186 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
accessSync,
|
|
3
|
-
closeSync,
|
|
4
|
-
constants,
|
|
5
|
-
existsSync,
|
|
6
|
-
lstatSync,
|
|
7
|
-
openSync,
|
|
8
|
-
readdirSync,
|
|
9
|
-
readFileSync,
|
|
10
|
-
readSync,
|
|
11
|
-
realpathSync,
|
|
12
|
-
statSync,
|
|
13
|
-
type Stats,
|
|
14
|
-
} from "node:fs";
|
|
15
|
-
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
16
|
-
import { invocationMap, listed, realDirectory } from "./directories.ts";
|
|
17
|
-
import { entryFor, isCandidate, prunes } from "./languages/index.ts";
|
|
18
|
-
import { ignoredByRules, parseIgnore, type Rule } from "./gitignore.ts";
|
|
19
|
-
import { diffChanges } from "./engine/hunks.ts";
|
|
20
|
-
import type { Changed } from "./engine/model.ts";
|
|
21
|
-
|
|
22
|
-
export interface Collected {
|
|
23
|
-
files: string[];
|
|
24
|
-
errors: string[];
|
|
25
|
-
warnings: string[];
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
let gitAvailable: boolean | undefined;
|
|
29
|
-
function hasGit(): boolean {
|
|
30
|
-
return (gitAvailable ??= Bun.which("git") !== null);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
type GitResult = { ok: true; output: string } | { ok: false; error: string };
|
|
34
|
-
|
|
35
|
-
type GitBytes = { ok: true; output: Uint8Array } | { ok: false; error: string };
|
|
36
|
-
|
|
37
|
-
type Selection = { ok: true; files: string[] } | { ok: false; error: string };
|
|
38
|
-
|
|
39
|
-
function runGit(
|
|
40
|
-
cwd: string,
|
|
41
|
-
args: string[],
|
|
42
|
-
stdin?: Uint8Array,
|
|
43
|
-
env?: NodeJS.ProcessEnv,
|
|
44
|
-
): GitResult {
|
|
45
|
-
const result = runGitBytes(cwd, args, stdin, env);
|
|
46
|
-
return result.ok ? { ok: true, output: new TextDecoder().decode(result.output) } : result;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function runGitBytes(
|
|
50
|
-
cwd: string,
|
|
51
|
-
args: string[],
|
|
52
|
-
stdin?: Uint8Array,
|
|
53
|
-
env?: NodeJS.ProcessEnv,
|
|
54
|
-
): GitBytes {
|
|
55
|
-
const result = Bun.spawnSync(["git", "-C", cwd, ...args], {
|
|
56
|
-
stdin,
|
|
57
|
-
stderr: "pipe",
|
|
58
|
-
// Bun snapshots the environment for a spawn given no env, so a later process.env change would miss git.
|
|
59
|
-
env: env ?? process.env,
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
if (result.exitCode === 0) return { ok: true, output: result.stdout };
|
|
63
|
-
|
|
64
|
-
const reason =
|
|
65
|
-
new TextDecoder()
|
|
66
|
-
.decode(result.stderr)
|
|
67
|
-
.split("\n")
|
|
68
|
-
.map((line) => line.trim())
|
|
69
|
-
.find(Boolean) ?? `exit ${result.exitCode}`;
|
|
70
|
-
|
|
71
|
-
const command = args.find((arg) => !arg.startsWith("-"));
|
|
72
|
-
return { ok: false, error: `git ${command} failed in ${cwd}: ${reason}` };
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function nulItems(text: string): string[] {
|
|
76
|
-
return text.split("\0").filter(Boolean);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export type EmptyReason = "generated" | "ignored" | "skipped" | "none";
|
|
80
|
-
|
|
81
|
-
export function emptyReason(paths: string[], cwd: string): EmptyReason {
|
|
82
|
-
if (collectFiles(paths, cwd, true).files.length > 0) return "generated";
|
|
83
|
-
|
|
84
|
-
let sawSupported = false;
|
|
85
|
-
function candidate(path: string): boolean {
|
|
86
|
-
if (entryFor(path) === undefined) return false;
|
|
87
|
-
sawSupported = true;
|
|
88
|
-
return isCandidate(path, true);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function walk(dir: string, root: string): boolean {
|
|
92
|
-
let entries;
|
|
93
|
-
try {
|
|
94
|
-
entries = readdirSync(dir, { withFileTypes: true });
|
|
95
|
-
} catch {
|
|
96
|
-
return false;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
for (const entry of entries) {
|
|
100
|
-
const path = join(dir, entry.name);
|
|
101
|
-
const rel = relative(root, path).split(sep).join("/");
|
|
102
|
-
if (entry.isDirectory()) {
|
|
103
|
-
if (entry.name === ".git" || (sawSupported && prunes(rel))) continue;
|
|
104
|
-
if (walk(path, root)) return true;
|
|
105
|
-
} else if (entry.isFile() && candidate(rel)) return true;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
return false;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
for (const input of paths) {
|
|
112
|
-
const path = isAbsolute(input) ? input : resolve(cwd, input);
|
|
113
|
-
|
|
114
|
-
let kind;
|
|
115
|
-
try {
|
|
116
|
-
kind = statSync(path);
|
|
117
|
-
} catch {
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
if (kind.isFile()) sawSupported ||= entryFor(path) !== undefined;
|
|
122
|
-
else if (kind.isDirectory() && walk(path, path)) return "ignored";
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
return sawSupported ? "skipped" : "none";
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
const generatedMarkers = [
|
|
129
|
-
/@generated\b/,
|
|
130
|
-
/^code generated\b.*\bdo not edit\b/i,
|
|
131
|
-
/\b(?:this|the) (?:file|code|class) (?:is|was|has been) (?:auto(?:matically)?[- ]?)?generated\b/i,
|
|
132
|
-
/\bauto(?:matically)?[- ]?generated (?:file|code|class)\b/i,
|
|
133
|
-
/^(?:auto(?:matically)?[- ]?)generated\b/i,
|
|
134
|
-
];
|
|
135
|
-
|
|
136
|
-
const generatorAttribution = /^(?:code )?generated (?:by|from|with|using|code)\b/i;
|
|
137
|
-
|
|
138
|
-
const editWarning = /\bdo not (?:edit|modify|make (?:direct )?changes)\b/i;
|
|
139
|
-
|
|
140
|
-
export function isGeneratedHeader(text: string): boolean {
|
|
141
|
-
const comments = headerComments(text);
|
|
142
|
-
if (comments.some((comment) => generatedMarkers.some((marker) => marker.test(comment))))
|
|
143
|
-
return true;
|
|
144
|
-
|
|
145
|
-
return (
|
|
146
|
-
comments.some((comment) => generatorAttribution.test(comment)) &&
|
|
147
|
-
comments.some((comment) => editWarning.test(comment))
|
|
148
|
-
);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
function headerComments(text: string): string[] {
|
|
152
|
-
const comments: string[] = [];
|
|
153
|
-
|
|
154
|
-
let inBlock = false;
|
|
155
|
-
for (const line of text.split(/\r?\n/, 10)) {
|
|
156
|
-
let rest = line.trim();
|
|
157
|
-
while (rest !== "") {
|
|
158
|
-
if (!inBlock) {
|
|
159
|
-
if (rest.startsWith("//")) {
|
|
160
|
-
comments.push(commentBody(rest.slice(2)));
|
|
161
|
-
break;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
if (!rest.startsWith("/*")) break;
|
|
165
|
-
|
|
166
|
-
rest = rest.slice(2);
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
const end = rest.indexOf("*/");
|
|
170
|
-
inBlock = end === -1;
|
|
171
|
-
comments.push(commentBody(inBlock ? rest : rest.slice(0, end)));
|
|
172
|
-
rest = inBlock ? "" : rest.slice(end + 2).trimStart();
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
return comments;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
function commentBody(text: string): string {
|
|
180
|
-
return text.replace(/^[/*]+/, "").trim();
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
export function errorCode(error: unknown): string {
|
|
184
|
-
const code = (error as NodeJS.ErrnoException).code;
|
|
185
|
-
return typeof code === "string" ? code : String(error);
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
interface IgnoreSource {
|
|
189
|
-
directory: string;
|
|
190
|
-
rules: Rule[];
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
function ignoredBySources(sources: IgnoreSource[], path: string, isDirectory: boolean): boolean {
|
|
194
|
-
let ignored = false;
|
|
195
|
-
for (const source of sources) {
|
|
196
|
-
const relativePath = relative(source.directory, path).split(sep).join("/");
|
|
197
|
-
ignored = ignoredByRules(source.rules, relativePath, isDirectory) ?? ignored;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
return ignored;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
function fallbackFiles(
|
|
204
|
-
dir: string,
|
|
205
|
-
cwd: string,
|
|
206
|
-
keepGenerated: boolean,
|
|
207
|
-
): { files: string[]; errors: string[] } {
|
|
208
|
-
const files: string[] = [];
|
|
209
|
-
const errors: string[] = [];
|
|
210
|
-
function withIgnoreFile(current: string, sources: IgnoreSource[]): IgnoreSource[] {
|
|
211
|
-
const ignoreFile = join(current, ".gitignore");
|
|
212
|
-
if (!existsSync(ignoreFile)) return sources;
|
|
213
|
-
|
|
214
|
-
try {
|
|
215
|
-
return [
|
|
216
|
-
...sources,
|
|
217
|
-
{ directory: current, rules: parseIgnore(readFileSync(ignoreFile, "utf8")) },
|
|
218
|
-
];
|
|
219
|
-
} catch (error: unknown) {
|
|
220
|
-
errors.push(`cannot read ${relative(cwd, ignoreFile)}: ${errorCode(error)}`);
|
|
221
|
-
return sources;
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
function walk(current: string, parents: IgnoreSource[]): void {
|
|
226
|
-
const active = withIgnoreFile(current, parents);
|
|
227
|
-
|
|
228
|
-
let entries;
|
|
229
|
-
try {
|
|
230
|
-
entries = readdirSync(current, { withFileTypes: true });
|
|
231
|
-
} catch (error: unknown) {
|
|
232
|
-
errors.push(
|
|
233
|
-
`cannot read directory: ${relative(cwd, current) || current}: ${errorCode(error)}`,
|
|
234
|
-
);
|
|
235
|
-
|
|
236
|
-
return;
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
for (const entry of entries) {
|
|
240
|
-
const file = join(current, entry.name);
|
|
241
|
-
const rel = relative(dir, file).split(sep).join("/");
|
|
242
|
-
if (prunes(rel)) continue;
|
|
243
|
-
if (ignoredBySources(active, file, entry.isDirectory())) continue;
|
|
244
|
-
|
|
245
|
-
if (entry.isDirectory()) walk(file, active);
|
|
246
|
-
else if (entry.isFile() && isCandidate(rel, keepGenerated)) files.push(resolve(file));
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
const ancestors: string[] = [];
|
|
251
|
-
for (let current = dir; !existsSync(join(current, ".git")) && dirname(current) !== current;) {
|
|
252
|
-
current = dirname(current);
|
|
253
|
-
ancestors.unshift(current);
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
let inherited: IgnoreSource[] = [];
|
|
257
|
-
for (const [index, ancestor] of ancestors.entries()) {
|
|
258
|
-
inherited = withIgnoreFile(ancestor, inherited);
|
|
259
|
-
const below = ancestors[index + 1] ?? dir;
|
|
260
|
-
if (ignoredBySources(inherited, below, true)) return { files, errors };
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
walk(dir, inherited);
|
|
264
|
-
return { files, errors };
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
export type Location =
|
|
268
|
-
| { kind: "repository"; root: string }
|
|
269
|
-
| { kind: "outside" }
|
|
270
|
-
| { kind: "failed"; error: string };
|
|
271
|
-
|
|
272
|
-
function ceilingDirectories(): Set<string> {
|
|
273
|
-
return new Set(
|
|
274
|
-
(process.env.GIT_CEILING_DIRECTORIES ?? "")
|
|
275
|
-
.split(delimiter)
|
|
276
|
-
.filter((path) => isAbsolute(path))
|
|
277
|
-
.map((path) => (existsSync(path) ? realpathSync(path) : resolve(path))),
|
|
278
|
-
);
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
function hasGitMarker(dir: string): boolean {
|
|
282
|
-
if (dir.split(sep).includes(".git")) return false;
|
|
283
|
-
|
|
284
|
-
const ceilings = ceilingDirectories();
|
|
285
|
-
for (let current = realpathSync(dir); ; current = dirname(current)) {
|
|
286
|
-
if (existsSync(join(current, ".git"))) return true;
|
|
287
|
-
const parent = dirname(current);
|
|
288
|
-
if (parent === current || ceilings.has(parent)) return false;
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
const locations = invocationMap<string, Location>();
|
|
293
|
-
|
|
294
|
-
interface GitVariable {
|
|
295
|
-
key: string;
|
|
296
|
-
value: string | undefined;
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
interface GitVariables {
|
|
300
|
-
readable: boolean;
|
|
301
|
-
text: string;
|
|
302
|
-
entries: GitVariable[];
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
const gitVariables = invocationMap<string, GitVariables>();
|
|
306
|
-
|
|
307
|
-
const discoveryEnvironment = [
|
|
308
|
-
"GIT_DIR",
|
|
309
|
-
"GIT_WORK_TREE",
|
|
310
|
-
"GIT_COMMON_DIR",
|
|
311
|
-
"GIT_OBJECT_DIRECTORY",
|
|
312
|
-
"GIT_CEILING_DIRECTORIES",
|
|
313
|
-
"GIT_TEST_ASSUME_DIFFERENT_OWNER",
|
|
314
|
-
];
|
|
315
|
-
|
|
316
|
-
function parseGitVariable(line: string): GitVariable {
|
|
317
|
-
const separator = line.indexOf("=");
|
|
318
|
-
if (separator === -1) return { key: line, value: undefined };
|
|
319
|
-
return { key: line.slice(0, separator), value: line.slice(separator + 1) };
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
function listGitVariables(root: string): GitVariables {
|
|
323
|
-
const cached = gitVariables.get(root);
|
|
324
|
-
if (cached !== undefined) return cached;
|
|
325
|
-
|
|
326
|
-
const result = Bun.spawnSync(["git", "-C", root, "var", "-l"], {
|
|
327
|
-
env: process.env,
|
|
328
|
-
stderr: "pipe",
|
|
329
|
-
});
|
|
330
|
-
|
|
331
|
-
const text = new TextDecoder().decode(result.stdout);
|
|
332
|
-
const variables = {
|
|
333
|
-
readable: result.exitCode === 0 && result.stderr.length === 0,
|
|
334
|
-
text,
|
|
335
|
-
entries: text.replace(/\n$/, "").split("\n").map(parseGitVariable),
|
|
336
|
-
};
|
|
337
|
-
|
|
338
|
-
gitVariables.set(root, variables);
|
|
339
|
-
return variables;
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
function plainConfig(root: string): boolean {
|
|
343
|
-
const { readable, text } = listGitVariables(root);
|
|
344
|
-
return (
|
|
345
|
-
readable &&
|
|
346
|
-
!/^(?:core\.worktree|extensions\.[^=]*)(?:=|$)/im.test(text) &&
|
|
347
|
-
!/^core\.bare(?:=(?!(?:false|no|off|0)$)|$)/im.test(text) &&
|
|
348
|
-
!/^core\.repositoryformatversion(?:=(?![01]$)|$)/im.test(text)
|
|
349
|
-
);
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
function plainRepository(
|
|
353
|
-
worktree: string,
|
|
354
|
-
marker: string,
|
|
355
|
-
markerStat: Stats,
|
|
356
|
-
user: number,
|
|
357
|
-
): boolean {
|
|
358
|
-
if (lstatSync(worktree).uid !== user || markerStat.uid !== user) return false;
|
|
359
|
-
|
|
360
|
-
const head = join(marker, "HEAD");
|
|
361
|
-
if (!lstatSync(head).isFile()) return false;
|
|
362
|
-
|
|
363
|
-
const descriptor = openSync(head, "r");
|
|
364
|
-
const bytes = Buffer.alloc(255);
|
|
365
|
-
|
|
366
|
-
let text: string;
|
|
367
|
-
try {
|
|
368
|
-
text = bytes.subarray(0, readSync(descriptor, bytes, 0, bytes.length, 0)).toString("latin1");
|
|
369
|
-
} finally {
|
|
370
|
-
closeSync(descriptor);
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
if (!/^(?:ref: refs\/|[0-9a-f]{40})/.test(text)) return false;
|
|
374
|
-
|
|
375
|
-
accessSync(join(marker, "objects"), constants.X_OK);
|
|
376
|
-
accessSync(join(marker, "refs"), constants.X_OK);
|
|
377
|
-
if (lstatSync(join(marker, "commondir"), { throwIfNoEntry: false }) !== undefined) return false;
|
|
378
|
-
|
|
379
|
-
return plainConfig(worktree);
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
function knownRoot(dir: string): string | undefined {
|
|
383
|
-
try {
|
|
384
|
-
if (discoveryEnvironment.some((name) => process.env[name] !== undefined)) return undefined;
|
|
385
|
-
if (Object.keys(process.env).some((name) => name.startsWith("GIT_CONFIG"))) return undefined;
|
|
386
|
-
|
|
387
|
-
const user = process.geteuid?.();
|
|
388
|
-
if (user === undefined) return undefined;
|
|
389
|
-
|
|
390
|
-
const start = realpathSync(dir);
|
|
391
|
-
const startStat = statSync(start);
|
|
392
|
-
if (!startStat.isDirectory() || /[^\x20-\x7e]/.test(start) || start.split(sep).includes(".git"))
|
|
393
|
-
return undefined;
|
|
394
|
-
|
|
395
|
-
const device = startStat.dev;
|
|
396
|
-
|
|
397
|
-
let current = start;
|
|
398
|
-
while (true) {
|
|
399
|
-
const marker = join(current, ".git");
|
|
400
|
-
const entry = lstatSync(marker, { throwIfNoEntry: false });
|
|
401
|
-
if (entry !== undefined)
|
|
402
|
-
return entry.isDirectory() && plainRepository(current, marker, entry, user)
|
|
403
|
-
? current
|
|
404
|
-
: undefined;
|
|
405
|
-
|
|
406
|
-
if (lstatSync(join(current, "HEAD"), { throwIfNoEntry: false }) !== undefined)
|
|
407
|
-
return undefined;
|
|
408
|
-
|
|
409
|
-
const parent = dirname(current);
|
|
410
|
-
if (parent === current || statSync(parent).dev !== device) return undefined;
|
|
411
|
-
|
|
412
|
-
current = parent;
|
|
413
|
-
}
|
|
414
|
-
} catch {
|
|
415
|
-
return undefined;
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
function discoverLocation(dir: string): Location {
|
|
420
|
-
if (!hasGit()) return { kind: "outside" };
|
|
421
|
-
|
|
422
|
-
const known = knownRoot(dir);
|
|
423
|
-
if (known !== undefined) return { kind: "repository", root: known };
|
|
424
|
-
|
|
425
|
-
const result = runGit(dir, ["rev-parse", "--show-toplevel"]);
|
|
426
|
-
const root = result.ok ? result.output.replace(/\n$/, "") : "";
|
|
427
|
-
if (root) return { kind: "repository", root };
|
|
428
|
-
if (!result.ok && hasGitMarker(dir)) return { kind: "failed", error: result.error };
|
|
429
|
-
return { kind: "outside" };
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
export function locate(dir: string): Location {
|
|
433
|
-
const known = locations.get(dir);
|
|
434
|
-
if (known !== undefined) return known;
|
|
435
|
-
|
|
436
|
-
const location = discoverLocation(dir);
|
|
437
|
-
locations.set(dir, location);
|
|
438
|
-
return location;
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
function repositoryPath(root: string, file: string): string {
|
|
442
|
-
return relative(root, file).split(sep).join("/");
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
function within(root: string, path: string): boolean {
|
|
446
|
-
const pathFromRoot = relative(root, path);
|
|
447
|
-
return pathFromRoot !== ".." && !pathFromRoot.startsWith(`..${sep}`) && !isAbsolute(pathFromRoot);
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
function suppliedBelow(anchor: string, path: string): string {
|
|
451
|
-
for (let current = dirname(path); ; current = dirname(current)) {
|
|
452
|
-
if (existsSync(current) && realpathSync(current) === anchor)
|
|
453
|
-
return repositoryPath(current, path);
|
|
454
|
-
|
|
455
|
-
if (dirname(current) === current) return basename(path);
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
function selectedBelow(
|
|
460
|
-
anchor: string,
|
|
461
|
-
supplied: string,
|
|
462
|
-
file: string,
|
|
463
|
-
keepGenerated = false,
|
|
464
|
-
): boolean {
|
|
465
|
-
return (
|
|
466
|
-
isCandidate(repositoryPath(anchor, file), keepGenerated) &&
|
|
467
|
-
isCandidate(suppliedBelow(anchor, supplied), keepGenerated)
|
|
468
|
-
);
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
function isSet(value: string | undefined): boolean {
|
|
472
|
-
return value === "true" || value === "set";
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
type Attributes = { ok: true; values: Map<string, string> } | { ok: false; error: string };
|
|
476
|
-
|
|
477
|
-
function sourceMaySetAttributes(path: string, names: string[]): boolean {
|
|
478
|
-
const entry = lstatSync(path, { throwIfNoEntry: false });
|
|
479
|
-
if (entry === undefined) return false;
|
|
480
|
-
if (!entry.isFile()) return true;
|
|
481
|
-
|
|
482
|
-
const text = readFileSync(path, "utf8");
|
|
483
|
-
return text.includes("[attr]") || names.some((name) => text.includes(name));
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
function indexMayHaveAttributes(root: string): boolean {
|
|
487
|
-
const path = join(root, ".git/index");
|
|
488
|
-
const entry = lstatSync(path, { throwIfNoEntry: false });
|
|
489
|
-
if (entry === undefined) return false;
|
|
490
|
-
if (!entry.isFile()) return true;
|
|
491
|
-
|
|
492
|
-
const bytes = readFileSync(path);
|
|
493
|
-
if (bytes.length < 32 || bytes.toString("ascii", 0, 4) !== "DIRC") return true;
|
|
494
|
-
|
|
495
|
-
const version = bytes.readUInt32BE(4);
|
|
496
|
-
if (version !== 2 && version !== 3) return true;
|
|
497
|
-
|
|
498
|
-
let offset = 12;
|
|
499
|
-
const count = bytes.readUInt32BE(8);
|
|
500
|
-
for (let entryIndex = 0; entryIndex < count; entryIndex++) {
|
|
501
|
-
if (offset + 62 > bytes.length - 20) return true;
|
|
502
|
-
if ((bytes.readUInt32BE(offset + 24) & 0o170000) === 0o040000) return true;
|
|
503
|
-
|
|
504
|
-
const extended = (bytes.readUInt16BE(offset + 60) & 0x4000) !== 0;
|
|
505
|
-
if (extended && version !== 3) return true;
|
|
506
|
-
|
|
507
|
-
const start = offset + 62 + (extended ? 2 : 0);
|
|
508
|
-
const end = bytes.indexOf(0, start);
|
|
509
|
-
if (end < start || end >= bytes.length - 20) return true;
|
|
510
|
-
|
|
511
|
-
const name = bytes.toString("utf8", start, end);
|
|
512
|
-
if (name === ".gitattributes" || name.endsWith("/.gitattributes")) return true;
|
|
513
|
-
|
|
514
|
-
offset += Math.ceil((end + 1 - offset) / 8) * 8;
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
while (offset < bytes.length - 20) {
|
|
518
|
-
if (offset + 8 > bytes.length - 20) return true;
|
|
519
|
-
if (bytes.toString("ascii", offset, offset + 4) !== "TREE") return true;
|
|
520
|
-
offset += 8 + bytes.readUInt32BE(offset + 4);
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
return offset !== bytes.length - 20;
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
// git var -l prints GIT_EDITOR, GIT_SEQUENCE_EDITOR and GIT_PAGER raw, so a newline could forge a line.
|
|
527
|
-
const inertGitEnvironment = new Set([
|
|
528
|
-
"GIT_EDITOR",
|
|
529
|
-
"GIT_SEQUENCE_EDITOR",
|
|
530
|
-
"GIT_PAGER",
|
|
531
|
-
"GIT_TERMINAL_PROMPT",
|
|
532
|
-
"GIT_ASKPASS",
|
|
533
|
-
"GIT_SSH",
|
|
534
|
-
"GIT_SSH_COMMAND",
|
|
535
|
-
"GIT_SSH_VARIANT",
|
|
536
|
-
"GIT_AUTHOR_NAME",
|
|
537
|
-
"GIT_AUTHOR_EMAIL",
|
|
538
|
-
"GIT_AUTHOR_DATE",
|
|
539
|
-
"GIT_COMMITTER_NAME",
|
|
540
|
-
"GIT_COMMITTER_EMAIL",
|
|
541
|
-
"GIT_COMMITTER_DATE",
|
|
542
|
-
"GIT_OPTIONAL_LOCKS",
|
|
543
|
-
]);
|
|
544
|
-
|
|
545
|
-
function environmentMayAffectAttributes(): boolean {
|
|
546
|
-
return Object.entries(process.env).some(
|
|
547
|
-
([name, value]) =>
|
|
548
|
-
name.startsWith("GIT_") && (!inertGitEnvironment.has(name) || value?.includes("\n") === true),
|
|
549
|
-
);
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
function rebuildablePath(path: string | undefined): path is string {
|
|
553
|
-
return (
|
|
554
|
-
path !== undefined && (path.startsWith("~/") || !path.startsWith("~")) && !path.includes("%(")
|
|
555
|
-
);
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
function normalizeAsText(path: string): string {
|
|
559
|
-
return path
|
|
560
|
-
.split("/")
|
|
561
|
-
.filter((segment, position) => position === 0 || (segment !== "" && segment !== "."))
|
|
562
|
-
.join("/");
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
function defaultGlobalAttributes(): string | undefined {
|
|
566
|
-
const { HOME: home, XDG_CONFIG_HOME: configHome } = process.env;
|
|
567
|
-
if (configHome) return `${configHome}/git/attributes`;
|
|
568
|
-
return home === undefined ? undefined : `${home}/.config/git/attributes`;
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
function expectedGlobalAttributes(configured: (string | undefined)[]): string | undefined {
|
|
572
|
-
if (!configured.every(rebuildablePath)) return undefined;
|
|
573
|
-
|
|
574
|
-
const path = configured.at(-1);
|
|
575
|
-
const home = process.env.HOME;
|
|
576
|
-
if (path === undefined) return defaultGlobalAttributes();
|
|
577
|
-
if (!path.startsWith("~/")) return path;
|
|
578
|
-
return home === undefined ? undefined : `${home}/${path.slice(2)}`;
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
const attributeVariableOrder = ["GIT_ATTR_SYSTEM", "GIT_ATTR_GLOBAL", "GIT_CONFIG_SYSTEM"];
|
|
582
|
-
// Once each, adjacent and in git's order, so neither path value spans or forges a line.
|
|
583
|
-
function attributeVariableValues(entries: GitVariable[]): (string | undefined)[] | undefined {
|
|
584
|
-
const sequence = entries.flatMap((entry, position) =>
|
|
585
|
-
attributeVariableOrder.includes(entry.key) ? [{ ...entry, position }] : [],
|
|
586
|
-
);
|
|
587
|
-
|
|
588
|
-
const start = sequence[0]?.position;
|
|
589
|
-
const exact =
|
|
590
|
-
sequence.length === attributeVariableOrder.length &&
|
|
591
|
-
sequence.every(
|
|
592
|
-
(entry, offset) =>
|
|
593
|
-
entry.key === attributeVariableOrder[offset] && entry.position - offset === start,
|
|
594
|
-
);
|
|
595
|
-
|
|
596
|
-
return exact ? sequence.map((entry) => entry.value) : undefined;
|
|
597
|
-
}
|
|
598
|
-
|
|
599
|
-
function attributeSourcePaths(root: string): string[] | undefined {
|
|
600
|
-
const variables = gitVariables.get(root);
|
|
601
|
-
if (variables === undefined || !variables.readable) return undefined;
|
|
602
|
-
|
|
603
|
-
const { entries } = variables;
|
|
604
|
-
if (entries.some(({ key }) => /^attr\./i.test(key))) return undefined;
|
|
605
|
-
|
|
606
|
-
const [system, global] = attributeVariableValues(entries) ?? [];
|
|
607
|
-
if (system === undefined || global === undefined) return undefined;
|
|
608
|
-
|
|
609
|
-
const configured = entries
|
|
610
|
-
.filter(({ key }) => key.toLowerCase() === "core.attributesfile")
|
|
611
|
-
.map(({ value }) => value);
|
|
612
|
-
|
|
613
|
-
// git var collapses .. as text but check-attr opens the raw path, where a symlink resolves first.
|
|
614
|
-
const expected = expectedGlobalAttributes(configured);
|
|
615
|
-
if (expected === undefined || normalizeAsText(expected) !== global) return undefined;
|
|
616
|
-
|
|
617
|
-
const paths = [system, global];
|
|
618
|
-
return paths.every(isAbsolute) ? paths : undefined;
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
function attributesMayApply(files: string[], root: string, names: string[]): boolean {
|
|
622
|
-
if (environmentMayAffectAttributes()) return true;
|
|
623
|
-
|
|
624
|
-
const sources = attributeSourcePaths(root);
|
|
625
|
-
if (sources === undefined) return true;
|
|
626
|
-
|
|
627
|
-
try {
|
|
628
|
-
if (indexMayHaveAttributes(root)) return true;
|
|
629
|
-
|
|
630
|
-
const paths = new Set([...sources, join(root, ".git/info/attributes")]);
|
|
631
|
-
for (const file of files) {
|
|
632
|
-
if (!within(root, file)) return true;
|
|
633
|
-
|
|
634
|
-
for (let directory = dirname(file); ; directory = dirname(directory)) {
|
|
635
|
-
paths.add(join(directory, ".gitattributes"));
|
|
636
|
-
if (directory === root) break;
|
|
637
|
-
if (!within(root, directory)) return true;
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
return [...paths].some((path) => sourceMaySetAttributes(path, names));
|
|
642
|
-
} catch {
|
|
643
|
-
return true;
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
function readAttributes(
|
|
648
|
-
files: string[],
|
|
649
|
-
root: string,
|
|
650
|
-
names: string[],
|
|
651
|
-
source: "worktree" | "index",
|
|
652
|
-
): Attributes {
|
|
653
|
-
if (files.length === 0) return { ok: true, values: new Map() };
|
|
654
|
-
if (
|
|
655
|
-
source === "worktree" &&
|
|
656
|
-
names.length === 1 &&
|
|
657
|
-
names[0] === "linguist-generated" &&
|
|
658
|
-
!attributesMayApply(files, root, names)
|
|
659
|
-
)
|
|
660
|
-
return { ok: true, values: new Map() };
|
|
661
|
-
|
|
662
|
-
const paths = files.map((file) => `${repositoryPath(root, file)}\0`).join("");
|
|
663
|
-
const result = runGit(
|
|
664
|
-
root,
|
|
665
|
-
["check-attr", ...(source === "index" ? ["--cached"] : []), ...names, "-z", "--stdin"],
|
|
666
|
-
new TextEncoder().encode(paths),
|
|
667
|
-
);
|
|
668
|
-
|
|
669
|
-
if (!result.ok) return result;
|
|
670
|
-
|
|
671
|
-
const values = new Map<string, string>();
|
|
672
|
-
const fields = result.output.split("\0");
|
|
673
|
-
for (let index = 0; index + 2 < fields.length; index += 3)
|
|
674
|
-
values.set(`${fields[index]}\0${fields[index + 1]}`, fields[index + 2]!);
|
|
675
|
-
|
|
676
|
-
return { ok: true, values };
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
function attribute(
|
|
680
|
-
attributes: Map<string, string>,
|
|
681
|
-
root: string,
|
|
682
|
-
file: string,
|
|
683
|
-
name: string,
|
|
684
|
-
): string | undefined {
|
|
685
|
-
return attributes.get(`${repositoryPath(root, file)}\0${name}`);
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
function dropGeneratedAttributes(files: string[], root: string): Selection {
|
|
689
|
-
const read = readAttributes(files, root, ["linguist-generated"], "worktree");
|
|
690
|
-
if (!read.ok) return read;
|
|
691
|
-
|
|
692
|
-
return {
|
|
693
|
-
ok: true,
|
|
694
|
-
files: files.filter((file) => !isSet(attribute(read.values, root, file, "linguist-generated"))),
|
|
695
|
-
};
|
|
696
|
-
}
|
|
697
|
-
|
|
698
|
-
function directoryFiles(dir: string, root: string, keepGenerated: boolean): Selection {
|
|
699
|
-
const result = runGit(dir, [
|
|
700
|
-
"ls-files",
|
|
701
|
-
"-z",
|
|
702
|
-
"--cached",
|
|
703
|
-
"--others",
|
|
704
|
-
"--exclude-standard",
|
|
705
|
-
"--",
|
|
706
|
-
".",
|
|
707
|
-
]);
|
|
708
|
-
|
|
709
|
-
if (!result.ok) return result;
|
|
710
|
-
|
|
711
|
-
const files = nulItems(result.output)
|
|
712
|
-
.filter((path) => isCandidate(path, keepGenerated))
|
|
713
|
-
.map((path) => resolve(dir, path))
|
|
714
|
-
.filter((path) => {
|
|
715
|
-
try {
|
|
716
|
-
return lstatSync(path).isFile();
|
|
717
|
-
} catch {
|
|
718
|
-
return false;
|
|
719
|
-
}
|
|
720
|
-
});
|
|
721
|
-
|
|
722
|
-
const inside = files.map((path) => listedFileRealpath(path)).filter((path) => within(root, path));
|
|
723
|
-
return { ok: true, files: inside };
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
// realpathSync returns the name in its on disk case and normalization, so only an exact listing match may join.
|
|
727
|
-
function listedFileRealpath(path: string): string {
|
|
728
|
-
const dir = dirname(path);
|
|
729
|
-
const name = basename(path);
|
|
730
|
-
return listed(dir, name) ? join(realDirectory(dir), name) : fileRealpath(path);
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
function fileRealpath(path: string): string {
|
|
734
|
-
try {
|
|
735
|
-
return realpathSync(path);
|
|
736
|
-
} catch (error: unknown) {
|
|
737
|
-
if (lstatSync(path).isFile()) return join(realpathSync(dirname(path)), basename(path));
|
|
738
|
-
throw error;
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
function sorted(files: string[]): string[] {
|
|
743
|
-
return [...new Set(files)].sort((left, right) => left.localeCompare(right));
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
export function collectFiles(paths: string[], cwd: string, keepGenerated = false): Collected {
|
|
747
|
-
const byRoot = new Map<string, string[]>();
|
|
748
|
-
const outside: string[] = [];
|
|
749
|
-
const errors: string[] = [];
|
|
750
|
-
const warnings = hasGit()
|
|
751
|
-
? []
|
|
752
|
-
: ["git not found on PATH, file selection fell back to the directory walk"];
|
|
753
|
-
|
|
754
|
-
function add(root: string, files: string[]): void {
|
|
755
|
-
const listed = byRoot.get(root);
|
|
756
|
-
if (listed) listed.push(...files);
|
|
757
|
-
else byRoot.set(root, files);
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
for (const input of paths) {
|
|
761
|
-
const path = isAbsolute(input) ? input : resolve(cwd, input);
|
|
762
|
-
if (!existsSync(path)) {
|
|
763
|
-
errors.push(`no such file: ${input}`);
|
|
764
|
-
continue;
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
let directory = false;
|
|
768
|
-
try {
|
|
769
|
-
directory = statSync(path).isDirectory();
|
|
770
|
-
} catch {}
|
|
771
|
-
|
|
772
|
-
if (directory) {
|
|
773
|
-
const location = locate(path);
|
|
774
|
-
if (location.kind === "failed") {
|
|
775
|
-
errors.push(location.error);
|
|
776
|
-
continue;
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
if (location.kind === "outside") {
|
|
780
|
-
const fallback = fallbackFiles(path, cwd, keepGenerated);
|
|
781
|
-
outside.push(...fallback.files);
|
|
782
|
-
errors.push(...fallback.errors);
|
|
783
|
-
continue;
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
const listed = directoryFiles(path, location.root, keepGenerated);
|
|
787
|
-
if (listed.ok) add(location.root, listed.files);
|
|
788
|
-
else errors.push(listed.error);
|
|
789
|
-
|
|
790
|
-
continue;
|
|
791
|
-
}
|
|
792
|
-
|
|
793
|
-
if (entryFor(path) === undefined) {
|
|
794
|
-
errors.push(`not a TypeScript or JavaScript file: ${input}`);
|
|
795
|
-
continue;
|
|
796
|
-
}
|
|
797
|
-
|
|
798
|
-
const file = fileRealpath(path);
|
|
799
|
-
const location = locate(dirname(file));
|
|
800
|
-
if (location.kind === "failed") {
|
|
801
|
-
errors.push(location.error);
|
|
802
|
-
continue;
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
const anchor = location.kind === "repository" ? location.root : dirname(file);
|
|
806
|
-
if (!selectedBelow(anchor, path, file, keepGenerated)) continue;
|
|
807
|
-
|
|
808
|
-
if (location.kind === "outside") outside.push(file);
|
|
809
|
-
else add(location.root, [file]);
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
const files = [...outside];
|
|
813
|
-
for (const [root, candidates] of byRoot) {
|
|
814
|
-
if (keepGenerated) {
|
|
815
|
-
files.push(...candidates);
|
|
816
|
-
continue;
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
const kept = dropGeneratedAttributes(candidates, root);
|
|
820
|
-
if (kept.ok) files.push(...kept.files);
|
|
821
|
-
else errors.push(kept.error);
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
return { files: sorted(files), errors: [...new Set(errors)], warnings };
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
function existingAncestor(path: string): string {
|
|
828
|
-
const parent = dirname(path);
|
|
829
|
-
return existsSync(path) || parent === path ? path : existingAncestor(parent);
|
|
830
|
-
}
|
|
831
|
-
|
|
832
|
-
export type StdinTarget =
|
|
833
|
-
| { status: "format"; path: string; root: string | undefined }
|
|
834
|
-
| { status: "skip" }
|
|
835
|
-
| { status: "unsupported"; error: string }
|
|
836
|
-
| { status: "failed"; error: string };
|
|
837
|
-
|
|
838
|
-
export function stdinTarget(input: string, cwd: string): StdinTarget {
|
|
839
|
-
const path = isAbsolute(input) ? input : resolve(cwd, input);
|
|
840
|
-
if (entryFor(path) === undefined)
|
|
841
|
-
return { status: "unsupported", error: `not a TypeScript or JavaScript file: ${input}` };
|
|
842
|
-
|
|
843
|
-
const directory = existingAncestor(dirname(path));
|
|
844
|
-
const real = realpathSync(directory);
|
|
845
|
-
const file = join(real, relative(directory, path));
|
|
846
|
-
|
|
847
|
-
const location = locate(real);
|
|
848
|
-
if (location.kind === "failed") return { status: "failed", error: location.error };
|
|
849
|
-
|
|
850
|
-
const anchor = location.kind === "repository" ? location.root : dirname(file);
|
|
851
|
-
if (!selectedBelow(anchor, path, file)) return { status: "skip" };
|
|
852
|
-
if (location.kind === "outside") return { status: "format", path: file, root: undefined };
|
|
853
|
-
|
|
854
|
-
const kept = dropGeneratedAttributes([file], location.root);
|
|
855
|
-
if (!kept.ok) return { status: "failed", error: kept.error };
|
|
856
|
-
if (kept.files.length === 0) return { status: "skip" };
|
|
857
|
-
|
|
858
|
-
return { status: "format", path: file, root: location.root };
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
export function landsWithin(root: string, path: string): boolean {
|
|
862
|
-
try {
|
|
863
|
-
let entry = path;
|
|
864
|
-
while (!lstatSync(entry, { throwIfNoEntry: false }) && dirname(entry) !== entry)
|
|
865
|
-
entry = dirname(entry);
|
|
866
|
-
|
|
867
|
-
return within(root, realpathSync(entry));
|
|
868
|
-
} catch {
|
|
869
|
-
return false;
|
|
870
|
-
}
|
|
871
|
-
}
|
|
872
|
-
|
|
873
|
-
export function ignoredByGit(root: string, path: string): boolean {
|
|
874
|
-
return runGit(root, ["check-ignore", "-q", "--", repositoryPath(root, path)]).ok;
|
|
875
|
-
}
|
|
876
|
-
|
|
877
|
-
export function trackedInHead(root: string, path: string): boolean {
|
|
878
|
-
return runGit(root, ["cat-file", "-e", `HEAD:${repositoryPath(root, path)}`]).ok;
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
function diffSections(text: string): string[][] {
|
|
882
|
-
const sections: string[][] = [];
|
|
883
|
-
for (const line of text.split("\n")) {
|
|
884
|
-
if (line.startsWith("diff --git ") && sections.at(-1)?.[0] !== line) sections.push([]);
|
|
885
|
-
sections.at(-1)?.push(line);
|
|
886
|
-
}
|
|
887
|
-
|
|
888
|
-
return sections;
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
type ChangedLines = { ok: true; lines: Changed[] } | { ok: false; error: string };
|
|
892
|
-
|
|
893
|
-
function diffLines(
|
|
894
|
-
root: string,
|
|
895
|
-
range: string[],
|
|
896
|
-
count: number,
|
|
897
|
-
paths: string[] = [],
|
|
898
|
-
): ChangedLines {
|
|
899
|
-
const env = { ...process.env };
|
|
900
|
-
delete env.GIT_DIFF_OPTS;
|
|
901
|
-
const diff = runGit(
|
|
902
|
-
root,
|
|
903
|
-
[
|
|
904
|
-
"-c",
|
|
905
|
-
"diff.suppressBlankEmpty=false",
|
|
906
|
-
"--literal-pathspecs",
|
|
907
|
-
"diff",
|
|
908
|
-
"--unified=999999999",
|
|
909
|
-
"--text",
|
|
910
|
-
"--submodule=short",
|
|
911
|
-
"--no-color",
|
|
912
|
-
"--no-ext-diff",
|
|
913
|
-
"--no-textconv",
|
|
914
|
-
"--no-renames",
|
|
915
|
-
...range,
|
|
916
|
-
"--",
|
|
917
|
-
...paths,
|
|
918
|
-
],
|
|
919
|
-
undefined,
|
|
920
|
-
env,
|
|
921
|
-
);
|
|
922
|
-
|
|
923
|
-
if (!diff.ok) return diff;
|
|
924
|
-
|
|
925
|
-
const sections = diffSections(diff.output);
|
|
926
|
-
if (sections.length !== count)
|
|
927
|
-
return { ok: false, error: "git diff section count differs from the changed file count" };
|
|
928
|
-
|
|
929
|
-
return { ok: true, lines: sections.map(diffChanges) };
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
const pathspecBudget = 64 * 1024;
|
|
933
|
-
export function collectChanged(
|
|
934
|
-
cwd: string,
|
|
935
|
-
location: Location = locate(cwd),
|
|
936
|
-
hunks = false,
|
|
937
|
-
written?: Set<string>,
|
|
938
|
-
): Collected & { changedLines: Map<string, Changed> } {
|
|
939
|
-
const changedLines = new Map<string, Changed>();
|
|
940
|
-
if (!hasGit())
|
|
941
|
-
return {
|
|
942
|
-
changedLines,
|
|
943
|
-
files: [],
|
|
944
|
-
errors: ["--changed needs git, which was not found on PATH"],
|
|
945
|
-
warnings: [],
|
|
946
|
-
};
|
|
947
|
-
|
|
948
|
-
if (location.kind === "failed")
|
|
949
|
-
return { files: [], errors: [location.error], warnings: [], changedLines };
|
|
950
|
-
|
|
951
|
-
if (location.kind === "outside")
|
|
952
|
-
return { files: [], errors: ["not inside a git repository"], warnings: [], changedLines };
|
|
953
|
-
|
|
954
|
-
const root = location.root;
|
|
955
|
-
const realRoot = realpathSync(root);
|
|
956
|
-
const scope = [...(written ?? [])]
|
|
957
|
-
.filter((path) => within(realRoot, path))
|
|
958
|
-
.map((path) => repositoryPath(realRoot, path));
|
|
959
|
-
|
|
960
|
-
const pathspecs = Buffer.byteLength(scope.join("")) <= pathspecBudget ? scope : [];
|
|
961
|
-
|
|
962
|
-
let changed = runGit(root, [
|
|
963
|
-
"--literal-pathspecs",
|
|
964
|
-
"diff",
|
|
965
|
-
"--name-only",
|
|
966
|
-
"-z",
|
|
967
|
-
"--no-renames",
|
|
968
|
-
"--submodule=short",
|
|
969
|
-
"HEAD",
|
|
970
|
-
"--",
|
|
971
|
-
...pathspecs,
|
|
972
|
-
]);
|
|
973
|
-
|
|
974
|
-
const born = changed.ok || runGit(root, ["rev-parse", "--verify", "-q", "HEAD"]).ok;
|
|
975
|
-
if (!born) {
|
|
976
|
-
const branch = runGit(root, ["symbolic-ref", "-q", "HEAD"]);
|
|
977
|
-
if (!branch.ok) return { files: [], errors: [branch.error], warnings: [], changedLines };
|
|
978
|
-
|
|
979
|
-
changed = runGit(root, [
|
|
980
|
-
"--literal-pathspecs",
|
|
981
|
-
"ls-files",
|
|
982
|
-
"-z",
|
|
983
|
-
"--cached",
|
|
984
|
-
"--",
|
|
985
|
-
...pathspecs,
|
|
986
|
-
]);
|
|
987
|
-
}
|
|
988
|
-
|
|
989
|
-
const untracked = runGit(root, [
|
|
990
|
-
"--literal-pathspecs",
|
|
991
|
-
"ls-files",
|
|
992
|
-
"-z",
|
|
993
|
-
"--others",
|
|
994
|
-
"--exclude-standard",
|
|
995
|
-
"--",
|
|
996
|
-
...pathspecs,
|
|
997
|
-
]);
|
|
998
|
-
|
|
999
|
-
if (!changed.ok || !untracked.ok) {
|
|
1000
|
-
const errors = [changed, untracked].flatMap((result) => (result.ok ? [] : [result.error]));
|
|
1001
|
-
return { files: [], errors: [...new Set(errors)], warnings: [], changedLines };
|
|
1002
|
-
}
|
|
1003
|
-
|
|
1004
|
-
const kept = (name: string) => written === undefined || written.has(resolve(realRoot, name));
|
|
1005
|
-
const names = nulItems(changed.output).filter(kept);
|
|
1006
|
-
const candidates = names.filter((name) => isCandidate(name));
|
|
1007
|
-
if (hunks && born && candidates.length > 0) {
|
|
1008
|
-
const diff = diffLines(root, ["HEAD"], candidates.length, candidates);
|
|
1009
|
-
if (!diff.ok) return { files: [], errors: [diff.error], warnings: [], changedLines };
|
|
1010
|
-
|
|
1011
|
-
for (let index = 0; index < candidates.length; index++)
|
|
1012
|
-
changedLines.set(resolve(root, candidates[index]!), diff.lines[index]!);
|
|
1013
|
-
}
|
|
1014
|
-
|
|
1015
|
-
const untrackedNames = nulItems(untracked.output).filter(kept);
|
|
1016
|
-
for (const name of untrackedNames) changedLines.delete(resolve(root, name));
|
|
1017
|
-
|
|
1018
|
-
const files = [...names, ...untrackedNames]
|
|
1019
|
-
.filter((path) => isCandidate(path))
|
|
1020
|
-
.map((path) => resolve(root, path))
|
|
1021
|
-
.filter((path) => existsSync(path) && lstatSync(path).isFile())
|
|
1022
|
-
.filter((path) => within(realRoot, fileRealpath(path)));
|
|
1023
|
-
|
|
1024
|
-
const generated = dropGeneratedAttributes(files, root);
|
|
1025
|
-
if (!generated.ok) return { files: [], errors: [generated.error], warnings: [], changedLines };
|
|
1026
|
-
|
|
1027
|
-
return { files: sorted(generated.files), errors: [], warnings: [], changedLines };
|
|
1028
|
-
}
|
|
1029
|
-
|
|
1030
|
-
export interface StagedFile {
|
|
1031
|
-
path: string;
|
|
1032
|
-
bytes: Uint8Array;
|
|
1033
|
-
unstaged: boolean;
|
|
1034
|
-
lines?: Changed;
|
|
1035
|
-
}
|
|
1036
|
-
|
|
1037
|
-
export type StagedSelection = { ok: true; files: StagedFile[] } | { ok: false; error: string };
|
|
1038
|
-
|
|
1039
|
-
const regularFileModes = new Set(["100644", "100755"]);
|
|
1040
|
-
|
|
1041
|
-
type Blobs = { ok: true; blobs: Uint8Array[] } | { ok: false; error: string };
|
|
1042
|
-
|
|
1043
|
-
function readBlobs(root: string, ids: string[]): Blobs {
|
|
1044
|
-
if (ids.length === 0) return { ok: true, blobs: [] };
|
|
1045
|
-
|
|
1046
|
-
const result = runGitBytes(
|
|
1047
|
-
root,
|
|
1048
|
-
["cat-file", "--batch"],
|
|
1049
|
-
new TextEncoder().encode(`${ids.join("\n")}\n`),
|
|
1050
|
-
);
|
|
1051
|
-
|
|
1052
|
-
if (!result.ok) return result;
|
|
1053
|
-
|
|
1054
|
-
const output = result.output;
|
|
1055
|
-
const blobs: Uint8Array[] = [];
|
|
1056
|
-
|
|
1057
|
-
let offset = 0;
|
|
1058
|
-
for (const id of ids) {
|
|
1059
|
-
const end = output.indexOf(10, offset);
|
|
1060
|
-
const [, type, size] =
|
|
1061
|
-
end < 0 ? [] : new TextDecoder().decode(output.subarray(offset, end)).split(" ");
|
|
1062
|
-
|
|
1063
|
-
if (type !== "blob") return { ok: false, error: `git cat-file could not read blob ${id}` };
|
|
1064
|
-
|
|
1065
|
-
const start = end + 1;
|
|
1066
|
-
blobs.push(output.subarray(start, start + Number(size)));
|
|
1067
|
-
offset = start + Number(size) + 1;
|
|
1068
|
-
}
|
|
1069
|
-
|
|
1070
|
-
return { ok: true, blobs };
|
|
1071
|
-
}
|
|
1072
|
-
|
|
1073
|
-
function readFilteredBlob(
|
|
1074
|
-
root: string,
|
|
1075
|
-
tree: string | undefined,
|
|
1076
|
-
path: string,
|
|
1077
|
-
id: string,
|
|
1078
|
-
): GitBytes {
|
|
1079
|
-
return runGitBytes(root, [
|
|
1080
|
-
...(tree === undefined ? [] : [`--attr-source=${tree}`]),
|
|
1081
|
-
"cat-file",
|
|
1082
|
-
"--filters",
|
|
1083
|
-
`--path=${repositoryPath(root, path)}`,
|
|
1084
|
-
id,
|
|
1085
|
-
]);
|
|
1086
|
-
}
|
|
1087
|
-
|
|
1088
|
-
export function collectStaged(cwd: string, hunks = false): StagedSelection {
|
|
1089
|
-
if (!hasGit()) return { ok: false, error: "--staged needs git, which was not found on PATH" };
|
|
1090
|
-
|
|
1091
|
-
const location = locate(cwd);
|
|
1092
|
-
if (location.kind === "failed") return { ok: false, error: location.error };
|
|
1093
|
-
if (location.kind === "outside") return { ok: false, error: "not inside a git repository" };
|
|
1094
|
-
|
|
1095
|
-
const root = location.root;
|
|
1096
|
-
const range = ["--cached", "--diff-filter=ACMT"];
|
|
1097
|
-
const diff = runGit(root, ["diff", ...range, "--raw", "-z", "--no-renames", "--no-abbrev"]);
|
|
1098
|
-
if (!diff.ok) return diff;
|
|
1099
|
-
|
|
1100
|
-
const items = nulItems(diff.output);
|
|
1101
|
-
const blobOf = new Map<string, string>();
|
|
1102
|
-
const edited: string[] = [];
|
|
1103
|
-
for (let index = 0; index + 1 < items.length; index += 2) {
|
|
1104
|
-
const [, mode, , blob, status] = items[index]!.split(" ");
|
|
1105
|
-
const name = items[index + 1]!;
|
|
1106
|
-
if (
|
|
1107
|
-
mode === undefined ||
|
|
1108
|
-
blob === undefined ||
|
|
1109
|
-
!regularFileModes.has(mode) ||
|
|
1110
|
-
!isCandidate(name)
|
|
1111
|
-
)
|
|
1112
|
-
continue;
|
|
1113
|
-
|
|
1114
|
-
blobOf.set(resolve(root, name), blob);
|
|
1115
|
-
if (status === "M") edited.push(name);
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
const changed =
|
|
1119
|
-
hunks && edited.length > 0 ? diffLines(root, range, edited.length, edited) : undefined;
|
|
1120
|
-
|
|
1121
|
-
if (changed && !changed.ok) return changed;
|
|
1122
|
-
|
|
1123
|
-
const linesOf = new Map(
|
|
1124
|
-
edited.map((name, index) => [resolve(root, name), changed?.lines[index]]),
|
|
1125
|
-
);
|
|
1126
|
-
|
|
1127
|
-
const attributes = readAttributes(
|
|
1128
|
-
[...blobOf.keys()],
|
|
1129
|
-
root,
|
|
1130
|
-
["linguist-generated", "filter"],
|
|
1131
|
-
"index",
|
|
1132
|
-
);
|
|
1133
|
-
|
|
1134
|
-
if (!attributes.ok) return attributes;
|
|
1135
|
-
|
|
1136
|
-
const unstaged = runGit(root, ["diff", "--name-only", "-z", "--no-renames"]);
|
|
1137
|
-
if (!unstaged.ok) return unstaged;
|
|
1138
|
-
|
|
1139
|
-
const dirty = new Set(nulItems(unstaged.output).map((path) => resolve(root, path)));
|
|
1140
|
-
const paths = sorted([...blobOf.keys()]).filter(
|
|
1141
|
-
(path) => !isSet(attribute(attributes.values, root, path, "linguist-generated")),
|
|
1142
|
-
);
|
|
1143
|
-
|
|
1144
|
-
const filtered = (path: string) =>
|
|
1145
|
-
!["unspecified", "unset"].includes(
|
|
1146
|
-
attribute(attributes.values, root, path, "filter") ?? "unset",
|
|
1147
|
-
);
|
|
1148
|
-
|
|
1149
|
-
const plain = paths.filter((path) => !filtered(path));
|
|
1150
|
-
const read = readBlobs(
|
|
1151
|
-
root,
|
|
1152
|
-
plain.map((path) => blobOf.get(path)!),
|
|
1153
|
-
);
|
|
1154
|
-
|
|
1155
|
-
if (!read.ok) return read;
|
|
1156
|
-
|
|
1157
|
-
const bytes = new Map(plain.map((path, index) => [path, read.blobs[index]!]));
|
|
1158
|
-
const smudge = paths.filter(filtered);
|
|
1159
|
-
const worktree = readAttributes(smudge, root, ["filter"], "worktree");
|
|
1160
|
-
if (!worktree.ok) return worktree;
|
|
1161
|
-
|
|
1162
|
-
const diverged = smudge.some(
|
|
1163
|
-
(path) =>
|
|
1164
|
-
attribute(worktree.values, root, path, "filter") !==
|
|
1165
|
-
attribute(attributes.values, root, path, "filter"),
|
|
1166
|
-
);
|
|
1167
|
-
|
|
1168
|
-
const tree = diverged ? runGit(root, ["write-tree"]) : undefined;
|
|
1169
|
-
if (tree && !tree.ok) return tree;
|
|
1170
|
-
|
|
1171
|
-
for (const path of smudge) {
|
|
1172
|
-
const smudged = readFilteredBlob(root, tree?.output.trim(), path, blobOf.get(path)!);
|
|
1173
|
-
if (!smudged.ok) return smudged;
|
|
1174
|
-
bytes.set(path, smudged.output);
|
|
1175
|
-
}
|
|
1176
|
-
|
|
1177
|
-
return {
|
|
1178
|
-
ok: true,
|
|
1179
|
-
files: paths.map((path) => ({
|
|
1180
|
-
path,
|
|
1181
|
-
bytes: bytes.get(path)!,
|
|
1182
|
-
unstaged: dirty.has(path),
|
|
1183
|
-
lines: filtered(path) ? undefined : linesOf.get(path),
|
|
1184
|
-
})),
|
|
1185
|
-
};
|
|
1186
|
-
}
|