-
Notifications
You must be signed in to change notification settings - Fork 9
/
load.go
123 lines (104 loc) 路 2.2 KB
/
load.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package config
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/Equationzhao/g/internal/util"
"gopkg.in/yaml.v3"
)
const (
NoConfig = "-no-config"
DefaultConfigFile = "g.yaml"
)
func GetUserConfigDir() (string, error) {
err := InitConfigDir.Do(
func() error {
home, err := os.UserConfigDir()
if err != nil {
return err
}
Dir = filepath.Join(home, "g")
err = os.MkdirAll(Dir, os.ModePerm)
if err != nil {
return err
}
return nil
},
)
if err != nil {
return "", err
}
return Dir, nil
}
var (
InitConfigDir util.Once
Dir = ""
)
// READ config
// g.yaml
// Args:
// - args
// - ...
type Config struct {
Args []string `yaml:"Args"`
CustomTreeStyle TreeStyle `yaml:"CustomTreeStyle"`
ThemeLocation string `yaml:"Theme"`
}
type TreeStyle struct {
Child string `yaml:"Child"`
LastChild string `yaml:"LastChild"`
Mid string `yaml:"Mid"`
Empty string `yaml:"Empty"`
}
func (t TreeStyle) IsEmpty() bool {
return t.Empty == "" && t.Child == "" && t.LastChild == "" && t.Mid == ""
}
func (t TreeStyle) IsEnabled() bool {
return !t.IsEmpty()
}
type ErrReadConfig struct {
error
Location string
}
func (e ErrReadConfig) Error() string {
if e.Location != "" {
return fmt.Sprintf("failed to load configuration at %s: %s", e.Location, e.error.Error())
}
return fmt.Sprintf("failed to load configuration: %s", e.error.Error())
}
var Default = Config{
Args: make([]string, 0),
}
var emptyConfig = Config{}
func Load() (*Config, error) {
Dir, err := GetUserConfigDir()
if err != nil {
return nil, ErrReadConfig{error: err}
}
location := filepath.Join(Dir, DefaultConfigFile)
content, err := os.ReadFile(location)
if err != nil {
return nil, err
}
// parse yaml
configErr := yaml.Unmarshal(content, &Default)
if configErr != nil {
return nil, ErrReadConfig{error: configErr, Location: location}
}
for i, v := range Default.Args {
if v == NoConfig {
Default = emptyConfig
return nil, nil
}
// if not prefixed with '-', add '-'
if !strings.HasPrefix(v, "-") {
if len(v) == 1 {
Default.Args[i] = "-" + v
} else {
Default.Args[i] = "--" + v
}
}
}
return &Default, nil
}