1
0
mirror of https://github.com/danog/gojekyll.git synced 2024-11-30 08:48:59 +01:00
gojekyll/cache/cache.go

59 lines
1.8 KiB
Go
Raw Normal View History

2017-07-10 00:19:22 +02:00
package cache
2017-07-01 23:16:46 +02:00
import (
2017-07-02 00:11:35 +02:00
"crypto/md5" // nolint: gas
2017-07-01 23:16:46 +02:00
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
)
var disableCache = false
func init() {
s := os.Getenv("GOJEKYLL_DISABLE_CACHE")
if s != "" && s != "0" && s != "false" {
disableCache = true
}
}
2017-07-10 00:19:22 +02:00
// WithFile looks (header, content) up in a user-specific file cache.
2017-07-01 23:16:46 +02:00
// If found, it writes the file contents. Else it calls fn to write to
// both the writer and the file system.
//
// header and content are distinct parameters to relieve the caller from
// having to concatenate them.
2017-07-10 00:19:22 +02:00
func WithFile(header string, content string, fn func() (string, error)) (string, error) {
h := md5.New() // nolint: gas, noncrypto
2017-07-02 00:11:35 +02:00
io.WriteString(h, content) // nolint: errcheck, gas
io.WriteString(h, "\n") // nolint: errcheck, gas
io.WriteString(h, header) // nolint: errcheck, gas
2017-07-01 23:16:46 +02:00
sum := h.Sum(nil)
// don't use ioutil.TempDir, because we want this to last across invocations
2017-07-03 03:08:09 +02:00
// cachedir := filepath.Join("/tmp", os.ExpandEnv("gojekyll-$USER"))
cachedir := filepath.Join(os.TempDir(), os.ExpandEnv("gojekyll-$USER"))
cachefile := filepath.Join(cachedir, fmt.Sprintf("%x%c%x", sum[:1], filepath.Separator, sum[1:]))
2017-07-01 23:16:46 +02:00
// ignore errors; if there's a missing file we don't care, and if it's
// another error we'll pick it up during write
// WriteFile truncates the file before writing it, so ignore empty files.
// If the writer actually wrote an empty file, we'll end up gratuitously
// re-running it, which is okay.
if b, err := ioutil.ReadFile(cachefile); err == nil && len(b) > 0 && !disableCache {
2017-07-04 14:06:34 +02:00
return string(b), err
2017-07-01 23:16:46 +02:00
}
2017-07-04 14:06:34 +02:00
s, err := fn()
if err != nil {
return "", err
2017-07-01 23:16:46 +02:00
}
2017-07-03 03:08:09 +02:00
if err := os.MkdirAll(filepath.Dir(cachefile), 0700); err != nil {
2017-07-04 14:06:34 +02:00
return "", err
2017-07-01 23:16:46 +02:00
}
2017-07-04 14:06:34 +02:00
if err := ioutil.WriteFile(cachefile, []byte(s), 0600); err != nil {
return "", err
2017-07-01 23:16:46 +02:00
}
2017-07-04 14:06:34 +02:00
return s, nil
2017-07-01 23:16:46 +02:00
}