-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
102 lines (84 loc) · 1.78 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/urfave/cli/v2"
"github.com/nick-jones/astpath/pkg/query"
)
func main() {
app := &cli.App{
Name: "astpath",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "template",
Value: "{{.Filename}}:{{.Line}}:{{.Column}} > {{.Source}}",
Usage: "text/template format",
},
},
Action: run,
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func run(c *cli.Context) error {
xpath, root := c.Args().Get(0), c.Args().Get(1)
if xpath == "" {
return fmt.Errorf("xpath must be provided")
}
if root == "" {
root = "."
}
expr, err := query.Compile(xpath)
if err != nil {
return fmt.Errorf("invalid query: %w", err)
}
tmpl, err := template.New("format").Parse(c.String("template"))
if err != nil {
return fmt.Errorf("failed to parse format flag: %w", err)
}
paths, err := findFiles(root)
if err != nil {
return err
}
results := make([]query.Result, 0)
for _, path := range paths {
res, err := queryFile(path, expr)
if err != nil {
return err
}
results = append(results, res...)
}
for _, res := range results {
if err := tmpl.Execute(os.Stdout, res); err != nil {
return fmt.Errorf("failed to execute template: %w", err)
}
fmt.Println()
}
return nil
}
func findFiles(root string) (paths []string, err error) {
err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !strings.HasSuffix(path, ".go") {
return nil
}
paths = append(paths, path)
return nil
})
return
}
func queryFile(path string, expr *query.Expr) ([]query.Result, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return query.FindAll(f, path, expr)
}