-
Notifications
You must be signed in to change notification settings - Fork 256
/
parse.go
183 lines (175 loc) · 4.32 KB
/
parse.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main
import (
"fmt"
"io"
"os"
"strconv"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/charset"
"golang.org/x/text/transform"
)
var (
pupIn io.ReadCloser = os.Stdin
pupCharset string = ""
pupMaxPrintLevel int = -1
pupPreformatted bool = false
pupPrintColor bool = false
pupEscapeHTML bool = true
pupIndentString string = " "
pupDisplayer Displayer = TreeDisplayer{}
)
// Parse the html while handling the charset
func ParseHTML(r io.Reader, cs string) (*html.Node, error) {
var err error
if cs == "" {
// attempt to guess the charset of the HTML document
r, err = charset.NewReader(r, "")
if err != nil {
return nil, err
}
} else {
// let the user specify the charset
e, name := charset.Lookup(cs)
if name == "" {
return nil, fmt.Errorf("'%s' is not a valid charset", cs)
}
r = transform.NewReader(r, e.NewDecoder())
}
return html.Parse(r)
}
func PrintHelp(w io.Writer, exitCode int) {
helpString := `Usage
pup [flags] [selectors] [optional display function]
Version
%s
Flags
-c --color print result with color
-f --file file to read from
-h --help display this help
-i --indent number of spaces to use for indent or character
-n --number print number of elements selected
-l --limit restrict number of levels printed
-p --plain don't escape html
--pre preserve preformatted text
--charset specify the charset for pup to use
--version display version
`
fmt.Fprintf(w, helpString, VERSION)
os.Exit(exitCode)
}
func ParseArgs() ([]string, error) {
cmds, err := ProcessFlags(os.Args[1:])
if err != nil {
return []string{}, err
}
return ParseCommands(strings.Join(cmds, " "))
}
// Process command arguments and return all non-flags.
func ProcessFlags(cmds []string) (nonFlagCmds []string, err error) {
var i int
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Option '%s' requires an argument", cmds[i])
}
}()
nonFlagCmds = make([]string, len(cmds))
n := 0
for i = 0; i < len(cmds); i++ {
cmd := cmds[i]
switch cmd {
case "-c", "--color":
pupPrintColor = true
case "-p", "--plain":
pupEscapeHTML = false
case "--pre":
pupPreformatted = true
case "-f", "--file":
filename := cmds[i+1]
pupIn, err = os.Open(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(2)
}
i++
case "-h", "--help":
PrintHelp(os.Stdout, 0)
case "-i", "--indent":
indentLevel, err := strconv.Atoi(cmds[i+1])
if err == nil {
pupIndentString = strings.Repeat(" ", indentLevel)
} else {
pupIndentString = cmds[i+1]
}
i++
case "-l", "--limit":
pupMaxPrintLevel, err = strconv.Atoi(cmds[i+1])
if err != nil {
return []string{}, fmt.Errorf("Argument for '%s' must be numeric", cmd)
}
i++
case "--charset":
pupCharset = cmds[i+1]
i++
case "--version":
fmt.Println(VERSION)
os.Exit(0)
case "-n", "--number":
pupDisplayer = NumDisplayer{}
default:
if cmd[0] == '-' {
return []string{}, fmt.Errorf("Unrecognized flag '%s'", cmd)
}
nonFlagCmds[n] = cmds[i]
n++
}
}
return nonFlagCmds[:n], nil
}
// Split a string with awareness for quoted text and commas
func ParseCommands(cmdString string) ([]string, error) {
cmds := []string{}
last, next, max := 0, 0, len(cmdString)
for {
// if we're at the end of the string, return
if next == max {
if next > last {
cmds = append(cmds, cmdString[last:next])
}
return cmds, nil
}
// evaluate a rune
c := cmdString[next]
switch c {
case ' ':
if next > last {
cmds = append(cmds, cmdString[last:next])
}
last = next + 1
case ',':
if next > last {
cmds = append(cmds, cmdString[last:next])
}
cmds = append(cmds, ",")
last = next + 1
case '\'', '"':
// for quotes, consume runes until the quote has ended
quoteChar := c
for {
next++
if next == max {
return []string{}, fmt.Errorf("Unmatched open quote (%c)", quoteChar)
}
if cmdString[next] == '\\' {
next++
if next == max {
return []string{}, fmt.Errorf("Unmatched open quote (%c)", quoteChar)
}
} else if cmdString[next] == quoteChar {
break
}
}
}
next++
}
}