1
2
3
4
5 package modernize
6
7 import (
8 "strings"
9
10 "golang.org/x/tools/go/analysis"
11 "golang.org/x/tools/internal/analysis/analyzerutil"
12 )
13
14 var importCommentAnalyzer = &analysis.Analyzer{
15 Name: "importcomment",
16 Doc: analyzerutil.MustExtractDoc(doc, "importcomment"),
17 URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#hdr-Analyzer_importcomment",
18 Run: importcomment,
19 }
20
21 func importcomment(pass *analysis.Pass) (any, error) {
22
23 if pass.Module == nil {
24 return nil, nil
25 }
26
27 for _, file := range pass.Files {
28
29 pkgEnd := file.Name.End()
30 pkgLine := pass.Fset.Position(pkgEnd).Line
31 for _, c := range file.Comments {
32 if len(c.List) != 1 {
33 continue
34 }
35 if c.Pos() < pkgEnd {
36 continue
37 }
38 commentLine := pass.Fset.Position(c.Pos()).Line
39 if commentLine > pkgLine {
40 break
41 }
42
43 if !isImportComment(c.Text()) {
44 continue
45 }
46 pass.Report(analysis.Diagnostic{
47 Pos: c.Pos(),
48 End: c.End(),
49 Message: "canonical import path comment is ignored in module mode",
50 SuggestedFixes: []analysis.SuggestedFix{{
51 Message: "Remove obsolete import path comment",
52 TextEdits: []analysis.TextEdit{{
53 Pos: pkgEnd,
54 End: c.End(),
55 }},
56 }},
57 })
58 }
59 }
60
61 return nil, nil
62 }
63
64
65
66 func isImportComment(text string) bool {
67 text = strings.TrimSpace(text)
68 return strings.HasPrefix(text, `import "`) && strings.HasSuffix(text, `"`)
69 }
70
View as plain text