/
format.go
103 lines (89 loc) · 2.56 KB
/
format.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package format
import (
"bytes"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/parser"
"go/token"
"os"
"runtime"
"strconv"
"strings"
)
const (
Test = 1
)
type ImportGroups [][]string
func getAstString(fileSet *token.FileSet, node ast.Node) string {
buf := &bytes.Buffer{}
if err := format.Node(buf, fileSet, node); err != nil {
panic(err)
}
return buf.String()
}
func Format(filename string, src []byte) []byte {
fileSet := token.NewFileSet()
file, err := parser.ParseFile(fileSet, filename, src, parser.ParseComments)
if err != nil {
panic(fmt.Errorf("errors %s in %s", err.Error(), filename))
}
buf := &bytes.Buffer{}
if err := format.Node(buf, fileSet, file); err != nil {
panic(fmt.Errorf("errors %s in %s", err.Error(), filename))
}
return buf.Bytes()
}
func Process(filename string, src []byte) ([]byte, error) {
cwd, _ := os.Getwd()
fileSet := token.NewFileSet()
file, err := parser.ParseFile(fileSet, filename, src, parser.ParseComments)
if err != nil {
return nil, err
}
ast.SortImports(fileSet, file)
formattedCode := getAstString(fileSet, file)
for _, decl := range file.Decls {
if genDecl, ok := decl.(*ast.GenDecl); ok {
if genDecl.Tok != token.IMPORT {
break
}
importsCode := getAstString(fileSet, genDecl)
importGroups := make(ImportGroups, 4)
for _, spec := range genDecl.Specs {
importSpec := spec.(*ast.ImportSpec)
importPath, _ := strconv.Unquote(importSpec.Path.Value)
pkg, err := build.Import(importPath, "", build.ImportComment)
if err != nil {
panic(fmt.Errorf("errors %s in %s", err.Error(), filename))
}
if strings.Contains(pkg.Dir, runtime.GOROOT()) {
// libexec
importGroups[0] = append(importGroups[0], getAstString(fileSet, importSpec))
} else {
if strings.HasPrefix(pkg.Dir, cwd) {
importGroups[3] = append(importGroups[3], getAstString(fileSet, importSpec))
} else {
if strings.HasPrefix(pkg.ImportPath, "golib") || strings.HasPrefix(pkg.ImportPath, "g7pay") {
importGroups[2] = append(importGroups[2], getAstString(fileSet, importSpec))
} else {
importGroups[1] = append(importGroups[1], getAstString(fileSet, importSpec))
}
}
}
}
buf := &bytes.Buffer{}
buf.WriteString("import (\n")
for _, importGroup := range importGroups {
for _, code := range importGroup {
buf.WriteString(code + "\n")
}
buf.WriteString("\n")
}
buf.WriteString(")")
formattedCode = strings.Replace(formattedCode, importsCode, buf.String(), -1)
}
}
return Format(filename, []byte(formattedCode)), nil
}