-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
91 lines (74 loc) · 2.52 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
package tusk
// This file contains our configuration logic
import (
"bufio"
"bytes"
"errors"
"github.com/BurntSushi/toml"
"github.com/JoshStrobl/trunk"
"io/ioutil"
"path/filepath"
)
// ConfigFoundPath is the directory we found the config in
var ConfigFoundPath string
// ReadConfig will read our narwhal configuration, if it exists, and return it
func ReadConfig() (NarwhalConfig, error) {
var config NarwhalConfig
var readErr error
for index, dir := range Paths { // Search each path
tomlPath := filepath.Join(dir, "config.toml")
if configBytes, readErr := ioutil.ReadFile(tomlPath); readErr == nil { // If we successfully read the file
if len(configBytes) > 0 { // If file is not empty
decodeErr := toml.Unmarshal(configBytes, &config)
if decodeErr == nil { // No error during unmarshal
ConfigFoundPath = tomlPath
config = SetDefaults(config) // Enforce config defaults
} else {
readErr = decodeErr
break
}
break
} else {
trunk.LogFatal("config cannot be empty")
}
} else { // Failed to read the file
if index == (len(Paths) - 1) { // Last file being read
readErr = errors.New("Failed to find Narwhal's config.toml in any recognized location.")
}
}
}
return config, readErr
}
// SaveConfig will save the config in our previously recognized location
func SaveConfig() {
var saveErr error
var buffer bytes.Buffer
writer := bufio.NewWriter(&buffer)
encoder := toml.NewEncoder(writer) // Create a new toml encoder
encoder.Indent = "\t" // Use a tab because we're opinionated
if saveErr = encoder.Encode(Config); saveErr == nil { // Encode our Config into a buffer
saveErr = ioutil.WriteFile(ConfigFoundPath, buffer.Bytes(), 0644) // Write the config
}
if saveErr != nil {
trunk.LogWarn("Failed to update the configuration: " + saveErr.Error())
}
}
// SetDefaults will set the defaults for the provided NarwhalConfig
func SetDefaults(config NarwhalConfig) NarwhalConfig {
if config.Name == "" {
config.Name = "Narwhal Bot"
}
if config.Network == "" {
config.Network = "chat.libera.chat" // Default to freenode
}
if config.Port == 0 {
config.Port = 6667 // Default to 6667
}
if config.Plugins.AutoKick.MinimumKickToBanCount <= 0 { // Not a reasonable amount (if you want to immediately ban someone, use the ban function)
config.Plugins.AutoKick.MinimumKickToBanCount = 3
}
if config.Plugins.Replacer.CachedMessageLimit == 0 { // Can't have a cache limit of 0
config.Plugins.Replacer.CachedMessageLimit = 10 // Set to 10
}
return config
}