Add YAML anchor/alias expansion.

This commit is contained in:
monopole
2021-08-10 14:18:26 -07:00
parent 6c4e8019f8
commit 360585dfaf
6 changed files with 207 additions and 9 deletions

View File

@@ -903,6 +903,48 @@ func (rn *RNode) UnmarshalJSON(b []byte) error {
return nil
}
// DeAnchor inflates all YAML aliases with their anchor values.
// All YAML anchor data is permanently removed (feel free to call Copy first).
func (rn *RNode) DeAnchor() (err error) {
rn.value, err = deAnchor(rn.value)
return
}
// deAnchor removes all AliasNodes from the yaml.Node's tree, replacing
// them with what they point to. All Anchor fields (these are used to mark
// anchor definitions) are cleared.
func deAnchor(yn *yaml.Node) (res *yaml.Node, err error) {
if yn == nil {
return nil, nil
}
if yn.Anchor != "" {
// This node defines an anchor. Clear the field so that it
// doesn't show up when marshalling.
if yn.Kind == yaml.AliasNode {
// Maybe this is OK, but for now treating it as a bug.
return nil, fmt.Errorf(
"anchor %q defined using alias %v", yn.Anchor, yn.Alias)
}
yn.Anchor = ""
}
switch yn.Kind {
case yaml.ScalarNode:
return yn, nil
case yaml.AliasNode:
return deAnchor(yn.Alias)
case yaml.DocumentNode, yaml.MappingNode, yaml.SequenceNode:
for i := range yn.Content {
yn.Content[i], err = deAnchor(yn.Content[i])
if err != nil {
return nil, err
}
}
return yn, nil
default:
return nil, fmt.Errorf("cannot deAnchor kind %q", yn.Kind)
}
}
// GetValidatedMetadata returns metadata after subjecting it to some tests.
func (rn *RNode) GetValidatedMetadata() (ResourceMeta, error) {
m, err := rn.GetMeta()