/
config.go
100 lines (88 loc) · 2.16 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 config
import (
"errors"
"fmt"
"os"
"gopkg.in/yaml.v2"
)
type Configuration struct {
Global map[string]string `yaml:"global"`
Repositories map[string]map[string]string `yaml:"repositories"`
}
type ConfigAPI struct {
configFilePath string
config Configuration
}
func NewConfigAPI(filePath string) *ConfigAPI {
return &ConfigAPI{
configFilePath: filePath,
config: Configuration{
Global: make(map[string]string),
Repositories: make(map[string]map[string]string),
},
}
}
func (c *ConfigAPI) loadConfig() error {
data, err := os.ReadFile(c.configFilePath)
if err != nil {
return err
}
return yaml.Unmarshal(data, &c.config)
}
func (c *ConfigAPI) saveConfig() error {
data, err := yaml.Marshal(c.config)
if err != nil {
return err
}
return os.WriteFile(c.configFilePath, data, os.ModePerm)
}
func (c *ConfigAPI) ListGlobalParameters() error {
if err := c.loadConfig(); err != nil {
return err
}
for key, value := range c.config.Global {
fmt.Printf("%s: %s\n", key, value)
}
return nil
}
func (c *ConfigAPI) GetGlobalParameter(key string) (string, error) {
if err := c.loadConfig(); err != nil {
return "", err
}
value, exists := c.config.Global[key]
if !exists {
return "", errors.New("parameter not found")
}
return value, nil
}
func (c *ConfigAPI) SetGlobalParameter(key string, value string) error {
if err := c.loadConfig(); err != nil {
return err
}
c.config.Global[key] = value
return c.saveConfig()
}
func (c *ConfigAPI) GetRepositoryParameter(repo string, key string) (string, error) {
if err := c.loadConfig(); err != nil {
return "", err
}
params, exists := c.config.Repositories[repo]
if !exists {
return "", errors.New("repository not found")
}
value, exists := params[key]
if !exists {
return "", errors.New("parameter not found")
}
return value, nil
}
func (c *ConfigAPI) SetRepositoryParameter(repo string, key string, value string) error {
if err := c.loadConfig(); err != nil {
return err
}
if _, exists := c.config.Repositories[repo]; !exists {
c.config.Repositories[repo] = make(map[string]string)
}
c.config.Repositories[repo][key] = value
return c.saveConfig()
}