@ryuugg/stanza 0.1.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/LICENSE.md +21 -0
- package/README.md +163 -0
- package/package.json +63 -0
- package/src/cli.ts +820 -0
- package/src/compile/darwin-arm64.ts +3 -0
- package/src/compile/darwin-x64.ts +3 -0
- package/src/compile/linux-arm64-musl.ts +3 -0
- package/src/compile/linux-arm64.ts +3 -0
- package/src/compile/linux-x64-musl.ts +3 -0
- package/src/compile/linux-x64.ts +3 -0
- package/src/compiled.ts +6 -0
- package/src/engine/attach.ts +62 -0
- package/src/engine/directives.ts +154 -0
- package/src/engine/doc.ts +93 -0
- package/src/engine/edits.ts +79 -0
- package/src/engine/explain.ts +333 -0
- package/src/engine/gaps.ts +329 -0
- package/src/engine/hunks.ts +320 -0
- package/src/engine/index.ts +254 -0
- package/src/engine/model.ts +102 -0
- package/src/engine/rules.ts +103 -0
- package/src/engine/types.ts +37 -0
- package/src/files.ts +822 -0
- package/src/gitignore.ts +279 -0
- package/src/hook.ts +282 -0
- package/src/languages/index.ts +32 -0
- package/src/languages/javascript/ast.ts +199 -0
- package/src/languages/javascript/braces.ts +374 -0
- package/src/languages/javascript/config/biome.ts +112 -0
- package/src/languages/javascript/config/eslint.ts +128 -0
- package/src/languages/javascript/config/evaluate.ts +278 -0
- package/src/languages/javascript/config/find.ts +108 -0
- package/src/languages/javascript/config/glob.ts +150 -0
- package/src/languages/javascript/config/index.ts +48 -0
- package/src/languages/javascript/config/layers.ts +425 -0
- package/src/languages/javascript/config/module.ts +326 -0
- package/src/languages/javascript/config/oxlint.ts +170 -0
- package/src/languages/javascript/config/width.ts +715 -0
- package/src/languages/javascript/entry.ts +39 -0
- package/src/languages/javascript/facts.ts +268 -0
- package/src/languages/javascript/index.ts +20 -0
- package/src/languages/javascript/lists.ts +49 -0
- package/src/languages/javascript/oracle.ts +191 -0
- package/src/languages/javascript/parse.ts +58 -0
- package/src/languages/javascript/scan.ts +68 -0
- package/src/languages/language.ts +109 -0
- package/src/launcher +21 -0
- package/src/native-file.d.ts +4 -0
- package/src/step.ts +108 -0
- package/src/usage.ts +30 -0
package/src/files.ts
ADDED
|
@@ -0,0 +1,822 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { entryFor, isCandidate, prunes } from "./languages/index.ts";
|
|
4
|
+
import { ignoredByRules, parseIgnore, type Rule } from "./gitignore.ts";
|
|
5
|
+
import { diffChanges } from "./engine/hunks.ts";
|
|
6
|
+
import type { Changed } from "./engine/model.ts";
|
|
7
|
+
|
|
8
|
+
export interface Collected {
|
|
9
|
+
files: string[];
|
|
10
|
+
errors: string[];
|
|
11
|
+
warnings: string[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
let gitAvailable: boolean | undefined;
|
|
15
|
+
|
|
16
|
+
function hasGit(): boolean {
|
|
17
|
+
return (gitAvailable ??= Bun.which("git") !== null);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type GitResult = { ok: true; output: string } | { ok: false; error: string };
|
|
21
|
+
|
|
22
|
+
type GitBytes = { ok: true; output: Uint8Array } | { ok: false; error: string };
|
|
23
|
+
|
|
24
|
+
type Selection = { ok: true; files: string[] } | { ok: false; error: string };
|
|
25
|
+
|
|
26
|
+
function runGit(
|
|
27
|
+
cwd: string,
|
|
28
|
+
args: string[],
|
|
29
|
+
stdin?: Uint8Array,
|
|
30
|
+
env?: NodeJS.ProcessEnv,
|
|
31
|
+
): GitResult {
|
|
32
|
+
const result = runGitBytes(cwd, args, stdin, env);
|
|
33
|
+
return result.ok ? { ok: true, output: new TextDecoder().decode(result.output) } : result;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function runGitBytes(
|
|
37
|
+
cwd: string,
|
|
38
|
+
args: string[],
|
|
39
|
+
stdin?: Uint8Array,
|
|
40
|
+
env?: NodeJS.ProcessEnv,
|
|
41
|
+
): GitBytes {
|
|
42
|
+
const result = Bun.spawnSync(["git", "-C", cwd, ...args], {
|
|
43
|
+
stdin,
|
|
44
|
+
stderr: "pipe",
|
|
45
|
+
// Bun snapshots the environment for a spawn given no env, so a later process.env change would miss git.
|
|
46
|
+
env: env ?? process.env,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
if (result.exitCode === 0) return { ok: true, output: result.stdout };
|
|
50
|
+
|
|
51
|
+
const reason =
|
|
52
|
+
new TextDecoder()
|
|
53
|
+
.decode(result.stderr)
|
|
54
|
+
.split("\n")
|
|
55
|
+
.map((line) => line.trim())
|
|
56
|
+
.find(Boolean) ?? `exit ${result.exitCode}`;
|
|
57
|
+
|
|
58
|
+
const command = args.find((arg) => !arg.startsWith("-"));
|
|
59
|
+
return { ok: false, error: `git ${command} failed in ${cwd}: ${reason}` };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function nulItems(text: string): string[] {
|
|
63
|
+
return text.split("\0").filter(Boolean);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type EmptyReason = "generated" | "ignored" | "skipped" | "none";
|
|
67
|
+
|
|
68
|
+
export function emptyReason(paths: string[], cwd: string): EmptyReason {
|
|
69
|
+
if (collectFiles(paths, cwd, true).files.length > 0) return "generated";
|
|
70
|
+
|
|
71
|
+
let sawSupported = false;
|
|
72
|
+
function candidate(path: string): boolean {
|
|
73
|
+
if (entryFor(path) === undefined) return false;
|
|
74
|
+
sawSupported = true;
|
|
75
|
+
return isCandidate(path, true);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function walk(dir: string, root: string): boolean {
|
|
79
|
+
let entries;
|
|
80
|
+
try {
|
|
81
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
82
|
+
} catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
for (const entry of entries) {
|
|
87
|
+
const path = join(dir, entry.name);
|
|
88
|
+
const rel = relative(root, path).split(sep).join("/");
|
|
89
|
+
if (entry.isDirectory()) {
|
|
90
|
+
if (entry.name === ".git" || (sawSupported && prunes(rel))) continue;
|
|
91
|
+
if (walk(path, root)) return true;
|
|
92
|
+
} else if (entry.isFile() && candidate(rel)) return true;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
for (const input of paths) {
|
|
99
|
+
const path = isAbsolute(input) ? input : resolve(cwd, input);
|
|
100
|
+
|
|
101
|
+
let kind;
|
|
102
|
+
try {
|
|
103
|
+
kind = statSync(path);
|
|
104
|
+
} catch {
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (kind.isFile()) sawSupported ||= entryFor(path) !== undefined;
|
|
109
|
+
else if (kind.isDirectory() && walk(path, path)) return "ignored";
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return sawSupported ? "skipped" : "none";
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const generatedMarkers = [
|
|
116
|
+
/@generated\b/,
|
|
117
|
+
/^code generated\b.*\bdo not edit\b/i,
|
|
118
|
+
/\b(?:this|the) (?:file|code|class) (?:is|was|has been) (?:auto(?:matically)?[- ]?)?generated\b/i,
|
|
119
|
+
/\bauto(?:matically)?[- ]?generated (?:file|code|class)\b/i,
|
|
120
|
+
/^(?:auto(?:matically)?[- ]?)generated\b/i,
|
|
121
|
+
];
|
|
122
|
+
|
|
123
|
+
const generatorAttribution = /^(?:code )?generated (?:by|from|with|using|code)\b/i;
|
|
124
|
+
|
|
125
|
+
const editWarning = /\bdo not (?:edit|modify|make (?:direct )?changes)\b/i;
|
|
126
|
+
|
|
127
|
+
export function isGeneratedHeader(text: string): boolean {
|
|
128
|
+
const comments = headerComments(text);
|
|
129
|
+
if (comments.some((comment) => generatedMarkers.some((marker) => marker.test(comment))))
|
|
130
|
+
return true;
|
|
131
|
+
|
|
132
|
+
return (
|
|
133
|
+
comments.some((comment) => generatorAttribution.test(comment)) &&
|
|
134
|
+
comments.some((comment) => editWarning.test(comment))
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function headerComments(text: string): string[] {
|
|
139
|
+
const comments: string[] = [];
|
|
140
|
+
|
|
141
|
+
let inBlock = false;
|
|
142
|
+
for (const line of text.split(/\r?\n/, 10)) {
|
|
143
|
+
let rest = line.trim();
|
|
144
|
+
while (rest !== "") {
|
|
145
|
+
if (!inBlock) {
|
|
146
|
+
if (rest.startsWith("//")) {
|
|
147
|
+
comments.push(commentBody(rest.slice(2)));
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (!rest.startsWith("/*")) break;
|
|
152
|
+
|
|
153
|
+
rest = rest.slice(2);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const end = rest.indexOf("*/");
|
|
157
|
+
inBlock = end === -1;
|
|
158
|
+
comments.push(commentBody(inBlock ? rest : rest.slice(0, end)));
|
|
159
|
+
rest = inBlock ? "" : rest.slice(end + 2).trimStart();
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return comments;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function commentBody(text: string): string {
|
|
167
|
+
return text.replace(/^[/*]+/, "").trim();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function errorCode(error: unknown): string {
|
|
171
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
172
|
+
return typeof code === "string" ? code : String(error);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
interface IgnoreSource {
|
|
176
|
+
directory: string;
|
|
177
|
+
rules: Rule[];
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function ignoredBySources(sources: IgnoreSource[], path: string, isDirectory: boolean): boolean {
|
|
181
|
+
let ignored = false;
|
|
182
|
+
for (const source of sources) {
|
|
183
|
+
const relativePath = relative(source.directory, path).split(sep).join("/");
|
|
184
|
+
ignored = ignoredByRules(source.rules, relativePath, isDirectory) ?? ignored;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return ignored;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function fallbackFiles(
|
|
191
|
+
dir: string,
|
|
192
|
+
cwd: string,
|
|
193
|
+
keepGenerated: boolean,
|
|
194
|
+
): { files: string[]; errors: string[] } {
|
|
195
|
+
const files: string[] = [];
|
|
196
|
+
const errors: string[] = [];
|
|
197
|
+
function withIgnoreFile(current: string, sources: IgnoreSource[]): IgnoreSource[] {
|
|
198
|
+
const ignoreFile = join(current, ".gitignore");
|
|
199
|
+
if (!existsSync(ignoreFile)) return sources;
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
return [
|
|
203
|
+
...sources,
|
|
204
|
+
{ directory: current, rules: parseIgnore(readFileSync(ignoreFile, "utf8")) },
|
|
205
|
+
];
|
|
206
|
+
} catch (error: unknown) {
|
|
207
|
+
errors.push(`cannot read ${relative(cwd, ignoreFile)}: ${errorCode(error)}`);
|
|
208
|
+
return sources;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function walk(current: string, parents: IgnoreSource[]): void {
|
|
213
|
+
const active = withIgnoreFile(current, parents);
|
|
214
|
+
|
|
215
|
+
let entries;
|
|
216
|
+
try {
|
|
217
|
+
entries = readdirSync(current, { withFileTypes: true });
|
|
218
|
+
} catch (error: unknown) {
|
|
219
|
+
errors.push(
|
|
220
|
+
`cannot read directory: ${relative(cwd, current) || current}: ${errorCode(error)}`,
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
for (const entry of entries) {
|
|
227
|
+
const file = join(current, entry.name);
|
|
228
|
+
const rel = relative(dir, file).split(sep).join("/");
|
|
229
|
+
if (prunes(rel)) continue;
|
|
230
|
+
if (ignoredBySources(active, file, entry.isDirectory())) continue;
|
|
231
|
+
|
|
232
|
+
if (entry.isDirectory()) walk(file, active);
|
|
233
|
+
else if (entry.isFile() && isCandidate(rel, keepGenerated)) files.push(resolve(file));
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const ancestors: string[] = [];
|
|
238
|
+
for (let current = dir; !existsSync(join(current, ".git")) && dirname(current) !== current;) {
|
|
239
|
+
current = dirname(current);
|
|
240
|
+
ancestors.unshift(current);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
let inherited: IgnoreSource[] = [];
|
|
244
|
+
for (const [index, ancestor] of ancestors.entries()) {
|
|
245
|
+
inherited = withIgnoreFile(ancestor, inherited);
|
|
246
|
+
const below = ancestors[index + 1] ?? dir;
|
|
247
|
+
if (ignoredBySources(inherited, below, true)) return { files, errors };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
walk(dir, inherited);
|
|
251
|
+
return { files, errors };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export type Location =
|
|
255
|
+
| { kind: "repository"; root: string }
|
|
256
|
+
| { kind: "outside" }
|
|
257
|
+
| { kind: "failed"; error: string };
|
|
258
|
+
|
|
259
|
+
function ceilingDirectories(): Set<string> {
|
|
260
|
+
return new Set(
|
|
261
|
+
(process.env.GIT_CEILING_DIRECTORIES ?? "")
|
|
262
|
+
.split(delimiter)
|
|
263
|
+
.filter((path) => isAbsolute(path))
|
|
264
|
+
.map((path) => (existsSync(path) ? realpathSync(path) : resolve(path))),
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function hasGitMarker(dir: string): boolean {
|
|
269
|
+
if (dir.split(sep).includes(".git")) return false;
|
|
270
|
+
|
|
271
|
+
const ceilings = ceilingDirectories();
|
|
272
|
+
for (let current = realpathSync(dir); ; current = dirname(current)) {
|
|
273
|
+
if (existsSync(join(current, ".git"))) return true;
|
|
274
|
+
const parent = dirname(current);
|
|
275
|
+
if (parent === current || ceilings.has(parent)) return false;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export function locate(dir: string): Location {
|
|
280
|
+
if (!hasGit()) return { kind: "outside" };
|
|
281
|
+
|
|
282
|
+
const result = runGit(dir, ["rev-parse", "--show-toplevel"]);
|
|
283
|
+
const root = result.ok ? result.output.trim() : "";
|
|
284
|
+
if (root) return { kind: "repository", root };
|
|
285
|
+
if (!result.ok && hasGitMarker(dir)) return { kind: "failed", error: result.error };
|
|
286
|
+
return { kind: "outside" };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function repositoryPath(root: string, file: string): string {
|
|
290
|
+
return relative(root, file).split(sep).join("/");
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function within(root: string, path: string): boolean {
|
|
294
|
+
const pathFromRoot = relative(root, path);
|
|
295
|
+
return pathFromRoot !== ".." && !pathFromRoot.startsWith(`..${sep}`) && !isAbsolute(pathFromRoot);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function suppliedBelow(anchor: string, path: string): string {
|
|
299
|
+
for (let current = dirname(path); ; current = dirname(current)) {
|
|
300
|
+
if (existsSync(current) && realpathSync(current) === anchor)
|
|
301
|
+
return repositoryPath(current, path);
|
|
302
|
+
|
|
303
|
+
if (dirname(current) === current) return basename(path);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function selectedBelow(
|
|
308
|
+
anchor: string,
|
|
309
|
+
supplied: string,
|
|
310
|
+
file: string,
|
|
311
|
+
keepGenerated = false,
|
|
312
|
+
): boolean {
|
|
313
|
+
return (
|
|
314
|
+
isCandidate(repositoryPath(anchor, file), keepGenerated) &&
|
|
315
|
+
isCandidate(suppliedBelow(anchor, supplied), keepGenerated)
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function isSet(value: string | undefined): boolean {
|
|
320
|
+
return value === "true" || value === "set";
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
type Attributes = { ok: true; values: Map<string, string> } | { ok: false; error: string };
|
|
324
|
+
|
|
325
|
+
function readAttributes(
|
|
326
|
+
files: string[],
|
|
327
|
+
root: string,
|
|
328
|
+
names: string[],
|
|
329
|
+
source: "worktree" | "index",
|
|
330
|
+
): Attributes {
|
|
331
|
+
if (files.length === 0) return { ok: true, values: new Map() };
|
|
332
|
+
|
|
333
|
+
const paths = files.map((file) => `${repositoryPath(root, file)}\0`).join("");
|
|
334
|
+
const result = runGit(
|
|
335
|
+
root,
|
|
336
|
+
["check-attr", ...(source === "index" ? ["--cached"] : []), ...names, "-z", "--stdin"],
|
|
337
|
+
new TextEncoder().encode(paths),
|
|
338
|
+
);
|
|
339
|
+
|
|
340
|
+
if (!result.ok) return result;
|
|
341
|
+
|
|
342
|
+
const values = new Map<string, string>();
|
|
343
|
+
const fields = result.output.split("\0");
|
|
344
|
+
for (let index = 0; index + 2 < fields.length; index += 3)
|
|
345
|
+
values.set(`${fields[index]}\0${fields[index + 1]}`, fields[index + 2]!);
|
|
346
|
+
|
|
347
|
+
return { ok: true, values };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function attribute(
|
|
351
|
+
attributes: Map<string, string>,
|
|
352
|
+
root: string,
|
|
353
|
+
file: string,
|
|
354
|
+
name: string,
|
|
355
|
+
): string | undefined {
|
|
356
|
+
return attributes.get(`${repositoryPath(root, file)}\0${name}`);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function dropGeneratedAttributes(files: string[], root: string): Selection {
|
|
360
|
+
const read = readAttributes(files, root, ["linguist-generated"], "worktree");
|
|
361
|
+
if (!read.ok) return read;
|
|
362
|
+
|
|
363
|
+
return {
|
|
364
|
+
ok: true,
|
|
365
|
+
files: files.filter((file) => !isSet(attribute(read.values, root, file, "linguist-generated"))),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function directoryFiles(dir: string, root: string, keepGenerated: boolean): Selection {
|
|
370
|
+
const result = runGit(dir, [
|
|
371
|
+
"ls-files",
|
|
372
|
+
"-z",
|
|
373
|
+
"--cached",
|
|
374
|
+
"--others",
|
|
375
|
+
"--exclude-standard",
|
|
376
|
+
"--",
|
|
377
|
+
".",
|
|
378
|
+
]);
|
|
379
|
+
|
|
380
|
+
if (!result.ok) return result;
|
|
381
|
+
|
|
382
|
+
const files = nulItems(result.output)
|
|
383
|
+
.filter((path) => isCandidate(path, keepGenerated))
|
|
384
|
+
.map((path) => resolve(dir, path))
|
|
385
|
+
.filter((path) => existsSync(path) && lstatSync(path).isFile());
|
|
386
|
+
|
|
387
|
+
const inside = files.map((path) => fileRealpath(path)).filter((path) => within(root, path));
|
|
388
|
+
return { ok: true, files: inside };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function fileRealpath(path: string): string {
|
|
392
|
+
try {
|
|
393
|
+
return realpathSync(path);
|
|
394
|
+
} catch (error: unknown) {
|
|
395
|
+
if (lstatSync(path).isFile()) return join(realpathSync(dirname(path)), basename(path));
|
|
396
|
+
throw error;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function sorted(files: string[]): string[] {
|
|
401
|
+
return [...new Set(files)].sort((left, right) => left.localeCompare(right));
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
export function collectFiles(paths: string[], cwd: string, keepGenerated = false): Collected {
|
|
405
|
+
const locations = new Map<string, Location>();
|
|
406
|
+
const byRoot = new Map<string, string[]>();
|
|
407
|
+
const outside: string[] = [];
|
|
408
|
+
const errors: string[] = [];
|
|
409
|
+
const warnings = hasGit()
|
|
410
|
+
? []
|
|
411
|
+
: ["git not found on PATH, file selection fell back to the directory walk"];
|
|
412
|
+
|
|
413
|
+
function locationOf(dir: string): Location {
|
|
414
|
+
const known = locations.get(dir);
|
|
415
|
+
if (known) return known;
|
|
416
|
+
|
|
417
|
+
const location = locate(dir);
|
|
418
|
+
locations.set(dir, location);
|
|
419
|
+
return location;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function add(root: string, files: string[]): void {
|
|
423
|
+
const listed = byRoot.get(root);
|
|
424
|
+
if (listed) listed.push(...files);
|
|
425
|
+
else byRoot.set(root, files);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
for (const input of paths) {
|
|
429
|
+
const path = isAbsolute(input) ? input : resolve(cwd, input);
|
|
430
|
+
if (!existsSync(path)) {
|
|
431
|
+
errors.push(`no such file: ${input}`);
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
let directory = false;
|
|
436
|
+
try {
|
|
437
|
+
directory = statSync(path).isDirectory();
|
|
438
|
+
} catch {}
|
|
439
|
+
|
|
440
|
+
if (directory) {
|
|
441
|
+
const location = locationOf(path);
|
|
442
|
+
if (location.kind === "failed") {
|
|
443
|
+
errors.push(location.error);
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (location.kind === "outside") {
|
|
448
|
+
const fallback = fallbackFiles(path, cwd, keepGenerated);
|
|
449
|
+
outside.push(...fallback.files);
|
|
450
|
+
errors.push(...fallback.errors);
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const listed = directoryFiles(path, location.root, keepGenerated);
|
|
455
|
+
if (listed.ok) add(location.root, listed.files);
|
|
456
|
+
else errors.push(listed.error);
|
|
457
|
+
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
if (entryFor(path) === undefined) {
|
|
462
|
+
errors.push(`not a TypeScript or JavaScript file: ${input}`);
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const file = fileRealpath(path);
|
|
467
|
+
const location = locationOf(dirname(file));
|
|
468
|
+
if (location.kind === "failed") {
|
|
469
|
+
errors.push(location.error);
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
const anchor = location.kind === "repository" ? location.root : dirname(file);
|
|
474
|
+
if (!selectedBelow(anchor, path, file, keepGenerated)) continue;
|
|
475
|
+
|
|
476
|
+
if (location.kind === "outside") outside.push(file);
|
|
477
|
+
else add(location.root, [file]);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const files = [...outside];
|
|
481
|
+
for (const [root, candidates] of byRoot) {
|
|
482
|
+
if (keepGenerated) {
|
|
483
|
+
files.push(...candidates);
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const kept = dropGeneratedAttributes(candidates, root);
|
|
488
|
+
if (kept.ok) files.push(...kept.files);
|
|
489
|
+
else errors.push(kept.error);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
return { files: sorted(files), errors: [...new Set(errors)], warnings };
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function existingAncestor(path: string): string {
|
|
496
|
+
const parent = dirname(path);
|
|
497
|
+
return existsSync(path) || parent === path ? path : existingAncestor(parent);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
export type StdinTarget =
|
|
501
|
+
| { status: "format"; path: string; root: string | undefined }
|
|
502
|
+
| { status: "skip" }
|
|
503
|
+
| { status: "unsupported"; error: string }
|
|
504
|
+
| { status: "failed"; error: string };
|
|
505
|
+
|
|
506
|
+
export function stdinTarget(input: string, cwd: string): StdinTarget {
|
|
507
|
+
const path = isAbsolute(input) ? input : resolve(cwd, input);
|
|
508
|
+
if (entryFor(path) === undefined)
|
|
509
|
+
return { status: "unsupported", error: `not a TypeScript or JavaScript file: ${input}` };
|
|
510
|
+
|
|
511
|
+
const directory = existingAncestor(dirname(path));
|
|
512
|
+
const real = realpathSync(directory);
|
|
513
|
+
const file = join(real, relative(directory, path));
|
|
514
|
+
|
|
515
|
+
const location = locate(real);
|
|
516
|
+
if (location.kind === "failed") return { status: "failed", error: location.error };
|
|
517
|
+
|
|
518
|
+
const anchor = location.kind === "repository" ? location.root : dirname(file);
|
|
519
|
+
if (!selectedBelow(anchor, path, file)) return { status: "skip" };
|
|
520
|
+
if (location.kind === "outside") return { status: "format", path: file, root: undefined };
|
|
521
|
+
|
|
522
|
+
const kept = dropGeneratedAttributes([file], location.root);
|
|
523
|
+
if (!kept.ok) return { status: "failed", error: kept.error };
|
|
524
|
+
if (kept.files.length === 0) return { status: "skip" };
|
|
525
|
+
|
|
526
|
+
return { status: "format", path: file, root: location.root };
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
export function landsWithin(root: string, path: string): boolean {
|
|
530
|
+
try {
|
|
531
|
+
let entry = path;
|
|
532
|
+
while (!lstatSync(entry, { throwIfNoEntry: false }) && dirname(entry) !== entry)
|
|
533
|
+
entry = dirname(entry);
|
|
534
|
+
|
|
535
|
+
return within(root, realpathSync(entry));
|
|
536
|
+
} catch {
|
|
537
|
+
return false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
export function ignoredByGit(root: string, path: string): boolean {
|
|
542
|
+
return runGit(root, ["check-ignore", "-q", "--", repositoryPath(root, path)]).ok;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
export function trackedInHead(root: string, path: string): boolean {
|
|
546
|
+
return runGit(root, ["cat-file", "-e", `HEAD:${repositoryPath(root, path)}`]).ok;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
function diffSections(text: string): string[][] {
|
|
550
|
+
const sections: string[][] = [];
|
|
551
|
+
for (const line of text.split("\n")) {
|
|
552
|
+
if (line.startsWith("diff --git ") && sections.at(-1)?.[0] !== line) sections.push([]);
|
|
553
|
+
sections.at(-1)?.push(line);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
return sections;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
type ChangedLines = { ok: true; lines: Changed[] } | { ok: false; error: string };
|
|
560
|
+
|
|
561
|
+
function diffLines(
|
|
562
|
+
root: string,
|
|
563
|
+
range: string[],
|
|
564
|
+
count: number,
|
|
565
|
+
paths: string[] = [],
|
|
566
|
+
): ChangedLines {
|
|
567
|
+
const env = { ...process.env };
|
|
568
|
+
delete env.GIT_DIFF_OPTS;
|
|
569
|
+
const diff = runGit(
|
|
570
|
+
root,
|
|
571
|
+
[
|
|
572
|
+
"-c",
|
|
573
|
+
"diff.suppressBlankEmpty=false",
|
|
574
|
+
"--literal-pathspecs",
|
|
575
|
+
"diff",
|
|
576
|
+
"--unified=999999999",
|
|
577
|
+
"--text",
|
|
578
|
+
"--submodule=short",
|
|
579
|
+
"--no-color",
|
|
580
|
+
"--no-ext-diff",
|
|
581
|
+
"--no-textconv",
|
|
582
|
+
"--no-renames",
|
|
583
|
+
...range,
|
|
584
|
+
"--",
|
|
585
|
+
...paths,
|
|
586
|
+
],
|
|
587
|
+
undefined,
|
|
588
|
+
env,
|
|
589
|
+
);
|
|
590
|
+
|
|
591
|
+
if (!diff.ok) return diff;
|
|
592
|
+
|
|
593
|
+
const sections = diffSections(diff.output);
|
|
594
|
+
if (sections.length !== count)
|
|
595
|
+
return { ok: false, error: "git diff section count differs from the changed file count" };
|
|
596
|
+
|
|
597
|
+
return { ok: true, lines: sections.map(diffChanges) };
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
export function collectChanged(
|
|
601
|
+
cwd: string,
|
|
602
|
+
location: Location = locate(cwd),
|
|
603
|
+
hunks = false,
|
|
604
|
+
written?: Set<string>,
|
|
605
|
+
): Collected & { changedLines: Map<string, Changed> } {
|
|
606
|
+
const changedLines = new Map<string, Changed>();
|
|
607
|
+
if (!hasGit())
|
|
608
|
+
return {
|
|
609
|
+
changedLines,
|
|
610
|
+
files: [],
|
|
611
|
+
errors: ["--changed needs git, which was not found on PATH"],
|
|
612
|
+
warnings: [],
|
|
613
|
+
};
|
|
614
|
+
|
|
615
|
+
if (location.kind === "failed")
|
|
616
|
+
return { files: [], errors: [location.error], warnings: [], changedLines };
|
|
617
|
+
|
|
618
|
+
if (location.kind === "outside")
|
|
619
|
+
return { files: [], errors: ["not inside a git repository"], warnings: [], changedLines };
|
|
620
|
+
|
|
621
|
+
const root = location.root;
|
|
622
|
+
|
|
623
|
+
const born = runGit(root, ["rev-parse", "--verify", "-q", "HEAD"]).ok;
|
|
624
|
+
if (!born) {
|
|
625
|
+
const branch = runGit(root, ["symbolic-ref", "-q", "HEAD"]);
|
|
626
|
+
if (!branch.ok) return { files: [], errors: [branch.error], warnings: [], changedLines };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
const changed = born
|
|
630
|
+
? runGit(root, ["diff", "--name-only", "-z", "--no-renames", "--submodule=short", "HEAD", "--"])
|
|
631
|
+
: runGit(root, ["ls-files", "-z", "--cached"]);
|
|
632
|
+
|
|
633
|
+
const untracked = runGit(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
|
|
634
|
+
if (!changed.ok || !untracked.ok) {
|
|
635
|
+
const errors = [changed, untracked].flatMap((result) => (result.ok ? [] : [result.error]));
|
|
636
|
+
return { files: [], errors: [...new Set(errors)], warnings: [], changedLines };
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
const realRoot = realpathSync(root);
|
|
640
|
+
const kept = (name: string) => written === undefined || written.has(resolve(realRoot, name));
|
|
641
|
+
const names = nulItems(changed.output).filter(kept);
|
|
642
|
+
const candidates = names.filter((name) => isCandidate(name));
|
|
643
|
+
if (hunks && born && candidates.length > 0) {
|
|
644
|
+
const diff = diffLines(root, ["HEAD"], candidates.length, candidates);
|
|
645
|
+
if (!diff.ok) return { files: [], errors: [diff.error], warnings: [], changedLines };
|
|
646
|
+
|
|
647
|
+
for (let index = 0; index < candidates.length; index++)
|
|
648
|
+
changedLines.set(resolve(root, candidates[index]!), diff.lines[index]!);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
const untrackedNames = nulItems(untracked.output).filter(kept);
|
|
652
|
+
for (const name of untrackedNames) changedLines.delete(resolve(root, name));
|
|
653
|
+
|
|
654
|
+
const files = [...names, ...untrackedNames]
|
|
655
|
+
.filter((path) => isCandidate(path))
|
|
656
|
+
.map((path) => resolve(root, path))
|
|
657
|
+
.filter((path) => existsSync(path) && lstatSync(path).isFile())
|
|
658
|
+
.filter((path) => within(realRoot, fileRealpath(path)));
|
|
659
|
+
|
|
660
|
+
const generated = dropGeneratedAttributes(files, root);
|
|
661
|
+
if (!generated.ok) return { files: [], errors: [generated.error], warnings: [], changedLines };
|
|
662
|
+
|
|
663
|
+
return { files: sorted(generated.files), errors: [], warnings: [], changedLines };
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
export interface StagedFile {
|
|
667
|
+
path: string;
|
|
668
|
+
bytes: Uint8Array;
|
|
669
|
+
unstaged: boolean;
|
|
670
|
+
lines?: Changed;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
export type StagedSelection = { ok: true; files: StagedFile[] } | { ok: false; error: string };
|
|
674
|
+
|
|
675
|
+
const regularFileModes = new Set(["100644", "100755"]);
|
|
676
|
+
|
|
677
|
+
type Blobs = { ok: true; blobs: Uint8Array[] } | { ok: false; error: string };
|
|
678
|
+
|
|
679
|
+
function readBlobs(root: string, ids: string[]): Blobs {
|
|
680
|
+
if (ids.length === 0) return { ok: true, blobs: [] };
|
|
681
|
+
|
|
682
|
+
const result = runGitBytes(
|
|
683
|
+
root,
|
|
684
|
+
["cat-file", "--batch"],
|
|
685
|
+
new TextEncoder().encode(`${ids.join("\n")}\n`),
|
|
686
|
+
);
|
|
687
|
+
|
|
688
|
+
if (!result.ok) return result;
|
|
689
|
+
|
|
690
|
+
const output = result.output;
|
|
691
|
+
const blobs: Uint8Array[] = [];
|
|
692
|
+
|
|
693
|
+
let offset = 0;
|
|
694
|
+
for (const id of ids) {
|
|
695
|
+
const end = output.indexOf(10, offset);
|
|
696
|
+
const [, type, size] =
|
|
697
|
+
end < 0 ? [] : new TextDecoder().decode(output.subarray(offset, end)).split(" ");
|
|
698
|
+
|
|
699
|
+
if (type !== "blob") return { ok: false, error: `git cat-file could not read blob ${id}` };
|
|
700
|
+
|
|
701
|
+
const start = end + 1;
|
|
702
|
+
blobs.push(output.subarray(start, start + Number(size)));
|
|
703
|
+
offset = start + Number(size) + 1;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
return { ok: true, blobs };
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function readFilteredBlob(
|
|
710
|
+
root: string,
|
|
711
|
+
tree: string | undefined,
|
|
712
|
+
path: string,
|
|
713
|
+
id: string,
|
|
714
|
+
): GitBytes {
|
|
715
|
+
return runGitBytes(root, [
|
|
716
|
+
...(tree === undefined ? [] : [`--attr-source=${tree}`]),
|
|
717
|
+
"cat-file",
|
|
718
|
+
"--filters",
|
|
719
|
+
`--path=${repositoryPath(root, path)}`,
|
|
720
|
+
id,
|
|
721
|
+
]);
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
export function collectStaged(cwd: string, hunks = false): StagedSelection {
|
|
725
|
+
if (!hasGit()) return { ok: false, error: "--staged needs git, which was not found on PATH" };
|
|
726
|
+
|
|
727
|
+
const location = locate(cwd);
|
|
728
|
+
if (location.kind === "failed") return { ok: false, error: location.error };
|
|
729
|
+
if (location.kind === "outside") return { ok: false, error: "not inside a git repository" };
|
|
730
|
+
|
|
731
|
+
const root = location.root;
|
|
732
|
+
const range = ["--cached", "--diff-filter=ACMT"];
|
|
733
|
+
const diff = runGit(root, ["diff", ...range, "--raw", "-z", "--no-renames", "--no-abbrev"]);
|
|
734
|
+
if (!diff.ok) return diff;
|
|
735
|
+
|
|
736
|
+
const items = nulItems(diff.output);
|
|
737
|
+
const blobOf = new Map<string, string>();
|
|
738
|
+
const edited: string[] = [];
|
|
739
|
+
for (let index = 0; index + 1 < items.length; index += 2) {
|
|
740
|
+
const [, mode, , blob, status] = items[index]!.split(" ");
|
|
741
|
+
const name = items[index + 1]!;
|
|
742
|
+
if (
|
|
743
|
+
mode === undefined ||
|
|
744
|
+
blob === undefined ||
|
|
745
|
+
!regularFileModes.has(mode) ||
|
|
746
|
+
!isCandidate(name)
|
|
747
|
+
)
|
|
748
|
+
continue;
|
|
749
|
+
|
|
750
|
+
blobOf.set(resolve(root, name), blob);
|
|
751
|
+
if (status === "M") edited.push(name);
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
const changed =
|
|
755
|
+
hunks && edited.length > 0 ? diffLines(root, range, edited.length, edited) : undefined;
|
|
756
|
+
|
|
757
|
+
if (changed && !changed.ok) return changed;
|
|
758
|
+
|
|
759
|
+
const linesOf = new Map(
|
|
760
|
+
edited.map((name, index) => [resolve(root, name), changed?.lines[index]]),
|
|
761
|
+
);
|
|
762
|
+
|
|
763
|
+
const attributes = readAttributes(
|
|
764
|
+
[...blobOf.keys()],
|
|
765
|
+
root,
|
|
766
|
+
["linguist-generated", "filter"],
|
|
767
|
+
"index",
|
|
768
|
+
);
|
|
769
|
+
|
|
770
|
+
if (!attributes.ok) return attributes;
|
|
771
|
+
|
|
772
|
+
const unstaged = runGit(root, ["diff", "--name-only", "-z", "--no-renames"]);
|
|
773
|
+
if (!unstaged.ok) return unstaged;
|
|
774
|
+
|
|
775
|
+
const dirty = new Set(nulItems(unstaged.output).map((path) => resolve(root, path)));
|
|
776
|
+
const paths = sorted([...blobOf.keys()]).filter(
|
|
777
|
+
(path) => !isSet(attribute(attributes.values, root, path, "linguist-generated")),
|
|
778
|
+
);
|
|
779
|
+
|
|
780
|
+
const filtered = (path: string) =>
|
|
781
|
+
!["unspecified", "unset"].includes(
|
|
782
|
+
attribute(attributes.values, root, path, "filter") ?? "unset",
|
|
783
|
+
);
|
|
784
|
+
|
|
785
|
+
const plain = paths.filter((path) => !filtered(path));
|
|
786
|
+
const read = readBlobs(
|
|
787
|
+
root,
|
|
788
|
+
plain.map((path) => blobOf.get(path)!),
|
|
789
|
+
);
|
|
790
|
+
|
|
791
|
+
if (!read.ok) return read;
|
|
792
|
+
|
|
793
|
+
const bytes = new Map(plain.map((path, index) => [path, read.blobs[index]!]));
|
|
794
|
+
const smudge = paths.filter(filtered);
|
|
795
|
+
const worktree = readAttributes(smudge, root, ["filter"], "worktree");
|
|
796
|
+
if (!worktree.ok) return worktree;
|
|
797
|
+
|
|
798
|
+
const diverged = smudge.some(
|
|
799
|
+
(path) =>
|
|
800
|
+
attribute(worktree.values, root, path, "filter") !==
|
|
801
|
+
attribute(attributes.values, root, path, "filter"),
|
|
802
|
+
);
|
|
803
|
+
|
|
804
|
+
const tree = diverged ? runGit(root, ["write-tree"]) : undefined;
|
|
805
|
+
if (tree && !tree.ok) return tree;
|
|
806
|
+
|
|
807
|
+
for (const path of smudge) {
|
|
808
|
+
const smudged = readFilteredBlob(root, tree?.output.trim(), path, blobOf.get(path)!);
|
|
809
|
+
if (!smudged.ok) return smudged;
|
|
810
|
+
bytes.set(path, smudged.output);
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
return {
|
|
814
|
+
ok: true,
|
|
815
|
+
files: paths.map((path) => ({
|
|
816
|
+
path,
|
|
817
|
+
bytes: bytes.get(path)!,
|
|
818
|
+
unstaged: dirty.has(path),
|
|
819
|
+
lines: filtered(path) ? undefined : linesOf.get(path),
|
|
820
|
+
})),
|
|
821
|
+
};
|
|
822
|
+
}
|