github.com/sfdevops1/terrra4orm@v0.11.12-beta1/configs/version_constraint.go (about) 1 package configs 2 3 import ( 4 "fmt" 5 6 version "github.com/hashicorp/go-version" 7 "github.com/hashicorp/hcl2/hcl" 8 "github.com/zclconf/go-cty/cty" 9 "github.com/zclconf/go-cty/cty/convert" 10 ) 11 12 // VersionConstraint represents a version constraint on some resource 13 // (e.g. Terraform Core, a provider, a module, ...) that carries with it 14 // a source range so that a helpful diagnostic can be printed in the event 15 // that a particular constraint does not match. 16 type VersionConstraint struct { 17 Required version.Constraints 18 DeclRange hcl.Range 19 } 20 21 func decodeVersionConstraint(attr *hcl.Attribute) (VersionConstraint, hcl.Diagnostics) { 22 ret := VersionConstraint{ 23 DeclRange: attr.Range, 24 } 25 26 val, diags := attr.Expr.Value(nil) 27 var err error 28 val, err = convert.Convert(val, cty.String) 29 if err != nil { 30 diags = append(diags, &hcl.Diagnostic{ 31 Severity: hcl.DiagError, 32 Summary: "Invalid version constraint", 33 Detail: fmt.Sprintf("A string value is required for %s.", attr.Name), 34 Subject: attr.Expr.Range().Ptr(), 35 }) 36 return ret, diags 37 } 38 39 if val.IsNull() { 40 // A null version constraint is strange, but we'll just treat it 41 // like an empty constraint set. 42 return ret, diags 43 } 44 45 constraintStr := val.AsString() 46 constraints, err := version.NewConstraint(constraintStr) 47 if err != nil { 48 // NewConstraint doesn't return user-friendly errors, so we'll just 49 // ignore the provided error and produce our own generic one. 50 diags = append(diags, &hcl.Diagnostic{ 51 Severity: hcl.DiagError, 52 Summary: "Invalid version constraint", 53 Detail: "This string does not use correct version constraint syntax.", // Not very actionable :( 54 Subject: attr.Expr.Range().Ptr(), 55 }) 56 return ret, diags 57 } 58 59 ret.Required = constraints 60 return ret, diags 61 }