Add options, keep seqindent annotation equivalent to index annotation

This commit is contained in:
Phani Teja Marupaka
2021-07-08 14:37:24 -07:00
parent 6dbc74b32e
commit f81201b74d
8 changed files with 248 additions and 129 deletions

View File

@@ -62,6 +62,12 @@ func (w ByteWriter) Write(inputNodes []*yaml.RNode) error {
// Even though we use the this value further down we must check this before removing annotations
jsonEncodeSingleBareNode := w.shouldJSONEncodeSingleBareNode(nodes)
// store seqindent annotation value for each node in order to set the encoder indentation
var seqIndentsForNodes []string
for i := range nodes {
seqIndentsForNodes = append(seqIndentsForNodes, nodes[i].GetAnnotations()[kioutil.SeqIndentAnnotation])
}
for i := range nodes {
// clean resources by removing annotations set by the Reader
if !w.KeepReaderAnnotations {
@@ -69,6 +75,11 @@ func (w ByteWriter) Write(inputNodes []*yaml.RNode) error {
if err != nil {
return errors.Wrap(err)
}
_, err = nodes[i].Pipe(yaml.ClearAnnotation(kioutil.SeqIndentAnnotation))
if err != nil {
return errors.Wrap(err)
}
}
for _, a := range w.ClearAnnotations {
_, err := nodes[i].Pipe(yaml.ClearAnnotation(a))
@@ -89,9 +100,6 @@ func (w ByteWriter) Write(inputNodes []*yaml.RNode) error {
if jsonEncodeSingleBareNode {
encoder := json.NewEncoder(w.Writer)
encoder.SetIndent("", " ")
if err := nodes[0].DeleteAnnotation(kioutil.SeqIndentAnnotation); err != nil {
return errors.Wrap(err)
}
return errors.Wrap(encoder.Encode(nodes[0]))
}
@@ -100,8 +108,13 @@ func (w ByteWriter) Write(inputNodes []*yaml.RNode) error {
// don't wrap the elements
if w.WrappingKind == "" {
for i := range nodes {
if err := unwrapAndEncodeYAML(nodes[i], encoder); err != nil {
return err
if seqIndentsForNodes[i] == string(yaml.WideSeqIndent) {
encoder.DefaultSeqIndent()
} else {
encoder.CompactSeqIndent()
}
if err := encoder.Encode(nodes[i].Document()); err != nil {
return errors.Wrap(err)
}
}
return nil
@@ -137,23 +150,6 @@ func (w ByteWriter) Write(inputNodes []*yaml.RNode) error {
return encoder.Encode(doc)
}
// unwrapAndEncodeYAML encodes the yaml RNode in unwrapped format,
// as a pre-step, it clears the sets the sequence indentation for encoder,
// based on the kioutil.SeqIndentAnnotation and clears it before encoding.
func unwrapAndEncodeYAML(node *yaml.RNode, encoder *yaml.Encoder) error {
anno := node.GetAnnotations()
seqIndent := anno[kioutil.SeqIndentAnnotation]
if seqIndent == string(yaml.WideSeqIndent) {
encoder.DefaultSeqIndent()
} else {
encoder.CompactSeqIndent()
}
if err := node.DeleteAnnotation(kioutil.SeqIndentAnnotation); err != nil {
return errors.Wrap(err)
}
return encoder.Encode(node.Document())
}
func copyRNodes(in []*yaml.RNode) []*yaml.RNode {
out := make([]*yaml.RNode, len(in))
for i := range in {