blob: 96286e343933486f8dfc7eeca4cb602a391e3a9e [file] [log] [blame]
Lorenz Bruncb2dcf62021-11-22 22:57:34 +01001// Package noioutil contains a Go analysis pass designed to prevent use of the
2// deprecated ioutil package for which a tree-wide migration was already done.
3package noioutil
4
5import (
6 "go/ast"
7 "strconv"
8 "strings"
9
10 "golang.org/x/tools/go/analysis"
11)
12
13var Analyzer = &analysis.Analyzer{
14 Name: "noioutil",
15 Doc: "noioutil checks for imports of the deprecated ioutil package",
16 Run: run,
17}
18
19func run(p *analysis.Pass) (interface{}, error) {
20 for _, file := range p.Files {
21 if isGeneratedFile(file) {
22 continue
23 }
24 for _, i := range file.Imports {
25 importPath, err := strconv.Unquote(i.Path.Value)
26 if err != nil {
27 continue
28 }
29 if importPath == "io/ioutil" {
30 p.Report(analysis.Diagnostic{
31 Pos: i.Path.ValuePos,
32 End: i.Path.End(),
33 Message: "File imports the deprecated io/ioutil package. See https://pkg.go.dev/io/ioutil for replacements.",
34 })
35 }
36 }
37 }
38
39 return nil, nil
40}
41
42const (
43 genPrefix = "// Code generated"
44 genSuffix = "DO NOT EDIT."
45)
46
47// isGeneratedFile returns true if the file is generated
48// according to https://golang.org/s/generatedcode.
49func isGeneratedFile(file *ast.File) bool {
50 for _, c := range file.Comments {
51 for _, t := range c.List {
52 if strings.HasPrefix(t.Text, genPrefix) && strings.HasSuffix(t.Text, genSuffix) {
53 return true
54 }
55 }
56 }
57 return false
58}