mirror of
https://github.com/gotify/cli.git
synced 2024-01-28 15:20:39 +03:00
Add config stuff
This commit is contained in:
7
config/config.go
Normal file
7
config/config.go
Normal 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
28
config/locations.go
Normal 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
63
config/readwrite.go
Normal 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)
|
||||
}
|
||||
Reference in New Issue
Block a user