Skip to content

Full-file syntax highlighting for diff pages #33766

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 31 commits into from
Mar 9, 2025
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
1955475
initial pass at fixing multiline comment highlighting in git diffs
dfirebaugh Mar 1, 2025
0452d27
updating tests since diffwithhighlight is now only responsible for pl…
dfirebaugh Mar 1, 2025
60898a6
adding language var back
dfirebaugh Mar 1, 2025
a180f0f
Merge remote-tracking branch 'upstream/main' into git-diff-highlights
dfirebaugh Mar 1, 2025
aac3ec4
updating tests
dfirebaugh Mar 2, 2025
68dd510
- making highlighted code members private
dfirebaugh Mar 2, 2025
3607a25
after make fmt
dfirebaugh Mar 2, 2025
843cb3d
implementing lint suggestion
dfirebaugh Mar 2, 2025
0eaefbc
- removing filename and language from `diffWithHighlight` func
dfirebaugh Mar 2, 2025
9a59d9a
reverting span close logic
dfirebaugh Mar 2, 2025
5b0adf2
updating `highlightdiff_test.go` test data
dfirebaugh Mar 2, 2025
447236e
- readding call to `highligh.Code` in `diffWithHighlight`
dfirebaugh Mar 2, 2025
09dc97b
- calling `template.HTMLEscapeString` directly in `diffWithHighlight`…
dfirebaugh Mar 2, 2025
14d6c0e
reverting htmlescape because we already escape it when we highlight t…
dfirebaugh Mar 2, 2025
d42de12
- reverting original hunk-based syntax highlighting
dfirebaugh Mar 2, 2025
6aa9099
temp: simplify code
wxiaoguang Mar 3, 2025
8bb9de4
temp: add highlight fallback and FIXME comment
wxiaoguang Mar 3, 2025
44c2766
Merge branch 'main' into git-diff-highlights
wxiaoguang Mar 5, 2025
1e6c8dd
add FIXME for abused GitDiff
wxiaoguang Mar 5, 2025
e424efe
Merge branch 'main' into git-diff-highlights
wxiaoguang Mar 8, 2025
493e32b
fix merge
wxiaoguang Mar 8, 2025
abc63e9
fix DiffFile struct
wxiaoguang Mar 8, 2025
7de148a
split GetDiff
wxiaoguang Mar 8, 2025
0a29d4d
only save the highlighted lines we need, but not the whole file, to s…
wxiaoguang Mar 8, 2025
d786956
fix tests
wxiaoguang Mar 8, 2025
ba96e9f
fix test & lint
wxiaoguang Mar 8, 2025
7fffde1
Update services/gitdiff/gitdiff.go
wxiaoguang Mar 8, 2025
632ea32
improve test
wxiaoguang Mar 8, 2025
a07ca6a
Merge branch 'main' into git-diff-highlights
wxiaoguang Mar 8, 2025
7939850
Merge branch 'main' into git-diff-highlights
wxiaoguang Mar 9, 2025
b2dbc78
fix 500 in blob_excerpt
wxiaoguang Mar 9, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 50 additions & 18 deletions services/gitdiff/gitdiff.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,13 +289,6 @@
return DiffInline{EscapeStatus: status, Content: content}
}

// DiffInlineWithHighlightCode makes a DiffInline with code highlight and hidden unicode characters escaped
func DiffInlineWithHighlightCode(fileName, language, code string, locale translation.Locale) DiffInline {
highlighted, _ := highlight.Code(fileName, language, code)
status, content := charset.EscapeControlHTML(highlighted, locale)
return DiffInline{EscapeStatus: status, Content: content}
}

