1
0
mirror of https://github.com/ericchiang/pup synced 2024-11-28 10:58:12 +00:00
pup/funcs/display.go

70 lines
1.5 KiB
Go
Raw Normal View History

2014-09-02 03:53:12 +00:00
package funcs
import (
"code.google.com/p/go.net/html"
"fmt"
"regexp"
)
type Displayer interface {
Display(nodes []*html.Node)
}
type TextDisplayer struct {
}
func (t TextDisplayer) Display(nodes []*html.Node) {
for _, node := range nodes {
if node.Type == html.TextNode {
fmt.Println(node.Data)
}
children := []*html.Node{}
child := node.FirstChild
for child != nil {
children = append(children, child)
child = child.NextSibling
}
t.Display(children)
}
}
2014-09-03 02:23:02 +00:00
type AttrDisplayer struct {
Attr string
}
func (a AttrDisplayer) Display(nodes []*html.Node) {
for _, node := range nodes {
attributes := node.Attr
for _, attr := range attributes {
if attr.Key == a.Attr {
fmt.Println(attr.Val)
}
}
}
}
2014-09-02 03:53:12 +00:00
var (
// Display function helpers
displayMatcher *regexp.Regexp = regexp.MustCompile(`\{[^\}]*\}$`)
textFuncMatcher = regexp.MustCompile(`^text\{\}$`)
2014-09-03 02:23:02 +00:00
attrFuncMatcher = regexp.MustCompile(`^attr\{([^\}]*)\}$`)
2014-09-02 03:53:12 +00:00
)
func NewDisplayFunc(text string) (Displayer, error) {
if !displayMatcher.MatchString(text) {
return nil, fmt.Errorf("Not a display function")
}
switch {
case textFuncMatcher.MatchString(text):
return TextDisplayer{}, nil
case attrFuncMatcher.MatchString(text):
2014-09-03 02:23:02 +00:00
matches := attrFuncMatcher.FindStringSubmatch(text)
if len(matches) != 2 {
return nil, fmt.Errorf("")
} else {
return AttrDisplayer{matches[1]}, nil
}
2014-09-02 03:53:12 +00:00
}
return nil, fmt.Errorf("Not a display function")
}