Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checkers: optimize commentFormatting #1192

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
64 changes: 49 additions & 15 deletions checkers/commentFormatting_checker.go
Expand Up @@ -20,20 +20,30 @@ func init() {
info.After = `// This is a comment`

collection.AddChecker(&info, func(ctx *linter.CheckerContext) (linter.FileWalker, error) {
regexpPatterns := []*regexp.Regexp{
regexp.MustCompile(`^//[\w-]+:.*$`), // e.g.: key: value
}
equalPatterns := []string{
"//nolint",
}
parts := []string{
`^//go:generate .*$`, // e.g.: go:generate value
`^//[\w-]+:.*$`, // e.g.: key: value
`^//nolint\b`, // e.g.: nolint
`^//line /.*:\d+`, // e.g.: line /path/to/file:123
`^//export \w+$`, // e.g.: export Foo
`^//[/+#-]+.*$`, // e.g.: vertical breaker /////////////
`^//noinspection `, // e.g.: noinspection ALL, some GoLand and friends versions
"//go:generate ", // e.g.: go:generate value
"//line /", // e.g.: line /path/to/file:123
"//nolint ", // e.g.: nolint
"//noinspection ", // e.g.: noinspection ALL, some GoLand and friends versions
"//export ", // e.g.: export Foo
"///", // e.g.: vertical breaker /////////////
"//+",
"//#",
"//-",
"//!",
}
pat := "(?m)" + strings.Join(parts, "|")
pragmaRE := regexp.MustCompile(pat)

return astwalk.WalkerForComment(&commentFormattingChecker{
ctx: ctx,
pragmaRE: pragmaRE,
ctx: ctx,
partPatterns: parts,
equalPatterns: equalPatterns,
regexpPatterns: regexpPatterns,
}), nil
})
}
Expand All @@ -42,19 +52,43 @@ type commentFormattingChecker struct {
astwalk.WalkHandler
ctx *linter.CheckerContext

pragmaRE *regexp.Regexp
partPatterns []string
equalPatterns []string
regexpPatterns []*regexp.Regexp
}

func (c *commentFormattingChecker) VisitComment(cg *ast.CommentGroup) {
if strings.HasPrefix(cg.List[0].Text, "/*") {
return
}

outerLoop:
for _, comment := range cg.List {
if len(comment.Text) <= len("// ") {
commentLen := len(comment.Text)
if commentLen <= len("// ") {
continue
}
if c.pragmaRE.MatchString(comment.Text) {
continue

for _, p := range c.partPatterns {
if commentLen < len(p) {
continue
}

if strings.EqualFold(comment.Text[:len(p)], p) {
continue outerLoop
}
}

for _, p := range c.equalPatterns {
if strings.EqualFold(comment.Text, p) {
continue outerLoop
}
}

for _, p := range c.regexpPatterns {
if p.MatchString(comment.Text) {
continue outerLoop
}
}

// Make a decision based on a first comment text rune.
Expand Down