1
0
mirror of https://github.com/ericchiang/pup synced 2024-10-31 20:58:59 +00:00
pup/pup.go

81 lines
1.7 KiB
Go
Raw Normal View History

package main
import (
"fmt"
"os"
2016-07-23 04:42:23 +00:00
"golang.org/x/net/html"
)
// _=,_
// o_/6 /#\
// \__ |##/
// ='|--\
// / #'-.
// \#|_ _'-. /
// |/ \_( # |"
// C/ ,--___/
var VERSION string = "0.4.0"
func main() {
// process flags and arguments
2014-11-22 15:47:33 +00:00
cmds, err := ParseArgs()
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(2)
}
// Parse the input and get the root node
2014-12-14 04:52:41 +00:00
root, err := ParseHTML(pupIn, pupCharset)
if err != nil {
2014-12-14 04:52:41 +00:00
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(2)
}
2014-12-14 04:52:41 +00:00
pupIn.Close()
// Parse the selectors
selectorFuncs := []SelectorFunc{}
funcGenerator := Select
var cmd string
for len(cmds) > 0 {
cmd, cmds = cmds[0], cmds[1:]
if len(cmds) == 0 {
if err := ParseDisplayer(cmd); err == nil {
continue
}
}
switch cmd {
2014-11-22 15:56:35 +00:00
case "*": // select all
continue
case ">":
2014-12-07 02:08:03 +00:00
funcGenerator = SelectFromChildren
case "+":
funcGenerator = SelectNextSibling
2014-11-22 15:56:35 +00:00
case ",": // nil will signify a comma
selectorFuncs = append(selectorFuncs, nil)
default:
selector, err := ParseSelector(cmd)
if err != nil {
fmt.Fprintf(os.Stderr, "Selector parsing error: %s\n", err.Error())
os.Exit(2)
}
selectorFuncs = append(selectorFuncs, funcGenerator(selector))
funcGenerator = Select
}
}
2014-11-22 15:56:35 +00:00
selectedNodes := []*html.Node{}
currNodes := []*html.Node{root}
for _, selectorFunc := range selectorFuncs {
2014-11-22 15:56:35 +00:00
if selectorFunc == nil { // hit a comma
selectedNodes = append(selectedNodes, currNodes...)
currNodes = []*html.Node{root}
} else {
currNodes = selectorFunc(currNodes)
}
}
2014-11-22 15:56:35 +00:00
selectedNodes = append(selectedNodes, currNodes...)
pupDisplayer.Display(selectedNodes)
}