55 lines
936 B
Go
55 lines
936 B
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path"
|
|
"strings"
|
|
|
|
"github.com/go-yaml/yaml"
|
|
)
|
|
|
|
func LoadConfig(filePath string) (*Config, error) {
|
|
cfg := Config{}
|
|
|
|
isDefaultConfig := filePath == DefaultConfigPath
|
|
|
|
if strings.HasPrefix(filePath, "~") {
|
|
if v, ok := os.LookupEnv("HOME"); ok {
|
|
filePath = strings.Replace(filePath, "~", v, 1)
|
|
} else {
|
|
return nil, fmt.Errorf("$HOME not set in env")
|
|
}
|
|
}
|
|
|
|
if _, err := os.Stat(filePath); errors.Is(err, os.ErrNotExist) {
|
|
if isDefaultConfig {
|
|
dir, _ := path.Split(filePath)
|
|
err := os.MkdirAll(dir, os.ModePerm)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = os.WriteFile(filePath, []byte(DefaultConfig), 0644)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return &cfg, nil
|
|
}
|
|
|
|
data, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = yaml.Unmarshal([]byte(data), &cfg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &cfg, nil
|
|
}
|