func()

in custom-targets/util/applysetters/apply_setters.go [106:190]


func (as *ApplySetters) visitMapping(object *yaml.RNode, path string) error {
	return object.VisitFields(func(node *yaml.MapNode) error {
		if node == nil || node.Key.IsNil() || node.Value.IsNil() {
			// don't do IsNilOrEmpty check as empty sequences are allowed
			return nil
		}

		// the aim of this method is to apply-setter for sequence nodes
		if node.Value.YNode().Kind != yaml.SequenceNode {
			// return if it is not a sequence node
			return nil
		}

		lineComment := node.Key.YNode().LineComment
		if node.Value.YNode().Style == yaml.FlowStyle {
			// if node is FlowStyle e.g. env: [foo, bar] # from-param: ${env}
			// the setter comment will be on value node
			lineComment = node.Value.YNode().LineComment
		}

		setterPattern := extractSetterPattern(lineComment)
		if setterPattern == "" {
			// the node is not tagged with setter pattern
			return nil
		}

		if !shouldSet(setterPattern, as.Setters) {
			// this means there is no intent from user to modify this setter tagged resources
			return nil
		}

		// since this setter pattern is found on sequence node, make sure that it is
		// not interpolation of setters, it should be simple setter e.g. ${environments}
		if !validArraySetterPattern(setterPattern) {
			return errors.Errorf("invalid setter pattern for array node: %q", setterPattern)
		}

		// get the setter value for the setter name in the comment
		sv := setterValue(as.Setters, setterPattern)

		// add the key to the field path
		fieldPath := strings.TrimPrefix(fmt.Sprintf("%s.%s", path, node.Key.YNode().Value), ".")

		if sv == "" {
			node.Value.YNode().Content = []*yaml.Node{}
			// empty sequence must be FlowStyle e.g. env: [] # from-param: ${env}
			node.Value.YNode().Style = yaml.FlowStyle
			// setter pattern comment must be on value node
			node.Value.YNode().LineComment = lineComment
			node.Key.YNode().LineComment = ""
			as.Results = append(as.Results, &Result{
				FilePath:  as.filePath,
				FieldPath: fieldPath,
				Value:     sv,
			})
			return nil
		}

		// parse the setter value as yaml node
		rn, err := yaml.Parse(sv)
		if err != nil {
			return errors.Errorf("input to array setter must be an array of values, but found %q", sv)
		}

		// the setter value must parse as sequence node
		if rn.YNode().Kind != yaml.SequenceNode {
			return errors.Errorf("input to array setter must be an array of values, but found %q", sv)
		}

		node.Value.YNode().Content = rn.YNode().Content
		node.Key.YNode().LineComment = lineComment
		// non-empty sequences should be standardized to FoldedStyle
		// env: # from-param: ${env}
		//  - foo
		//  - bar
		node.Value.YNode().Style = yaml.FoldedStyle

		as.Results = append(as.Results, &Result{
			FilePath:  as.filePath,
			FieldPath: fieldPath,
			Value:     sv,
		})
		return nil
	})
}