github.com/richardwilkes/toolbox@v1.121.0/xio/fs/yaml.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package fs
    11  
    12  import (
    13  	"bufio"
    14  	"io"
    15  	"io/fs"
    16  	"os"
    17  
    18  	"github.com/richardwilkes/toolbox/errs"
    19  	"github.com/richardwilkes/toolbox/xio"
    20  	"github.com/richardwilkes/toolbox/xio/fs/safe"
    21  
    22  	"gopkg.in/yaml.v3"
    23  )
    24  
    25  // LoadYAML data from the specified path.
    26  func LoadYAML(path string, data any) error {
    27  	f, err := os.Open(path)
    28  	if err != nil {
    29  		return errs.NewWithCause(path, err)
    30  	}
    31  	return loadYAML(f, path, data)
    32  }
    33  
    34  // LoadYAMLFromFS data from the specified filesystem path.
    35  func LoadYAMLFromFS(fsys fs.FS, path string, data any) error {
    36  	f, err := fsys.Open(path)
    37  	if err != nil {
    38  		return errs.NewWithCause(path, err)
    39  	}
    40  	return loadYAML(f, path, data)
    41  }
    42  
    43  func loadYAML(r io.ReadCloser, path string, data any) error {
    44  	defer xio.CloseIgnoringErrors(r)
    45  	if err := yaml.NewDecoder(bufio.NewReader(r)).Decode(data); err != nil {
    46  		return errs.NewWithCause(path, err)
    47  	}
    48  	return nil
    49  }
    50  
    51  // SaveYAML data to the specified path.
    52  func SaveYAML(path string, data any) error {
    53  	return SaveYAMLWithMode(path, data, 0o644)
    54  }
    55  
    56  // SaveYAMLWithMode data to the specified path.
    57  func SaveYAMLWithMode(path string, data any, mode os.FileMode) error {
    58  	if err := safe.WriteFileWithMode(path, func(w io.Writer) error {
    59  		encoder := yaml.NewEncoder(w)
    60  		encoder.SetIndent(2)
    61  		if err := encoder.Encode(data); err != nil {
    62  			return errs.Wrap(err)
    63  		}
    64  		return errs.Wrap(encoder.Close())
    65  	}, mode); err != nil {
    66  		return errs.NewWithCause(path, err)
    67  	}
    68  	return nil
    69  }