Pipe generated C code through clang-format.

This commit is contained in:
Nigel Tao committed 2017-05-25 12:44:45 +10:00
1 parent f01f9c2fba
commit 090c5f057c
2 files changed
+25 -1

No files matched your search

+19
View File
@@ -13,7 +13,9 @@ package main
import (
"bytes"
"errors"
"os"
"os/exec"
"github.com/google/puffs/lang/generate"
)
@@ -38,3 +40,20 @@ func (gen) WritePostamble(w *bytes.Buffer) error {
w.WriteString("\n#ifdef __cplusplus\n} // extern \"C\"\n#endif\n")
return nil
}
func (gen) Format(in []byte) ([]byte, error) {
cmd := exec.Command("clang-format", "-style=Chromium")
cmd.Stdin = bytes.NewReader(in)
out, err := cmd.CombinedOutput()
if _, ok := err.(*exec.ExitError); ok && len(out) > 0 {
// Go error messages usually don't end in "\n". The caller, who sees
// the error we return here, usually adds the "\n" themselves.
if out[len(out)-1] == '\n' {
out = out[:len(out)-1]
}
// The exec.ExitError's Error message doesn't include stderr, so we
// return that explicitly.
return nil, errors.New(string(out))
}
return out, err
}
+6 -1
View File
@@ -23,6 +23,7 @@ var (
type Generator interface {
WritePreamble(w *bytes.Buffer) error
WritePostamble(w *bytes.Buffer) error
Format([]byte) ([]byte, error)
}
func Main(g Generator) error {
@@ -51,7 +52,11 @@ func Main(g Generator) error {
if err := g.WritePostamble(b); err != nil {
return err
}
if _, err := os.Stdout.Write(b.Bytes()); err != nil {
formatted, err := g.Format(b.Bytes())
if err != nil {
return err
}
if _, err := os.Stdout.Write(formatted); err != nil {
return err
}
return nil