Skip to content

Commit 518a8fb

Browse files
feat(git): describe the working tree when nothing is staged
Staged changes are still what a message describes whenever there are any. Only when the index is empty does collection now fall back to the working tree, so an unstaged or untracked-only change is described instead of being refused, as issue #282 requires. The two are never mixed: staged wins outright. Untracked files carry no diff, so their contents are inlined. That is bounded on every axis that can grow without limit - at most ten files, at most 8KB read from each without loading the rest, and anything with a NUL byte marked binary rather than pasted in. Files past the limit are still named, since an added file is part of the change even when there is no room to show it. Rename and copy detection is also now requested explicitly instead of inheriting `diff.renames`, which decided whether a moved file reached the model as a rename or as an unrelated delete plus add depending on the user's git configuration. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent f182cd6 commit 518a8fb

2 files changed

Lines changed: 202 additions & 23 deletions

File tree

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

Lines changed: 114 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -401,17 +401,16 @@ describe("git utils", () => {
401401
}
402402

403403
const staged = (nameStatus: string, diff = mockDiff): Record<string, string> => ({
404-
"diff --cached --name-status -z": nameStatus,
405-
"diff --cached --unified=1": diff,
404+
"diff --cached --name-status -z --find-renames --find-copies": nameStatus,
405+
"diff --cached --unified=1 --find-renames --find-copies": diff,
406406
"branch --show-current": "feature/x\n",
407407
"log -n5 --format=%s": "earlier subject\n",
408408
})
409409

410410
const workingTree = (status: string, diff = mockDiff): Record<string, string> => ({
411-
"diff --cached --name-status -z": "",
411+
"diff --cached --name-status -z --find-renames --find-copies": "",
412412
"status --porcelain=v1 -z --untracked-files=all": status,
413-
"diff --unified=1": diff,
414-
"rev-parse --show-toplevel": `${cwd}\n`,
413+
"diff --unified=1 --find-renames --find-copies": diff,
415414
"branch --show-current": "main\n",
416415
"log -n5 --format=%s": "earlier subject\n",
417416
})
@@ -478,17 +477,119 @@ describe("git utils", () => {
478477

479478
expect(calls.length).toBeGreaterThan(0)
480479
expect(calls.every((call) => call.file === "git")).toBe(true)
481-
expect(calls.map((call) => call.args)).toContainEqual(["diff", "--cached", "--name-status", "-z"])
482-
expect(calls.map((call) => call.args)).toContainEqual(["diff", "--cached", "--unified=1"])
480+
expect(calls.map((call) => call.args)).toContainEqual([
481+
"diff",
482+
"--cached",
483+
"--name-status",
484+
"-z",
485+
"--find-renames",
486+
"--find-copies",
487+
])
488+
expect(calls.map((call) => call.args)).toContainEqual([
489+
"diff",
490+
"--cached",
491+
"--unified=1",
492+
"--find-renames",
493+
"--find-copies",
494+
])
495+
})
496+
497+
// Left to `diff.renames`, a moved file reaches the model as a delete plus an add for some
498+
// users and as a rename for others.
499+
it("should ask for rename and copy detection rather than relying on git configuration", async () => {
500+
mockProbes()
501+
const calls = mockGit(staged(`R100${NUL}src/old.ts${NUL}src/new.ts${NUL}`))
502+
503+
await getCommitContext(cwd)
504+
505+
expect(
506+
calls.every(
507+
(call) =>
508+
!call.args.includes("diff") ||
509+
(call.args.includes("--find-renames") && call.args.includes("--find-copies")),
510+
),
511+
).toBe(true)
512+
})
513+
514+
it("should describe the working tree when the index is empty", async () => {
515+
mockProbes()
516+
mockGit(workingTree(` M src/file1.ts${NUL}`))
517+
518+
const context = await expectContext()
519+
520+
expect(context.files).toEqual([{ status: "modified", path: "src/file1.ts" }])
521+
expect(context.diff).toContain("+new line")
522+
})
523+
524+
// Reads `bytes` into the caller's buffer, the way a real file handle would.
525+
const mockUntrackedFile = (bytes: Buffer) => {
526+
const close = vitest.fn().mockResolvedValue(undefined)
527+
528+
vitest.mocked(fs.promises.open).mockResolvedValue({
529+
read: vitest.fn().mockImplementation(async (buffer: Buffer, offset: number, length: number) => {
530+
const written = bytes.copy(buffer, offset, 0, Math.min(length, bytes.length))
531+
return { bytesRead: written }
532+
}),
533+
close,
534+
} as never)
535+
536+
return { close }
537+
}
538+
539+
// A path alone does not say what an added file is for, which is most of what a commit
540+
// message about a new file has to convey.
541+
it("should inline the contents of untracked files", async () => {
542+
mockProbes()
543+
mockGit(workingTree(`?? src/added.ts${NUL}`, ""))
544+
mockUntrackedFile(Buffer.from("export const answer = 42\n"))
545+
546+
const context = await expectContext()
547+
548+
expect(context.files).toEqual([{ status: "untracked", path: "src/added.ts" }])
549+
expect(context.diff).toContain("+++ b/src/added.ts")
550+
expect(context.diff).toContain("export const answer = 42")
551+
})
552+
553+
it("should mark binary untracked files instead of inlining them", async () => {
554+
mockProbes()
555+
mockGit(workingTree(`?? assets/logo.png${NUL}`, ""))
556+
mockUntrackedFile(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0x01, 0x02]))
557+
558+
expect((await expectContext()).diff).toContain("(binary file)")
559+
})
560+
561+
it("should read only the beginning of a large untracked file", async () => {
562+
mockProbes()
563+
mockGit(workingTree(`?? data/big.txt${NUL}`, ""))
564+
mockUntrackedFile(Buffer.from("x".repeat(64 * 1024)))
565+
566+
const context = await expectContext()
567+
568+
expect(context.diff).toContain("(truncated)")
569+
// The cap is what bounds this, not the number of bytes the file happens to hold.
570+
expect(context.diff.length).toBeLessThan(32 * 1024)
571+
})
572+
573+
it("should list untracked files past the limit by path only", async () => {
574+
mockProbes()
575+
const status = Array.from({ length: 12 }, (_, index) => `?? src/file${index}.ts${NUL}`).join("")
576+
mockGit(workingTree(status, ""))
577+
mockUntrackedFile(Buffer.from("contents\n"))
578+
579+
const context = await expectContext()
580+
581+
expect(context.files).toHaveLength(12)
582+
expect(context.diff).toContain("(contents omitted)")
583+
// Ten are read; the remaining two are named without being opened.
584+
expect(fs.promises.open).toHaveBeenCalledTimes(10)
483585
})
484586

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 () => {
587+
it("should still describe an untracked file it cannot read", async () => {
488588
mockProbes()
489-
mockGit(workingTree(` M src/file1.ts${NUL}?? src/untracked.ts${NUL}`))
589+
mockGit(workingTree(`?? src/vanished.ts${NUL}`, ""))
590+
vitest.mocked(fs.promises.open).mockRejectedValue(new Error("ENOENT"))
490591

491-
expect(await getCommitContext(cwd)).toEqual({ ok: false, reason: "nothing-staged" })
592+
expect((await expectContext()).diff).toContain("(unreadable)")
492593
})
493594

494595
it("should describe only the index when both it and the working tree have changes", async () => {
@@ -550,7 +651,7 @@ describe("git utils", () => {
550651
it("should report failed instead of rejecting when a git command fails", async () => {
551652
mockProbes()
552653
const responses = staged(`M${NUL}src/file1.ts${NUL}`)
553-
delete responses["diff --cached --unified=1"]
654+
delete responses["diff --cached --unified=1 --find-renames --find-copies"]
554655
mockGit(responses)
555656

556657
const result = await getCommitContext(cwd)

‎src/utils/git.ts‎

Lines changed: 88 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,24 @@ const GIT_OUTPUT_CHARACTER_LIMIT = 100 * 1024
2323
// Node's default `exec` buffer is 1MB, which real-world diffs routinely exceed.
2424
const GIT_DIFF_MAX_BUFFER = 10 * 1024 * 1024
2525

26+
// Rename and copy detection is asked for explicitly rather than left to `diff.renames`, so a file
27+
// that moved is classified the same way for everyone. With the user's configuration deciding it, a
28+
// rename reaches the model as an unrelated delete plus add wherever that setting is off.
29+
const RENAME_DETECTION_ARGS = ["--find-renames", "--find-copies"]
30+
2631
// A commit message needs to know what changed, not every line of how. One line of surrounding
2732
// context per hunk is enough to tell the model where an edit landed, and shrinking the prompt is
2833
// the one latency factor we control without affecting the model's output.
29-
const COMMIT_DIFF_ARGS = ["--unified=1"]
34+
const COMMIT_DIFF_ARGS = ["--unified=1", ...RENAME_DETECTION_ARGS]
3035

3136
const RECENT_COMMIT_COUNT = 5
3237

38+
// An untracked file has no diff to read, so its contents are inlined instead. These bounds are what
39+
// keep a dropped build directory or a stray archive from becoming the entire prompt: a file count,
40+
// a per-file byte cap read without loading the whole file, and a skip for anything binary.
41+
const UNTRACKED_FILE_LIMIT = 10
42+
const UNTRACKED_FILE_BYTE_LIMIT = 8 * 1024
43+
3344
/**
3445
* Extracts git repository information from the workspace's .git directory
3546
* @param workspaceRoot The root path of the workspace
@@ -385,7 +396,7 @@ export interface CommitContext {
385396

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

390401
async function runGit(args: string[], cwd: string): Promise<string> {
391402
const { stdout } = await execFileAsync("git", args, { cwd, maxBuffer: GIT_DIFF_MAX_BUFFER })
@@ -509,9 +520,9 @@ async function getRecentCommits(cwd: string): Promise<string[]> {
509520
/**
510521
* Collects the changes to describe in a commit message.
511522
*
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.
523+
* Staged changes are described whenever there are any, since that is exactly what a commit will
524+
* contain. Only when the index is empty does this fall back to the working tree - unstaged edits
525+
* plus untracked files - so the two are never mixed into one message.
515526
*
516527
* Every command runs through `execFile` with an argument array, so no path is ever interpolated
517528
* into a shell string, and every listing is read in NUL-delimited form.
@@ -529,21 +540,33 @@ export async function getCommitContext(cwd: string): Promise<CommitContextResult
529540
}
530541

531542
try {
532-
const staged = parseNameStatus(await runGit(["diff", "--cached", "--name-status", "-z"], cwd))
543+
const staged = parseNameStatus(
544+
await runGit(["diff", "--cached", "--name-status", "-z", ...RENAME_DETECTION_ARGS], cwd),
545+
)
533546

534547
if (staged.length > 0) {
535548
const diff = await runGit(["diff", "--cached", ...COMMIT_DIFF_ARGS], cwd)
536549
return { ok: true, context: await buildContext(cwd, staged, diff) }
537550
}
538551

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.
552+
// Nothing is staged, so fall back to the working tree rather than refusing: a commit made
553+
// from here would stage these files first, so they are what the message has to describe.
542554
const worktree = parsePorcelainStatus(
543555
await runGit(["status", "--porcelain=v1", "-z", "--untracked-files=all"], cwd),
544556
)
545557

546-
return { ok: false, reason: worktree.length > 0 ? "nothing-staged" : "no-changes" }
558+
if (worktree.length === 0) {
559+
return { ok: false, reason: "no-changes" }
560+
}
561+
562+
// Tracked edits still come from `git diff`. Untracked files are absent from it by
563+
// definition, so their contents are appended separately or the model would be naming files
564+
// it has never seen.
565+
const tracked = await runGit(["diff", ...COMMIT_DIFF_ARGS], cwd)
566+
const untracked = await readUntrackedFiles(cwd, worktree)
567+
const diff = [tracked.trim(), untracked].filter(Boolean).join("\n\n")
568+
569+
return { ok: true, context: await buildContext(cwd, worktree, diff) }
547570
} catch (error) {
548571
// Failures here are expected rather than exceptional - an oversized diff exceeding
549572
// `maxBuffer`, a repository in a state git refuses to describe - so the caller gets a
@@ -552,6 +575,61 @@ export async function getCommitContext(cwd: string): Promise<CommitContextResult
552575
}
553576
}
554577

578+
/**
579+
* Reads the beginning of each untracked file, rendered as an addition so it sits alongside the real
580+
* diff without needing its own section in the prompt.
581+
*
582+
* Bounded on every axis that can grow without limit - how many files are read, how much of each is
583+
* read, and whether the bytes are text at all - because an untracked listing is whatever happens to
584+
* be sitting in the working directory.
585+
*/
586+
async function readUntrackedFiles(cwd: string, files: GitFileChange[]): Promise<string> {
587+
const untracked = files.filter((file) => file.status === "untracked")
588+
const blocks: string[] = []
589+
590+
for (const file of untracked.slice(0, UNTRACKED_FILE_LIMIT)) {
591+
blocks.push(`--- /dev/null\n+++ b/${file.path}\n${await readUntrackedFile(cwd, file.path)}`)
592+
}
593+
594+
// The rest are still worth naming - that files were added is part of the change even when there
595+
// is no room to show what is in them.
596+
const remaining = untracked.slice(UNTRACKED_FILE_LIMIT)
597+
598+
if (remaining.length > 0) {
599+
blocks.push(remaining.map((file) => `+++ b/${file.path} (contents omitted)`).join("\n"))
600+
}
601+
602+
return blocks.join("\n\n")
603+
}
604+
605+
/** Reads at most `UNTRACKED_FILE_BYTE_LIMIT` bytes, so a huge file costs one bounded read. */
606+
async function readUntrackedFile(cwd: string, filePath: string): Promise<string> {
607+
let handle
608+
609+
try {
610+
handle = await fs.open(path.resolve(cwd, filePath), "r")
611+
612+
const buffer = Buffer.alloc(UNTRACKED_FILE_BYTE_LIMIT)
613+
const { bytesRead } = await handle.read(buffer, 0, UNTRACKED_FILE_BYTE_LIMIT, 0)
614+
const contents = buffer.subarray(0, bytesRead)
615+
616+
// The same heuristic git uses: a NUL byte early in the file means it is not text.
617+
if (contents.includes(0)) {
618+
return "(binary file)"
619+
}
620+
621+
const text = contents.toString("utf8")
622+
623+
return bytesRead < UNTRACKED_FILE_BYTE_LIMIT ? text : `${text}\n(truncated)`
624+
} catch {
625+
// A file listed a moment ago can be gone, or unreadable. Its path is already in the changed
626+
// files list, so the message can still mention it.
627+
return "(unreadable)"
628+
} finally {
629+
await handle?.close().catch(() => {})
630+
}
631+
}
632+
555633
async function buildContext(cwd: string, files: GitFileChange[], diff: string): Promise<CommitContext> {
556634
return {
557635
branch: await getCurrentBranch(cwd),

0 commit comments

Comments
 (0)