forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_config.go
109 lines (91 loc) · 2.14 KB
/
generate_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 main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
"text/template"
"github.com/pkg/errors"
)
const defaultGlob = "module/*/_meta/config*.yml.tpl"
var (
goos = flag.String("os", runtime.GOOS, "generate config specific to the specified operating system")
reference = flag.Bool("ref", false, "generate a reference config")
concat = flag.Bool("concat", false, "concatenate all configs instead writing individual files")
)
func findConfigFiles(globs []string) ([]string, error) {
var configFiles []string
for _, glob := range globs {
files, err := filepath.Glob(glob)
if err != nil {
return nil, errors.Wrapf(err, "failed on glob %v", glob)
}
configFiles = append(configFiles, files...)
}
return configFiles, nil
}
func getConfig(file string) ([]byte, error) {
tpl, err := template.ParseFiles(file)
if err != nil {
return nil, errors.Wrapf(err, "failed reading %v", file)
}
data := map[string]interface{}{
"goos": *goos,
"reference": *reference,
}
buf := new(bytes.Buffer)
if err = tpl.Execute(buf, data); err != nil {
return nil, errors.Wrapf(err, "failed executing template %v", file)
}
return buf.Bytes(), nil
}
func output(content []byte, file string) error {
if file == "-" {
fmt.Println(string(content))
return nil
}
if err := ioutil.WriteFile(file, content, 0640); err != nil {
return errors.Wrapf(err, "failed writing output to %v", file)
}
return nil
}
func logAndExit(err error) {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
func main() {
flag.Parse()
globs := os.Args
if len(os.Args) > 0 {
path, err := filepath.Abs(defaultGlob)
if err != nil {
logAndExit(err)
}
globs = []string{path}
}
files, err := findConfigFiles(globs)
if err != nil {
logAndExit(err)
}
var segments [][]byte
for _, file := range files {
segment, err := getConfig(file)
if err != nil {
logAndExit(err)
}
if *concat {
segments = append(segments, segment)
} else {
output(segment, strings.TrimSuffix(file, ".tpl"))
}
}
if *concat {
if err := output(bytes.Join(segments, []byte{'\n'}), "-"); err != nil {
logAndExit(err)
}
}
}