Skip to content

Commit

Permalink
Merge pull request #72 from kpucynski/version-from-tf-code
Browse files Browse the repository at this point in the history
Support reading required version from TF code.
  • Loading branch information
warrensbox committed Apr 16, 2020
2 parents d747848 + 40550c3 commit d9f261d
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,20 @@ import (
"io/ioutil"
"log"
"os"
"sort"
"strings"

"github.com/Masterminds/semver"

// original hashicorp upstream have broken dependencies, so using fork as workaround
// TODO: move back to upstream
"github.com/kiranjthomas/terraform-config-inspect/tfconfig"
// "github.com/hashicorp/terraform-config-inspect/tfconfig"

"github.com/manifoldco/promptui"
"github.com/pborman/getopt"
"github.com/spf13/viper"

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

Expand Down Expand Up @@ -121,6 +130,50 @@ func main() {
os.Exit(1)
}
}
} else if module, _ := tfconfig.LoadModule(dir); len(module.RequiredCore) >= 1 && len(args) == 0 { //if there is a .tfswitchrc file, and no commmand line arguments
tfversion := ""

// we skip duplicated definitions and use only first one
tfconstraint := module.RequiredCore[0]
tflist, _ := lib.GetTFList(hashiURL, true)
fmt.Printf("Reading required version from terraform code, constraint: %s\n", tfconstraint)

c, err := semver.NewConstraint(tfconstraint)
if err != nil {
fmt.Println("Error parsing constraint:", err)
os.Exit(1)
}
vs := make([]*semver.Version, len(tflist))
for i, r := range tflist {
v, err := semver.NewVersion(r)
if err != nil {
fmt.Printf("Error parsing version: %s", err)
os.Exit(1)
}

vs[i] = v
}

sort.Sort(sort.Reverse(semver.Collection(vs)))

for _, element := range vs {
// Validate a version against a constraint.
if c.Check(element) {
tfversion = string(element.String())
fmt.Printf("Matched version: %s\n", tfversion)

if lib.ValidVersionFormat(tfversion) {
lib.Install(string(tfversion), *custBinPath)
break
} else {
fmt.Println("Invalid terraform version format. Format should be #.#.# or #.#.#-@# where # is numbers and @ is word characters. For example, 0.11.7 and 0.11.9-beta1 are valid versions")
os.Exit(1)
}
}
}

fmt.Println("No version found to match constraint.")
os.Exit(1)

} else if _, err := os.Stat(rcfile); err == nil && len(args) == 0 { //if there is a .tfswitchrc file, and no commmand line arguments
fmt.Printf("Reading required terraform version %s \n", rcFilename)
Expand Down

0 comments on commit d9f261d

Please sign in to comment.