95 lines
1.7 KiB
Go
95 lines
1.7 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"gitea.micah.wiki/pandora/naive/pkg/filex"
|
|
)
|
|
|
|
type Config struct {
|
|
ShellConfig string `yaml:"shell_config" toml:"shell_config" json:"shell_config"`
|
|
Nginx []*Nginx `yaml:"nginx" toml:"nginx" json:"nginx"`
|
|
AcmeShs []*AcmeSh `yaml:"acme_sh" toml:"acme_sh" json:"acme_sh"`
|
|
}
|
|
|
|
var (
|
|
config *Config
|
|
configTypes = []string{"yaml", "toml", "json"}
|
|
fileName = ""
|
|
configType = ""
|
|
)
|
|
|
|
func init() {
|
|
homeDir, _ := os.UserHomeDir()
|
|
for _, cType := range configTypes {
|
|
name := fmt.Sprintf("%s/.magic/config.%s", homeDir, cType)
|
|
exist, err := filex.Exists(name)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if exist {
|
|
fileName = name
|
|
configType = cType
|
|
break
|
|
}
|
|
}
|
|
conf, err := parseByType()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
config = conf
|
|
}
|
|
|
|
func parseByType() (*Config, error) {
|
|
conf := &Config{}
|
|
switch configType {
|
|
case "yaml":
|
|
err := filex.ParseYAML(fileName, conf)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
case "toml":
|
|
err := filex.ParseTOML(fileName, conf)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
case "json":
|
|
err := filex.ParseJSON(fileName, conf)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return conf, nil
|
|
}
|
|
|
|
func Save(conf *Config) error {
|
|
if configType == "" {
|
|
configType = "yaml"
|
|
homeDir, _ := os.UserHomeDir()
|
|
fileName = fmt.Sprintf("%s/.magic/config.%s", homeDir, configType)
|
|
}
|
|
switch configType {
|
|
case "yaml":
|
|
err := filex.GenerateYAML(fileName, conf)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
case "toml":
|
|
err := filex.ParseTOML(fileName, conf)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
case "json":
|
|
err := filex.ParseJSON(fileName, conf)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func Get() *Config {
|
|
return config
|
|
}
|