diff --git a/main.go b/main.go index 445b0f56..149b610c 100644 --- a/main.go +++ b/main.go @@ -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" ) @@ -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)