@@ -22,6 +22,7 @@ import (
2222 "fmt"
2323 "io"
2424 "os"
25+ "os/exec"
2526 "path/filepath"
2627 "strings"
2728
@@ -114,19 +115,44 @@ func assembleGoFile(w io.Writer, f *File) {
114115 w .Write (f .Body .Bytes ())
115116}
116117
118+ func formatCode (src []byte ) ([]byte , error ) {
119+ // We call goimports because it formats imports better than gofmt, but also
120+ // call gofmt because it has the "simplify" logic.
121+ src , err := importsWrapper (src )
122+ if err != nil {
123+ return nil , err
124+ }
125+ return gofmtWrapper (src )
126+ }
127+
117128func importsWrapper (src []byte ) ([]byte , error ) {
118129 opt := imports.Options {
119130 Comments : true ,
120131 TabIndent : true ,
121132 TabWidth : 8 ,
122- FormatOnly : true , // Disable the insertion and deletion of imports
133+ FormatOnly : true , // Disable the insertion and deletion of imports (slow!)
123134 }
124135 return imports .Process ("" , src , & opt )
125136}
126137
138+ func gofmtWrapper (src []byte ) ([]byte , error ) {
139+ cmd := exec .Command ("gofmt" , "-s" )
140+ cmd .Stdin = bytes .NewReader (src )
141+ stdout := & bytes.Buffer {}
142+ cmd .Stdout = stdout
143+ stderr := & bytes.Buffer {}
144+ cmd .Stderr = stderr
145+ if err := cmd .Run (); err != nil {
146+ if stderr .Len () > 0 {
147+ return nil , fmt .Errorf ("gofmt failed: %v: %s" , err , strings .TrimSpace (stderr .String ()))
148+ }
149+ }
150+ return stdout .Bytes (), nil
151+ }
152+
127153func NewGoFile () * DefaultFileType {
128154 return & DefaultFileType {
129- Format : importsWrapper ,
155+ Format : formatCode ,
130156 Assemble : assembleGoFile ,
131157 }
132158}
0 commit comments