| 1 | import childProcess from 'node:child_process' |
| 2 | import { AsyncLocalStorage } from 'node:async_hooks' |
| 3 | import { syncBuiltinESMExports } from 'node:module' |
| 4 | import { resolve } from 'node:path' |
| 5 | import { PassThrough } from 'node:stream' |
| 6 | import { promisify } from 'node:util' |
| 7 | import type { CoreApi } from './core.ts' |
| 8 | import type { Json } from '../protocol.ts' |
| 9 | |
| 10 | interface GitInvocation { |
| 11 | workspace: string |
| 12 | core: Readonly<CoreApi> |
| 13 | signal: AbortSignal |
| 14 | live(): boolean |
| 15 | } |
| 16 | |
| 17 | export const gitInvocations = new AsyncLocalStorage<GitInvocation | undefined>() |
| 18 | let installed = false |
| 19 | |
| 20 | function queryFor(args: unknown): Record<string, Json> { |
| 21 | if (!Array.isArray(args) || args.length > 8 || args.some(x => typeof x !== 'string' || x.length > 1024 || /[\x00-\x1f\x7f]/.test(x))) { |
| 22 | throw new Error('Git review scopes require bounded metadata arguments') |
| 23 | } |
| 24 | const argv = args[0] === '--no-optional-locks' ? args.slice(1) : args |
| 25 | const exact = (...values: string[]) => argv.length === values.length && argv.every((value, index) => value === values[index]) |
| 26 | if (exact('for-each-ref', '--format=%(refname:short)', 'refs/heads')) return { query: 'branches' } |
| 27 | if (exact('log', '-n', '100', '--format=%H%x09%s')) return { query: 'commits' } |
| 28 | if (exact('rev-parse', '--show-toplevel')) return { query: 'root' } |
| 29 | if (argv.length === 4 && argv[0] === 'rev-parse' && argv[1] === '--verify' && argv[2] === '--end-of-options') return { query: 'resolve', rev: argv[3] } |
| 30 | if (argv.length === 4 && argv[0] === 'rev-list' && argv[1] === '--left-right' && argv[2] === '--count') { |
| 31 | const refs = argv[3].split('...') |
| 32 | if (refs.length === 2) return { query: 'ahead_behind', ours: refs[0], theirs: refs[1] } |
| 33 | } |
| 34 | if (argv.length === 3 && argv[0] === 'merge-base') return { query: 'merge_base', ours: argv[1], theirs: argv[2] } |
| 35 | throw new Error('Only read-only Git review metadata is available through the Engine') |
| 36 | } |
| 37 | |
| 38 | export function installGitAdapter(inPluginContext: () => boolean): void { |
| 39 | if (installed) return |
| 40 | installed = true |
| 41 | const original = childProcess.execFile |
| 42 | const adapter = function (...raw: unknown[]): childProcess.ChildProcess { |
| 43 | if (raw[0] !== 'git' || (!gitInvocations.getStore() && !inPluginContext())) return Reflect.apply(original, childProcess, raw) |
| 44 | const invocation = gitInvocations.getStore() |
| 45 | const callback = typeof raw.at(-1) === 'function' ? raw.pop() as (error: unknown, stdout: string | Buffer, stderr: string | Buffer) => void : undefined |
| 46 | const args = Array.isArray(raw[1]) ? raw[1] : [] |
| 47 | const options = (Array.isArray(raw[1]) ? raw[2] : raw[1]) ?? {} |
| 48 | const child = new childProcess.ChildProcess() |
| 49 | const stdout = new PassThrough() |
| 50 | const stderr = new PassThrough() |
| 51 | child.stdout = stdout |
| 52 | child.stderr = stderr |
| 53 | const cancelled = new AbortController() |
| 54 | child.kill = () => { cancelled.abort(); return true } |
| 55 | let timeout: NodeJS.Timeout | undefined |
| 56 | let userSignal: AbortSignal | undefined |
| 57 | let gitExit = false |
| 58 | const run = async () => { |
| 59 | if (!invocation || !invocation.live() || invocation.signal.aborted) throw new Error('Git review metadata requires a live plugin tool invocation') |
| 60 | if (typeof options !== 'object' || options === null || Array.isArray(options)) throw new TypeError('Invalid Git metadata options') |
| 61 | const opts = options as Record<string, unknown> |
| 62 | if (Object.keys(opts).some(key => !['cwd', 'signal', 'encoding', 'maxBuffer', 'timeout', 'windowsHide', 'env'].includes(key))) throw new TypeError('Unsupported Git metadata option') |
| 63 | if (opts.cwd !== undefined && (typeof opts.cwd !== 'string' || resolve(opts.cwd) !== resolve(invocation.workspace))) throw new Error('Git review metadata is scoped to the calling workspace') |
| 64 | if (opts.env !== undefined) { |
| 65 | if (typeof opts.env !== 'object' || opts.env === null || Array.isArray(opts.env)) throw new TypeError('Invalid Git metadata environment') |
| 66 | for (const [key, value] of Object.entries(opts.env)) { |
| 67 | if (value === process.env[key] || (key === 'GIT_TERMINAL_PROMPT' && value === '0') || (key === 'GIT_OPTIONAL_LOCKS' && value === '0')) continue |
| 68 | throw new Error('Git review metadata uses the Engine environment') |
| 69 | } |
| 70 | } |
| 71 | const max = opts.maxBuffer ?? 1024 * 1024 |
| 72 | if (!Number.isSafeInteger(max) || (max as number) < 1 || (max as number) > 1024 * 1024) throw new TypeError('Git metadata maxBuffer must be at most 1 MiB') |
| 73 | const encoding = opts.encoding ?? 'utf8' |
| 74 | if (encoding !== 'buffer' && (typeof encoding !== 'string' || !Buffer.isEncoding(encoding))) throw new TypeError('Invalid Git metadata encoding') |
| 75 | if (opts.signal !== undefined && !(opts.signal instanceof AbortSignal)) throw new TypeError('Invalid Git metadata signal') |
| 76 | if (opts.timeout !== undefined && (!Number.isSafeInteger(opts.timeout) || (opts.timeout as number) < 0)) throw new TypeError('Invalid Git metadata timeout') |
| 77 | if (typeof opts.timeout === 'number' && opts.timeout > 0) timeout = setTimeout(() => cancelled.abort(), Math.min(opts.timeout, 10_000)) |
| 78 | userSignal = opts.signal instanceof AbortSignal ? opts.signal : undefined |
| 79 | const signal = AbortSignal.any([invocation.signal, cancelled.signal, ...(userSignal ? [userSignal] : [])]) |
| 80 | signal.throwIfAborted() |
| 81 | const result = await invocation.core.call('Git', { action: 'review_scope', ...queryFor(args) }, { signal }) |
| 82 | signal.throwIfAborted() |
| 83 | if (!invocation.live()) throw new Error('Git metadata invocation ended') |
| 84 | const value = result.structured |
| 85 | if (result.isError) throw new Error(`Git review metadata unavailable: ${result.content.slice(0, 300)}`) |
| 86 | if (value === null || typeof value !== 'object' || Array.isArray(value) || typeof value.stdout !== 'string' || typeof value.stderr !== 'string' || !Number.isInteger(value.exit_code)) { |
| 87 | throw new Error(result.content.includes('[output truncated') ? 'Git review metadata exceeded the Engine nested-call result limit' : 'Engine did not return complete Git review metadata') |
| 88 | } |
| 89 | if (Buffer.byteLength(value.stdout) > (max as number) || Buffer.byteLength(value.stderr) > (max as number)) throw Object.assign(new RangeError('stdout maxBuffer length exceeded'), { code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' }) |
| 90 | const out = Buffer.from(value.stdout) |
| 91 | const err = Buffer.from(value.stderr) |
| 92 | const data = { stdout: encoding === 'buffer' ? out : out.toString(encoding as BufferEncoding), stderr: encoding === 'buffer' ? err : err.toString(encoding as BufferEncoding), code: value.exit_code as number } |
| 93 | if (data.code !== 0) { |
| 94 | gitExit = true |
| 95 | throw Object.assign(new Error(value.stderr || 'Git review metadata failed'), { code: data.code, stdout: data.stdout, stderr: data.stderr }) |
| 96 | } |
| 97 | return data |
| 98 | } |
| 99 | void run().then(data => { |
| 100 | stdout.end(data.stdout) |
| 101 | stderr.end(data.stderr) |
| 102 | Object.defineProperty(child, 'exitCode', { value: 0, configurable: true }) |
| 103 | callback?.(null, data.stdout, data.stderr) |
| 104 | child.emit('exit', 0, null) |
| 105 | child.emit('close', 0, null) |
| 106 | }, failure => { |
| 107 | let error = failure instanceof Error ? failure : new Error(String(failure)) |
| 108 | const verdict = (error as { code?: unknown }).code |
| 109 | const decided = verdict === 'denied' || verdict === 'refused' || verdict === 'unavailable' |
| 110 | if (!gitExit && !decided && (cancelled.signal.aborted || invocation?.signal.aborted || userSignal?.aborted)) { |
| 111 | const killed = cancelled.signal.aborted && !invocation?.signal.aborted && !userSignal?.aborted |
| 112 | error = killed |
| 113 | ? Object.assign(new Error('Command failed: git'), { killed: true, signal: 'SIGTERM', code: null, cause: failure }) |
| 114 | : Object.assign(new Error('The operation was aborted', { cause: failure }), { name: 'AbortError', code: 'ABORT_ERR' }) |
| 115 | } |
| 116 | const detail = error as Error & { code?: string | number | null; stdout?: string | Buffer; stderr?: string | Buffer } |
| 117 | if (detail.code === undefined) detail.code = 'CW_GIT_REFUSED' |
| 118 | detail.stdout ??= '' |
| 119 | detail.stderr ??= '' |
| 120 | stdout.end(detail.stdout ?? '') |
| 121 | stderr.end(detail.stderr ?? '') |
| 122 | if (callback) callback(error, detail.stdout ?? '', detail.stderr ?? '') |
| 123 | if (gitExit) { |
| 124 | Object.defineProperty(child, 'exitCode', { value: detail.code, configurable: true }) |
| 125 | child.emit('exit', detail.code as number, null) |
| 126 | child.emit('close', detail.code as number, null) |
| 127 | } else { |
| 128 | if (!callback && child.listenerCount('error') > 0) child.emit('error', error) |
| 129 | child.emit('close', null, null) |
| 130 | } |
| 131 | }).finally(() => { if (timeout !== undefined) clearTimeout(timeout) }) |
| 132 | return child |
| 133 | } |
| 134 | Object.defineProperty(adapter, promisify.custom, { value: (...raw: unknown[]) => { |
| 135 | let child: childProcess.ChildProcess |
| 136 | const promise = new Promise((resolveResult, reject) => { |
| 137 | child = adapter(...raw, (error: unknown, stdout: string | Buffer, stderr: string | Buffer) => error ? reject(error) : resolveResult({ stdout, stderr })) |
| 138 | }) |
| 139 | return Object.assign(promise, { child: child! }) |
| 140 | } }) |
| 141 | childProcess.execFile = adapter as typeof childProcess.execFile |
| 142 | syncBuiltinESMExports() |
| 143 | } |
| 144 |