Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / honnef.co / go / tools@v0.0.1-2020.1.5 / internal / cmd / gogrep / gogrep.go
1 package main
2
3 import (
4         "flag"
5         "fmt"
6         "go/ast"
7         "go/format"
8         "go/parser"
9         "go/token"
10         "os"
11         "path/filepath"
12         "reflect"
13         "strings"
14
15         "honnef.co/go/tools/pattern"
16 )
17
18 func match(fset *token.FileSet, pat pattern.Pattern, f *ast.File) {
19         ast.Inspect(f, func(node ast.Node) bool {
20                 if node == nil {
21                         return true
22                 }
23
24                 for _, rel := range pat.Relevant {
25                         if rel == reflect.TypeOf(node) {
26                                 m := &pattern.Matcher{}
27                                 if m.Match(pat.Root, node) {
28                                         fmt.Printf("%s: ", fset.Position(node.Pos()))
29                                         format.Node(os.Stdout, fset, node)
30                                         fmt.Println()
31                                 }
32
33                                 // OPT(dh): we could further speed this up by not
34                                 // chasing down impossible subtrees. For example,
35                                 // we'll never find an ImportSpec beneath a FuncLit.
36                                 return true
37                         }
38                 }
39                 return true
40         })
41
42 }
43
44 func main() {
45         flag.Parse()
46         // XXX don't use MustParse, handle error
47         p := &pattern.Parser{}
48         q, err := p.Parse(flag.Args()[0])
49         if err != nil {
50                 fmt.Println(err)
51                 os.Exit(1)
52         }
53         dir := flag.Args()[1]
54         // XXX should we create a new fileset per file? what if we're
55         // checking millions of files, will this use up a lot of memory?
56         fset := token.NewFileSet()
57         filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
58                 if err != nil {
59                         // XXX error handling
60                         panic(err)
61                 }
62                 if !strings.HasSuffix(path, ".go") {
63                         return nil
64                 }
65                 // XXX don't try to parse irregular files or directories
66                 f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
67                 if err != nil {
68                         // XXX log error?
69                         return nil
70                 }
71
72                 match(fset, q, f)
73
74                 return nil
75         })
76 }