Debian Codegraph @

internal/cmd/gogrep/gogrep.go

raw
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 entryNodesMap := make(map[reflect.Type]struct{})
20 for _, node := range pat.EntryNodes {
21 entryNodesMap[reflect.TypeOf(node)] = struct{}{}
22 }
23 ast.Inspect(f, func(node ast.Node) bool {
24 if node == nil {
25 return true
26 }
27
28 if _, ok := entryNodesMap[reflect.TypeOf(node)]; ok {
29 m := &pattern.Matcher{}
30 if m.Match(pat, node) {
31 fmt.Printf("%s: ", fset.Position(node.Pos()))
32 format.Node(os.Stdout, fset, node)
33 fmt.Println()
34 }
35
36 // OPT(dh): we could further speed this up by not
37 // chasing down impossible subtrees. For example,
38 // we'll never find an ImportSpec beneath a FuncLit.
39 }
40 return true
41 })
42
43 }
44
45 func main() {
46 flag.Parse()
47 // XXX don't use MustParse, handle error
48 p := &pattern.Parser{}
49 q, err := p.Parse(flag.Args()[0])
50 if err != nil {
51 fmt.Println(err)
52 os.Exit(1)
53 }
54 dir := flag.Args()[1]
55 // XXX should we create a new fileset per file? what if we're
56 // checking millions of files, will this use up a lot of memory?
57 fset := token.NewFileSet()
58 filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
59 if err != nil {
60 // XXX error handling
61 panic(err)
62 }
63 if !strings.HasSuffix(path, ".go") {
64 return nil
65 }
66 // XXX don't try to parse irregular files or directories
67 f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
68 if err != nil {
69 // XXX log error?
70 return nil
71 }
72
73 match(fset, q, f)
74
75 return nil
76 })
77 }