PKGBUILD/pkg/config/io.go

63 lines
1.4 KiB
Go
Raw Permalink Normal View History

package config
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
)
// Decode a configuration from a reader
func Decode(r io.Reader) (*Config, error) {
cnf := new(Config)
jsonDecoder := json.NewDecoder(r)
if err := jsonDecoder.Decode(&cnf); err != nil {
return nil, fmt.Errorf("Can not unmarshal JSON: %v", err)
}
return cnf, nil
}
// Encode a configuration to a writer
func Encode(cnf *Config, w io.Writer) error {
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
err := encoder.Encode(cnf)
if err != nil {
return fmt.Errorf("Error encoding config to json: %v", err)
}
return nil
}
// Read the configuration file
func Read(configFile string) (*Config, error) {
2021-05-16 21:02:46 +00:00
/* #nosec */
f, err := os.Open(configFile)
if err != nil {
return nil, fmt.Errorf("Can not open file %v: %v", configFile, err)
}
2021-05-16 21:02:46 +00:00
defer func() { _ = f.Close() }()
return Decode(f)
}
// Write the configuration into a file, specified by the configuration filepath
func Write(cnf *Config, configFile string) error {
if _, err := os.Stat(configFile); os.IsNotExist(err) {
configDir := filepath.Dir(configFile)
2021-05-16 21:02:46 +00:00
/* #nosec */
err := os.MkdirAll(configDir, 0775)
if err != nil {
return fmt.Errorf("Failed to create config directory %v: %v", configDir, err)
}
}
f, err := os.Create(configFile)
if err != nil {
return fmt.Errorf("Failed not create config file %v: %v", configFile, err)
}
2021-05-16 21:02:46 +00:00
defer func() { _ = f.Close() }()
return Encode(cnf, f)
}