Skip to content

Commit

Permalink
use go1.21 ast.IsGenerated when available
Browse files Browse the repository at this point in the history
  • Loading branch information
nishanths committed Nov 2, 2023
1 parent 829aae6 commit 879cdef
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 33 deletions.
33 changes: 0 additions & 33 deletions comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,9 @@ package exhaustive
import (
"go/ast"
"go/token"
"regexp"
"strings"
)

// For definition of generated file see:
// http://golang.org/s/generatedcode

var generatedCodeRe = regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`)

func isGeneratedFile(file *ast.File) bool {
// NOTE: file.Comments includes file.Doc as well, so no need
// to separately check file.Doc.
for _, c := range file.Comments {
for _, cc := range c.List {
// This check handles the "must appear before the first
// non-comment, non-blank text in the file" requirement.
//
// According to https://golang.org/ref/spec#Source_file_organization
// the package clause is the first element in a file, which
// should make it the first non-comment, non-blank text.
if c.Pos() >= file.Package {
return false
}
// According to the docs:
// '\r' has been removed.
// '\n' has been removed for //-style comments
// This has also been manually verified.
if generatedCodeRe.MatchString(cc.Text) {
return true
}
}
}

return false
}

const (
ignoreComment = "//exhaustive:ignore"
enforceComment = "//exhaustive:enforce"
Expand Down
11 changes: 11 additions & 0 deletions comment_go121.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
//go:build go1.21

package exhaustive

import (
"go/ast"
)

func isGeneratedFile(file *ast.File) bool {
return ast.IsGenerated(file)
}
27 changes: 27 additions & 0 deletions comment_pre_go121.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//go:build !go1.21

package exhaustive

import (
"go/ast"
"regexp"
)

// For definition of generated file see:
// http://golang.org/s/generatedcode

var generatedCodeRe = regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`)

func isGeneratedFile(file *ast.File) bool {
for _, c := range file.Comments {
for _, cc := range c.List {
if cc.Pos() > file.Package {
break
}
if generatedCodeRe.MatchString(cc.Text) {
return true
}
}
}
return false
}

0 comments on commit 879cdef

Please sign in to comment.