github.com/zoomfoo/nomad@v0.8.5-0.20180907175415-f28fd3a1a056/plugins/shared/util.go (about) 1 package shared 2 3 import ( 4 "bytes" 5 "fmt" 6 7 hjson "github.com/hashicorp/hcl2/hcl/json" 8 "github.com/hashicorp/nomad/nomad/structs" 9 "github.com/ugorji/go/codec" 10 11 "github.com/hashicorp/hcl2/hcl" 12 "github.com/hashicorp/hcl2/hcldec" 13 "github.com/zclconf/go-cty/cty" 14 "github.com/zclconf/go-cty/cty/function" 15 "github.com/zclconf/go-cty/cty/function/stdlib" 16 ) 17 18 // ParseHclInterface is used to convert an interface value representing a hcl2 19 // body and return the interpolated value. 20 func ParseHclInterface(val interface{}, spec hcldec.Spec, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { 21 // Encode to json 22 var buf bytes.Buffer 23 enc := codec.NewEncoder(&buf, structs.JsonHandle) 24 err := enc.Encode(val) 25 if err != nil { 26 // Convert to a hcl diagnostics message 27 return cty.NilVal, hcl.Diagnostics([]*hcl.Diagnostic{ 28 { 29 Severity: hcl.DiagError, 30 Summary: "Failed to JSON encode value", 31 Detail: fmt.Sprintf("JSON encoding failed: %v", err), 32 }}) 33 } 34 35 // Parse the json as hcl2 36 hclFile, diag := hjson.Parse(buf.Bytes(), "") 37 if diag.HasErrors() { 38 return cty.NilVal, diag 39 } 40 41 value, decDiag := hcldec.Decode(hclFile.Body, spec, ctx) 42 diag = diag.Extend(decDiag) 43 if diag.HasErrors() { 44 return cty.NilVal, diag 45 } 46 47 return value, diag 48 } 49 50 // GetStdlibFuncs returns the set of stdlib functions. 51 func GetStdlibFuncs() map[string]function.Function { 52 return map[string]function.Function{ 53 "abs": stdlib.AbsoluteFunc, 54 "coalesce": stdlib.CoalesceFunc, 55 "concat": stdlib.ConcatFunc, 56 "hasindex": stdlib.HasIndexFunc, 57 "int": stdlib.IntFunc, 58 "jsondecode": stdlib.JSONDecodeFunc, 59 "jsonencode": stdlib.JSONEncodeFunc, 60 "length": stdlib.LengthFunc, 61 "lower": stdlib.LowerFunc, 62 "max": stdlib.MaxFunc, 63 "min": stdlib.MinFunc, 64 "reverse": stdlib.ReverseFunc, 65 "strlen": stdlib.StrlenFunc, 66 "substr": stdlib.SubstrFunc, 67 "upper": stdlib.UpperFunc, 68 } 69 }