Debian Codegraph @

match/internal/yaml/yaml.go

raw
1 package yaml
2
3 import (
4 "bytes"
5 "errors"
6 "strings"
7
8 "github.com/goccy/go-yaml"
9 "github.com/goccy/go-yaml/ast"
10 )
11
12 // GetValue returns the value of the node.
13 func GetValue(node ast.Node) (any, error) {
14 data, err := node.MarshalYAML()
15 if err != nil {
16 return nil, err
17 }
18
19 var value any
20 if err := yaml.Unmarshal(data, &value); err != nil {
21 return nil, err
22 }
23
24 return value, nil
25 }
26
27 // Get takes an ast.File and a string representing a path
28 // and returns the yaml.Path, the node and a bool indicating if the node exists.
29 func Get(f *ast.File, p string) (*yaml.Path, ast.Node, bool, error) {
30 path, err := yaml.PathString(p)
31 if err != nil {
32 return nil, nil, false, err
33 }
34
35 node, err := path.FilterFile(f)
36 if err != nil {
37 if errors.Is(err, yaml.ErrNotFoundNode) {
38 return path, nil, false, nil
39 }
40
41 return path, nil, false, err
42 }
43
44 return path, node, true, nil
45 }
46
47 // Update marshals the value and replaces the file at the path provided with the new value.
48 func Update(f *ast.File, path *yaml.Path, value any) error {
49 b, err := yaml.Marshal(value)
50 if err != nil {
51 return err
52 }
53
54 return path.ReplaceWithReader(f, bytes.NewReader(b))
55 }
56
57 // MarshalFile returns the representation of the ast.File to a byte slice.
58 func MarshalFile(f *ast.File, addNewLine bool) []byte {
59 docs := make([]string, 0, len(f.Docs))
60
61 for _, doc := range f.Docs {
62 docs = append(docs, doc.String())
63 }
64
65 if addNewLine {
66 docs = append(docs, "")
67 }
68
69 return []byte(strings.Join(docs, "\n"))
70 }