/
reader.go
93 lines (85 loc) · 2.17 KB
/
reader.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
package reader
import (
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/aquaproj/aqua/v2/pkg/config"
"github.com/aquaproj/aqua/v2/pkg/config/aqua"
"github.com/aquaproj/aqua/v2/pkg/osfile"
"github.com/spf13/afero"
"gopkg.in/yaml.v2"
)
var errHomeDirEmpty = errors.New("failed to get a user home directory")
type ConfigReader struct {
fs afero.Fs
homeDir string
}
func New(fs afero.Fs, param *config.Param) *ConfigReader {
return &ConfigReader{
fs: fs,
homeDir: param.HomeDir,
}
}
const homePrefix = "$HOME" + string(os.PathSeparator)
func (r *ConfigReader) Read(configFilePath string, cfg *aqua.Config) error {
file, err := r.fs.Open(configFilePath)
if err != nil {
return err //nolint:wrapcheck
}
defer file.Close()
if err := yaml.NewDecoder(file).Decode(cfg); err != nil {
return fmt.Errorf("parse a configuration file as YAML %s: %w", configFilePath, err)
}
var configFileDir string
for _, rgst := range cfg.Registries {
if rgst.Type == "local" {
if strings.HasPrefix(rgst.Path, homePrefix) {
if r.homeDir == "" {
return errHomeDirEmpty
}
rgst.Path = filepath.Join(r.homeDir, rgst.Path[6:])
}
if configFileDir == "" {
configFileDir = filepath.Dir(configFilePath)
}
rgst.Path = osfile.Abs(configFileDir, rgst.Path)
}
}
if err := r.readImports(configFilePath, cfg); err != nil {
return fmt.Errorf("read imports (%s): %w", configFilePath, err)
}
return nil
}
func (r *ConfigReader) readImports(configFilePath string, cfg *aqua.Config) error {
pkgs := []*aqua.Package{}
for _, pkg := range cfg.Packages {
if pkg == nil {
continue
}
if pkg.Import == "" {
pkgs = append(pkgs, pkg)
continue
}
p := filepath.Join(filepath.Dir(configFilePath), pkg.Import)
filePaths, err := afero.Glob(r.fs, p)
if err != nil {
return fmt.Errorf("read files with glob pattern (%s): %w", p, err)
}
sort.Strings(filePaths)
for _, filePath := range filePaths {
subCfg := &aqua.Config{}
if err := r.Read(filePath, subCfg); err != nil {
return err
}
for _, pkg := range subCfg.Packages {
pkg.FilePath = filePath
pkgs = append(pkgs, pkg)
}
}
}
cfg.Packages = pkgs
return nil
}