Repository navigation
Expand file tree
/
Copy pathrun.ts
More file actions
403 lines (376 loc) · 14.3 KB
/
Copy pathrun.ts
File metadata and controls
403 lines (376 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import path from 'path';
import { promises as fs } from 'fs';
import { readTextStreamPrefix, readTextStreamWithLimit } from '../../common/bounded-text-stream.js';
import { ProjectBoundaryError } from '../../common/path-boundary.js';
import { assertGitWorkingPath, gitOperationOptions, isGitCancellation, markGitOutputTruncated, markGitMutationDispatched, trackGitProcess } from './operation-context.js';
import type {
GitCommandOptions,
GitCommandResult,
GitCommandTrace,
GitProcessError,
} from './types.js';
const GIT_LOCK_RETRY_DELAY_MS = 100;
const GIT_LOCK_MAX_RETRIES = 50;
const GIT_DEFAULT_TIMEOUT_MS = 30_000;
const GIT_DEFAULT_MAX_STDOUT_BYTES = 64 * 1024 * 1024;
const GIT_DEFAULT_MAX_STDERR_BYTES = 2 * 1024 * 1024;
const GIT_TERMINATION_GRACE_MS = 250;
async function terminateGitProcess(proc: Bun.Subprocess): Promise<void> {
if (process.platform === 'win32') {
const killer = Bun.spawn(['taskkill', '/PID', String(proc.pid), '/T', '/F'], {
env: { ...process.env },
stdin: 'ignore',
stdout: 'ignore',
stderr: 'ignore',
});
await killer.exited;
return;
}
try {
process.kill(-proc.pid, 'SIGTERM');
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ESRCH') return;
throw error;
}
// Git gets a chance to clean its locks before uncooperative filters are forced to exit.
await sleep(GIT_TERMINATION_GRACE_MS);
try {
process.kill(-proc.pid, 'SIGKILL');
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
}
}
export function gitCommandEnv(options: GitCommandOptions): NodeJS.ProcessEnv | undefined {
if (!options.disableOptionalLocks && !options.env) return undefined;
return {
...process.env,
...options.env,
...(options.disableOptionalLocks ? { GIT_OPTIONAL_LOCKS: '0' } : {}),
};
}
// Builds command options that avoid optional Git index writes for read-only probes.
export function readOnlyGitOptions(options: GitCommandOptions = {}): GitCommandOptions {
return { ...options, disableOptionalLocks: true };
}
// Returns true when stderr indicates a git index.lock contention error.
function isLockError(stderr: string): boolean {
const lower = stderr.toLowerCase();
return lower.includes('index.lock') || lower.includes('unable to create') && lower.includes('.lock');
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export class GitOutputLimitError extends Error {
constructor(
readonly stream: 'stdout' | 'stderr',
readonly maxBytes: number,
) {
super(`Git ${stream} exceeded the ${maxBytes} byte limit.`);
this.name = 'GitOutputLimitError';
}
}
function readGitOutput(
stream: ReadableStream<Uint8Array> | null,
streamName: 'stdout' | 'stderr',
maxBytes: number,
): Promise<string> {
return readTextStreamWithLimit(
stream,
maxBytes,
() => new GitOutputLimitError(streamName, maxBytes),
);
}
function createGitAbortState(options: GitCommandOptions, timeoutMs: number): {
signal?: AbortSignal;
cleanup: () => void;
timedOut: () => boolean;
aborted: () => boolean;
} {
const timeoutController = new AbortController();
let timeoutReached = false;
const timeoutHandle = setTimeout(() => {
timeoutReached = true;
timeoutController.abort();
}, timeoutMs);
timeoutHandle.unref?.();
const callerSignal = options.signal;
const signal = callerSignal
? AbortSignal.any([callerSignal, timeoutController.signal])
: timeoutController.signal;
return {
signal,
cleanup: () => {
clearTimeout(timeoutHandle);
},
timedOut: () => timeoutReached,
// Reads the sticky signal state directly: the abort event cannot fire
// for a pre-aborted signal, so a latched flag alone would misreport that
// case (and any abort after cleanup) as a plain exit failure.
aborted: () => timeoutReached || callerSignal?.aborted === true,
};
}
function makeGitProcessError(
args: string[],
exitCode: number | null,
stdout: string,
stderr: string,
options: { timedOut?: boolean; aborted?: boolean } = {},
): GitProcessError {
let reason: string;
if (options.timedOut) {
reason = 'timed out';
} else if (options.aborted) {
reason = 'aborted';
} else {
reason = `exit ${exitCode}`;
}
const message = stderr.trim() || stdout.trim() || reason;
const error: GitProcessError = new Error(`git ${args[0]} failed (${reason}): ${message}`);
if (typeof exitCode === 'number') error.code = exitCode;
error.stdout = stdout;
error.stderr = stderr;
error.timedOut = options.timedOut;
error.aborted = options.aborted;
return error;
}
type GitStdin = 'ignore' | Blob;
// Shared subprocess loop for every git invocation: abort wiring, output-limit
// capture, and transparent index.lock retry. One absolute timeout budget
// spans every attempt and retry delay, so a caller-supplied ceiling such as
// the HTTP idle margin holds for the whole command, not per attempt. Retries
// stop honoring the caller once its abort fired during the retry delay.
async function runGitProcess(
cwd: string,
args: string[],
options: GitCommandOptions,
stdin: GitStdin,
): Promise<GitCommandResult> {
const deadlineAt = performance.now() + (options.timeoutMs ?? GIT_DEFAULT_TIMEOUT_MS);
// Kept from the last lock failure so budget expiry mid-retry still reports
// its output; classifyGitError is message-based and would otherwise map
// lock contention to UNKNOWN instead of GIT_LOCKED.
let lastFailure: { exitCode: number | null; stdout: string; stderr: string } | null = null;
for (let attempt = 0; ; attempt++) {
const remainingMs = deadlineAt - performance.now();
if (remainingMs <= 0) {
const prior = lastFailure ?? { exitCode: null, stdout: '', stderr: '' };
throw makeGitProcessError(args, prior.exitCode, prior.stdout, prior.stderr, { timedOut: true });
}
const abortState = createGitAbortState(options, remainingMs);
let proc: Bun.Subprocess<GitStdin, 'pipe', 'pipe'>;
try {
abortState.signal?.throwIfAborted();
proc = Bun.spawn(['git', ...args], {
cwd,
stdin,
stdout: 'pipe',
stderr: 'pipe',
detached: process.platform !== 'win32',
env: gitCommandEnv(options),
});
if (!options.disableOptionalLocks) markGitMutationDispatched();
} catch (error) {
abortState.cleanup();
// Bun.spawn throws synchronously for an already-aborted signal; route
// that through the same abort reporting as every other failure path.
if (abortState.aborted()) {
throw makeGitProcessError(args, null, '', '', {
timedOut: abortState.timedOut(),
aborted: true,
});
}
throw error;
}
let termination: Promise<void> | undefined;
const abortListener = (): void => {
termination ??= terminateGitProcess(proc);
};
abortState.signal?.addEventListener('abort', abortListener, { once: true });
if (abortState.signal?.aborted) abortListener();
let outputLimitError: GitOutputLimitError | null = null;
const captureOutput = (output: Promise<string>): Promise<string> =>
output.catch((error) => {
if (error instanceof GitOutputLimitError) {
outputLimitError ??= error;
abortListener();
}
return '';
});
const diagnosticOutput = options.truncateStdout === true;
const stdoutLimit = diagnosticOutput ? options.maxStdoutBytes ?? 32_768 : options.maxStdoutBytes ?? GIT_DEFAULT_MAX_STDOUT_BYTES;
const [stdout, stderr, exitCode] = await Promise.all([
captureOutput(diagnosticOutput
? readTextStreamPrefix(proc.stdout, stdoutLimit)
: readGitOutput(proc.stdout, 'stdout', stdoutLimit)),
captureOutput(readTextStreamPrefix(
proc.stderr,
options.maxStderrBytes ?? GIT_DEFAULT_MAX_STDERR_BYTES,
)),
proc.exited,
]).finally(async () => {
abortState.signal?.removeEventListener('abort', abortListener);
abortState.cleanup();
await termination;
});
if (diagnosticOutput && Buffer.byteLength(stdout) >= stdoutLimit) markGitOutputTruncated();
if (outputLimitError) throw outputLimitError;
if (exitCode === 0 && !abortState.aborted()) return { stdout, stderr };
if (isLockError(stderr) && attempt < GIT_LOCK_MAX_RETRIES) {
lastFailure = { exitCode, stdout, stderr };
// The attempt's timer was already cleaned up, so the delay itself must
// respect the absolute budget; otherwise the total runtime overshoots
// timeoutMs by up to a full retry delay.
await sleep(Math.min(GIT_LOCK_RETRY_DELAY_MS, Math.max(0, deadlineAt - performance.now())));
// aborted() reads the live caller signal, so an abort during the retry
// delay is reported here instead of spawning another attempt.
const timedOut = abortState.timedOut();
const aborted = abortState.aborted();
if (timedOut || aborted) {
throw makeGitProcessError(args, exitCode, stdout, stderr, { timedOut, aborted });
}
continue;
}
throw makeGitProcessError(args, exitCode, stdout, stderr, {
timedOut: abortState.timedOut(),
aborted: abortState.aborted(),
});
}
}
// Spawns a git subprocess and returns stdout/stderr on success.
export async function runGit(
cwd: string,
args: string[],
options: GitCommandOptions = {},
): Promise<GitCommandResult> {
return trackGitProcess(() => runGitProcess(cwd, args, gitOperationOptions(options), 'ignore'));
}
// Runs git and appends safe command timing metadata when a trace is provided.
export async function runGitTraced(
cwd: string,
args: string[],
trace?: GitCommandTrace[],
options: GitCommandOptions = {},
): Promise<GitCommandResult> {
const startedAt = performance.now();
try {
const result = await runGit(cwd, args, options);
trace?.push({
args,
durationMs: Math.round(performance.now() - startedAt),
stdoutBytes: Buffer.byteLength(result.stdout),
stderrBytes: Buffer.byteLength(result.stderr),
});
return result;
} catch (error) {
const processError = error as GitProcessError;
trace?.push({
args,
durationMs: Math.round(performance.now() - startedAt),
stdoutBytes: Buffer.byteLength(processError.stdout ?? ''),
stderrBytes: Buffer.byteLength(processError.stderr ?? ''),
failed: true,
...(typeof processError.code === 'number' ? { exitCode: processError.code } : {}),
...(processError.timedOut ? { timedOut: true } : {}),
...(processError.aborted ? { aborted: true } : {}),
});
throw error;
}
}
// Spawns a git subprocess that reads from stdin (e.g. git apply).
export async function runGitWithStdin(
cwd: string,
args: string[],
input: string,
options: GitCommandOptions = {},
): Promise<GitCommandResult> {
return trackGitProcess(() => runGitProcess(cwd, args, gitOperationOptions(options), new Blob([input])));
}
export function readGitBlobPrefix(cwd: string, object: string, signal?: AbortSignal): Promise<Buffer> {
return trackGitProcess(async () => {
const options = gitOperationOptions(readOnlyGitOptions({ signal }));
const abort = createGitAbortState(options, options.timeoutMs ?? GIT_DEFAULT_TIMEOUT_MS);
let process: Bun.Subprocess<'ignore', 'pipe', 'ignore'> | undefined;
try {
process = Bun.spawn(['git', 'show', object], { cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'ignore', signal: abort.signal, env: gitCommandEnv(options) });
const reader = process.stdout.getReader();
const chunks: Uint8Array[] = [];
let size = 0;
try {
while (size < 8192) {
const chunk = await reader.read();
if (chunk.done) break;
const bytes = chunk.value.subarray(0, 8192 - size);
chunks.push(bytes);
size += bytes.length;
}
return Buffer.concat(chunks, size);
} finally {
process.kill();
await reader.cancel().catch(() => undefined);
}
} finally {
if (process) { process.kill(); await process.exited; }
abort.cleanup();
}
});
}
// Detects binary files by checking for null bytes in the first 8KB.
// This is the same heuristic Git uses in its buffer_is_binary() function.
export async function isBinaryFile(filePath: string): Promise<boolean> {
try {
await assertGitWorkingPath(filePath);
const fileHandle = await fs.open(filePath, 'r');
try {
const buf = Buffer.alloc(8192);
const { bytesRead } = await fileHandle.read(buf, 0, 8192, 0);
return bytesRead > 0 && buf.subarray(0, bytesRead).includes(0x00);
} finally {
await fileHandle.close();
}
} catch {
return false;
}
}
// Strips git diff metadata headers, keeping only hunk content starting from @@ markers.
export function stripDiffHeaders(diff: string): string {
if (!diff) return '';
if (diff.startsWith('@@')) return diff;
const hunkStart = diff.indexOf('\n@@');
return hunkStart === -1 ? diff : diff.substring(hunkStart + 1);
}
// Asserts that the given path is an accessible git working tree.
// Throws on failure with a descriptive error message.
export async function assertGitRepository(
projectPath: string,
signal?: AbortSignal,
): Promise<void> {
try {
await fs.access(projectPath);
} catch {
throw new Error(`Unable to access project directory: ${projectPath}`);
}
let stdout;
try {
({ stdout } = await runGit(
projectPath,
['rev-parse', '--is-inside-work-tree'],
readOnlyGitOptions({ signal }),
));
} catch (error) {
if (signal?.aborted || isGitCancellation(error)) throw error;
throw new Error('Git is not initialized in this directory. Initialize a repository with "git init" before using source control actions.');
}
if (stdout.trim() !== 'true') {
throw new Error('The target path exists but is not inside a Git working tree.');
}
}
// Resolves a file path within a project root, guarding against path traversal.
export function resolvePathWithinProject(projectPath: string, file: string): string {
const resolvedRoot = path.resolve(projectPath);
const resolvedFile = path.resolve(resolvedRoot, file);
const normalizedRoot = `${resolvedRoot}${path.sep}`;
if (!resolvedFile.startsWith(normalizedRoot) && resolvedFile !== resolvedRoot) {
throw new ProjectBoundaryError('The requested file path resolves outside the project root.');
}
return resolvedFile;
}