Full-file syntax highlighting for diff pages (#33766)

Fix #33358, fix #21970

This adds a step in the `GitDiffForRender` that does syntax highlighting for the
entire file and then only references lines from that syntax highlighted
code. This allows things like multi-line comments to be syntax
highlighted correctly.

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
Dustin Firebaugh
2025-03-08 23:51:58 -05:00
committed by GitHub
parent 6f13331754
commit 3f1f808b9e
14 changed files with 361 additions and 323 deletions

View File

@ -7,6 +7,7 @@ package git
import (
"bytes"
"encoding/base64"
"errors"
"io"
"code.gitea.io/gitea/modules/typesniffer"
@ -34,8 +35,9 @@ func (b *Blob) GetBlobContent(limit int64) (string, error) {
return string(buf), err
}
// GetBlobLineCount gets line count of the blob
func (b *Blob) GetBlobLineCount() (int, error) {
// GetBlobLineCount gets line count of the blob.
// It will also try to write the content to w if it's not nil, then we could pre-fetch the content without reading it again.
func (b *Blob) GetBlobLineCount(w io.Writer) (int, error) {
reader, err := b.DataAsync()
if err != nil {
return 0, err
@ -44,20 +46,20 @@ func (b *Blob) GetBlobLineCount() (int, error) {
buf := make([]byte, 32*1024)
count := 1
lineSep := []byte{'\n'}
c, err := reader.Read(buf)
if c == 0 && err == io.EOF {
return 0, nil
}
for {
c, err := reader.Read(buf)
if w != nil {
if _, err := w.Write(buf[:c]); err != nil {
return count, err
}
}
count += bytes.Count(buf[:c], lineSep)
switch {
case err == io.EOF:
case errors.Is(err, io.EOF):
return count, nil
case err != nil:
return count, err
}
c, err = reader.Read(buf)
}
}