diff --git a/cmd/interfacer/main.go b/cmd/interfacer/main.go index 5f0b2f7..e8e714d 100644 --- a/cmd/interfacer/main.go +++ b/cmd/interfacer/main.go @@ -2,8 +2,11 @@ package main import ( + "bytes" + "errors" "flag" "fmt" + "go/format" "os" "strings" "text/template" @@ -40,31 +43,24 @@ type vars struct { Interface interfaces.Interface } -func nonil(err ...error) error { - for _, e := range err { - if e != nil { - return e - } +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) } - return nil } -func die(v interface{}) { - fmt.Fprintln(os.Stderr, v) - os.Exit(1) -} - -func main() { +func run() error { flag.Parse() if *query == "" { - die("empty -for flag value; see -help for details") + return errors.New("empty -for flag value; see -help for details") } if *output == "" { - die("empty -o flag value; see -help for details") + return errors.New("empty -o flag value; see -help for details") } q, err := interfaces.ParseQuery(*query) if err != nil { - die(err) + return err } opts := &interfaces.Options{ Query: q, @@ -72,7 +68,7 @@ func main() { } i, err := interfaces.NewWithOptions(opts) if err != nil { - die(err) + return err } v := &vars{ Type: fmt.Sprintf(`"%s"`, *query), @@ -85,15 +81,24 @@ func main() { } else { v.InterfaceName = *as } + var buf bytes.Buffer + if err := tmpl.Execute(&buf, v); err != nil { + return err + } + formatted, err := format.Source(buf.Bytes()) + if err != nil { + return err + } f := os.Stdout if *output != "-" { f, err = os.OpenFile(*output, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { - die(err) + return err } + defer f.Close() } - err = nonil(tmpl.Execute(f, v), f.Close()) - if err != nil { - die(err) + if _, err := f.Write(formatted); err != nil { + return err } + return nil }