...
1
2
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
13 func CopyComments(from, to *yaml.RNode) error {
14
15 fromCopy := from.Copy()
16 copyFieldComments(fromCopy, to)
17
18 _, err := walk.Walker{
19 Sources: []*yaml.RNode{fromCopy, to},
20 Visitor: &copier{},
21 VisitKeysAsScalars: true}.Walk()
22 return err
23 }
24
25
26
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
37
38
39
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
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
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 }
84
View as plain text