Skip to content

Commit c297c0c

Browse files
authored
Merge pull request #312 from thockin/master
Call goimports AND gofmt -s
2 parents ca8cf6f + 1034962 commit c297c0c

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

v2/generator/execute.go

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
117128
func 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+
127153
func NewGoFile() *DefaultFileType {
128154
return &DefaultFileType{
129-
Format: importsWrapper,
155+
Format: formatCode,
130156
Assemble: assembleGoFile,
131157
}
132158
}

0 commit comments

Comments
 (0)