diff --git a/libbeat/generator/fields/fields.go b/libbeat/generator/fields/fields.go index b26bf7e36a3..c6210b28d2e 100644 --- a/libbeat/generator/fields/fields.go +++ b/libbeat/generator/fields/fields.go @@ -20,6 +20,7 @@ package fields import ( "bufio" "bytes" + "io" "os" "path/filepath" "strings" @@ -104,28 +105,13 @@ func isLibbeat(beatPath string) bool { return filepath.Base(beatPath) == "libbeat" } -func writeGeneratedFieldsYml(fieldFiles []*YmlFile, output string) error { +func writeGeneratedFieldsYml(fieldFiles []*YmlFile, output io.Writer) error { data, err := GenerateFieldsYml(fieldFiles) if err != nil { return err } - if output == "-" { - fw := bufio.NewWriter(os.Stdout) - _, err = fw.Write(data) - if err != nil { - return err - } - return fw.Flush() - } - - f, err := os.Create(output) - if err != nil { - return err - } - defer f.Close() - - fw := bufio.NewWriter(f) + fw := bufio.NewWriter(output) _, err = fw.Write(data) if err != nil { return err @@ -164,7 +150,7 @@ func writeIndentedLine(buf *bytes.Buffer, line string, indent int) error { } // Generate collects fields.yml files and concatenates them into one global file. -func Generate(esBeatsPath, beatPath string, files []*YmlFile, output string) error { +func Generate(esBeatsPath, beatPath string, files []*YmlFile, output io.Writer) error { files, err := collectCommonFiles(esBeatsPath, beatPath, files) if err != nil { return err diff --git a/libbeat/scripts/cmd/global_fields/main.go b/libbeat/scripts/cmd/global_fields/main.go index 41f60e1fe43..b71a848d845 100644 --- a/libbeat/scripts/cmd/global_fields/main.go +++ b/libbeat/scripts/cmd/global_fields/main.go @@ -18,8 +18,10 @@ package main import ( + "bytes" "flag" "fmt" + "io/ioutil" "os" "path/filepath" @@ -90,21 +92,29 @@ func main() { fieldsFiles = append(fieldsFiles, fieldsFile...) } - err = fields.Generate(esBeatsPath, beatPath, fieldsFiles, output) + var buffer bytes.Buffer + err = fields.Generate(esBeatsPath, beatPath, fieldsFiles, &buffer) if err != nil { fmt.Fprintf(os.Stderr, "Cannot generate global fields.yml file for %s: %+v\n", name, err) os.Exit(3) } - _, err = mapping.LoadFieldsYaml(output) + _, err = mapping.LoadFields(buffer.Bytes()) if err != nil { fmt.Fprintf(os.Stderr, "Generated global fields.yml file for %s is invalid: %+v\n", name, err) os.Exit(3) } - outputPath, _ := filepath.Abs(output) + if output == "-" { + fmt.Print(buffer.String()) + return + } + + err = ioutil.WriteFile(output, buffer.Bytes(), 0644) if err != nil { - outputPath = output + fmt.Fprintf(os.Stderr, "Cannot write global fields.yml file for %s: %v", name, err) } + + outputPath, _ := filepath.Abs(output) fmt.Fprintf(os.Stderr, "Generated fields.yml for %s to %s\n", name, outputPath) }