-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
126 lines (112 loc) · 2.64 KB
/
main.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"github.com/labstack/gommon/log"
"github.com/urfave/cli/v2"
"gopkg.in/yaml.v3"
)
var version = "v0.0.1"
func main() {
app := &cli.App{
Name: "yaml-merge",
Usage: "Merge multiple YAML files",
Version: version,
Authors: []*cli.Author{
{
Name: "NinjaOps by raftech.io",
Email: "[email protected]",
},
},
Flags: []cli.Flag{
&cli.StringSliceFlag{
Name: "input",
Aliases: []string{"i"},
Usage: "Input YAML files to merge",
},
&cli.StringFlag{
Name: "output",
Aliases: []string{"o"},
Usage: "Output file path for merged YAML",
},
},
Action: func(c *cli.Context) error {
// Read input files
inputFiles := c.StringSlice("input")
if len(inputFiles) <= 0 {
return cli.ShowAppHelp(c)
}
mergedData, err := MergeYAML(inputFiles...)
if err != nil {
return err
}
// Write merged data to output file
outputFile := c.String("output")
if outputFile != "" {
if err := ioutil.WriteFile(outputFile, mergedData, 0644); err != nil {
return err
}
} else {
// Print merged data to console
fmt.Println(string(mergedData))
}
return nil
},
}
if err := app.Run(os.Args); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func mergeMaps(dst, src map[string]interface{}) {
for k, v := range src {
if _, ok := dst[k]; !ok {
// key does not exist in dst, just copy from src
dst[k] = v
continue
}
// key exists in both dst and src, need to merge recursively
dstValue := dst[k]
switch dstValue := dstValue.(type) {
case map[string]interface{}:
srcValue, ok := v.(map[string]interface{})
if !ok {
// type mismatch, just copy from src
dst[k] = v
continue
}
mergeMaps(dstValue, srcValue)
default:
// type mismatch or dst has scalar value, just copy from src
dst[k] = v
continue
}
}
}
func MergeYAML(filenames ...string) ([]byte, error) {
if len(filenames) <= 0 {
return nil, errors.New("You must provide at least one filename for reading Values")
}
resultValues := make(map[string]interface{})
for _, filename := range filenames {
var override map[string]interface{}
bs, err := ioutil.ReadFile(filename)
if err != nil {
log.Info(err)
return nil, fmt.Errorf("failed to read file %q: %w", filename, err)
}
if err := yaml.Unmarshal(bs, &override); err != nil {
log.Info(err)
return nil, fmt.Errorf("failed to unmarshal data from file %q: %w", filename, err)
}
mergeMaps(resultValues, override)
}
bs, err := yaml.Marshal(resultValues)
if err != nil {
log.Info(err)
return nil, err
}
return bs, nil
}