Skip to content

Commit

Permalink
Merge pull request #350 from MatrixCrawler/logging-refactoring
Browse files Browse the repository at this point in the history
Logging refactoring
  • Loading branch information
MatrixCrawler authored Apr 5, 2024
2 parents 4941e9a + 2bb4acb commit fa36c17
Show file tree
Hide file tree
Showing 17 changed files with 213 additions and 215 deletions.
10 changes: 9 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/warrensbox/terraform-switcher
go 1.22

require (
github.com/gookit/slog v0.5.5
github.com/hashicorp/go-version v1.6.0
github.com/hashicorp/hcl2 v0.0.0-20191002203319-fb75b3253c80
github.com/hashicorp/terraform-config-inspect v0.0.0-20231204233900-a34142ec2a72
Expand All @@ -19,6 +20,9 @@ require (
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/gookit/color v1.5.4 // indirect
github.com/gookit/goutil v0.6.15 // indirect
github.com/gookit/gsr v0.1.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hashicorp/hcl/v2 v2.0.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
Expand All @@ -31,11 +35,15 @@ require (
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/testify v1.9.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/zclconf/go-cty v1.1.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect
golang.org/x/sync v0.5.0 // indirect
golang.org/x/text v0.14.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
23 changes: 20 additions & 3 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
github.com/gookit/goutil v0.6.15 h1:mMQ0ElojNZoyPD0eVROk5QXJPh2uKR4g06slgPDF5Jo=
github.com/gookit/goutil v0.6.15/go.mod h1:qdKdYEHQdEtyH+4fNdQNZfJHhI0jUZzHxQVAV3DaMDY=
github.com/gookit/gsr v0.1.0 h1:0gadWaYGU4phMs0bma38t+Do5OZowRMEVlHv31p0Zig=
github.com/gookit/gsr v0.1.0/go.mod h1:7wv4Y4WCnil8+DlDYHBjidzrEzfHhXEoFjEA0pPPWpI=
github.com/gookit/slog v0.5.5 h1:XoyK3NilKzuC/umvnqTQDHTOnpC8R6pvlr/ht9PyfgU=
github.com/gookit/slog v0.5.5/go.mod h1:RfIwzoaQ8wZbKdcqG7+3EzbkMqcp2TUn3mcaSZAw2EQ=
github.com/hashicorp/errwrap v0.0.0-20180715044906-d6c0cd880357/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v0.0.0-20180717150148-3d5d8f294aa0/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I=
github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek=
Expand Down Expand Up @@ -98,11 +106,16 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/zclconf/go-cty v1.0.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s=
github.com/zclconf/go-cty v1.1.0 h1:uJwc9HiBOCpoKIObTQaLR+tsEXx1HBHnOsOOpcdhZgw=
github.com/zclconf/go-cty v1.1.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s=
Expand All @@ -112,21 +125,25 @@ go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190502183928-7f726cade0ab/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190502175342-a43fa875dd82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4=
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
Expand Down
13 changes: 5 additions & 8 deletions lib/common_test.go → lib/common.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package lib_test
package lib

import (
"fmt"
"log"
"os"
"path/filepath"
)
Expand All @@ -23,22 +21,21 @@ func createFile(path string) {
if os.IsNotExist(err) {
file, err := os.Create(path)
if err != nil {
fmt.Printf("%v", err)
logger.Error(err)
return
}
defer file.Close()
}

fmt.Println("==> done creating file", path)
logger.Infof("==> done creating %q file", path)
}

func createDirIfNotExist(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
log.Printf("Creating directory for terraform: %v", dir)
logger.Infof("Creating directory for terraform: %v", dir)
err = os.MkdirAll(dir, 0755)
if err != nil {
fmt.Printf("Unable to create directory for terraform: %v", dir)
panic(err)
logger.Panic("Unable to create %q directory for terraform: %v", dir, err)
}
}
}
Expand Down
3 changes: 1 addition & 2 deletions lib/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package lib

import (
"github.com/mitchellh/go-homedir"
"log"
"runtime"
)

Expand All @@ -12,7 +11,7 @@ func GetDefaultBin() string {
if runtime.GOOS == "windows" {
home, err := homedir.Dir()
if err != nil {
log.Fatalf("Could not detect home directory.")
logger.Fatal("Could not detect home directory.")
}
defaultBin = home + "/bin/terraform.exe"
}
Expand Down
7 changes: 3 additions & 4 deletions lib/dir_perm_windows.go
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
package lib

import (
"fmt"
"os"
)

func CheckDirWritable(path string) bool {

info, err := os.Stat(path)
if err != nil {
fmt.Println("Path doesn't exist")
logger.Errorf("Path doesn't exist: %q", path)
return false
}

err = nil
if !info.IsDir() {
fmt.Println("Path isn't a directory")
logger.Errorf("Path isn't a directory: %q", path)
return false
}

// Check if the user bit is enabled in file permission
if info.Mode().Perm()&(1<<(uint(7))) == 0 {
fmt.Println("Write permission bit is not set on this file for user")
logger.Errorf("Path is not writable by the user: %q", path)
return false
}

Expand Down
14 changes: 7 additions & 7 deletions lib/download.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package lib

import (
"fmt"
"errors"
"io"
"net/http"
"os"
Expand All @@ -13,35 +13,35 @@ import (
func DownloadFromURL(installLocation string, url string) (string, error) {
tokens := strings.Split(url, "/")
fileName := tokens[len(tokens)-1]
fmt.Printf("Downloading to: %s\n", installLocation)
logger.Infof("Downloading to %q", installLocation)

response, err := http.Get(url)
if err != nil {
fmt.Println("[Error] : Error while downloading", url, "-", err)
logger.Errorf("Error downloading %s: %v", url, err)
return "", err
}
defer response.Body.Close()

if response.StatusCode != 200 {
//Sometimes hashicorp terraform file names are not consistent
//For example 0.12.0-alpha4 naming convention in the release repo is not consistent
return "", fmt.Errorf("[Error] : Unable to download from %s", url)
return "", errors.New("Unable to download from " + url)
}

zipFile := filepath.Join(installLocation, fileName)
output, err := os.Create(zipFile)
if err != nil {
fmt.Println("[Error] : Error while creating", zipFile, "-", err)
logger.Errorf("Error while creating %q: %v", zipFile, err)
return "", err
}
defer output.Close()

n, err := io.Copy(output, response.Body)
if err != nil {
fmt.Println("[Error] : Error while downloading", url, "-", err)
logger.Errorf("Error while downloading %s: %v", url, err)
return "", err
}

fmt.Println(n, "bytes downloaded")
logger.Info(n, "bytes downloaded")
return zipFile, nil
}
15 changes: 6 additions & 9 deletions lib/download_test.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
package lib_test
package lib

import (
"fmt"
"github.com/mitchellh/go-homedir"
"log"
"net/url"
"os"
"path/filepath"
"runtime"
"testing"

"github.com/warrensbox/terraform-switcher/lib"
)

// TestDownloadFromURL_FileNameMatch : Check expected filename exist when downloaded
Expand All @@ -24,17 +21,17 @@ func TestDownloadFromURL_FileNameMatch(t *testing.T) {

home, err := homedir.Dir()
if err != nil {
log.Fatalf("Could not detect home directory.")
logger.Fatalf("Could not detect home directory")
}

fmt.Printf("Current user homedir: %v \n", home)
logger.Infof("Current home directory: %q", home)
var installLocation = ""
if runtime.GOOS != "windows" {
installLocation = filepath.Join(home, installPath)
} else {
installLocation = installPath
}
fmt.Printf("Install Location: %v \n", installLocation)
logger.Infof("Install Location: %v", installLocation)

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

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

if errDownload != nil {
t.Logf("Expected file name %v to be downloaded", expectedFile)
Expand All @@ -76,7 +73,7 @@ func TestDownloadFromURL_FileNameMatch(t *testing.T) {

t.Cleanup(func() {
defer os.Remove(tempDir)
fmt.Println("Cleanup temporary directory")
logger.Infof("Cleanup temporary directory %q", tempDir)
})
}

Expand Down
19 changes: 8 additions & 11 deletions lib/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ import (
"archive/zip"
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
Expand All @@ -17,7 +15,7 @@ import (
func RenameFile(src string, dest string) {
err := os.Rename(src, dest)
if err != nil {
fmt.Println(err)
logger.Error(err)
return
}
}
Expand Down Expand Up @@ -103,11 +101,11 @@ func Unzip(src string, dest string) ([]string, error) {
// 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)
logger.Infof("Creating directory for terraform binary at %q", dir)
err = os.MkdirAll(dir, 0755)
if err != nil {
fmt.Printf("Unable to create directory for terraform binary at: %v", dir)
panic(err)
logger.Error(err)
logger.Panicf("Unable to create directory for terraform binary at: %v", dir)
}
}
}
Expand All @@ -126,7 +124,7 @@ func WriteLines(lines []string, path string) (err error) {
for _, item := range lines {
_, err := file.WriteString(strings.TrimSpace(item) + "\n")
if err != nil {
fmt.Println(err)
logger.Error(err)
break
}
}
Expand Down Expand Up @@ -171,7 +169,7 @@ func IsDirEmpty(name string) bool {

f, err := os.Open(name)
if err != nil {
log.Fatal(err)
logger.Fatal(err)
}
defer f.Close()

Expand All @@ -189,8 +187,7 @@ func CheckDirHasTGBin(dir, prefix string) bool {

files, err := ioutil.ReadDir(dir)
if err != nil {
log.Fatal(err)
//return exist, err
logger.Fatal(err)
}
res := []string{}
for _, f := range files {
Expand Down Expand Up @@ -228,7 +225,7 @@ func GetCurrentDirectory() string {

dir, err := os.Getwd() //get current directory
if err != nil {
log.Printf("Failed to get current directory %v\n", err)
logger.Fatalf("Failed to get current directory %v", err)
os.Exit(1)
}
return dir
Expand Down
Loading

0 comments on commit fa36c17

Please sign in to comment.