Files
himewiki/internal/format/diff.go

67 lines
1.5 KiB
Go
Raw Permalink Normal View History

2025-09-14 13:50:57 +09:00
package format
import (
"html/template"
2025-11-15 18:43:05 +09:00
"strings"
2025-09-14 13:50:57 +09:00
)
2025-11-18 18:49:40 +09:00
func escapeIndentHTML(line string) string {
var buf strings.Builder
i := 0
for i < len(line) && line[i] == ' ' {
buf.WriteString("&nbsp;")
i++
}
buf.WriteString(template.HTMLEscapeString(line[i:]))
return buf.String()
}
2025-11-15 18:43:05 +09:00
// Diff formats diff text to HTML.
2025-09-14 13:50:57 +09:00
func Diff(text string) string {
index := 0
2025-11-15 18:43:05 +09:00
// skip headers
lineNumber := 0
2025-11-17 20:12:10 +09:00
for lineNumber < 2 && index < len(text) {
2025-11-15 18:43:05 +09:00
_, index = indexLineEnd(text, index)
2025-11-17 20:12:10 +09:00
lineNumber++
2025-11-15 18:43:05 +09:00
}
var html strings.Builder
for index < len(text) {
lineEnd, nextLine := indexLineEnd(text, index)
line := text[index:lineEnd]
index = nextLine
2025-09-14 13:50:57 +09:00
if len(line) < 1 {
2025-11-15 09:11:41 +09:00
html.WriteString("<br />\n")
2025-11-15 18:43:05 +09:00
continue
}
c := line[0]
if c == '+' {
2025-12-01 20:38:13 +09:00
html.WriteString("<strong class=\"plus\">+</strong>")
html.WriteString("<strong class=\"plus-line\">")
2025-11-18 18:49:40 +09:00
html.WriteString(escapeIndentHTML(line[1:]))
2025-12-01 20:38:13 +09:00
html.WriteString("</strong><br />\n")
2025-11-15 18:43:05 +09:00
} else if c == '-' {
2025-12-01 20:38:13 +09:00
html.WriteString("<em class=\"minus\">-</em>")
html.WriteString("<em class=\"minus-line\">")
2025-11-18 18:49:40 +09:00
html.WriteString(escapeIndentHTML(line[1:]))
2025-12-01 20:38:13 +09:00
html.WriteString("</em><br />\n")
2025-11-15 18:43:05 +09:00
} else if c == '@' {
2025-11-18 18:49:40 +09:00
html.WriteString("<span class=\"hunk\">")
html.WriteString(template.HTMLEscapeString(line))
2025-11-15 18:43:05 +09:00
html.WriteString("</span><br />\n")
} else if c == ' ' {
2025-11-18 18:49:40 +09:00
html.WriteString(escapeIndentHTML(line))
2025-11-15 18:43:05 +09:00
html.WriteString("<br />\n")
2025-09-14 13:50:57 +09:00
} else {
2025-11-18 18:49:40 +09:00
html.WriteString(template.HTMLEscapeString(line))
2025-11-15 18:43:05 +09:00
html.WriteString("<br />\n")
2025-09-14 13:50:57 +09:00
}
}
return html.String()
}