-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathprealloc.go
180 lines (151 loc) · 3.98 KB
/
prealloc.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package main
import (
"flag"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"log"
"os"
"path/filepath"
"strings"
"github.com/alexkohler/prealloc/pkg"
)
// Support: (in order of priority)
// * Full make suggestion with type?
// * Test flag
// * Embedded ifs?
// * Use an import rather than the duplcated import.go
const (
pwd = "./"
)
func init() {
// Ignore build flags
build.Default.UseAllFiles = true
}
func usage() {
log.Printf("Usage of %s:\n", os.Args[0])
log.Printf("\nprealloc [flags] # runs on package in current directory\n")
log.Printf("\nprealloc [flags] [packages]\n")
log.Printf("Flags:\n")
flag.PrintDefaults()
}
func main() {
// Remove log timestamp
log.SetFlags(0)
simple := flag.Bool("simple", true, "Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them")
includeRangeLoops := flag.Bool("rangeloops", true, "Report preallocation suggestions on range loops")
includeForLoops := flag.Bool("forloops", false, "Report preallocation suggestions on for loops")
setExitStatus := flag.Bool("set_exit_status", false, "Set exit status to 1 if any issues are found")
flag.Usage = usage
flag.Parse()
fset := token.NewFileSet()
hints, err := checkForPreallocations(
flag.Args(),
fset,
*simple,
*includeRangeLoops,
*includeForLoops,
)
if err != nil {
log.Println(err)
}
for _, hint := range hints {
log.Println(hint.StringFromFS(fset))
}
if *setExitStatus && len(hints) > 0 {
os.Exit(1)
}
}
func checkForPreallocations(
args []string,
fset *token.FileSet,
simple, includeRangeLoops, includeForLoops bool,
) ([]pkg.Hint, error) {
files, err := parseInput(args, fset)
if err != nil {
return nil, fmt.Errorf("could not parse input %v", err)
}
hints := pkg.Check(files, simple, includeRangeLoops, includeForLoops)
return hints, nil
}
func parseInput(args []string, fset *token.FileSet) ([]*ast.File, error) {
var directoryList []string
var fileMode bool
files := make([]*ast.File, 0)
if len(args) == 0 {
directoryList = append(directoryList, pwd)
} else {
for _, arg := range args {
if strings.HasSuffix(arg, "/...") && isDir(arg[:len(arg)-len("/...")]) {
for _, dirname := range allPackagesInFS(arg) {
directoryList = append(directoryList, dirname)
}
} else if isDir(arg) {
directoryList = append(directoryList, arg)
} else if exists(arg) {
if strings.HasSuffix(arg, ".go") {
fileMode = true
f, err := parser.ParseFile(fset, arg, nil, 0)
if err != nil {
return nil, err
}
files = append(files, f)
} else {
return nil, fmt.Errorf("invalid file %v specified", arg)
}
} else {
//TODO clean this up a bit
imPaths := importPaths([]string{arg})
for _, importPath := range imPaths {
pkg, err := build.Import(importPath, ".", 0)
if err != nil {
return nil, err
}
var stringFiles []string
stringFiles = append(stringFiles, pkg.GoFiles...)
// files = append(files, pkg.CgoFiles...)
stringFiles = append(stringFiles, pkg.TestGoFiles...)
if pkg.Dir != "." {
for i, f := range stringFiles {
stringFiles[i] = filepath.Join(pkg.Dir, f)
}
}
fileMode = true
for _, stringFile := range stringFiles {
f, err := parser.ParseFile(fset, stringFile, nil, 0)
if err != nil {
return nil, err
}
files = append(files, f)
}
}
}
}
}
// if we're not in file mode, then we need to grab each and every package in each directory
// we can to grab all the files
if !fileMode {
for _, fpath := range directoryList {
pkgs, err := parser.ParseDir(fset, fpath, nil, 0)
if err != nil {
return nil, err
}
for _, pkg := range pkgs {
for _, f := range pkg.Files {
files = append(files, f)
}
}
}
}
return files, nil
}
func isDir(filename string) bool {
fi, err := os.Stat(filename)
return err == nil && fi.IsDir()
}
func exists(filename string) bool {
_, err := os.Stat(filename)
return err == nil
}