// GetComputedInlineDiffFor computes inline diff for the given line.
func (diffSection *DiffSection) GetComputedInlineDiffFor(diffLine *DiffLine, locale translation.Locale) DiffInline {
if setting.Git.DisableDiffHighlight {
Expand All @@ -312,37 +305,40 @@
if diffSection.file != nil {
language = diffSection.file.Language
}

// try to find equivalent diff line. ignore, otherwise
switch diffLine.Type {
case DiffLineSection:
return getLineContent(diffLine.Content[1:], locale)
case DiffLineAdd:
compareDiffLine = diffSection.GetLine(DiffLineDel, diffLine.RightIdx)
if compareDiffLine == nil {
return DiffInlineWithHighlightCode(diffSection.FileName, language, diffLine.Content[1:], locale)
highlightedLine := diffSection.file.highlightedNewLines[diffLine.RightIdx-1]
return DiffInlineWithUnicodeEscape(template.HTML(highlightedLine), locale)
}
diff1 = compareDiffLine.Content
diff2 = diffLine.Content
diff1 = diffSection.file.highlightedOldLines[compareDiffLine.LeftIdx-1]
diff2 = diffSection.file.highlightedNewLines[diffLine.RightIdx-1]
case DiffLineDel:
compareDiffLine = diffSection.GetLine(DiffLineAdd, diffLine.LeftIdx)
if compareDiffLine == nil {
return DiffInlineWithHighlightCode(diffSection.FileName, language, diffLine.Content[1:], locale)
highlightedLine := diffSection.file.highlightedOldLines[diffLine.LeftIdx-1]
return DiffInlineWithUnicodeEscape(template.HTML(highlightedLine), locale)
}
diff1 = diffLine.Content
diff2 = compareDiffLine.Content
diff1 = diffSection.file.highlightedOldLines[diffLine.LeftIdx-1]
diff2 = diffSection.file.highlightedNewLines[compareDiffLine.RightIdx-1]
default:
if strings.IndexByte(" +-", diffLine.Content[0]) > -1 {
return DiffInlineWithHighlightCode(diffSection.FileName, language, diffLine.Content[1:], locale)
highlightedContent := diffSection.file.highlightedNewLines[diffLine.RightIdx-1]
return DiffInlineWithUnicodeEscape(template.HTML(highlightedContent), locale)
}
return DiffInlineWithHighlightCode(diffSection.FileName, language, diffLine.Content, locale)
highlightedContent := diffSection.file.highlightedOldLines[diffLine.LeftIdx-1]
return DiffInlineWithUnicodeEscape(template.HTML(highlightedContent), locale)
}

hcd := newHighlightCodeDiff()
diffRecord := hcd.diffWithHighlight(diffSection.FileName, language, diff1[1:], diff2[1:])
diffRecord := hcd.diffWithHighlight(diffSection.FileName, language, diff1, diff2)
// it seems that Gitea doesn't need the line wrapper of Chroma, so do not add them back
// if the line wrappers are still needed in the future, it can be added back by "diffToHTML(hcd.lineWrapperTags. ...)"
diffHTML := diffToHTML(nil, diffRecord, diffLine.Type)
diffHTML := html.UnescapeString(diffToHTML(nil, diffRecord, diffLine.Type))
return DiffInlineWithUnicodeEscape(template.HTML(diffHTML), locale)
}

Expand Down Expand Up @@ -374,6 +370,9 @@

IsSubmodule bool // if IsSubmodule==true, then there must be a SubmoduleDiffInfo
SubmoduleDiffInfo *SubmoduleDiffInfo

highlightedOldLines []string
highlightedNewLines []string
}

// GetType returns type of diff file.
Expand Down Expand Up @@ -1227,6 +1226,8 @@
}
diffFile.IsGenerated = isGenerated.Value()

diffFile.highlightedOldLines, diffFile.highlightedNewLines = highlightCode(commit, beforeCommit, diffFile)

tailSection := diffFile.GetTailSection(gitRepo, beforeCommit, commit)
if tailSection != nil {
diffFile.Sections = append(diffFile.Sections, tailSection)
Expand All @@ -1247,6 +1248,37 @@
return diff, nil
}

