Skip to content

Commit f182cd6

Browse files
feat(git): describe only staged changes
Falling back to the working tree meant the message could describe changes the commit would not contain. An empty index now returns `nothing-staged`, which the caller turns into advice to stage something, and `no-changes` is reserved for a genuinely clean tree. Removes the untracked-file reading that only the fallback needed.
1 parent 2e6f3a3 commit f182cd6

2 files changed

Lines changed: 25 additions & 144 deletions

File tree

‎src/utils/__tests__/git.spec.ts‎

Lines changed: 13 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -427,25 +427,11 @@ describe("git utils", () => {
427427
return result.context
428428
}
429429

430-
const mockUntrackedFile = (contents: Buffer | null) => {
431-
vitest.mocked(fs.promises.open).mockImplementation((async () => {
432-
if (!contents) {
433-
throw new Error("ENOENT")
434-
}
435-
436-
return {
437-
read: async (buffer: Buffer) => ({ bytesRead: contents.copy(buffer) }),
438-
close: async () => {},
439-
}
440-
}) as unknown as typeof fs.promises.open)
441-
}
442-
443430
it("should collect staged changes as structured entries", async () => {
444431
mockProbes()
445432
mockGit(staged(`M${NUL}src/file1.ts${NUL}A${NUL}src/new.ts${NUL}D${NUL}src/gone.ts${NUL}`))
446433

447434
const context = await expectContext()
448-
expect(context.staged).toBe(true)
449435
expect(context.files).toEqual([
450436
{ status: "modified", path: "src/file1.ts" },
451437
{ status: "added", path: "src/new.ts" },
@@ -496,61 +482,36 @@ describe("git utils", () => {
496482
expect(calls.map((call) => call.args)).toContainEqual(["diff", "--cached", "--unified=1"])
497483
})
498484

499-
it("should fall back to the working tree when nothing is staged", async () => {
485+
// Only the index is described, so a dirty working tree with an empty index is a distinct
486+
// outcome: the user can fix it by staging, and the caller says so.
487+
it("should report nothing-staged when the working tree is dirty but the index is empty", async () => {
500488
mockProbes()
501489
mockGit(workingTree(` M src/file1.ts${NUL}?? src/untracked.ts${NUL}`))
502-
mockUntrackedFile(Buffer.from("export const value = 1\n"))
503490

504-
const context = await expectContext()
505-
expect(context.staged).toBe(false)
506-
expect(context.files).toEqual([
507-
{ status: "modified", path: "src/file1.ts" },
508-
{ status: "untracked", path: "src/untracked.ts" },
509-
])
491+
expect(await getCommitContext(cwd)).toEqual({ ok: false, reason: "nothing-staged" })
510492
})
511493

512-
// Porcelain reverses the field order of `diff --name-status`: here the new path comes first.
513-
it("should parse porcelain renames, where the new path comes first", async () => {
494+
it("should describe only the index when both it and the working tree have changes", async () => {
514495
mockProbes()
515-
mockGit(workingTree(`R new name.ts${NUL}old name.ts${NUL}M after.ts${NUL}`))
516-
517-
expect((await expectContext()).files).toEqual([
518-
{ status: "renamed", path: "new name.ts", oldPath: "old name.ts" },
519-
{ status: "modified", path: "after.ts" },
520-
])
521-
})
522-
523-
it("should include bounded contents for untracked files", async () => {
524-
mockProbes()
525-
mockGit(workingTree(`?? src/untracked.ts${NUL}`))
526-
mockUntrackedFile(Buffer.from("export const answer = 42\n"))
527-
528-
const context = await expectContext()
529-
expect(context.diff).toContain("New file: src/untracked.ts")
530-
expect(context.diff).toContain("export const answer = 42")
531-
})
532-
533-
it("should skip untracked files that look binary", async () => {
534-
mockProbes()
535-
mockGit(workingTree(`?? assets/logo.png${NUL}`))
536-
mockUntrackedFile(Buffer.from([0x89, 0x50, 0x00, 0x4e, 0x47]))
496+
// `workingTree` blanks the staged listing, so the staged responses have to win.
497+
mockGit({
498+
...workingTree(` M src/unstaged.ts${NUL}`),
499+
...staged(`M${NUL}src/staged.ts${NUL}`),
500+
})
537501

538-
const context = await expectContext()
539-
expect(context.files).toEqual([{ status: "untracked", path: "assets/logo.png" }])
540-
expect(context.diff).not.toContain("New file: assets/logo.png")
502+
expect((await expectContext()).files).toEqual([{ status: "modified", path: "src/staged.ts" }])
541503
})
542504

543505
it("should work in a repository without an initial commit", async () => {
544506
mockProbes()
545507
// `git log` fails before the first commit, and must not take the collection down with it.
546-
const responses = workingTree(`?? file.txt${NUL}`)
508+
const responses = staged(`A${NUL}file.txt${NUL}`)
547509
delete responses["log -n5 --format=%s"]
548510
mockGit(responses)
549-
mockUntrackedFile(Buffer.from("hello\n"))
550511

551512
const context = await expectContext()
552513
expect(context.recentCommits).toEqual([])
553-
expect(context.files).toEqual([{ status: "untracked", path: "file.txt" }])
514+
expect(context.files).toEqual([{ status: "added", path: "file.txt" }])
554515
})
555516

556517
// A line limit alone is not a bound: one generated file can be a single enormous line.

‎src/utils/git.ts‎

Lines changed: 12 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,6 @@ const GIT_DIFF_MAX_BUFFER = 10 * 1024 * 1024
2828
// the one latency factor we control without affecting the model's output.
2929
const COMMIT_DIFF_ARGS = ["--unified=1"]
3030

31-
// Untracked files have no diff, so their contents are read directly. Enough to tell the model
32-
// what a new file is for, not enough for a large one to crowd out the rest of the context.
33-
const UNTRACKED_FILE_BYTE_LIMIT = 2 * 1024
34-
const UNTRACKED_TOTAL_CHARACTER_LIMIT = 20 * 1024
35-
3631
const RECENT_COMMIT_COUNT = 5
3732

3833
/**
@@ -380,19 +375,17 @@ export interface GitFileChange {
380375
}
381376

382377
export interface CommitContext {
383-
/** True when describing the index, false when describing the whole working tree. */
384-
staged: boolean
385378
/** Undefined when HEAD is detached. */
386379
branch?: string
387380
recentCommits: string[]
388381
files: GitFileChange[]
389-
/** The diff, followed by the contents of any untracked files. Truncated to fit a prompt. */
382+
/** The staged diff, truncated to fit a prompt. */
390383
diff: string
391384
}
392385

393386
export type CommitContextResult =
394387
| { ok: true; context: CommitContext }
395-
| { ok: false; reason: "git-missing" | "not-a-repo" | "no-changes" | "failed"; error?: string }
388+
| { ok: false; reason: "git-missing" | "not-a-repo" | "no-changes" | "nothing-staged" | "failed"; error?: string }
396389

397390
async function runGit(args: string[], cwd: string): Promise<string> {
398391
const { stdout } = await execFileAsync("git", args, { cwd, maxBuffer: GIT_DIFF_MAX_BUFFER })
@@ -499,65 +492,6 @@ function parsePorcelainStatus(stdout: string): GitFileChange[] {
499492
return files
500493
}
501494

502-
/**
503-
* Reads up to `UNTRACKED_FILE_BYTE_LIMIT` bytes of a file, or null if it cannot be read or looks
504-
* binary. Only the head of the file is read, so an enormous untracked file costs nothing.
505-
*/
506-
async function readBoundedText(filePath: string): Promise<string | null> {
507-
const handle = await fs.open(filePath, "r").catch(() => null)
508-
509-
if (!handle) {
510-
return null
511-
}
512-
513-
try {
514-
const buffer = Buffer.alloc(UNTRACKED_FILE_BYTE_LIMIT)
515-
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0)
516-
const contents = buffer.subarray(0, bytesRead)
517-
518-
// An embedded NUL is the same heuristic git itself uses to call a file binary.
519-
return contents.includes(0) ? null : contents.toString("utf8")
520-
} catch {
521-
return null
522-
} finally {
523-
await handle.close().catch(() => {})
524-
}
525-
}
526-
527-
/**
528-
* Collects the contents of untracked files, which no diff would show. Without this an
529-
* untracked-only change reaches the model as a bare list of filenames.
530-
*/
531-
async function getUntrackedContents(cwd: string, files: GitFileChange[]): Promise<string> {
532-
const untracked = files.filter((file) => file.status === "untracked")
533-
534-
if (untracked.length === 0) {
535-
return ""
536-
}
537-
538-
// Porcelain paths are relative to the repository root, which is not necessarily `cwd`.
539-
const root = (await runGit(["rev-parse", "--show-toplevel"], cwd).catch(() => "")).trim() || cwd
540-
const sections: string[] = []
541-
let total = 0
542-
543-
for (const file of untracked) {
544-
if (total >= UNTRACKED_TOTAL_CHARACTER_LIMIT) {
545-
break
546-
}
547-
548-
const contents = await readBoundedText(path.join(root, file.path))
549-
550-
if (contents === null) {
551-
continue
552-
}
553-
554-
sections.push(`--- New file: ${file.path} ---\n${contents}`)
555-
total += contents.length
556-
}
557-
558-
return sections.join("\n\n")
559-
}
560-
561495
/** Both of these are context, not the payload, so a repository without commits still works. */
562496
async function getCurrentBranch(cwd: string): Promise<string | undefined> {
563497
const branch = await runGit(["branch", "--show-current"], cwd).catch(() => "")
@@ -575,8 +509,9 @@ async function getRecentCommits(cwd: string): Promise<string[]> {
575509
/**
576510
* Collects the changes to describe in a commit message.
577511
*
578-
* Prefers staged changes, since that is what a commit will actually contain. When nothing is
579-
* staged, falls back to the whole working tree so the caller still has something to summarize.
512+
* Only the index is described, since that is exactly what a commit will contain. An empty index
513+
* returns `nothing-staged` rather than falling back to the working tree, so the message can never
514+
* describe changes the commit would not include.
580515
*
581516
* Every command runs through `execFile` with an argument array, so no path is ever interpolated
582517
* into a shell string, and every listing is read in NUL-delimited form.
@@ -598,26 +533,17 @@ export async function getCommitContext(cwd: string): Promise<CommitContextResult
598533

599534
if (staged.length > 0) {
600535
const diff = await runGit(["diff", "--cached", ...COMMIT_DIFF_ARGS], cwd)
601-
return { ok: true, context: await buildContext(cwd, true, staged, diff) }
536+
return { ok: true, context: await buildContext(cwd, staged, diff) }
602537
}
603538

604-
// Nothing staged - describe the working tree instead. `--untracked-files=all` lists files
605-
// inside new directories individually, which the default summarized form would collapse.
606-
const files = parsePorcelainStatus(
539+
// Only the index is described, so an empty one has nothing to summarize. Whether the
540+
// working tree is dirty decides which of the two messages the caller shows: "stage
541+
// something first" is only useful advice when there is in fact something to stage.
542+
const worktree = parsePorcelainStatus(
607543
await runGit(["status", "--porcelain=v1", "-z", "--untracked-files=all"], cwd),
608544
)
609545

610-
if (files.length === 0) {
611-
return { ok: false, reason: "no-changes" }
612-
}
613-
614-
// Deliberately `git diff` rather than `git diff HEAD`: we only reach this branch when the
615-
// index is empty, so the two produce identical output - but `HEAD` does not resolve in a
616-
// repository without an initial commit, where it would fail outright.
617-
const diff = await runGit(["diff", ...COMMIT_DIFF_ARGS], cwd)
618-
const untracked = await getUntrackedContents(cwd, files)
619-
620-
return { ok: true, context: await buildContext(cwd, false, files, `${diff}\n\n${untracked}`) }
546+
return { ok: false, reason: worktree.length > 0 ? "nothing-staged" : "no-changes" }
621547
} catch (error) {
622548
// Failures here are expected rather than exceptional - an oversized diff exceeding
623549
// `maxBuffer`, a repository in a state git refuses to describe - so the caller gets a
@@ -626,14 +552,8 @@ export async function getCommitContext(cwd: string): Promise<CommitContextResult
626552
}
627553
}
628554

629-
async function buildContext(
630-
cwd: string,
631-
staged: boolean,
632-
files: GitFileChange[],
633-
diff: string,
634-
): Promise<CommitContext> {
555+
async function buildContext(cwd: string, files: GitFileChange[], diff: string): Promise<CommitContext> {
635556
return {
636-
staged,
637557
branch: await getCurrentBranch(cwd),
638558
recentCommits: await getRecentCommits(cwd),
639559
files,

0 commit comments

Comments
 (0)