-
Notifications
You must be signed in to change notification settings - Fork 0
/
input.go
112 lines (96 loc) · 2.02 KB
/
input.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
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
)
type InputMap map[string]interface{}
func buildInput(inputFiles []string) (InputMap, error) {
result := InputMap{}
for k, v := range getEnvs() {
result[k] = v
}
for _, inputFile := range inputFiles {
if err := loadFile(result, inputFile); err != nil {
return nil, err
}
}
return result, nil
}
func getEnvs() map[string]string {
envs := make(map[string]string)
for _, env := range os.Environ() {
pair := strings.Split(env, "=")
envs[pair[0]] = pair[1]
}
return envs
}
func loadFile(dest InputMap, fpath string) error {
switch filepath.Ext(fpath) {
case ".json":
return readAndUnmarshal(json.Unmarshal, dest, fpath)
case ".yaml", ".yml":
return readAndUnmarshal(yaml.Unmarshal, dest, fpath)
case ".env":
return loadEnvFile(dest, fpath)
default:
return fmt.Errorf("unsupported file type: %s", fpath)
}
}
func readAndUnmarshal(unmarshalFunc func([]byte, interface{}) error, dest InputMap, fpath string) error {
f, err := os.Open(fpath)
if err != nil {
return err
}
defer f.Close()
b, err := io.ReadAll(f)
if err != nil {
return err
}
var data InputMap
if err := unmarshalFunc(b, &data); err != nil {
return err
}
for k, v := range data {
oldVal, ok := dest[k]
if ok {
fmt.Fprintf(os.Stderr, "Overwriting %s: %s -> %s by %s\n", k, oldVal, v, fpath)
}
dest[k] = v
}
return nil
}
func loadEnvFile(dest InputMap, fpath string) error {
f, err := os.Open(fpath)
if err != nil {
return err
}
defer f.Close()
envs := make(InputMap)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
envs[parts[0]] = ""
} else {
envs[parts[0]] = parts[1]
}
}
if err := scanner.Err(); err != nil {
return err
}
for k, v := range envs {
oldVal, ok := dest[k]
if ok {
fmt.Printf("[WARN] Overwriting %s: %s -> %s by %s\n", k, oldVal, v, fpath)
}
dest[k] = v
}
return nil
}