Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: alias command #10

Merged
merged 12 commits into from Mar 5, 2024
36 changes: 36 additions & 0 deletions cmd/alias.go
@@ -0,0 +1,36 @@
package cmd

import (
"fmt"
"os"

"github.com/fatih/color"
"github.com/spf13/cobra"

"github.com/tfversion/tfversion/pkg/alias"
)

const (
aliasExample = "# Alias a Terraform version\n" +
ChrisTerBeke marked this conversation as resolved.
Show resolved Hide resolved
"tfversion alias default 1.7.4"
ChrisTerBeke marked this conversation as resolved.
Show resolved Hide resolved
)

var (
aliasCmd = &cobra.Command{
Use: "alias",
Short: "Alias a Terraform version",
Example: aliasExample,
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 2 {
fmt.Println("error: provide an alias name and Terraform version")
fmt.Printf("See %s for help and examples\n", color.CyanString("`tfversion alias -h`"))
os.Exit(1)
}
alias.AliasVersion(args[0], args[1])
},
}
)

func init() {
rootCmd.AddCommand(aliasCmd)
ChrisTerBeke marked this conversation as resolved.
Show resolved Hide resolved
}
47 changes: 47 additions & 0 deletions pkg/alias/alias.go
@@ -0,0 +1,47 @@
package alias

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

"github.com/fatih/color"
"github.com/tfversion/tfversion/pkg/download"
"github.com/tfversion/tfversion/pkg/helpers"
)

func AliasVersion(alias string, version string) {
if !download.IsAlreadyDownloaded(version) {
if helpers.IsPreReleaseVersion(version) {
fmt.Printf("Terraform version %s not found, run %s to install\n", color.YellowString(version), color.CyanString(fmt.Sprintf("`tfversion install %s`", version)))
} else {
fmt.Printf("Terraform version %s not found, run %s to install\n", color.CyanString(version), color.CyanString(fmt.Sprintf("`tfversion install %s`", version)))
}
os.Exit(0)
}

// delete existing alias symlink, we consider it non-destructive anyways since you can easily restore it
aliasPath := filepath.Join(download.GetDownloadLocation(), alias)
_, err := os.Lstat(aliasPath)
if err == nil {
err = os.RemoveAll(aliasPath)
if err != nil {
fmt.Printf("error removing symlink: %v\n", err)
os.Exit(1)
}
}

// create the symlink
binaryVersionPath := download.GetInstallLocation(version)
err = os.Symlink(binaryVersionPath, aliasPath)
if err != nil {
fmt.Printf("error creating symlink: %v\n", err)
os.Exit(1)
}

if helpers.IsPreReleaseVersion(version) {
fmt.Printf("Aliased Terraform version %s as %s\n", color.YellowString(version), color.YellowString(alias))
} else {
fmt.Printf("Aliased Terraform version %s as %s\n", color.CyanString(version), color.CyanString(alias))
}
}