Debian Codegraph @

eutils/format.go

raw
1 // ===========================================================================
2 //
3 // PUBLIC DOMAIN NOTICE
4 // National Center for Biotechnology Information (NCBI)
5 //
6 // This software/database is a "United States Government Work" under the
7 // terms of the United States Copyright Act. It was written as part of
8 // the author's official duties as a United States Government employee and
9 // thus cannot be copyrighted. This software/database is freely available
10 // to the public for use. The National Library of Medicine and the U.S.
11 // Government do not place any restriction on its use or reproduction.
12 // We would, however, appreciate having the NCBI and the author cited in
13 // any work or product based on this material.
14 //
15 // Although all reasonable efforts have been taken to ensure the accuracy
16 // and reliability of the software and data, the NLM and the U.S.
17 // Government do not and cannot warrant the performance or results that
18 // may be obtained by using this software or data. The NLM and the U.S.
19 // Government disclaim all warranties, express or implied, including
20 // warranties of performance, merchantability or fitness for any particular
21 // purpose.
22 //
23 // ===========================================================================
24 //
25 // File Name: format.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "os"
35 "strings"
36 )
37
38 // FormatArgs contains XML format customization arguments
39 type FormatArgs struct {
40 Format string
41 XML string
42 Doctype string
43 Unicode string
44 Script string
45 Mathml string
46 Combine bool
47 Self bool
48 Comment bool
49 Cdata bool
50 }
51
52 // xmlFormatter reformats a record string or a stream of XML tokens
53 func xmlFormatter(rcrd, prnt string, inp <-chan XMLToken, offset int, doXML bool, args FormatArgs) <-chan string {
54
55 if rcrd == "" && inp == nil {
56 return nil
57 }
58
59 out := make(chan string, chanDepth)
60 if out == nil {
61 DisplayError("Unable to create formatter channel")
62 os.Exit(1)
63 }
64
65 compRecrd := false
66 flushLeft := false
67 wrapAttrs := false
68 ret := "\n"
69
70 switch args.Format {
71 case "compact", "compacted", "compress", "compressed", "terse", "*":
72 // compress to one record per line
73 compRecrd = true
74 ret = ""
75 case "flush", "flushed", "left":
76 // suppress line indentation
77 flushLeft = true
78 case "expand", "expanded", "extend", "extended", "verbose", "@":
79 // each attribute on its own line
80 wrapAttrs = true
81 case "indent", "indented", "normal", "default", "":
82 // default behavior
83 default:
84 DisplayError("Unrecognized format '%s'", args.Format)
85 os.Exit(1)
86 }
87
88 fuseTopSets := args.Combine
89 keepSelfClosing := args.Self
90
91 doComment := args.Comment
92 doCdata := args.Cdata
93
94 // formatXML goroutine processes one record
95 formatXML := func(rcrd, prnt string, inp <-chan XMLToken, offset int, doXML bool, out chan<- string) {
96
97 // close channel when all chunks have been sent
98 defer close(out)
99
100 xml := args.XML
101
102 doctype := ""
103 customDoctype := false
104
105 if args.Doctype != "" {
106 customDoctype = true
107 if !strings.HasPrefix(args.Doctype, "-") {
108 doctype = args.Doctype
109 }
110 }
111
112 var buffer strings.Builder
113
114 count := 0
115
116 // array to speed up indentation
117 indentSpaces := []string{
118 "",
119 " ",
120 " ",
121 " ",
122 " ",
123 " ",
124 " ",
125 " ",
126 " ",
127 " ",
128 }
129
130 indent := offset
131
132 // indent a specified number of spaces
133 doIndent := func(indt int) {
134 if compRecrd || flushLeft {
135 return
136 }
137 i := indt
138 for i > 9 {
139 buffer.WriteString(" ")
140 i -= 10
141 }
142 if i < 0 {
143 return
144 }
145 buffer.WriteString(indentSpaces[i])
146 }
147
148 badAttributeSpacing := func(attr string) bool {
149
150 if len(attr) < 2 {
151 return false
152 }
153
154 var prev rune
155
156 insideQuotes := false
157
158 for _, ch := range attr {
159 if ch == '"' {
160 // "
161 if insideQuotes {
162 insideQuotes = false
163 } else {
164 insideQuotes = true
165 }
166 prev = ch
167 continue
168 }
169 if insideQuotes {
170 prev = ch
171 continue
172 }
173 if ch == '=' && prev == ' ' {
174 return true
175 }
176 if ch == ' ' && prev == '=' {
177 return true
178 }
179 prev = ch
180 }
181
182 return false
183 }
184
185 // print attributes
186 printAttributes := func(attr string) {
187
188 if attr == "" {
189 return
190 }
191 attr = strings.TrimSpace(attr)
192 attr = CompressRunsOfSpaces(attr)
193
194 if deAccent {
195 if IsNotASCII(attr) {
196 attr = TransformAccents(attr, false, true)
197 }
198 }
199 if doASCII {
200 if IsNotASCII(attr) {
201 attr = UnicodeToASCII(attr)
202 }
203 }
204
205 if wrapAttrs {
206
207 start := 0
208 idx := 0
209 inQuote := false
210
211 attlen := len(attr)
212
213 for idx < attlen {
214 ch := attr[idx]
215 if ch == '=' && !inQuote {
216 inQuote = true
217 str := strings.TrimSpace(attr[start:idx])
218 buffer.WriteString("\n")
219 doIndent(indent)
220 buffer.WriteString(" ")
221 buffer.WriteString(str)
222 // skip past equal sign
223 idx++
224 ch = attr[idx]
225 if ch != '"' && ch != '\'' {
226 // "
227 // skip past unexpected blanks
228 for inBlank[ch] {
229 idx++
230 ch = attr[idx]
231 }
232 }
233 // skip past leading double quote
234 idx++
235 start = idx
236 } else if ch == '"' || ch == '\'' {
237 // "
238 inQuote = !inQuote
239 str := strings.TrimSpace(attr[start:idx])
240 buffer.WriteString("=\"")
241 buffer.WriteString(str)
242 buffer.WriteString("\"")
243 // skip past trailing double quote and (possible) space
244 idx += 2
245 start = idx
246 } else {
247 idx++
248 }
249 }
250
251 buffer.WriteString("\n")
252 doIndent(indent)
253
254 } else if badAttributeSpacing(attr) {
255
256 buffer.WriteString(" ")
257
258 start := 0
259 idx := 0
260
261 attlen := len(attr)
262
263 for idx < attlen {
264 ch := attr[idx]
265 if ch == '=' {
266 str := strings.TrimSpace(attr[start:idx])
267 buffer.WriteString(str)
268 // skip past equal sign
269 idx++
270 ch = attr[idx]
271 if ch != '"' && ch != '\'' {
272 // "
273 // skip past unexpected blanks
274 for inBlank[ch] {
275 idx++
276 ch = attr[idx]
277 }
278 }
279 // skip past leading double quote
280 idx++
281 start = idx
282 } else if ch == '"' || ch == '\'' {
283 // "
284 str := strings.TrimSpace(attr[start:idx])
285 buffer.WriteString("=\"")
286 buffer.WriteString(str)
287 buffer.WriteString("\"")
288 // skip past trailing double quote and (possible) space
289 idx += 2
290 start = idx
291 } else {
292 idx++
293 }
294 }
295
296 } else {
297
298 buffer.WriteString(" ")
299 buffer.WriteString(attr)
300 }
301 }
302
303 parent := ""
304 pfx := ""
305 skip := 0
306 okIndent := true
307
308 printXMLAndDoctype := func(xml, doctype, parent string) {
309
310 // check for xml line explicitly set in argument
311 if xml != "" {
312 xml = CleanXmltype(xml)
313 buffer.WriteString(xml)
314 } else {
315 buffer.WriteString("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>")
316 }
317
318 buffer.WriteString("\n")
319
320 // check for doctype taken from XML file or explicitly set in argument
321 if doctype != "" {
322 doctype = CleanDoctype(doctype)
323 buffer.WriteString(doctype)
324 } else {
325 buffer.WriteString("<!DOCTYPE ")
326 buffer.WriteString(parent)
327 buffer.WriteString(">")
328 }
329
330 buffer.WriteString("\n")
331 }
332
333 cleanupMixed := func(txt string) string {
334
335 txt = DoTrimFlankingHTML(txt)
336 if HasBadSpace(txt) {
337 txt = CleanupBadSpaces(txt)
338 }
339 if HasAdjacentSpaces(txt) {
340 txt = CompressRunsOfSpaces(txt)
341 }
342 if NeedsTightening(txt) {
343 txt = TightenParentheses(txt)
344 }
345
346 return txt
347 }
348
349 cleanToken := func(tkn XMLToken, nxtTag int, nxtName, nxtAttr string, lastContent bool) {
350
351 if skip > 0 {
352 skip--
353 return
354 }
355
356 name := tkn.Name
357
358 switch tkn.Tag {
359 case STARTTAG:
360 // detect first start tag, print xml and doctype parent
361 if indent == 0 && parent == "" {
362 parent = name
363 if doXML {
364 printXMLAndDoctype(xml, doctype, parent)
365 }
366 // do not fuse <opt> or <anon> top-level objects (converted from JSON)
367 if parent == "opt" || parent == "anon" {
368 fuseTopSets = false
369 }
370 }
371 // convert start-stop to self-closing tag if attributes are present, otherwise skip
372 if nxtTag == STOPTAG && nxtName == name {
373 if tkn.Attr != "" || keepSelfClosing {
374 buffer.WriteString(pfx)
375 doIndent(indent)
376 buffer.WriteString("<")
377 buffer.WriteString(name)
378 printAttributes(tkn.Attr)
379 buffer.WriteString("/>")
380 pfx = ret
381 okIndent = true
382 }
383 skip++
384 return
385 }
386 buffer.WriteString(pfx)
387 if doMixed {
388 if !lastContent {
389 doIndent(indent)
390 }
391 } else {
392 doIndent(indent)
393 }
394 indent++
395 buffer.WriteString("<")
396 buffer.WriteString(name)
397 printAttributes(tkn.Attr)
398 buffer.WriteString(">")
399 pfx = ret
400 okIndent = true
401 if compRecrd && indent == 1 {
402 buffer.WriteString("\n")
403 }
404 case SELFTAG:
405 if tkn.Attr != "" || keepSelfClosing {
406 buffer.WriteString(pfx)
407 doIndent(indent)
408 buffer.WriteString("<")
409 buffer.WriteString(name)
410 printAttributes(tkn.Attr)
411 buffer.WriteString("/>")
412 pfx = ret
413 okIndent = true
414 }
415 case STOPTAG:
416 // skip internal copies of top-level </parent><parent> tags (to fuse multiple chunks returned by efetch)
417 // do not skip if attributes are present, unless pattern ends in "Set" (e.g., <DocumentSummarySet status="OK">)
418 if nxtTag == STARTTAG && indent == 1 && fuseTopSets && nxtName == parent {
419 if nxtAttr == "" || (strings.HasSuffix(parent, "Set") && len(parent) > 3) {
420 skip++
421 return
422 }
423 }
424 buffer.WriteString(pfx)
425 indent--
426 if okIndent {
427 doIndent(indent)
428 }
429 buffer.WriteString("</")
430 buffer.WriteString(name)
431 buffer.WriteString(">")
432 if doMixed && nxtTag == CONTENTTAG && nxtName != "." {
433 buffer.WriteString(" ")
434 }
435 pfx = ret
436 okIndent = true
437 if compRecrd && indent < 2 {
438 buffer.WriteString("\n")
439 }
440 case CONTENTTAG:
441 if nxtTag == STARTTAG || nxtTag == SELFTAG {
442 if doStrict {
443 DisplayError("UNRECOGNIZED MIXED CONTENT <%s> IN <%s>", nxtName, name)
444 } else if !doMixed {
445 DisplayError("UNEXPECTED MIXED CONTENT <%s> IN <%s>", nxtName, name)
446 }
447 }
448 if len(name) > 0 && IsNotJustWhitespace(name) {
449 // support for all content processing flags
450 if doStrict || doMixed || doCompress || deAccent {
451 ctype := tkn.Cont
452 name = CleanupContents(name, (ctype&ASCII) != 0, (ctype&AMPER) != 0, (ctype&MIXED) != 0)
453 }
454 if doMixed {
455 name = cleanupMixed(name)
456 }
457 buffer.WriteString(name)
458 }
459 if (doStrict || doMixed) && !deAccent && nxtTag == STARTTAG {
460 buffer.WriteString(" ")
461 }
462 pfx = ""
463 okIndent = false
464 case CDATATAG:
465 if doCdata {
466 buffer.WriteString(pfx)
467 doIndent(indent)
468 buffer.WriteString("<![CDATA[")
469 buffer.WriteString(name)
470 buffer.WriteString("]]>")
471 pfx = ret
472 okIndent = true
473 }
474 case COMMENTTAG:
475 if doComment {
476 buffer.WriteString(pfx)
477 doIndent(indent)
478 buffer.WriteString("<!--")
479 buffer.WriteString(name)
480 buffer.WriteString("-->")
481 pfx = ret
482 okIndent = true
483 }
484 case DOCTYPETAG:
485 if customDoctype && doctype == "" {
486 doctype = name
487 }
488 case PROCESSTAG:
489 case NOTAG:
490 case ISCLOSED:
491 // now handled at end of calling function
492 default:
493 buffer.WriteString(pfx)
494 pfx = ""
495 okIndent = false
496 }
497
498 count++
499 if count > 1000 {
500 count = 0
501 txt := buffer.String()
502 if txt != "" {
503 // send current result through output channel
504 out <- txt
505 }
506 buffer.Reset()
507 }
508 }
509
510 var prev XMLToken
511 primed := false
512 skipDoctype := false
513 lastContent := false
514
515 // track adjacent pairs to give look-ahead at next token
516 doPair := func(tkn XMLToken) {
517
518 if tkn.Tag == NOTAG {
519 return
520 }
521
522 if tkn.Tag == DOCTYPETAG {
523 if skipDoctype {
524 return
525 }
526 skipDoctype = true
527 }
528
529 if primed {
530 cleanToken(prev, tkn.Tag, tkn.Name, tkn.Attr, lastContent)
531 }
532
533 lastContent = (prev.Tag == CONTENTTAG)
534 prev = XMLToken{Tag: tkn.Tag, Cont: tkn.Cont, Name: tkn.Name, Attr: tkn.Attr, Index: tkn.Index, Line: tkn.Line}
535 primed = true
536 }
537
538 if inp != nil {
539
540 // track adjacent pairs to give look-ahead at next token
541 for tkn := range inp {
542
543 doPair(tkn)
544 }
545
546 } else {
547
548 parseXML(rcrd, prnt, nil, doPair, nil, nil)
549 }
550
551 // isclosed tag
552 if primed {
553 buffer.WriteString(pfx)
554 txt := buffer.String()
555 if txt != "" {
556 // send remaining result through output channel
557 out <- txt
558 }
559 }
560 }
561
562 // launch single formatter goroutine
563 go formatXML(rcrd, prnt, inp, offset, doXML, out)
564
565 return out
566 }
567
568 // FormatRecord formats a single partitioned XML record
569 func FormatRecord(rcrd, prnt string, args FormatArgs) <-chan string {
570
571 return xmlFormatter(rcrd, prnt, nil, 1, false, args)
572 }
573
574 // FormatTokens formats an XML token stream
575 func FormatTokens(inp <-chan XMLToken, args FormatArgs) <-chan string {
576
577 return xmlFormatter("", "", inp, 0, true, args)
578 }