Skip to content

Commit

Permalink
Don't require HOME if TERRAGRUNT_PROVIDER_CACHE_DIR is set (#3649)
Browse files Browse the repository at this point in the history
* Don't require HOME if TERRAGRUNT_PROVIDER_CACHE_DIR is set

* Add ProviderCache tests related to `ProviderCacheDir`

The new tests ensure correct behaviour with $HOME when `ProviderCacheDir`is specified.
  • Loading branch information
g7r authored Dec 13, 2024
1 parent 4f55464 commit 38ceae2
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 5 deletions.
11 changes: 6 additions & 5 deletions cli/provider_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,17 +62,18 @@ type ProviderCache struct {
}

func InitProviderCacheServer(opts *options.TerragruntOptions) (*ProviderCache, error) {
cacheDir, err := util.GetCacheDir()
if err != nil {
return nil, err
}

// ProviderCacheDir has the same file structure as terraform plugin_cache_dir.
// https://developer.hashicorp.com/terraform/cli/config/config-file#provider-plugin-cache
if opts.ProviderCacheDir == "" {
cacheDir, err := util.GetCacheDir()
if err != nil {
return nil, err
}

opts.ProviderCacheDir = filepath.Join(cacheDir, "providers")
}

var err error
if opts.ProviderCacheDir, err = filepath.Abs(opts.ProviderCacheDir); err != nil {
return nil, errors.New(err)
}
Expand Down
39 changes: 39 additions & 0 deletions cli/provider_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

"github.com/google/uuid"
"github.com/gruntwork-io/terragrunt/cli"
"github.com/gruntwork-io/terragrunt/options"
"github.com/gruntwork-io/terragrunt/pkg/log"
"github.com/gruntwork-io/terragrunt/terraform/cache"
"github.com/gruntwork-io/terragrunt/terraform/cache/handlers"
Expand Down Expand Up @@ -162,3 +163,41 @@ func TestProviderCache(t *testing.T) {
})
}
}

func TestProviderCacheWithProviderCacheDir(t *testing.T) {
// testing.T can Setenv, but can't Unsetenv
unsetEnv := func(t *testing.T, v string) {
// let testing.T do the recovery and work around t.Parallel()
t.Setenv(v, "")
require.NoError(t, os.Unsetenv(v))
}

t.Run("Homeless", func(t *testing.T) {
cacheDir := t.TempDir()

unsetEnv(t, "HOME")
unsetEnv(t, "XDG_CACHE_HOME")

_, err := cli.InitProviderCacheServer(&options.TerragruntOptions{
ProviderCacheDir: cacheDir,
})
require.NoError(t, err, "ProviderCache shouldn't read HOME environment variable")
})

t.Run("NoNewDirectoriesAtHOME", func(t *testing.T) {
home := t.TempDir()
cacheDir := t.TempDir()

t.Setenv("HOME", home)

_, err := cli.InitProviderCacheServer(&options.TerragruntOptions{
ProviderCacheDir: cacheDir,
})
require.NoError(t, err)

// Cache server shouldn't create any directory at $HOME when ProviderCacheDir is specified
entries, err := os.ReadDir(home)
require.NoError(t, err)
require.Empty(t, entries, "No new directories should be created at $HOME")
})
}

0 comments on commit 38ceae2

Please sign in to comment.