github.com/beauknowssoftware/makehcl@v0.0.0-20200322000747-1b9bb1e1c008/internal/parse/parseRule.go (about)

     1  package parse
     2  
     3  import (
     4  	"github.com/pkg/errors"
     5  	"github.com/zclconf/go-cty/cty"
     6  
     7  	"github.com/beauknowssoftware/makehcl/internal/definition"
     8  	"github.com/hashicorp/hcl/v2"
     9  )
    10  
    11  var (
    12  	ruleSchema = hcl.BodySchema{
    13  		Attributes: []hcl.AttributeSchema{
    14  			{
    15  				Name:     "tee_target",
    16  				Required: false,
    17  			},
    18  			{
    19  				Name:     "environment",
    20  				Required: false,
    21  			},
    22  			{
    23  				Name:     "target",
    24  				Required: true,
    25  			},
    26  			{
    27  				Name:     "command",
    28  				Required: true,
    29  			},
    30  			{
    31  				Name:     "dependencies",
    32  				Required: false,
    33  			},
    34  		},
    35  	}
    36  )
    37  
    38  func fillRule(body hcl.Body, ctx *hcl.EvalContext) (*definition.Rule, error) {
    39  	con, diag := body.Content(&ruleSchema)
    40  	if diag.HasErrors() {
    41  		return nil, diag
    42  	}
    43  
    44  	target, err := evaluateString(con.Attributes["target"].Expr, ctx)
    45  	if err != nil {
    46  		err = errors.Wrap(err, "failed to evaluate target")
    47  		return nil, err
    48  	}
    49  
    50  	ectx := ctx.NewChild()
    51  	ectx.Variables = map[string]cty.Value{
    52  		"target": cty.StringVal(target),
    53  	}
    54  
    55  	var r definition.Rule
    56  	r.Target = target
    57  
    58  	for name, attr := range con.Attributes {
    59  		switch name {
    60  		case "tee_target":
    61  			teeTarget, err := evaluateBool(attr.Expr, ectx)
    62  			if err != nil {
    63  				err = errors.Wrap(err, "failed to evaluate tee_target")
    64  				return nil, err
    65  			}
    66  
    67  			r.TeeTarget = teeTarget
    68  		case "environment":
    69  			environment, err := evaluateStringMap(attr.Expr, ectx)
    70  			if err != nil {
    71  				err = errors.Wrap(err, "failed to evaluate environment")
    72  				return nil, err
    73  			}
    74  
    75  			r.Environment = environment
    76  		case "command":
    77  			command, err := evaluateString(attr.Expr, ectx)
    78  			if err != nil {
    79  				err = errors.Wrap(err, "failed to evaluate command")
    80  				return nil, err
    81  			}
    82  
    83  			r.Command = command
    84  		case "dependencies":
    85  			dependencies, err := evaluateStringArray(attr.Expr, ectx)
    86  			if err != nil {
    87  				err = errors.Wrap(err, "failed to evaluate dependencies")
    88  				return nil, err
    89  			}
    90  
    91  			r.Dependencies = dependencies
    92  		}
    93  	}
    94  
    95  	return &r, nil
    96  }
    97  
    98  func constructRule(blk *hcl.Block, ctx *hcl.EvalContext) (*definition.Rule, error) {
    99  	return fillRule(blk.Body, ctx)
   100  }