Skip to content

Commit

Permalink
checkers: optimize commentFormatting (#1192)
Browse files Browse the repository at this point in the history
  • Loading branch information
peakle committed Jan 8, 2022
1 parent 4286793 commit eb73c6d
Showing 1 changed file with 49 additions and 15 deletions.
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

0 comments on commit eb73c6d

Please sign in to comment.