-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcache.go
96 lines (81 loc) · 2.06 KB
/
cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package template // import "github.com/orkestr8/template"
import (
"fmt"
"net/url"
"os"
"os/user"
"path/filepath"
"strings"
"github.com/spf13/afero"
)
// CacheDirEnvVar is the environment variable used to set the cache of the playbooks
const CacheDirEnvVar = "INFRAKIT_PLAYBOOKS_CACHE"
// default filesystem abstraction
var fs = afero.NewOsFs()
// Setup sets up the necessary environment for running this module -- ie make sure cache directory exists, etc.
func Setup() error {
dir := Dir()
if dir == "" {
return fmt.Errorf("Env not set:%s", CacheDirEnvVar)
}
exists, err := afero.Exists(fs, dir)
if err != nil || !exists {
err = fs.MkdirAll(dir, 0755)
if err != nil {
return err
}
}
// try again
exists, err = afero.Exists(fs, dir)
if !exists {
return fmt.Errorf("Cannot set up directory %s: err=%v", dir, err)
}
return err
}
// Dir returns the directory to use for playbooks caching which can be customize via environment variable
func Dir() string {
if cacheDir := os.Getenv(CacheDirEnvVar); cacheDir != "" {
return cacheDir
}
// if there's INFRAKIT_HOME defined
home := os.Getenv("INFRAKIT_HOME")
if home != "" {
return filepath.Join(home, "playbook-cache")
}
home = os.Getenv("HOME")
if usr, err := user.Current(); err == nil {
home = usr.HomeDir
}
return filepath.Join(home, ".infrakit/playbook-cache")
}
// cache is turned on only when opt.CacheDir is not empty string
func checkCache(p string, opt Options, fetch func() ([]byte, error)) ([]byte, error) {
if opt.CacheDir == "" {
return fetch()
}
// No need to cache: str:// and file:// since the contents are local.
if strings.Index("str://", p) == 0 {
return fetch()
}
if strings.Index("file://", p) == 0 {
return fetch()
}
u, err := url.Parse(p)
if err != nil {
return nil, err
}
path := filepath.Join(opt.CacheDir, u.Path)
buff, err := afero.ReadFile(fs, path)
if err != nil {
buff, err = fetch()
if err != nil {
return nil, err
}
}
go func() {
fs.MkdirAll(filepath.Dir(path), 0755)
afero.WriteFile(fs, path, buff, 0644)
return
}()
return buff, err
}