func highlightCode(commit, beforeCommit *git.Commit, diffFile *DiffFile) ([]string, []string) {
var oldLines []string
var newLines []string

if beforeCommit != nil {
oldBlob, err := beforeCommit.GetBlobByPath(diffFile.Name)
if err == nil {
oldContent, _ := oldBlob.GetBlobContent(oldBlob.Size())
highlightedOldContent, _ := highlight.Code(diffFile.Name, diffFile.Language, oldContent)

oldLines = strings.Split(string(highlightedOldContent), "\n")
for _, line := range oldLines {

Check failure on line 1262 in services/gitdiff/gitdiff.go

View workflow job for this annotation

GitHub Actions / lint-backend

S1011: should replace loop with `oldLines = append(oldLines, oldLines...)` (gosimple)

Check failure on line 1262 in services/gitdiff/gitdiff.go

View workflow job for this annotation

GitHub Actions / lint-go-gogit

S1011: should replace loop with `oldLines = append(oldLines, oldLines...)` (gosimple)

Check failure on line 1262 in services/gitdiff/gitdiff.go

View workflow job for this annotation

GitHub Actions / lint-go-windows

S1011: should replace loop with `oldLines = append(oldLines, oldLines...)` (gosimple)
oldLines = append(oldLines, line)
}
}
}

newBlob, err := commit.GetBlobByPath(diffFile.Name)
if err == nil {
newContent, _ := newBlob.GetBlobContent(newBlob.Size())
highlightedNewContent, _ := highlight.Code(diffFile.Name, diffFile.Language, newContent)

newLines = strings.Split(string(highlightedNewContent), "\n")
for _, line := range newLines {

Check failure on line 1274 in services/gitdiff/gitdiff.go

View workflow job for this annotation

GitHub Actions / lint-backend

S1011: should replace loop with `newLines = append(newLines, newLines...)` (gosimple)

Check failure on line 1274 in services/gitdiff/gitdiff.go

View workflow job for this annotation

GitHub Actions / lint-go-gogit

S1011: should replace loop with `newLines = append(newLines, newLines...)` (gosimple)

Check failure on line 1274 in services/gitdiff/gitdiff.go

View workflow job for this annotation

GitHub Actions / lint-go-windows

S1011: should replace loop with `newLines = append(newLines, newLines...)` (gosimple)
newLines = append(newLines, line)
}
}

return oldLines, newLines
}

type PullDiffStats struct {
NumFiles, TotalAddition, TotalDeletion int
}
Expand Down
21 changes: 2 additions & 19 deletions services/gitdiff/highlightdiff.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import (
"strings"

"code.gitea.io/gitea/modules/highlight"

"github.com/sergi/go-diff/diffmatchpatch"
)

Expand Down Expand Up @@ -86,15 +84,12 @@
}
}

func (hcd *highlightCodeDiff) diffWithHighlight(filename, language, codeA, codeB string) []diffmatchpatch.Diff {

Check failure on line 87 in services/gitdiff/highlightdiff.go

View workflow job for this annotation

GitHub Actions / lint-backend

`(*highlightCodeDiff).diffWithHighlight` - `filename` is unused (unparam)

Check failure on line 87 in services/gitdiff/highlightdiff.go

View workflow job for this annotation

GitHub Actions / lint-go-gogit

`(*highlightCodeDiff).diffWithHighlight` - `filename` is unused (unparam)

Check failure on line 87 in services/gitdiff/highlightdiff.go

View workflow job for this annotation

GitHub Actions / lint-go-windows

`(*highlightCodeDiff).diffWithHighlight` - `filename` is unused (unparam)
hcd.collectUsedRunes(codeA)
hcd.collectUsedRunes(codeB)

highlightCodeA, _ := highlight.Code(filename, language, codeA)
highlightCodeB, _ := highlight.Code(filename, language, codeB)

convertedCodeA := hcd.convertToPlaceholders(string(highlightCodeA))
convertedCodeB := hcd.convertToPlaceholders(string(highlightCodeB))
convertedCodeA := hcd.convertToPlaceholders(codeA)
convertedCodeB := hcd.convertToPlaceholders(codeB)

diffs := diffMatchPatch.DiffMain(convertedCodeA, convertedCodeB, true)
diffs = diffMatchPatch.DiffCleanupEfficiency(diffs)
Expand Down Expand Up @@ -206,17 +201,5 @@
sb.WriteString(tokenToRecover)
}

if len(tagStack) > 0 {
// close all opening tags
for i := len(tagStack) - 1; i >= 0; i-- {
tagToClose := tagStack[i]
// get the closing tag "</span>" from "<span class=...>" or "<span>"
pos := strings.IndexAny(tagToClose, " >")
if pos != -1 {
sb.WriteString("</" + tagToClose[1:pos] + ">")
} // else: impossible. every tag was pushed into the stack by the code above and is valid HTML opening tag
}
}

diff.Text = sb.String()
}
50 changes: 9 additions & 41 deletions services/gitdiff/highlightdiff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ package gitdiff

