/
config.go
61 lines (50 loc) · 1.24 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
package config
import (
"errors"
"os"
"path/filepath"
"github.com/fingcloud/cli/pkg/api"
"github.com/fingcloud/cli/pkg/config/encoding"
)
var (
ErrConfigFileNotFound = errors.New("fing config file not found")
configFiles = []string{
"fing.yaml",
"fing.yml",
"fing.json",
"fing.toml",
}
)
func findConfigFile(path string) (string, error) {
for _, configFile := range configFiles {
configPath := filepath.Join(path, configFile)
if _, err := os.Stat(configPath); os.IsNotExist(err) {
continue
}
return configPath, nil
}
return "", ErrConfigFileNotFound
}
// ReadAppConfig reads config file from path
func ReadAppConfig(path string) (*api.AppConfig, error) {
configPath, err := findConfigFile(path)
if err != nil {
return nil, err
}
bytes, err := os.ReadFile(configPath)
if err != nil {
return nil, err
}
cfg := new(api.AppConfig)
err = encoding.Decode(filepath.Ext(configPath)[1:], bytes, cfg)
return cfg, err
}
// WriteAppConfig writes config file to path
func WriteAppConfig(path, filename string, cfg *api.AppConfig) error {
bytes, err := encoding.Encode(filepath.Ext(filename)[1:], cfg)
if err != nil {
return err
}
configPath := filepath.Join(path, filename)
return os.WriteFile(configPath, bytes, 0644)
}