-
Notifications
You must be signed in to change notification settings - Fork 133
/
versiontf.go
67 lines (55 loc) · 1.86 KB
/
versiontf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package param_parsing
import (
semver "github.com/hashicorp/go-version"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/terraform-config-inspect/tfconfig"
"github.com/warrensbox/terraform-switcher/lib"
)
func GetVersionFromVersionsTF(params Params) (Params, error) {
var tfConstraints []string
curDir, err := os.Getwd()
if err != nil {
logger.Fatalf("Could not get current working directory: %v", err)
}
absPath := params.ChDirPath
if !filepath.IsAbs(params.ChDirPath) {
absPath, err = filepath.Abs(params.ChDirPath)
if err != nil {
logger.Fatalf("Could not derive absolute path to %q: %v", params.ChDirPath, err)
}
}
relPath, err := filepath.Rel(curDir, absPath)
if err != nil {
logger.Fatalf("Could not derive relative path to %q: %v", params.ChDirPath, err)
}
logger.Infof("Reading version from Terraform module at %q", relPath)
module, _ := tfconfig.LoadModule(params.ChDirPath)
if module.Diagnostics.HasErrors() {
logger.Fatalf("Could not load Terraform module at %q", params.ChDirPath)
}
requiredVersions := module.RequiredCore
for key := range requiredVersions {
// Check if the version contraint is valid
constraint, constraintErr := semver.NewConstraint(requiredVersions[key])
if constraintErr != nil {
logger.Errorf("Invalid version constraint found: %q", requiredVersions[key])
return params, constraintErr
}
// It's valid. Add to list
tfConstraints = append(tfConstraints, constraint.String())
}
tfConstraint := strings.Join(tfConstraints, ", ")
version, err2 := lib.GetSemver(tfConstraint, params.MirrorURL)
if err2 != nil {
logger.Errorf("No version found matching %q", tfConstraint)
return params, err2
}
params.Version = version
return params, nil
}
func isTerraformModule(params Params) bool {
module, err := tfconfig.LoadModule(params.ChDirPath)
return err == nil && len(module.RequiredCore) > 0
}