Project Amber CLI client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.3 KiB

package main
import (
"encoding/json"
"io/ioutil"
"os"
"runtime"
)
// Config holds app configuration values.
type Config struct {
path string
Server string `json:"server"`
Token string `json:"token"`
}
// DetermineAppPath returns the roaming path where application data
// is stored. It tries to deduce the closest alternative to `%APPDATA%`
// on Windows.
func DetermineAppPath() string {
var path string
switch runtime.GOOS {
case "windows":
appData := os.Getenv("APPDATA")
path = appData + "/" + AppName
default:
path = os.Getenv("HOME") + "/." + AppName
}
return path
}
// GetConfigPath wraps `DetermineAppPath()` and adds `/{AppName}.json`
// at the end.
func GetConfigPath() string {
path := DetermineAppPath() + "/" + AppName + ".json"
return path
}
// GetDefaultConfig returns the config structure with the default values
// inside.
func GetDefaultConfig() *Config {
return &Config{Server: DefaultInstance}
}
// ReadConfig tries to read the configuration file, and returns the default
// config on failing to parse it as JSON.
//
// The values of environment variables AMBER_SERVER and AMBER_TOKEN override
// their corresponding config values.
func ReadConfig(filename string) (*Config, error) {
file, oferr := os.OpenFile(filename, os.O_RDONLY, 0777)
if oferr != nil {
return GetDefaultConfig().MergeEnv().SetPath(filename), oferr
}
defer file.Close()
bytes, readerr := ioutil.ReadAll(file)
if readerr != nil {
return GetDefaultConfig().SetPath(filename), readerr
}
appConfig := GetDefaultConfig()
if jsonerr := json.Unmarshal(bytes, appConfig); jsonerr != nil {
return GetDefaultConfig().MergeEnv().SetPath(filename), jsonerr
}
return appConfig.MergeEnv().SetPath(filename), nil
}
// Write writes the config as JSON to a file it was read from.
func (c *Config) Write() error {
jsonBytes, jsonerr := json.Marshal(c)
if jsonerr != nil {
return jsonerr
}
if writeerr := ioutil.WriteFile(c.path, jsonBytes, 0600); writeerr != nil {
return writeerr
}
return nil
}
// MergeEnv parses config values from OS environment.
func (c *Config) MergeEnv() *Config {
if server := os.Getenv("AMBER_SERVER"); server != "" {
c.Server = server
}
return c
}
// SetPath sets the internal config path field.
func (c *Config) SetPath(path string) *Config {
c.path = path
return c
}