From 9d34e7f6f54918ed239f8ee9577e9b194d72d159 Mon Sep 17 00:00:00 2001 From: mitch Date: Fri, 25 Feb 2022 20:11:25 -0500 Subject: [PATCH] Resolved missing configuration folder / file on initial run --- cmd/main.go | 31 ++++++++++++++++++++++++++----- configManagement.go | 14 ++++++++++++++ 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 9300ac1..679822b 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -18,6 +18,21 @@ const ( func main() { homeDir, _ := os.UserHomeDir() configDirString := homeDir + shortConfigDirString + + _, err := os.Stat(configDirString) + if os.IsNotExist(err) { + err = versionedTerraform.CreateConfig(configDirString, configFileLocation) + } + + _, err = os.Stat(configDirString + "/" + configFileLocation) + if os.IsNotExist(err) { + err = versionedTerraform.CreateConfig(configDirString, configFileLocation) + } + + if err != nil { + fmt.Printf("Unable to create config directory: %v", err) + } + configDir := os.DirFS(configDirString) workingDir := os.DirFS(pwd) var versionsFromConfig []versionedTerraform.SemVersion @@ -25,17 +40,23 @@ func main() { flag.Parse() args := flag.Args() + versionsFromConfig, err = versionedTerraform.LoadVersionsFromConfig(configDir, configFileLocation) + + if err != nil { + fmt.Printf("Unable to read config: %v", err) + os.Exit(1) + } + needsUpdate, err := versionedTerraform.NeedToUpdateAvailableVersions(configDir, configFileLocation) + if os.ErrNotExist == err { + fmt.Println("Unable to update version: %v", err) + } + if needsUpdate { fileHandle, _ := os.OpenFile(configDirString+"/"+configFileLocation, os.O_RDWR, 0666) defer fileHandle.Close() versionedTerraform.UpdateConfig(*fileHandle) } - versionsFromConfig, err = versionedTerraform.LoadVersionsFromConfig(configDir, configFileLocation) - if err != nil { - fmt.Printf("Unable to read config: %v", err) - os.Exit(1) - } installedVersions, err := versionedTerraform.LoadInstalledVersions(configDir) if err != nil { diff --git a/configManagement.go b/configManagement.go index 5650937..06431fe 100644 --- a/configManagement.go +++ b/configManagement.go @@ -109,3 +109,17 @@ func UpdateConfig(File os.File) error { File.Write(lineToByte) return nil } + +func CreateConfig(directory string, configFile string) error { + configFileName := directory + "/" + configFile + err := os.MkdirAll(directory, 0755) + if err != nil { + return err + } + + fileHandler, err := os.Create(configFileName) + defer fileHandler.Close() + + err = UpdateConfig(*fileHandler) + return err +}