1 Star 0 Fork 0

zhangjungang/beats

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
generate_config.go 2.14 KB
一键复制 编辑 原始数据 按行查看 历史
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)
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zhangjungang/beats.git
git@gitee.com:zhangjungang/beats.git
zhangjungang
beats
beats
v6.0.0-beta2

搜索帮助