File: xmlreader.go

package info (click to toggle)
golang-github-spdx-gordf 0.0~git20221230.b735bd5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 324 kB
  • sloc: makefile: 4
file content (450 lines) | stat: -rw-r--r-- 11,698 bytes parent folder | download
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package rdfloader

/**
 * This module provides the functions needed to read a file tag by tag.
 * Since the documents are written in rdf/xml,
 * Creating an xml reader for reading rdf tags.
 */

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os"
)

// reads a:b into a Pair Object.
func (xmlReader *XMLReader) readColonPair(delim uint64) (pair Pair, colonFound bool, err error) {
	// file pointer must point to the start of the attribute.
	word, err := xmlReader.readTill(delim)
	if err != nil {
		return
	}

	for i, r := range word {
		if r == ':' {
			colonFound = true
			pair.First = string(word[:i])
			latter := string(word[i+1:])
			if len(latter) == 0 {
				err = errors.New("expected a word after colon")
				return
			}
			pair.Second = latter
			break
		}
	}
	if !colonFound {
		// no colon was found.
		pair.First = string(word)
	}
	return
}

func (xmlReader *XMLReader) readAttribute() (attr Attribute, err error) {
	// assumes the file pointer is pointing to the attribute name
	pair, colonExists, err := xmlReader.readColonPair(WHITESPACE | 1<<'=')
	if err != nil {
		return
	}

	if colonExists {
		attr.SchemaName = pair.First.(string)
		attr.Name = pair.Second.(string)
	} else {
		attr.Name = pair.First.(string)
	}
	_, err = xmlReader.ignoreWhiteSpace()
	if err != nil {
		return
	}

	nextRune, err := xmlReader.readARune()
	if err != nil {
		return attr, err
	}
	if nextRune != '=' {
		err = errors.New("expected an assignment sign (=)")
	}

	firstQuote, err := xmlReader.readARune()
	if !(firstQuote == '\'' || firstQuote == '"') {
		err = errors.New("assignment operator must be followed by an attribute enclosed within quotes")
	}

	// read till next quote or a blank character.
	word, err := xmlReader.readTill(WHITESPACE | 1<<uint(firstQuote))
	if err != nil {
		return attr, err
	}

	secondQuote, _ := xmlReader.readARune()
	if firstQuote != secondQuote {
		return attr, errors.New("unexpected blank char. expected a closing quote")
	}

	attr.Value = string(word)
	return attr, nil
}

func (xmlReader *XMLReader) readCDATA() (cdata string, err error) {
	// Cdata tag is given by <![CDATA[ data ]]
	// before calling this function, < should've be read.
	// the file pointer should  point to !
	CDATA_OPENING := "<![CDATA["
	CDATA_CLOSING := "]]>"
	nBytes, err := xmlReader.readNBytes(len(CDATA_OPENING))
	if err != nil {
		return
	}
	tempString := string(nBytes)
	if tempString != CDATA_OPENING {
		return cdata, fmt.Errorf("not a valid cdata tag. expected: %s, found: %s", CDATA_OPENING, tempString)
	}

	// move the file pointer to exclude the cdata declaration tag.
	data, err := xmlReader.readTillString(CDATA_CLOSING)
	if err != nil {
		return cdata, fmt.Errorf("%v reading CDATA End Tag", err)
	}

	// move file pointer by 3 to ignore the ]]> chars.
	xmlReader.readNBytes(len(CDATA_CLOSING))

	return CDATA_OPENING + string(data) + CDATA_CLOSING, nil
}

