@leolastforce/chalice-hashline-edit 0.0.0-stage → 4.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/LICENSE +21 -0
- package/README.md +153 -2
- package/index.ts +282 -0
- package/package.json +79 -4
- package/prompts/find-guidelines.md +2 -0
- package/prompts/find-snippet.md +1 -0
- package/prompts/find.md +1 -0
- package/prompts/grep-guidelines.md +2 -0
- package/prompts/grep-snippet.md +1 -0
- package/prompts/grep.md +1 -0
- package/prompts/insert-guidelines.md +1 -0
- package/prompts/insert-snippet.md +1 -0
- package/prompts/insert.md +1 -0
- package/prompts/read-guidelines.md +2 -0
- package/prompts/read-snippet.md +1 -0
- package/prompts/read.md +1 -0
- package/prompts/replace-guidelines.md +4 -0
- package/prompts/replace-snippet.md +1 -0
- package/prompts/replace.md +1 -0
- package/prompts/undo-last-change-guidelines.md +1 -0
- package/prompts/undo-last-change-snippet.md +1 -0
- package/prompts/undo-last-change.md +1 -0
- package/src/anchor-registry.ts +977 -0
- package/src/auto-read-all-state.ts +27 -0
- package/src/auto-read-all.ts +477 -0
- package/src/batch.ts +767 -0
- package/src/commit.ts +137 -0
- package/src/config-ui.ts +212 -0
- package/src/config.ts +235 -0
- package/src/constants.ts +26 -0
- package/src/edit-common.ts +206 -0
- package/src/file-kind.ts +191 -0
- package/src/file-reader.ts +135 -0
- package/src/find.ts +244 -0
- package/src/fs-write.ts +231 -0
- package/src/glob.ts +186 -0
- package/src/grep.ts +690 -0
- package/src/hash-store/cache.ts +18 -0
- package/src/hash-store/retry.ts +44 -0
- package/src/hash-store/validation.ts +62 -0
- package/src/hash-store.ts +609 -0
- package/src/hashline/alphabet.ts +21 -0
- package/src/hashline/anchor-table.json +1 -0
- package/src/hashline/apply.ts +297 -0
- package/src/hashline/hash.ts +119 -0
- package/src/hashline/hasher.ts +47 -0
- package/src/hashline/index.ts +50 -0
- package/src/hashline/parse.ts +84 -0
- package/src/hashline/resolve.ts +373 -0
- package/src/insert.ts +258 -0
- package/src/normalize.ts +27 -0
- package/src/paths.ts +56 -0
- package/src/payload-contract.ts +133 -0
- package/src/prompts.ts +13 -0
- package/src/read.ts +286 -0
- package/src/replace-diff.ts +610 -0
- package/src/replace-render.ts +390 -0
- package/src/replace-response.ts +166 -0
- package/src/replace-undo.ts +270 -0
- package/src/replace.ts +318 -0
- package/src/served.ts +36 -0
- package/src/utils.ts +387 -0
- package/src/validation.ts +45 -0
- package/src/write-hook.ts +53 -0
package/src/find.ts
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { stat } from "node:fs/promises";
|
|
6
|
+
import { dirname } from "node:path";
|
|
7
|
+
import { globToRegex } from "./glob";
|
|
8
|
+
import { resolveRgPath } from "./grep";
|
|
9
|
+
import { toCwd, toDisplayPath } from "./paths";
|
|
10
|
+
import { loadP, loadGuide } from "./prompts";
|
|
11
|
+
import { normReq } from "./payload-contract";
|
|
12
|
+
import { errCode, isRec, makePrepareArguments, rejectUnknownFields } from "./utils";
|
|
13
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
14
|
+
import { expandHint, getResultText, reuseText, type CallT, type FgT } from "./replace-render";
|
|
15
|
+
|
|
16
|
+
const FIND_KS = new Set(["pattern", "path", "limit"]);
|
|
17
|
+
const DEFAULT_LIMIT = 1000;
|
|
18
|
+
|
|
19
|
+
export interface FindReq {
|
|
20
|
+
pattern: string;
|
|
21
|
+
path?: string;
|
|
22
|
+
limit?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function assertFindReq(request: unknown): asserts request is FindReq {
|
|
26
|
+
if (!isRec(request)) {
|
|
27
|
+
throw new Error("[E_BAD_SHAPE] Find request must be an object.");
|
|
28
|
+
}
|
|
29
|
+
rejectUnknownFields(request, FIND_KS, "Find request");
|
|
30
|
+
if (typeof request.pattern !== "string" || request.pattern.length === 0) {
|
|
31
|
+
throw new Error('[E_BAD_SHAPE] Find request requires a non-empty "pattern" glob string.');
|
|
32
|
+
}
|
|
33
|
+
if (request.path !== undefined && typeof request.path !== "string") {
|
|
34
|
+
throw new Error('[E_BAD_SHAPE] Find request field "path" must be a string when provided.');
|
|
35
|
+
}
|
|
36
|
+
if (request.limit !== undefined && (typeof request.limit !== "number" || !Number.isInteger(request.limit) || request.limit < 1)) {
|
|
37
|
+
throw new Error('[E_BAD_SHAPE] Find request field "limit" must be a positive integer.');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function cmp(a: string, b: string): number {
|
|
42
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function collectRgFiles(rgPath: string, searchPath: string, signal?: AbortSignal): Promise<string[]> {
|
|
46
|
+
const args = ["--files", "--hidden", "--no-require-git", "--glob", "!.git", "--null"];
|
|
47
|
+
return await new Promise<string[]>((resolve, reject) => {
|
|
48
|
+
const child = spawn(rgPath, args, { cwd: searchPath, stdio: ["ignore", "pipe", "pipe"] });
|
|
49
|
+
const chunks: Buffer[] = [];
|
|
50
|
+
let stderr = "";
|
|
51
|
+
let settled = false;
|
|
52
|
+
const settle = (fn: () => void) => {
|
|
53
|
+
if (settled) return;
|
|
54
|
+
settled = true;
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
signal?.removeEventListener("abort", onAbort);
|
|
57
|
+
fn();
|
|
58
|
+
};
|
|
59
|
+
const timer = setTimeout(() => {
|
|
60
|
+
if (!child.killed) child.kill("SIGKILL");
|
|
61
|
+
settle(() => reject(new Error("rg timeout")));
|
|
62
|
+
}, 15000);
|
|
63
|
+
const onAbort = () => {
|
|
64
|
+
if (!child.killed) child.kill("SIGKILL");
|
|
65
|
+
settle(() => reject(new Error("Operation aborted")));
|
|
66
|
+
};
|
|
67
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
68
|
+
child.stdout?.on("data", (chunk: Buffer) => chunks.push(chunk));
|
|
69
|
+
child.stderr?.on("data", (chunk: Buffer) => {
|
|
70
|
+
stderr += chunk.toString();
|
|
71
|
+
});
|
|
72
|
+
child.on("error", (error) => settle(() => reject(error)));
|
|
73
|
+
child.on("close", (code) => {
|
|
74
|
+
if (code !== 0 && code !== 1) {
|
|
75
|
+
settle(() => reject(new Error(stderr.trim() || `ripgrep exited with code ${code}`)));
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const raw = Buffer.concat(chunks).toString("utf-8");
|
|
79
|
+
settle(() => resolve(raw.split("\0").filter((entry) => entry.length > 0)));
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const findToolSchema = Type.Object(
|
|
85
|
+
{
|
|
86
|
+
pattern: Type.String({
|
|
87
|
+
description: "Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'. `*` crosses directories.",
|
|
88
|
+
}),
|
|
89
|
+
path: Type.Optional(
|
|
90
|
+
Type.String({
|
|
91
|
+
description: "Directory to search in (default: current directory). A file path is also accepted.",
|
|
92
|
+
}),
|
|
93
|
+
),
|
|
94
|
+
limit: Type.Optional(
|
|
95
|
+
Type.Integer({
|
|
96
|
+
minimum: 1,
|
|
97
|
+
description: "Maximum number of results (default 1000)",
|
|
98
|
+
}),
|
|
99
|
+
),
|
|
100
|
+
},
|
|
101
|
+
{ additionalProperties: true },
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
const FIND_PREVIEW_LINES = 20;
|
|
105
|
+
const FIND_PREVIEW_LINES_EXPANDED = 60;
|
|
106
|
+
|
|
107
|
+
export function fmtFindCall(args: { pattern?: unknown; path?: unknown; limit?: unknown } | undefined, theme: CallT): string {
|
|
108
|
+
const pattern = typeof args?.pattern === "string" && args.pattern.length > 0 ? theme.fg("accent", args.pattern) : theme.fg("toolOutput", "...");
|
|
109
|
+
const qualifiers: string[] = [];
|
|
110
|
+
if (typeof args?.path === "string" && args.path.length > 0) qualifiers.push(args.path);
|
|
111
|
+
if (typeof args?.limit === "number") qualifiers.push(`limit ${args.limit}`);
|
|
112
|
+
let text = `${theme.fg("toolTitle", theme.bold("find"))} ${pattern}`;
|
|
113
|
+
if (qualifiers.length > 0) text += ` ${theme.fg("dim", qualifiers.join(" "))}`;
|
|
114
|
+
return text;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function styleFindLine(line: string, theme: FgT): string {
|
|
118
|
+
if (line.startsWith("[find:")) return theme.fg("dim", line);
|
|
119
|
+
return line;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function renderFindResult(
|
|
123
|
+
result: { content?: Array<{ type: string; text?: string }> },
|
|
124
|
+
options: { isPartial: boolean; expanded?: boolean } | boolean,
|
|
125
|
+
theme: FgT,
|
|
126
|
+
context: { isError?: boolean; expanded?: boolean; lastComponent?: unknown },
|
|
127
|
+
): Text {
|
|
128
|
+
const isPartial = typeof options === "boolean" ? options : options.isPartial;
|
|
129
|
+
const expanded = typeof options === "boolean" ? context.expanded === true : options.expanded === true || context.expanded === true;
|
|
130
|
+
if (isPartial) return reuseText(context, theme.fg("warning", "Finding..."));
|
|
131
|
+
const raw = getResultText(result);
|
|
132
|
+
if (context.isError) return raw ? reuseText(context, `\n${theme.fg("error", raw)}`) : new Text("", 0, 0);
|
|
133
|
+
if (!raw) return new Text("", 0, 0);
|
|
134
|
+
const maxLines = expanded ? FIND_PREVIEW_LINES_EXPANDED : FIND_PREVIEW_LINES;
|
|
135
|
+
const lines = raw.split("\n");
|
|
136
|
+
const shown = lines.slice(0, maxLines).map((line) => styleFindLine(line, theme));
|
|
137
|
+
if (lines.length > maxLines) shown.push(theme.fg("muted", `... ${lines.length - maxLines} more find lines (${expandHint()})`));
|
|
138
|
+
return reuseText(context, shown.join("\n"));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function regFind(pi: ExtensionAPI): void {
|
|
142
|
+
pi.registerTool({
|
|
143
|
+
name: "find",
|
|
144
|
+
label: "Find",
|
|
145
|
+
description: loadP("../prompts/find.md"),
|
|
146
|
+
promptSnippet: loadP("../prompts/find-snippet.md"),
|
|
147
|
+
promptGuidelines: loadGuide("../prompts/find-guidelines.md"),
|
|
148
|
+
prepareArguments: makePrepareArguments(),
|
|
149
|
+
parameters: findToolSchema,
|
|
150
|
+
executionMode: "sequential",
|
|
151
|
+
renderCall(args: any, theme: CallT, context: any) {
|
|
152
|
+
const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
|
|
153
|
+
text.setText(fmtFindCall(args as { pattern?: unknown; path?: unknown; limit?: unknown } | undefined, theme));
|
|
154
|
+
return text;
|
|
155
|
+
},
|
|
156
|
+
renderResult(result, opts, theme, context) {
|
|
157
|
+
return renderFindResult(result as never, opts as { isPartial: boolean; expanded?: boolean }, theme as never, context as never);
|
|
158
|
+
},
|
|
159
|
+
|
|
160
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
161
|
+
const canonical = normReq(params);
|
|
162
|
+
assertFindReq(canonical);
|
|
163
|
+
const req = canonical;
|
|
164
|
+
const limit = req.limit ?? DEFAULT_LIMIT;
|
|
165
|
+
const base = req.path ? toCwd(req.path, ctx.cwd) : ctx.cwd;
|
|
166
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
167
|
+
|
|
168
|
+
let baseStat;
|
|
169
|
+
try {
|
|
170
|
+
baseStat = await stat(base);
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if (errCode(error) === "ENOENT") {
|
|
173
|
+
throw new Error(`[E_NOT_FOUND] File not found: ${req.path ?? ctx.cwd}`);
|
|
174
|
+
}
|
|
175
|
+
throw new Error(`[E_ACCESS] Cannot access path: ${req.path ?? ctx.cwd}`);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const globRoot = baseStat.isFile() ? dirname(base) : base;
|
|
179
|
+
const globRegex = globToRegex(req.pattern);
|
|
180
|
+
const matchesGlob = (absPath: string): boolean => {
|
|
181
|
+
const displayPath = toDisplayPath(ctx.cwd, absPath);
|
|
182
|
+
const globPath = toDisplayPath(globRoot, absPath);
|
|
183
|
+
return globRegex.test(globPath) || globRegex.test(displayPath);
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const rgPath = await resolveRgPath();
|
|
187
|
+
const candidates = baseStat.isFile() ? [base] : await collectRgFiles(rgPath, base, signal);
|
|
188
|
+
const matches = candidates
|
|
189
|
+
.map((entry) => (baseStat.isFile() ? entry : toCwd(entry, base)))
|
|
190
|
+
.filter((absPath) => matchesGlob(absPath))
|
|
191
|
+
.map((absPath) => toDisplayPath(ctx.cwd, absPath))
|
|
192
|
+
.sort(cmp);
|
|
193
|
+
|
|
194
|
+
const limitReached = matches.length > limit;
|
|
195
|
+
const selected = matches.slice(0, limit);
|
|
196
|
+
|
|
197
|
+
const notices: string[] = [];
|
|
198
|
+
if (limitReached) notices.push(`[find: showing first ${limit} results; increase limit to see more.]`);
|
|
199
|
+
|
|
200
|
+
let text: string;
|
|
201
|
+
let truncation: TruncationResult | undefined;
|
|
202
|
+
if (selected.length === 0) {
|
|
203
|
+
text = "No files found matching pattern.";
|
|
204
|
+
} else {
|
|
205
|
+
const rawOutput = selected.join("\n");
|
|
206
|
+
const totalBytes = Buffer.byteLength(rawOutput, "utf-8");
|
|
207
|
+
const head = selected.slice(0, DEFAULT_MAX_LINES).join("\n");
|
|
208
|
+
const clipped = Buffer.byteLength(head, "utf-8") > DEFAULT_MAX_BYTES
|
|
209
|
+
? Buffer.from(head, "utf-8").subarray(0, DEFAULT_MAX_BYTES).toString("utf-8")
|
|
210
|
+
: head;
|
|
211
|
+
if (clipped !== rawOutput) {
|
|
212
|
+
const outputLines = clipped === "" ? 0 : clipped.split("\n").length;
|
|
213
|
+
truncation = {
|
|
214
|
+
content: clipped,
|
|
215
|
+
truncated: true,
|
|
216
|
+
truncatedBy: Buffer.byteLength(head, "utf-8") > DEFAULT_MAX_BYTES ? "bytes" : "lines",
|
|
217
|
+
totalLines: selected.length,
|
|
218
|
+
totalBytes,
|
|
219
|
+
outputLines,
|
|
220
|
+
outputBytes: Buffer.byteLength(clipped, "utf-8"),
|
|
221
|
+
lastLinePartial: false,
|
|
222
|
+
firstLineExceedsLimit: false,
|
|
223
|
+
maxLines: DEFAULT_MAX_LINES,
|
|
224
|
+
maxBytes: DEFAULT_MAX_BYTES,
|
|
225
|
+
};
|
|
226
|
+
notices.push(`[find: output truncated at ${DEFAULT_MAX_LINES} rows or ${formatSize(DEFAULT_MAX_BYTES)}; refine the pattern or narrow path.]`);
|
|
227
|
+
}
|
|
228
|
+
text = clipped;
|
|
229
|
+
}
|
|
230
|
+
if (notices.length > 0) text += `\n\n${notices.join("\n")}`;
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
content: [{ type: "text", text }],
|
|
234
|
+
details: {
|
|
235
|
+
...(truncation ? { truncation } : {}),
|
|
236
|
+
metrics: {
|
|
237
|
+
files: selected.length,
|
|
238
|
+
truncated: limitReached || truncation !== undefined,
|
|
239
|
+
},
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
}
|
package/src/fs-write.ts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import {
|
|
4
|
+
lstat,
|
|
5
|
+
mkdir,
|
|
6
|
+
open,
|
|
7
|
+
readdir,
|
|
8
|
+
readlink,
|
|
9
|
+
rename,
|
|
10
|
+
rm,
|
|
11
|
+
stat,
|
|
12
|
+
writeFile,
|
|
13
|
+
} from "node:fs/promises";
|
|
14
|
+
import { dirname, join, parse, resolve, sep } from "node:path";
|
|
15
|
+
import { toCwd } from "./paths";
|
|
16
|
+
import { errCode } from "./utils";
|
|
17
|
+
|
|
18
|
+
export interface FileIdentity {
|
|
19
|
+
dev: number;
|
|
20
|
+
ino: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function sameIdentity(
|
|
24
|
+
actual: FileIdentity,
|
|
25
|
+
expected: FileIdentity,
|
|
26
|
+
): boolean {
|
|
27
|
+
return actual.dev === expected.dev && actual.ino === expected.ino;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function pathChanged(path: string): Error {
|
|
31
|
+
return new Error(`[E_PATH_CHANGED] Refusing to write ${path}: the target changed after it was read.`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function resolveTarget(path: string): Promise<string> {
|
|
35
|
+
const absolutePath = resolve(path);
|
|
36
|
+
const { root } = parse(absolutePath);
|
|
37
|
+
const parts = absolutePath
|
|
38
|
+
.slice(root.length)
|
|
39
|
+
.split(sep)
|
|
40
|
+
.filter((part) => part.length > 0);
|
|
41
|
+
const visitedSymlinks = new Set<string>();
|
|
42
|
+
|
|
43
|
+
async function resParts(
|
|
44
|
+
currentPath: string,
|
|
45
|
+
remainingParts: string[],
|
|
46
|
+
symlinkDepth = 0,
|
|
47
|
+
): Promise<string> {
|
|
48
|
+
if (symlinkDepth > 40) {
|
|
49
|
+
const error = new Error(
|
|
50
|
+
`Too many symbolic links while resolving ${path}`,
|
|
51
|
+
) as NodeJS.ErrnoException;
|
|
52
|
+
error.code = "ELOOP";
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
if (remainingParts.length === 0) {
|
|
56
|
+
return currentPath;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const [nextPart, ...tail] = remainingParts;
|
|
60
|
+
const candidatePath = join(currentPath, nextPart);
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
const candidateStats = await lstat(candidatePath);
|
|
64
|
+
if (!candidateStats.isSymbolicLink()) {
|
|
65
|
+
return resParts(candidatePath, tail, symlinkDepth);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (visitedSymlinks.has(candidatePath)) {
|
|
69
|
+
const error = new Error(
|
|
70
|
+
`Too many symbolic links while resolving ${path}`,
|
|
71
|
+
) as NodeJS.ErrnoException;
|
|
72
|
+
error.code = "ELOOP";
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
visitedSymlinks.add(candidatePath);
|
|
76
|
+
|
|
77
|
+
const linkTargetPath = resolve(
|
|
78
|
+
dirname(candidatePath),
|
|
79
|
+
await readlink(candidatePath),
|
|
80
|
+
);
|
|
81
|
+
const targetParts = linkTargetPath
|
|
82
|
+
.slice(parse(linkTargetPath).root.length)
|
|
83
|
+
.split(sep)
|
|
84
|
+
.filter((part) => part.length > 0);
|
|
85
|
+
return resParts(parse(linkTargetPath).root, [
|
|
86
|
+
...targetParts,
|
|
87
|
+
...tail,
|
|
88
|
+
], symlinkDepth + 1);
|
|
89
|
+
} catch (error: unknown) {
|
|
90
|
+
if (errCode(error) === "ENOENT") {
|
|
91
|
+
return join(candidatePath, ...tail);
|
|
92
|
+
}
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return resParts(root, parts);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const TEMP_PREFIX = ".tmp-";
|
|
101
|
+
const TEMP_UUID_RE = /^\.tmp-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
102
|
+
const STALE_TEMP_MS = 60 * 60 * 1000;
|
|
103
|
+
const sweptDirs = new Map<string, number>();
|
|
104
|
+
const SWEPT_DIRS_LIMIT = 256;
|
|
105
|
+
|
|
106
|
+
async function sweepStaleTemps(dir: string): Promise<void> {
|
|
107
|
+
const sweepNow = Date.now();
|
|
108
|
+
const lastSweep = sweptDirs.get(dir);
|
|
109
|
+
if (lastSweep !== undefined && sweepNow - lastSweep < STALE_TEMP_MS) return;
|
|
110
|
+
sweptDirs.delete(dir);
|
|
111
|
+
sweptDirs.set(dir, sweepNow);
|
|
112
|
+
if (sweptDirs.size > SWEPT_DIRS_LIMIT) {
|
|
113
|
+
const oldest = sweptDirs.keys().next().value;
|
|
114
|
+
if (oldest !== undefined) sweptDirs.delete(oldest);
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
118
|
+
for (const entry of entries) {
|
|
119
|
+
if (!entry.isFile() || !TEMP_UUID_RE.test(entry.name)) continue;
|
|
120
|
+
const tempPath = join(dir, entry.name);
|
|
121
|
+
try {
|
|
122
|
+
const stats = await stat(tempPath);
|
|
123
|
+
if (sweepNow - stats.mtimeMs > STALE_TEMP_MS) {
|
|
124
|
+
await rm(tempPath, { force: true });
|
|
125
|
+
}
|
|
126
|
+
} catch {
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
} catch {
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function syncDir(dir: string): Promise<void> {
|
|
134
|
+
if (process.platform === "win32") return;
|
|
135
|
+
try {
|
|
136
|
+
const handle = await open(dir, "r");
|
|
137
|
+
try {
|
|
138
|
+
await handle.sync();
|
|
139
|
+
} finally {
|
|
140
|
+
await handle.close();
|
|
141
|
+
}
|
|
142
|
+
} catch {
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function resolveInCwd(path: string, cwd: string): Promise<{ absolute: string; resolved: string }> {
|
|
147
|
+
const absolute = toCwd(path, cwd);
|
|
148
|
+
const resolved = await resolveTarget(absolute);
|
|
149
|
+
return { absolute, resolved };
|
|
150
|
+
}
|
|
151
|
+
export async function writeAtomic(
|
|
152
|
+
path: string,
|
|
153
|
+
content: string,
|
|
154
|
+
expectedIdentity?: FileIdentity,
|
|
155
|
+
restoreMode?: number,
|
|
156
|
+
): Promise<void> {
|
|
157
|
+
const targetPath = await resolveTarget(path);
|
|
158
|
+
|
|
159
|
+
let existingStats: Awaited<ReturnType<typeof stat>> | null = null;
|
|
160
|
+
try {
|
|
161
|
+
existingStats = await stat(targetPath);
|
|
162
|
+
} catch (error: unknown) {
|
|
163
|
+
if (errCode(error) !== "ENOENT") {
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (expectedIdentity && (!existingStats || !sameIdentity(existingStats, expectedIdentity))) {
|
|
169
|
+
throw pathChanged(path);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (existingStats && existingStats.nlink > 1) {
|
|
173
|
+
const noFollow = process.platform === "win32" ? 0 : constants.O_NOFOLLOW;
|
|
174
|
+
const handle = await open(targetPath, constants.O_WRONLY | noFollow);
|
|
175
|
+
try {
|
|
176
|
+
const openedStats = await handle.stat();
|
|
177
|
+
if (!sameIdentity(openedStats, existingStats)) throw pathChanged(path);
|
|
178
|
+
await handle.writeFile(content, "utf-8");
|
|
179
|
+
await handle.truncate(Buffer.byteLength(content, "utf-8"));
|
|
180
|
+
try {
|
|
181
|
+
await handle.chmod(existingStats.mode & 0o7777);
|
|
182
|
+
} catch {}
|
|
183
|
+
await handle.sync();
|
|
184
|
+
} finally {
|
|
185
|
+
await handle.close();
|
|
186
|
+
}
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const dir = dirname(targetPath);
|
|
191
|
+
await sweepStaleTemps(dir);
|
|
192
|
+
const tempPath = join(dir, `${TEMP_PREFIX}${randomUUID()}`);
|
|
193
|
+
await mkdir(dir, { recursive: true });
|
|
194
|
+
const tempHandle = await open(tempPath, "wx", 0o600);
|
|
195
|
+
try {
|
|
196
|
+
await tempHandle.writeFile(content, "utf-8");
|
|
197
|
+
const mode = existingStats ? existingStats.mode & 0o7777 : restoreMode;
|
|
198
|
+
if (mode !== undefined) {
|
|
199
|
+
await tempHandle.chmod(mode);
|
|
200
|
+
}
|
|
201
|
+
await tempHandle.sync();
|
|
202
|
+
} catch (error: unknown) {
|
|
203
|
+
try { await tempHandle.close(); } catch {}
|
|
204
|
+
try { await rm(tempPath, { force: true }); } catch {}
|
|
205
|
+
throw error;
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
await tempHandle.close();
|
|
209
|
+
try {
|
|
210
|
+
const finalStats = await lstat(targetPath);
|
|
211
|
+
if (!existingStats || finalStats.isSymbolicLink() || !sameIdentity(finalStats, existingStats)) {
|
|
212
|
+
throw pathChanged(path);
|
|
213
|
+
}
|
|
214
|
+
} catch (error) {
|
|
215
|
+
if (errCode(error) !== "ENOENT" || existingStats) throw error;
|
|
216
|
+
}
|
|
217
|
+
await rename(tempPath, targetPath);
|
|
218
|
+
await syncDir(dir);
|
|
219
|
+
} catch (error: unknown) {
|
|
220
|
+
if (process.platform === "win32" && errCode(error) === "EPERM") {
|
|
221
|
+
try {
|
|
222
|
+
await writeFile(targetPath, content, "utf-8");
|
|
223
|
+
return;
|
|
224
|
+
} finally {
|
|
225
|
+
try { await rm(tempPath, { force: true }); } catch {}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
try { await rm(tempPath, { force: true }); } catch {}
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
231
|
+
}
|
package/src/glob.ts
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
function bracketEnd(source: string, start: number): number {
|
|
2
|
+
let j = start + 1;
|
|
3
|
+
if (j < source.length && (source[j] === "!" || source[j] === "^")) j++;
|
|
4
|
+
if (j < source.length && source[j] === "]") j++;
|
|
5
|
+
let esc = false;
|
|
6
|
+
while (j < source.length) {
|
|
7
|
+
const c = source[j]!;
|
|
8
|
+
if (esc) {
|
|
9
|
+
esc = false;
|
|
10
|
+
j++;
|
|
11
|
+
continue;
|
|
12
|
+
}
|
|
13
|
+
if (c === "\\") {
|
|
14
|
+
esc = true;
|
|
15
|
+
j++;
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
if (c === "]") return j;
|
|
19
|
+
j++;
|
|
20
|
+
}
|
|
21
|
+
return -1;
|
|
22
|
+
}
|
|
23
|
+
function globPartToSource(glob: string): string {
|
|
24
|
+
let source = "";
|
|
25
|
+
let i = 0;
|
|
26
|
+
while (i < glob.length) {
|
|
27
|
+
const ch = glob[i]!;
|
|
28
|
+
if (ch === "\\" && i + 1 < glob.length) {
|
|
29
|
+
const next = glob[i + 1]!;
|
|
30
|
+
source += next.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
31
|
+
i += 2;
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (ch === "*") {
|
|
35
|
+
if (glob[i + 1] === "*") {
|
|
36
|
+
i += 2;
|
|
37
|
+
if (glob[i] === "/") {
|
|
38
|
+
i += 1;
|
|
39
|
+
source += "(?:.*\\/)?";
|
|
40
|
+
} else {
|
|
41
|
+
source += ".*";
|
|
42
|
+
}
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
source += ".*";
|
|
46
|
+
i += 1;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (ch === "?") {
|
|
50
|
+
source += "[^/]";
|
|
51
|
+
i += 1;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (ch === "{") {
|
|
55
|
+
let depth = 1;
|
|
56
|
+
let j = i + 1;
|
|
57
|
+
let esc = false;
|
|
58
|
+
while (j < glob.length && depth > 0) {
|
|
59
|
+
const c = glob[j]!;
|
|
60
|
+
if (esc) {
|
|
61
|
+
esc = false;
|
|
62
|
+
j++;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (c === "\\") {
|
|
66
|
+
esc = true;
|
|
67
|
+
j++;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (c === "[") {
|
|
71
|
+
const e = bracketEnd(glob, j);
|
|
72
|
+
if (e >= 0) {
|
|
73
|
+
j = e + 1;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
j++;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (c === "{") depth++;
|
|
80
|
+
else if (c === "}") depth--;
|
|
81
|
+
if (depth === 0) break;
|
|
82
|
+
j++;
|
|
83
|
+
}
|
|
84
|
+
if (depth !== 0) {
|
|
85
|
+
source += "\\{";
|
|
86
|
+
i++;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
const inner = glob.slice(i + 1, j);
|
|
90
|
+
const parts: string[] = [];
|
|
91
|
+
let cur = "";
|
|
92
|
+
let d2 = 0;
|
|
93
|
+
let esc2 = false;
|
|
94
|
+
for (let k = 0; k < inner.length; k++) {
|
|
95
|
+
const c = inner[k]!;
|
|
96
|
+
if (esc2) {
|
|
97
|
+
cur += c;
|
|
98
|
+
esc2 = false;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (c === "\\") {
|
|
102
|
+
esc2 = true;
|
|
103
|
+
cur += c;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (c === "[") {
|
|
107
|
+
const e = bracketEnd(inner, k);
|
|
108
|
+
if (e >= 0) {
|
|
109
|
+
cur += inner.slice(k, e + 1);
|
|
110
|
+
k = e;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
cur += c;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (c === "{") {
|
|
117
|
+
d2++;
|
|
118
|
+
cur += c;
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (c === "}") {
|
|
122
|
+
d2--;
|
|
123
|
+
cur += c;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (c === "," && d2 === 0) {
|
|
127
|
+
parts.push(cur);
|
|
128
|
+
cur = "";
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
cur += c;
|
|
132
|
+
}
|
|
133
|
+
parts.push(cur);
|
|
134
|
+
if (parts.length <= 1) {
|
|
135
|
+
source += "\\{" + globPartToSource(inner) + "\\}";
|
|
136
|
+
} else {
|
|
137
|
+
source += "(?:" + parts.map((p) => globPartToSource(p)).join("|") + ")";
|
|
138
|
+
}
|
|
139
|
+
i = j + 1;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (ch === "[") {
|
|
143
|
+
let j = i + 1;
|
|
144
|
+
if (j < glob.length && (glob[j] === "!" || glob[j] === "^")) j++;
|
|
145
|
+
if (j < glob.length && glob[j] === "]") j++;
|
|
146
|
+
let esc3 = false;
|
|
147
|
+
while (j < glob.length) {
|
|
148
|
+
const c = glob[j]!;
|
|
149
|
+
if (esc3) {
|
|
150
|
+
esc3 = false;
|
|
151
|
+
j++;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (c === "\\") {
|
|
155
|
+
esc3 = true;
|
|
156
|
+
j++;
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (c === "]") break;
|
|
160
|
+
j++;
|
|
161
|
+
}
|
|
162
|
+
if (j >= glob.length) {
|
|
163
|
+
source += "\\[";
|
|
164
|
+
i++;
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
let content = glob.slice(i + 1, j);
|
|
168
|
+
if (content.startsWith("!")) content = "^" + content.slice(1);
|
|
169
|
+
if (content.startsWith("]") || content.startsWith("^]")) {
|
|
170
|
+
if (content.startsWith("^]")) content = "^\\]" + content.slice(2);
|
|
171
|
+
else content = "\\]" + content.slice(1);
|
|
172
|
+
}
|
|
173
|
+
if (content.startsWith("^") && !content.includes("/")) content = "^/" + content.slice(1);
|
|
174
|
+
source += "[" + content + "]";
|
|
175
|
+
i = j + 1;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
source += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
179
|
+
i++;
|
|
180
|
+
}
|
|
181
|
+
return source;
|
|
182
|
+
}
|
|
183
|
+
export function globToRegex(glob: string): RegExp {
|
|
184
|
+
if (glob.startsWith("/")) glob = glob.slice(1);
|
|
185
|
+
return new RegExp(`^${globPartToSource(glob)}$`);
|
|
186
|
+
}
|