-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
74 lines (62 loc) · 1.77 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
package main
import (
"encoding/json"
"flag"
"io/ioutil"
"path"
"path/filepath"
log "github.com/sirupsen/logrus"
)
// Config defines the available set of configuration options available for the
// service.
type Config struct {
GameDirectory string
WorkingRoot string
BotToken string
BotTokenFile string
Admins []string
}
// ParseConfigFile attempts to load a Config struct, using the data in a JSON
// file.
func ParseConfigFile(configFile string, logger log.FieldLogger) (config *Config, err error) {
// always return an empty config, rather than nil!
config = &Config{}
if len(configFile) == 0 {
return
}
logger.WithFields(log.Fields{
"component": "config",
"file": configFile,
}).Info("loading config")
byts, err := ioutil.ReadFile(configFile)
if err != nil {
return
}
err = json.Unmarshal(byts, &config)
if err != nil {
return
}
// Make sure any file paths are resolved relative to the config file.
// These need to be absolute paths if possible, because we will sometimes
// run executables (the game interpreter) from different directories
absConfig, err := filepath.Abs(configFile)
if err != nil {
logger.WithError(err).Error("getting config file absolute path")
return
}
configDir := filepath.Dir(absConfig)
absolutize(configDir, &config.GameDirectory)
absolutize(configDir, &config.WorkingRoot)
absolutize(configDir, &config.BotTokenFile)
return
}
func absolutize(baseDir string, relative *string) {
if relative != nil && *relative != "" && !path.IsAbs(*relative) {
*relative = path.Join(baseDir, *relative)
}
}
// AddConfigFlag adds the standard "-config" command-line flag for users of
// this package.
func AddConfigFlag() *string {
return flag.String("config", "", "The path to the JSON config file to load")
}