From 91c8adc4e5804b8c0d308dad1ea698a3549c878b Mon Sep 17 00:00:00 2001 From: Carolyn Van Slyck Date: Thu, 16 Apr 2020 09:58:29 -0500 Subject: [PATCH] Remove old cached bundle on refresh When we refresh the cached files for a bundle, delete the old directory so that any files that would not be overwritten, for example the updated bundle doesn't have a relocation mapping file or manifest, are removed. --- pkg/cache/cache.go | 6 ++++++ pkg/cache/cache_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index 16c1fc0f0..62746cbf7 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -75,6 +75,12 @@ func (c *Cache) StoreBundle(bundleTag string, bun bundle.Bundle, reloMap *reloca } cb.SetCacheDir(cacheDir) + // Remove any previously cached bundle files + err = c.FileSystem.RemoveAll(cb.cacheDir) + if err != nil { + return CachedBundle{}, errors.Wrapf(err, "cannot remove existing cache directory %s", cb.BundlePath) + } + cb.BundlePath = cb.BuildBundlePath() err = c.FileSystem.MkdirAll(filepath.Dir(cb.BundlePath), os.ModePerm) if err != nil { diff --git a/pkg/cache/cache_test.go b/pkg/cache/cache_test.go index 7f794d2a6..5c0697d49 100644 --- a/pkg/cache/cache_test.go +++ b/pkg/cache/cache_test.go @@ -222,3 +222,36 @@ func TestStoreManifest(t *testing.T) { }) } } + +func TestCache_StoreBundle_Overwrite(t *testing.T) { + cfg := config.NewTestConfig(t) + home, _ := cfg.Config.GetHomeDir() + cacheDir := filepath.Join(home, "cache") + cfg.TestContext.AddTestDirectory("testdata", cacheDir) + c := New(cfg.Config) + + // Setup an existing bundle with some extraneous junk that would not + // be overwritten + cb := CachedBundle{Tag: kahn1dot01} + cb.SetCacheDir(cacheDir) + cfg.FileSystem.Create(cb.BuildManifestPath()) + cfg.FileSystem.Create(cb.BuildRelocationFilePath()) + junkPath := filepath.Join(cb.cacheDir, "junk.txt") + cfg.FileSystem.Create(junkPath) + + // Refresh the cache + cb, err := c.StoreBundle(cb.Tag, bundle.Bundle{}, nil) + require.NoError(t, err, "StoreBundle failed") + + exists, _ := cfg.FileSystem.Exists(cb.BuildBundlePath()) + assert.True(t, exists, "bundle.json should have been written in the refreshed cache") + + exists, _ = cfg.FileSystem.Exists(cb.BuildManifestPath()) + assert.False(t, exists, "porter.yaml should have been deleted from the bundle cache") + + exists, _ = cfg.FileSystem.Exists(cb.BuildRelocationFilePath()) + assert.False(t, exists, "relocation-mapping.json should have been deleted from the bundle cache") + + exists, _ = cfg.FileSystem.Exists(junkPath) + assert.False(t, exists, "the random file should have been deleted from the bundle cache") +}