better support for reading / writing single resource yaml files

This commit is contained in:
Phillip Wittrock
2020-02-13 15:02:43 -08:00
parent 64c30a0678
commit 154939803f

View File

@@ -6,6 +6,7 @@ package yaml
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"strings" "strings"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
@@ -99,6 +100,42 @@ func Parse(value string) (*RNode, error) {
return Parser{Value: value}.Filter(nil) return Parser{Value: value}.Filter(nil)
} }
// ReadFile parses a single Resource from a yaml file
func ReadFile(path string) (*RNode, error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return Parse(string(b))
}
// WriteFile writes a single Resource to a yaml file
func WriteFile(node *RNode, path string) error {
out, err := node.String()
if err != nil {
return err
}
return ioutil.WriteFile(path, []byte(out), 0600)
}
// UpdateFile reads the file at path, applies the filter to it, and write the result back.
// path must contain a exactly 1 resource (YAML).
func UpdateFile(filter Filter, path string) error {
// Read the yaml
y, err := ReadFile(path)
if err != nil {
return err
}
// Update the yaml
if err := y.PipeE(filter); err != nil {
return err
}
// Write the yaml
return WriteFile(y, path)
}
// TODO(pwittrock): test this // TODO(pwittrock): test this
func GetStyle(styles ...string) Style { func GetStyle(styles ...string) Style {
var style Style var style Style