-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
100 lines (79 loc) · 2.18 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
94
95
96
97
98
99
100
package main
import (
"embed"
"encoding/json"
"fmt"
"os"
"strings"
)
const defaultConfigFileName = "defaultConfig.json"
//go:embed defaultConfig.json
var defaultConfigFile embed.FS
//go:embed layouts/default.sh
var defaultLayoutScript string
type LayoutType string
const (
LayoutDefault LayoutType = "default"
)
type Config struct {
ReposBasePath string `json:"reposBasePath"`
Layout LayoutType `json:"layout"`
}
func loadConfig() (Config, error) {
defaultConfig, defaultConfigErr := loadDefaultConfig()
if defaultConfigErr != nil {
return Config{}, fmt.Errorf("error loading default config: %w", defaultConfigErr)
}
validationErr := validateConfig(defaultConfig)
if validationErr != nil {
return Config{}, fmt.Errorf("error validating default config: %w", validationErr)
}
defaultConfig.ReposBasePath = expandPath(defaultConfig.ReposBasePath)
return defaultConfig, nil
}
func loadDefaultConfig() (Config, error) {
var defaultConfig Config
// Read the embedded file
configFileData, err := defaultConfigFile.ReadFile(defaultConfigFileName)
if err != nil {
return Config{}, fmt.Errorf("error reading embedded config file: %w", err)
}
// Decode the configuration from the embedded file data
if err := json.Unmarshal(configFileData, &defaultConfig); err != nil {
return Config{}, fmt.Errorf("error decoding embedded config file: %w", err)
}
return defaultConfig, nil
}
func validateConfig(config Config) error {
if config.ReposBasePath == "" {
return fmt.Errorf("reposBasePath is required")
}
if config.Layout == "" {
return fmt.Errorf("layout is required")
} else {
if err := validateLayout(config.Layout); err != nil {
return fmt.Errorf("error validating layout: %w", err)
}
}
return nil
}
func validateLayout(layout LayoutType) error {
switch layout {
case LayoutDefault:
return nil
default:
return fmt.Errorf(fmt.Sprintf("invalid layout: '%s'", layout))
}
}
func expandPath(path string) string {
log := NewLogUtil()
if strings.Contains(path, "$HOME") {
home, err := os.UserHomeDir()
if err != nil {
log.Negative("Error getting home directory:", err)
return ""
}
return strings.Replace(path, "$HOME", home, 1)
}
return path
}