1
0
mirror of https://github.com/ericchiang/pup synced 2024-11-28 02:48:16 +00:00

selector interface simplified

This commit is contained in:
ericchiang 2014-09-17 20:32:49 -04:00
parent 9f9ed735dc
commit 548f9480f4
2 changed files with 13 additions and 14 deletions

12
main.go
View File

@ -12,7 +12,7 @@ import (
"strings" "strings"
) )
const VERSION string = "0.1.3" const VERSION string = "0.2.0"
var ( var (
// Flags // Flags
@ -133,6 +133,8 @@ func main() {
} }
selectors := make([]selector.Selector, len(cmds)) selectors := make([]selector.Selector, len(cmds))
for i, cmd := range cmds { for i, cmd := range cmds {
// if this is the last element, check for a function like
// text{} or attr{}
if i+1 == len(cmds) { if i+1 == len(cmds) {
d, err := funcs.NewDisplayFunc(cmd) d, err := funcs.NewDisplayFunc(cmd)
if err == nil { if err == nil {
@ -147,14 +149,8 @@ func main() {
} }
} }
currNodes := []*html.Node{root} currNodes := []*html.Node{root}
var selected []*html.Node
for _, selector := range selectors { for _, selector := range selectors {
selected = []*html.Node{} currNodes = selector.Select(currNodes)
for _, node := range currNodes {
selected = append(selected,
selector.FindAllChildren(node)...)
}
currNodes = selected
} }
if displayer != nil { if displayer != nil {
displayer.Display(currNodes) displayer.Display(currNodes)

View File

@ -14,12 +14,7 @@ type BasicSelector struct {
} }
type Selector interface { type Selector interface {
// Does this selector match a given node? Select(nodes []*html.Node) []*html.Node
Match(node *html.Node) bool
// Find all nodes which match a selector. May return itself.
FindAll(node *html.Node) []*html.Node
// Find all child nodes which match a selector.
FindAllChildren(node *html.Node) []*html.Node
} }
type selectorField int type selectorField int
@ -161,6 +156,14 @@ func NewSelector(s string) (Selector, error) {
return selector, nil return selector, nil
} }
func (sel BasicSelector) Select(nodes []*html.Node) []*html.Node {
selected := []*html.Node{}
for _, node := range nodes {
selected = append(selected, sel.FindAllChildren(node)...)
}
return selected
}
// Find all nodes which match a selector. // Find all nodes which match a selector.
func (sel BasicSelector) FindAllChildren(node *html.Node) []*html.Node { func (sel BasicSelector) FindAllChildren(node *html.Node) []*html.Node {
selected := []*html.Node{} selected := []*html.Node{}