courgette/internal/cache/cache_manager.go

44 lines
959 B
Go
Raw Normal View History

2024-08-31 02:20:56 +00:00
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) {
2024-08-31 02:20:56 +00:00
return false
}
return true
2024-08-31 02:20:56 +00:00
}
// Deletes an element from the cache, if it exists.
func (c CacheManager) Evict(key string) {
os.RemoveAll(c.Path(key))
2024-08-31 02:20:56 +00:00
}