Compare commits

..

2 Commits

Author SHA1 Message Date
fe80f029b5 Merge pull request 'Add error handling and improve comments' (#7) from fix-1.9.x into master
Reviewed-on: #7
2024-09-12 00:38:13 +00:00
15742e8f3f Add error handling and improve comments
Added fmt.Errorf for better error messages during HTTP and file handling in InstallTerraformVersion. Also fixed indentation in comments to follow Go conventions. Made other small improvements for better readability and maintainability.
2024-09-11 20:27:10 -04:00

View File

@ -5,6 +5,7 @@ import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
@ -90,51 +91,54 @@ func (v *Version) InstallTerraformVersion() error {
if v.Version.IsLessThan(*minV) {
suffix = alternateSuffix
}
resp, err := http.Get(hashicorpUrl +
url := hashicorpUrl +
v.Version.ToString() +
"/" + terraformPrefix +
v.Version.ToString() +
suffix)
suffix
resp, err := http.Get(url)
if err != nil {
return err
return fmt.Errorf("failed to download Terraform: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
return fmt.Errorf("failed to read response body: %v", err)
}
zipReader, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
if err != nil {
return err
return fmt.Errorf("failed to create zip reader: %v", err)
}
versionedFileName := homeDir + versionedTerraformFolder + "/" + terraformPrefix + v.Version.ToString()
versionedFile, err := os.OpenFile(versionedFileName, os.O_WRONLY, 0755)
if os.IsNotExist(err) {
versionedFile, err = os.OpenFile(versionedFileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
versionedFile, err := os.OpenFile(versionedFileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
return err
}
}
if err != nil {
return err
return fmt.Errorf("failed to create output file: %v", err)
}
defer versionedFile.Close()
for _, zipFile := range zipReader.File {
if zipFile.Name != "terraform" {
continue
}
zr, err := zipFile.Open()
if err != nil {
return err
return fmt.Errorf("failed to open zip file: %v", err)
}
unzippedFileBytes, _ := ioutil.ReadAll(zr)
defer zr.Close()
_, err = versionedFile.Write(unzippedFileBytes)
_, err = io.Copy(versionedFile, zr)
if err != nil {
return err
return fmt.Errorf("failed to write terraform binary: %v", err)
}
zr.Close()
break
}
return nil
}