-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathshow.go
More file actions
86 lines (70 loc) · 1.71 KB
/
Copy pathshow.go
File metadata and controls
86 lines (70 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package zerocfg
import (
"bytes"
"sort"
"strings"
"gopkg.in/yaml.v3"
)
// Show returns a formatted string representation of all registered configuration options and their current values.
func Show() string {
vs := make([]*node, 0, len(c.vs))
for _, n := range c.vs {
vs = append(vs, n)
}
sort.Slice(vs, func(i, j int) bool {
return vs[i].Name < vs[j].Name
})
return render(vs)
}
func render(vs []*node) string {
doc := &yaml.Node{Kind: yaml.DocumentNode}
root := &yaml.Node{Kind: yaml.MappingNode}
doc.Content = []*yaml.Node{root}
for _, v := range vs {
addNode(root, v.Name, yamlValue(v), yamlDescription(v))
}
var buf bytes.Buffer
yamlEncoder := yaml.NewEncoder(&buf)
yamlEncoder.SetIndent(2)
_ = yamlEncoder.Encode(doc)
_ = yamlEncoder.Close()
return buf.String()
}
func addNode(root *yaml.Node, path string, value any, comment string) {
parts := strings.Split(path, ".")
cur := root
for i, part := range parts {
var keyNode *yaml.Node
var valueNode *yaml.Node
found := false
for j := 0; j+1 < len(cur.Content); j += 2 {
if cur.Content[j].Value == part {
keyNode = cur.Content[j]
valueNode = cur.Content[j+1]
found = true
break
}
}
if !found {
keyNode = &yaml.Node{Kind: yaml.ScalarNode, Value: part}
valueNode = &yaml.Node{Kind: yaml.MappingNode}
if i == len(parts)-1 {
valueNode = &yaml.Node{Kind: yaml.ScalarNode, Value: ToString(value)}
if comment != "" {
keyNode.LineComment = comment
}
}
cur.Content = append(cur.Content, keyNode, valueNode)
}
cur = valueNode
}
}
func yamlDescription(n *node) string {
return n.Description
}
func yamlValue(n *node) string {
if n.isSecret {
return "<secret>"
}
return ToString(n.Value)
}