-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
73 lines (61 loc) · 1.64 KB
/
Copy pathparser.go
File metadata and controls
73 lines (61 loc) · 1.64 KB
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
package jssquish
import (
"io"
"log"
"github.com/robertkrimen/otto/ast"
"github.com/robertkrimen/otto/parser"
)
func ParseRequires(r io.Reader, path string) ([]string, error) {
program, err := parser.ParseFile(nil, path, r, parser.IgnoreRegExpErrors)
if err != nil {
return nil, err
}
visitor := NewRequireVisitor()
for _, stmt := range program.Body {
if err := WalkNode(visitor, stmt); err != nil {
return nil, err
}
}
return visitor.Requires(), nil
}
type RequireVisitor struct {
requires map[string]bool
}
func NewRequireVisitor() *RequireVisitor {
return &RequireVisitor{
requires: make(map[string]bool),
}
}
func (rv *RequireVisitor) Visit(n ast.Node) bool {
if ce, ok := n.(*ast.CallExpression); ok {
return rv.visitCallExpression(ce)
}
return true
}
func (rv *RequireVisitor) visitCallExpression(ce *ast.CallExpression) bool {
if callee, ok := ce.Callee.(*ast.Identifier); ok && callee.Name == "require" {
args := ce.ArgumentList
// If encountering a `require` call with more than one argument, log a
// message and bail without descending.
if len(args) != 1 {
log.Printf("require statement found with >1 arguments.")
return false
}
// When encountering a non-string argument, log a message and bail without
// descending.
if str, ok := args[0].(*ast.StringLiteral); !ok {
log.Printf("require statement with non-string argument found")
return false
} else {
rv.requires[str.Value] = true
}
}
return true
}
func (rv *RequireVisitor) Requires() []string {
requires := make([]string, 0, len(rv.requires))
for k := range rv.requires {
requires = append(requires, k)
}
return requires
}