diff --git a/internal/git/diff.go b/internal/git/diff.go index 78954354e..a26652815 100644 --- a/internal/git/diff.go +++ b/internal/git/diff.go @@ -195,7 +195,7 @@ func (chunks Chunks) getClosestChunk(baseLineNumber int) *Chunk { var result *Chunk for i, chunk := range chunks { - if chunk.From.LineNumber > baseLineNumber { + if chunk.From.StartLineNumber() > baseLineNumber { break } @@ -209,12 +209,16 @@ func (chunk Chunk) EndDelta() int { return chunk.To.EndLineNumber() - chunk.From.EndLineNumber() } -func (chunkRange ChunkRange) EndLineNumber() int { +func (chunkRange ChunkRange) StartLineNumber() int { if chunkRange.LineCount == 0 { - return chunkRange.LineNumber + return chunkRange.LineNumber + 1 } - return chunkRange.LineNumber + chunkRange.LineCount - 1 + return chunkRange.LineNumber +} + +func (chunkRange ChunkRange) EndLineNumber() int { + return chunkRange.StartLineNumber() + chunkRange.LineCount - 1 } func (chunkRange ChunkRange) Overlap(other ChunkRange) bool { diff --git a/internal/git/diff_test.go b/internal/git/diff_test.go index be02b104c..877ba8ef3 100644 --- a/internal/git/diff_test.go +++ b/internal/git/diff_test.go @@ -152,6 +152,18 @@ var _ = Describe("Diff", func() { }) var _ = Describe("ChunkRange", func() { + Describe("StartLineNumber", func() { + It("returns the line number", func() { + Expect(git.ChunkRange{LineNumber: 2, LineCount: 1}.StartLineNumber()).To(Equal(2)) + }) + + When("there are no lines in the range", func() { + It("returns the next line after the line number", func() { + Expect(git.ChunkRange{LineNumber: 2, LineCount: 0}.StartLineNumber()).To(Equal(3)) + }) + }) + }) + Describe("EndLineNumber", func() { It("returns the (inclusive) end line number", func() { Expect(git.ChunkRange{LineNumber: 2, LineCount: 1}.EndLineNumber()).To(Equal(2)) @@ -228,6 +240,19 @@ var _ = Describe("Chunks", func() { }) }) + When("the base range is at an add chunk", func() { + chunks := git.Chunks{{ + From: git.ChunkRange{LineNumber: 1, LineCount: 0}, + To: git.ChunkRange{LineNumber: 2, LineCount: 1}, + }} + + It("returns a range shifted by the add", func() { + Expect(chunks.TranslateRange(git.ChunkRange{LineNumber: 2, LineCount: 2})).To( + Equal(git.ChunkRange{LineNumber: 3, LineCount: 2}), + ) + }) + }) + When("the base range surrounds a remove chunk", func() { chunks := git.Chunks{{ From: git.ChunkRange{LineNumber: 3, LineCount: 1}, diff --git a/internal/git/git_suite_test.go b/internal/git/git_suite_test.go index 754517933..110471943 100644 --- a/internal/git/git_suite_test.go +++ b/internal/git/git_suite_test.go @@ -5,6 +5,7 @@ import ( "os" "os/exec" "path" + "strings" "testing" . "github.com/onsi/ginkgo/v2" @@ -22,7 +23,7 @@ func runGit(dir string, args ...string) { output, err := command.CombinedOutput() if err != nil { - Fail(fmt.Sprintf("failed to run git command: %s\n%s", err, output)) + Fail(fmt.Sprintf("failed to run git command [%s]: %s\n%s", strings.Join(args, " "), err, output)) } }