isle/go/yamlutil/yamlutil.go

46 lines
1011 B
Go
Raw Permalink Normal View History

package yamlutil
import (
"errors"
"fmt"
"io"
"os"
"gopkg.in/yaml.v3"
)
// LoadYamlFile reads the file at the given path and unmarshals it into the
// given pointer.
func LoadYamlFile(into any, path string) error {
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("opening file: %w", err)
}
defer file.Close()
if err = yaml.NewDecoder(file).Decode(into); errors.Is(err, io.EOF) {
return nil
} else if err != nil {
return fmt.Errorf("decoding yaml: %w", err)
}
return nil
}
// WriteYamlFile encodes the given data as a yaml document, and writes it to the
// given file path, overwriting any previous data.
func WriteYamlFile(data any, path string, fileMode os.FileMode) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileMode)
if err != nil {
return fmt.Errorf("opening file: %w", err)
}
defer file.Close()
if err := yaml.NewEncoder(file).Encode(data); err != nil {
return fmt.Errorf("writing/encoding file: %w", err)
}
return nil
}