import (
"fmt"
"strings"
"testing"

"github.com/sergi/go-diff/diffmatchpatch"
Expand All @@ -20,11 +19,13 @@ func TestDiffWithHighlight(t *testing.T) {
" run(db)\n",
)

expected := ` <span class="n">run</span><span class="o">(</span><span class="removed-code"><span class="k">&#39;</span><span class="o">&lt;</span><span class="o">&gt;</span><span class="k">&#39;</span></span><span class="o">)</span>`
expected := ` run(<span class="removed-code">'<>'</span>)
`
output := diffToHTML(nil, diffs, DiffLineDel)
assert.Equal(t, expected, output)

expected = ` <span class="n">run</span><span class="o">(</span><span class="added-code"><span class="n">db</span></span><span class="o">)</span>`
expected = ` run(<span class="added-code">db</span>)
`
output = diffToHTML(nil, diffs, DiffLineAdd)
assert.Equal(t, expected, output)

Expand All @@ -33,14 +34,6 @@ func TestDiffWithHighlight(t *testing.T) {
hcd.placeholderTokenMap['C'] = "</span>"
diff := diffmatchpatch.Diff{}

diff.Text = "OC"
hcd.recoverOneDiff(&diff)
assert.Equal(t, "<span></span>", diff.Text)

diff.Text = "O"
hcd.recoverOneDiff(&diff)
assert.Equal(t, "<span></span>", diff.Text)

diff.Text = "C"
hcd.recoverOneDiff(&diff)
assert.Equal(t, "", diff.Text)
Expand All @@ -56,7 +49,7 @@ func TestDiffWithHighlightPlaceholder(t *testing.T) {
assert.Equal(t, "", hcd.placeholderTokenMap[0x00100000])
assert.Equal(t, "", hcd.placeholderTokenMap[0x0010FFFD])

expected := fmt.Sprintf(`<span class="nx">a</span><span class="o">=</span><span class="s1">&#39;</span><span class="removed-code">%s</span>&#39;`, "\U00100000")
expected := fmt.Sprintf(`a='<span class="removed-code">%s</span>'`, "\U00100000")
output := diffToHTML(hcd.lineWrapperTags, diffs, DiffLineDel)
assert.Equal(t, expected, output)

Expand All @@ -66,7 +59,7 @@ func TestDiffWithHighlightPlaceholder(t *testing.T) {
"a='\U00100000'",
"a='\U0010FFFD'",
)
expected = fmt.Sprintf(`<span class="nx">a</span><span class="o">=</span><span class="s1">&#39;</span><span class="added-code">%s</span>&#39;`, "\U0010FFFD")
expected = fmt.Sprintf(`a='<span class="added-code">%s</span>'`, "\U0010FFFD")
output = diffToHTML(nil, diffs, DiffLineAdd)
assert.Equal(t, expected, output)
}
Expand All @@ -80,7 +73,7 @@ func TestDiffWithHighlightPlaceholderExhausted(t *testing.T) {
``,
)
output := diffToHTML(nil, diffs, DiffLineDel)
expected := fmt.Sprintf(`<span class="removed-code">%s#39;</span>`, "\uFFFD")
expected := `<span class="removed-code">'</span>`
assert.Equal(t, expected, output)

hcd = newHighlightCodeDiff()
Expand All @@ -91,35 +84,10 @@ func TestDiffWithHighlightPlaceholderExhausted(t *testing.T) {
"a > b",
)
output = diffToHTML(nil, diffs, DiffLineDel)
expected = fmt.Sprintf(`a %s<span class="removed-code">l</span>t; b`, "\uFFFD")
expected = `a <span class="removed-code"><</span> b`
assert.Equal(t, expected, output)

output = diffToHTML(nil, diffs, DiffLineAdd)
expected = fmt.Sprintf(`a %s<span class="added-code">g</span>t; b`, "\uFFFD")
expected = `a <span class="added-code">></span> b`
assert.Equal(t, expected, output)
}

func TestDiffWithHighlightTagMatch(t *testing.T) {
totalOverflow := 0
for i := 0; i < 100; i++ {
hcd := newHighlightCodeDiff()
hcd.placeholderMaxCount = i
diffs := hcd.diffWithHighlight(
"main.js", "",
"a='1'",
"b='2'",
)
totalOverflow += hcd.placeholderOverflowCount

output := diffToHTML(nil, diffs, DiffLineDel)
c1 := strings.Count(output, "<span")
c2 := strings.Count(output, "</span")
assert.Equal(t, c1, c2)

output = diffToHTML(nil, diffs, DiffLineAdd)
c1 = strings.Count(output, "<span")
c2 = strings.Count(output, "</span")
assert.Equal(t, c1, c2)
}
assert.NotZero(t, totalOverflow)
}
Loading