@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/cli.ts
ADDED
|
@@ -0,0 +1,820 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { version } from "../package.json" with { type: "json" };
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import {
|
|
5
|
+
accessSync,
|
|
6
|
+
chmodSync,
|
|
7
|
+
constants,
|
|
8
|
+
readFileSync,
|
|
9
|
+
realpathSync,
|
|
10
|
+
renameSync,
|
|
11
|
+
type Stats,
|
|
12
|
+
statSync,
|
|
13
|
+
unlinkSync,
|
|
14
|
+
writeFileSync,
|
|
15
|
+
} from "node:fs";
|
|
16
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
17
|
+
import {
|
|
18
|
+
collectChanged,
|
|
19
|
+
collectFiles,
|
|
20
|
+
collectStaged,
|
|
21
|
+
emptyReason,
|
|
22
|
+
errorCode,
|
|
23
|
+
ignoredByGit,
|
|
24
|
+
isGeneratedHeader,
|
|
25
|
+
landsWithin,
|
|
26
|
+
locate,
|
|
27
|
+
stdinTarget,
|
|
28
|
+
trackedInHead,
|
|
29
|
+
type EmptyReason,
|
|
30
|
+
type Location,
|
|
31
|
+
type StagedFile,
|
|
32
|
+
} from "./files.ts";
|
|
33
|
+
import { explain } from "./engine/explain.ts";
|
|
34
|
+
import { languageOf } from "./languages/index.ts";
|
|
35
|
+
import { blockReason, claudeCodeHooks, hookInput, rereadLine, writtenFiles } from "./hook.ts";
|
|
36
|
+
import type { Changed } from "./engine/model.ts";
|
|
37
|
+
import { RULES } from "./engine/rules.ts";
|
|
38
|
+
import { decode, type Decoded, formatText, withoutMark } from "./step.ts";
|
|
39
|
+
import { compareFindings, type Braces, type Finding, type Mode } from "./engine/types.ts";
|
|
40
|
+
import { columns, flags, usage } from "./usage.ts";
|
|
41
|
+
|
|
42
|
+
declare const STANZA_COMMIT: string | undefined;
|
|
43
|
+
|
|
44
|
+
interface Arguments {
|
|
45
|
+
changed: boolean;
|
|
46
|
+
hunks: boolean;
|
|
47
|
+
json: boolean;
|
|
48
|
+
mode: Mode;
|
|
49
|
+
braces: Braces | undefined;
|
|
50
|
+
paths: string[];
|
|
51
|
+
staged: boolean;
|
|
52
|
+
stdin: string | undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface ExplainArguments {
|
|
56
|
+
path: string;
|
|
57
|
+
line: number;
|
|
58
|
+
noBraces: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
type Writer = (chunk: string | Uint8Array) => void;
|
|
62
|
+
|
|
63
|
+
export interface Io {
|
|
64
|
+
cwd: string;
|
|
65
|
+
env: Readonly<Record<string, string | undefined>>;
|
|
66
|
+
stdin: () => Uint8Array;
|
|
67
|
+
stdout: Writer;
|
|
68
|
+
stderr: Writer;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface Input {
|
|
72
|
+
path: string;
|
|
73
|
+
read: () => Decoded;
|
|
74
|
+
changedLines?: Changed | undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface Run {
|
|
78
|
+
cwd: string;
|
|
79
|
+
mode: Mode;
|
|
80
|
+
braces: Braces | undefined;
|
|
81
|
+
write: boolean;
|
|
82
|
+
display?: (path: string) => string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface Formatted {
|
|
86
|
+
findings: Finding[];
|
|
87
|
+
failed: boolean;
|
|
88
|
+
rewritten: string[];
|
|
89
|
+
kept: Map<string, string>;
|
|
90
|
+
unread: Set<string>;
|
|
91
|
+
unreadWidth: Set<string>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function ignoreBrokenPipe(error: NodeJS.ErrnoException): void {
|
|
95
|
+
if (error.code !== "EPIPE") throw error;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function systemIo(): Io {
|
|
99
|
+
// Under Bun a stream write throws EPIPE into a stack trace and exit 1, where console.log swallowed it.
|
|
100
|
+
process.stdout.on("error", ignoreBrokenPipe);
|
|
101
|
+
process.stderr.on("error", ignoreBrokenPipe);
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
cwd: process.cwd(),
|
|
105
|
+
env: process.env,
|
|
106
|
+
stdin: () => readFileSync(0),
|
|
107
|
+
stdout: (chunk) => {
|
|
108
|
+
process.stdout.write(chunk);
|
|
109
|
+
},
|
|
110
|
+
stderr: (chunk) => {
|
|
111
|
+
process.stderr.write(chunk);
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const switches = new Set(["--braces", "--changed", "--hunks", "--json", "--no-braces", "--staged"]);
|
|
117
|
+
const standalone = new Set(["--help", "-h", "--version"]);
|
|
118
|
+
const hookSwitches = new Set(["--braces", "--hunks", "--no-braces"]);
|
|
119
|
+
const bothBraces = "use one of --braces or --no-braces";
|
|
120
|
+
|
|
121
|
+
function help(): string {
|
|
122
|
+
const rules = Object.entries(RULES).map(([id, rule]) => [
|
|
123
|
+
` ${id}`,
|
|
124
|
+
rule.fixable ? "fix" : "check",
|
|
125
|
+
rule.summary,
|
|
126
|
+
]);
|
|
127
|
+
|
|
128
|
+
return [
|
|
129
|
+
usage,
|
|
130
|
+
"",
|
|
131
|
+
...columns(flags),
|
|
132
|
+
"",
|
|
133
|
+
"Claude Code .claude/settings.json:",
|
|
134
|
+
claudeCodeHooks,
|
|
135
|
+
"",
|
|
136
|
+
"Rules:",
|
|
137
|
+
...columns(rules),
|
|
138
|
+
].join("\n");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function parseExplain(args: string[]): ExplainArguments | { error: string } {
|
|
142
|
+
const targets = args.filter((arg) => arg !== "--no-braces");
|
|
143
|
+
if (args.length - targets.length > 1) return { error: "--no-braces given twice" };
|
|
144
|
+
|
|
145
|
+
const unexpected = targets.find((arg) => arg.startsWith("-")) ?? targets[1];
|
|
146
|
+
if (unexpected !== undefined) return { error: `unexpected argument ${unexpected}` };
|
|
147
|
+
|
|
148
|
+
const match = /^(.+):(\d+)$/.exec(targets[0] ?? "");
|
|
149
|
+
if (!match) return { error: "explain needs <file>:<line>" };
|
|
150
|
+
|
|
151
|
+
const line = Number(match[2]);
|
|
152
|
+
if (line < 1) return { error: `${targets[0]}: the line must be 1 or more` };
|
|
153
|
+
|
|
154
|
+
return { path: match[1]!, line, noBraces: targets.length < args.length };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function bracesFlag(given: (flag: string) => boolean): Arguments["braces"] {
|
|
158
|
+
if (given("--braces")) return "on";
|
|
159
|
+
if (given("--no-braces")) return "off";
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function parseArguments(args: string[]): Arguments | { error: string } {
|
|
163
|
+
const paths: string[] = [];
|
|
164
|
+
const seen = new Set<string>();
|
|
165
|
+
const queue = args.values();
|
|
166
|
+
|
|
167
|
+
let mode: Mode | undefined;
|
|
168
|
+
let stdin: string | undefined;
|
|
169
|
+
for (const arg of queue) {
|
|
170
|
+
if (arg === "--") {
|
|
171
|
+
paths.push(...queue);
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (arg === "--fix" || arg === "--check") {
|
|
176
|
+
if (mode !== undefined) return { error: "use one of --fix or --check" };
|
|
177
|
+
mode = arg.slice(2) as Mode;
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (switches.has(arg)) {
|
|
182
|
+
if (seen.has(arg)) return { error: `${arg} given twice` };
|
|
183
|
+
seen.add(arg);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (arg === "--stdin") {
|
|
188
|
+
const path = queue.next().value;
|
|
189
|
+
if (stdin !== undefined) return { error: "--stdin given twice" };
|
|
190
|
+
if (path === undefined || path.startsWith("-")) return { error: "--stdin needs a path" };
|
|
191
|
+
|
|
192
|
+
stdin = path;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (standalone.has(arg)) return { error: `${arg} takes no other arguments` };
|
|
197
|
+
if (arg.startsWith("-")) return { error: `unknown flag ${arg}` };
|
|
198
|
+
|
|
199
|
+
paths.push(arg);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const changed = seen.has("--changed");
|
|
203
|
+
const hunks = seen.has("--hunks");
|
|
204
|
+
const staged = seen.has("--staged");
|
|
205
|
+
const sources = [changed, staged, paths.length > 0, stdin !== undefined].filter(Boolean).length;
|
|
206
|
+
if (mode === undefined) return { error: "--fix or --check is required" };
|
|
207
|
+
if (sources === 0)
|
|
208
|
+
return { error: "nothing to format: give paths, --changed, --staged or --stdin <path>" };
|
|
209
|
+
|
|
210
|
+
if (sources > 1) return { error: "use only one of --changed, --staged, --stdin or paths" };
|
|
211
|
+
if (staged && mode === "fix") return { error: "--staged works only with --check" };
|
|
212
|
+
if (hunks && !changed && !staged) return { error: "--hunks needs --changed or --staged" };
|
|
213
|
+
if (seen.has("--braces") && seen.has("--no-braces")) return { error: bothBraces };
|
|
214
|
+
|
|
215
|
+
return {
|
|
216
|
+
changed,
|
|
217
|
+
hunks,
|
|
218
|
+
json: seen.has("--json"),
|
|
219
|
+
mode,
|
|
220
|
+
braces: bracesFlag((flag) => seen.has(flag)),
|
|
221
|
+
paths,
|
|
222
|
+
staged,
|
|
223
|
+
stdin,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function printedPath(path: string, cwd: string): string {
|
|
228
|
+
const output = relative(cwd, path);
|
|
229
|
+
return output || path;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function printFindings(findings: Finding[], json: boolean, print: (line: string) => void): void {
|
|
233
|
+
if (json) {
|
|
234
|
+
print(JSON.stringify(findings));
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
for (const finding of findings)
|
|
239
|
+
print(`${finding.path}:${finding.line}:${finding.col} ${finding.rule} ${finding.message}`);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function readText(path: string): Decoded {
|
|
243
|
+
try {
|
|
244
|
+
return decode(readFileSync(path));
|
|
245
|
+
} catch (error: unknown) {
|
|
246
|
+
return { message: String(error) };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function runStdin(input: string, args: Arguments, io: Io): number {
|
|
251
|
+
let source: Uint8Array;
|
|
252
|
+
try {
|
|
253
|
+
source = io.stdin();
|
|
254
|
+
} catch (error: unknown) {
|
|
255
|
+
const message = `cannot read stdin: ${errorCode(error)}`;
|
|
256
|
+
warn(io, `stanza: ${message}`);
|
|
257
|
+
return status([message], { failed: false, findings: [] });
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const target = stdinTarget(input, io.cwd);
|
|
261
|
+
const inputs =
|
|
262
|
+
target.status === "format" ? [{ path: target.path, read: () => decode(source) }] : [];
|
|
263
|
+
|
|
264
|
+
const result = formatInputs(inputs, {
|
|
265
|
+
cwd: io.cwd,
|
|
266
|
+
mode: args.mode,
|
|
267
|
+
braces: args.braces,
|
|
268
|
+
write: false,
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
const fix = args.mode === "fix";
|
|
272
|
+
if (fix)
|
|
273
|
+
io.stdout((target.status === "format" ? result.kept.get(target.path) : undefined) ?? source);
|
|
274
|
+
|
|
275
|
+
printFindings(result.findings, args.json, (line) => (fix ? io.stderr : io.stdout)(`${line}\n`));
|
|
276
|
+
|
|
277
|
+
if (!(fix && args.json)) warnUnread(io, io.cwd, result.unread, result.unreadWidth);
|
|
278
|
+
|
|
279
|
+
const errors =
|
|
280
|
+
target.status === "unsupported" || target.status === "failed" ? [target.error] : [];
|
|
281
|
+
|
|
282
|
+
for (const error of errors) warn(io, `stanza: ${error}`);
|
|
283
|
+
|
|
284
|
+
return status(errors, result);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function runExplain(argv: string[], io: Io): number {
|
|
288
|
+
const { cwd } = io;
|
|
289
|
+
const args = parseExplain(argv);
|
|
290
|
+
if ("error" in args) {
|
|
291
|
+
warn(io, `stanza: ${args.error}\n${usage}`);
|
|
292
|
+
return 2;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const target = stdinTarget(args.path, cwd);
|
|
296
|
+
if (target.status === "unsupported" || target.status === "failed") {
|
|
297
|
+
warn(io, `stanza: ${target.error}`);
|
|
298
|
+
return 2;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
let bytes: Uint8Array;
|
|
302
|
+
try {
|
|
303
|
+
bytes = readFileSync(resolve(cwd, args.path));
|
|
304
|
+
} catch (error: unknown) {
|
|
305
|
+
const code = errorCode(error);
|
|
306
|
+
const failure =
|
|
307
|
+
code === "ENOENT" ? `no such file: ${args.path}` : `cannot read ${args.path}: ${code}`;
|
|
308
|
+
|
|
309
|
+
warn(io, `stanza: ${failure}`);
|
|
310
|
+
return 2;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const text = decode(bytes);
|
|
314
|
+
if (typeof text !== "string") {
|
|
315
|
+
warn(io, `stanza: ${args.path}: ${text.message}`);
|
|
316
|
+
return 2;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const root = realpathSync(cwd);
|
|
320
|
+
const body = withoutMark(text);
|
|
321
|
+
const result = explain({
|
|
322
|
+
language: languageOf(args.path),
|
|
323
|
+
path: realpathSync(resolve(cwd, args.path)),
|
|
324
|
+
text: body,
|
|
325
|
+
line: args.line,
|
|
326
|
+
braces: args.noBraces ? "off" : undefined,
|
|
327
|
+
display: (path) => printedPath(path, root),
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
if ("error" in result) {
|
|
331
|
+
warn(io, `stanza: ${result.error}`);
|
|
332
|
+
return 2;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
for (const line of result.lines) io.stdout(`${line}\n`);
|
|
336
|
+
|
|
337
|
+
if (target.status === "skip" || isGeneratedHeader(body))
|
|
338
|
+
io.stdout("\nnote: --fix and --check skip this file as generated or excluded\n");
|
|
339
|
+
|
|
340
|
+
return result.found ? 0 : 1;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function removeQuietly(path: string): void {
|
|
344
|
+
try {
|
|
345
|
+
unlinkSync(path);
|
|
346
|
+
} catch {}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function replaceFile(real: string, text: string, target: Stats): boolean {
|
|
350
|
+
const temp = join(dirname(real), `.stanza-${randomUUID()}.tmp`);
|
|
351
|
+
try {
|
|
352
|
+
writeFileSync(temp, text, { encoding: "utf8", flag: "wx", mode: 0o600 });
|
|
353
|
+
} catch (error: unknown) {
|
|
354
|
+
removeQuietly(temp);
|
|
355
|
+
if (["EACCES", "EPERM"].includes(errorCode(error))) return false;
|
|
356
|
+
throw error;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
try {
|
|
360
|
+
const created = statSync(temp);
|
|
361
|
+
if (created.uid !== target.uid || created.gid !== target.gid) {
|
|
362
|
+
removeQuietly(temp);
|
|
363
|
+
return false;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
chmodSync(temp, target.mode & 0o7777);
|
|
367
|
+
renameSync(temp, real);
|
|
368
|
+
return true;
|
|
369
|
+
} catch (error: unknown) {
|
|
370
|
+
removeQuietly(temp);
|
|
371
|
+
throw error;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function writeInPlace(real: string, text: string): void {
|
|
376
|
+
const original = readFileSync(real);
|
|
377
|
+
try {
|
|
378
|
+
writeFileSync(real, text, "utf8");
|
|
379
|
+
} catch (error: unknown) {
|
|
380
|
+
try {
|
|
381
|
+
writeFileSync(real, original);
|
|
382
|
+
} catch {}
|
|
383
|
+
|
|
384
|
+
throw error;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function writeFixed(path: string, text: string, output: string): Finding | undefined {
|
|
389
|
+
try {
|
|
390
|
+
const real = realpathSync(path);
|
|
391
|
+
const target = statSync(real);
|
|
392
|
+
accessSync(real, constants.W_OK);
|
|
393
|
+
|
|
394
|
+
if (target.nlink > 1 || !replaceFile(real, text, target)) writeInPlace(real, text);
|
|
395
|
+
} catch (error: unknown) {
|
|
396
|
+
return { path: output, line: 1, col: 1, rule: "write", message: String(error), fixable: false };
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function formatInputs(inputs: Input[], run: Run): Formatted {
|
|
401
|
+
const findings: Finding[] = [];
|
|
402
|
+
const rewritten: string[] = [];
|
|
403
|
+
const kept = new Map<string, string>();
|
|
404
|
+
const unread = new Set<string>();
|
|
405
|
+
const unreadWidth = new Set<string>();
|
|
406
|
+
|
|
407
|
+
let failed = false;
|
|
408
|
+
for (const input of inputs) {
|
|
409
|
+
const output = run.display?.(input.path) ?? printedPath(input.path, run.cwd);
|
|
410
|
+
const result = formatText(input.path, input.read(), {
|
|
411
|
+
mode: run.mode,
|
|
412
|
+
braces: run.braces,
|
|
413
|
+
changedLines: input.changedLines,
|
|
414
|
+
unread,
|
|
415
|
+
unreadWidth,
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
findings.push(...result.findings.map((finding) => ({ ...finding, path: output })));
|
|
419
|
+
failed ||= result.parseError;
|
|
420
|
+
|
|
421
|
+
if (result.fixed === undefined) continue;
|
|
422
|
+
|
|
423
|
+
if (!run.write) {
|
|
424
|
+
kept.set(input.path, result.fixed);
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const unwritten = writeFixed(input.path, result.fixed, output);
|
|
429
|
+
if (unwritten) {
|
|
430
|
+
findings.push(unwritten);
|
|
431
|
+
failed = true;
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
rewritten.push(output);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
return { findings: findings.sort(compareFindings), failed, rewritten, kept, unread, unreadWidth };
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function status(
|
|
442
|
+
errors: readonly string[],
|
|
443
|
+
formatted: { failed: boolean; findings: Finding[] },
|
|
444
|
+
): number {
|
|
445
|
+
if (errors.length > 0 || formatted.failed) return 2;
|
|
446
|
+
return formatted.findings.length > 0 ? 1 : 0;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function runFiles(args: Arguments, io: Io): number {
|
|
450
|
+
const { cwd } = io;
|
|
451
|
+
|
|
452
|
+
let changed: ReturnType<typeof collectChanged> | undefined;
|
|
453
|
+
let collected: ReturnType<typeof collectFiles>;
|
|
454
|
+
let reason: EmptyReason | undefined;
|
|
455
|
+
try {
|
|
456
|
+
changed = args.changed ? collectChanged(cwd, locate(cwd), args.hunks) : undefined;
|
|
457
|
+
collected = changed ?? collectFiles(args.paths, cwd);
|
|
458
|
+
if (args.paths.length > 0 && collected.files.length === 0 && collected.errors.length === 0)
|
|
459
|
+
reason = emptyReason(args.paths, cwd);
|
|
460
|
+
} catch (error: unknown) {
|
|
461
|
+
warn(
|
|
462
|
+
io,
|
|
463
|
+
`stanza: file selection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
464
|
+
);
|
|
465
|
+
|
|
466
|
+
return 2;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
for (const warning of collected.warnings) warn(io, `stanza: ${warning}`);
|
|
470
|
+
|
|
471
|
+
if (reason !== undefined) {
|
|
472
|
+
const paths = args.paths.join(", ");
|
|
473
|
+
const messages: Record<EmptyReason, string> = {
|
|
474
|
+
generated: `stanza: nothing to format in ${paths}, generated files are skipped`,
|
|
475
|
+
ignored: `stanza: nothing to format in ${paths}, git ignores its files`,
|
|
476
|
+
skipped: `stanza: nothing to format in ${paths}, its files are always skipped`,
|
|
477
|
+
none: `stanza: no TypeScript or JavaScript files under ${paths}`,
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
warn(io, messages[reason]);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const result = formatInputs(
|
|
484
|
+
collected.files.map((path) => ({
|
|
485
|
+
path,
|
|
486
|
+
read: () => readText(path),
|
|
487
|
+
changedLines: args.hunks ? changed?.changedLines?.get(path) : undefined,
|
|
488
|
+
})),
|
|
489
|
+
{ cwd, mode: args.mode, braces: args.braces, write: true },
|
|
490
|
+
);
|
|
491
|
+
|
|
492
|
+
printFindings(result.findings, args.json, (line) => io.stdout(`${line}\n`));
|
|
493
|
+
|
|
494
|
+
for (const error of collected.errors) warn(io, `stanza: ${error}`);
|
|
495
|
+
|
|
496
|
+
warnUnread(io, cwd, result.unread, result.unreadWidth);
|
|
497
|
+
return status(collected.errors, result);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function shellWord(word: string): string {
|
|
501
|
+
return /^[\w@%+:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function repairLines(
|
|
505
|
+
findings: Finding[],
|
|
506
|
+
files: StagedFile[],
|
|
507
|
+
cwd: string,
|
|
508
|
+
braces: Braces | undefined,
|
|
509
|
+
): string[] {
|
|
510
|
+
const fixable = new Set(
|
|
511
|
+
findings.filter((finding) => finding.fixable).map((finding) => finding.path),
|
|
512
|
+
);
|
|
513
|
+
|
|
514
|
+
const targets = files.filter((file) => fixable.has(printedPath(file.path, cwd)));
|
|
515
|
+
const scoped = targets.filter((file) => file.lines !== undefined);
|
|
516
|
+
const whole = targets.filter((file) => file.lines === undefined);
|
|
517
|
+
const dirty = whole.filter((file) => file.unstaged);
|
|
518
|
+
const clean = whole.filter((file) => !file.unstaged);
|
|
519
|
+
const names = (list: StagedFile[]) =>
|
|
520
|
+
list.map((file) => shellWord(printedPath(file.path, cwd))).join(" ");
|
|
521
|
+
|
|
522
|
+
const lines: string[] = [];
|
|
523
|
+
if (scoped.length > 0)
|
|
524
|
+
lines.push(
|
|
525
|
+
`fix the staged lines of these by hand and restage them with git add -p, --fix would change the whole file: ${names(scoped)}`,
|
|
526
|
+
);
|
|
527
|
+
|
|
528
|
+
if (dirty.length > 0)
|
|
529
|
+
lines.push(
|
|
530
|
+
`these also have unstaged changes, fix them with --fix and restage by hand: ${names(dirty)}`,
|
|
531
|
+
);
|
|
532
|
+
|
|
533
|
+
if (clean.length > 0) {
|
|
534
|
+
const flags = braces === undefined ? "" : { on: " --braces", off: " --no-braces" }[braces];
|
|
535
|
+
|
|
536
|
+
lines.push(
|
|
537
|
+
`fix and restage with: cd ${shellWord(cwd)} && stanza --fix${flags} -- ${names(clean)} && git --literal-pathspecs add -- ${names(clean)}`,
|
|
538
|
+
);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
return lines;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function runStaged(args: Arguments, io: Io): number {
|
|
545
|
+
const collected = collectStaged(io.cwd, args.hunks);
|
|
546
|
+
const files = collected.ok ? collected.files : [];
|
|
547
|
+
const result = formatInputs(
|
|
548
|
+
files.map((file) => ({
|
|
549
|
+
path: file.path,
|
|
550
|
+
read: () => decode(file.bytes),
|
|
551
|
+
changedLines: file.lines,
|
|
552
|
+
})),
|
|
553
|
+
{ cwd: io.cwd, mode: args.mode, braces: args.braces, write: false },
|
|
554
|
+
);
|
|
555
|
+
|
|
556
|
+
printFindings(result.findings, args.json, (line) => io.stdout(`${line}\n`));
|
|
557
|
+
|
|
558
|
+
if (!collected.ok) warn(io, `stanza: ${collected.error}`);
|
|
559
|
+
else for (const line of repairLines(result.findings, files, io.cwd, args.braces)) warn(io, line);
|
|
560
|
+
|
|
561
|
+
warnUnread(io, io.cwd, result.unread, result.unreadWidth);
|
|
562
|
+
return status(collected.ok ? [] : [collected.error], result);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function warn(io: Io, line: string): void {
|
|
566
|
+
io.stderr(`${line}\n`);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function warnUnread(io: Io, cwd: string, unread: Set<string>, unreadWidth: Set<string>): void {
|
|
570
|
+
for (const [fileset, message] of [
|
|
571
|
+
[
|
|
572
|
+
unread,
|
|
573
|
+
(files: string) =>
|
|
574
|
+
`stanza: could not tell whether ${files} enforces braces, so braces stay; pass --braces or --no-braces to settle it`,
|
|
575
|
+
],
|
|
576
|
+
[
|
|
577
|
+
unreadWidth,
|
|
578
|
+
(files: string) =>
|
|
579
|
+
`stanza: could not read the line width from ${files}, so stanza used the next source for it`,
|
|
580
|
+
],
|
|
581
|
+
] as const) {
|
|
582
|
+
if (fileset.size === 0) continue;
|
|
583
|
+
|
|
584
|
+
const files = [...fileset]
|
|
585
|
+
.map((path) => printedPath(path, cwd))
|
|
586
|
+
.sort()
|
|
587
|
+
.join(", ");
|
|
588
|
+
|
|
589
|
+
warn(io, message(files));
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function runWriteHook(
|
|
594
|
+
cwdInput: string,
|
|
595
|
+
toolInput: { file_path: string; content: string } & Record<string, unknown>,
|
|
596
|
+
args: string[],
|
|
597
|
+
io: Io,
|
|
598
|
+
): number {
|
|
599
|
+
let cwd: string;
|
|
600
|
+
try {
|
|
601
|
+
cwd = realpathSync(cwdInput);
|
|
602
|
+
} catch {
|
|
603
|
+
return 0;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
let target: ReturnType<typeof stdinTarget>;
|
|
607
|
+
try {
|
|
608
|
+
target = stdinTarget(toolInput.file_path, cwd);
|
|
609
|
+
} catch {
|
|
610
|
+
return 0;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
if (target.status === "failed") {
|
|
614
|
+
warn(io, `stanza hook: ${target.error}`);
|
|
615
|
+
return 1;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
if (target.status !== "format" || target.root === undefined) return 0;
|
|
619
|
+
if (!landsWithin(target.root, target.path) || ignoredByGit(target.root, target.path)) return 0;
|
|
620
|
+
if (args.includes("--hunks") && trackedInHead(target.root, target.path)) return 0;
|
|
621
|
+
|
|
622
|
+
const result = formatInputs([{ path: target.path, read: () => toolInput.content }], {
|
|
623
|
+
cwd,
|
|
624
|
+
mode: "fix",
|
|
625
|
+
braces: bracesFlag((flag) => args.includes(flag)),
|
|
626
|
+
write: false,
|
|
627
|
+
});
|
|
628
|
+
|
|
629
|
+
const fixed = result.kept.get(target.path);
|
|
630
|
+
if (fixed !== undefined)
|
|
631
|
+
io.stdout(
|
|
632
|
+
`${JSON.stringify({
|
|
633
|
+
hookSpecificOutput: {
|
|
634
|
+
hookEventName: "PreToolUse",
|
|
635
|
+
updatedInput: { ...toolInput, content: fixed },
|
|
636
|
+
additionalContext: `stanza formatted ${toolInput.file_path} before writing it, so read it again before editing.`,
|
|
637
|
+
},
|
|
638
|
+
})}\n`,
|
|
639
|
+
);
|
|
640
|
+
|
|
641
|
+
warnUnread(io, cwd, result.unread, result.unreadWidth);
|
|
642
|
+
return 0;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
interface Repository {
|
|
646
|
+
location: Location;
|
|
647
|
+
written: Set<string> | undefined;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function repositories(cwd: string, written: Set<string> | undefined): Repository[] {
|
|
651
|
+
if (written === undefined) {
|
|
652
|
+
const location = locate(cwd);
|
|
653
|
+
return location.kind === "outside" ? [] : [{ location, written }];
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const found = new Map<string, Repository & { written: Set<string> }>();
|
|
657
|
+
for (const path of written) {
|
|
658
|
+
let real: string;
|
|
659
|
+
try {
|
|
660
|
+
real = realpathSync(path);
|
|
661
|
+
} catch {
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
const location = locate(dirname(path));
|
|
666
|
+
if (location.kind === "outside") continue;
|
|
667
|
+
if (location.kind === "repository" && !landsWithin(location.root, real)) continue;
|
|
668
|
+
|
|
669
|
+
const key = location.kind === "repository" ? location.root : location.error;
|
|
670
|
+
const repository = found.get(key) ?? { location, written: new Set<string>() };
|
|
671
|
+
repository.written.add(real);
|
|
672
|
+
found.set(key, repository);
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
return [...found.values()];
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
function fixChanged(
|
|
679
|
+
cwdInput: string,
|
|
680
|
+
written: Set<string> | undefined,
|
|
681
|
+
args: string[],
|
|
682
|
+
io: Io,
|
|
683
|
+
): Formatted | number {
|
|
684
|
+
let cwd: string;
|
|
685
|
+
try {
|
|
686
|
+
cwd = realpathSync(cwdInput);
|
|
687
|
+
} catch {
|
|
688
|
+
return 0;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
const hunks = args.includes("--hunks");
|
|
692
|
+
const files: string[] = [];
|
|
693
|
+
const changedLines = new Map<string, Changed>();
|
|
694
|
+
|
|
695
|
+
let failed = false;
|
|
696
|
+
for (const { location, written: kept } of repositories(cwd, written)) {
|
|
697
|
+
const collected = collectChanged(cwd, location, hunks, kept);
|
|
698
|
+
for (const warning of collected.warnings) warn(io, `stanza hook: ${warning}`);
|
|
699
|
+
for (const error of collected.errors) warn(io, `stanza hook: ${error}`);
|
|
700
|
+
|
|
701
|
+
failed ||= collected.errors.length > 0;
|
|
702
|
+
files.push(...collected.files);
|
|
703
|
+
for (const [path, lines] of collected.changedLines) changedLines.set(path, lines);
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
if (failed) return 1;
|
|
707
|
+
|
|
708
|
+
const result = formatInputs(
|
|
709
|
+
files.map((path) => ({
|
|
710
|
+
path,
|
|
711
|
+
read: () => readText(path),
|
|
712
|
+
changedLines: hunks ? changedLines.get(path) : undefined,
|
|
713
|
+
})),
|
|
714
|
+
{
|
|
715
|
+
cwd,
|
|
716
|
+
mode: "fix",
|
|
717
|
+
braces: bracesFlag((flag) => args.includes(flag)),
|
|
718
|
+
write: true,
|
|
719
|
+
display: (path) => (landsWithin(cwd, path) ? printedPath(path, cwd) : path),
|
|
720
|
+
},
|
|
721
|
+
);
|
|
722
|
+
|
|
723
|
+
warnUnread(io, cwd, result.unread, result.unreadWidth);
|
|
724
|
+
return result;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
function runStopHook(
|
|
728
|
+
input: { cwd: string; stopHookActive: boolean; transcriptPath: string | undefined },
|
|
729
|
+
args: string[],
|
|
730
|
+
io: Io,
|
|
731
|
+
): number {
|
|
732
|
+
if (input.stopHookActive) return 0;
|
|
733
|
+
|
|
734
|
+
const written =
|
|
735
|
+
input.transcriptPath === undefined ? undefined : writtenFiles(input.transcriptPath);
|
|
736
|
+
|
|
737
|
+
const result = fixChanged(input.cwd, written, args, io);
|
|
738
|
+
if (typeof result === "number") return result;
|
|
739
|
+
|
|
740
|
+
const reason = blockReason(result.findings, result.rewritten);
|
|
741
|
+
if (reason !== undefined) io.stdout(`${JSON.stringify({ decision: "block", reason })}\n`);
|
|
742
|
+
|
|
743
|
+
return 0;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
function runEditHook(input: { cwd: string; paths: string[] }, args: string[], io: Io): number {
|
|
747
|
+
const result = fixChanged(input.cwd, new Set(input.paths), args, io);
|
|
748
|
+
if (typeof result === "number") return result;
|
|
749
|
+
|
|
750
|
+
if (result.rewritten.length > 0)
|
|
751
|
+
io.stdout(
|
|
752
|
+
`${JSON.stringify({
|
|
753
|
+
hookSpecificOutput: {
|
|
754
|
+
hookEventName: "PostToolUse",
|
|
755
|
+
additionalContext: rereadLine("formatted", result.rewritten),
|
|
756
|
+
},
|
|
757
|
+
})}\n`,
|
|
758
|
+
);
|
|
759
|
+
|
|
760
|
+
return 0;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
function runHook(args: string[], io: Io): number {
|
|
764
|
+
if (io.env.AGENT_HOOKS === "0") return 0;
|
|
765
|
+
|
|
766
|
+
const unexpected = args.find(
|
|
767
|
+
(arg, index) => !hookSwitches.has(arg) || args.indexOf(arg) !== index,
|
|
768
|
+
);
|
|
769
|
+
|
|
770
|
+
if (unexpected !== undefined) {
|
|
771
|
+
warn(io, `stanza hook: unexpected argument ${unexpected}\n${usage}`);
|
|
772
|
+
return 1;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
if (args.includes("--braces") && args.includes("--no-braces")) {
|
|
776
|
+
warn(io, `stanza hook: ${bothBraces}\n${usage}`);
|
|
777
|
+
return 1;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
const input = hookInput(Buffer.from(io.stdin()).toString("utf8"), io.cwd);
|
|
781
|
+
if ("error" in input) {
|
|
782
|
+
warn(io, `stanza hook: ${input.error}`);
|
|
783
|
+
return 1;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
if (input.event === "ignored") return 0;
|
|
787
|
+
if (input.event === "write") return runWriteHook(input.cwd, input.toolInput, args, io);
|
|
788
|
+
if (input.event === "edit") return runEditHook(input, args, io);
|
|
789
|
+
return runStopHook(input, args, io);
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
export function main(argv: string[], io: Io): number {
|
|
793
|
+
if (argv[0] === "hook") return runHook(argv.slice(1), io);
|
|
794
|
+
if (argv[0] === "explain") return runExplain(argv.slice(1), io);
|
|
795
|
+
|
|
796
|
+
const [only] = argv;
|
|
797
|
+
if (argv.length === 1 && (only === "--help" || only === "-h")) {
|
|
798
|
+
io.stdout(`${help()}\n`);
|
|
799
|
+
return 0;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
if (argv.length === 1 && only === "--version") {
|
|
803
|
+
const commit = typeof STANZA_COMMIT === "string" ? STANZA_COMMIT : undefined;
|
|
804
|
+
io.stdout(`${commit === undefined ? `stanza ${version}` : `stanza ${version} (${commit})`}\n`);
|
|
805
|
+
return 0;
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
const args = parseArguments(argv);
|
|
809
|
+
if ("error" in args) {
|
|
810
|
+
warn(io, `stanza: ${args.error}\n${usage}`);
|
|
811
|
+
return 2;
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
if (args.stdin !== undefined) return runStdin(args.stdin, args, io);
|
|
815
|
+
if (args.staged) return runStaged(args, io);
|
|
816
|
+
|
|
817
|
+
return runFiles(args, io);
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
if (import.meta.main) process.exitCode = main(process.argv.slice(2), systemIo());
|