Skip to content

Commit 0696445

Browse files
structslop: add -generated flag for skipping issues in generated files (#60)
1 parent 6fe7dca commit 0696445

3 files changed

Lines changed: 39 additions & 1 deletion

File tree

structslop.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,14 @@ var (
3838
includeTestFiles bool
3939
verbose bool
4040
apply bool
41+
generated bool
4142
)
4243

4344
func init() {
4445
Analyzer.Flags.BoolVar(&includeTestFiles, "include-test-files", includeTestFiles, "also check test files")
4546
Analyzer.Flags.BoolVar(&verbose, "verbose", verbose, "print all information, even when struct is not sloppy")
4647
Analyzer.Flags.BoolVar(&apply, "apply", apply, "apply suggested fixes (using -fix won't work)")
48+
Analyzer.Flags.BoolVar(&generated, "generated", generated, "report issues in generated code")
4749
}
4850

4951
const Doc = `check for structs that can be rearrange fields to provide for maximum space/allocation efficiency`
@@ -76,8 +78,29 @@ func run(pass *analysis.Pass) (interface{}, error) {
7678
var af *ast.File
7779
var df *dst.File
7880

81+
// Track generated files unless -generated is set.
82+
genFiles := make(map[*token.File]bool)
83+
if !generated {
84+
files:
85+
for _, f := range pass.Files {
86+
for _, c := range f.Comments {
87+
for _, l := range c.List {
88+
if strings.HasPrefix(l.Text, "// Code generated ") && strings.HasSuffix(l.Text, " DO NOT EDIT.") {
89+
file := pass.Fset.File(f.Pos())
90+
genFiles[file] = true
91+
continue files
92+
}
93+
}
94+
}
95+
}
96+
}
7997
inspect.Preorder(nodeFilter, func(n ast.Node) {
80-
if strings.HasSuffix(pass.Fset.File(n.Pos()).Name(), "_test.go") && !includeTestFiles {
98+
file := pass.Fset.File(n.Pos())
99+
if strings.HasSuffix(file.Name(), "_test.go") && !includeTestFiles {
100+
return
101+
}
102+
// Skip generated structs if instructed.
103+
if !generated && genFiles[file] {
81104
return
82105
}
83106
if f, ok := n.(*ast.File); ok {

structslop_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,8 @@ func TestVerboseMode(t *testing.T) {
7373
}()
7474
analysistest.Run(t, testdata, structslop.Analyzer, "verbose")
7575
}
76+
77+
func TestGenerated(t *testing.T) {
78+
testdata := analysistest.TestData()
79+
analysistest.Run(t, testdata, structslop.Analyzer, "generated")
80+
}

testdata/src/generated/gen.go

Lines changed: 10 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)