43 lines
959 B
Go
43 lines
959 B
Go
package cache_manager
|
|
|
|
import (
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
type CacheManager struct {
|
|
Root string
|
|
}
|
|
|
|
// Creates a new cache manager rooted at <cacheRoot>.
|
|
//
|
|
// If <cacheRoot> does not exist, returns an error.
|
|
func NewCacheManager(cacheRoot string) (*CacheManager, error) {
|
|
if _, err := os.Stat(cacheRoot); errors.Is(err, os.ErrNotExist) {
|
|
return nil, errors.New("Cache root must exist.")
|
|
}
|
|
|
|
return &CacheManager{
|
|
Root: cacheRoot,
|
|
}, nil
|
|
}
|
|
|
|
// Returns a path prefixed with the cache root.
|
|
func (c CacheManager) Path(elems ...string) string {
|
|
return filepath.Join(c.Root, filepath.Join(elems...))
|
|
}
|
|
|
|
// Checks whether a specific top-level items exists in the cache.
|
|
func (c CacheManager) Exists(key string) bool {
|
|
if _, err := os.Stat(c.Path(key)); errors.Is(err, os.ErrNotExist) {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// Deletes an element from the cache, if it exists.
|
|
func (c CacheManager) Evict(key string) {
|
|
os.RemoveAll(c.Path(key))
|
|
}
|