From 3d71de6533d44fb79fd180ba0d67f937b4a912a3 Mon Sep 17 00:00:00 2001 From: Marc Cataford Date: Sun, 28 Jan 2024 23:50:17 -0500 Subject: [PATCH] fix(python): handle cases where the python runtime dir does not exist --- python/version.go | 8 ++++++++ python/version_test.go | 12 ++++++++++++ state/state.go | 8 ++++++++ 3 files changed, 28 insertions(+) diff --git a/python/version.go b/python/version.go index 04a94c3..888c588 100644 --- a/python/version.go +++ b/python/version.go @@ -30,9 +30,17 @@ type SelectedVersion struct { } func ListInstalledVersions() ([]string, error) { + if ensureErr := state.EnsureStatePath("runtimes"); ensureErr != nil { + return []string{}, ensureErr + } + runtimesDir := state.GetStatePath("runtimes", "python") entries, err := os.ReadDir(runtimesDir) + if os.IsNotExist(err) { + return []string{}, nil + } + if err != nil { return []string{}, err } diff --git a/python/version_test.go b/python/version_test.go index dd8b287..88790a8 100644 --- a/python/version_test.go +++ b/python/version_test.go @@ -149,6 +149,18 @@ func TestListInstalledVersionNoVersionsInstalled(t *testing.T) { } } +func TestListInstalledVersionNoVersionsInstalledNoPythonDir(t *testing.T) { + defer testutils.SetupAndCleanupEnvironment(t)() + + os.MkdirAll(state.GetStatePath("runtimes"), 0750) + + installedVersions, _ := ListInstalledVersions() + + if len(installedVersions) != 0 { + t.Errorf("Expected 0 elements, got %d (%s).", len(installedVersions), installedVersions) + } +} + func TestListInstalledVersionNoRuntimesDir(t *testing.T) { defer testutils.SetupAndCleanupEnvironment(t)() diff --git a/state/state.go b/state/state.go index c7a20c6..58afebc 100644 --- a/state/state.go +++ b/state/state.go @@ -27,6 +27,14 @@ func GetStatePath(pathSegments ...string) string { return path.Join(allSegments...) } +func EnsureStatePath(pathSegments ...string) error { + path := GetStatePath(pathSegments...) + + _, err := os.Stat(path) + + return err +} + func ReadState() State { c, _ := ioutil.ReadFile(GetStatePath("state.json"))