Skip to content

Commit

Permalink
Implement current subcommand (#28)
Browse files Browse the repository at this point in the history
* feat: implement current subcommand for displaying active tf version

* refactor: error handling

* refactor: simplify determining current active version

* chore: update error messages
  • Loading branch information
mmourick committed Mar 8, 2024
1 parent 11758df commit 3df93ca
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 2 deletions.
5 changes: 5 additions & 0 deletions README.md
Expand Up @@ -115,6 +115,11 @@ tfversion list --pre-release
tfversion uninstall 1.7.4
```

### Display the currently activated version of Terraform
```sh
tfversion current
```

## Contributing

Contributions are highly appreciated and always welcome.
Expand Down
26 changes: 26 additions & 0 deletions cmd/current.go
@@ -0,0 +1,26 @@
package cmd

import (
"github.com/spf13/cobra"
"github.com/tfversion/tfversion/pkg/current"
)

const (
currentExample = "# Print the current active version of Terraform\n" +
"tfversion current"
)

var (
currentCmd = &cobra.Command{
Use: "current",
Short: "Print the current active version of Terraform",
Example: currentExample,
Run: func(cmd *cobra.Command, args []string) {
current.CheckCurrentVersion()
},
}
)

func init() {
rootCmd.AddCommand(currentCmd)
}
29 changes: 29 additions & 0 deletions pkg/current/current.go
@@ -0,0 +1,29 @@
package current

import (
"fmt"
"os"
"path/filepath"

"github.com/tfversion/tfversion/pkg/download"
"github.com/tfversion/tfversion/pkg/helpers"
"github.com/tfversion/tfversion/pkg/use"
)

// CheckCurrentVersion prints the current active version of Terraform.
func CheckCurrentVersion() {

symlinkPath := filepath.Join(use.GetUseLocation(), download.TerraformBinaryName)
_, err := os.Lstat(symlinkPath)
if err != nil {
helpers.ExitWithError("no current terraform version found", err)
}

realPath, err := filepath.EvalSymlinks(symlinkPath)
if err != nil {
helpers.ExitWithError("resolving symlink", err)
}
_, currentVersion := filepath.Split(filepath.Dir(realPath))

fmt.Printf("Current active Terraform version: %s\n", helpers.ColoredVersion(currentVersion))
}
4 changes: 2 additions & 2 deletions pkg/use/use.go
Expand Up @@ -30,7 +30,7 @@ func UseVersion(versionOrAlias string) {
helpers.ExitWithError("using", err)
}

useLocation := getUseLocation()
useLocation := GetUseLocation()

// inform the user that they need to update their PATH
path := os.Getenv("PATH")
Expand Down Expand Up @@ -96,7 +96,7 @@ func UseRequiredVersion() {
UseVersion(foundVersion)
}

func getUseLocation() string {
func GetUseLocation() string {
user, err := os.UserHomeDir()
if err != nil {
helpers.ExitWithError("user home directory", err)
Expand Down

0 comments on commit 3df93ca

Please sign in to comment.