github.com/JarrahG/buffalocli@v0.0.0-20230801092127-b85bfd5d395a/internal/plugins/cache.go (about) 1 package plugins 2 3 import ( 4 "crypto/sha256" 5 "encoding/json" 6 "fmt" 7 "io" 8 "os" 9 "os/user" 10 "path/filepath" 11 "sync" 12 13 "github.com/gobuffalo/envy" 14 ) 15 16 type cachedPlugin struct { 17 Commands Commands `json:"commands"` 18 CheckSum string `json:"check_sum"` 19 } 20 21 type cachedPlugins map[string]cachedPlugin 22 23 // CachePath returns the path to the plugins cache 24 var CachePath = func() string { 25 home := "." 26 if usr, err := user.Current(); err == nil { 27 home = usr.HomeDir 28 } 29 return filepath.Join(home, ".buffalo", "plugin.cache") 30 }() 31 32 var cacheMoot sync.RWMutex 33 34 var cacheOn = envy.Get("BUFFALO_PLUGIN_CACHE", "on") 35 36 var cache = func() cachedPlugins { 37 m := cachedPlugins{} 38 if cacheOn != "on" { 39 return m 40 } 41 f, err := os.Open(CachePath) 42 if err != nil { 43 return m 44 } 45 defer f.Close() 46 if err := json.NewDecoder(f).Decode(&m); err != nil { 47 f.Close() 48 os.Remove(f.Name()) 49 } 50 return m 51 }() 52 53 func findInCache(path string) (cachedPlugin, bool) { 54 cacheMoot.RLock() 55 defer cacheMoot.RUnlock() 56 cp, ok := cache[path] 57 return cp, ok 58 } 59 60 func saveCache() error { 61 if cacheOn != "on" { 62 return nil 63 } 64 cacheMoot.Lock() 65 defer cacheMoot.Unlock() 66 if err := os.MkdirAll(filepath.Dir(CachePath), 0o744); err != nil { 67 return err 68 } 69 f, err := os.Create(CachePath) 70 if err != nil { 71 return err 72 } 73 return json.NewEncoder(f).Encode(cache) 74 } 75 76 func sum(path string) string { 77 f, err := os.Open(path) 78 if err != nil { 79 return "" 80 } 81 defer f.Close() 82 hash := sha256.New() 83 if _, err := io.Copy(hash, f); err != nil { 84 return "" 85 } 86 sum := hash.Sum(nil) 87 88 s := fmt.Sprintf("%x", sum) 89 return s 90 } 91 92 func addToCache(path string, cp cachedPlugin) { 93 if cp.CheckSum == "" { 94 cp.CheckSum = sum(path) 95 } 96 cacheMoot.Lock() 97 defer cacheMoot.Unlock() 98 cache[path] = cp 99 }