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"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
configPath string
|
|
|
|
|
2020-02-18 06:27:52 +01:00
|
|
|
// Config items
|
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-09-17 18:25:09 +02:00
|
|
|
func Init() error {
|
2020-02-14 21:46:02 +01:00
|
|
|
home, err := homedir.Dir()
|
|
|
|
if err != nil {
|
2020-09-17 18:25:09 +02:00
|
|
|
return err
|
2020-02-14 21:46:02 +01:00
|
|
|
}
|
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-09-17 18:25:09 +02:00
|
|
|
return err
|
2020-02-14 21:46:02 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := os.Create(configPath); err != nil {
|
2020-09-17 18:25:09 +02:00
|
|
|
return err
|
2020-02-14 21:46:02 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-17 18:25:09 +02:00
|
|
|
var cfg config
|
2020-02-14 21:46:02 +01:00
|
|
|
if _, err := toml.DecodeFile(configPath, &cfg); err != nil {
|
2020-09-17 18:25:09 +02:00
|
|
|
return 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-09-17 18:25:09 +02:00
|
|
|
return nil
|
2020-02-14 21:46:02 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func Save() error {
|
2020-09-17 18:25:09 +02:00
|
|
|
cfg := config{
|
|
|
|
Origin: Origin,
|
|
|
|
Upstream: Upstream,
|
|
|
|
Tokens: Tokens,
|
|
|
|
}
|
2020-02-14 21:46:02 +01:00
|
|
|
|
|
|
|
fi, err := os.Create(configPath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := toml.NewEncoder(fi).Encode(cfg); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-09-17 18:25:09 +02:00
|
|
|
return fi.Close()
|
2020-02-14 21:46:02 +01:00
|
|
|
}
|