From 2e8d188246a60aac4d698708c43529b774e94ba1 Mon Sep 17 00:00:00 2001 From: Marc Cataford Date: Sun, 1 Sep 2024 13:18:13 -0400 Subject: [PATCH] fix: use dynamic user cache dir instead of hardcoding value --- internal/commands/configuration.go | 12 ++++++++---- internal/commands/configuration_test.go | 10 ++-------- metadata/constants.go | 3 +++ 3 files changed, 13 insertions(+), 12 deletions(-) create mode 100644 metadata/constants.go diff --git a/internal/commands/configuration.go b/internal/commands/configuration.go index bfe9ac6..7bb5b29 100644 --- a/internal/commands/configuration.go +++ b/internal/commands/configuration.go @@ -7,10 +7,9 @@ import ( "os/user" "path/filepath" "strings" + metadata "courgette/metadata" ) -const defaultCacheDirectory = "~/.cache/courgette" - type CacheConfiguration struct { Dir string `yaml:"dir"` } @@ -29,6 +28,11 @@ type Configuration struct { Cache CacheConfiguration `yaml:"cache"` } +func getDefaultCacheDirectory() string { + dir, _ := os.UserCacheDir() + return filepath.Join(dir, metadata.APPLICATION_NAME) +} + func (c Configuration) GetCacheDir() string { currentUser, _ := user.Current() homeDir := currentUser.HomeDir @@ -53,7 +57,7 @@ func applyConfigDefaults(config Configuration) Configuration { Driver: "podman", }, Cache: CacheConfiguration{ - Dir: defaultCacheDirectory, + Dir: getDefaultCacheDirectory(), }, } @@ -77,7 +81,7 @@ func NewConfigFromYamlBytes(configRaw []byte) (*Configuration, error) { config = applyConfigDefaults(config) - if err := os.MkdirAll(config.Cache.Dir, 0755); err != nil { + if err := os.MkdirAll(config.GetCacheDir(), 0755); err != nil { return nil, err } diff --git a/internal/commands/configuration_test.go b/internal/commands/configuration_test.go index 3cc7a53..5bc17d7 100644 --- a/internal/commands/configuration_test.go +++ b/internal/commands/configuration_test.go @@ -3,20 +3,14 @@ package commands import ( "os/user" "path/filepath" - "strings" "testing" ) func TestGetCacheDirDefault(t *testing.T) { configuration, _ := NewConfigFromYamlBytes([]byte("")) - parts := strings.Split(defaultCacheDirectory, "/") - user, _ := user.Current() - defaultPathParts := []string{user.HomeDir} - defaultPathParts = append(defaultPathParts, parts[1:]...) - defaultPath := filepath.Join(defaultPathParts...) - if configuration.GetCacheDir() != defaultPath { - t.Errorf("Expected default %s, got %s instead.", defaultPath, configuration.GetCacheDir()) + if configuration.GetCacheDir() != getDefaultCacheDirectory() { + t.Errorf("Expected default %s, got %s instead.", getDefaultCacheDirectory(), configuration.GetCacheDir()) } } diff --git a/metadata/constants.go b/metadata/constants.go new file mode 100644 index 0000000..9120eff --- /dev/null +++ b/metadata/constants.go @@ -0,0 +1,3 @@ +package metadata + +const APPLICATION_NAME = "courgette"