-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
109 lines (87 loc) · 2.28 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
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
package parser
import (
"bufio"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
)
// ConfigDoc is an input document to be checked
type ConfigDoc struct {
ReadCloser io.ReadCloser
Filepath string
Parser Parser
}
// GetConfigurations parses and returns the configurations given in the file list
func GetConfigurations(ctx context.Context, input string, fileList []string) (map[string]interface{}, error) {
var fileConfigs []ConfigDoc
for _, fileName := range fileList {
var config io.ReadCloser
config, err := getConfig(fileName)
if err != nil {
return nil, fmt.Errorf("get config: %w", err)
}
fileType := getFileType(fileName, input)
parser, err := GetParser(fileType)
if err != nil {
return nil, fmt.Errorf("get parser: %w", err)
}
configDoc := ConfigDoc{
ReadCloser: config,
Filepath: fileName,
Parser: parser,
}
fileConfigs = append(fileConfigs, configDoc)
}
unmarshaledConfigs, err := bulkUnmarshal(fileConfigs)
if err != nil {
return nil, fmt.Errorf("bulk unmarshal: %w", err)
}
return unmarshaledConfigs, nil
}
func bulkUnmarshal(configList []ConfigDoc) (map[string]interface{}, error) {
configContents := make(map[string]interface{})
for _, config := range configList {
contents, err := ioutil.ReadAll(config.ReadCloser)
if err != nil {
return nil, fmt.Errorf("read config: %w", err)
}
var singleContent interface{}
if err := config.Parser.Unmarshal(contents, &singleContent); err != nil {
return nil, fmt.Errorf("parser unmarshal: %w", err)
}
configContents[config.Filepath] = singleContent
config.ReadCloser.Close()
}
return configContents, nil
}
func getConfig(fileName string) (io.ReadCloser, error) {
if fileName == "-" {
config := ioutil.NopCloser(bufio.NewReader(os.Stdin))
return config, nil
}
filePath, err := filepath.Abs(fileName)
if err != nil {
return nil, fmt.Errorf("get abs: %w", err)
}
config, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("open file: %w", err)
}
return config, nil
}
func getFileType(fileName string, input string) string {
if input != "" {
return input
}
if fileName == "-" {
return "yaml"
}
if filepath.Ext(fileName) == "" {
return filepath.Base(fileName)
}
fileExtension := filepath.Ext(fileName)
return fileExtension[1:]
}