ez/ez.go

90 lines
2.0 KiB
Go

// Package ez provides data serialization and deseralization in YAML format
package ez
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
p "path"
"path/filepath"
"gopkg.in/yaml.v2"
)
// DefaultConfigPath returns the default path to a configuration file for an
// application with the specified name. If no name is provided, the executable
// name is used.
func DefaultConfigPath(appName string) (string, error) {
homedir, err := os.UserHomeDir()
if err != nil {
return "", err
} else if homedir == "" {
return "", errors.New("a blank path to user homedir was returned")
}
if appName == "" {
appName = filepath.Base(os.Args[0])
}
dir := path.Join(homedir, ".config", appName)
_, err = os.Stat(path.Join(dir, "config.yaml"))
if err == nil {
return path.Join(dir, "config.yaml"), nil
}
_, err = os.Stat(path.Join(dir, "config.yml"))
if err == nil {
return path.Join(dir, "config.yml"), nil
}
return path.Join(dir, "config.yaml"), nil
}
// Serialize stores data in YAML format at the specified path.
func Serialize(object interface{}, path string) error {
if path == "" {
return errors.New("failed to serialize: no path specified")
}
out, err := yaml.Marshal(object)
if err != nil {
return fmt.Errorf("failed to marshal configuration: %s", err)
}
os.MkdirAll(p.Dir(path), 0755)
err = ioutil.WriteFile(path, out, 0644)
if err != nil {
return fmt.Errorf("failed to write to %s: %s", path, err)
}
return nil
}
// Deserialize loads data from the specified path. If a file does not exist at
// the specified path, no error is returned.
func Deserialize(object interface{}, path string) error {
if path == "" {
return errors.New("failed to deserialize: no path specified")
}
_, err := os.Stat(path)
if os.IsNotExist(err) {
return nil
}
configData, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to read file: %s", err)
}
err = yaml.Unmarshal(configData, object)
if err != nil {
return fmt.Errorf("failed to parse file: %s", err)
}
return nil
}