This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
/
commands.go
103 lines (87 loc) · 2.04 KB
/
commands.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
103
package parsers
import (
"go/ast"
"go/parser"
"go/token"
"strings"
)
// ParsedCommand represents a single Configuration option
type ParsedCommand struct {
Name string
Usage string
Flags string
Type string
FnName string
}
// ParsedCommands represents a set of Configuration options
type ParsedCommands []ParsedCommand
type commandVisitor struct {
currentFn string
parsedCommands []ParsedCommand
}
// ParseCommandFile parses a single go file for Configuration options
func ParseCommandFile(path string) (ParsedCommands, error) {
fs := token.NewFileSet()
f, err := parser.ParseFile(fs, path, nil, 0)
if err != nil {
return nil, err
}
fv := &commandVisitor{}
ast.Walk(fv, f)
return fv.parsedCommands, nil
}
// ParseCommandDir parses a folder for go files with Configuration options
func ParseCommandDir(path string) (ParsedCommands, error) {
fs := token.NewFileSet()
pkgs, err := parser.ParseDir(fs, path, nil, 0)
if err != nil {
return nil, err
}
fv := &commandVisitor{}
for _, pkg := range pkgs {
ast.Walk(fv, pkg)
}
return fv.parsedCommands, nil
}
func (v *commandVisitor) Visit(node ast.Node) (w ast.Visitor) {
if fn, ok := node.(*ast.FuncDecl); ok {
v.currentFn = fn.Name.Name
}
if comp, ok := node.(*ast.CompositeLit); ok {
if selExpr, ok := comp.Type.(*ast.SelectorExpr); ok && isCommandType(selExpr) {
c := ParsedCommand{}
c.Type = selExpr.Sel.Name
for _, v := range comp.Elts {
if kvExpr, ok := v.(*ast.KeyValueExpr); ok {
key := exprToStr(kvExpr.Key)
val := exprToStr(kvExpr.Value)
switch key {
case "Name":
c.Name = val
case "Usage":
c.Usage = val
case "Flags":
c.Flags = cleanFlagset(val)
}
}
}
c.FnName = v.currentFn
v.parsedCommands = append(v.parsedCommands, c)
}
}
return v
}
func isCommandType(sel *ast.SelectorExpr) bool {
switch sel.Sel.Name {
case "App", "Command":
return true
}
return false
}
func cleanFlagset(fl string) string {
r := strings.NewReplacer(
"flagset.", "",
"(cfg)", "",
)
return r.Replace(fl)
}