yq/pkg/yqlib/operator_env.go
Mike Farah 4c6c653d25 wip
2023-04-09 11:14:51 +10:00

86 lines
2.2 KiB
Go

package yqlib
import (
"container/list"
"fmt"
"os"
parse "github.com/a8m/envsubst/parse"
)
type envOpPreferences struct {
StringValue bool
NoUnset bool
NoEmpty bool
FailFast bool
}
func envOperator(d *dataTreeNavigator, context Context, expressionNode *ExpressionNode) (Context, error) {
envName := expressionNode.Operation.CandidateNode.Value
log.Debug("EnvOperator, env name:", envName)
rawValue := os.Getenv(envName)
preferences := expressionNode.Operation.Preferences.(envOpPreferences)
var node *CandidateNode
if preferences.StringValue {
node = &CandidateNode{
Kind: ScalarNode,
Tag: "!!str",
Value: rawValue,
}
} else if rawValue == "" {
return Context{}, fmt.Errorf("Value for env variable '%v' not provided in env()", envName)
} else {
decoder := NewYamlDecoder(ConfiguredYamlPreferences)
result, err := decoder.Decode()
if err != nil {
return Context{}, err
}
node = result.unwrapDocument()
}
log.Debug("ENV tag", node.Tag)
log.Debug("ENV value", node.Value)
log.Debug("ENV Kind", node.Kind)
return context.SingleChildContext(node), nil
}
func envsubstOperator(d *dataTreeNavigator, context Context, expressionNode *ExpressionNode) (Context, error) {
var results = list.New()
preferences := envOpPreferences{}
if expressionNode.Operation.Preferences != nil {
preferences = expressionNode.Operation.Preferences.(envOpPreferences)
}
parser := parse.New("string", os.Environ(),
&parse.Restrictions{NoUnset: preferences.NoUnset, NoEmpty: preferences.NoEmpty})
if preferences.FailFast {
parser.Mode = parse.Quick
} else {
parser.Mode = parse.AllErrors
}
for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
candidate := el.Value.(*CandidateNode)
node := candidate.unwrapDocument()
if node.Tag != "!!str" {
log.Warning("EnvSubstOperator, env name:", node.Tag, node.Value)
return Context{}, fmt.Errorf("cannot substitute with %v, can only substitute strings. Hint: Most often you'll want to use '|=' over '=' for this operation", node.Tag)
}
value, err := parser.Parse(node.Value)
if err != nil {
return Context{}, err
}
result := candidate.CreateReplacement(ScalarNode, "!!str", value)
results.PushBack(result)
}
return context.ChildContext(results), nil
}