func (xmlReader *XMLReader) readOpeningTag() (tag Tag, isProlog, blockComplete bool, err error) {
	// Opening Tag can be:
	//		<tag[:schema]
	//			[attr=attr_val]
	//			[attr=attr_val]...	>
	// or
	//		<tag[:schema]
	//			[attr=attr_val]
	//			[attr=attr_val]...	/>
	// Second example is a completed block where no value or internal nodes were found.

	var word []rune

	// forward file pointer until a non-blank character is found.
	// removing all blank characters before opening bracket.
	_, err = xmlReader.ignoreWhiteSpace()
	if err != nil {
		return // possibly an eof error
	}

	// find the opening angular bracket.
	// after stripping all the spaces, the next character should be '<'
	//   If the next character is not '<',
	//       there are few chars before opening tag. Which is not allowed!
	word, err = xmlReader.readTill(1 << '<')
	if err == io.EOF {
		// we reached the end of the file while searching for a new tag.
		if len(word) > 0 {
			return tag, isProlog, blockComplete, errors.New("found stray characters at EOF")
		} else {
			// no new tags were found.
			return tag, isProlog, blockComplete, io.EOF
		}
	}
	if len(word) != 0 {
		return tag, isProlog, blockComplete, errors.New("found extra chars before tag start")
	}

	// next char is '<'.
	xmlReader.readARune()
	xmlReader.ignoreWhiteSpace() // there shouldn't be any spaces in a well-formed rdf/xml document.

	nextRune, err := xmlReader.peekARune()
	if err != nil {
		return
	}

	switch nextRune {
	case '/':
		return tag, isProlog, blockComplete, errors.New("unexpected closing tag")
	case '?':
		// a prolog is found.
		isProlog = true
		// ignore the question mark character.
		xmlReader.readARune()
		// read till the next question mark.
		_, err := xmlReader.readTill(1 << '?')
		if err != nil {
			return tag, isProlog, blockComplete, err
		}
		// ignore the question mark character.
		xmlReader.readARune()

		_, err = xmlReader.ignoreWhiteSpace()
		if err != nil {
			return tag, isProlog, blockComplete, err
		}

		nextRune, err = xmlReader.peekARune()
		if err != nil {
			return tag, isProlog, blockComplete, err
		}
		if nextRune == '>' {
			// ignore >
			xmlReader.readARune()
			return tag, isProlog, blockComplete, err
		}
		err = fmt.Errorf("expected a > char after ?. Found %v", nextRune)
		return tag, isProlog, blockComplete, err
	}

	// reading the next word till we reach a colon or a blank-char or a closing angular bracket.
	pair, colonExist, err := xmlReader.readColonPair(1<<'>' | WHITESPACE | 1<<'/')
	if err != nil {
		return
	}

	if colonExist {
		tag.SchemaName = pair.First.(string)
		tag.Name = pair.Second.(string)
	} else {
		tag.Name = pair.First.(string)
	}

	delim, _ := xmlReader.peekARune() // read the delimiter.
	if ((1 << uint(delim)) & WHITESPACE) != 0 {
		// delimiter was a blank space.
		// <schemaName:tagName [whitespace] was found.
		xmlReader.ignoreWhiteSpace()
	}
	delim, _ = xmlReader.peekARune()
	switch delim {
	case '>':
		// found end of tag. entire tag was parsed.
		xmlReader.readARune()
		return

	case '/':
		// "<[schemaName:]tag /" was parsed. expecting next character to be a closing angular bracket.
		xmlReader.readARune()
		blockComplete = true

		nextRune, err := xmlReader.readARune()
		if err != nil {
			return tag, isProlog, blockComplete, err
		}

		if nextRune != '>' {
			err = errors.New("expected closing angular bracket after /")
		}
		return tag, isProlog, blockComplete, err
	}

	// "<[schemaName:]tagName" is parsed till now.

	_, err = xmlReader.ignoreWhiteSpace()
	if err != nil {
		return
	}

	nextRune, err = xmlReader.peekARune()
	if err != nil {
		return
	}

	if nextRune == '>' {
		// opening tag didn't had any attributes.
		tag.Name = string(word)
		xmlReader.readARune() // consuming the '>' character
		return
	}

	// there are some attributes to be read.
	// read attributes till the next character is a forward slash or a '>'
	for !(nextRune == '>' || nextRune == '/') {
		attr, err := xmlReader.readAttribute()
		if err != nil {
			return tag, isProlog, blockComplete, err
		}

		tag.Attrs = append(tag.Attrs, attr)
		_, err = xmlReader.ignoreWhiteSpace()
		if err != nil {
			return tag, isProlog, blockComplete, err
		}

		nextRune, err = xmlReader.peekARune()
		if err != nil {
			return tag, isProlog, blockComplete, err
		}
	}

	nextRune, _ = xmlReader.readARune()

	if nextRune == '/' {
		// "<[schemaName:]tag /" was parsed. expecting next character to be a closing angular bracket.
		blockComplete = true

		nextRune, err := xmlReader.readARune()
		if err != nil {
			return tag, isProlog, blockComplete, err
		}

		if nextRune != '>' {
			err = errors.New("expected closing angular bracket after /")
		}
	}
	return tag, isProlog, blockComplete, err
}

