2025-09-14 13:50:57 +09:00
|
|
|
package format
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
|
|
|
|
"html/template"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func detectLine(data []byte) (int, int) {
|
|
|
|
|
lineFeed := bytes.IndexByte(data, '\n')
|
|
|
|
|
if lineFeed == -1 {
|
|
|
|
|
lineFeed = len(data)
|
|
|
|
|
}
|
|
|
|
|
lineEnd := lineFeed
|
|
|
|
|
if lineEnd > 0 {
|
|
|
|
|
c := data[lineEnd - 1]
|
|
|
|
|
if c == '\r' {
|
|
|
|
|
lineEnd -= 1
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
nextLine := lineFeed + 1
|
|
|
|
|
return lineEnd, nextLine
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func Diff(text string) string {
|
|
|
|
|
data := []byte(text)
|
|
|
|
|
index := 0
|
|
|
|
|
var html bytes.Buffer
|
2025-09-15 06:46:04 +09:00
|
|
|
lineNo := 0
|
2025-09-14 13:50:57 +09:00
|
|
|
|
|
|
|
|
for index < len(data) {
|
|
|
|
|
lineEnd, nextLine := detectLine(data[index:])
|
|
|
|
|
lineEnd += index
|
|
|
|
|
nextLine += index
|
|
|
|
|
line := data[index:lineEnd]
|
2025-09-15 06:46:04 +09:00
|
|
|
lineNo += 1
|
|
|
|
|
|
|
|
|
|
if lineNo < 3 {
|
|
|
|
|
index = nextLine
|
|
|
|
|
continue
|
|
|
|
|
}
|
2025-09-14 13:50:57 +09:00
|
|
|
|
|
|
|
|
if len(line) < 1 {
|
2025-09-17 22:14:50 +09:00
|
|
|
html.WriteString("<br />\n");
|
2025-09-14 13:50:57 +09:00
|
|
|
} else {
|
|
|
|
|
c := line[0]
|
2025-09-27 07:01:29 +09:00
|
|
|
htmlLine := template.HTMLEscapeString(string(line))
|
2025-09-14 13:50:57 +09:00
|
|
|
if c == '+' {
|
|
|
|
|
html.WriteString("<span class=\"plus\">+</span>")
|
2025-09-27 07:01:29 +09:00
|
|
|
html.WriteString("<span class=\"plus-line\">" + htmlLine[1:] + "</span><br />\n")
|
2025-09-14 13:50:57 +09:00
|
|
|
} else if c == '-' {
|
|
|
|
|
html.WriteString("<span class=\"minus\">-</span>")
|
2025-09-27 07:01:29 +09:00
|
|
|
html.WriteString("<span class=\"minus-line\">" + htmlLine[1:] + "</span><br />\n")
|
2025-09-15 06:46:04 +09:00
|
|
|
} else if c == '@' {
|
|
|
|
|
html.WriteString("<span class=\"hunk\">@")
|
2025-09-27 07:01:29 +09:00
|
|
|
html.WriteString(htmlLine[1:] + "</span><br />\n")
|
|
|
|
|
} else if c == ' ' {
|
|
|
|
|
html.WriteString(" ")
|
|
|
|
|
html.WriteString(htmlLine[1:] + "<br />\n")
|
2025-09-14 13:50:57 +09:00
|
|
|
} else {
|
2025-09-17 22:14:50 +09:00
|
|
|
html.WriteString(htmlLine + "<br />\n")
|
2025-09-14 13:50:57 +09:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
index = nextLine
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return html.String()
|
|
|
|
|
}
|