-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrun.go
79 lines (72 loc) · 1.51 KB
/
run.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
package main
import (
"go/ast"
"go/build"
"go/parser"
"go/token"
"os"
"strings"
"github.com/kballard/go-shellquote"
"github.com/spf13/cobra"
)
const prefix = "graffiti: "
func run(target string) error {
i, err := os.Stat(target)
if err != nil {
return err
}
if !i.IsDir() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, target, nil, parser.ParseComments)
if err != nil {
return err
}
return runfile(f, target)
}
p, err := build.Default.ImportDir(target, 0)
if err != nil {
return err
}
for _, file := range p.GoFiles {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, file, nil, parser.ParseComments)
if err != nil {
return err
}
if err := runfile(f, file); err != nil {
return err
}
}
return nil
}
// runfile generates struct tags for the given file.
func runfile(f *ast.File, file string) error {
cmd := makeCmd()
for _, c := range cmd.Commands() {
if c.Name() == "gen" {
runner := c.Run
// Default to appending the filename to the args, if a target isn't
// specified.
c.Run = func(cmd *cobra.Command, args []string) {
if len(args) == 1 {
args = append(args, file)
}
runner(cmd, args)
}
}
}
for _, c := range f.Comments {
if strings.HasPrefix(c.Text(), prefix) {
args, err := shellquote.Split(c.Text()[len(prefix):])
if err != nil {
return err
}
args = append([]string{"graffiti", "gen"}, args...)
os.Args = args
if err := cmd.Execute(); err != nil {
return err
}
}
}
return nil
}