func (xmlReader *XMLReader) readClosingTag() (closingTag Tag, err error) {
	// expects white space to be stripped before the call to this function.
	next2Bytes, err := xmlReader.readNBytes(2)
	if err != nil {
		return closingTag, err
	}

	if string(next2Bytes) != "</" {
		return closingTag, errors.New("expected a closing tag")
	}

	pair, colonExists, err := xmlReader.readColonPair(1<<'>' | WHITESPACE)
	if err != nil {
		return closingTag, err
	}
	if colonExists {
		closingTag.SchemaName = pair.First.(string)
		closingTag.Name = pair.Second.(string)
	} else {
		closingTag.Name = pair.First.(string)
	}

	xmlReader.ignoreWhiteSpace()
	nextChar, err := xmlReader.readARune()
	if err != nil {
		return closingTag, err
	}

	if nextChar != '>' {
		return closingTag, errors.New("expected a > char")
	}

	return closingTag, err
}

func (xmlReader *XMLReader) readBlock() (block Block, err error) {
	openingTag, isProlog, blockComplete, err := xmlReader.readOpeningTag()
	if isProlog {
		return xmlReader.readBlock()
	}
	if err != nil {
		return
	}
	block.OpeningTag = openingTag

	if blockComplete {
		// tag was of this type: <schemaName:tagName />
		return block, err
	}

	xmlReader.ignoreWhiteSpace()

	// <schemaName:tagName [attributes] > is read till now.
	nextRune, err := xmlReader.peekARune()
	if err != nil {
		return
	}

	if nextRune != '<' {
		// the tag must be wrapping a string resource within it.
		// tag is of type <schemaName:tagName> value </schemaName:tagName>
		word, err := xmlReader.readTill(1 << '<') // according to the example, word=value.
		if err != nil {
			return block, err
		}
		block.Value = string(word)
	} else {
		// expecting a new tag or closing tag of the currently read tag or CDATA.
		nextTwoBytes, err := xmlReader.peekNBytes(2)
		if err != nil {
			return block, err
		}

		if string(nextTwoBytes) == "<!" {
			// cdata tag is found
			cdataTag, err := xmlReader.readCDATA()
			if err != nil {
				return block, err
			}
			block.Value = cdataTag
		} else {
			// while we don't get a closing tag, read the children.
			for string(nextTwoBytes) != "</" {
				// a new tag is found.
				childBlock, err := xmlReader.readBlock()
				if err != nil {
					return block, err
				}

				block.Children = append(block.Children, &childBlock)

				xmlReader.ignoreWhiteSpace()
				nextTwoBytes, err = xmlReader.peekNBytes(2)
				if err != nil {
					return block, err
				}
			}
		}
	}
	xmlReader.ignoreWhiteSpace()  // if any
	closingTag, err := xmlReader.readClosingTag()
	if err != nil {
		return block, err
	}
	if openingTag.Name != closingTag.Name || openingTag.SchemaName != closingTag.SchemaName {
		// opening and closing tags are not same.
		return block, fmt.Errorf("opening and closing tags doesn't match: opening tag; %v:%v, closing tag: %v:%v.", openingTag.SchemaName, openingTag.Name, closingTag.SchemaName, closingTag.Name)
	}
	return block, err
}

func (xmlReader *XMLReader) Read() (rootBlock Block, err error) {
	rootBlock, err = xmlReader.readBlock()
	if err != nil {
		return rootBlock, err
	}
	if xmlReader.fileObj != nil {
		xmlReader.fileObj.Close()
	}

	// after reading the first block ( the root block ),
	// there shouldn't be any other tags or characters.
	_, err = xmlReader.ignoreWhiteSpace()
	if err == nil {
		// some other chars were found after reading the rootblock.
		// expected err to be an EOF error.
		nextRune, _ := xmlReader.peekARune()
		return rootBlock, fmt.Errorf("unexpected chars after reading root block. Char Found: %v", string(nextRune))
	}
	return rootBlock, nil
}

func XMLReaderFromFileObject(fileObject *bufio.Reader) XMLReader {
	// user will be responsible for closing the file.
	return XMLReader{fileObject, nil}
}

func XMLReaderFromFilePath(filePath string) (xmlReader XMLReader, err error) {
	fileObj, err := os.Open(filePath)
	if err != nil {
		return xmlReader, err
	}

	xmlReader.fileReader = bufio.NewReader(fileObj)
	xmlReader.fileObj = fileObj
	return xmlReader, nil
}

func (xmlReader *XMLReader) CloseFileObj() {
	if xmlReader.fileObj != nil {
		xmlReader.fileObj.Close()
	}
}