Skip to content

Commit

Permalink
Show nicer error when version does not exist (#31)
Browse files Browse the repository at this point in the history
* Show nicer error when version does not exist

* Add very first unit test

* Fix test env
  • Loading branch information
ChrisTerBeke committed Mar 8, 2024
1 parent bfa849f commit e64ec58
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
23 changes: 23 additions & 0 deletions pkg/download/download_test.go
@@ -0,0 +1,23 @@
package download

import (
"os"
"path/filepath"
"testing"
)

func TestGetDownloadLocation(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("HOME", tempDir)
downloadLocation := GetDownloadLocation()

expectedLocation := filepath.Join(tempDir, ".tfversion", "versions")
if downloadLocation != expectedLocation {
t.Errorf("Expected download location %s, but got %s", expectedLocation, downloadLocation)
}

_, err := os.Stat(downloadLocation)
if os.IsNotExist(err) {
t.Errorf("Download location directory does not exist: %s", downloadLocation)
}
}
4 changes: 4 additions & 0 deletions pkg/helpers/helper.go
Expand Up @@ -24,6 +24,10 @@ func ColoredInstallHelper(version string) string {
return color.CyanString(fmt.Sprintf("`tfversion install %s`", version))
}

func ColoredListHelper() string {
return color.CyanString("`tfversion list`")
}

// ExitWithError prints an error message and exits with status code 1
func ExitWithError(message string, err error) {
fmt.Printf("%s %s: %s\n", color.HiRedString("error:"), message, err)
Expand Down
8 changes: 8 additions & 0 deletions pkg/install/install.go
Expand Up @@ -3,6 +3,7 @@ package install
import (
"fmt"
"runtime"
"slices"

"github.com/tfversion/tfversion/pkg/download"
"github.com/tfversion/tfversion/pkg/helpers"
Expand All @@ -16,6 +17,13 @@ func InstallVersion(version string) {
helpers.ExitWithError("installing", err)
}

// Check if the version exists
availableVersions := list.GetAvailableVersions()
if !slices.Contains(availableVersions, version) {
err := fmt.Errorf("terraform version %s does not exist, please run %s to check available versions", helpers.ColoredVersion(version), helpers.ColoredListHelper())
helpers.ExitWithError("installing", err)
}

// Download the Terraform release
zipFile, err := download.Download(version, runtime.GOOS, runtime.GOARCH)
if err != nil {
Expand Down

0 comments on commit e64ec58

Please sign in to comment.