2021-04-20 21:31:37 +00:00
|
|
|
package yamlutil
|
|
|
|
|
|
|
|
import (
|
2024-12-19 08:38:15 +00:00
|
|
|
"errors"
|
2021-04-20 21:31:37 +00:00
|
|
|
"fmt"
|
2024-12-19 08:38:15 +00:00
|
|
|
"io"
|
2021-04-20 21:31:37 +00:00
|
|
|
"os"
|
|
|
|
|
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
)
|
|
|
|
|
|
|
|
// LoadYamlFile reads the file at the given path and unmarshals it into the
|
|
|
|
// given pointer.
|
2024-06-10 16:56:36 +00:00
|
|
|
func LoadYamlFile(into any, path string) error {
|
2021-04-20 21:31:37 +00:00
|
|
|
file, err := os.Open(path)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("opening file: %w", err)
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
2024-12-19 08:38:15 +00:00
|
|
|
if err = yaml.NewDecoder(file).Decode(into); errors.Is(err, io.EOF) {
|
|
|
|
return nil
|
|
|
|
} else if err != nil {
|
2021-04-20 21:31:37 +00:00
|
|
|
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.
|
2024-06-10 16:56:36 +00:00
|
|
|
func WriteYamlFile(data any, path string, fileMode os.FileMode) error {
|
2021-04-20 21:31:37 +00:00
|
|
|
|
2024-06-10 16:56:36 +00:00
|
|
|
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileMode)
|
2021-04-20 21:31:37 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("opening file: %w", err)
|
|
|
|
}
|
2024-06-10 16:56:36 +00:00
|
|
|
defer file.Close()
|
2021-04-20 21:31:37 +00:00
|
|
|
|
2024-06-10 16:56:36 +00:00
|
|
|
if err := yaml.NewEncoder(file).Encode(data); err != nil {
|
2021-04-20 21:31:37 +00:00
|
|
|
return fmt.Errorf("writing/encoding file: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|