Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

git.ts

295 lines8.2 KB

1/**
2 * Git snapshot, patch, worktree, commit, and push helpers. All git I/O goes through an injected runner
3 * so tests can use fixed Git responses or isolated fixture repositories.
4 */
5​
6export type GitRunner = (
7 args: Array<string>,
8 cwd: string,
9 input?: string,
10) => Promise<{ stdout: string; stderr: string; code: number }>
11​
12/** Read one complete diff from fixed commits without checking out PR files. */
13export async function readPullSnapshot(
14 repoRoot: string,
15 pull: { baseSha: string; headSha: string },
16 runner: GitRunner,
17) {
18 for (const sha of [pull.baseSha, pull.headSha]) {
19 if (!/^[0-9a-f]{40}$/i.test(sha)) throw new Error('Invalid snapshot SHA')
20 }
21 async function read(args: Array<string>) {
22 const result = await runner(args, repoRoot)
23 if (result.code !== 0) gitFailed(args, result)
24 if (Buffer.byteLength(result.stdout, 'utf8') > 10_000_000) {
25 throw new Error('Review snapshot exceeds 10 MB')
26 }
27 return result.stdout
28 }
29 await read([
30 'fetch',
31 '--no-tags',
32 '--no-recurse-submodules',
33 'origin',
34 pull.baseSha,
35 pull.headSha,
36 ])
37 const mergeBase = (
38 await read(['merge-base', pull.baseSha, pull.headSha])
39 ).trim()
40 if (!/^[0-9a-f]{40}$/i.test(mergeBase))
41 throw new Error('Missing snapshot merge base')
42 const diffArgs = [
43 'diff',
44 '--no-ext-diff',
45 '--no-textconv',
46 '--no-renames',
47 '--no-color',
48 '--no-relative',
49 '--ignore-submodules=none',
50 ]
51 const raw = await read([
52 ...diffArgs,
53 '--raw',
54 '-z',
55 '--no-abbrev',
56 mergeBase,
57 pull.headSha,
58 '--',
59 ])
60 const fields = raw.split('\0')
61 if (fields.pop() !== '' || fields.length % 2 !== 0)
62 throw new Error('Incomplete snapshot file list')
63 // A type change is one raw entry but two patch sections (delete, then add),
64 // so it would fail the count check below with a misleading reason.
65 if (fields.some((field, index) => index % 2 === 0 && field.endsWith(' T')))
66 throw new Error('File type changes are not supported')
67 const diff = await read([
68 ...diffArgs,
69 '--patch',
70 '--full-index',
71 '--src-prefix=a/',
72 '--dst-prefix=b/',
73 mergeBase,
74 pull.headSha,
75 '--',
76 ])
77 const starts = [...diff.matchAll(/^diff --git /gm)].map(
78 (match) => match.index,
79 )
80 if (diff.length > 0 && starts[0] !== 0)
81 throw new Error('Malformed snapshot patch')
82 const sections = starts.map((start, index) =>
83 diff.slice(start, starts[index + 1]),
84 )
85 if (sections.length !== fields.length / 2)
86 throw new Error('Incomplete snapshot patch')
87 const files = []
88 for (let index = 0; index < fields.length; index += 2) {
89 const header =
90 /^:(\d{6}) (\d{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) ([AMD])$/.exec(
91 fields[index] ?? '',
92 )
93 const path = fields[index + 1]
94 const patch = sections[index / 2]
95 if (
96 header === null ||
97 path === undefined ||
98 path.length === 0 ||
99 patch === undefined
100 ) {
101 throw new Error('Malformed snapshot file entry')
102 }
103 const baseMode = header[1] ?? ''
104 const headMode = header[2] ?? ''
105 const packageFile = /(^|\/)package\.json$/.test(path)
106 const before =
107 packageFile && ['100644', '100755'].includes(baseMode)
108 ? await read(['cat-file', 'blob', header[3] ?? ''])
109 : null
110 const after =
111 packageFile && ['100644', '100755'].includes(headMode)
112 ? await read(['cat-file', 'blob', header[4] ?? ''])
113 : null
114 files.push({
115 path,
116 patch: /^Binary files |^GIT binary patch$/m.test(patch) ? null : patch,
117 baseMode,
118 headMode,
119 before,
120 after,
121 })
122 }
123 return { mergeBase, diff, files }
125​
126/** A git command exited non-zero. `args` lets a caller tell fetch from diff. */
127export class GitCommandError extends Error {
128 readonly args: Array<string>
129​
130 constructor(args: Array<string>, message: string) {
131 super(message)
132 this.args = args
133 }
135​
136function gitFailed(
137 args: Array<string>,
138 result: { stdout: string; stderr: string; code: number },
139): never {
140 const detail = result.stderr.trim() || result.stdout.trim()
141 const suffix = detail.length > 0 ? `: ${detail}` : ''
142 throw new GitCommandError(
143 args,
144 `git ${args.join(' ')} exited ${result.code}${suffix}`,
145 )
147​
148/** Check and apply a unified patch through stdin. */
149export async function applyPatch(
150 cwd: string,
151 patch: string,
152 runner: GitRunner,
153) {
154 const checkArgs = ['apply', '--check', '--whitespace=error-all', '-']
155 const check = await runner(checkArgs, cwd, patch)
156 if (check.code !== 0) gitFailed(checkArgs, check)
157​
158 const applyArgs = ['apply', '--whitespace=error-all', '-']
159 const apply = await runner(applyArgs, cwd, patch)
160 if (apply.code !== 0) gitFailed(applyArgs, apply)
162​
163/** Fetch a PR head and create a detached worktree only when its SHA matches. */
164export async function preparePullWorktree(
165 repoRoot: string,
166 worktreeRoot: string,
167 pullNumber: number,
168 expectedSha: string,
169 runner: GitRunner,
170) {
171 const fetchArgs = [
172 'fetch',
173 '--no-tags',
174 'origin',
175 `pull/${String(pullNumber)}/head`,
176 ]
177 const fetch = await runner(fetchArgs, repoRoot)
178 if (fetch.code !== 0) gitFailed(fetchArgs, fetch)
179​
180 const revParseArgs = ['rev-parse', 'FETCH_HEAD']
181 const revParse = await runner(revParseArgs, repoRoot)
182 if (revParse.code !== 0) gitFailed(revParseArgs, revParse)
183 const actualSha = revParse.stdout.trim()
184 if (actualSha !== expectedSha) {
185 throw new Error(
186 `PR head changed during review: expected ${expectedSha}, got ${actualSha}`,
187 )
188 }
189​
190 const worktreeArgs = [
191 'worktree',
192 'add',
193 '--detach',
194 worktreeRoot,
195 expectedSha,
196 ]
197 const worktree = await runner(worktreeArgs, repoRoot)
198 if (worktree.code !== 0) gitFailed(worktreeArgs, worktree)
200​
201/**
202 * Stage every change in `cwd` and commit with `identity`.
203 *
204 * Runs `git add -A`, then `git -c user.name= -c user.email= commit -m`.
205 * Returns `{ committed: false }` when commit exits 1 because there is
206 * nothing to commit. Other non-zero exits throw.
207 *
208 * @param cwd git working tree
209 * @param message commit message
210 * @param runner injected git runner
211 * @param identity author and committer name and email
212 */
213export async function commitAll(
214 cwd: string,
215 message: string,
216 runner: GitRunner,
217 identity: { name: string; email: string },
218): Promise<{ committed: boolean }> {
219 const addArgs = ['add', '-A']
220 const add = await runner(addArgs, cwd)
221 if (add.code !== 0) {
222 gitFailed(addArgs, add)
223 }
224​
225 const commitArgs = [
226 '-c',
227 `user.name=${identity.name}`,
228 '-c',
229 `user.email=${identity.email}`,
230 'commit',
231 '-m',
232 message,
233 ]
234 const commit = await runner(commitArgs, cwd)
235 if (commit.code === 0) {
236 return { committed: true }
237 }
238​
239 const output = `${commit.stdout}\n${commit.stderr}`
240 const isEmptyCommit =
241 commit.code === 1 && output.includes('nothing to commit')
242 if (isEmptyCommit) {
243 return { committed: false }
244 }
245​
246 gitFailed(commitArgs, commit)
248​
249/**
250 * Push `HEAD` to `dest.ref` on `dest.remoteUrl` with `--force-with-lease`.
251 *
252 * Never uses a bare `--force`. Throws when git exits non-zero.
253 *
254 * @param cwd git working tree
255 * @param runner injected git runner
256 * @param dest remote URL and destination ref
257 */
258export async function pushHead(
259 cwd: string,
260 runner: GitRunner,
261 dest: { remoteUrl: string; ref: string; expectedSha: string },
262) {
263 const args = [
264 'push',
265 `--force-with-lease=refs/heads/${dest.ref}:${dest.expectedSha}`,
266 dest.remoteUrl,
267 `HEAD:${dest.ref}`,
268 ]
269 const result = await runner(args, cwd)
270 if (result.code !== 0) {
271 const detail = (result.stderr.trim() || result.stdout.trim()).replaceAll(
272 dest.remoteUrl,
273 '<redacted remote>',
274 )
275 const suffix = detail.length > 0 ? `: ${detail}` : ''
276 throw new Error(`git push exited ${result.code}${suffix}`)
277 }
279​
280/**
281 * HTTPS remote URL for pushing the PR head, with an access token.
282 *
283 * Same-repo PRs use `originRepo`. Forks use `headRepo`.
284 *
285 * @param opts fork flag, origin/head repos, and token
286 */
287export function headRemoteUrl(opts: {
288 isFork: boolean
289 originRepo: string
290 headRepo: string
291 token: string
292}) {
293 const repo = opts.isFork ? opts.headRepo : opts.originRepo
294 return `https://x-access-token:${opts.token}@github.com/${repo}.git`