Skip to content

Commit

Permalink
Use os.UserHomeDir() everywhere
Browse files Browse the repository at this point in the history
Signed-off-by: Ahmed Kamal <[email protected]>
  • Loading branch information
kim0 committed Aug 25, 2023
1 parent d7dfd1b commit 395e143
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 80 deletions.
9 changes: 4 additions & 5 deletions lib/download_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"log"
"net/url"
"os"
"os/user"
"path/filepath"
"testing"

Expand All @@ -22,13 +21,13 @@ func TestDownloadFromURL_FileNameMatch(t *testing.T) {
macOS := "_darwin_amd64.zip"

// get current user
usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}

fmt.Printf("Current user: %v \n", usr.HomeDir)
installLocation := filepath.Join(usr.HomeDir, installPath)
fmt.Printf("Current home directory: %v \n", homedir)
installLocation := filepath.Join(homedir, installPath)

// create /.terraform.versions_test/ directory to store code
if _, err := os.Stat(installLocation); os.IsNotExist(err) {
Expand All @@ -44,7 +43,7 @@ func TestDownloadFromURL_FileNameMatch(t *testing.T) {
lowestVersion := "0.11.0"

url := hashiURL + lowestVersion + "/" + installVersion + lowestVersion + macOS
expectedFile := filepath.Join(usr.HomeDir, installPath, installVersion+lowestVersion+macOS)
expectedFile := filepath.Join(homedir, installPath, installVersion+lowestVersion+macOS)
installedFile, errDownload := lib.DownloadFromURL(installLocation, url)

if errDownload != nil {
Expand Down
18 changes: 8 additions & 10 deletions lib/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import (
"os"
"path/filepath"
"strings"

"github.com/mitchellh/go-homedir"
)

// RenameFile : rename file name
Expand Down Expand Up @@ -102,7 +100,7 @@ func Unzip(src string, dest string) ([]string, error) {
return filenames, nil
}

//CreateDirIfNotExist : create directory if directory does not exist
// CreateDirIfNotExist : create directory if directory does not exist
func CreateDirIfNotExist(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
fmt.Printf("Creating directory for terraform binary at: %v\n", dir)
Expand All @@ -114,7 +112,7 @@ func CreateDirIfNotExist(dir string) {
}
}

//WriteLines : writes into file
// WriteLines : writes into file
func WriteLines(lines []string, path string) (err error) {
var (
file *os.File
Expand Down Expand Up @@ -166,7 +164,7 @@ func ReadLines(path string) (lines []string, err error) {
return
}

//IsDirEmpty : check if directory is empty (TODO UNIT TEST)
// IsDirEmpty : check if directory is empty (TODO UNIT TEST)
func IsDirEmpty(name string) bool {

exist := false
Expand All @@ -184,7 +182,7 @@ func IsDirEmpty(name string) bool {
return exist // Either not empty or error, suits both cases
}

//CheckDirHasTGBin : // check binary exist (TODO UNIT TEST)
// CheckDirHasTGBin : // check binary exist (TODO UNIT TEST)
func CheckDirHasTGBin(dir, prefix string) bool {

exist := false
Expand All @@ -204,9 +202,9 @@ func CheckDirHasTGBin(dir, prefix string) bool {
return exist
}

//CheckDirExist : check if directory exist
//dir=path to file
//return bool
// CheckDirExist : check if directory exist
// dir=path to file
// return bool
func CheckDirExist(dir string) bool {
if _, err := os.Stat(dir); os.IsNotExist(err) {
return false
Expand Down Expand Up @@ -239,7 +237,7 @@ func GetCurrentDirectory() string {
// GetHomeDirectory : return the home directory
func GetHomeDirectory() string {

homedir, errHome := homedir.Dir()
homedir, errHome := os.UserHomeDir()
if errHome != nil {
log.Printf("Failed to get home directory %v\n", errHome)
os.Exit(1)
Expand Down
45 changes: 22 additions & 23 deletions lib/files_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"io"
"log"
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
Expand All @@ -26,11 +25,11 @@ func TestRenameFile(t *testing.T) {
installPath := "/.terraform.versions_test/"
version := "0.0.7"

usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}
installLocation := filepath.Join(usr.HomeDir, installPath)
installLocation := filepath.Join(homedir, installPath)

createDirIfNotExist(installLocation)

Expand Down Expand Up @@ -72,11 +71,11 @@ func TestRemoveFiles(t *testing.T) {
installFile := lib.ConvertExecutableExt("terraform")
installPath := "/.terraform.versions_test/"

usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}
installLocation := filepath.Join(usr.HomeDir, installPath)
installLocation := filepath.Join(homedir, installPath)

createDirIfNotExist(installLocation)

Expand Down Expand Up @@ -111,11 +110,11 @@ func TestUnzip(t *testing.T) {

fmt.Println(absPath)

usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}
installLocation := filepath.Join(usr.HomeDir, installPath)
installLocation := filepath.Join(homedir, installPath)

createDirIfNotExist(installLocation)

Expand Down Expand Up @@ -143,11 +142,11 @@ func TestUnzip(t *testing.T) {
func TestCreateDirIfNotExist(t *testing.T) {
installPath := "/.terraform.versions_test/"

usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}
installLocation := filepath.Join(usr.HomeDir, installPath)
installLocation := filepath.Join(homedir, installPath)

cleanUp(installLocation)

Expand All @@ -171,18 +170,18 @@ func TestCreateDirIfNotExist(t *testing.T) {
cleanUp(installLocation)
}

//TestWriteLines : write to file, check readline to verify
// TestWriteLines : write to file, check readline to verify
func TestWriteLines(t *testing.T) {
installPath := "/.terraform.versions_test/"
recentFile := "RECENT"
semverRegex := regexp.MustCompile(`\A\d+(\.\d+){2}(-\w+\d*)?\z`)
//semverRegex := regexp.MustCompile(`\A\d+(\.\d+){2}\z`)

usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}
installLocation := filepath.Join(usr.HomeDir, installPath)
installLocation := filepath.Join(homedir, installPath)

createDirIfNotExist(installLocation)

Expand Down Expand Up @@ -246,11 +245,11 @@ func TestReadLines(t *testing.T) {
recentFile := "RECENT"
semverRegex := regexp.MustCompile(`\A\d+(\.\d+){2}(-\w+\d*)?\z`)

usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}
installLocation := filepath.Join(usr.HomeDir, installPath)
installLocation := filepath.Join(homedir, installPath)

createDirIfNotExist(installLocation)

Expand Down Expand Up @@ -299,11 +298,11 @@ func TestIsDirEmpty(t *testing.T) {

installPath := "/.terraform.versions_test/"

usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}
installLocation := filepath.Join(usr.HomeDir, installPath)
installLocation := filepath.Join(homedir, installPath)

test_dir := current.Format("2006-01-02")
test_dir_path := filepath.Join(installLocation, test_dir)
Expand Down Expand Up @@ -334,11 +333,11 @@ func TestCheckDirHasTFBin(t *testing.T) {
installPath := "/.terraform.versions_test/"
installFilePrefix := "terraform"

usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}
installLocation := filepath.Join(usr.HomeDir, installPath)
installLocation := filepath.Join(homedir, installPath)

createDirIfNotExist(installLocation)

Expand All @@ -363,11 +362,11 @@ func TestPath(t *testing.T) {
installPath := "/.terraform.versions_test"
installFile := lib.ConvertExecutableExt("terraform")

usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}
installLocation := filepath.Join(usr.HomeDir, installPath)
installLocation := filepath.Join(homedir, installPath)

createDirIfNotExist(installLocation)

Expand Down Expand Up @@ -404,7 +403,7 @@ func TestGetFileName(t *testing.T) {

// TestConvertExecutableExt : convert executable binary with extension
func TestConvertExecutableExt(t *testing.T) {
usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}
Expand All @@ -413,8 +412,8 @@ func TestConvertExecutableExt(t *testing.T) {
test_array := []string{
"terraform",
"terraform.exe",
filepath.Join(usr.HomeDir, installPath, "terraform"),
filepath.Join(usr.HomeDir, installPath, "terraform.exe"),
filepath.Join(homedir, installPath, "terraform"),
filepath.Join(homedir, installPath, "terraform.exe"),
}

for _, fpath := range test_array {
Expand Down
37 changes: 18 additions & 19 deletions lib/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"log"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
Expand Down Expand Up @@ -58,12 +57,12 @@ func initialize() {
// will create a directory in the home location if it does not exist
func GetInstallLocation() string {
/* get current user */
usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}

userCommon := usr.HomeDir
userCommon := homedir

/* set installation location */
installLocation = filepath.Join(userCommon, installPath)
Expand All @@ -75,7 +74,7 @@ func GetInstallLocation() string {

}

//Install : Install the provided version in the argument
// Install : Install the provided version in the argument
func Install(tfversion string, binPath string, mirrorURL string) {

// if !ValidVersionFormat(tfversion) {
Expand Down Expand Up @@ -252,15 +251,15 @@ func GetRecentVersions() ([]string, error) {
return nil, nil
}

//CreateRecentFile : create a recent file
// CreateRecentFile : create a recent file
func CreateRecentFile(requestedVersion string) {

installLocation = GetInstallLocation() //get installation location - this is where we will put our terraform binary file

WriteLines([]string{requestedVersion}, filepath.Join(installLocation, recentFile))
}

//ConvertExecutableExt : convert excutable with local OS extension
// ConvertExecutableExt : convert excutable with local OS extension
func ConvertExecutableExt(fpath string) string {
switch runtime.GOOS {
case "windows":
Expand All @@ -273,38 +272,38 @@ func ConvertExecutableExt(fpath string) string {
}
}

//InstallableBinLocation : Checks if terraform is installable in the location provided by the user.
//If not, create $HOME/bin. Ask users to add $HOME/bin to $PATH and return $HOME/bin as install location
// InstallableBinLocation : Checks if terraform is installable in the location provided by the user.
// If not, create $HOME/bin. Ask users to add $HOME/bin to $PATH and return $HOME/bin as install location
func InstallableBinLocation(userBinPath string) string {

usr, errCurr := user.Current()
homedir, errCurr := os.UserHomeDir()
if errCurr != nil {
log.Fatal(errCurr)
}

binDir := Path(userBinPath) //get path directory from binary path
binPathExist := CheckDirExist(binDir) //the default is /usr/local/bin but users can provide custom bin locations

if binPathExist == true { //if bin path exist - check if we can write to to it
if binPathExist { //if bin path exist - check if we can write to to it

binPathWritable := false //assume bin path is not writable
if runtime.GOOS != "windows" {
binPathWritable = CheckDirWritable(binDir) //check if is writable on ( only works on LINUX)
}

// IF: "/usr/local/bin" or `custom bin path` provided by user is non-writable, (binPathWritable == false), we will attempt to install terraform at the ~/bin location. See ELSE
if binPathWritable == false {
if !binPathWritable {

homeBinExist := CheckDirExist(filepath.Join(usr.HomeDir, "bin")) //check to see if ~/bin exist
if homeBinExist { //if ~/bin exist, install at ~/bin/terraform
fmt.Printf("Installing terraform at %s\n", filepath.Join(usr.HomeDir, "bin"))
return filepath.Join(usr.HomeDir, "bin", "terraform")
homeBinExist := CheckDirExist(filepath.Join(homedir, "bin")) //check to see if ~/bin exist
if homeBinExist { //if ~/bin exist, install at ~/bin/terraform
fmt.Printf("Installing terraform at %s\n", filepath.Join(homedir, "bin"))
return filepath.Join(homedir, "bin", "terraform")
} else { //if ~/bin directory does not exist, create ~/bin for terraform installation
fmt.Printf("Unable to write to: %s\n", userBinPath)
fmt.Printf("Creating bin directory at: %s\n", filepath.Join(usr.HomeDir, "bin"))
CreateDirIfNotExist(filepath.Join(usr.HomeDir, "bin")) //create ~/bin
fmt.Printf("RUN `export PATH=$PATH:%s` to append bin to $PATH\n", filepath.Join(usr.HomeDir, "bin"))
return filepath.Join(usr.HomeDir, "bin", "terraform")
fmt.Printf("Creating bin directory at: %s\n", filepath.Join(homedir, "bin"))
CreateDirIfNotExist(filepath.Join(homedir, "bin")) //create ~/bin
fmt.Printf("RUN `export PATH=$PATH:%s` to append bin to $PATH\n", filepath.Join(homedir, "bin"))
return filepath.Join(homedir, "bin", "terraform")
}
} else { // ELSE: the "/usr/local/bin" or custom path provided by user is writable, we will return installable location
return filepath.Join(userBinPath)
Expand Down
9 changes: 4 additions & 5 deletions lib/install_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,14 @@ func TestInstall(t *testing.T) {

t.Run("User should exist",
func(t *testing.T) {
usr, errCurr := user.Current()
_, errCurr := user.Current()
if errCurr != nil {
t.Errorf("Unable to get user %v [unexpected]", errCurr)
}

if usr != nil {
t.Logf("Current user exist: %v [expected]\n", usr.HomeDir)
} else {
t.Error("Unable to get user [unexpected]")
_, errCurr = os.UserHomeDir()
if errCurr != nil {
t.Errorf("Unable to get user home directory: %v [unexpected]", errCurr)
}
},
)
Expand Down

0 comments on commit 395e143

Please sign in to comment.