forked from tcnksm/gcli
/
gofmt.go
55 lines (48 loc) · 972 Bytes
/
gofmt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package helper
import (
"bytes"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io"
"io/ioutil"
"os"
)
// GoFmt runs `gofmt` to io.Reader and save it as file
// If something wrong it returns error.
func GoFmt(filename string, in io.Reader) error {
if in == nil {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
in = f
}
src, err := ioutil.ReadAll(in)
if err != nil {
return err
}
fileSet := token.NewFileSet()
file, err := parser.ParseFile(fileSet, filename, src, parser.ParseComments)
if err != nil {
return err
}
ast.SortImports(fileSet, file)
var buf bytes.Buffer
tabWidth := 8
printerMode := printer.UseSpaces | printer.TabIndent
err = (&printer.Config{Mode: printerMode, Tabwidth: tabWidth}).Fprint(&buf, fileSet, file)
if err != nil {
return err
}
res := buf.Bytes()
if !bytes.Equal(src, res) {
err = ioutil.WriteFile(filename, res, 0)
if err != nil {
return err
}
}
return nil
}