-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
359 lines (295 loc) · 8.26 KB
/
parser.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package netscape
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"io"
"strings"
)
const (
NetscapeBookmarkDoctype string = "NETSCAPE-Bookmark-file-1"
)
var (
ErrDoctypeMissing error = errors.New("missing DOCTYPE")
ErrDoctypeInvalid error = errors.New("invalid DOCTYPE")
)
var (
// Byte order mark
utf8bom = []byte{0xef, 0xbb, 0xbf}
)
// A ParseError is returned when we fail to parse a Netscape Bookmark token or XML
// element.
type ParseError struct {
Msg string
Pos int64
Err error
}
// Error returns the string representation for this error.
func (e *ParseError) Error() string {
return fmt.Sprintf("%s at position %d: %s", e.Msg, e.Pos, e.Err)
}
// Is compares this Error with a target error to satisfy an equality check.
func (e *ParseError) Is(target error) bool {
t, ok := target.(*ParseError)
if !ok {
return false
}
return e.Msg == t.Msg && e.Pos == t.Pos
}
// Unwrap returns the inner error wrapped by this Error.
func (e *ParseError) Unwrap() error {
return e.Err
}
func wrapWitParseError(msg string, pos int64, inner error) error {
return &ParseError{
Msg: msg,
Pos: pos,
Err: inner,
}
}
// Parse reads a Netscape Bookmark document and processes it token by token to
// build and return the corresponding AST.
func Parse(readseeker io.ReadSeeker) (*FileNode, error) {
p := newParser(readseeker)
return p.parse()
}
type parser struct {
readseeker io.ReadSeeker
decoder *xml.Decoder
tokenOffset int64
file *FileNode
currentFolder *FolderNode
currentBookmark *BookmarkNode
}
// newXMLDecoder initializes and returns a xml.Decoder with strict mode disabled,
// to handle Netscape Bookmark format quirks.
func newXMLDecoder(reader io.Reader) *xml.Decoder {
decoder := xml.NewDecoder(reader)
decoder.Strict = false
decoder.AutoClose = []string{
"p",
}
return decoder
}
func newParser(readseeker io.ReadSeeker) *parser {
decoder := newXMLDecoder(readseeker)
file := &FileNode{}
return &parser{
readseeker: readseeker,
decoder: decoder,
file: file,
}
}
func (p *parser) parse() (*FileNode, error) {
if err := p.verifyDoctype(); err != nil {
return &FileNode{}, err
}
for {
tok, err := p.decoder.Token()
if tok == nil || errors.Is(err, io.EOF) {
break
}
switch tokType := tok.(type) {
case xml.StartElement:
switch tokType.Name.Local {
case "TITLE", "Title":
if err := p.parseTitle(&tokType); err != nil {
return &FileNode{}, err
}
case "H1":
folder, err := p.parseFolder(&tokType)
if err != nil {
return &FileNode{}, err
}
p.file.Root = folder
p.currentFolder = &p.file.Root
case "DL", "DT":
if err := p.parseBookmarks(&tokType); err != nil {
return &FileNode{}, err
}
}
}
}
return p.file, nil
}
func (p *parser) parseTitle(start *xml.StartElement) error {
var title struct {
Value string `xml:",chardata"`
}
if err := p.decoder.DecodeElement(&title, start); err != nil {
return wrapWitParseError("failed to parse title", p.tokenOffset, err)
}
p.tokenOffset = p.decoder.InputOffset()
p.file.Title = title.Value
return nil
}
func (p *parser) parseFolder(start *xml.StartElement) (FolderNode, error) {
var elt struct {
Name string `xml:",chardata"`
}
if err := p.decoder.DecodeElement(&elt, start); err != nil {
return FolderNode{}, wrapWitParseError("failed to parse folder", p.tokenOffset, err)
}
p.tokenOffset = p.decoder.InputOffset()
folder := FolderNode{
Name: elt.Name,
Attributes: map[string]string{},
}
for _, attr := range start.Attr {
folder.Attributes[attr.Name.Local] = attr.Value
}
return folder, nil
}
func (p *parser) parseBookmarks(start *xml.StartElement) error {
var lastElementType string
for {
tok, err := p.decoder.Token()
if tok == nil || errors.Is(err, io.EOF) {
break
}
switch tokType := tok.(type) {
case xml.StartElement:
switch tokType.Name.Local {
case "A":
bookmark, err := p.parseBookmark(&tokType)
if err != nil {
return err
}
p.currentFolder.Bookmarks = append(p.currentFolder.Bookmarks, bookmark)
p.currentBookmark = &p.currentFolder.Bookmarks[len(p.currentFolder.Bookmarks)-1]
lastElementType = "A"
case "DD":
description, err := p.parseDescription()
if err != nil {
return err
}
switch lastElementType {
case "A":
p.currentBookmark.Description = description
case "H3":
p.currentFolder.Description = description
}
case "H3":
folder, err := p.parseFolder(&tokType)
if err != nil {
return err
}
folder.Parent = p.currentFolder
p.currentFolder.Subfolders = append(p.currentFolder.Subfolders, folder)
p.currentFolder = &p.currentFolder.Subfolders[len(p.currentFolder.Subfolders)-1]
lastElementType = "H3"
}
case xml.EndElement:
if tokType.Name.Local == "DL" {
p.currentFolder = p.currentFolder.Parent
}
}
}
return nil
}
func (p *parser) parseBookmark(start *xml.StartElement) (BookmarkNode, error) {
var link struct {
Title string `xml:",chardata"`
}
if err := p.decoder.DecodeElement(&link, start); err != nil {
return BookmarkNode{}, wrapWitParseError("failed to parse bookmark", p.tokenOffset, err)
}
p.tokenOffset = p.decoder.InputOffset()
bookmark := BookmarkNode{
Title: link.Title,
Attributes: map[string]string{},
}
for _, attr := range start.Attr {
if attr.Name.Local == "HREF" {
bookmark.Href = attr.Value
continue
}
bookmark.Attributes[attr.Name.Local] = attr.Value
}
return bookmark, nil
}
// parseDescription returns a string containing all data following a <DD>
// element, and preceding either a <DT> or </DL> element.
//
// Leading and trailing whitespace is trimmed from the returned string.
//
// A description may contain text and HTML elements.
func (p *parser) parseDescription() (string, error) {
startOffset := p.decoder.InputOffset()
endOffset := startOffset
var readseekOffset int64
// As the description may contain either text or HTML elements, we do not
// directly process the stream of XML tokens, and instead look for the start
// and end offsets of the description data in the underlying io.ReadSeeker.
loop:
for {
tok, err := p.decoder.Token()
if err != nil {
return "", wrapWitParseError("failed to parse description", p.tokenOffset, err)
}
p.tokenOffset = p.decoder.InputOffset()
switch tokType := tok.(type) {
case xml.CharData:
endOffset = p.decoder.InputOffset()
case xml.StartElement:
if tokType.Name.Local == "DL" || tokType.Name.Local == "DT" {
break loop
}
case xml.EndElement:
if tokType.Name.Local == "DD" || tokType.Name.Local == "DL" {
break loop
}
endOffset = p.decoder.InputOffset()
}
}
readseekOffset, err := p.readseeker.Seek(0, io.SeekCurrent)
if err != nil {
return "", err
}
// read raw data between start and end offsets
dataLen := int(endOffset - startOffset)
data := make([]byte, dataLen)
_, err = p.readseeker.Seek(startOffset, io.SeekStart)
if err != nil {
return "", fmt.Errorf("description: failed to reset readseeker position to %d: %w", startOffset, err)
}
nRead, err := p.readseeker.Read(data)
if err != nil {
return "", fmt.Errorf("description: failed to read data in range [%d:%d]: %w", startOffset, endOffset, err)
}
if nRead != dataLen {
return "", fmt.Errorf("description: expected to read %d bytes, read %d", dataLen, nRead)
}
// reset the io.ReadSeeker position
_, err = p.readseeker.Seek(readseekOffset, io.SeekStart)
if err != nil {
return "", fmt.Errorf("description: failed to reset readseeker position to %d: %w", startOffset, err)
}
// sanitize data
description := strings.TrimSpace(string(data))
return description, nil
}
func (p *parser) verifyDoctype() error {
for {
tok, err := p.decoder.Token()
if tok == nil || errors.Is(err, io.EOF) {
return ErrDoctypeMissing
}
p.tokenOffset = p.decoder.InputOffset()
switch tokType := tok.(type) {
case xml.CharData:
if bytes.Equal(tokType, utf8bom) {
continue
}
return wrapWitParseError("unexpected character data", p.tokenOffset, ErrDoctypeInvalid)
case xml.Directive:
if string(tokType) != fmt.Sprintf("DOCTYPE %s", NetscapeBookmarkDoctype) {
return wrapWitParseError(fmt.Sprintf("unknown DOCTYPE %s", string(tokType)), p.tokenOffset, ErrDoctypeInvalid)
}
return nil
default:
return ErrDoctypeMissing
}
}
}