-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseConfig.go
More file actions
88 lines (74 loc) · 2.22 KB
/
parseConfig.go
File metadata and controls
88 lines (74 loc) · 2.22 KB
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
package main
import (
_ "embed"
"encoding/json"
"log"
"os"
"path/filepath"
"strings"
)
//go:embed defaultConfig.json
var defaultConfig []byte
// Holds info for a defined "color"
type Color struct {
Hex string `json:"hex"`
RGB string `json:"rgb"`
HSL string `json:"hsl"`
RGBA string `json:"rgba"`
HexTrans string `json:"hexTrans"`
}
// Holds info about a config that needs to be updated
type ServiceConfig struct {
Path string `json:"path"`
Restart string `json:"restart,omitempty"`
Name string `json:"name"`
}
type Config struct {
Colors map[string]Color `json:"colors"`
ConfigFiles []ServiceConfig `json:"configs"`
}
// expandPath expands a path that starts with "~/" into the full absolute path
// ex: ~/ would become /home/user/
func expandPath(path string) string {
if strings.HasPrefix(path, "~/") {
homeDir, err := os.UserHomeDir()
if err != nil {
log.Fatalf("Unable to get home directory: %v\n", err)
}
return filepath.Join(homeDir, path[2:])
}
return path
}
func parseConfig(flags Flags) Config {
configPath := expandPath(flags.ConfigPath)
config, err := os.ReadFile(configPath)
if err != nil {
// If using default path, create the default config there.
if flags.ConfigPath == "~/.config/palettro/config.json" {
log.Println("No file found at default path, creating default config.")
if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
log.Fatalf("Unable to create config directory: %v\n", err)
}
if err := os.WriteFile(configPath, defaultConfig, 0644); err != nil {
log.Fatalf("Unable to write config file: %v\n", err)
}
config = defaultConfig
} else {
log.Fatalf("[ENOENT]: Unable to read config file at \"%s\"\n", flags.ConfigPath)
}
}
var parsedConfig Config
if err := json.Unmarshal(config, &parsedConfig); err != nil {
log.Fatalf("Unable to parse config file: %v\n", err)
}
// Validate that all color names are lowercase
for key := range parsedConfig.Colors {
if key != strings.ToLower(key) {
log.Fatalf("Config error: Color name '%s' must be lowercase", key)
}
}
for _, v := range parsedConfig.ConfigFiles {
os.MkdirAll(expandPath("~/.config/palettro/"+strings.ToLower(v.Name)), 0755)
}
return parsedConfig
}