-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
124 lines (97 loc) · 2.13 KB
/
config.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 medialocker
import (
"os"
"path"
"runtime"
"gopkg.in/ini.v1"
)
type Config struct {
DbPath string
WorkerCnt int
MemDB bool
LogSQL bool
ConfigPath string
LogPath string
ForceColor bool
DisableColor bool
ConsoleLog bool
Bind string
DebugLogging bool
}
var (
EmptyConfig = Config{}
)
type Configuration func(*Config) error
func FileConfiguration(configPath string) Configuration {
if configPath == "" {
configPath = LocalFileSystem().ConfigPath("locker.conf")
}
if LocalFileExists(configPath) {
return func(c *Config) error {
cfg, err := ini.Load(configPath)
if err != nil {
return err
}
cfg.MapTo(c)
return nil
}
} else {
return func(c *Config) error {
fn := DefaultConfiguration()
err := fn(c)
if err != nil {
return err
}
confDir := path.Dir(configPath)
err = LocalFileSystem().MkdirAll(confDir, os.ModeDir|os.ModePerm)
if err != nil {
return err
}
cfgFile, err := LocalFileSystem().Create(configPath)
if err != nil {
return err
}
cfg := ini.Empty()
cfg.ReflectFrom(c)
_, err = cfg.WriteTo(cfgFile)
return err
}
}
}
// DefaultConfiguration will set any unset options a default value
func DefaultConfiguration() Configuration {
return func(c *Config) error {
c.WorkerCnt = runtime.NumCPU()
c.DebugLogging = true
c.ForceColor = true
if c.Bind == EmptyConfig.Bind {
c.Bind = ":3000"
}
if c.ConfigPath == EmptyConfig.ConfigPath {
c.ConfigPath = LocalFileSystem().ConfigPath("locker.conf")
}
if c.LogPath == EmptyConfig.LogPath {
c.LogPath = LocalFileSystem().DataPath("medialocker.log")
}
if c.DbPath == EmptyConfig.DbPath {
c.DbPath = LocalFileSystem().DataPath("data.db")
}
return nil
}
}
func BuildConfig(opts ...Configuration) (Config, []error) {
c := &Config{}
errors := make([]error, 0)
opts = append(opts, DefaultConfiguration())
for _, fn := range opts {
err := fn(c)
if err != nil {
errors = append(errors, err)
}
}
return *c, errors
}
func (c Config) withConfiguration(fn Configuration) (*Config, error) {
err := fn(&c)
return &c, err
}