From ed5a8e8880f4572673406391d200d36589319641 Mon Sep 17 00:00:00 2001 From: Lavanya Verma <108087018+lverma14@users.noreply.github.com> Date: Wed, 3 Apr 2024 00:22:39 -0700 Subject: [PATCH] Fix nil ptr bug in checkGenerated (#159) 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. --- main.go | 3 +++ main_test.go | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/main.go b/main.go index 8959fa5..77b38c8 100644 --- a/main.go +++ b/main.go @@ -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 diff --git a/main_test.go b/main_test.go index 5994f9b..5f38da8 100644 --- a/main_test.go +++ b/main_test.go @@ -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) {