refactor(consts): lazily initialize cache dir

This commit is contained in:
ayn2op 2026-07-02 20:59:50 -04:00
parent 878d2d2ca0
commit 825745e9e2

View file

@ -4,25 +4,26 @@ import (
"log/slog"
"os"
"path/filepath"
"sync"
)
const Name = "discordo"
var cacheDir string
func CacheDir() string {
return cacheDir
}
func init() {
var cacheDir = sync.OnceValue(func() string {
userCacheDir, err := os.UserCacheDir()
if err != nil {
userCacheDir = os.TempDir()
slog.Warn("failed to get user cache dir; falling back to temp dir", "err", err, "path", userCacheDir)
}
cacheDir = filepath.Join(userCacheDir, Name)
if err := os.MkdirAll(cacheDir, os.ModePerm); err != nil {
slog.Error("failed to create cache dir", "err", err, "path", cacheDir)
path := filepath.Join(userCacheDir, Name)
if err := os.MkdirAll(path, os.ModePerm); err != nil {
slog.Error("failed to create cache dir", "err", err, "path", path)
}
return path
})
func CacheDir() string {
return cacheDir()
}