diff --git a/apps/backend/internal/agentctl/server/process/git_log.go b/apps/backend/internal/agentctl/server/process/git_log.go index 163ac87fcc..b7bb8ed8a9 100644 --- a/apps/backend/internal/agentctl/server/process/git_log.go +++ b/apps/backend/internal/agentctl/server/process/git_log.go @@ -7,6 +7,8 @@ import ( "os/exec" "sort" "strings" + + "github.com/kandev/kandev/internal/common/unidiff" ) // GitLogResult represents the result of a git log operation. @@ -260,7 +262,14 @@ func (g *GitOperator) GetCumulativeDiff(ctx context.Context, baseCommit string) _, _ = fmt.Sscanf(strings.TrimSpace(countOutput), "%d", &result.TotalCommits) } - // Get the cumulative diff (base → working tree, includes uncommitted changes) + // Get the cumulative diff (base → working tree, includes uncommitted changes). + // Deliberately no --numstat here: parseCommitDiffWithOptions falls back to + // unidiff.CountLines, which was checked against git's own numstat over 600 + // commits of this repo's history with zero disagreements on line counts. + // (Binary files were excluded from that comparison — numstat reports them as + // `-` with nothing to compare — but both routes report 0/0 for them anyway, + // since a binary block carries no hunk.) Adding the flag would change a + // production git invocation for a difference no test can observe. diffOutput, err := g.runGitCommand(ctx, "diff", baseCommit) if err != nil { result.Error = fmt.Sprintf("failed to get diff: %s", err.Error()) @@ -444,6 +453,12 @@ func (g *GitOperator) parseCommitDiffWithOptions(output string, opts parseCommit return files } + // When the caller's git command included --numstat, git printed authoritative + // per-file counts ahead of the first "diff --git" — exactly the text the split + // above discards. Recover them; files without a row fall back to counting + // their own patch body. + numstat := numstatByPath(parts[0]) + totalDiffBytes := 0 for _, part := range parts[1:] { if part == "" { @@ -483,15 +498,7 @@ func (g *GitOperator) parseCommitDiffWithOptions(output string, opts parseCommit } // Count additions and deletions (always from the full content). - additions := 0 - deletions := 0 - for _, line := range strings.Split(diffContent, "\n") { - if strings.HasPrefix(line, "+") && !strings.HasPrefix(line, "+++") { - additions++ - } else if strings.HasPrefix(line, "-") && !strings.HasPrefix(line, "---") { - deletions++ - } - } + additions, deletions := fileLineCounts(numstat, filePath, diffContent) diffOut, skipReason := applyDiffBudget(diffContent, totalDiffBytes, opts) totalDiffBytes += len(diffOut) @@ -512,6 +519,36 @@ func (g *GitOperator) parseCommitDiffWithOptions(output string, opts parseCommit return files } +// numstatByPath indexes the `\t\t` rows git writes for +// --numstat by their new-side path (parseNumstatEntry already expands git's +// `dir/{old => new}` rename notation, so the key matches the path +// parseCommitDiffWithOptions reads out of the `diff --git` header). Rows that +// are not numstat — the `--stat` table, which is tab-free — are skipped, and a +// binary file's `-\t-\t` row yields a zero pair, which is the correct +// answer since binary changes have no lines. +func numstatByPath(block string) map[string]numstatEntry { + rows := make(map[string]numstatEntry) + for _, line := range strings.Split(block, "\n") { + entry, ok := parseNumstatEntry(line) + if !ok { + continue + } + rows[entry.path] = entry + } + return rows +} + +// fileLineCounts returns the add/delete counts for one file section: git's own +// --numstat row when the caller's command supplied one, otherwise a count of the +// patch body. Counting is positional (in-hunk), never textual — a removed +// `-- seed data` line arrives as `--- seed data` and a prefix test drops it. +func fileLineCounts(numstat map[string]numstatEntry, filePath, diffContent string) (additions, deletions int) { + if entry, ok := numstat[filePath]; ok { + return entry.additions, entry.deletions + } + return unidiff.CountLines(diffContent) +} + // applyDiffBudget enforces the per-file and cumulative byte budgets in opts and // returns the (possibly truncated/empty) diff content plus a skip reason. A zero // budget means "no cap" for that dimension. The cumulative budget is strict: the diff --git a/apps/backend/internal/agentctl/server/process/git_log_diffstats_test.go b/apps/backend/internal/agentctl/server/process/git_log_diffstats_test.go new file mode 100644 index 0000000000..d6a5b89e45 --- /dev/null +++ b/apps/backend/internal/agentctl/server/process/git_log_diffstats_test.go @@ -0,0 +1,333 @@ +package process + +import ( + "context" + "strings" + "testing" +) + +// fileStats pulls the additions/deletions a parsed file entry carries. +func fileStats(t *testing.T, files map[string]interface{}, path string) (int, int) { + t.Helper() + entry, ok := files[path].(map[string]interface{}) + if !ok { + t.Fatalf("no file entry for %q (have %v)", path, keysOf(files)) + } + additions, ok := entry["additions"].(int) + if !ok { + t.Fatalf("file %q: additions is not an int: %#v", path, entry["additions"]) + } + deletions, ok := entry["deletions"].(int) + if !ok { + t.Fatalf("file %q: deletions is not an int: %#v", path, entry["deletions"]) + } + return additions, deletions +} + +func keysOf(files map[string]interface{}) []string { + out := make([]string, 0, len(files)) + for k := range files { + out = append(out, k) + } + return out +} + +func TestNumstatByPath(t *testing.T) { + tests := []struct { + name string + block string + want map[string]numstatEntry + }{ + {name: "empty block", block: "", want: map[string]numstatEntry{}}, + { + name: "single row", + block: "3\t1\tapps/a.go\n", + want: map[string]numstatEntry{"apps/a.go": {path: "apps/a.go", additions: 3, deletions: 1}}, + }, + { + name: "binary file reports dashes and yields a zero pair", + block: "-\t-\tassets/logo.png\n", + want: map[string]numstatEntry{"assets/logo.png": {path: "assets/logo.png"}}, + }, + { + name: "stat table lines are ignored", + // `git show --stat --numstat` emits both blocks; only the tab-separated + // numstat rows are ours to read. + block: "1\t1\tseed.sql\n schema.sql | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)\n", + want: map[string]numstatEntry{"seed.sql": {path: "seed.sql", additions: 1, deletions: 1}}, + }, + { + name: "rename row is keyed by its new-side path", + block: "2\t0\tapps/{old => new}/file.go\n", + want: map[string]numstatEntry{ + "apps/new/file.go": {path: "apps/new/file.go", additions: 2, deletions: 0}, + }, + }, + { + name: "two rows", + block: "1\t1\ta.go\n0\t4\tb.go\n", + want: map[string]numstatEntry{ + "a.go": {path: "a.go", additions: 1, deletions: 1}, + "b.go": {path: "b.go", additions: 0, deletions: 4}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := numstatByPath(tt.block) + if len(got) != len(tt.want) { + t.Fatalf("numstatByPath() = %+v, want %+v", got, tt.want) + } + for path, want := range tt.want { + if got[path] != want { + t.Errorf("row %q = %+v, want %+v", path, got[path], want) + } + } + }) + } +} + +// TestParseCommitDiffWithOptions_LineCounts covers both counting routes: the +// authoritative --numstat rows when git supplied them, and the in-hunk fallback +// when it did not. +func TestParseCommitDiffWithOptions_LineCounts(t *testing.T) { + // Removing the SQL line `-- seed data` emits `--- seed data`; adding the C + // line `++counter;` emits `+++counter;`. A prefix test drops both and reports + // +0 -0 where git reports +1 -1. + dashAndPlusPatch := "diff --git a/seed.sql b/seed.sql\n" + + "index 64cf6a5..2559267 100644\n" + + "--- a/seed.sql\n" + + "+++ b/seed.sql\n" + + "@@ -1,2 +1,2 @@\n" + + "--- seed data\n" + + " counter;\n" + + "+++counter;\n" + + tests := []struct { + name string + output string + wantFile string + wantAdd int + wantDel int + }{ + { + name: "content starting with dashes and pluses, no numstat", + output: dashAndPlusPatch, + wantFile: "seed.sql", + wantAdd: 1, + wantDel: 1, + }, + { + name: "content starting with dashes and pluses, with numstat", + output: "1\t1\tseed.sql\n" + dashAndPlusPatch, + wantFile: "seed.sql", + wantAdd: 1, + wantDel: 1, + }, + { + name: "file headers of a real multi-file diff are not counted", + output: "diff --git a/a.go b/a.go\n" + + "index 111..222 100644\n" + + "--- a/a.go\n" + + "+++ b/a.go\n" + + "@@ -1,3 +1,3 @@\n" + + " package a\n" + + "-old\n" + + "+new\n" + + "diff --git a/b.go b/b.go\n" + + "index 333..444 100644\n" + + "--- a/b.go\n" + + "+++ b/b.go\n" + + "@@ -1,2 +1,3 @@\n" + + " package b\n" + + "+added\n", + wantFile: "a.go", + wantAdd: 1, + wantDel: 1, + }, + { + name: "no newline at end of file marker is not content", + output: "diff --git a/a.txt b/a.txt\n" + + "--- a/a.txt\n" + + "+++ b/a.txt\n" + + "@@ -1 +1 @@\n" + + "-old\n" + + "\\ No newline at end of file\n" + + "+new\n" + + "\\ No newline at end of file\n", + wantFile: "a.txt", + wantAdd: 1, + wantDel: 1, + }, + { + name: "binary file from numstat dashes", + output: "-\t-\tlogo.png\n" + + "diff --git a/logo.png b/logo.png\n" + + "index 111..222 100644\n" + + "Binary files a/logo.png and b/logo.png differ\n", + wantFile: "logo.png", + wantAdd: 0, + wantDel: 0, + }, + { + name: "diff with no hunk header at all", + output: "diff --git a/mode.sh b/mode.sh\n" + + "old mode 100644\n" + + "new mode 100755\n", + wantFile: "mode.sh", + wantAdd: 0, + wantDel: 0, + }, + { + name: "numstat rows for other paths fall back to counting this file", + output: "5\t5\tsomewhere-else.go\n" + + "7\t7\tand-another.go\n" + + dashAndPlusPatch, + wantFile: "seed.sql", + wantAdd: 1, + wantDel: 1, + }, + { + name: "renamed file is paired via git's brace notation", + output: "1\t0\tapps/{old => new}/file.go\n" + + "diff --git a/apps/old/file.go b/apps/new/file.go\n" + + "similarity index 90%\n" + + "rename from apps/old/file.go\n" + + "rename to apps/new/file.go\n" + + "--- a/apps/old/file.go\n" + + "+++ b/apps/new/file.go\n" + + "@@ -1,2 +1,3 @@\n" + + " package p\n" + + "+added\n", + wantFile: "apps/new/file.go", + wantAdd: 1, + wantDel: 0, + }, + } + + gitOp := &GitOperator{} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + files := gitOp.parseCommitDiffWithOptions(tt.output, parseCommitDiffOptions{}) + additions, deletions := fileStats(t, files, tt.wantFile) + if additions != tt.wantAdd || deletions != tt.wantDel { + t.Errorf("%s: got +%d -%d, want +%d -%d", + tt.wantFile, additions, deletions, tt.wantAdd, tt.wantDel) + } + }) + } +} + +func TestParseCommitDiffWithOptions_EmptyDiff(t *testing.T) { + gitOp := &GitOperator{} + for _, output := range []string{"", "\n", "1\t1\tseed.sql\n"} { + files := gitOp.parseCommitDiffWithOptions(output, parseCommitDiffOptions{}) + if len(files) != 0 { + t.Errorf("parseCommitDiffWithOptions(%q) returned %d files, want 0", output, len(files)) + } + } +} + +// TestParseCommitDiffWithOptions_MultiFileTotals checks the rolled-up +// Insertions/Deletions that feed the commit-detail header. +func TestParseCommitDiffWithOptions_MultiFileTotals(t *testing.T) { + output := "1\t1\ta.go\n" + + "1\t0\tb.go\n" + + "diff --git a/a.go b/a.go\n" + + "--- a/a.go\n" + + "+++ b/a.go\n" + + "@@ -1,3 +1,3 @@\n" + + " package a\n" + + "-old\n" + + "+new\n" + + "diff --git a/b.go b/b.go\n" + + "--- a/b.go\n" + + "+++ b/b.go\n" + + "@@ -1,2 +1,3 @@\n" + + " package b\n" + + "+added\n" + + gitOp := &GitOperator{} + files := gitOp.parseCommitDiffWithOptions(output, parseCommitDiffOptions{}) + if len(files) != 2 { + t.Fatalf("got %d files, want 2 (%v)", len(files), keysOf(files)) + } + insertions, deletions := sumFileDiffStats(files) + if insertions != 2 || deletions != 1 { + t.Errorf("sumFileDiffStats() = +%d -%d, want +2 -1", insertions, deletions) + } +} + +// seedDashAndPlusCommit writes the pathological file, commits a baseline, then +// rewrites it so the patch contains a removed line starting with "--" and an +// added line starting with "++". git reports +1 -1 for the resulting commit. +func seedDashAndPlusCommit(t *testing.T, repoDir string) string { + t.Helper() + writeFile(t, repoDir, "seed.sql", "-- seed data\ncounter;\n") + runGit(t, repoDir, "add", ".") + runGit(t, repoDir, "commit", "-m", "seed: baseline") + base := strings.TrimSpace(runGit(t, repoDir, "rev-parse", "HEAD")) + + writeFile(t, repoDir, "seed.sql", "counter;\n++counter;\n") + runGit(t, repoDir, "add", ".") + runGit(t, repoDir, "commit", "-m", "seed: rewrite") + return base +} + +// TestShowCommit_CountsDashAndPlusPrefixedContent is the end-to-end guard on the +// commit-detail view: real git output, real numbers, compared against git's own +// --numstat for the same commit. +func TestShowCommit_CountsDashAndPlusPrefixedContent(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + t.Cleanup(cleanup) + + seedDashAndPlusCommit(t, repoDir) + head := strings.TrimSpace(runGit(t, repoDir, "rev-parse", "HEAD")) + + gitOp := NewGitOperator(repoDir, newTestLogger(t), nil) + result, err := gitOp.ShowCommit(context.Background(), head) + if err != nil { + t.Fatalf("ShowCommit returned error: %v", err) + } + if !result.Success { + t.Fatalf("ShowCommit failed: %s", result.Error) + } + + // git's own answer for this commit. + wantNumstat := "1\t1\tseed.sql" + if got := strings.TrimSpace(runGit(t, repoDir, "show", "--format=", "--numstat", head)); got != wantNumstat { + t.Fatalf("test fixture drifted: git numstat = %q, want %q", got, wantNumstat) + } + + additions, deletions := fileStats(t, result.Files, "seed.sql") + if additions != 1 || deletions != 1 { + t.Errorf("seed.sql = +%d -%d, want +1 -1", additions, deletions) + } + if result.Insertions != 1 || result.Deletions != 1 { + t.Errorf("rolled-up stats = +%d -%d, want +1 -1", result.Insertions, result.Deletions) + } +} + +// TestGetCumulativeDiff_CountsDashAndPlusPrefixedContent covers the second +// caller, which builds its diff from `git diff ` rather than `git show`. +func TestGetCumulativeDiff_CountsDashAndPlusPrefixedContent(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + t.Cleanup(cleanup) + + base := seedDashAndPlusCommit(t, repoDir) + + gitOp := NewGitOperator(repoDir, newTestLogger(t), nil) + result, err := gitOp.GetCumulativeDiff(context.Background(), base) + if err != nil { + t.Fatalf("GetCumulativeDiff returned error: %v", err) + } + if !result.Success { + t.Fatalf("GetCumulativeDiff failed: %s", result.Error) + } + + additions, deletions := fileStats(t, result.Files, "seed.sql") + if additions != 1 || deletions != 1 { + t.Errorf("seed.sql = +%d -%d, want +1 -1", additions, deletions) + } +} diff --git a/apps/backend/internal/common/unidiff/count.go b/apps/backend/internal/common/unidiff/count.go new file mode 100644 index 0000000000..010dfb0655 --- /dev/null +++ b/apps/backend/internal/common/unidiff/count.go @@ -0,0 +1,62 @@ +// Package unidiff reads unified-diff text without mistaking content for +// structure. Diff markers are prepended to the original line, so a textual test +// like `strings.HasPrefix(line, "---")` cannot tell the header `--- a/seed.sql` +// apart from a removed SQL comment (`-- seed data` -> `--- seed data`) or an +// added C increment (`++counter;` -> `+++counter;`). The only reliable test is +// positional: a line is content when it sits inside a hunk. +package unidiff + +import ( + "regexp" + "strings" +) + +// hunkHeaderPattern matches a unified-diff hunk header, e.g. `@@ -12,7 +34,9 @@ func Foo()`. +// It mirrors the pattern used by internal/review's anchor walker, which walks the +// same format for a different purpose. +// +// It deliberately does NOT match a combined-diff header (`@@@ -1,3 -1,3 +1,3 @@@`, +// from `git show --cc` on a merge): the body requires exactly one old-side range, +// and the leading `@@+` only tolerates the extra `@` characters. Combined diffs +// also use two marker columns, which this one-column counter would misread. No +// caller produces one — ShowCommit passes --first-parent, GetCumulativeDiff uses +// `git diff `, and GitLab returns per-file patches — so a combined patch +// counts as zero rather than counting wrongly. See TestCountLines. +var hunkHeaderPattern = regexp.MustCompile(`^@@+ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@`) + +// CountLines returns the number of added and removed content lines in a unified +// diff. It tracks in-hunk state exactly the way review.ExtractAnchorText does: +// counting only starts after a `@@` hunk header, and any line that is neither +// content nor hunk metadata (`diff --git`, `index`, `+++`, `---`) ends the hunk. +// A diff with no hunk header at all therefore counts nothing, which is correct — +// binary and mode-only changes carry no line counts. +func CountLines(diff string) (additions, deletions int) { + inHunk := false + + for _, raw := range strings.Split(diff, "\n") { + line := strings.TrimSuffix(raw, "\r") + if hunkHeaderPattern.MatchString(line) { + inHunk = true + continue + } + if !inHunk { + continue + } + switch { + case strings.HasPrefix(line, "+"): + additions++ + case strings.HasPrefix(line, "-"): + deletions++ + case strings.HasPrefix(line, " "), strings.HasPrefix(line, "\\"), line == "": + // Context line, a blank context line inside the hunk body (some + // producers drop the marker on an empty line), the `\ No newline at + // end of file` marker, or the empty element a trailing newline + // leaves behind. None is content, and none ends the hunk. + default: + // File metadata between hunks ends the current hunk. + inHunk = false + } + } + + return additions, deletions +} diff --git a/apps/backend/internal/common/unidiff/count_test.go b/apps/backend/internal/common/unidiff/count_test.go new file mode 100644 index 0000000000..26491a3a5a --- /dev/null +++ b/apps/backend/internal/common/unidiff/count_test.go @@ -0,0 +1,163 @@ +package unidiff + +import "testing" + +func TestCountLines(t *testing.T) { + tests := []struct { + name string + diff string + wantAddition int + wantDeletion int + }{ + { + name: "content lines whose own text starts with dashes or pluses", + // Removing `-- seed data` emits `--- seed data`; adding `++counter;` + // emits `+++counter;`. git reports +1 -1 for exactly this diff. + diff: "diff --git a/seed.sql b/seed.sql\n" + + "index 64cf6a5..2559267 100644\n" + + "--- a/seed.sql\n" + + "+++ b/seed.sql\n" + + "@@ -1,2 +1,2 @@\n" + + "--- seed data\n" + + " counter;\n" + + "+++counter;\n", + wantAddition: 1, + wantDeletion: 1, + }, + { + name: "multi-file diff does not count file headers", + diff: "diff --git a/a.go b/a.go\n" + + "index 111..222 100644\n" + + "--- a/a.go\n" + + "+++ b/a.go\n" + + "@@ -1,3 +1,3 @@\n" + + " package a\n" + + "-old\n" + + "+new\n" + + "diff --git a/b.go b/b.go\n" + + "index 333..444 100644\n" + + "--- a/b.go\n" + + "+++ b/b.go\n" + + "@@ -1,2 +1,3 @@\n" + + " package b\n" + + "+added\n", + wantAddition: 2, + wantDeletion: 1, + }, + { + name: "no newline at end of file marker is not content", + diff: "diff --git a/a.txt b/a.txt\n" + + "--- a/a.txt\n" + + "+++ b/a.txt\n" + + "@@ -1 +1 @@\n" + + "-old\n" + + "\\ No newline at end of file\n" + + "+new\n" + + "\\ No newline at end of file\n", + wantAddition: 1, + wantDeletion: 1, + }, + { + name: "empty diff", + diff: "", + wantAddition: 0, + wantDeletion: 0, + }, + { + name: "no hunk header at all", + diff: "diff --git a/logo.png b/logo.png\n" + + "index 111..222 100644\n" + + "Binary files a/logo.png and b/logo.png differ\n", + wantAddition: 0, + wantDeletion: 0, + }, + { + name: "new file", + diff: "diff --git a/new.txt b/new.txt\n" + + "new file mode 100644\n" + + "index 0000000..111\n" + + "--- /dev/null\n" + + "+++ b/new.txt\n" + + "@@ -0,0 +1,2 @@\n" + + "+one\n" + + "+two\n", + wantAddition: 2, + wantDeletion: 0, + }, + { + name: "deleted file whose content starts with dashes", + diff: "diff --git a/gone.sql b/gone.sql\n" + + "deleted file mode 100644\n" + + "index 111..0000000\n" + + "--- a/gone.sql\n" + + "+++ /dev/null\n" + + "@@ -1,2 +0,0 @@\n" + + "--- header comment\n" + + "-select 1;\n", + wantAddition: 0, + wantDeletion: 2, + }, + { + name: "hunk header without line spans", + diff: "--- a/a.txt\n" + + "+++ b/a.txt\n" + + "@@ -1 +1 @@\n" + + "-old\n" + + "+new\n", + wantAddition: 1, + wantDeletion: 1, + }, + { + name: "CRLF line endings", + diff: "--- a/a.txt\r\n" + + "+++ b/a.txt\r\n" + + "@@ -1,2 +1,2 @@\r\n" + + "--- old comment\r\n" + + "+++new value\r\n", + wantAddition: 1, + wantDeletion: 1, + }, + { + // Real `git show --cc` output for a conflicted merge. The two marker + // columns would break a one-column counter, so the hunk pattern + // deliberately does not match `@@@` and the patch counts as zero. + // No caller produces one (ShowCommit passes --first-parent), and + // counting nothing beats counting wrongly. + name: "combined merge diff is not counted", + diff: "diff --cc f.txt\n" + + "index 797be14,0c02ccc..db3c03a\n" + + "--- a/f.txt\n" + + "+++ b/f.txt\n" + + "@@@ -1,3 -1,3 +1,3 @@@\n" + + " a\n" + + "- Y\n" + + " -X\n" + + "++Z\n" + + " c\n", + wantAddition: 0, + wantDeletion: 0, + }, + { + name: "empty context line carrying no marker stays in the hunk", + diff: "--- a/a.txt\n" + + "+++ b/a.txt\n" + + "@@ -1,4 +1,4 @@\n" + + " first\n" + + "\n" + + "-old\n" + + "+new\n", + wantAddition: 1, + wantDeletion: 1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + additions, deletions := CountLines(tt.diff) + if additions != tt.wantAddition || deletions != tt.wantDeletion { + t.Errorf("CountLines() = +%d -%d, want +%d -%d", + additions, deletions, tt.wantAddition, tt.wantDeletion) + } + }) + } +} diff --git a/apps/backend/internal/gitlab/client_helpers.go b/apps/backend/internal/gitlab/client_helpers.go index a74d2d2b22..91c3d41bcd 100644 --- a/apps/backend/internal/gitlab/client_helpers.go +++ b/apps/backend/internal/gitlab/client_helpers.go @@ -4,6 +4,8 @@ import ( "net/url" "strings" "time" + + "github.com/kandev/kandev/internal/common/unidiff" ) // rawMR is the JSON shape of a GitLab merge request as returned by the @@ -557,22 +559,17 @@ func appendFilter(values url.Values, filter string) { } } -// countDiffLines returns (additions, deletions) by counting lines starting -// with "+" or "-" (excluding the diff header lines that start with -// "+++"/"---"). Best-effort; matches the GitLab UI's own counting. +// countDiffLines returns (additions, deletions) for one file's patch from the +// MR /changes payload. GitLab's REST API carries no per-file line counts, so the +// patch body has to be counted here. +// +// It counts only lines inside a `@@` hunk. The previous "+++"/"---" prefix test +// was content-blind: GitLab returns `--- a/` / `+++ b/` headers ahead +// of the first hunk, but so does a removed SQL comment (`-- x` arrives as +// `--- x`) or an added C increment (`++n;` arrives as `+++n;`), and those were +// dropped from the totals. func countDiffLines(diff string) (int, int) { - additions, deletions := 0, 0 - for _, line := range strings.Split(diff, "\n") { - switch { - case strings.HasPrefix(line, "+++"), strings.HasPrefix(line, "---"): - continue - case strings.HasPrefix(line, "+"): - additions++ - case strings.HasPrefix(line, "-"): - deletions++ - } - } - return additions, deletions + return unidiff.CountLines(diff) } func diffStatus(newFile, deletedFile, renamedFile bool) string { diff --git a/apps/backend/internal/gitlab/client_helpers_diffstats_test.go b/apps/backend/internal/gitlab/client_helpers_diffstats_test.go new file mode 100644 index 0000000000..2d2e616e06 --- /dev/null +++ b/apps/backend/internal/gitlab/client_helpers_diffstats_test.go @@ -0,0 +1,112 @@ +package gitlab + +import ( + "context" + "encoding/json" + "net/http" + "testing" +) + +func TestCountDiffLines_Table(t *testing.T) { + tests := []struct { + name string + diff string + wantAdd int + wantDel int + }{ + { + // GitLab's /changes payload puts `--- a/` / `+++ b/` + // ahead of the first hunk, so the old prefix test could not tell them + // apart from a removed `-- seed data` or an added `++counter;`. + name: "content lines starting with dashes and pluses", + diff: "--- a/seed.sql\n" + + "+++ b/seed.sql\n" + + "@@ -1,2 +1,2 @@\n" + + "--- seed data\n" + + " counter;\n" + + "+++counter;\n", + wantAdd: 1, + wantDel: 1, + }, + { + name: "file headers are still excluded", + diff: "--- a/foo.go\n" + + "+++ b/foo.go\n" + + "@@ -1,3 +1,3 @@\n" + + "-old\n" + + "+new1\n" + + "+new2\n" + + " unchanged\n", + wantAdd: 2, + wantDel: 1, + }, + { + name: "multiple hunks in one file patch", + diff: "@@ -1,2 +1,2 @@\n" + + "-a\n" + + "+b\n" + + "@@ -10,2 +10,3 @@\n" + + " ctx\n" + + "+c\n", + wantAdd: 2, + wantDel: 1, + }, + { + name: "no newline at end of file marker", + diff: "@@ -1 +1 @@\n" + + "-old\n" + + "\\ No newline at end of file\n" + + "+new\n" + + "\\ No newline at end of file\n", + wantAdd: 1, + wantDel: 1, + }, + {name: "empty diff (binary or renamed-only change)", diff: "", wantAdd: 0, wantDel: 0}, + { + name: "no hunk header at all", + diff: "--- a/foo.png\n+++ b/foo.png\n", + wantAdd: 0, + wantDel: 0, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + add, del := countDiffLines(tt.diff) + if add != tt.wantAdd || del != tt.wantDel { + t.Errorf("countDiffLines() = +%d -%d, want +%d -%d", add, del, tt.wantAdd, tt.wantDel) + } + }) + } +} + +// TestPATClient_ListMRFiles_CountsDashAndPlusPrefixedContent walks the live path +// so a regression in countDiffLines shows up in the MR file stats the UI renders. +func TestPATClient_ListMRFiles_CountsDashAndPlusPrefixedContent(t *testing.T) { + host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "changes": []map[string]any{{ + "old_path": "seed.sql", + "new_path": "seed.sql", + "diff": "--- a/seed.sql\n" + + "+++ b/seed.sql\n" + + "@@ -1,2 +1,2 @@\n" + + "--- seed data\n" + + " counter;\n" + + "+++counter;\n", + }}, + }) + })) + defer stop() + + files, err := NewPATClient(host, "tok").ListMRFiles(context.Background(), "group/project", 7) + if err != nil { + t.Fatalf("ListMRFiles: %v", err) + } + if len(files) != 1 { + t.Fatalf("got %d files, want 1", len(files)) + } + if files[0].Additions != 1 || files[0].Deletions != 1 { + t.Errorf("seed.sql = +%d -%d, want +1 -1", files[0].Additions, files[0].Deletions) + } +} diff --git a/apps/web/lib/utils/file-diff.ts b/apps/web/lib/utils/file-diff.ts index e0119017b5..8153680012 100644 --- a/apps/web/lib/utils/file-diff.ts +++ b/apps/web/lib/utils/file-diff.ts @@ -51,27 +51,6 @@ export async function calculateHash(content: string): Promise { return djb2Hash(content); } -/** - * Calculate diff stats (additions and deletions) - * @param diff - Unified diff string - * @returns Object with additions and deletions count - */ -export function calculateDiffStats(diff: string): { additions: number; deletions: number } { - const lines = diff.split("\n"); - let additions = 0; - let deletions = 0; - - for (const line of lines) { - if (line.startsWith("+") && !line.startsWith("+++")) { - additions++; - } else if (line.startsWith("-") && !line.startsWith("---")) { - deletions++; - } - } - - return { additions, deletions }; -} - /** * Format diff stats for display * @param additions - Number of additions