-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsavior.go
More file actions
85 lines (81 loc) · 1.94 KB
/
savior.go
File metadata and controls
85 lines (81 loc) · 1.94 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
package figtree
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"github.com/go-ini/ini"
"gopkg.in/yaml.v3"
)
func (tree *figTree) ReadFrom(path string) error {
_, fileErr := os.Stat(path)
if os.IsNotExist(fileErr) || os.IsPermission(fileErr) {
return fileErr
}
return tree.loadFile(path)
}
func (tree *figTree) SaveTo(path string) error {
var properties = make(map[string]interface{})
tree.mu.Lock()
defer tree.mu.Unlock()
for name, fig := range tree.figs {
valueAny, ok := tree.values.Load(name)
if !ok {
return errors.Join(fig.Error, fmt.Errorf("failed to load %s", fig.name))
}
_value, ok := valueAny.(*Value)
if !ok {
return errors.Join(fig.Error, fmt.Errorf("failed to cast %s as *Value ; got %T", fig.name, valueAny))
}
switch v := _value.Value.(type) {
case MapFlag:
properties[name] = v.values
case *MapFlag:
properties[name] = v.values
case ListFlag:
properties[name] = v.values
case *ListFlag:
properties[name] = v.values
default:
properties[name] = _value.Value
}
}
formatValue := func(val interface{}) string {
return fmt.Sprintf("%v", val)
}
ext := filepath.Ext(path)
switch ext {
case ".yaml", ".yml":
yamlBytes, yamlErr := yaml.Marshal(properties)
if yamlErr != nil {
return yamlErr
}
return os.WriteFile(path, yamlBytes, 0644)
case ".json":
jsonBytes, jsonErr := json.MarshalIndent(properties, "", " ")
if jsonErr != nil {
return jsonErr
}
return os.WriteFile(path, jsonBytes, 0644)
case ".ini":
cfg := ini.Empty()
for key, value := range properties {
switch v := value.(type) {
case map[string]interface{}:
section, err := cfg.NewSection(key)
if err != nil {
return err
}
for sk, sv := range v {
section.Key(sk).SetValue(formatValue(sv))
}
default:
cfg.Section("").Key(key).SetValue(formatValue(value))
}
}
return cfg.SaveTo(path)
default:
return errors.New("invalid file extension provided")
}
}