From 8104aa80934d322989b5fe9449fb330b6538d488 Mon Sep 17 00:00:00 2001 From: Stephen Kitt Date: Thu, 10 Feb 2022 14:46:35 +0100 Subject: [PATCH] Try a temporary directory if the user cache fails MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since commit 58c17f6 ("addr.Suggest should lock a file instead of memory"), pkg/internal/testing/addr/manager.go’s init() function tries to create a directory using either os.UserCacheDir() or os.TempDir(), whichever succeeds first. In many build environments, $HOME is non-empty but points to an unusable directory; in such cases, os.UserCacheDir() returns an unusable directory, which causes init() to panic. This changes init() to first try os.UserCacheDir(), including creating the desired directory; if that fails, the whole operation is tried again with os.TempDir(). Fixes: #1799 Signed-off-by: Stephen Kitt --- pkg/internal/testing/addr/manager.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/pkg/internal/testing/addr/manager.go b/pkg/internal/testing/addr/manager.go index caaafa2627..2ce884dd7c 100644 --- a/pkg/internal/testing/addr/manager.go +++ b/pkg/internal/testing/addr/manager.go @@ -42,16 +42,30 @@ var ( ) func init() { - baseDir, err := os.UserCacheDir() + var err error + cacheDir, err = tryUserCacheDir() if err != nil { - baseDir = os.TempDir() + // Either we didn't get a cache directory, or we can't use it + cacheDir, err = tryCacheInDir(os.TempDir()) } - cacheDir = filepath.Join(baseDir, "kubebuilder-envtest") - if err := os.MkdirAll(cacheDir, 0750); err != nil { + if err != nil { panic(err) } } +func tryUserCacheDir() (string, error) { + baseDir, err := os.UserCacheDir() + if err != nil { + return "", err + } + return tryCacheInDir(baseDir) +} + +func tryCacheInDir(dir string) (string, error) { + dir = filepath.Join(dir, "kubebuilder-envtest") + return dir, os.MkdirAll(dir, 0o750) +} + type portCache struct{} func (c *portCache) add(port int) (bool, error) {