Debian Codegraph @

cmd/rchive.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: rchive.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package main
32
33 import (
34 "bufio"
35 "bytes"
36 "eutils"
37 "fmt"
38 "github.com/klauspost/pgzip"
39 "hash/crc32"
40 "html"
41 "io"
42 "maps"
43 "os"
44 "os/user"
45 "path/filepath"
46 "runtime"
47 "runtime/debug"
48 "runtime/pprof"
49 "slices"
50 "strconv"
51 "strings"
52 "time"
53 )
54
55 // CONCURRENT GOROUTINE SERVERS
56
57 // processes with single goroutine call defer close(out) so consumer(s) can range over channel
58 // processes with multiple instances call defer wg.Done(), separate goroutine uses wg.Wait() to delay close(out)
59
60 // MAIN FUNCTION
61
62 func main() {
63
64 // skip past executable name
65 args := os.Args[1:]
66
67 if len(args) < 1 {
68 eutils.DisplayError("No command-line arguments supplied to rchive")
69 os.Exit(1)
70 }
71
72 // print EDirect local archive master and working paths, separated by colon
73 if args[0] == "-local" && len(args) > 1 {
74 db := args[1]
75 if len(args) > 2 {
76 fld := args[2]
77 base := eutils.GetLocalArchiveFolder(db, fld, false)
78 if base != "" {
79 fmt.Fprintf(os.Stdout, "%s\n", base)
80 }
81 // WARNING: no longer supporting old mechanism, in preparation for reuse of fetch-* names in order
82 // to add new archive databases by a few external component scripts (download, cache, index)
83 /*
84 } else {
85 mstr, wrkg := eutils.GetLocalArchivePaths(db)
86 if mstr != "" && wrkg != "" {
87 fmt.Fprintf(os.Stdout, "%s:%s\n", mstr, wrkg)
88 }
89 */
90 }
91 return
92 }
93
94 origArgs := args
95
96 // performance arguments
97 chanDepth := 0
98 farmSize := 0
99 heapSize := 0
100 numServe := 0
101 goGc := 0
102
103 // processing option arguments
104 doCompress := false
105 doCleanup := false
106 doStrict := false
107 doMixed := false
108 doSelf := false
109 deAccent := false
110 deSymbol := false
111 doASCII := false
112 doStem := false
113 deStop := true
114
115 // CONCURRENCY, CLEANUP, AND DEBUGGING FLAGS
116
117 // do these first because -defcpu and -maxcpu can be sent from wrapper before other arguments
118
119 ncpu := runtime.NumCPU()
120 if ncpu < 1 {
121 ncpu = 1
122 }
123
124 // wrapper can limit maximum number of processors to use (undocumented)
125 maxProcs := ncpu
126 defProcs := 0
127
128 // concurrent performance tuning parameters, can be overridden by -proc and -cons
129 numProcs := 0
130 serverRatio := 4
131
132 // garbage collector control can be set by environment variable or default value with -gogc 0
133 goGc = 200
134 gcdefault := true
135
136 // -flag sets -strict or -mixed cleanup flags from argument
137 flgs := ""
138
139 // read data from file instead of stdin
140 fileName := ""
141
142 // -e2incIndex path to local archive
143 archivePath := ""
144
145 // -e2incInvert (and -e2incIndex) paths to incremental indices and inverted indices
146 indicesPath := ""
147 incrementPath := ""
148
149 // flag for indexed input file
150 turbo := false
151
152 // debugging
153 mpty := false
154 idnt := false
155 dbug := false
156 stts := false
157 timr := false
158
159 // profiling
160 prfl := false
161
162 // -transform path can be added early or late in command line
163 tform := ""
164
165 // element to use as local data index
166 indx := ""
167
168 // file of index values for removing duplicates
169 unqe := ""
170
171 // database argument, built-in support for pubmed (default), pmc, and taxonomy
172 db := ""
173
174 // pattern argument, built-in support for PubmedArticle, PMCInfo, and TaxonInfo
175 recname := ""
176
177 // indexing options (e.g., STEM)
178 options := ""
179
180 // file with indexing argument lines
181 idxargs := ""
182
183 // rolling count limit for printing progress dot
184 dotmax := 0
185
186 // path for local data indexed as trie
187 stsh := ""
188 dlet := ""
189 idcs := ""
190 incr := ""
191 ftch := ""
192 strm := ""
193
194 // offset for skipping separately-compressed xml/DOCTYPE block
195 recskip := 0
196
197 // path for local extra link data
198 smmn := ""
199
200 // flag for inverted index
201 nvrt := false
202
203 // flag for combining sets of inverted files
204 join := false
205
206 // flag for combining sets of inverted files
207 fuse := false
208
209 // destination directory for merging and splitting inverted files
210 merg := ""
211 isLink := false
212
213 // base destination directory for promoting inverted index to retrieval indices
214 prom := ""
215
216 // fields for promoting inverted index files
217 fild := ""
218
219 // base for queries
220 base := ""
221
222 // query by phrase, normalized terms (with truncation wildcarding)
223 phrs := ""
224 xact := false
225 titl := false
226 mtch := false
227 mock := false
228 btch := false
229
230 // print term list with counts
231 trms := ""
232 plrl := false
233 psns := false
234
235 // link field
236 lnks := ""
237
238 // use gzip compression on local data files
239 zipp := false
240
241 // create Pubmed-entry ASN.1 file from PubmedArticle XML
242 pma2pme := false
243
244 // make 6-digit .inv trie from PMID
245 invt := false
246
247 // print UIDs and hash values
248 hshv := false
249
250 // convert UIDs to archive trie
251 trei := false
252
253 arcvTrei := false
254 idcsTrei := false
255 pstgTrei := false
256 linkTrei := false
257
258 // pad PMIDs with leading zeros
259 padz := false
260
261 // compare input record against stash
262 cmpr := false
263 cmprType := ""
264 ignr := ""
265
266 // flag missing identifiers
267 msng := false
268
269 // flag records with damaged embedded HTML tags
270 dmgd := false
271 dmgdType := ""
272
273 // kludge to use non-threaded fetching for windows
274 windows := false
275
276 inSwitch := true
277
278 // get concurrency, cleanup, and debugging flags in any order
279 for {
280
281 inSwitch = true
282
283 switch args[0] {
284
285 // concurrency override arguments can be passed in by local wrapper script (undocumented)
286 case "-maxcpu":
287 maxProcs = eutils.GetNumericArg(args, "Maximum number of processors", 1, 1, ncpu)
288 args = args[1:]
289 case "-defcpu":
290 defProcs = eutils.GetNumericArg(args, "Default number of processors", ncpu, 1, ncpu)
291 args = args[1:]
292 // performance tuning flags
293 case "-proc":
294 numProcs = eutils.GetNumericArg(args, "Number of processors", ncpu, 1, ncpu)
295 args = args[1:]
296 case "-cons":
297 serverRatio = eutils.GetNumericArg(args, "Parser to processor ratio", 4, 1, 32)
298 args = args[1:]
299 case "-serv":
300 numServe = eutils.GetNumericArg(args, "Concurrent parser count", 0, 1, 128)
301 args = args[1:]
302 case "-chan":
303 chanDepth = eutils.GetNumericArg(args, "Communication channel depth", 0, ncpu, 128)
304 args = args[1:]
305 case "-heap":
306 heapSize = eutils.GetNumericArg(args, "Unshuffler heap size", 8, 8, 64)
307 args = args[1:]
308 case "-farm":
309 farmSize = eutils.GetNumericArg(args, "Node buffer length", 4, 4, 2048)
310 args = args[1:]
311 case "-gogc":
312 goGc = eutils.GetNumericArg(args, "Garbage collection percentage", 0, 50, 1000)
313 args = args[1:]
314 gcdefault = false
315
316 // read data from file
317 case "-input":
318 fileName = eutils.GetStringArg(args, "Input file name")
319 args = args[1:]
320
321 // path to local archive and index folders for incremental updating of cached index components
322 case "-e2incIndex":
323 archivePath = eutils.GetStringArg(args, "Path to local archive")
324 args = args[1:]
325 indicesPath = eutils.GetStringArg(args, "Path to local indices")
326 args = args[1:]
327 // should be followed by -transform meshtree.txt -e2index
328
329 // path to local index folder for incremental updating of cached inverted index components
330 case "-e2incInvert":
331 indicesPath = eutils.GetStringArg(args, "Path to local indices")
332 args = args[1:]
333 incrementPath = eutils.GetStringArg(args, "Path to local increment")
334 args = args[1:]
335
336 // input is indexed with <NEXT_RECORD_SIZE> objects
337 case "-turbo":
338 turbo = true
339
340 // file with selected indexes for removing duplicates
341 case "-unique":
342 unqe = eutils.GetStringArg(args, "Unique identifier file")
343 args = args[1:]
344
345 // database (currently pubmed, pmc, or taxonomy)
346 case "-db":
347 db = eutils.GetStringArg(args, "Local archive database")
348 db = strings.ToLower(db)
349 args = args[1:]
350
351 case "-tag":
352 recname = eutils.GetStringArg(args, "Local archive pattern")
353 args = args[1:]
354
355 case "-skip":
356 recskip = eutils.GetNumericArg(args, "Bytes to skip compressed xml/DOCTYPE block", 0, 0, 1000)
357 args = args[1:]
358
359 case "-options":
360 options = eutils.GetStringArg(args, "Local archive options")
361 options = strings.ToLower(options)
362 args = args[1:]
363
364 case "-idxargs":
365 idxargs = eutils.GetStringArg(args, "File with local archive indexing argument lines")
366 args = args[1:]
367
368 case "-dotmax":
369 dotmax = eutils.GetNumericArg(args, "Progress dot printing frequency", 0, 0, 10000)
370 args = args[1:]
371
372 // local directory path for indexing
373 case "-archive", "-stash":
374 if len(args) < 4 {
375 eutils.DisplayError("Archive, indices, and increment path needed")
376 os.Exit(1)
377 }
378 stsh = eutils.GetStringArg(args, "Archive path")
379 if stsh != "" && !strings.HasSuffix(stsh, "/") {
380 stsh += "/"
381 }
382 args = args[1:]
383 idcs = eutils.GetStringArg(args, "Indices path")
384 if idcs != "" && !strings.HasSuffix(idcs, "/") {
385 idcs += "/"
386 }
387 args = args[1:]
388 incr = eutils.GetStringArg(args, "Increment path")
389 if incr != "" && !strings.HasSuffix(incr, "/") {
390 incr += "/"
391 }
392 args = args[1:]
393 // local directory path for deletion
394 case "-delete":
395 if len(args) < 4 {
396 eutils.DisplayError("Archive, indices, and increment path needed")
397 os.Exit(1)
398 }
399 dlet = eutils.GetStringArg(args, "Archive path")
400 if dlet != "" && !strings.HasSuffix(dlet, "/") {
401 dlet += "/"
402 }
403 args = args[1:]
404 idcs = eutils.GetStringArg(args, "Indices path")
405 if idcs != "" && !strings.HasSuffix(idcs, "/") {
406 idcs += "/"
407 }
408 args = args[1:]
409 incr = eutils.GetStringArg(args, "Increment path")
410 if incr != "" && !strings.HasSuffix(incr, "/") {
411 incr += "/"
412 }
413 args = args[1:]
414 // local directory path for retrieval
415 case "-fetch":
416 ftch = eutils.GetStringArg(args, "Fetch path")
417 if ftch != "" && !strings.HasSuffix(ftch, "/") {
418 ftch += "/"
419 }
420 args = args[1:]
421 // local directory path for retrieval of compressed XML
422 case "-stream":
423 strm = eutils.GetStringArg(args, "Stream path")
424 if strm != "" && !strings.HasSuffix(strm, "/") {
425 strm += "/"
426 }
427 args = args[1:]
428
429 // local directory path for extra link retrieval
430 case "-summon":
431 smmn = eutils.GetStringArg(args, "Summon path")
432 args = args[1:]
433
434 // index transformation file
435 case "-transform":
436 tform = eutils.GetStringArg(args, "Transformation file")
437 args = args[1:]
438
439 // data element for indexing
440 case "-index":
441 indx = eutils.GetStringArg(args, "Index element")
442 args = args[1:]
443
444 // build inverted index
445 case "-e2invert":
446 nvrt = true
447
448 // combine sets of inverted index files
449 case "-join":
450 join = true
451
452 case "-fuse":
453 fuse = true
454
455 case "-mergelink":
456 isLink = true
457 fallthrough
458 // merge inverted index files, distribute by prefix
459 case "-merge":
460 merg = eutils.GetStringArg(args, "Merge field")
461 args = args[1:]
462
463 case "-promotelink":
464 isLink = true
465 fallthrough
466 // promote inverted index to term-specific postings files
467 case "-promote":
468 if len(args) < 3 {
469 eutils.DisplayError("Promote path is missing")
470 os.Exit(1)
471 }
472 prom = args[1]
473 fild = args[2]
474 // skip past first and second arguments
475 args = args[2:]
476
477 case "-path":
478 base = eutils.GetStringArg(args, "Postings path")
479 args = args[1:]
480
481 case "-title":
482 titl = true
483 fallthrough
484 case "-exact":
485 xact = true
486 fallthrough
487 case "-query", "-search":
488 phrs = eutils.GetStringArg(args, "Query argument")
489 args = args[1:]
490
491 case "-match", "-partial":
492 mtch = true
493 phrs = eutils.GetStringArg(args, "Match argument")
494 args = args[1:]
495
496 case "-link":
497 lnks = eutils.GetStringArg(args, "Links field")
498 isLink = true
499 args = args[1:]
500
501 case "-batch":
502 btch = true
503
504 case "-mockt":
505 titl = true
506 fallthrough
507 case "-mockx":
508 xact = true
509 fallthrough
510 case "-mock", "-mocks":
511 phrs = eutils.GetStringArg(args, "Query argument")
512 mock = true
513 args = args[1:]
514
515 // -countp tests the files containing positions of terms per UID (undocumented)
516 case "-countp":
517 psns = true
518 fallthrough
519 case "-counts":
520 plrl = true
521 fallthrough
522 case "-count", "-countr":
523 trms = eutils.GetStringArg(args, "Count argument")
524 args = args[1:]
525
526 case "-gzip":
527 zipp = true
528 case "-asn":
529 pma2pme = true
530 case "-xml":
531 pma2pme = false
532 case "-inv":
533 invt = true
534 case "-hash":
535 hshv = true
536 case "-trie":
537 trei = true
538 if len(args) > 1 {
539 next := args[1]
540 // if next argument is not another flag
541 if next != "" && next[0] != '-' {
542 // get type of trie
543 switch next {
544 case "archive":
545 arcvTrei = true
546 case "indices":
547 idcsTrei = true
548 case "posting", "postings":
549 pstgTrei = true
550 case "link", "links":
551 linkTrei = true
552 }
553 // skip past first of two arguments
554 args = args[1:]
555 }
556 }
557 case "-padz":
558 padz = true
559 // check for missing records
560 case "-missing":
561 msng = true
562
563 // use non-threaded fetch function for windows (undocumented)
564 case "-windows":
565 windows = true
566
567 // data cleanup flags
568 case "-compress", "-compressed":
569 doCompress = true
570 case "-spaces", "-cleanup":
571 doCleanup = true
572 case "-strict":
573 doStrict = true
574 case "-mixed":
575 doMixed = true
576 case "-self":
577 doSelf = true
578 case "-accent":
579 deAccent = true
580 case "-symbol":
581 deSymbol = true
582 case "-ascii":
583 doASCII = true
584
585 // previously visible processing flags (undocumented)
586 case "-stems", "-stem":
587 doStem = true
588 case "-stops", "-stop":
589 deStop = false
590
591 case "-unicode":
592 // DoUnicode = true
593 case "-script":
594 // DoScript = true
595 case "-mathml":
596 // DoMathML = true
597
598 case "-flag", "-flags":
599 if len(args) < 2 {
600 eutils.DisplayError("-flags argument is missing")
601 os.Exit(1)
602 }
603 flgs = eutils.GetStringArg(args, "Flags argument")
604 args = args[1:]
605
606 // debugging flags
607 case "-damaged", "-damage", "-broken":
608 dmgd = true
609 if len(args) > 1 {
610 next := args[1]
611 // if next argument is not another flag
612 if next != "" && next[0] != '-' {
613 // get optional extraction class (SELF, SINGLE, DOUBLE, AMPER, or ALL)
614 dmgdType = next
615 // skip past first of two arguments
616 args = args[1:]
617 }
618 }
619 case "-prepare":
620 cmpr = true
621 if len(args) > 1 {
622 next := args[1]
623 // if next argument is not another flag
624 if next != "" && next[0] != '-' {
625 // get optional data source specifier
626 cmprType = next
627 // skip past first of two arguments
628 args = args[1:]
629 }
630 }
631 case "-ignore":
632 ignr = eutils.GetStringArg(args, "-ignore value")
633 args = args[1:]
634
635 // debugging flags
636 case "-debug":
637 dbug = true
638 case "-stats", "-stat":
639 stts = true
640 case "-timer":
641 timr = true
642 case "-profile":
643 prfl = true
644
645 default:
646 // if not any of the controls, set flag to break out of for loop
647 inSwitch = false
648 }
649
650 if !inSwitch {
651 break
652 }
653
654 // skip past argument
655 args = args[1:]
656
657 if len(args) < 1 {
658 break
659 }
660 }
661
662 // -flag allows script to set -strict or -mixed (or -stops) from argument
663 switch flgs {
664 case "strict":
665 doStrict = true
666 case "mixed":
667 doMixed = true
668 case "stems", "stem":
669 doStem = true
670 case "stops", "stop":
671 deStop = false
672 case "none", "default":
673 default:
674 if flgs != "" {
675 eutils.DisplayError("Unrecognized -flag value '%s'", flgs)
676 os.Exit(1)
677 }
678 }
679
680 /*
681 UnicodeFix = ParseMarkup(unicodePolicy, "-unicode")
682 ScriptFix = ParseMarkup(scriptPolicy, "-script")
683 MathMLFix = ParseMarkup(mathmlPolicy, "-mathml")
684
685 if UnicodeFix != NOMARKUP {
686 doUnicode = true
687 }
688
689 if ScriptFix != NOMARKUP {
690 doScript = true
691 }
692
693 if MathMLFix != NOMARKUP {
694 doMathML = true
695 }
696 */
697
698 if numProcs == 0 {
699 if defProcs > 0 {
700 numProcs = defProcs
701 } else if maxProcs > 0 {
702 numProcs = maxProcs
703 }
704 }
705 if numProcs > ncpu {
706 numProcs = ncpu
707 }
708 if numProcs > maxProcs {
709 numProcs = maxProcs
710 }
711
712 eutils.SetTunings(numProcs, numServe, serverRatio, chanDepth, farmSize, heapSize, goGc, turbo)
713
714 eutils.SetOptions(doStrict, doMixed, doSelf, deAccent, deSymbol, doASCII, doCompress, doCleanup, doStem, deStop)
715
716 // -stats prints number of CPUs and performance tuning values if no other arguments (undocumented)
717 if stts && len(args) < 1 {
718
719 eutils.PrintStats()
720
721 return
722 }
723
724 // if copying from local files accessed by identifier, add dummy argument to bypass length tests
725 if stsh != "" && indx == "" {
726 args = append(args, "-dummy")
727 } else if dlet != "" {
728 args = append(args, "-dummy")
729 } else if ftch != "" || strm != "" || smmn != "" {
730 args = append(args, "-dummy")
731 } else if base != "" {
732 args = append(args, "-dummy")
733 } else if trei || padz || dmgd || cmpr {
734 args = append(args, "-dummy")
735 }
736
737 // expand -archive ~/ to home directory path
738 if stsh != "" {
739
740 if stsh[:2] == "~/" {
741 cur, err := user.Current()
742 if err == nil {
743 hom := cur.HomeDir
744 stsh = strings.Replace(stsh, "~/", hom+"/", 1)
745 }
746 }
747 }
748 if dlet != "" {
749
750 if dlet[:2] == "~/" {
751 cur, err := user.Current()
752 if err == nil {
753 hom := cur.HomeDir
754 dlet = strings.Replace(dlet, "~/", hom+"/", 1)
755 }
756 }
757 }
758 if idcs != "" {
759
760 if idcs[:2] == "~/" {
761 cur, err := user.Current()
762 if err == nil {
763 hom := cur.HomeDir
764 idcs = strings.Replace(idcs, "~/", hom+"/", 1)
765 }
766 }
767 }
768 if incr != "" {
769
770 if incr[:2] == "~/" {
771 cur, err := user.Current()
772 if err == nil {
773 hom := cur.HomeDir
774 incr = strings.Replace(incr, "~/", hom+"/", 1)
775 }
776 }
777 }
778
779 // expand -fetch ~/ to home directory path
780 if ftch != "" {
781
782 if ftch[:2] == "~/" {
783 cur, err := user.Current()
784 if err == nil {
785 hom := cur.HomeDir
786 ftch = strings.Replace(ftch, "~/", hom+"/", 1)
787 }
788 }
789 }
790
791 // expand -stream ~/ to home directory path
792 if strm != "" {
793
794 if strm[:2] == "~/" {
795 cur, err := user.Current()
796 if err == nil {
797 hom := cur.HomeDir
798 strm = strings.Replace(strm, "~/", hom+"/", 1)
799 }
800 }
801 }
802
803 // expand -promote ~/ to home directory path
804 if prom != "" {
805
806 if prom[:2] == "~/" {
807 cur, err := user.Current()
808 if err == nil {
809 hom := cur.HomeDir
810 prom = strings.Replace(prom, "~/", hom+"/", 1)
811 }
812 }
813 }
814
815 // expand -summon ~/ to home directory path
816 if smmn != "" {
817
818 if smmn[:2] == "~/" {
819 cur, err := user.Current()
820 if err == nil {
821 hom := cur.HomeDir
822 smmn = strings.Replace(smmn, "~/", hom+"/", 1)
823 }
824 }
825 }
826
827 // DOCUMENTATION COMMANDS
828
829 if len(args) > 0 {
830
831 inSwitch = true
832
833 switch args[0] {
834 case "-version":
835 fmt.Printf("%s\n", eutils.EDirectVersion)
836 case "-help", "help", "--help":
837 eutils.PrintHelp("rchive", "rchive-help.txt")
838 case "-extras", "-extra", "-advanced":
839 eutils.PrintHelp("rchive", "rchive-extras.txt")
840 case "-internal", "-internals":
841 eutils.PrintHelp("rchive", "rchive-internal.txt")
842 default:
843 // if not any of the documentation commands, keep going
844 inSwitch = false
845 }
846
847 if inSwitch {
848 return
849 }
850 }
851
852 // FILE NAME CAN BE SUPPLIED WITH -input COMMAND
853
854 in := os.Stdin
855
856 // check for data being piped into stdin
857 isPipe := false
858 fi, staterr := os.Stdin.Stat()
859 if staterr == nil {
860 isPipe = bool((fi.Mode() & os.ModeNamedPipe) != 0)
861 }
862
863 usingFile := false
864
865 if fileName != "" {
866
867 inFile, err := os.Open(fileName)
868 if err != nil {
869 eutils.DisplayError("Unable to open input file '%s'", fileName)
870 os.Exit(1)
871 }
872
873 defer inFile.Close()
874
875 // use indicated file instead of stdin
876 in = inFile
877 usingFile = true
878
879 if isPipe && runtime.GOOS != "windows" {
880 mode := fi.Mode().String()
881 eutils.DisplayError("Input data from both stdin and file '%s', mode is '%s'", fileName, mode)
882 os.Exit(1)
883 }
884 }
885
886 // check for -input command after extraction arguments
887 for _, str := range args {
888 if str == "-input" {
889 eutils.DisplayError("Misplaced -input command")
890 os.Exit(1)
891 }
892 }
893
894 // START PROFILING IF REQUESTED
895
896 if prfl {
897
898 f, err := os.Create("cpu.pprof")
899 if err != nil {
900 eutils.DisplayError("Unable to create profile output file")
901 os.Exit(1)
902 }
903
904 pprof.StartCPUProfile(f)
905
906 defer pprof.StopCPUProfile()
907 }
908
909 // INITIALIZE RECORD COUNT
910
911 recordCount := 0
912 byteCount := 0
913
914 // print processing rate and program duration
915 printDuration := func(name string) {
916
917 eutils.PrintDuration(name, recordCount, byteCount)
918 }
919
920 // NAME OF OUTPUT STRING TRANSFORMATION FILE
921
922 transform := make(map[string]string)
923
924 populateTx := func(tf string) {
925
926 inFile, err := os.Open(tf)
927 if err != nil {
928 eutils.DisplayError("Unable to open transformation file %s", err.Error())
929 os.Exit(1)
930 }
931 defer inFile.Close()
932
933 scanr := bufio.NewScanner(inFile)
934
935 // populate transformation map for -translate (and -matrix) output
936 for scanr.Scan() {
937
938 line := scanr.Text()
939 frst, scnd := eutils.SplitInTwoLeft(line, "\t")
940
941 transform[frst] = scnd
942 }
943 }
944
945 // also check for -transform late in command line
946 if len(args) > 2 && args[0] == "-transform" {
947 tform = args[1]
948 args = args[2:]
949 }
950
951 if tform != "" {
952 populateTx(tform)
953 }
954
955 // SPECIFY STRINGS TO GO BEFORE AND AFTER ENTIRE OUTPUT OR EACH RECORD
956
957 head := ""
958 tail := ""
959
960 hd := ""
961 tl := ""
962
963 parseHeadTail := func() {
964
965 for {
966
967 if len(args) < 1 {
968 break
969 }
970
971 inSwitch = true
972
973 switch args[0] {
974 case "-head":
975 if len(args) < 2 {
976 eutils.DisplayError("Pattern missing after -head command")
977 os.Exit(1)
978 }
979 head = eutils.ConvertSlash(args[1])
980 // allow splitting of -head argument, keep appending until next command (undocumented)
981 ofs, nxt := 0, args[2:]
982 for {
983 if len(nxt) < 1 {
984 break
985 }
986 tmp := nxt[0]
987 if strings.HasPrefix(tmp, "-") {
988 break
989 }
990 ofs++
991 txt := eutils.ConvertSlash(tmp)
992 if head != "" && !strings.HasSuffix(head, "\t") {
993 head += "\t"
994 }
995 head += txt
996 nxt = nxt[1:]
997 }
998 if ofs > 0 {
999 args = args[ofs:]
1000 }
1001 case "-tail":
1002 if len(args) < 2 {
1003 eutils.DisplayError("Pattern missing after -tail command")
1004 os.Exit(1)
1005 }
1006 tail = eutils.ConvertSlash(args[1])
1007 case "-hd":
1008 if len(args) < 2 {
1009 eutils.DisplayError("Pattern missing after -hd command")
1010 os.Exit(1)
1011 }
1012 hd = eutils.ConvertSlash(args[1])
1013 case "-tl":
1014 if len(args) < 2 {
1015 eutils.DisplayError("Pattern missing after -tl command")
1016 os.Exit(1)
1017 }
1018 tl = eutils.ConvertSlash(args[1])
1019 case "-wrp":
1020 // shortcut to wrap records in XML tags
1021 if len(args) < 2 {
1022 eutils.DisplayError("Pattern missing after -wrp command")
1023 os.Exit(1)
1024 }
1025 tmp := eutils.ConvertSlash(args[1])
1026 lft, rgt := eutils.SplitInTwoLeft(tmp, ",")
1027 if lft != "" {
1028 head = "<" + lft + ">"
1029 tail = "</" + lft + ">"
1030 }
1031 if rgt != "" {
1032 hd = "<" + rgt + ">"
1033 tl = "</" + rgt + ">"
1034 }
1035 case "-set":
1036 if len(args) < 2 {
1037 eutils.DisplayError("Pattern missing after -set command")
1038 os.Exit(1)
1039 }
1040 tmp := eutils.ConvertSlash(args[1])
1041 if tmp != "" {
1042 head = "<" + tmp + ">"
1043 tail = "</" + tmp + ">"
1044 }
1045 case "-rec":
1046 if len(args) < 2 {
1047 eutils.DisplayError("Pattern missing after -rec command")
1048 os.Exit(1)
1049 }
1050 tmp := eutils.ConvertSlash(args[1])
1051 if tmp != "" {
1052 hd = "<" + tmp + ">"
1053 tl = "</" + tmp + ">"
1054 }
1055 default:
1056 // if not any of the controls, set flag to break out of for loop
1057 inSwitch = false
1058 }
1059
1060 if !inSwitch {
1061 break
1062 }
1063
1064 // skip past arguments
1065 args = args[2:]
1066
1067 if len(args) < 1 {
1068 eutils.DisplayError("Insufficient command-line arguments supplied to rchive")
1069 os.Exit(1)
1070 }
1071 }
1072 }
1073
1074 // -e2incIndex FOLLOWED BY -transform meshtree.txt AND -e2index
1075
1076 if len(args) > 0 && args[0] == "-e2index" && archivePath != "" && indicesPath != "" {
1077
1078 // skip past command name
1079 args = args[1:]
1080
1081 // environment variable can override garbage collector (undocumented)
1082 gcEnv := os.Getenv("EDIRECT_INDEX_GOGC")
1083 if gcEnv != "" {
1084 val, err := strconv.Atoi(gcEnv)
1085 if err == nil {
1086 if val >= 50 && val <= 1000 {
1087 debug.SetGCPercent(val)
1088 } else {
1089 debug.SetGCPercent(100)
1090 }
1091 }
1092 }
1093
1094 // environment variable can override number of servers (undocumented)
1095 svEnv := os.Getenv("EDIRECT_INDEX_SERV")
1096 if svEnv != "" {
1097 val, err := strconv.Atoi(svEnv)
1098 if err == nil {
1099 if val >= 1 && val <= 128 {
1100 numServe = val
1101 } else {
1102 numServe = 1
1103 }
1104 eutils.SetTunings(numProcs, numServe, serverRatio, chanDepth, farmSize, heapSize, goGc, false)
1105 }
1106 }
1107
1108 pfx := ""
1109
1110 if recname == "" {
1111 if db == "pubmed" {
1112 recname = "PubmedArticle"
1113 } else if db == "pmc" {
1114 pfx = "PMC"
1115 recname = "PMCInfo"
1116 } else if db == "taxonomy" {
1117 recname = "TaxonInfo"
1118 }
1119 }
1120
1121 res := eutils.MakeE2Commands(tform, idxargs)
1122
1123 // data in pipe, so replace arguments, execute dynamically
1124 args = res
1125
1126 if len(args) < 1 {
1127 eutils.DisplayError("-e2index argument generation failure")
1128 os.Exit(1)
1129 }
1130
1131 // parse new -head, -tail, etc.
1132 parseHeadTail()
1133
1134 // parse expected -e2index generated arguments
1135 cmds := eutils.ParseArguments(args, recname)
1136 if cmds == nil {
1137 eutils.DisplayError("Problem parsing -e2index arguments after -e2incIndex")
1138 os.Exit(1)
1139 }
1140
1141 callConsumers := func(inp <-chan eutils.XMLRecord) <-chan eutils.XMLRecord {
1142
1143 // closure allows access to unchanging cmds and transform arguments
1144 return eutils.CreateXMLConsumers(cmds, "", "<IdxDocument>", "</IdxDocument>", transform, false, nil, inp)
1145 }
1146
1147 e2iq := eutils.IncrementalIndex(db, pfx, recname, dotmax, callConsumers)
1148 if e2iq == nil {
1149 eutils.DisplayError("Unable to create indexer channel")
1150 os.Exit(1)
1151 }
1152
1153 // drain channel for names of folder-specific inverted index files that were updated
1154 for range e2iq {
1155 recordCount++
1156 // fmt.Fprintf(os.Stdout, "%s\n", itm)
1157 runtime.Gosched()
1158 }
1159
1160 // newline after progress monitor dots
1161 fmt.Fprintf(os.Stdout, "\n")
1162
1163 debug.FreeOSMemory()
1164
1165 if timr {
1166 printDuration("files")
1167 }
1168
1169 return
1170 }
1171
1172 // -e2incInvert
1173
1174 if len(args) == 0 && archivePath == "" && indicesPath != "" && incrementPath != "" {
1175
1176 // environment variable can override garbage collector (undocumented)
1177 gcEnv := os.Getenv("EDIRECT_INDEX_GOGC")
1178 if gcEnv != "" {
1179 val, err := strconv.Atoi(gcEnv)
1180 if err == nil {
1181 if val >= 50 && val <= 1000 {
1182 debug.SetGCPercent(val)
1183 } else {
1184 debug.SetGCPercent(100)
1185 }
1186 }
1187 }
1188
1189 // environment variable can override number of servers (undocumented)
1190 svEnv := os.Getenv("EDIRECT_INDEX_SERV")
1191 if svEnv != "" {
1192 val, err := strconv.Atoi(svEnv)
1193 if err == nil {
1194 if val >= 1 && val <= 128 {
1195 numServe = val
1196 } else {
1197 numServe = 1
1198 }
1199 eutils.SetTunings(numProcs, numServe, serverRatio, chanDepth, farmSize, heapSize, goGc, false)
1200 }
1201 }
1202
1203 // parse new -head, -tail, etc.
1204 parseHeadTail()
1205
1206 e2iq := eutils.IncrementalInvert(db, dotmax)
1207 if e2iq == nil {
1208 eutils.DisplayError("Unable to create inverter channel")
1209 os.Exit(1)
1210 }
1211
1212 // drain channel for names of folder-specific inverted index files that were updated
1213 for range e2iq {
1214 recordCount++
1215 // fmt.Fprintf(os.Stdout, "%s\n", itm)
1216 runtime.Gosched()
1217 }
1218
1219 debug.FreeOSMemory()
1220
1221 if timr {
1222 printDuration("files")
1223 }
1224
1225 return
1226 }
1227
1228 // -delete REMOVES RECORDS AND INCREMENTAL INDICES BY LIST OF PMIDs
1229
1230 if dlet != "" {
1231
1232 dltq := eutils.CreateDeleter(dlet, db, in)
1233 clrq := eutils.CreateClearer(idcs, incr, db, dltq)
1234
1235 if dltq == nil || clrq == nil {
1236 eutils.DisplayError("Unable to create deleter")
1237 os.Exit(1)
1238 }
1239
1240 // drain output channel
1241 for str := range clrq {
1242
1243 if dbug {
1244 fmt.Fprintf(os.Stderr, "%s\n", str)
1245 }
1246
1247 recordCount++
1248 runtime.Gosched()
1249 }
1250
1251 debug.FreeOSMemory()
1252
1253 if timr {
1254 printDuration("records")
1255 }
1256
1257 return
1258 }
1259
1260 // -e2index PROCESSING OF PUBMED RECORDS
1261
1262 if len(args) > 0 && args[0] == "-e2index" {
1263
1264 // e.g., rchive -transform [meshtree.txt] -e2index
1265
1266 // skip past command name
1267 args = args[1:]
1268
1269 // environment variable can override garbage collector (undocumented)
1270 gcEnv := os.Getenv("EDIRECT_INDEX_GOGC")
1271 if gcEnv != "" {
1272 val, err := strconv.Atoi(gcEnv)
1273 if err == nil {
1274 if val >= 50 && val <= 1000 {
1275 debug.SetGCPercent(val)
1276 } else {
1277 debug.SetGCPercent(100)
1278 }
1279 }
1280 }
1281
1282 // environment variable can override number of servers (undocumented)
1283 svEnv := os.Getenv("EDIRECT_INDEX_SERV")
1284 if svEnv != "" {
1285 val, err := strconv.Atoi(svEnv)
1286 if err == nil {
1287 if val >= 1 && val <= 128 {
1288 numServe = val
1289 } else {
1290 numServe = 1
1291 }
1292 eutils.SetTunings(numProcs, numServe, serverRatio, chanDepth, farmSize, heapSize, goGc, turbo)
1293 }
1294 }
1295
1296 if recname == "" {
1297 if db == "pubmed" {
1298 recname = "PubmedArticle"
1299 } else if db == "pmc" {
1300 recname = "PMCInfo"
1301 } else if db == "taxonomy" {
1302 recname = "TaxonInfo"
1303 }
1304 }
1305
1306 res := eutils.MakeE2Commands(tform, idxargs)
1307
1308 if !isPipe && !usingFile {
1309 // no piped input, so write output instructions
1310 fmt.Printf("rchive")
1311 if tform != "" {
1312 fmt.Printf(" -transform %s", tform)
1313 }
1314 for _, str := range res {
1315 if strings.HasPrefix(str, "-") {
1316 fmt.Printf(" %s", str)
1317 } else {
1318 fmt.Printf(" \"%s\"", str)
1319 }
1320 }
1321 fmt.Printf("\n")
1322 return
1323 }
1324
1325 // data in pipe, so replace arguments, execute dynamically
1326 args = res
1327
1328 if len(args) < 1 {
1329 eutils.DisplayError("-e2index argument generation failure")
1330 os.Exit(1)
1331 }
1332
1333 // parse new -head, -tail, etc.
1334 parseHeadTail()
1335
1336 // parse expected -e2index generated arguments
1337 cmds := eutils.ParseArguments(args, recname)
1338 if cmds == nil {
1339 eutils.DisplayError("Problem parsing -e2index arguments")
1340 os.Exit(1)
1341 }
1342
1343 rdr := eutils.CreateXMLStreamer(in, nil)
1344
1345 if rdr == nil {
1346 eutils.DisplayError("Unable to create XML Block Reader")
1347 os.Exit(1)
1348 }
1349
1350 // launch producer goroutine to partition XML by pattern
1351 xmlq := eutils.CreateXMLProducer(recname, "", false, rdr)
1352
1353 // launch consumer goroutines to parse and explore partitioned XML objects
1354 tblq := eutils.CreateXMLConsumers(cmds, recname, hd, tl, transform, false, nil, xmlq)
1355
1356 // launch unshuffler goroutine to restore order of results
1357 unsq := eutils.CreateXMLUnshuffler(tblq)
1358
1359 if xmlq == nil || tblq == nil || unsq == nil {
1360 eutils.DisplayError("Unable to create servers")
1361 os.Exit(1)
1362 }
1363
1364 recordCount, byteCount = eutils.DrainExtractions(head, tail, "", mpty, idnt, nil, unsq)
1365
1366 if timr {
1367 printDuration("records")
1368 }
1369
1370 return
1371 }
1372
1373 // PRINT ALL TERMS IN A FIELD
1374
1375 if len(args) > 1 && args[0] == "-terms" {
1376
1377 // skip past command name
1378 args = args[1:]
1379
1380 fld := args[0]
1381
1382 trms := eutils.StreamTerms(db, fld)
1383 if trms == nil {
1384 eutils.DisplayError("Unable to create term generator")
1385 os.Exit(1)
1386 }
1387
1388 for str := range trms {
1389 // returning multi-line strings, no need for trailing newline
1390 fmt.Fprintf(os.Stdout, "%s", str)
1391 }
1392
1393 return
1394 }
1395
1396 // PRINT ALL TERMS AND COUNTS IN A FIELD
1397
1398 if len(args) > 1 && args[0] == "-totals" {
1399
1400 // skip past command name
1401 args = args[1:]
1402
1403 fld := args[0]
1404
1405 trms := eutils.StreamTotals(db, fld)
1406 if trms == nil {
1407 eutils.DisplayError("Unable to create totals generator")
1408 os.Exit(1)
1409 }
1410
1411 for str := range trms {
1412 // returning multi-line strings, no need for trailing newline
1413 fmt.Fprintf(os.Stdout, "%s", str)
1414 }
1415
1416 return
1417 }
1418
1419 // JOIN SUBSETS OF INVERTED INDEX FILES
1420
1421 // -join combines subsets of inverted files for subsequent -merge operation
1422 if join {
1423
1424 // environment variable can override garbage collector (undocumented)
1425 gcEnv := os.Getenv("EDIRECT_JOIN_GOGC")
1426 if gcEnv != "" {
1427 val, err := strconv.Atoi(gcEnv)
1428 if err == nil {
1429 if val >= 50 && val <= 1000 {
1430 debug.SetGCPercent(val)
1431 } else {
1432 debug.SetGCPercent(100)
1433 }
1434 }
1435 } else if gcdefault {
1436 // default to 200 for join
1437 debug.SetGCPercent(200)
1438 }
1439
1440 // environment variable can override number of servers (undocumented)
1441 svEnv := os.Getenv("EDIRECT_JOIN_SERV")
1442 if svEnv != "" {
1443 val, err := strconv.Atoi(svEnv)
1444 if err == nil {
1445 if val >= 1 && val <= 128 {
1446 numServe = val
1447 } else {
1448 numServe = 1
1449 }
1450 eutils.SetTunings(numProcs, numServe, serverRatio, chanDepth, farmSize, heapSize, goGc, false)
1451 }
1452 }
1453
1454 chns := eutils.CreatePresenters(args)
1455 mfld := eutils.CreateManifold(chns)
1456 // mrgr := eutils.CreateMergers(mfld)
1457 // for faster performance, joiner does not fuse adjacent records with same key, leaves it to subsequent merge step
1458 mrgr := eutils.CreateJoiners(mfld)
1459 unsq := eutils.CreateXMLUnshuffler(mrgr)
1460
1461 if chns == nil || mfld == nil || mrgr == nil || unsq == nil {
1462 eutils.DisplayError("Unable to create inverted index joiner")
1463 os.Exit(1)
1464 }
1465
1466 var out io.Writer
1467
1468 out = os.Stdout
1469
1470 if zipp {
1471
1472 zpr, err := pgzip.NewWriterLevel(out, pgzip.BestSpeed)
1473 if err != nil {
1474 eutils.DisplayError("Unable to create compressor")
1475 os.Exit(1)
1476 }
1477
1478 // close decompressor when all records have been processed
1479 defer zpr.Close()
1480
1481 // use compressor for writing file
1482 out = zpr
1483 }
1484
1485 // create buffered writer layer
1486 wrtr := bufio.NewWriter(out)
1487
1488 wrtr.WriteString("<InvDocumentSet>\n")
1489
1490 // drain channel of alphabetized results
1491 for curr := range unsq {
1492
1493 str := curr.Text
1494
1495 if str == "" {
1496 continue
1497 }
1498
1499 // send result to output
1500 wrtr.WriteString(str)
1501
1502 recordCount++
1503 runtime.Gosched()
1504 }
1505
1506 wrtr.WriteString("</InvDocumentSet>\n\n")
1507
1508 wrtr.Flush()
1509
1510 debug.FreeOSMemory()
1511
1512 if timr {
1513 printDuration("terms")
1514 }
1515
1516 return
1517 }
1518
1519 // MERGE INVERTED INDEX FILES AND GROUP BY TERM
1520
1521 // -merge combines inverted files, distributes by prefix
1522 if merg != "" {
1523
1524 // environment variable can override garbage collector (undocumented)
1525 gcEnv := os.Getenv("EDIRECT_MERGE_GOGC")
1526 if gcEnv != "" {
1527 val, err := strconv.Atoi(gcEnv)
1528 if err == nil {
1529 if val >= 50 && val <= 1000 {
1530 debug.SetGCPercent(val)
1531 } else {
1532 debug.SetGCPercent(100)
1533 }
1534 }
1535 } else if gcdefault {
1536 // default to 100 for merge
1537 debug.SetGCPercent(100)
1538 }
1539
1540 // environment variable can override number of servers (undocumented)
1541 svEnv := os.Getenv("EDIRECT_MERGE_SERV")
1542 if svEnv != "" {
1543 val, err := strconv.Atoi(svEnv)
1544 if err == nil {
1545 if val >= 1 && val <= 128 {
1546 numServe = val
1547 } else {
1548 numServe = 1
1549 }
1550 eutils.SetTunings(numProcs, numServe, serverRatio, chanDepth, farmSize, heapSize, goGc, false)
1551 }
1552 }
1553
1554 chns := eutils.CreatePresenters(args)
1555 mfld := eutils.CreateManifold(chns)
1556 mrgr := eutils.CreateMergers(mfld)
1557 unsq := eutils.CreateXMLUnshuffler(mrgr)
1558 sptr := eutils.CreateSplitter(merg, db, zipp, isLink, unsq)
1559
1560 if chns == nil || mfld == nil || mrgr == nil || unsq == nil || sptr == nil {
1561 eutils.DisplayError("Unable to create inverted index merger")
1562 os.Exit(1)
1563 }
1564
1565 // drain channel, print two-to-four-character index name
1566 startTime := time.Now()
1567 first := true
1568 col := 0
1569 spaces := " "
1570
1571 for str := range sptr {
1572
1573 stopTime := time.Now()
1574 duration := stopTime.Sub(startTime)
1575 seconds := float64(duration.Nanoseconds()) / 1e9
1576
1577 if timr {
1578 if first {
1579 first = false
1580 } else {
1581 fmt.Fprintf(os.Stdout, "%.3f\n", seconds)
1582 }
1583 fmt.Fprintf(os.Stdout, "%s\t", str)
1584 } else {
1585 blank := 7 - len(str)
1586 if blank > 0 {
1587 fmt.Fprintf(os.Stdout, "%s", spaces[:blank])
1588 }
1589 fmt.Fprintf(os.Stdout, "%s", str)
1590 col++
1591 if col >= 10 {
1592 col = 0
1593 fmt.Fprintf(os.Stdout, "\n")
1594 }
1595 }
1596
1597 recordCount++
1598 runtime.Gosched()
1599
1600 startTime = time.Now()
1601 }
1602
1603 stopTime := time.Now()
1604 duration := stopTime.Sub(startTime)
1605 seconds := float64(duration.Nanoseconds()) / 1e9
1606
1607 if timr {
1608 fmt.Fprintf(os.Stdout, "%.3f\n", seconds)
1609 } else if col > 0 {
1610 fmt.Fprintf(os.Stdout, "\n")
1611 }
1612
1613 debug.FreeOSMemory()
1614
1615 if timr {
1616 printDuration("groups")
1617 }
1618
1619 return
1620 }
1621
1622 // PROMOTE MERGED INVERTED INDEX TO TERM LIST AND POSTINGS FILES
1623
1624 if prom != "" && fild != "" {
1625
1626 prmq := eutils.CreatePromoters(prom, db, fild, isLink, args)
1627
1628 if prmq == nil {
1629 eutils.DisplayError("Unable to create new postings file generator")
1630 os.Exit(1)
1631 }
1632
1633 col := 0
1634 spaces := " "
1635
1636 // drain channel, print 2-4 character file prefix
1637 for str := range prmq {
1638
1639 blank := 7 - len(str)
1640 if blank > 0 {
1641 fmt.Fprintf(os.Stdout, "%s", spaces[:blank])
1642 }
1643 fmt.Fprintf(os.Stdout, "%s", str)
1644 col++
1645 if col >= 10 {
1646 col = 0
1647 fmt.Fprintf(os.Stdout, "\n")
1648 }
1649
1650 recordCount++
1651 runtime.Gosched()
1652 }
1653
1654 if col > 0 {
1655 fmt.Fprintf(os.Stdout, "\n")
1656 }
1657
1658 debug.FreeOSMemory()
1659
1660 if timr {
1661 printDuration("terms")
1662 }
1663
1664 return
1665 }
1666
1667 // QUERY POSTINGS FILES
1668
1669 if btch {
1670
1671 // read query lines for exact match
1672 scanr := bufio.NewScanner(in)
1673
1674 for scanr.Scan() {
1675 txt := scanr.Text()
1676
1677 // deStop should match value used in building the indices
1678 recordCount += eutils.ProcessSearch(db, txt, true, false, false, deStop)
1679 }
1680
1681 debug.FreeOSMemory()
1682
1683 if timr {
1684 printDuration("records")
1685 }
1686
1687 return
1688 }
1689
1690 if phrs != "" {
1691
1692 // deStop should match value used in building the indices
1693 if mock {
1694 recordCount = eutils.ProcessMock(db, phrs, xact, titl, deStop)
1695 } else if mtch {
1696 eutils.ProcessMatch(db, phrs, deStop)
1697 } else {
1698 recordCount = eutils.ProcessSearch(db, phrs, xact, titl, false, deStop)
1699 }
1700
1701 debug.FreeOSMemory()
1702
1703 if timr {
1704 printDuration("records")
1705 }
1706
1707 return
1708 }
1709
1710 if lnks != "" {
1711
1712 eutils.ProcessLinks(db, lnks)
1713
1714 debug.FreeOSMemory()
1715
1716 if timr {
1717 printDuration("terms")
1718 }
1719
1720 return
1721 }
1722
1723 if trms != "" {
1724
1725 // deStop should match value used in building the indices
1726 recordCount = eutils.ProcessCount(db, trms, plrl, psns, deStop)
1727
1728 debug.FreeOSMemory()
1729
1730 if timr {
1731 printDuration("terms")
1732 }
1733
1734 return
1735 }
1736
1737 // CONFIRM INPUT DATA AVAILABILITY AFTER RUNNING COMMAND GENERATORS
1738
1739 if fileName == "" && runtime.GOOS != "windows" {
1740
1741 fromStdin := bool((fi.Mode() & os.ModeCharDevice) == 0)
1742 if !isPipe || !fromStdin {
1743 mode := fi.Mode().String()
1744 eutils.DisplayError("No data supplied to rchive from stdin or file, mode is '%s'", mode)
1745 os.Exit(1)
1746 }
1747 }
1748
1749 if !usingFile && !isPipe {
1750
1751 eutils.DisplayError("No XML input data supplied to rchive")
1752 os.Exit(1)
1753 }
1754
1755 // SPECIFY STRINGS TO GO BEFORE AND AFTER ENTIRE OUTPUT OR EACH RECORD
1756
1757 parseHeadTail()
1758
1759 // PAD IDENTIFIER WITH LEADING ZEROS
1760
1761 if padz {
1762
1763 scanr := bufio.NewScanner(in)
1764
1765 // read lines of identifiers
1766 for scanr.Scan() {
1767
1768 str := scanr.Text()
1769
1770 if len(str) > 64 {
1771 continue
1772 }
1773
1774 if eutils.IsAllDigits(str) {
1775
1776 // pad numeric identifier to 8 characters with leading zeros
1777 ln := len(str)
1778 if ln < 8 {
1779 zeros := "00000000"
1780 str = zeros[ln:] + str
1781 }
1782 }
1783
1784 os.Stdout.WriteString(str)
1785 os.Stdout.WriteString("\n")
1786 }
1787
1788 return
1789 }
1790
1791 // PRODUCE ARCHIVE SUBPATH FROM IDENTIFIER
1792
1793 // -trie converts identifier to directory subpath plus file name (undocumented)
1794 if trei {
1795
1796 scanr := bufio.NewScanner(in)
1797
1798 sfx := ".xml"
1799 if pma2pme {
1800 sfx = ".asn"
1801 } else if idcsTrei || invt {
1802 sfx = ".e2x"
1803 } else if pstgTrei {
1804 sfx = ""
1805 }
1806 if zipp {
1807 sfx += ".gz"
1808 }
1809
1810 // read lines of identifiers
1811 for scanr.Scan() {
1812
1813 file := scanr.Text()
1814
1815 dir := ""
1816 id := ""
1817
1818 if arcvTrei {
1819 dir, id = eutils.ArchiveTrie(file)
1820 } else if idcsTrei || invt {
1821 dir, id = eutils.IndexTrie(file)
1822 } else if pstgTrei {
1823 dir, id = eutils.PostingsTrie(file)
1824 } else if linkTrei {
1825 dir, id = eutils.LinksTrie(file, true)
1826 } else {
1827 dir, id = eutils.ArchiveTrie(file)
1828 }
1829
1830 if id == "" {
1831 continue
1832 }
1833 if dir == "" {
1834 continue
1835 }
1836
1837 fpath := filepath.Join(dir, id+sfx)
1838 if fpath == "" {
1839 continue
1840 }
1841
1842 os.Stdout.WriteString(fpath)
1843 os.Stdout.WriteString("\n")
1844 }
1845
1846 return
1847 }
1848
1849 // CHECK FOR MISSING RECORDS IN LOCAL DIRECTORY INDEXED BY TRIE ON IDENTIFIER
1850
1851 // -archive plus -missing checks for missing records
1852 if stsh != "" && msng {
1853
1854 scanr := bufio.NewScanner(in)
1855
1856 sfx := ".xml"
1857 if zipp {
1858 sfx += ".gz"
1859 }
1860
1861 // read lines of identifiers
1862 for scanr.Scan() {
1863
1864 id := scanr.Text()
1865
1866 pos := strings.Index(id, ".")
1867 if pos >= 0 {
1868 // remove version suffix
1869 id = id[:pos]
1870 }
1871
1872 dir, file := eutils.ArchiveTrie(id)
1873
1874 if dir == "" || file == "" {
1875 continue
1876 }
1877
1878 fpath := filepath.Join(stsh, dir, file+sfx)
1879 if fpath == "" {
1880 continue
1881 }
1882
1883 _, err := os.Stat(fpath)
1884
1885 // if failed to find ".xml" file, try ".xml.gz" without requiring -gzip
1886 if err != nil && os.IsNotExist(err) && !zipp {
1887 fpath := filepath.Join(stsh, dir, file+".xml.gz")
1888 if fpath == "" {
1889 continue
1890 }
1891 _, err = os.Stat(fpath)
1892 }
1893 if err != nil && os.IsNotExist(err) {
1894 // record is missing from local file cache
1895 os.Stdout.WriteString(file)
1896 os.Stdout.WriteString("\n")
1897 }
1898 }
1899
1900 return
1901 }
1902
1903 // RETRIEVE XML COMPONENT RECORDS FROM LOCAL DIRECTORY INDEXED BY TRIE ON IDENTIFIER
1904
1905 // alternative windows version limits memory by not using goroutines
1906 if ftch != "" && indx == "" && runtime.GOOS == "windows" && windows {
1907
1908 scanr := bufio.NewScanner(in)
1909 if scanr == nil {
1910 eutils.DisplayError("Unable to create UID scanner")
1911 os.Exit(1)
1912 }
1913
1914 sfx := ".xml"
1915 if pma2pme {
1916 sfx = ".asn"
1917 }
1918 if zipp {
1919 sfx += ".gz"
1920 }
1921
1922 if head != "" {
1923 os.Stdout.WriteString(head)
1924 os.Stdout.WriteString("\n")
1925 }
1926
1927 var buf bytes.Buffer
1928
1929 for scanr.Scan() {
1930
1931 // read next identifier
1932 id := scanr.Text()
1933
1934 pos := strings.Index(id, ".")
1935 if pos >= 0 {
1936 // remove version suffix
1937 id = id[:pos]
1938 }
1939
1940 dir, file := eutils.ArchiveTrie(id)
1941
1942 if dir == "" || file == "" {
1943 continue
1944 }
1945
1946 fpath := filepath.Join(ftch, dir, file+sfx)
1947 if fpath == "" {
1948 continue
1949 }
1950
1951 iszip := zipp
1952
1953 inFile, err := os.Open(fpath)
1954
1955 // if failed to find ".xml" file, try ".xml.gz" without requiring -gzip
1956 if err != nil && os.IsNotExist(err) && !zipp {
1957 iszip = true
1958 fpath := filepath.Join(ftch, dir, file+".xml.gz")
1959 if fpath == "" {
1960 continue
1961 }
1962 inFile, err = os.Open(fpath)
1963 }
1964 if err != nil {
1965 continue
1966 }
1967
1968 buf.Reset()
1969
1970 brd := bufio.NewReader(inFile)
1971
1972 if iszip {
1973
1974 zpr, err := pgzip.NewReader(brd)
1975
1976 if err == nil {
1977 // copy and decompress cached file contents
1978 buf.ReadFrom(zpr)
1979 }
1980
1981 zpr.Close()
1982
1983 } else {
1984
1985 // copy cached file contents
1986 buf.ReadFrom(brd)
1987 }
1988
1989 inFile.Close()
1990
1991 str := buf.String()
1992
1993 if str == "" {
1994 continue
1995 }
1996
1997 if !pma2pme {
1998 pos := strings.Index(str, "<PubmedArticle")
1999 if pos > 0 {
2000 // remove leading xml and DOCTYPE lines
2001 str = str[pos:]
2002 if str == "" {
2003 continue
2004 }
2005 }
2006 }
2007
2008 recordCount++
2009
2010 if hd != "" {
2011 os.Stdout.WriteString(hd)
2012 os.Stdout.WriteString("\n")
2013 }
2014
2015 if hshv {
2016 // calculate hash code for verification table
2017 hsh := crc32.NewIEEE()
2018 hsh.Write([]byte(str))
2019 val := hsh.Sum32()
2020 res := strconv.FormatUint(uint64(val), 10)
2021 txt := file + "\t" + res + "\n"
2022 os.Stdout.WriteString(txt)
2023 } else {
2024 // send result to output
2025 os.Stdout.WriteString(str)
2026 if !strings.HasSuffix(str, "\n") {
2027 os.Stdout.WriteString("\n")
2028 }
2029 }
2030
2031 if tl != "" {
2032 os.Stdout.WriteString(tl)
2033 os.Stdout.WriteString("\n")
2034 }
2035
2036 debug.FreeOSMemory()
2037 }
2038
2039 if tail != "" {
2040 os.Stdout.WriteString(tail)
2041 os.Stdout.WriteString("\n")
2042 }
2043
2044 debug.FreeOSMemory()
2045
2046 if timr {
2047 printDuration("records")
2048 }
2049
2050 return
2051 }
2052
2053 // -fetch without -index retrieves XML files in trie-based directory structure
2054 if ftch != "" && indx == "" {
2055
2056 pfx := ""
2057 sfx := ".xml"
2058
2059 if db == "pmc" {
2060 pfx = "PMC"
2061 }
2062
2063 if pma2pme {
2064 sfx = ".asn"
2065 }
2066
2067 if recname == "" {
2068 if db == "pubmed" {
2069 recname = "PubmedArticle"
2070 } else if db == "pmc" {
2071 recname = "PMCInfo"
2072 } else if db == "taxonomy" {
2073 recname = "TaxonInfo"
2074 }
2075 }
2076
2077 uidq := eutils.CreateUIDReader(in)
2078 strq := eutils.CreateFetchers(ftch, db, pfx, sfx, recname, zipp, uidq)
2079 unsq := eutils.CreateXMLUnshuffler(strq)
2080
2081 if uidq == nil || strq == nil || unsq == nil {
2082 eutils.DisplayError("Unable to create archive reader")
2083 os.Exit(1)
2084 }
2085
2086 retlength := len("\n")
2087
2088 if head != "" {
2089 os.Stdout.WriteString(head)
2090 os.Stdout.WriteString("\n")
2091 }
2092
2093 // drain output channel
2094 for curr := range unsq {
2095
2096 str := curr.Text
2097
2098 if str == "" {
2099 continue
2100 }
2101
2102 if hd != "" {
2103 os.Stdout.WriteString(hd)
2104 os.Stdout.WriteString("\n")
2105 }
2106
2107 if hshv {
2108 // calculate hash code for verification table
2109 hsh := crc32.NewIEEE()
2110 hsh.Write([]byte(str))
2111 val := hsh.Sum32()
2112 res := strconv.FormatUint(uint64(val), 10)
2113 txt := curr.Ident + "\t" + res + "\n"
2114 os.Stdout.WriteString(txt)
2115 } else {
2116 // send result to output
2117 newln := false
2118 if !strings.HasSuffix(str, "\n") {
2119 newln = true
2120 }
2121
2122 if turbo {
2123 os.Stdout.WriteString("<NEXT_RECORD_SIZE>")
2124 nxt := len(str)
2125 if newln {
2126 nxt += retlength
2127 }
2128 val := strconv.Itoa(nxt)
2129 os.Stdout.WriteString(val)
2130 os.Stdout.WriteString("</NEXT_RECORD_SIZE>\n")
2131 }
2132
2133 os.Stdout.WriteString(str)
2134 if newln {
2135 os.Stdout.WriteString("\n")
2136 }
2137 }
2138
2139 if tl != "" {
2140 os.Stdout.WriteString(tl)
2141 os.Stdout.WriteString("\n")
2142 }
2143
2144 recordCount++
2145 runtime.Gosched()
2146 }
2147
2148 if tail != "" {
2149 os.Stdout.WriteString(tail)
2150 os.Stdout.WriteString("\n")
2151 }
2152
2153 debug.FreeOSMemory()
2154
2155 if timr {
2156 printDuration("records")
2157 }
2158
2159 return
2160 }
2161
2162 // -stream without -index retrieves compressed XML files in trie-based directory structure
2163 if strm != "" && indx == "" {
2164
2165 pfx := ""
2166 sfx := ".xml"
2167
2168 if pma2pme {
2169 sfx = ".asn"
2170 }
2171
2172 if db == "pmc" {
2173 pfx = "PMC"
2174 }
2175
2176 uidq := eutils.CreateUIDReader(in)
2177 strq := eutils.CreateCacheStreamers(strm, db, pfx, sfx, recskip, uidq)
2178 unsq := eutils.CreateXMLUnshuffler(strq)
2179
2180 if uidq == nil || strq == nil || unsq == nil {
2181 eutils.DisplayError("Unable to create archive reader")
2182 os.Exit(1)
2183 }
2184
2185 // drain output channel
2186 for curr := range unsq {
2187
2188 data := curr.Data
2189
2190 if data == nil {
2191 continue
2192 }
2193
2194 recordCount++
2195 runtime.Gosched()
2196
2197 _, err := os.Stdout.Write(data)
2198 if err != nil {
2199 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
2200 }
2201 }
2202
2203 debug.FreeOSMemory()
2204
2205 if timr {
2206 printDuration("records")
2207 }
2208
2209 return
2210 }
2211
2212 // -summon retrieves link files in trie-based directory structure
2213 if smmn != "" && indx == "" {
2214
2215 if recname == "" {
2216 if db == "pubmed" {
2217 recname = "PubmedArticle"
2218 } else if db == "pmc" {
2219 recname = "PMCInfo"
2220 } else if db == "taxonomy" {
2221 recname = "TaxonInfo"
2222 }
2223 }
2224
2225 uidq := eutils.CreateUIDReader(in)
2226 strq := eutils.CreateFetchers(smmn, db, "", ".e2x", recname, zipp, uidq)
2227 unsq := eutils.CreateXMLUnshuffler(strq)
2228
2229 if uidq == nil || strq == nil || unsq == nil {
2230 eutils.DisplayError("Unable to create link reader")
2231 os.Exit(1)
2232 }
2233
2234 if head != "" {
2235 os.Stdout.WriteString(head)
2236 os.Stdout.WriteString("\n")
2237 }
2238
2239 // drain output channel
2240 for curr := range unsq {
2241
2242 str := curr.Text
2243
2244 if str == "" {
2245 continue
2246 }
2247
2248 if hd != "" {
2249 os.Stdout.WriteString(hd)
2250 os.Stdout.WriteString("\n")
2251 }
2252
2253 if hshv {
2254 // calculate hash code for verification table
2255 hsh := crc32.NewIEEE()
2256 hsh.Write([]byte(str))
2257 val := hsh.Sum32()
2258 res := strconv.FormatUint(uint64(val), 10)
2259 txt := curr.Ident + "\t" + res + "\n"
2260 os.Stdout.WriteString(txt)
2261 } else {
2262 // send result to output
2263 os.Stdout.WriteString(str)
2264 if !strings.HasSuffix(str, "\n") {
2265 os.Stdout.WriteString("\n")
2266 }
2267 }
2268
2269 if tl != "" {
2270 os.Stdout.WriteString(tl)
2271 os.Stdout.WriteString("\n")
2272 }
2273
2274 recordCount++
2275 runtime.Gosched()
2276 }
2277
2278 if tail != "" {
2279 os.Stdout.WriteString(tail)
2280 os.Stdout.WriteString("\n")
2281 }
2282
2283 debug.FreeOSMemory()
2284
2285 if timr {
2286 printDuration("records")
2287 }
2288
2289 return
2290 }
2291
2292 // ENTREZ INDEX INVERSION
2293
2294 // -e2invert reads IdxDocumentSet XML and creates an inverted index
2295 if nvrt {
2296
2297 // environment variable can override garbage collector (undocumented)
2298 gcEnv := os.Getenv("EDIRECT_INVERT_GOGC")
2299 if gcEnv != "" {
2300 val, err := strconv.Atoi(gcEnv)
2301 if err == nil {
2302 if val >= 50 && val <= 1000 {
2303 debug.SetGCPercent(val)
2304 } else {
2305 debug.SetGCPercent(100)
2306 }
2307 }
2308 }
2309
2310 // environment variable can override number of servers (undocumented)
2311 svEnv := os.Getenv("EDIRECT_INVERT_SERV")
2312 if svEnv != "" {
2313 val, err := strconv.Atoi(svEnv)
2314 if err == nil {
2315 if val >= 1 && val <= 128 {
2316 numServe = val
2317 } else {
2318 numServe = 1
2319 }
2320 eutils.SetTunings(numProcs, numServe, serverRatio, chanDepth, farmSize, heapSize, goGc, false)
2321 }
2322 }
2323
2324 byt, err := io.ReadAll(in)
2325 if err != nil {
2326 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
2327 return
2328 }
2329
2330 str := string(byt)
2331 if str == "" {
2332 return
2333 }
2334
2335 if !strings.HasSuffix(str, "\n") {
2336 str += "\n"
2337 }
2338
2339 colq := eutils.StringToChan(str)
2340 iifq := eutils.InvertIndexedFile(colq)
2341
2342 if colq == nil || iifq == nil {
2343 eutils.DisplayError("Unable to create inverter")
2344 os.Exit(1)
2345 }
2346
2347 var out io.Writer
2348
2349 out = os.Stdout
2350
2351 if zipp {
2352
2353 zpr, err := pgzip.NewWriterLevel(out, pgzip.BestSpeed)
2354 if err != nil {
2355 eutils.DisplayError("Unable to create compressor")
2356 os.Exit(1)
2357 }
2358
2359 // close decompressor when all records have been processed
2360 defer zpr.Close()
2361
2362 // use compressor for writing file
2363 out = zpr
2364 }
2365
2366 // create buffered writer layer
2367 wrtr := bufio.NewWriter(out)
2368
2369 wrtr.WriteString("<InvDocumentSet>\n")
2370
2371 // drain channel of alphabetized results
2372 for str := range iifq {
2373
2374 // send result to output
2375 wrtr.WriteString(str)
2376
2377 recordCount++
2378 runtime.Gosched()
2379 }
2380
2381 wrtr.WriteString("</InvDocumentSet>\n\n")
2382
2383 wrtr.Flush()
2384
2385 debug.FreeOSMemory()
2386
2387 if timr {
2388 printDuration("terms")
2389 }
2390
2391 return
2392 }
2393
2394 // CREATE XML BLOCK READER FROM STDIN OR FILE
2395
2396 rdr := eutils.CreateXMLStreamer(in, nil)
2397 if rdr == nil {
2398 eutils.DisplayError("Unable to create XML Block Reader")
2399 os.Exit(1)
2400 }
2401
2402 // FUSE SUBSETS OF INVERTED INDEX FILES
2403
2404 // -fuse combines subsets of inverted files for subsequent -merge operation
2405 if fuse {
2406
2407 // environment variable can override garbage collector (undocumented)
2408 gcEnv := os.Getenv("EDIRECT_FUSE_GOGC")
2409 if gcEnv != "" {
2410 val, err := strconv.Atoi(gcEnv)
2411 if err == nil {
2412 if val >= 50 && val <= 1000 {
2413 debug.SetGCPercent(val)
2414 } else {
2415 debug.SetGCPercent(100)
2416 }
2417 }
2418 } else if gcdefault {
2419 // default to 100 for fuse and merge
2420 debug.SetGCPercent(100)
2421 }
2422
2423 // environment variable can override number of servers (undocumented)
2424 svEnv := os.Getenv("EDIRECT_FUSE_SERV")
2425 if svEnv != "" {
2426 val, err := strconv.Atoi(svEnv)
2427 if err == nil {
2428 if val >= 1 && val <= 128 {
2429 numServe = val
2430 } else {
2431 numServe = 1
2432 }
2433 eutils.SetTunings(numProcs, numServe, serverRatio, chanDepth, farmSize, heapSize, goGc, false)
2434 }
2435 }
2436
2437 chns := eutils.CreateXMLProducer("InvDocument", "", false, rdr)
2438 fusr := eutils.CreateFusers(chns)
2439 mrgr := eutils.CreateMergers(fusr)
2440 unsq := eutils.CreateXMLUnshuffler(mrgr)
2441
2442 if chns == nil || fusr == nil || mrgr == nil || unsq == nil {
2443 eutils.DisplayError("Unable to create inverted index fuser")
2444 os.Exit(1)
2445 }
2446
2447 var out io.Writer
2448
2449 out = os.Stdout
2450
2451 if zipp {
2452
2453 zpr, err := pgzip.NewWriterLevel(out, pgzip.BestSpeed)
2454 if err != nil {
2455 eutils.DisplayError("Unable to create compressor")
2456 os.Exit(1)
2457 }
2458
2459 // close decompressor when all records have been processed
2460 defer zpr.Close()
2461
2462 // use compressor for writing file
2463 out = zpr
2464 }
2465
2466 // create buffered writer layer
2467 wrtr := bufio.NewWriter(out)
2468
2469 wrtr.WriteString("<InvDocumentSet>\n")
2470
2471 // drain channel of alphabetized results
2472 for curr := range unsq {
2473
2474 str := curr.Text
2475
2476 if str == "" {
2477 continue
2478 }
2479
2480 // send result to output
2481 wrtr.WriteString(str)
2482
2483 recordCount++
2484 runtime.Gosched()
2485 }
2486
2487 wrtr.WriteString("</InvDocumentSet>\n\n")
2488
2489 wrtr.Flush()
2490
2491 debug.FreeOSMemory()
2492
2493 if timr {
2494 printDuration("terms")
2495 }
2496
2497 return
2498 }
2499
2500 // ENSURE PRESENCE OF PATTERN ARGUMENT
2501
2502 if len(args) < 1 {
2503 eutils.DisplayError("Insufficient command-line arguments supplied to rchive")
2504 os.Exit(1)
2505 }
2506
2507 // allow -record as synonym of -pattern (undocumented)
2508 if args[0] == "-record" || args[0] == "-Record" {
2509 args[0] = "-pattern"
2510 }
2511
2512 // make sure top-level -pattern command is next
2513 if args[0] != "-pattern" && args[0] != "-Pattern" {
2514 eutils.DisplayError("No -pattern in command-line arguments")
2515 os.Exit(1)
2516 }
2517 if len(args) < 2 {
2518 eutils.DisplayError("Item missing after -pattern command")
2519 os.Exit(1)
2520 }
2521
2522 topPat := args[1]
2523 if topPat == "" {
2524 eutils.DisplayError("Item missing after -pattern command")
2525 os.Exit(1)
2526 }
2527 if strings.HasPrefix(topPat, "-") {
2528 eutils.DisplayError("Misplaced %s command", topPat)
2529 os.Exit(1)
2530 }
2531
2532 // look for -pattern Parent/* construct for heterogeneous data, e.g., -pattern PubmedArticleSet/*
2533 topPattern, star := eutils.SplitInTwoLeft(topPat, "/")
2534 if topPattern == "" {
2535 return
2536 }
2537
2538 parent := ""
2539 if star == "*" {
2540 parent = topPattern
2541 } else if star != "" {
2542 eutils.DisplayError("-pattern Parent/Child construct is not supported")
2543 os.Exit(1)
2544 }
2545
2546 // REPORT RECORDS THAT CONTAIN DAMAGED EMBEDDED HTML TAGS
2547
2548 reportEncodedMarkup := func(typ, id, str string) {
2549
2550 var buffer strings.Builder
2551
2552 max := len(str)
2553
2554 lookAhead := func(txt string, to int) string {
2555
2556 mx := len(txt)
2557 if to > mx {
2558 to = mx
2559 }
2560 pos := strings.Index(txt[:to], "gt;")
2561 if pos > 0 {
2562 to = pos + 3
2563 }
2564 return txt[:to]
2565 }
2566
2567 findContext := func(fr, to int) string {
2568
2569 numSpaces := 0
2570
2571 for fr > 0 {
2572 ch := str[fr]
2573 if ch == ' ' {
2574 numSpaces++
2575 if numSpaces > 1 {
2576 fr++
2577 break
2578 }
2579 } else if ch == '\n' || ch == '>' {
2580 fr++
2581 break
2582 }
2583 fr--
2584 }
2585
2586 numSpaces = 0
2587
2588 for to < max {
2589 ch := str[to]
2590 if ch == ' ' {
2591 numSpaces++
2592 if numSpaces > 1 {
2593 break
2594 }
2595 } else if ch == '\n' || ch == '<' {
2596 break
2597 }
2598 to++
2599 }
2600
2601 return str[fr:to]
2602 }
2603
2604 reportMarkup := func(lbl string, fr, to int, txt string) {
2605
2606 if lbl == typ || typ == "ALL" {
2607 // extract XML of SELF, SINGLE, DOUBLE, or AMPER types, or ALL
2608 buffer.WriteString(str)
2609 buffer.WriteString("\n")
2610 } else if typ == "" {
2611 // print report
2612 buffer.WriteString(id)
2613 buffer.WriteString("\t")
2614 buffer.WriteString(lbl)
2615 buffer.WriteString("\t")
2616 buffer.WriteString(txt)
2617 buffer.WriteString("\t| ")
2618 ctx := findContext(fr, to)
2619 buffer.WriteString(ctx)
2620 if eutils.HasUnicodeMarkup(ctx) {
2621 ctx = eutils.RepairUnicodeMarkup(ctx, eutils.SPACE)
2622 }
2623 ctx = eutils.CleanupEncodedMarkup(ctx)
2624 buffer.WriteString("\t| ")
2625 buffer.WriteString(ctx)
2626 if eutils.HasAmpOrNotASCII(ctx) {
2627 ctx = html.UnescapeString(ctx)
2628 }
2629 buffer.WriteString("\t| ")
2630 buffer.WriteString(ctx)
2631 buffer.WriteString("\n")
2632 }
2633 }
2634
2635 /*
2636 badTags := [10]string{
2637 "<i/>",
2638 "<i />",
2639 "<b/>",
2640 "<b />",
2641 "<u/>",
2642 "<u />",
2643 "<sup/>",
2644 "<sup />",
2645 "<sub/>",
2646 "<sub />",
2647 }
2648 */
2649
2650 skip := 0
2651
2652 /*
2653 var prev rune
2654 */
2655
2656 for i, ch := range str {
2657 if skip > 0 {
2658 skip--
2659 continue
2660 }
2661 /*
2662 if ch > 127 {
2663 if IsUnicodeSuper(ch) {
2664 if IsUnicodeSubsc(prev) {
2665 // reportMarkup("UNIUP", i, i+2, string(ch))
2666 }
2667 } else if IsUnicodeSubsc(ch) {
2668 if IsUnicodeSuper(prev) {
2669 // reportMarkup("UNIDN", i, i+2, string(ch))
2670 }
2671 } else if ch == '\u0038' || ch == '\u0039' {
2672 // reportMarkup("ANGLE", i, i+2, string(ch))
2673 }
2674 prev = ch
2675 continue
2676 } else {
2677 prev = ' '
2678 }
2679 */
2680 if ch == '<' {
2681 /*
2682 j := i + 1
2683 if j < max {
2684 nxt := str[j]
2685 if nxt == 'i' || nxt == 'b' || nxt == 'u' || nxt == 's' {
2686 for _, tag := range badTags {
2687 if strings.HasPrefix(str, tag) {
2688 k := len(tag)
2689 reportMarkup("SELF", i, i+k, tag)
2690 break
2691 }
2692 }
2693 }
2694 }
2695 if strings.HasPrefix(str[i:], "</sup><sub>") {
2696 // reportMarkup("SUPSUB", i, i+11, "</sup><sub>")
2697 } else if strings.HasPrefix(str[i:], "</sub><sup>") {
2698 // reportMarkup("SUBSUP", i, i+11, "</sub><sup>")
2699 }
2700 */
2701 continue
2702 } else if ch != '&' {
2703 continue
2704 } else if strings.HasPrefix(str[i:], "&lt;") {
2705 sub := lookAhead(str[i:], 14)
2706 _, ok := eutils.HTMLRepair(sub)
2707 if ok {
2708 skip = len(sub) - 1
2709 reportMarkup("SINGLE", i, i+skip+1, sub)
2710 continue
2711 }
2712 } else if strings.HasPrefix(str[i:], "&amp;lt;") {
2713 sub := lookAhead(str[i:], 22)
2714 _, ok := eutils.HTMLRepair(sub)
2715 if ok {
2716 skip = len(sub) - 1
2717 reportMarkup("DOUBLE", i, i+skip+1, sub)
2718 continue
2719 }
2720 } else if strings.HasPrefix(str[i:], "&amp;amp;") {
2721 reportMarkup("AMPER", i, i+9, "&amp;amp;")
2722 skip = 8
2723 continue
2724 }
2725 }
2726
2727 res := buffer.String()
2728
2729 os.Stdout.WriteString(res)
2730 }
2731
2732 // -damaged plus -index plus -pattern reports records with multiply-encoded HTML tags
2733 if dmgd && indx != "" {
2734
2735 find := eutils.ParseIndex(indx)
2736
2737 eutils.PartitionXML(topPattern, star, false, rdr,
2738 func(str string) {
2739 recordCount++
2740
2741 id := eutils.FindIdentifier(str[:], parent, find)
2742 if id == "" {
2743 return
2744 }
2745
2746 // remove default version suffix
2747 if strings.HasSuffix(id, ".1") {
2748 idlen := len(id)
2749 id = id[:idlen-2]
2750 }
2751
2752 reportEncodedMarkup(dmgdType, id, str)
2753 })
2754
2755 if timr {
2756 printDuration("records")
2757 }
2758
2759 return
2760 }
2761
2762 // COMPARE XML UPDATES TO LOCAL DIRECTORY, RETAIN NEW OR SUBSTANTIVELY CHANGED RECORDS
2763
2764 // -prepare plus -archive plus -index plus -pattern compares XML files against stash
2765 if stsh != "" && indx != "" && cmpr {
2766
2767 doReport := false
2768 if cmprType == "" || cmprType == "report" {
2769 doReport = true
2770 } else if cmprType != "release" {
2771 eutils.DisplayError("-prepare argument must be release or report")
2772 os.Exit(1)
2773 }
2774
2775 find := eutils.ParseIndex(indx)
2776
2777 if head != "" {
2778 os.Stdout.WriteString(head)
2779 os.Stdout.WriteString("\n")
2780 }
2781
2782 eutils.PartitionXML(topPattern, star, false, rdr,
2783 func(str string) {
2784 recordCount++
2785
2786 id := eutils.FindIdentifier(str[:], parent, find)
2787 if id == "" {
2788 return
2789 }
2790
2791 pos := strings.Index(id, ".")
2792 if pos >= 0 {
2793 // remove version suffix
2794 id = id[:pos]
2795 }
2796
2797 dir, file := eutils.ArchiveTrie(id)
2798
2799 if dir == "" || file == "" {
2800 return
2801 }
2802
2803 fpath := filepath.Join(stsh, dir, file+".xml")
2804 if fpath == "" {
2805 return
2806 }
2807
2808 // print new or updated XML record
2809 printRecord := func(stn string, isNew bool) {
2810
2811 if stn == "" {
2812 return
2813 }
2814
2815 if doReport {
2816 if isNew {
2817 os.Stdout.WriteString("NW ")
2818 os.Stdout.WriteString(id)
2819 os.Stdout.WriteString("\n")
2820 } else {
2821 os.Stdout.WriteString("UP ")
2822 os.Stdout.WriteString(id)
2823 os.Stdout.WriteString("\n")
2824 }
2825 return
2826 }
2827
2828 if hd != "" {
2829 os.Stdout.WriteString(hd)
2830 os.Stdout.WriteString("\n")
2831 }
2832
2833 os.Stdout.WriteString(stn)
2834 os.Stdout.WriteString("\n")
2835
2836 if tl != "" {
2837 os.Stdout.WriteString(tl)
2838 os.Stdout.WriteString("\n")
2839 }
2840 }
2841
2842 _, err := os.Stat(fpath)
2843 if err != nil && os.IsNotExist(err) {
2844 // new record
2845 printRecord(str, true)
2846 return
2847 }
2848 if err != nil {
2849 return
2850 }
2851
2852 buf, err := os.ReadFile(fpath)
2853 if err != nil {
2854 return
2855 }
2856
2857 txt := string(buf[:])
2858 txt = strings.TrimSuffix(txt, "\n")
2859
2860 // check for optional -ignore argument
2861 if ignr != "" {
2862
2863 // ignore differences inside specified object
2864 ltag := "<" + ignr + ">"
2865 sleft, _ := eutils.SplitInTwoLeft(str, ltag)
2866 tleft, _ := eutils.SplitInTwoLeft(txt, ltag)
2867
2868 rtag := "</" + ignr + ">"
2869 _, srght := eutils.SplitInTwoRight(str, rtag)
2870 _, trght := eutils.SplitInTwoRight(txt, rtag)
2871
2872 if sleft == tleft && srght == trght {
2873 if doReport {
2874 os.Stdout.WriteString("NO ")
2875 os.Stdout.WriteString(id)
2876 os.Stdout.WriteString("\n")
2877 }
2878 return
2879 }
2880
2881 } else {
2882
2883 // compare entirety of objects
2884 if str == txt {
2885 if doReport {
2886 os.Stdout.WriteString("NO ")
2887 os.Stdout.WriteString(id)
2888 os.Stdout.WriteString("\n")
2889 }
2890 return
2891 }
2892 }
2893
2894 // substantively modified record
2895 printRecord(str, false)
2896 })
2897
2898 if tail != "" {
2899 os.Stdout.WriteString(tail)
2900 os.Stdout.WriteString("\n")
2901 }
2902
2903 if timr {
2904 printDuration("records")
2905 }
2906
2907 return
2908 }
2909
2910 // SAVE XML COMPONENT RECORDS TO LOCAL DIRECTORY INDEXED BY TRIE ON IDENTIFIER
2911
2912 // common xml + DOCTYPE header for PubmedArticle XML
2913 pmaSetHead := `<?xml version="1.0" encoding="UTF-8"?>
2914 <!DOCTYPE PubmedArticle PUBLIC "-//NLM//DTD PubMedArticle, 1st January 2019//EN" "https://dtd.nlm.nih.gov/ncbi/pubmed/out/pubmed_190101.dtd">
2915 `
2916
2917 // common xml without DOCTYPE header for PMCInfo XML
2918 pmcSetHead := `<?xml version="1.0" encoding="UTF-8"?>
2919 `
2920
2921 // -archive plus -index plus -pattern saves XML files in trie-based directory structure
2922 if stsh != "" && indx != "" {
2923
2924 asn := false
2925 pfx := ""
2926 sfx := ".xml"
2927 xmlString := ""
2928 report := 1000
2929
2930 if db == "pmc" {
2931 pfx = "PMC"
2932 xmlString = pmcSetHead
2933 } else if db == "pubmed" {
2934 xmlString = pmaSetHead
2935 } else if db == "taxonomy" {
2936 report = 50000
2937 }
2938
2939 if pma2pme {
2940 asn = true
2941 sfx = ".asn"
2942 }
2943
2944 xmlq := eutils.CreateXMLProducer(topPattern, star, false, rdr)
2945 stsq := eutils.CreateStashers(stsh, parent, indx, pfx, sfx, db, xmlString, transform, hshv, zipp, asn, report, xmlq)
2946 clrq := eutils.CreateClearer(idcs, incr, db, stsq)
2947
2948 if xmlq == nil || stsq == nil || clrq == nil {
2949 eutils.DisplayError("Unable to create stash generator")
2950 os.Exit(1)
2951 }
2952
2953 if hshv {
2954 // if printing hash, do not clear incremental indices, just pass hash value
2955 clrq = stsq
2956 }
2957
2958 // drain output channel
2959 for str := range clrq {
2960
2961 if hshv {
2962 // print table of UIDs and hash values
2963 os.Stdout.WriteString(str)
2964 }
2965
2966 if dbug {
2967 fmt.Fprintf(os.Stderr, "%s\n", str)
2968 }
2969
2970 recordCount++
2971 runtime.Gosched()
2972 }
2973
2974 debug.FreeOSMemory()
2975
2976 if timr {
2977 printDuration("records")
2978 }
2979
2980 return
2981 }
2982
2983 // READ FILE OF IDENTIFIERS AND EXTRACT SELECTED RECORDS FROM XML INPUT FILE
2984
2985 // -index plus -unique [plus -head/-tail/-hd/-tl] plus -pattern with no other extraction arguments
2986 // takes an XML input file and a file of its UIDs and keeps only the last version of each record
2987 if indx != "" && unqe != "" && len(args) == 2 {
2988
2989 // read file of identifiers to use for filtering
2990 fl, err := os.Open(unqe)
2991 if err != nil {
2992 eutils.DisplayError("Unable to open identifier file '%s'", unqe)
2993 os.Exit(1)
2994 }
2995
2996 // create map that counts instances of each UID
2997 order := make(map[string]int)
2998
2999 scanr := bufio.NewScanner(fl)
3000
3001 // read lines of identifiers
3002 for scanr.Scan() {
3003
3004 id := scanr.Text()
3005
3006 // map records count for given identifier
3007 val := order[id]
3008 val++
3009 order[id] = val
3010 }
3011
3012 fl.Close()
3013
3014 find := eutils.ParseIndex(indx)
3015
3016 if head != "" {
3017 os.Stdout.WriteString(head)
3018 os.Stdout.WriteString("\n")
3019 }
3020
3021 eutils.PartitionXML(topPattern, star, false, rdr,
3022 func(str string) {
3023 recordCount++
3024
3025 id := eutils.FindIdentifier(str[:], parent, find)
3026 if id == "" {
3027 return
3028 }
3029
3030 val, ok := order[id]
3031 if !ok {
3032 // not in identifier list, skip
3033 return
3034 }
3035 // decrement count in map
3036 val--
3037 order[id] = val
3038 if val > 0 {
3039 // only write last record with a given identifier
3040 return
3041 }
3042
3043 if hd != "" {
3044 os.Stdout.WriteString(hd)
3045 os.Stdout.WriteString("\n")
3046 }
3047
3048 // write selected record
3049 os.Stdout.WriteString(str[:])
3050 os.Stdout.WriteString("\n")
3051
3052 if tl != "" {
3053 os.Stdout.WriteString(tl)
3054 os.Stdout.WriteString("\n")
3055 }
3056 })
3057
3058 if tail != "" {
3059 os.Stdout.WriteString(tail)
3060 os.Stdout.WriteString("\n")
3061 }
3062
3063 if timr {
3064 printDuration("records")
3065 }
3066
3067 return
3068 }
3069
3070 // GENERATE RECORD INDEX ON XML INPUT FILE
3071
3072 // -index plus -pattern prints record identifier and XML size
3073 if indx != "" {
3074
3075 lbl := ""
3076 // check for optional filename label after -pattern argument (undocumented)
3077 if len(args) > 3 && args[2] == "-lbl" {
3078 lbl = args[3]
3079
3080 lbl = strings.TrimSpace(lbl)
3081 if strings.HasPrefix(lbl, "pubmed") {
3082 lbl = lbl[7:]
3083 }
3084 if strings.HasSuffix(lbl, ".xml.gz") {
3085 xlen := len(lbl)
3086 lbl = lbl[:xlen-7]
3087 }
3088 lbl = strings.TrimSpace(lbl)
3089 }
3090
3091 // legend := "ID\tREC\tSIZE"
3092
3093 find := eutils.ParseIndex(indx)
3094
3095 eutils.PartitionXML(topPattern, star, false, rdr,
3096 func(str string) {
3097 recordCount++
3098
3099 id := eutils.FindIdentifier(str[:], parent, find)
3100 if id == "" {
3101 return
3102 }
3103 if lbl != "" {
3104 fmt.Printf("%s\t%d\t%s\n", id, len(str), lbl)
3105 } else {
3106 fmt.Printf("%s\t%d\n", id, len(str))
3107 }
3108 })
3109
3110 if timr {
3111 printDuration("records")
3112 }
3113
3114 return
3115 }
3116
3117 // SORT XML RECORDS BY IDENTIFIER
3118
3119 // -pattern record_name -sort parent/element@attribute^version, strictly alphabetic sort order (undocumented)
3120 if len(args) == 4 && args[2] == "-sort" {
3121
3122 indx := args[3]
3123
3124 // create map that records each UID
3125 order := make(map[string][]string)
3126
3127 find := eutils.ParseIndex(indx)
3128
3129 eutils.PartitionXML(topPattern, star, false, rdr,
3130 func(str string) {
3131 recordCount++
3132
3133 id := eutils.FindIdentifier(str[:], parent, find)
3134 if id == "" {
3135 return
3136 }
3137
3138 data, ok := order[id]
3139 if !ok {
3140 data = make([]string, 0, 1)
3141 }
3142 data = append(data, str)
3143 // always need to update order, since data may be reallocated
3144 order[id] = data
3145 })
3146
3147 // sort fields in alphabetical order, unlike xtract version, which sorts numbers by numeric value
3148 keys := slices.Sorted(maps.Keys(order))
3149
3150 if head != "" {
3151 os.Stdout.WriteString(head)
3152 os.Stdout.WriteString("\n")
3153 }
3154
3155 for _, id := range keys {
3156
3157 strs := order[id]
3158 for _, str := range strs {
3159 os.Stdout.WriteString(str)
3160 os.Stdout.WriteString("\n")
3161 }
3162 }
3163
3164 if tail != "" {
3165 os.Stdout.WriteString(tail)
3166 os.Stdout.WriteString("\n")
3167 }
3168
3169 debug.FreeOSMemory()
3170
3171 if timr {
3172 printDuration("records")
3173 }
3174
3175 return
3176 }
3177
3178 // REPORT UNRECOGNIZED COMMAND
3179
3180 eutils.DisplayError("Unrecognized rchive command")
3181
3182 for _, str := range origArgs {
3183 fmt.Fprintf(os.Stderr, "%s\n", str)
3184 }
3185 fmt.Fprintf(os.Stderr, "\n")
3186
3187 os.Exit(1)
3188 }