oh-my-posh/src/environment_cache.go

79 lines
1.5 KiB
Go
Raw Normal View History

2021-09-21 11:22:59 -07:00
package main
import (
2021-09-21 22:53:59 -07:00
"encoding/json"
2021-09-21 11:22:59 -07:00
"io/ioutil"
2021-09-21 22:53:59 -07:00
"time"
2021-09-21 11:22:59 -07:00
)
const (
fileName = "/omp.cache"
2021-09-21 11:22:59 -07:00
)
2021-09-21 22:53:59 -07:00
type cacheObject struct {
Value string `json:"value"`
Timestamp int64 `json:"timestamp"`
TTL int `json:"ttl"`
2021-09-21 22:53:59 -07:00
}
2021-09-21 11:22:59 -07:00
type fileCache struct {
cache *concurrentMap
cachePath string
2021-09-21 11:22:59 -07:00
}
func (fc *fileCache) init(cachePath string) {
2021-09-21 11:22:59 -07:00
fc.cache = newConcurrentMap()
fc.cachePath = cachePath
content, err := ioutil.ReadFile(fc.cachePath + fileName)
2021-09-21 11:22:59 -07:00
if err != nil {
return
}
2021-09-21 22:53:59 -07:00
var list map[string]*cacheObject
if err := json.Unmarshal(content, &list); err != nil {
return
}
for key, co := range list {
fc.cache.set(key, co)
2021-09-21 11:22:59 -07:00
}
}
func (fc *fileCache) close() {
cache := fc.cache.list()
if len(cache) == 0 {
return
}
if dump, err := json.MarshalIndent(cache, "", " "); err == nil {
_ = ioutil.WriteFile(fc.cachePath+fileName, dump, 0644)
2021-09-21 11:22:59 -07:00
}
}
// returns the value for the given key as long as
// the TTL (minutes) is not expired
2021-09-21 11:22:59 -07:00
func (fc *fileCache) get(key string) (string, bool) {
2021-09-21 22:53:59 -07:00
val, found := fc.cache.get(key)
if !found {
return "", false
}
co, ok := val.(*cacheObject)
if !ok {
return "", false
}
expired := time.Now().Unix() >= (co.Timestamp + int64(co.TTL)*60)
2021-09-21 22:53:59 -07:00
if expired {
fc.cache.remove(key)
return "", false
}
return co.Value, true
2021-09-21 11:22:59 -07:00
}
// sets the value for the given key with a TTL (minutes)
func (fc *fileCache) set(key, value string, ttl int) {
2021-09-21 22:53:59 -07:00
fc.cache.set(key, &cacheObject{
Value: value,
Timestamp: time.Now().Unix(),
TTL: ttl,
})
2021-09-21 11:22:59 -07:00
}