-
Notifications
You must be signed in to change notification settings - Fork 1
/
loader.go
108 lines (89 loc) · 2.29 KB
/
loader.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
package configuration
import (
"github.com/evg4b/fisherman/internal/constants"
"github.com/evg4b/fisherman/internal/utils"
"github.com/evg4b/fisherman/pkg/log"
"os/user"
"path/filepath"
"github.com/evg4b/fisherman/pkg/shell" // TODO: remove this dependency
"github.com/go-errors/errors"
"github.com/go-git/go-billy/v5"
"github.com/imdario/mergo"
"gopkg.in/yaml.v3"
)
const gitDir = ".git"
func FindConfigFiles(usr *user.User, cwd string, fs billy.Filesystem) (map[string]string, error) {
configs := map[string]string{}
for _, mode := range ModeOptions {
folder, err := GetConfigFolder(usr, cwd, mode)
if err != nil {
return nil, err
}
var files []string
for _, name := range constants.AppConfigNames {
configPath := filepath.Join(folder, name)
exist, err := utils.Exists(fs, configPath)
if err != nil {
return nil, err
}
if exist {
files = append(files, configPath)
}
}
if len(files) > 1 {
return nil, errors.Errorf("more then one config file specifies in folder '%s'", folder)
}
if len(files) == 1 {
configs[mode] = files[0]
}
}
return configs, nil
}
func GetConfigFolder(usr *user.User, cwd, mode string) (string, error) {
switch mode {
case LocalMode:
return filepath.Join(cwd, gitDir), nil
case RepoMode:
return cwd, nil
case GlobalMode:
return usr.HomeDir, nil
default:
return "", errors.New("unknown config mode")
}
}
func Load(fs billy.Filesystem, files map[string]string) (*FishermanConfig, error) {
config := FishermanConfig{
Output: log.DefaultOutputConfig,
DefaultShell: shell.Default().GetName(),
}
for _, mode := range ModeOptions {
file, ok := files[mode]
if ok {
loadedConfig, err := unmarshalFile(fs, file)
if err != nil {
return &config, err
}
err = mergo.MergeWithOverwrite(&config, loadedConfig)
if err != nil {
return &config, err
}
}
}
// TODO: incorrect log level margin
return &config, nil
}
func unmarshalFile(fs billy.Filesystem, path string) (*FishermanConfig, error) {
var config FishermanConfig
file, err := fs.Open(path)
if err != nil {
return nil, errors.Errorf("open %s: %w", path, err)
}
defer file.Close()
decoder := yaml.NewDecoder(file)
decoder.KnownFields(true)
err = decoder.Decode(&config)
if err != nil {
return nil, err
}
return &config, nil
}