package yamlutil import ( "fmt" "io/fs" "os" "gopkg.in/yaml.v3" ) // LoadYamlFile reads the file at the given path and unmarshals it into the // given pointer. func LoadYamlFile(into interface{}, 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); 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 interface{}, path string) error { file, err := os.OpenFile( path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0640, ) if err != nil { return fmt.Errorf("opening file: %w", err) } err = yaml.NewEncoder(file).Encode(data) file.Close() if err != nil { return fmt.Errorf("writing/encoding file: %w", err) } return nil } // LoadYamlFSFile is like LoadYamlFile, but it will read the file from the given // fs.FS instance. func LoadYamlFSFile(into interface{}, f fs.FS, path string) error { body, err := fs.ReadFile(f, path) if err != nil { return fmt.Errorf("reading file from FS: %w", err) } if err := yaml.Unmarshal(body, into); err != nil { return fmt.Errorf("yaml unmarshaling: %w", err) } return nil }