...

Source file src/code.rocketnine.space/tslocum/ez/ez.go

Documentation: code.rocketnine.space/tslocum/ez

     1  // Package ez provides data serialization and deseralization in YAML format
     2  package ez
     3  
     4  import (
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"os"
     9  	"path"
    10  	p "path"
    11  	"path/filepath"
    12  
    13  	"gopkg.in/yaml.v2"
    14  )
    15  
    16  // DefaultConfigPath returns the default path to a configuration file for an
    17  // application with the specified name.  If no name is provided, the executable
    18  // name is used.
    19  func DefaultConfigPath(appName string) (string, error) {
    20  	homedir, err := os.UserHomeDir()
    21  	if err != nil {
    22  		return "", err
    23  	} else if homedir == "" {
    24  		return "", errors.New("a blank path to user homedir was returned")
    25  	}
    26  
    27  	if appName == "" {
    28  		appName = filepath.Base(os.Args[0])
    29  	}
    30  
    31  	dir := path.Join(homedir, ".config", appName)
    32  
    33  	_, err = os.Stat(path.Join(dir, "config.yaml"))
    34  	if err == nil {
    35  		return path.Join(dir, "config.yaml"), nil
    36  	}
    37  
    38  	_, err = os.Stat(path.Join(dir, "config.yml"))
    39  	if err == nil {
    40  		return path.Join(dir, "config.yml"), nil
    41  	}
    42  
    43  	return path.Join(dir, "config.yaml"), nil
    44  }
    45  
    46  // Serialize stores data in YAML format at the specified path.
    47  func Serialize(object interface{}, path string) error {
    48  	if path == "" {
    49  		return errors.New("failed to serialize: no path specified")
    50  	}
    51  
    52  	out, err := yaml.Marshal(object)
    53  	if err != nil {
    54  		return fmt.Errorf("failed to marshal configuration: %s", err)
    55  	}
    56  
    57  	os.MkdirAll(p.Dir(path), 0755)
    58  
    59  	err = ioutil.WriteFile(path, out, 0644)
    60  	if err != nil {
    61  		return fmt.Errorf("failed to write to %s: %s", path, err)
    62  	}
    63  	return nil
    64  }
    65  
    66  // Deserialize loads data from the specified path. If a file does not exist at
    67  // the specified path, no error is returned.
    68  func Deserialize(object interface{}, path string) error {
    69  	if path == "" {
    70  		return errors.New("failed to deserialize: no path specified")
    71  	}
    72  
    73  	_, err := os.Stat(path)
    74  	if os.IsNotExist(err) {
    75  		return nil
    76  	}
    77  
    78  	configData, err := ioutil.ReadFile(path)
    79  	if err != nil {
    80  		return fmt.Errorf("failed to read file: %s", err)
    81  	}
    82  
    83  	err = yaml.Unmarshal(configData, object)
    84  	if err != nil {
    85  		return fmt.Errorf("failed to parse file: %s", err)
    86  	}
    87  
    88  	return nil
    89  }
    90  

View as plain text