-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
93 lines (76 loc) · 2.08 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
package main
import (
"fmt"
"os"
"github.com/BurntSushi/toml"
"github.com/nolanlum/tanya/irc"
"github.com/nolanlum/tanya/token"
)
type slack struct {
Token string
}
// Config holds configuration data for Tanya
type Config struct {
Gateway []GatewayInstance
}
// SetDefaults overwrites config entries with their default values
func (c *Config) SetDefaults() {
for i := range c.Gateway {
c.Gateway[i].SetDefaults()
}
}
// GatewayInstance holds configuration data for a single IRC<->Slack bridge instance
type GatewayInstance struct {
Slack slack
IRC irc.Config
}
// SetDefaults overwrites config entries with their default values
func (g *GatewayInstance) SetDefaults() {
g.IRC.SetDefaults()
}
// LoadConfig parses a config if it exists, or generates a new one
func LoadConfig(configPath string, disableConfigGen bool) (*Config, error) {
tomlData, err := os.ReadFile(configPath)
if !disableConfigGen && os.IsNotExist(err) {
fmt.Println("config.toml does not exist, generating one...")
return initializeConfig()
} else if err != nil {
return nil, err
}
return parseConfig(string(tomlData))
}
// initializeConfig interactively generates and writes a config
func initializeConfig() (*Config, error) {
var conf Config
conf.SetDefaults()
slackToken, err := token.GetSlackToken()
if err != nil {
return nil, err
}
conf.Gateway = []GatewayInstance{{Slack: slack{Token: slackToken}}}
fmt.Print("Writing config.toml...")
f, err := os.Create("config.toml")
if err != nil {
return nil, err
}
defer f.Close()
if err := toml.NewEncoder(f).Encode(conf); err != nil {
return nil, err
}
fmt.Println("Done")
return &conf, nil
}
// parseConfig reads a toml string and returns a parsed config
func parseConfig(tomlData string) (*Config, error) {
var conf Config
// Parse the config once to populate list fields
if _, err := toml.Decode(tomlData, &conf); err != nil {
return nil, err
}
// Re-parse the config to make sure defaults for each GatewayInstance are set
conf.SetDefaults()
if _, err := toml.Decode(tomlData, &conf); err != nil {
return nil, err
}
return &conf, nil
}