2020-02-14 21:46:02 +01:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2020-05-07 03:09:31 +02:00
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
|
2020-02-14 21:46:02 +01:00
|
|
|
"github.com/BurntSushi/toml"
|
|
|
|
"github.com/mitchellh/go-homedir"
|
2020-02-27 03:53:11 +01:00
|
|
|
"go.jolheiser.com/beaver"
|
2020-02-14 21:46:02 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
configPath string
|
|
|
|
cfg *config
|
|
|
|
|
2020-02-18 06:27:52 +01:00
|
|
|
// Config items
|
2020-02-18 16:51:10 +01:00
|
|
|
|
2020-02-16 23:31:01 +01:00
|
|
|
Origin string
|
2020-02-16 06:51:14 +01:00
|
|
|
Upstream string
|
2020-02-18 03:57:51 +01:00
|
|
|
Tokens []Token
|
2020-02-14 21:46:02 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type config struct {
|
2020-02-16 23:31:01 +01:00
|
|
|
Origin string `toml:"origin"`
|
2020-02-16 06:51:14 +01:00
|
|
|
Upstream string `toml:"upstream"`
|
2020-02-18 03:57:51 +01:00
|
|
|
Tokens []Token `toml:"token"`
|
2020-02-14 21:46:02 +01:00
|
|
|
}
|
|
|
|
|
2020-02-18 03:57:51 +01:00
|
|
|
type Token struct {
|
2020-02-14 21:46:02 +01:00
|
|
|
Name string `toml:"name"`
|
|
|
|
URL string `toml:"url"`
|
|
|
|
Token string `toml:"token"`
|
|
|
|
}
|
|
|
|
|
2020-02-18 06:27:52 +01:00
|
|
|
// Load on init so that CLI contexts are correctly populated
|
2020-02-14 21:46:02 +01:00
|
|
|
func init() {
|
|
|
|
home, err := homedir.Dir()
|
|
|
|
if err != nil {
|
|
|
|
beaver.Fatalf("could not locate home directory: %v", err)
|
|
|
|
}
|
2020-02-17 21:50:02 +01:00
|
|
|
configPath = fmt.Sprintf("%s/.sip/config.toml", home)
|
2020-02-14 21:46:02 +01:00
|
|
|
|
|
|
|
if _, err := os.Stat(configPath); os.IsNotExist(err) {
|
|
|
|
if err := os.MkdirAll(path.Dir(configPath), os.ModePerm); err != nil {
|
2020-02-17 21:50:02 +01:00
|
|
|
beaver.Fatalf("could not create Sip home: %v", err)
|
2020-02-14 21:46:02 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := os.Create(configPath); err != nil {
|
2020-02-17 21:50:02 +01:00
|
|
|
beaver.Fatalf("could not create Sip config: %v", err)
|
2020-02-14 21:46:02 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := toml.DecodeFile(configPath, &cfg); err != nil {
|
2020-02-17 21:50:02 +01:00
|
|
|
beaver.Fatalf("could not decode Sip config: %v", err)
|
2020-02-14 21:46:02 +01:00
|
|
|
}
|
|
|
|
|
2020-02-16 23:31:01 +01:00
|
|
|
Origin = cfg.Origin
|
2020-02-16 06:51:14 +01:00
|
|
|
Upstream = cfg.Upstream
|
2020-02-18 03:57:51 +01:00
|
|
|
Tokens = cfg.Tokens
|
2020-02-14 21:46:02 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func Save() error {
|
2020-02-16 23:31:01 +01:00
|
|
|
cfg.Origin = Origin
|
2020-02-16 06:51:14 +01:00
|
|
|
cfg.Upstream = Upstream
|
2020-02-18 03:57:51 +01:00
|
|
|
cfg.Tokens = Tokens
|
2020-02-14 21:46:02 +01:00
|
|
|
|
|
|
|
fi, err := os.Create(configPath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer fi.Close()
|
|
|
|
|
|
|
|
if err := toml.NewEncoder(fi).Encode(cfg); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|