Source file src/cmd/vendor/golang.org/x/tools/go/analysis/passes/modernize/importcomment.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     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  	// Import path comments are ignored in module mode.
    23  	if pass.Module == nil {
    24  		return nil, nil
    25  	}
    26  
    27  	for _, file := range pass.Files {
    28  		// An import comment follows the package name on the same line.
    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 // comments are sorted; the rest are on later lines
    41  			}
    42  			// Have: package p // comment
    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, // deletes the preceding space too
    54  						End: c.End(),
    55  					}},
    56  				}},
    57  			})
    58  		}
    59  	}
    60  
    61  	return nil, nil
    62  }
    63  
    64  // isImportComment reports whether text, a comment's content with its
    65  // markers removed, is a canonical import path comment, import "path".
    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