Skip to content

Commit

Permalink
Fix nil ptr bug in checkGenerated (#159)
Browse files Browse the repository at this point in the history
Currently, while checking if a file contains generated code, if the file
doesn't contain any package comment,
 we run into a nil pointer dereference error.
```
package example
... // rest of the logic
```
**Why**
This happens due to missing nil check in the `checkGenerated` function
before iterating `ast.File.Doc.List` ([pkg
ref](https://pkg.go.dev/go/ast#File))
```
for _, comm := range f.Doc.List { // nil pointer error when f.Doc is nil
```
This commit adds a nil pointer check in `checkGenerated` to continue
with the rest of the logic only if there's a package comment.
  • Loading branch information
lverma14 authored Apr 3, 2024
1 parent be15f28 commit ed5a8e8
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
3 changes: 3 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,9 @@ func checkGeneratedCode(f *ast.File) bool {
if ast.IsGenerated(f) {
return true
}
if f.Doc == nil {
return false
}
for _, comm := range f.Doc.List {
if strings.Contains(comm.Text, "@generated") {
return true
Expand Down
4 changes: 4 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,10 @@ func TestCheckGeneratedCode(t *testing.T) {
},
},
},
{
name: "non-generated code with no package comment",
file: &ast.File{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit ed5a8e8

Please sign in to comment.