import { spawn } from 'node:child_process'; // Git never inherits provider configuration or arbitrary runtime environment. export function gitEnvironment(extra = {}) { const allowed = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|homedrive|homepath|home|appdata|localappdata|programfiles(?:\(x86\))?|commonprogramfiles(?:\(x86\))?|lang|lc_all)$/i; const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => allowed.test(key))); return { ...env, GIT_TERMINAL_PROMPT: '0', GIT_NO_REPLACE_OBJECTS: '1', ...extra }; } export function gitArguments(root, args, hooksDirectory) { return ['--no-pager', '--no-optional-locks', '--literal-pathspecs', '-C', root, '-c', 'core.fsmonitor=false', '-c', 'core.untrackedCache=false', '-c', 'commit.gpgSign=false', ...(hooksDirectory ? ['-c', 'core.hooksPath=' + hooksDirectory] : []), ...args]; } export function runGit(root, args, { input, env = {}, signal, timeoutMs = 0, hooksDirectory, maximumBytes = Infinity, onSpawn } = {}) { return new Promise((resolve, reject) => { if (signal?.aborted) return reject(signal.reason ?? new Error('Git操作已停止。')); const child = spawn('git', gitArguments(root, args, hooksDirectory), { env: gitEnvironment(env), windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] }); const chunks = [], errors = []; let bytes = 0, exceeded = false, timedOut = false, spawnError = null; const capture = list => chunk => { bytes += chunk.length; if (bytes > maximumBytes) { exceeded = true; child.kill(); } else list.push(chunk); }; child.stdout.on('data', capture(chunks)); child.stderr.on('data', capture(errors)); child.stdin.on('error', () => {}); const timer = timeoutMs > 0 ? setTimeout(() => { timedOut = true; child.kill(); }, timeoutMs) : null; const stop = () => child.kill(); signal?.addEventListener('abort', stop, { once: true }); child.once('error', error => { clearTimeout(timer); signal?.removeEventListener('abort', stop); reject(error); }); child.once('close', code => { clearTimeout(timer); signal?.removeEventListener('abort', stop); if (spawnError) return reject(spawnError); const output = Buffer.concat(chunks), errorOutput = Buffer.concat(errors).toString('utf8'); resolve({ ok: code === 0 && !exceeded && !timedOut && !signal?.aborted, code, output, text: output.toString('utf8'), error: errorOutput, exceeded, timedOut, aborted: !!signal?.aborted }); }); child.once('spawn', () => { try { onSpawn?.(child.pid); } catch (error) { spawnError = error; child.kill(); } }); child.stdin.end(input); }); }