fix: git diff blob excerpt (#38808)

1. refactor the legacy code and add more comments, remove the "+1/-1"
tricks, clarify the BuildBlobExcerptDiffSection behavior
2. fix a line-counting bug (see screenshot below)
This commit is contained in:
wxiaoguang
2026-08-07 10:44:55 +08:00
committed by GitHub
parent 9dac77fdc2
commit a7df0d5f41
5 changed files with 98 additions and 56 deletions
+16 -4
View File
@@ -49,20 +49,32 @@ func (b *Blob) GetBlobLineCount(ctx context.Context, w io.Writer) (size int64, c
return 0, 0, err
}
defer reader.Close()
return getBlobLineCount(reader, w)
}
func getBlobLineCount(r io.Reader, w io.Writer) (size int64, count int, _ error) {
buf := make([]byte, 32*1024)
size, count = 0, 1
lineSep := []byte{'\n'}
size, count = 0, 0
var lastChar byte
lineSep := []byte("\n")
for {
c, err := reader.Read(buf)
c, err := r.Read(buf)
size += int64(c)
if w != nil {
if _, err := w.Write(buf[:c]); err != nil {
return size, count, err
}
}
count += bytes.Count(buf[:c], lineSep)
if c > 0 {
count += bytes.Count(buf[:c], lineSep)
lastChar = buf[c-1]
}
switch {
case errors.Is(err, io.EOF):
if size > 0 && lastChar != '\n' {
// it should match "git diff" hunk line number. "a\nb" => 2 lines, "a\nb\n" => 2 lines
count++
}
return size, count, nil
case err != nil:
return size, count, err
+18
View File
@@ -7,6 +7,7 @@ package git
import (
"io"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -56,3 +57,20 @@ func Benchmark_Blob_Data(b *testing.B) {
_ = r.Close()
}
}
func TestGetBlobLineCount(t *testing.T) {
size, count, err := getBlobLineCount(strings.NewReader(""), nil)
assert.NoError(t, err)
assert.EqualValues(t, 0, size)
assert.Equal(t, 0, count)
size, count, err = getBlobLineCount(strings.NewReader("\n"), nil)
assert.NoError(t, err)
assert.EqualValues(t, 1, size)
assert.Equal(t, 1, count)
size, count, err = getBlobLineCount(strings.NewReader("a\nb"), nil)
assert.NoError(t, err)
assert.EqualValues(t, 3, size)
assert.Equal(t, 2, count)
}