π OpenHands: AI-Driven Development
fix(utils): correctly count diff stats for hunk lines starting with -- or ++ (#16979) (#17071)
Prakhar Saini1a34e0222ee9
diff --git a/__tests__/utils/git-diff-stats.test.ts b/__tests__/utils/git-diff-stats.test.tsnew file mode 100644index 0000000000..370937bad6--- /dev/null+++ b/__tests__/utils/git-diff-stats.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from "vitest";+import {+ countGitChangeDiffStats,+ countUnifiedDiffStats,+} from "#/utils/git-diff-stats";++describe("git-diff-stats", () => {+ it("counts hunk lines whose content starts with -- or ++", () => {+ const diff = [+ "--- a/file.txt",+ "+++ b/file.txt",+ "@@ -1,3 +1,3 @@",+ " keep this line",+ "-normal deleted line",+ "--- a deleted line that starts with two dashes",+ "+normal added line",+ "+++ an added line that starts with two pluses",+ ].join("\n");++ expect(countUnifiedDiffStats(diff)).toEqual({+ additions: 2,+ deletions: 2,+ });+ });++ it("handles multi-file diffs without counting subsequent file headers", () => {+ const multiDiff = [+ "diff --git a/file1.txt b/file1.txt",+ "--- a/file1.txt",+ "+++ b/file1.txt",+ "@@ -1,1 +1,1 @@",+ "-old1",+ "+new1",+ "diff --git a/file2.txt b/file2.txt",+ "--- a/file2.txt",+ "+++ b/file2.txt",+ "@@ -1,1 +1,1 @@",+ "-old2",+ "+new2",+ ].join("\n");++ expect(countUnifiedDiffStats(multiDiff)).toEqual({+ additions: 2,+ deletions: 2,+ });+ });++ it("integrates with countGitChangeDiffStats", () => {+ const diff = [+ "@@ -1,3 +1,3 @@",+ " keep this line",+ "-normal deleted line",+ "--- a deleted line that starts with two dashes",+ "+normal added line",+ "+++ an added line that starts with two pluses",+ ].join("\n");++ expect(countGitChangeDiffStats({ diff } as never)).toEqual({+ additions: 2,+ deletions: 2,+ });+ });+});\ No newline at end of filediff --git a/src/utils/git-diff-stats.ts b/src/utils/git-diff-stats.tsindex 705ba79dae..df8e896cb1 100644--- a/src/utils/git-diff-stats.ts+++ b/src/utils/git-diff-stats.ts@@ -5,22 +5,37 @@ export interface GitDiffLineStats {deletions: number;}-function countUnifiedDiffStats(diff: string): GitDiffLineStats {+export function countUnifiedDiffStats(diff: string): {+ additions: number;+ deletions: number;+} {let additions = 0;let deletions = 0;+ let inHunk = false;for (const line of diff.split("\n")) {- if (- line.startsWith("+++") ||- line.startsWith("---") ||- line.startsWith("@@")- ) {+ if (line.startsWith("diff --git") || line.startsWith("index ")) {+ inHunk = false;continue;}- if (line.startsWith("+")) {- additions += 1;- } else if (line.startsWith("-")) {- deletions += 1;++ if (line.startsWith("@@")) {+ inHunk = true;+ continue;+ }++ if (!inHunk) {+ if (line.startsWith("---") || line.startsWith("+++")) {+ continue;+ }+ }++ if (inHunk) {+ if (line.startsWith("+")) {+ additions += 1;+ } else if (line.startsWith("-")) {+ deletions += 1;+ }}}