Lorenz Brun | cb2dcf6 | 2021-11-22 22:57:34 +0100 | [diff] [blame^] | 1 | // 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. |
| 3 | package noioutil |
| 4 | |
| 5 | import ( |
| 6 | "go/ast" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | |
| 10 | "golang.org/x/tools/go/analysis" |
| 11 | ) |
| 12 | |
| 13 | var Analyzer = &analysis.Analyzer{ |
| 14 | Name: "noioutil", |
| 15 | Doc: "noioutil checks for imports of the deprecated ioutil package", |
| 16 | Run: run, |
| 17 | } |
| 18 | |
| 19 | func 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 | |
| 42 | const ( |
| 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. |
| 49 | func 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 | } |