diff options
Diffstat (limited to 'src/config.go')
-rw-r--r-- | src/config.go | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/src/config.go b/src/config.go new file mode 100644 index 0000000..1b4a998 --- /dev/null +++ b/src/config.go | |||
@@ -0,0 +1,90 @@ | |||
1 | package src | ||
2 | |||
3 | import ( | ||
4 | "fmt" | ||
5 | "os" | ||
6 | "path/filepath" | ||
7 | "runtime" | ||
8 | |||
9 | "github.com/BurntSushi/toml" | ||
10 | ) | ||
11 | |||
12 | type Config struct { | ||
13 | BaseURL string | ||
14 | Username string | ||
15 | Password string | ||
16 | } | ||
17 | |||
18 | func LoadConfigFromFile(filename string) (*Config, error) { | ||
19 | var cfg Config | ||
20 | _, err := toml.DecodeFile(filename, &cfg) | ||
21 | |||
22 | return &cfg, err | ||
23 | } | ||
24 | |||
25 | func LoadDefaultConfig() (*Config, error) { | ||
26 | path, err := getConfigFilePath() | ||
27 | if err != nil { | ||
28 | return nil, err | ||
29 | } | ||
30 | |||
31 | f, err := os.Open(path) | ||
32 | if err != nil && !os.IsNotExist(err) { | ||
33 | return nil, err | ||
34 | } else if os.IsNotExist(err) { | ||
35 | return &Config{}, nil | ||
36 | } | ||
37 | f.Close() | ||
38 | |||
39 | return LoadConfigFromFile(path) | ||
40 | } | ||
41 | |||
42 | func getConfigFilePath() (string, error) { | ||
43 | path := "" | ||
44 | if runtime.GOOS == "linux" { | ||
45 | configDir := os.Getenv("XDG_CONFIG_DIR") | ||
46 | if configDir == "" { | ||
47 | home := os.Getenv("HOME") | ||
48 | if home == "" { | ||
49 | return "", fmt.Errorf("could not determine where to store configuration") | ||
50 | } | ||
51 | |||
52 | path = filepath.Join(home, ".config") | ||
53 | os.MkdirAll(path, os.ModeDir.Perm()) | ||
54 | |||
55 | path = filepath.Join(path, "termsonic.toml") | ||
56 | } else { | ||
57 | path = filepath.Join(configDir, "termsonic.toml") | ||
58 | } | ||
59 | } else if runtime.GOOS == "windows" { | ||
60 | appdata := os.Getenv("APPDATA") | ||
61 | if appdata == "" { | ||
62 | return "", fmt.Errorf("could not find %%APPDATA%%") | ||
63 | } | ||
64 | |||
65 | path = filepath.Join(appdata, "Termsonic") | ||
66 | os.MkdirAll(path, os.ModeDir.Perm()) | ||
67 | |||
68 | path = filepath.Join(path, "termsonic.toml") | ||
69 | } else { | ||
70 | return "", fmt.Errorf("unsupported operating system: %s", runtime.GOOS) | ||
71 | } | ||
72 | |||
73 | return path, nil | ||
74 | } | ||
75 | |||
76 | func (c *Config) Save() error { | ||
77 | path, err := getConfigFilePath() | ||
78 | if err != nil { | ||
79 | return err | ||
80 | } | ||
81 | |||
82 | f, err := os.Create(path) | ||
83 | if err != nil { | ||
84 | return err | ||
85 | } | ||
86 | defer f.Close() | ||
87 | |||
88 | enc := toml.NewEncoder(f) | ||
89 | return enc.Encode(*c) | ||
90 | } | ||