diff options
author | Ruben Vermeersch <ruben@rocketeer.be> | 2015-03-27 17:05:17 +0100 |
---|---|---|
committer | bep <bjorn.erik.pedersen@gmail.com> | 2015-03-27 19:50:48 +0100 |
commit | 15463d3d4584675d1d8c9a25c8259adce163c4ea (patch) | |
tree | f65957da84174db91c63286a7f1668fae9d601d4 | |
parent | be8c06757707cf240baaa72d6e659fcd2b6261f2 (diff) |
Cache pygments rendering between runs
Fixes #1000
-rw-r--r-- | helpers/pygments.go | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/helpers/pygments.go b/helpers/pygments.go index a615f21ba..0f06635fc 100644 --- a/helpers/pygments.go +++ b/helpers/pygments.go @@ -15,10 +15,13 @@ package helpers import ( "bytes" + "crypto/sha1" "fmt" + "io/ioutil" "os/exec" "strings" + "github.com/spf13/hugo/hugofs" jww "github.com/spf13/jwalterweatherman" "github.com/spf13/viper" ) @@ -42,6 +45,33 @@ func Highlight(code string, lexer string) string { return code } + fs := hugofs.OsFs + + // Try to read from cache first + hash := sha1.Sum([]byte(code)) + cachefile := fmt.Sprintf("%s/pygments-%s-%x", viper.GetString("CacheDir"), lexer, hash) + exists, err := Exists(cachefile, fs) + if err != nil { + jww.ERROR.Print(err.Error()) + return code + } + if exists { + f, err := fs.Open(cachefile) + if err != nil { + jww.ERROR.Print(err.Error()) + return code + } + + s, err := ioutil.ReadAll(f) + if err != nil { + jww.ERROR.Print(err.Error()) + return code + } + + return string(s) + } + + // No cache file, render and cache it var out bytes.Buffer var stderr bytes.Buffer style := viper.GetString("PygmentsStyle") @@ -62,5 +92,10 @@ func Highlight(code string, lexer string) string { return code } + // Write cache file + if err := WriteToDisk(cachefile, bytes.NewReader(out.Bytes()), fs); err != nil { + jww.ERROR.Print(stderr.String()) + } + return out.String() } |