1
0
mirror of https://gitea.com/jolheiser/sip synced 2024-11-22 19:51:58 +01:00
sip/config/config.go

80 lines
1.3 KiB
Go
Raw Normal View History

package config
import (
"fmt"
"os"
"path"
"github.com/BurntSushi/toml"
"github.com/mitchellh/go-homedir"
)
var (
configPath string
// Config items
Origin string
Upstream string
Tokens []Token
)
type config struct {
Origin string `toml:"origin"`
Upstream string `toml:"upstream"`
Tokens []Token `toml:"token"`
}
type Token struct {
Name string `toml:"name"`
URL string `toml:"url"`
Token string `toml:"token"`
}
// Load on init so that CLI contexts are correctly populated
func Init() error {
home, err := homedir.Dir()
if err != nil {
return err
}
configPath = fmt.Sprintf("%s/.sip/config.toml", home)
if _, err := os.Stat(configPath); os.IsNotExist(err) {
if err := os.MkdirAll(path.Dir(configPath), os.ModePerm); err != nil {
return err
}
if _, err := os.Create(configPath); err != nil {
return err
}
}
var cfg config
if _, err := toml.DecodeFile(configPath, &cfg); err != nil {
return err
}
Origin = cfg.Origin
Upstream = cfg.Upstream
Tokens = cfg.Tokens
return nil
}
func Save() error {
cfg := config{
Origin: Origin,
Upstream: Upstream,
Tokens: Tokens,
}
fi, err := os.Create(configPath)
if err != nil {
return err
}
if err := toml.NewEncoder(fi).Encode(cfg); err != nil {
return err
}
return fi.Close()
}