Debian Codegraph @

kyaml/comments/comments.go

raw symbols SCIP
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package comments
5
6 import (
7 "sigs.k8s.io/kustomize/kyaml/openapi"
8 "sigs.k8s.io/kustomize/kyaml/yaml"
9 "sigs.k8s.io/kustomize/kyaml/yaml/walk"
10 )
11
12 // CopyComments recursively copies the comments on fields in from to fields in to
13 func CopyComments(from, to *yaml.RNode) error {
14 // from node should not be modified, it should be just used as a reference
15 fromCopy := from.Copy()
16 copyFieldComments(fromCopy, to)
17 // walk the fields copying comments
18 _, err := walk.Walker{
19 Sources: []*yaml.RNode{fromCopy, to},
20 Visitor: &copier{},
21 VisitKeysAsScalars: true}.Walk()
22 return err
23 }
24
25 // copier implements walk.Visitor, and copies comments to fields shared between 2 instances
26 // of a resource
27 type copier struct{}
28
29 func (c *copier) VisitMap(s walk.Sources, _ *openapi.ResourceSchema) (*yaml.RNode, error) {
30 copyFieldComments(s.Dest(), s.Origin())
31 return s.Dest(), nil
32 }
33
34 func (c *copier) VisitScalar(s walk.Sources, _ *openapi.ResourceSchema) (*yaml.RNode, error) {
35 to := s.Origin()
36 // TODO: File a bug with upstream yaml to handle comments for FoldedStyle scalar nodes
37 // Hack: convert FoldedStyle scalar node to DoubleQuotedStyle as the line comments are
38 // being serialized without space
39 // https://github.com/GoogleContainerTools/kpt/issues/766
40 if to != nil && to.Document().Style == yaml.FoldedStyle {
41 to.Document().Style = yaml.DoubleQuotedStyle
42 }
43
44 copyFieldComments(s.Dest(), to)
45 return s.Dest(), nil
46 }
47
48 func (c *copier) VisitList(s walk.Sources, _ *openapi.ResourceSchema, _ walk.ListKind) (
49 *yaml.RNode, error) {
50 copyFieldComments(s.Dest(), s.Origin())
51 destItems := s.Dest().Content()
52 originItems := s.Origin().Content()
53
54 for i := 0; i < len(destItems) && i < len(originItems); i++ {
55 dest := destItems[i]
56 origin := originItems[i]
57
58 if dest.Value == origin.Value {
59 // We copy the comments recursively on each node in the list.
60 if err := CopyComments(yaml.NewRNode(dest), yaml.NewRNode(origin)); err != nil {
61 return nil, err
62 }
63 }
64 }
65
66 return s.Dest(), nil
67 }
68
69 // copyFieldComments copies the comment from one field to another
70 func copyFieldComments(from, to *yaml.RNode) {
71 if from == nil || to == nil {
72 return
73 }
74 if to.Document().LineComment == "" {
75 to.Document().LineComment = from.Document().LineComment
76 }
77 if to.Document().HeadComment == "" {
78 to.Document().HeadComment = from.Document().HeadComment
79 }
80 if to.Document().FootComment == "" {
81 to.Document().FootComment = from.Document().FootComment
82 }
83 }