| 1 | import { spawn } from 'node:child_process'; |
| 2 | import { once } |
| 3 | import type { Readable |
| 4 | import { StringDecoder } |
| 5 | |
| 6 | import { GitCommandFailedError } |
| 7 | |
| 8 | export interface RunGitOptions |
| 9 | args: string[] |
| 10 | gitDir: string; |
| 11 | input?: Buffer |
| 12 | /** Merged over the inherited environment, after `GIT_DIR`. */ |
| 13 | env?: Record |
| 14 | } |
| 15 | |
| 16 | export async function runGit |
| 17 | return (await runGitBuffer |
| 18 | } |
| 19 | |
| 20 | /** Same as {@ |
| 21 | export async function runGitBuffer |
| 22 | args, |
| 23 | gitDir, |
| 24 | input, |
| 25 | env, |
| 26 | }: RunGitOptions) |
| 27 | return new Promise |
| 28 | const child = |
| 29 | env: { ...process |
| 30 | }); |
| 31 | |
| 32 | const stdout: |
| 33 | const stderr: |
| 34 | child.stdout.on |
| 35 | child.stderr.on |
| 36 | |
| 37 | child.on('error |
| 38 | child.on('close |
| 39 | if (code === |
| 40 | reject( |
| 41 | new GitCommandFailedError( |
| 42 | args[0], |
| 43 | code, |
| 44 | Buffer.concat(stderr |
| 45 | Buffer.concat(stdout |
| 46 | ), |
| 47 | ); |
| 48 | }); |
| 49 | |
| 50 | if (input === |
| 51 | else if (Buffer. |
| 52 | else input.pipe( |
| 53 | }); |
| 54 | } |
| 55 | |
| 56 | /** git's stdout as a stream, for output too large to hold in memory. */ |
| 57 | export function runGitReadable({ |
| 58 | const child = |
| 59 | env: { ...process |
| 60 | }); |
| 61 | child.stdin.end |
| 62 | child.on('error |
| 63 | |
| 64 | return child.stdout |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Same as {@link |
| 69 | * |
| 70 | * A consumer that stops iterating kills git rather than paying for output nobody reads, so the exit status is only checked once the stream drains. |
| 71 | */ |
| 72 | export async function* |
| 73 | args, |
| 74 | gitDir, |
| 75 | input, |
| 76 | env, |
| 77 | }: RunGitOptions) |
| 78 | const child = |
| 79 | env: { ...process |
| 80 | }); |
| 81 | |
| 82 | if (input === |
| 83 | else if (Buffer. |
| 84 | else input.pipe( |
| 85 | |
| 86 | const stderr: |
| 87 | const failures: |
| 88 | child.stderr.on |
| 89 | child.on('error |
| 90 | |
| 91 | // A chunk boundary can land mid-codepoint, so decode across chunks. |
| 92 | const decoder = |
| 93 | let drained = |
| 94 | |
| 95 | try { |
| 96 | for await (const |
| 97 | const text = |
| 98 | if (text) yield |
| 99 | } |
| 100 | const tail = |
| 101 | if (tail) yield |
| 102 | drained = true; |
| 103 | } finally { |
| 104 | if (!drained) |
| 105 | } |
| 106 | |
| 107 | const [code] |
| 108 | if (failures.length |
| 109 | if (code !== |
| 110 | throw new GitCommandFailedError( |
| 111 | args[0], |
| 112 | code, |
| 113 | Buffer.concat(stderr |
| 114 | ); |
| 115 | } |
| 116 | } |