Add config stuff

This commit is contained in:
Jannis Mattheis
2018-11-24 17:06:46 +01:00
parent e3be2ac8fc
commit dc859bf01b
3 changed files with 98 additions and 0 deletions

7
config/config.go Normal file
View File

@@ -0,0 +1,7 @@
package config
type Config struct {
Token string `json:"token"`
URL string `json:"url"`
FromLocation string `json:"-"`
}

28
config/locations.go Normal file
View File

@@ -0,0 +1,28 @@
package config
import (
"os/user"
"path/filepath"
"runtime"
"github.com/gotify/cli/utils"
)
func userDir() string {
usr, err := user.Current()
if err != nil {
utils.Exit1With(err)
}
return usr.HomeDir
}
func GetLocations() []string {
inUserDir := filepath.Join(userDir(), ".gotify", "cli.json")
etcPath := "/etc/gotify/cli.json"
relativePath := "./cli.json"
if runtime.GOOS == "windows" {
return []string{relativePath, inUserDir}
} else {
return []string{relativePath, inUserDir, etcPath}
}
}

63
config/readwrite.go Normal file
View File

@@ -0,0 +1,63 @@
package config
import (
"encoding/json"
"errors"
"io/ioutil"
"os"
"path/filepath"
)
var (
ErrNoneSet = errors.New("no config set, run 'gotify init'")
)
func ExistingConfig(locations []string) (string, error) {
for _, location := range locations {
_, err := os.Stat(location)
if err == nil {
return location, nil
}
}
for _, location := range locations {
_, err := os.Stat(location)
if os.IsPermission(err) {
return "", errors.New("Permission denied " + location)
}
}
return "", ErrNoneSet
}
func ReadConfig(locations []string) (*Config, error) {
location, err := ExistingConfig(locations)
if err != nil {
return nil, err
}
file, err := os.Open(location)
defer file.Close()
if err != nil {
panic(err)
}
conf := Config{}
conf.FromLocation = location
err = json.NewDecoder(file).Decode(&conf)
if err != nil {
return nil, errors.New("Error while decoding " + err.Error())
}
return &conf, nil
}
func WriteConfig(location string, conf *Config) error {
bytes, err := json.MarshalIndent(conf,"", " ")
if err != nil {
return err
}
os.MkdirAll(filepath.Dir(location), 0644)
return ioutil.WriteFile(location, bytes, 0644)
}