-
Notifications
You must be signed in to change notification settings - Fork 1
/
carrot.go
102 lines (81 loc) · 1.77 KB
/
carrot.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 carrot
import (
"net/http"
"github.com/zzossig/carrot/eval"
"github.com/zzossig/carrot/lexer"
"github.com/zzossig/carrot/parser"
"golang.org/x/net/html"
)
// CSS is a base object to evaluate css selectors.
type CSS struct {
selector string
context *eval.Context
errors []error
}
// New creates new CSS object.
func New() *CSS {
return &CSS{context: eval.NewContext()}
}
// SetDoc set document to a context.
// input param can be url or local filepath.
func (c *CSS) SetDoc(input string) *CSS {
c.context.GetBackCtx()
c.selector = ""
err := c.context.SetDoc(input)
if err != nil {
c.errors = append(c.errors, err)
}
return c
}
// SetDocR is another version of SetDoc.
func (c *CSS) SetDocR(r *http.Response) *CSS {
c.context.GetBackCtx()
c.selector = ""
err := c.context.SetDocR(r)
if err != nil {
c.errors = append(c.errors, err)
}
return c
}
// SetDocN is another version of SetDoc.
func (c *CSS) SetDocN(n *html.Node) *CSS {
c.context.GetBackCtx()
c.selector = ""
c.context.SetDocN(n)
return c
}
// SetDocS is another version of SetDoc.
func (c *CSS) SetDocS(s string) *CSS {
c.context.GetBackCtx()
c.selector = ""
err := c.context.SetDocS(s)
if err != nil {
c.errors = append(c.errors, err)
}
return c
}
// Eval evaluates a css selector
func (c *CSS) Eval(input string) []*html.Node {
if len(c.errors) > 0 {
return nil
}
c.selector = input
l := lexer.New(input)
p := parser.New(l)
pe := p.ParseExpression()
if len(p.Errors()) != 0 {
c.errors = append(c.errors, p.Errors()...)
return nil
}
e := eval.Eval(pe, c.context)
c.context.GetBackCtx()
return e
}
// Errors returns errors field
func (c *CSS) Errors() []error {
return c.errors
}
// String returns input field
func (c *CSS) String() string {
return c.selector
}