-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
124 lines (95 loc) · 2.48 KB
/
loader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package config
import (
goErrors "errors"
"os"
"path"
"path/filepath"
"github.com/comunidade-shallom/peristera/pkg/support"
"github.com/comunidade-shallom/peristera/pkg/support/errors"
"github.com/creasty/defaults"
"github.com/kkyr/fig"
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v3"
)
var (
ErrFailToLoadConfig = errors.System(nil, "fail to load config", "CONF:001")
ErrFailEnsureConfig = errors.System(nil, "fail to ensure config", "CONF:002")
ConfigFileWasCreated = errors.Business("a new config file was created (%s)", "CONF:003")
ErrMissingTelegramToken = errors.System(nil, "missing telegram token", "CONF:004")
ErrMissingYoutubeToken = errors.System(nil, "missing youtube token", "CONF:005")
)
func Load(file string) (AppConfig, error) {
var err error
cfg := AppConfig{}
if file != "" {
err = fig.Load(&cfg,
fig.File(filepath.Base(file)),
fig.Dirs(filepath.Dir(file)),
)
if err != nil {
return cfg, ErrFailToLoadConfig.WithErr(err)
}
return applyDefaults(cfg)
}
home, err := homedir.Dir()
if err != nil {
return cfg, ErrFailToLoadConfig.WithErr(err)
}
err = fig.Load(&cfg,
fig.File("peristera.yml"),
fig.Dirs(
".",
path.Join(home, ".peristera"),
path.Join(home, ".config"),
path.Join(home, ".config/peristera"),
home,
"/etc/peristera",
"/peristera.d",
support.GetBinDirPath(),
),
)
if goErrors.Is(err, fig.ErrFileNotFound) {
return ensureConfig()
}
if err != nil {
return cfg, err
}
return applyDefaults(cfg)
}
func applyDefaults(cfg AppConfig) (AppConfig, error) {
if cfg.Telegram.Token == "" {
cfg.Telegram.Token = os.Getenv("TELEGRAM_TOKEN")
}
if cfg.Youtube.Token == "" {
cfg.Youtube.Token = os.Getenv("YOUTUBE_TOKEN")
}
if cfg.Telegram.Token == "" {
return cfg, ErrMissingTelegramToken
}
if cfg.Youtube.Token == "" {
return cfg, ErrMissingYoutubeToken
}
return cfg, nil
}
func ensureConfig() (AppConfig, error) {
var err error
cfg := AppConfig{}
if err = defaults.Set(&cfg); err != nil {
return cfg, ErrFailEnsureConfig.WithErr(err)
}
cfg, err = applyDefaults(cfg)
if err != nil {
return cfg, ErrFailEnsureConfig.WithErr(err)
}
buf, err := yaml.Marshal(cfg)
if err != nil {
return cfg, ErrFailEnsureConfig.WithErr(err)
}
pwd, _ := os.Getwd()
configFile := path.Join(pwd, "peristera.yml")
err = os.WriteFile(configFile, buf, os.ModePerm)
if err != nil {
return cfg, ErrFailEnsureConfig.WithErr(err)
}
return cfg, ConfigFileWasCreated.Msgf(configFile)
}