diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..3646366 --- /dev/null +++ b/Makefile @@ -0,0 +1,38 @@ +EXE := gswap +PKG := github.com/warrensbox/terragrunt-switcher +VER := $(shell git ls-remote --tags git://github.com/warrensbox/terragrunt-switcher | awk '{print $$2}'| awk -F"/" '{print $$3}' | sort -n -t. -k1,1 -k2,2 -k3,3 | tail -n 1) +PATH := build:$(PATH) +GOOS ?= $(shell go env GOOS) +GOARCH ?= $(shell go env GOARCH) + +$(EXE): Gopkg.lock *.go lib/*.go + go build -v -ldflags "-X main.version=$(VER)" -o $@ $(PKG) + +Gopkg.lock: Gopkg.toml + dep ensure + +.PHONY: release +release: $(EXE) darwin linux + +.PHONY: darwin linux +darwin linux: + GOOS=$@ go build -ldflags "-X main.version=$(VER)" -o $(EXE)-$(VER)-$@-$(GOARCH) $(PKG) + +.PHONY: clean +clean: + rm -f $(EXE) $(EXE)-*-*-* + +.PHONY: test +test: $(EXE) + mv $(EXE) build + go test -v ./... + + +.PHONEY: dep +dep: + dep ensure + + +test-local: + go get -v -t -d ./... + go test -v ./... diff --git a/build b/build new file mode 100755 index 0000000..041186a Binary files /dev/null and b/build differ diff --git a/lib/command_test.go b/lib/command_test.go new file mode 100644 index 0000000..7a582e9 --- /dev/null +++ b/lib/command_test.go @@ -0,0 +1,56 @@ +package lib_test + +import ( + "reflect" + "testing" + + "github.com/warrensbox/terraform-switcher/lib" +) + +// TestNewCommand : pass value and check if returned value is a pointer +func TestNewCommand(t *testing.T) { + + testCmd := "terraform" + cmd := lib.NewCommand(testCmd) + + if reflect.ValueOf(cmd).Kind() == reflect.Ptr { + t.Logf("Value returned is a pointer %v [expected]", cmd) + } else { + t.Errorf("Value returned is not a pointer %v [expected", cmd) + } +} + +// TestPathList : check if bin path exist +func TestPathList(t *testing.T) { + + testCmd := "" + cmd := lib.NewCommand(testCmd) + listBin := cmd.PathList() + + if listBin == nil { + t.Error("No bin path found [unexpected]") + } else { + t.Logf("Found bin path [expected]") + } +} + +type Command struct { + name string +} + +// TestFind : check common "cd" command exist +// This is assuming that Windows and linux has the "cd" command +func TestFind(t *testing.T) { + + testCmd := "cd" + cmd := lib.NewCommand(testCmd) + + next := cmd.Find() + for path := next(); len(path) > 0; path = next() { + if path != "" { + t.Logf("Found installation path: %v [expected]\n", path) + } else { + t.Errorf("Unable to find '%v' command in this operating system [unexpected]", testCmd) + } + } +} diff --git a/lib/common_test.go b/lib/common_test.go new file mode 100644 index 0000000..8813107 --- /dev/null +++ b/lib/common_test.go @@ -0,0 +1,81 @@ +package lib_test + +import ( + "fmt" + "log" + "os" + "path/filepath" +) + +func checkFileExist(file string) bool { + _, err := os.Stat(file) + if err != nil { + return false + } + return true +} + +func createFile(path string) { + // detect if file exists + var _, err = os.Stat(path) + + // create file if not exists + if os.IsNotExist(err) { + file, err := os.Create(path) + if err != nil { + fmt.Printf("%v", err) + return + } + defer file.Close() + } + + fmt.Println("==> done creating file", path) +} + +func createDirIfNotExist(dir string) { + if _, err := os.Stat(dir); os.IsNotExist(err) { + log.Printf("Creating directory for teraform: %v", dir) + err = os.MkdirAll(dir, 0755) + if err != nil { + fmt.Printf("Unable to create directory for teraform: %v", dir) + panic(err) + } + } +} + +func cleanUp(path string) { + removeContents(path) + removeFiles(path) +} + +func removeFiles(src string) { + files, err := filepath.Glob(src) + if err != nil { + + panic(err) + } + for _, f := range files { + if err := os.Remove(f); err != nil { + panic(err) + } + } +} + +func removeContents(dir string) error { + d, err := os.Open(dir) + if err != nil { + return err + } + defer d.Close() + names, err := d.Readdirnames(-1) + if err != nil { + return err + } + for _, name := range names { + err = os.RemoveAll(filepath.Join(dir, name)) + if err != nil { + return err + } + } + return nil +} diff --git a/lib/download.go b/lib/download.go index d7afa8f..600522f 100644 --- a/lib/download.go +++ b/lib/download.go @@ -10,11 +10,12 @@ import ( // DownloadFromURL : Downloads the binary from the source url func DownloadFromURL(installLocation string, url string) (string, error) { + tokens := strings.Split(url, "/") fileName := tokens[len(tokens)-1] fmt.Println("Downloading", url, "to", fileName) fmt.Println("Downloading ...") - // TODO: check file existence first with io.IsExist + output, err := os.Create(installLocation + fileName) if err != nil { fmt.Println("Error while creating", installLocation+fileName, "-", err) @@ -29,10 +30,10 @@ func DownloadFromURL(installLocation string, url string) (string, error) { } defer response.Body.Close() - n, err := io.Copy(output, response.Body) - if err != nil { - fmt.Println("Error while downloading", url, "-", err) - return "", err + n, errCopy := io.Copy(output, response.Body) + if errCopy != nil { + fmt.Println("Error while downloading", url, "-", errCopy) + return "", errCopy } fmt.Println(n, "bytes downloaded.") diff --git a/lib/download_test.go b/lib/download_test.go new file mode 100644 index 0000000..a5faa68 --- /dev/null +++ b/lib/download_test.go @@ -0,0 +1,156 @@ +package lib_test + +import ( + "fmt" + "log" + "net/url" + "os" + "os/user" + "runtime" + "testing" + + lib "github.com/warrensbox/terragrunt-switcher/lib" +) + +// TestDownloadFromURL_FileNameMatch : Check expected filename exist when downloaded +func TestDownloadFromURL_FileNameMatch(t *testing.T) { + + gruntURL := "https://github.com/gruntwork-io/terragrunt/releases/download/" + installVersion := "terragrunt_" + installPath := "/.terragrunt.versions_test/" + goarch := runtime.GOARCH + goos := runtime.GOOS + + // get current user + usr, errCurr := user.Current() + if errCurr != nil { + log.Fatal(errCurr) + } + + fmt.Printf("Current user: %v \n", usr.HomeDir) + installLocation := usr.HomeDir + installPath + + // create /.terragrunt.versions_test/ directory to store code + if _, err := os.Stat(installLocation); os.IsNotExist(err) { + log.Printf("Creating directory for terragrunt: %v", installLocation) + err = os.MkdirAll(installLocation, 0755) + if err != nil { + fmt.Printf("Unable to create directory for terragrunt: %v", installLocation) + panic(err) + } + } + + /* test download lowest terragrunt version */ + lowestVersion := "0.13.9" + + url := gruntURL + "v" + lowestVersion + "/" + installVersion + goos + "_" + goarch + expectedFile := usr.HomeDir + installPath + installVersion + goos + "_" + goarch + installedFile, _ := lib.DownloadFromURL(installLocation, url) + + if installedFile == expectedFile { + t.Logf("Expected file %v", expectedFile) + t.Logf("Downloaded file %v", installedFile) + t.Log("Download file matches expected file") + } else { + t.Logf("Expected file %v", expectedFile) + t.Logf("Downloaded file %v", installedFile) + t.Error("Download file mismatches expected file") + } + + /* test download latest terragrunt version */ + latestVersion := "0.14.11" + + url = gruntURL + "v" + latestVersion + "/" + installVersion + goos + "_" + goarch + expectedFile = usr.HomeDir + installPath + installVersion + goos + "_" + goarch + installedFile, _ = lib.DownloadFromURL(installLocation, url) + + if installedFile == expectedFile { + t.Logf("Expected file name %v", expectedFile) + t.Logf("Downloaded file name %v", installedFile) + t.Log("Download file name matches expected file") + } else { + t.Logf("Expected file name %v", expectedFile) + t.Logf("Downloaded file name %v", installedFile) + t.Error("Downoad file name mismatches expected file") + } + + cleanUp(installLocation) +} + +// TestDownloadFromURL_FileExist : Check expected file exist when downloaded +func TestDownloadFromURL_FileExist(t *testing.T) { + + gruntURL := "https://github.com/gruntwork-io/terragrunt/releases/download/" + installVersion := "terragrunt_" + installPath := "/.terragrunt.versions_test/" + goarch := runtime.GOARCH + goos := runtime.GOOS + + // get current user + usr, errCurr := user.Current() + if errCurr != nil { + log.Fatal(errCurr) + } + + fmt.Printf("Current user: %v \n", usr.HomeDir) + installLocation := usr.HomeDir + installPath + + // create /.terragrunt.versions_test/ directory to store code + if _, err := os.Stat(installLocation); os.IsNotExist(err) { + log.Printf("Creating directory for terragrunt: %v", installLocation) + err = os.MkdirAll(installLocation, 0755) + if err != nil { + fmt.Printf("Unable to create directory for terragrunt: %v", installLocation) + panic(err) + } + } + + /* test download lowest terragrunt version */ + lowestVersion := "0.13.9" + + url := gruntURL + "v" + lowestVersion + "/" + installVersion + goos + "_" + goarch + expectedFile := usr.HomeDir + installPath + installVersion + goos + "_" + goarch + installedFile, _ := lib.DownloadFromURL(installLocation, url) + + if checkFileExist(expectedFile) { + t.Logf("Expected file %v", expectedFile) + t.Logf("Downloaded file %v", installedFile) + t.Log("Download file matches expected file") + } else { + t.Logf("Expected file %v", expectedFile) + t.Logf("Downloaded file %v", installedFile) + t.Error("Downoad file mismatches expected file") + } + + /* test download latest terragrunt version */ + latestVersion := "0.14.11" + + url = gruntURL + "v" + latestVersion + "/" + installVersion + goos + "_" + goarch + expectedFile = usr.HomeDir + installPath + installVersion + goos + "_" + goarch + installedFile, _ = lib.DownloadFromURL(installLocation, url) + + if checkFileExist(expectedFile) { + t.Logf("Expected file %v", expectedFile) + t.Logf("Downloaded file %v", installedFile) + t.Log("Download file matches expected file") + } else { + t.Logf("Expected file %v", expectedFile) + t.Logf("Downloaded file %v", installedFile) + t.Error("Downoad file mismatches expected file") + } + + cleanUp(installLocation) +} + +func TestDownloadFromURL_Valid(t *testing.T) { + + gruntURL := "https://github.com/gruntwork-io/terragrunt/releases/download/" + + url, err := url.ParseRequestURI(gruntURL) + if err != nil { + t.Errorf("Valid URL provided: %v", err) + t.Errorf("Invalid URL %v", err) + } else { + t.Logf("Valid URL from %v", url) + } +} diff --git a/lib/files.go b/lib/files.go index 449ee2f..0d16248 100644 --- a/lib/files.go +++ b/lib/files.go @@ -1,11 +1,11 @@ package lib import ( - "archive/zip" "bufio" "bytes" "fmt" "io" + "io/ioutil" "log" "os" "path/filepath" @@ -44,61 +44,6 @@ func CheckFileExist(file string) bool { return true } -// Unzip will decompress a zip archive, moving all files and folders -// within the zip file (parameter 1) to an output directory (parameter 2). -func Unzip(src string, dest string) ([]string, error) { - - var filenames []string - - r, err := zip.OpenReader(src) - if err != nil { - return filenames, err - } - defer r.Close() - - for _, f := range r.File { - - rc, err := f.Open() - if err != nil { - return filenames, err - } - defer rc.Close() - - // Store filename/path for returning and using later on - fpath := filepath.Join(dest, f.Name) - filenames = append(filenames, fpath) - - if f.FileInfo().IsDir() { - - // Make Folder - os.MkdirAll(fpath, os.ModePerm) - - } else { - - // Make File - if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil { - return filenames, err - } - - outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) - if err != nil { - return filenames, err - } - - _, err = io.Copy(outFile, rc) - - // Close the file without defer to close before next iteration of loop - outFile.Close() - - if err != nil { - return filenames, err - } - - } - } - return filenames, nil -} - //CreateDirIfNotExist : create directory if directory does not exist func CreateDirIfNotExist(dir string) { if _, err := os.Stat(dir); os.IsNotExist(err) { @@ -162,3 +107,41 @@ func ReadLines(path string) (lines []string, err error) { } return } + +//IsDirEmpty : check if directory is empty (TODO UNIT TEST) +func IsDirEmpty(name string) bool { + + exist := false + + f, err := os.Open(name) + if err != nil { + log.Fatal(err) + } + defer f.Close() + + _, err = f.Readdirnames(1) // Or f.Readdir(1) + if err == io.EOF { + exist = true + } + return exist // Either not empty or error, suits both cases +} + +//CheckDirHasTGBin : // check binary exist (TODO UNIT TEST) +func CheckDirHasTGBin(dir, prefix string) bool { + + exist := false + + files, err := ioutil.ReadDir(dir) + if err != nil { + log.Fatal(err) + //return exist, err + } + res := []string{} + for _, f := range files { + if !f.IsDir() && strings.HasPrefix(f.Name(), prefix) { + res = append(res, filepath.Join(dir, f.Name())) + exist = true + } + } + return exist +} diff --git a/lib/install.go b/lib/install.go index 758660f..c4b8421 100644 --- a/lib/install.go +++ b/lib/install.go @@ -10,13 +10,11 @@ import ( ) const ( - hashiURL = "https://github.com/gruntwork-io/terragrunt/releases/download/" + gruntURL = "https://github.com/gruntwork-io/terragrunt/releases/download/" installFile = "terragrunt" installVersion = "terragrunt_" binLocation = "/usr/local/bin/terragrunt" installPath = "/.terragrunt.versions/" - macOS = "_darwin_amd64.zip" - linux = "_darwin_amd64.zip" recentFile = "RECENT" ) @@ -35,22 +33,21 @@ func init() { /* set installation location */ installLocation = usr.HomeDir + installPath - /* set default binary path for terraform */ + /* set default binary path for terragrunt */ installedBinPath = binLocation - /* find terraform binary location if terraform is already installed*/ + /* find terragrunt binary location if terragrunt is already installed*/ cmd := NewCommand("terragrunt") next := cmd.Find() - //existed := false - /* overrride installation default binary path if terraform is already installed */ + /* overrride installation default binary path if terragrunt is already installed */ /* find the last bin path */ for path := next(); len(path) > 0; path = next() { fmt.Printf("Found installation path: %v \n", path) installedBinPath = path } - fmt.Printf("Terraform binary path: %v \n", installedBinPath) + fmt.Printf("Terragrunt binary path: %v \n", installedBinPath) /* Create local installation directory if it does not exist */ CreateDirIfNotExist(installLocation) @@ -58,76 +55,60 @@ func init() { } //Install : Install the provided version in the argument -func Install(tfversion string) { +func Install(tgversion string) { goarch := runtime.GOARCH goos := runtime.GOOS /* check if selected version already downloaded */ - fileExist := CheckFileExist(installLocation + installVersion + tfversion) + fileExist := CheckFileExist(installLocation + installVersion + tgversion) + + //fmt.Println(fileExist) /* if selected version already exist, */ if fileExist { + /* remove current symlink if exist*/ - exist := CheckFileExist(installedBinPath) + symlinkExist := CheckSymlink(installedBinPath) - if !exist { - fmt.Println("Symlink does not exist") - } else { + if symlinkExist { + fmt.Println("Reset symlink") RemoveSymlink(installedBinPath) } - /* set symlink to desired version */ - CreateSymlink(installLocation+installVersion+tfversion, installedBinPath) - fmt.Printf("Swicthed terraform to version %q \n", tfversion) - os.Exit(0) + CreateSymlink(installLocation+installVersion+tgversion, installedBinPath) + fmt.Printf("Switched terragrunt to version %q \n", tgversion) + return } - /* if selected version already exist, */ - /* proceed to download it from the hashicorp release page */ - - //https: //github.com/gruntwork-io/terragrunt/releases/download/v0.14.11/terragrunt_darwin_386 - - url := hashiURL + "v" + tfversion + "/" + "terragrunt" + "_" + goos + "_" + goarch - zipFile, _ := DownloadFromURL(installLocation, url) - - fmt.Printf("Downloaded zipFile: %v \n", zipFile) - - /* unzip the downloaded zipfile */ - // files, errUnzip := Unzip(zipFile, installLocation) - // if errUnzip != nil { - // fmt.Println("Unable to unzip downloaded zip file") - // log.Fatal(errUnzip) - // os.Exit(1) - // } + /* remove current symlink if exist*/ + symlinkExist := CheckSymlink(installedBinPath) - //fmt.Println("Unzipped: " + strings.Join(files, "\n")) + if symlinkExist { + fmt.Println("Reset symlink") + RemoveSymlink(installedBinPath) + } - /* rename unzipped file to terraform version name - terraform_x.x.x */ - RenameFile(installLocation+installFile+"_"+goos+"_"+goarch, installLocation+installVersion+tfversion) + /* if selected version already exist, */ + /* proceed to download it from the hashicorp release page */ - /* remove zipped file to clear clutter */ - RemoveFiles(installLocation + installVersion + "_" + goos + "_" + goarch) + url := gruntURL + "v" + tgversion + "/" + "terragrunt" + "_" + goos + "_" + goarch + file, _ := DownloadFromURL(installLocation, url) - /* remove current symlink if exist*/ - exist := CheckFileExist(installedBinPath) + fmt.Printf("Downloaded File: %v \n", file) - if !exist { - fmt.Println("Symlink does not exist") - } else { - fmt.Println("Symlink exist") - RemoveSymlink(installedBinPath) - } + /* rename file to terragrunt version name - terragrunt_x.x.x */ + RenameFile(installLocation+installFile+"_"+goos+"_"+goarch, installLocation+installVersion+tgversion) - err := os.Chmod(installLocation+installVersion+tfversion, 0755) + err := os.Chmod(installLocation+installVersion+tgversion, 0755) if err != nil { log.Println(err) } /* set symlink to desired version */ - CreateSymlink(installLocation+installVersion+tfversion, installedBinPath) - fmt.Printf("Swicthed terraform to version %q \n", tfversion) - os.Exit(0) + CreateSymlink(installLocation+installVersion+tgversion, installedBinPath) + fmt.Printf("Switched terragrunt to version %q \n", tgversion) + return } // AddRecent : add to recent file diff --git a/lib/list_versions.go b/lib/list_versions.go index 0f42ab4..011a3a0 100644 --- a/lib/list_versions.go +++ b/lib/list_versions.go @@ -11,6 +11,7 @@ import ( "time" ) +//Repo : properties type Repo struct { URL string `json:"url"` AssetsURL string `json:"assets_url"` @@ -32,6 +33,7 @@ type Repo struct { Assets []Assets `json:"assets"` } +//Author : git owner properties type Author struct { Login string `json:"login"` ID int `json:"id"` @@ -53,6 +55,7 @@ type Author struct { SiteAdmin bool `json:"site_admin"` } +//Author : author properties type Assets struct { URL string `json:"url"` ID int `json:"id"` @@ -69,6 +72,7 @@ type Assets struct { Uploader Uploader `json:"uploader"` } +//Uploader : repo uploader properties type Uploader struct { Login string `json:"login"` ID int `json:"id"` @@ -90,89 +94,16 @@ type Uploader struct { SiteAdmin bool `json:"site_admin"` } -type AutoGenerated []struct { - URL string `json:"url"` - AssetsURL string `json:"assets_url"` - UploadURL string `json:"upload_url"` - HTMLURL string `json:"html_url"` - ID int `json:"id"` - NodeID string `json:"node_id"` - TagName string `json:"tag_name"` - TargetCommitish string `json:"target_commitish"` - Name string `json:"name"` - Draft bool `json:"draft"` - Author struct { - Login string `json:"login"` - ID int `json:"id"` - NodeID string `json:"node_id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"author"` - Prerelease bool `json:"prerelease"` - CreatedAt time.Time `json:"created_at"` - PublishedAt time.Time `json:"published_at"` - Assets []struct { - URL string `json:"url"` - ID int `json:"id"` - NodeID string `json:"node_id"` - Name string `json:"name"` - Label string `json:"label"` - Uploader struct { - Login string `json:"login"` - ID int `json:"id"` - NodeID string `json:"node_id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"uploader"` - ContentType string `json:"content_type"` - State string `json:"state"` - Size int `json:"size"` - DownloadCount int `json:"download_count"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - BrowserDownloadURL string `json:"browser_download_url"` - } `json:"assets"` - TarballURL string `json:"tarball_url"` - ZipballURL string `json:"zipball_url"` - Body string `json:"body"` -} - type tgVersionList struct { tglist []string } -//GetTFList : Get the list of available terraform version given the hashicorp url +//GetTGList : Get the list of available terraform version given the hashicorp url func GetTGList(gruntURL string) ([]string, error) { url := "https://api.github.com/repos/gruntwork-io/terragrunt/releases" - tgswap := http.Client{ + gswitch := http.Client{ Timeout: time.Second * 2, // Maximum of 2 secs } @@ -180,11 +111,10 @@ func GetTGList(gruntURL string) ([]string, error) { if err != nil { log.Fatal(err) } - //defer req.Body.Close() req.Header.Set("User-Agent", "terragrunt-switcher") - res, getErr := tgswap.Do(req) + res, getErr := gswitch.Do(req) if getErr != nil { log.Fatal(getErr) } @@ -194,15 +124,12 @@ func GetTGList(gruntURL string) ([]string, error) { log.Fatal(readErr) } - //people1 := people{} var repo []Repo jsonErr := json.Unmarshal(body, &repo) if jsonErr != nil { log.Fatal(jsonErr) } - //fmt.Println(repo) - var tgVersionList tgVersionList for _, num := range repo { @@ -212,27 +139,11 @@ func GetTGList(gruntURL string) ([]string, error) { trimstr := strings.Trim(num.Name, "v") tgVersionList.tglist = append(tgVersionList.tglist, trimstr) } - - //fmt.Println(num.Name) } } - // - - // for i := range result { - // //getting versions from body; should return match /X.X.X/ - // semverRegex := regexp.MustCompile(`\Av\d+(\.\d+){2}\z`) - // if r.MatchString(result[i]) { - // str := r.FindString(result[i]) - // trimstr := strings.Trim(str, "/") //remove "/" from /X.X.X/ - // tfVersionList.tflist = append(tfVersionList.tflist, trimstr) - // } - // } - - // fmt.Println(tgVersionList.tglist) return tgVersionList.tglist, nil - } //VersionExist : check if requested version exist diff --git a/lib/symlink.go b/lib/symlink.go index efe545f..1ab84f0 100644 --- a/lib/symlink.go +++ b/lib/symlink.go @@ -1,6 +1,7 @@ package lib import ( + "fmt" "log" "os" ) @@ -8,9 +9,12 @@ import ( //CreateSymlink : create symlink func CreateSymlink(cwd string, dir string) { + fmt.Println("CREATe") + err := os.Symlink(cwd, dir) if err != nil { - log.Fatal("Unable to create symlink. You must have SUDO privileges") + fmt.Println(err) + log.Fatalf("Unable to create symlink. You must have SUDO privileges %v \n", err) panic(err) } } @@ -20,13 +24,36 @@ func RemoveSymlink(symlinkPath string) { _, err := os.Lstat(symlinkPath) if err != nil { + fmt.Println(err) log.Fatalf("Unable to find symlink. You must have SUDO privileges - %v \n", err) panic(err) } else { errRemove := os.Remove(symlinkPath) if errRemove != nil { - log.Fatalf("Unable to remove symlink. You must have SUDO privileges - %v \n", err) + fmt.Println(errRemove) + log.Fatalf("Unable to remove symlink. You must have SUDO privileges - %v \n", errRemove) panic(errRemove) } } } + +// CheckSymlink : check file is symlink +func CheckSymlink(symlinkPath string) bool { + + //symlink := false + //fmt.Println("Checking symlink") + + fi, err := os.Lstat(symlinkPath) + if err != nil { + fmt.Println(err) + // symlink = false + return false + } + + if fi.Mode()&os.ModeSymlink != 0 { + //symlink = true + return true + } + + return false +} diff --git a/main.go b/main.go index 572b42e..ce865a0 100644 --- a/main.go +++ b/main.go @@ -7,14 +7,12 @@ package main /*** OPERATION WORKFLOW ***/ /* -* 1- Create /usr/local/terraform directory if does not exist -* 2- Download zip file from url to /usr/local/terraform -* 3- Unzip the file to /usr/local/terraform -* 4- Rename the file from `terraform` to `terraform_version` -* 5- Remove the downloaded zip file -* 6- Read the existing symlink for terraform (Check if it's a homebrew symlink) -* 7- Remove that symlink (Check if it's a homebrew symlink) -* 8- Create new symlink to binary `terraform_version` +* 1- Create /usr/local/terragrunt directory if does not exist +* 2- Download binary file from url to /usr/local/terragrunt +* 3- Rename the file from `terragrunt` to `terragrunt_version` +* 4- Read the existing symlink for terragrunt (Check if it's a homebrew symlink) +* 6- Remove that symlink (Check if it's a homebrew symlink) +* 7- Create new symlink to binary `terragrunt_version` */ import ( @@ -28,10 +26,10 @@ import ( ) const ( - hashiURL = "https://api.github.com/repos/gruntwork-io/terragrunt/releases" + terragruntURL = "https://api.github.com/repos/gruntwork-io/terragrunt/releases" ) -var version = "0.3.0\n" +var version = "0.1.0\n" func main() { @@ -40,28 +38,28 @@ func main() { if len(args) == 0 { - tflist, _ := lib.GetTGList(hashiURL) + tglist, _ := lib.GetTGList(terragruntURL) recentVersions, _ := lib.GetRecentVersions() //get recent versions from RECENT file - tflist = append(recentVersions, tflist...) //append recent versions to the top of the list - tflist = lib.RemoveDuplicateVersions(tflist) //remove duplicate version + tglist = append(recentVersions, tglist...) //append recent versions to the top of the list + tglist = lib.RemoveDuplicateVersions(tglist) //remove duplicate version - /* prompt user to select version of terraform */ + /* prompt user to select version of terragrunt */ prompt := promptui.Select{ - Label: "Select Terraform version", - Items: tflist, + Label: "Select terragrunt version", + Items: tglist, } - _, tfversion, errPrompt := prompt.Run() + _, tgversion, errPrompt := prompt.Run() if errPrompt != nil { log.Printf("Prompt failed %v\n", errPrompt) os.Exit(1) } - fmt.Printf("Terraform version %q selected\n", tfversion) - lib.AddRecent(tfversion) //add to recent file for faster lookup - lib.Install(tfversion) - + fmt.Printf("Terragrunt version %q selected\n", tgversion) + lib.Install(tgversion) + lib.AddRecent(tgversion) //add to recent file for faster lookup (cache) + os.Exit(0) } else { usageMessage() } @@ -71,5 +69,5 @@ func main() { func usageMessage() { fmt.Print("\n\n") getopt.PrintUsage(os.Stderr) - fmt.Println("Supply the terraform version as an argument, or choose from a menu") + fmt.Println("Supply the terragrunt version as an argument, or choose from a menu") } diff --git a/terragrunt_darwin_386 b/terragrunt_darwin_386 deleted file mode 100644 index 5e4c135..0000000 Binary files a/terragrunt_darwin_386 and /dev/null differ diff --git a/vendor/github.com/warrensbox/terraform-switcher/lib/install.go b/vendor/github.com/warrensbox/terraform-switcher/lib/install.go index 22f8d1e..131beef 100644 --- a/vendor/github.com/warrensbox/terraform-switcher/lib/install.go +++ b/vendor/github.com/warrensbox/terraform-switcher/lib/install.go @@ -113,7 +113,7 @@ func Install(tfversion string) { if !exist { fmt.Println("Symlink does not exist") } else { - fmt.Println("Symlink exist") + //fmt.Println("Symlink exist") RemoveSymlink(installedBinPath) }