Skip to content

Commit

Permalink
Feature: remove alias (#23)
Browse files Browse the repository at this point in the history
* Implement tfversion unalias

* Fix typo

* Move unalias implementation to separate package

* Use MkdirAll to ensure all parent dirs are also created

* Update function name to remove 'version'
  • Loading branch information
ChrisTerBeke committed Mar 7, 2024
1 parent ad25cd8 commit 25b3a23
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 3 deletions.
33 changes: 33 additions & 0 deletions cmd/unalias.go
@@ -0,0 +1,33 @@
package cmd

import (
"github.com/spf13/cobra"

"github.com/tfversion/tfversion/pkg/helpers"
"github.com/tfversion/tfversion/pkg/unalias"
)

const (
unaliasExample = "# Un-alias a Terraform version\n" +
"tfversion unalias default\n" +
"tfversion unalias legacy"
)

var (
unaliasCmd = &cobra.Command{
Use: "unalias",
Short: "Un-alias a Terraform version",
Example: unaliasExample,
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
err := helpers.ErrorWithHelp("tfversion unalias -h")
helpers.ExitWithError("provide an alias name", err)
}
unalias.Unalias(args[0])
},
}
)

func init() {
rootCmd.AddCommand(unaliasCmd)
}
6 changes: 3 additions & 3 deletions pkg/alias/alias.go
Expand Up @@ -24,7 +24,7 @@ func AliasVersion(alias string, version string) {
if err == nil {
err = os.RemoveAll(aliasPath)
if err != nil {
helpers.ExitWithError("error removing symlink", err)
helpers.ExitWithError("removing symlink", err)
}
}

Expand All @@ -42,14 +42,14 @@ func AliasVersion(alias string, version string) {
func GetAliasLocation() string {
user, err := os.UserHomeDir()
if err != nil {
helpers.ExitWithError("error getting user home directory", err)
helpers.ExitWithError("getting user home directory", err)
}

aliasLocation := filepath.Join(user, download.ApplicationDir, download.AliasesDir)
if _, err := os.Stat(aliasLocation); os.IsNotExist(err) {
err := os.MkdirAll(aliasLocation, 0755)
if err != nil {
helpers.ExitWithError("error creating alias directory", err)
helpers.ExitWithError("creating alias directory", err)
}
}

Expand Down
27 changes: 27 additions & 0 deletions pkg/unalias/unalias.go
@@ -0,0 +1,27 @@
package unalias

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

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

// Unalias removes the symlink for the specified alias.
func Unalias(aliasName string) {
aliasLocation := alias.GetAliasLocation()
aliasPath := filepath.Join(aliasLocation, aliasName)
_, err := os.Lstat(aliasPath)
if err != nil {
helpers.ExitWithError("removing symlink", err)
}

err = os.RemoveAll(aliasPath)
if err != nil {
helpers.ExitWithError("removing symlink", err)
}

fmt.Printf("Removed alias %s\n", helpers.ColoredVersion(aliasName))
}

0 comments on commit 25b3a23

Please sign in to comment.