mirror of
https://github.com/gohugoio/hugo.git
synced 2025-03-21 02:22:58 +00:00
parent
be8c067577
commit
15463d3d45
1 changed files with 35 additions and 0 deletions
|
@ -15,10 +15,13 @@ package helpers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"crypto/sha1"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io/ioutil"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/spf13/hugo/hugofs"
|
||||||
jww "github.com/spf13/jwalterweatherman"
|
jww "github.com/spf13/jwalterweatherman"
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
)
|
)
|
||||||
|
@ -42,6 +45,33 @@ func Highlight(code string, lexer string) string {
|
||||||
return code
|
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 out bytes.Buffer
|
||||||
var stderr bytes.Buffer
|
var stderr bytes.Buffer
|
||||||
style := viper.GetString("PygmentsStyle")
|
style := viper.GetString("PygmentsStyle")
|
||||||
|
@ -62,5 +92,10 @@ func Highlight(code string, lexer string) string {
|
||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Write cache file
|
||||||
|
if err := WriteToDisk(cachefile, bytes.NewReader(out.Bytes()), fs); err != nil {
|
||||||
|
jww.ERROR.Print(stderr.String())
|
||||||
|
}
|
||||||
|
|
||||||
return out.String()
|
return out.String()
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue