oh-my-posh/src/environment_cache.go

72 lines
1.3 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 (
cachePath = "/.omp.cache"
)
2021-09-21 22:53:59 -07:00
type cacheObject struct {
Value string `json:"value"`
Timestamp int64 `json:"timestamp"`
TTL int64 `json:"ttl"`
}
2021-09-21 11:22:59 -07:00
type fileCache struct {
cache *concurrentMap
home string
}
func (fc *fileCache) init(home string) {
fc.cache = newConcurrentMap()
fc.home = home
2021-09-21 22:53:59 -07:00
content, err := ioutil.ReadFile(fc.home + cachePath)
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() {
2021-09-23 13:57:38 -07:00
if dump, err := json.MarshalIndent(fc.cache.list(), "", " "); err == nil {
2021-09-21 22:53:59 -07:00
_ = ioutil.WriteFile(fc.home+cachePath, dump, 0644)
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 + co.TTL*60)
if expired {
fc.cache.remove(key)
return "", false
}
return co.Value, true
2021-09-21 11:22:59 -07:00
}
2021-09-21 22:53:59 -07:00
func (fc *fileCache) set(key, value string, ttl int64) {
fc.cache.set(key, &cacheObject{
Value: value,
Timestamp: time.Now().Unix(),
TTL: ttl,
})
2021-09-21 11:22:59 -07:00
}