Git diff to HTML

744 Views Asked by At

I'm writing a webhook in Go that sends me an email with the diff for every commit to certain repository. Right now I am sending the diff as raw text like this:

https://github.com/ee92/go-lambda/commit/ac56fc2cfe86c50e9d73ecb0f8db74c672e205cd.diff

I wish to send it as pretty formatted HTML with color like you see on github or bitbucket so it will be easier to read what changed. Really stumped on how to go about this. Appreciate any advice. Thanks.

1

There are 1 best solutions below

0
On

You could use the stdlib html/template library to make a pretty HTML template and pass your raw string as a param:

https://golang.org/pkg/html/template/

import "text/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")

will produce this:

Hello, <script>alert('you have been pwned')</script>!

So in your case, define a template in a separate file, read it in, and then call

t, err := template.ParseFiles("./path/to/template.html")
if err != nil {
    log.Fatal(err)
}

err = t.ExecuteTemplate(out, "T", rawDiffString)
if err != nil {
    log.Fatal(err)
}

which will take your diff string and stick it into the template wherever you defined the template variable.

You'll have to read the spec for how Go parses through the HTML template to properly format your HTML file.