-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmain.go
100 lines (85 loc) · 2.07 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
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"strings"
"github.com/fatih/motion/astcontext"
"github.com/fatih/motion/vim"
)
func main() {
if err := realMain(); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(1)
}
}
func realMain() error {
var (
flagFile = flag.String("file", "", "Filename to be parsed")
flagDir = flag.String("dir", "", "Directory to be parsed")
flagOffset = flag.Int("offset", 0, "Byte offset of the cursor position")
flagMode = flag.String("mode", "",
"Running mode. One of {enclosing, next, prev, decls, comment}")
flagInclude = flag.String("include", "",
"Included declarations for mode {decls}. Comma delimited. Options: {func, type}")
flagShift = flag.Int("shift", 0, "Shift value for the modes {next, prev}")
flagFormat = flag.String("format", "json", "Output format. One of {json, vim}")
flagParseComments = flag.Bool("parse-comments", false,
"Parse comments and add them to AST")
)
flag.Parse()
if flag.NFlag() == 0 {
flag.Usage()
return nil
}
if *flagMode == "" {
return errors.New("no mode is passed")
}
if *flagMode == "comment" {
*flagParseComments = true
}
opts := &astcontext.ParserOptions{
Comments: *flagParseComments,
File: *flagFile,
Dir: *flagDir,
}
parser, err := astcontext.NewParser(opts)
if err != nil {
return err
}
query := &astcontext.Query{
Mode: *flagMode,
Offset: *flagOffset,
Shift: *flagShift,
Includes: strings.Split(*flagInclude, ","),
}
result, err := parser.Run(query)
var res interface{}
res = result
if err != nil {
res = struct {
Err string `json:"err" vim:"err"`
}{
Err: err.Error(),
}
}
switch *flagFormat {
case "json":
b, err := json.MarshalIndent(&res, "", "\t")
if err != nil {
return fmt.Errorf("JSON error: %s", err)
}
os.Stdout.Write(b)
case "vim":
b, err := vim.Marshal(&res)
if err != nil {
return fmt.Errorf("VIM error: %s", err)
}
os.Stdout.Write(b)
default:
return fmt.Errorf("wrong -format value: %q", *flagFormat)
}
return nil
}