github.com/beauknowssoftware/makehcl@v0.0.0-20200322000747-1b9bb1e1c008/internal/parse/parse.go (about) 1 package parse 2 3 import ( 4 "os" 5 "strings" 6 7 "github.com/beauknowssoftware/makehcl/internal/definition" 8 "github.com/beauknowssoftware/makehcl/internal/functions" 9 "github.com/hashicorp/hcl/v2" 10 "github.com/hashicorp/hcl/v2/hclparse" 11 "github.com/pkg/errors" 12 "github.com/zclconf/go-cty/cty" 13 ) 14 15 const ( 16 defaultFilename = "make.hcl" 17 ) 18 19 type Options struct { 20 Filename string 21 } 22 23 func envValue() cty.Value { 24 env := make(map[string]cty.Value) 25 26 for _, e := range os.Environ() { 27 p := strings.SplitN(e, "=", 2) 28 env[p[0]] = cty.StringVal(p[1]) 29 } 30 31 return cty.MapVal(env) 32 } 33 34 func createBaseContext() (*hcl.EvalContext, error) { 35 curdir, err := os.Getwd() 36 if err != nil { 37 return nil, errors.Wrap(err, "failed to get working directory") 38 } 39 40 var baseContext = hcl.EvalContext{ 41 Functions: functions.GetFunctions(curdir), 42 Variables: make(map[string]cty.Value), 43 } 44 45 baseContext.Variables["env"] = envValue() 46 47 return &baseContext, nil 48 } 49 50 func Parse(o Options) (*definition.Definition, error) { 51 if o.Filename == "" { 52 o.Filename = defaultFilename 53 } 54 55 p := hclparse.NewParser() 56 57 f, diag := p.ParseHCLFile(o.Filename) 58 if diag.HasErrors() { 59 return nil, diag 60 } 61 62 ctx, err := createBaseContext() 63 if err != nil { 64 return nil, err 65 } 66 67 return constructDefinition(f, ctx) 68 }