-
Notifications
You must be signed in to change notification settings - Fork 171
/
yaml.go
90 lines (78 loc) · 2.08 KB
/
yaml.go
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
87
88
89
90
package utils
// fork from https://github.com/goccy/go-yaml/blob/master/cmd/ycat/ycat.go
import (
"fmt"
"io/fs"
"io/ioutil"
"github.com/defenseunicorns/zarf/cli/internal/message"
"github.com/fatih/color"
"github.com/goccy/go-yaml"
"github.com/goccy/go-yaml/lexer"
"github.com/goccy/go-yaml/printer"
"github.com/mattn/go-colorable"
)
const yamlEscape = "\x1b"
func yamlFormat(attr color.Attribute) string {
return fmt.Sprintf("%s[%dm", yamlEscape, attr)
}
func ColorPrintYAML(text string) {
tokens := lexer.Tokenize(text)
var p printer.Printer
p.Bool = func() *printer.Property {
return &printer.Property{
Prefix: yamlFormat(color.FgHiWhite),
Suffix: yamlFormat(color.Reset),
}
}
p.Number = func() *printer.Property {
return &printer.Property{
Prefix: yamlFormat(color.FgHiWhite),
Suffix: yamlFormat(color.Reset),
}
}
p.MapKey = func() *printer.Property {
return &printer.Property{
Prefix: yamlFormat(color.FgHiCyan),
Suffix: yamlFormat(color.Reset),
}
}
p.Anchor = func() *printer.Property {
return &printer.Property{
Prefix: yamlFormat(color.FgHiYellow),
Suffix: yamlFormat(color.Reset),
}
}
p.Alias = func() *printer.Property {
return &printer.Property{
Prefix: yamlFormat(color.FgHiYellow),
Suffix: yamlFormat(color.Reset),
}
}
p.String = func() *printer.Property {
return &printer.Property{
Prefix: yamlFormat(color.FgHiMagenta),
Suffix: yamlFormat(color.Reset),
}
}
writer := colorable.NewColorableStdout()
_, err := writer.Write([]byte("\n" + p.PrintTokens(tokens) + "\n"))
if err != nil {
message.Error(err, "Unable to print the config yaml contents")
}
}
func ReadYaml(path string, destConfig interface{}) error {
message.Debugf("Loading zarf config %s", path)
file, err := ioutil.ReadFile(path)
if err != nil {
return err
}
return yaml.Unmarshal(file, destConfig)
}
func WriteYaml(path string, srcConfig interface{}, perm fs.FileMode) error {
// Save the parsed output to the config path given
content, err := yaml.Marshal(srcConfig)
if err != nil {
return err
}
return ioutil.WriteFile(path, content, perm)
}