package server import ( "fmt" "html" "html/template" "net/http" "strings" ) func (s *Server) handleRevisionView( w http.ResponseWriter, r *http.Request, ) { hash := strings.TrimPrefix( r.URL.Path, "/r/view/", ) revision, err := s.store.GetRevision(hash) if err != nil { http.Error( w, err.Error(), 500, ) return } s.render( w, "revision_view.gohtml", map[string]any{ "Title": "Revision View", "Revision": revision, "RenderedHTML": template.HTML( revision.Body, ), }, ) } func renderColoredDiff( before string, after string, ) string { beforeLines := strings.Split( before, "\n", ) afterLines := strings.Split( after, "\n", ) max := len(beforeLines) if len(afterLines) > max { max = len(afterLines) } var out []string out = append( out, `
`,
)
for i := 0; i < max; i++ {
lineNo := i + 1
var b string
var a string
if i < len(beforeLines) {
b = beforeLines[i]
}
if i < len(afterLines) {
a = afterLines[i]
}
switch {
case b == a:
out = append(
out,
fmt.Sprintf(
`%4d %s`,
lineNo,
html.EscapeString(a),
),
)
default:
if b != "" {
out = append(
out,
fmt.Sprintf(
`%4d - %s`,
lineNo,
html.EscapeString(b),
),
)
}
if a != "" {
out = append(
out,
fmt.Sprintf(
`%4d + %s`,
lineNo,
html.EscapeString(a),
),
)
}
}
}
out = append(
out,
"",
)
return strings.Join(
out,
"\n",
)
}
func (s *Server) handleRevisionDiff(
w http.ResponseWriter,
r *http.Request,
) {
path := strings.TrimPrefix(
r.URL.Path,
"/r/diff/",
)
parts := strings.SplitN(
path,
"/",
2,
)
if len(parts) != 2 {
http.Error(
w,
"bad diff path",
400,
)
return
}
beforeRev, err :=
s.store.GetRevision(parts[0])
if err != nil {
http.Error(
w,
err.Error(),
500,
)
return
}
afterRev, err :=
s.store.GetRevision(parts[1])
if err != nil {
http.Error(
w,
err.Error(),
500,
)
return
}
diffHTML := renderColoredDiff(
beforeRev.Body,
afterRev.Body,
)
s.render(
w,
"revision_diff.gohtml",
map[string]any{
"Title": "Revision Diff",
"Before": beforeRev,
"After": afterRev,
"DiffHTML": template.HTML(
diffHTML,
),
},
)
}