Debian Codegraph @

ecommon.sh

raw
1 #!/bin/bash
2
3 # ===========================================================================
4 #
5 # PUBLIC DOMAIN NOTICE
6 # National Center for Biotechnology Information (NCBI)
7 #
8 # This software/database is a "United States Government Work" under the
9 # terms of the United States Copyright Act. It was written as part of
10 # the author's official duties as a United States Government employee and
11 # thus cannot be copyrighted. This software/database is freely available
12 # to the public for use. The National Library of Medicine and the U.S.
13 # Government do not place any restriction on its use or reproduction.
14 # We would, however, appreciate having the NCBI and the author cited in
15 # any work or product based on this material.
16 #
17 # Although all reasonable efforts have been taken to ensure the accuracy
18 # and reliability of the software and data, the NLM and the U.S.
19 # Government do not and cannot warrant the performance or results that
20 # may be obtained by using this software or data. The NLM and the U.S.
21 # Government disclaim all warranties, express or implied, including
22 # warranties of performance, merchantability or fitness for any particular
23 # purpose.
24 #
25 # ===========================================================================
26 #
27 # File Name: ecommon.sh
28 #
29 # Author: Jonathan Kans, Aaron Ucko
30 #
31 # Version Creation Date: 04/17/2020
32 #
33 # ==========================================================================
34
35 # environment variable turns on shell tracing
36
37 if [ -n "${EDIRECT_TRACE}" ] && [ "${EDIRECT_TRACE}" = true ]
38 then
39 set -x
40 fi
41
42 version="24.0"
43
44 # initialize common flags
45
46 raw=false
47 dev=false
48 internal=false
49 external=false
50 api_key=""
51 immediate=false
52 express=false
53
54 reldate=""
55 mindate=""
56 maxdate=""
57 datetype=""
58
59 # undocumented -quick argument bypasses logic that works around PubMed SOLR server limits
60 quick=false
61 quickx=false
62
63 email=""
64 emailr=""
65 emailx=""
66
67 tool="edirect"
68 toolr=""
69 toolx=""
70
71 debug=false
72 debugx=false
73
74 log=false
75 logx=false
76
77 # timer now on by default
78 timer=true
79 timerx=false
80
81 label=""
82 labels=""
83 labelx=""
84
85 reldatex=""
86 mindatex=""
87 maxdatex=""
88 datetypex=""
89
90 verbose=false
91 tranquil=false
92
93 basx=""
94 base="https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"
95
96 argsConsumed=0
97
98 seconds_start=$(date "+%s")
99
100 # initialize database and identifier command-line variables
101
102 db=""
103
104 ids=""
105 input=""
106
107 needHistory=false
108
109 # initialize EDirect message fields
110
111 mssg=""
112 err=""
113 dbase=""
114 web_env=""
115 qry_key=""
116 num=0
117 empty=false
118 stp=0
119
120 rest=""
121 qury=""
122
123 # environment variable disables retry attempts
124
125 showErrors=true
126 if [ -n "${EDIRECT_NO_ERRORS}" ] && [ "${EDIRECT_NO_ERRORS}" = true ]
127 then
128 showErrors=false
129 fi
130
131 retryAllowed=true
132 if [ -n "${EDIRECT_NO_RETRY}" ] && [ "${EDIRECT_NO_RETRY}" = true ]
133 then
134 retryAllowed=false
135 fi
136
137 # set up colors for error report
138
139 ColorSetup() {
140
141 if [ -z "$TERM" ] || [ ! -t 2 ]
142 then
143 RED=""
144 BLUE=""
145 BOLD=""
146 FLIP=""
147 INIT=""
148 elif command -v tput >/dev/null
149 then
150 RED="$(tput setaf 1)"
151 BLUE="$(tput setaf 4)"
152 BOLD="$(tput bold)"
153 FLIP="$(tput rev)"
154 INIT="$(tput sgr0)"
155 else
156 # assume ANSI
157 escape="$(printf '\033')"
158 RED="${escape}[31m"
159 BLUE="${escape}[34m"
160 BOLD="${escape}[1m"
161 FLIP="${escape}[7m"
162 INIT="${escape}[0m"
163 fi
164 LOUD="${INIT}${RED}${BOLD}"
165 INVT="${LOUD}${FLIP}"
166 # clear color on terminal if "export EDIRECT_TRACE=true" has been used
167 echo "${INIT}" > /dev/null
168 }
169
170 ColorSetup
171
172 # highlighted error and warning functions
173
174 DisplayError() {
175
176 if [ $# -gt 0 ]
177 then
178 msg="$1"
179 echo "${INVT} ERROR: ${LOUD} ${msg}${INIT}" >&2
180 fi
181 }
182
183 DisplayWarning() {
184
185 if [ $# -gt 0 ]
186 then
187 msg="$1"
188 echo "${INVT} WARNING: ${LOUD} ${msg}${INIT}" >&2
189 fi
190 }
191
192 DisplayNote() {
193
194 if [ $# -gt 0 ]
195 then
196 msg="$1"
197 echo "${INVT} NOTE: ${LOUD} ${msg}${INIT}" >&2
198 fi
199 }
200
201 # parse ENTREZ_DIRECT, eSearchResult, eLinkResult, or ePostResult
202
203 ParseMessage() {
204
205 mesg=$1
206 objc=$2
207 shift 2
208
209 if [ -z "$mesg" ]
210 then
211 return 1
212 fi
213
214 object=$( echo "$mesg" | tr -d '\n' | sed -n "s|.*<$objc>\\(.*\\)</$objc>.*|\\1|p" )
215 if [ -z "$object" ]
216 then
217 return 2
218 fi
219
220 err=$( echo "$object" | sed -n 's|.*<Error>\(.*\)</Error>.*|\1|p' )
221 if [ -z "$err" ]
222 then
223 while [ $# -gt 0 ]
224 do
225 var=$1
226 fld=$2
227 shift 2
228 value=$( echo "$object" | sed -n "s|.*<$fld>\\(.*\\)</$fld>.*|\\1|p" )
229 eval "$var=\$value"
230 done
231 fi
232
233 return 0
234 }
235
236 AdjustEmailAndTool() {
237
238 # hierarchy is -email argument, then Email XML field, then calculated email
239
240 if [ -n "$emailr" ]
241 then
242 emailx="$emailr"
243 fi
244 if [ -n "$emailx" ]
245 then
246 email="$emailx"
247 fi
248
249 if [ -n "$toolr" ]
250 then
251 toolx="$toolr"
252 fi
253 if [ -n "$toolx" ]
254 then
255 tool="$toolx"
256 fi
257 }
258
259 # check for ENTREZ_DIRECT object, or list of UIDs, piped from stdin
260
261 ParseStdin() {
262
263 if [ \( -e /dev/fd/0 -o ! -d /dev/fd \) -a ! -t 0 ]
264 then
265 mssg=$( cat )
266 ParseMessage "$mssg" ENTREZ_DIRECT \
267 dbase Db web_env WebEnv qry_key QueryKey qury Query \
268 mindatex MinDate maxdatex MaxDate reldatex RelDate \
269 datetypex DateType num Count \
270 stp Step toolx Tool emailx Email labelx Labels \
271 quickx Quick debugx Debug logx Log timerx Elapsed
272 if [ "$?" = 2 ]
273 then
274 # if no ENTREZ_DIRECT message present, support passing raw UIDs via stdin
275 rest="$mssg"
276 else
277 # support for UIDs instantiated within message in lieu of Entrez History
278 rest=$( echo "$mssg" |
279 xtract -pattern ENTREZ_DIRECT -sep "\n" -element Id |
280 grep '.' | sort -n | uniq )
281 if [ -z "$stp" ]
282 then
283 stp=1
284 fi
285 # hierarchy is -email argument, then Email XML field, then calculated email
286 AdjustEmailAndTool
287 if [ "$quickx" = "Y" ]
288 then
289 quick=true
290 fi
291 if [ "$debugx" = "Y" ]
292 then
293 debug=true
294 fi
295 if [ "$logx" = "Y" ]
296 then
297 log=true
298 fi
299 if [ -n "$timerx" ]
300 then
301 timer=true
302 fi
303 if [ -n "$labelx" ]
304 then
305 labels="$labelx"
306 fi
307 cnt=$( echo "$mssg" | xtract -pattern ENTREZ_DIRECT -element Count )
308 if [ -n "$cnt" ] && [ "$cnt" = "0" ]
309 then
310 empty=true
311 fi
312 fi
313 fi
314 }
315
316 # process common control flags
317
318 CheckForArgumentValue() {
319
320 tag="$1"
321 rem="$2"
322
323 if [ "$rem" -lt 2 ]
324 then
325 DisplayError "Missing ${tag} argument"
326 exit 1
327 fi
328 }
329
330 ParseCommonArgs() {
331
332 argsConsumed=0
333 while [ $# -gt 0 ]
334 do
335 tag="$1"
336 rem="$#"
337 case "$tag" in
338 -dev )
339 dev=true
340 argsConsumed=$((argsConsumed + 1))
341 shift
342 ;;
343 -raw )
344 raw=true
345 argsConsumed=$((argsConsumed + 1))
346 shift
347 ;;
348 -internal | -int )
349 internal=true
350 argsConsumed=$((argsConsumed + 1))
351 shift
352 ;;
353 -external | -ext )
354 external=true
355 argsConsumed=$((argsConsumed + 1))
356 shift
357 ;;
358 -immediate )
359 immediate=true
360 argsConsumed=$((argsConsumed + 1))
361 shift
362 ;;
363 -express )
364 express=true
365 argsConsumed=$((argsConsumed + 1))
366 shift
367 ;;
368 -base )
369 argsConsumed=$((argsConsumed + 1))
370 CheckForArgumentValue "$tag" "$rem"
371 shift
372 basx="$1"
373 argsConsumed=$((argsConsumed + 1))
374 shift
375 ;;
376 -input )
377 argsConsumed=$((argsConsumed + 1))
378 CheckForArgumentValue "$tag" "$rem"
379 shift
380 input="$1"
381 argsConsumed=$((argsConsumed + 1))
382 shift
383 ;;
384 -web )
385 argsConsumed=$((argsConsumed + 1))
386 CheckForArgumentValue "$tag" "$rem"
387 shift
388 web_env="$1"
389 argsConsumed=$((argsConsumed + 1))
390 shift
391 ;;
392 -step )
393 argsConsumed=$((argsConsumed + 1))
394 CheckForArgumentValue "$tag" "$rem"
395 shift
396 stp="$1"
397 argsConsumed=$((argsConsumed + 1))
398 shift
399 ;;
400 -label )
401 argsConsumed=$((argsConsumed + 1))
402 CheckForArgumentValue "$tag" "$rem"
403 shift
404 stp="$1"
405 argsConsumed=$((argsConsumed + 1))
406 shift
407 ;;
408 -email )
409 argsConsumed=$((argsConsumed + 1))
410 CheckForArgumentValue "$tag" "$rem"
411 shift
412 emailr="$1"
413 argsConsumed=$((argsConsumed + 1))
414 shift
415 ;;
416 -tool )
417 argsConsumed=$((argsConsumed + 1))
418 CheckForArgumentValue "$tag" "$rem"
419 shift
420 toolr="$1"
421 argsConsumed=$((argsConsumed + 1))
422 shift
423 ;;
424 -quick )
425 argsConsumed=$((argsConsumed + 1))
426 shift
427 if [ $# -gt 0 ]
428 then
429 if [ "$1" = "true" ]
430 then
431 argsConsumed=$((argsConsumed + 1))
432 shift
433 quick=true
434 elif [ "$1" = "false" ]
435 then
436 argsConsumed=$((argsConsumed + 1))
437 shift
438 quick=false
439 else
440 quick=true
441 fi
442 else
443 quick=true
444 fi
445 ;;
446 -debug )
447 argsConsumed=$((argsConsumed + 1))
448 shift
449 if [ $# -gt 0 ]
450 then
451 if [ "$1" = "true" ]
452 then
453 argsConsumed=$((argsConsumed + 1))
454 shift
455 debug=true
456 elif [ "$1" = "false" ]
457 then
458 argsConsumed=$((argsConsumed + 1))
459 shift
460 debug=false
461 else
462 debug=true
463 fi
464 else
465 debug=true
466 fi
467 ;;
468 -verbose )
469 argsConsumed=$((argsConsumed + 1))
470 shift
471 if [ $# -gt 0 ]
472 then
473 if [ "$1" = "true" ]
474 then
475 argsConsumed=$((argsConsumed + 1))
476 shift
477 verbose=true
478 elif [ "$1" = "false" ]
479 then
480 argsConsumed=$((argsConsumed + 1))
481 shift
482 verbose=false
483 else
484 verbose=true
485 fi
486 else
487 verbose=true
488 fi
489 ;;
490 -tranquil )
491 tranquil=true
492 argsConsumed=$((argsConsumed + 1))
493 shift
494 ;;
495 -clear )
496 quick=false
497 quickx=false
498 debug=false
499 debugx=false
500 verbose=false
501 tranquil=false
502 argsConsumed=$((argsConsumed + 1))
503 shift
504 ;;
505 -log )
506 argsConsumed=$((argsConsumed + 1))
507 shift
508 if [ $# -gt 0 ]
509 then
510 if [ "$1" = "true" ]
511 then
512 argsConsumed=$((argsConsumed + 1))
513 shift
514 log=true
515 elif [ "$1" = "false" ]
516 then
517 argsConsumed=$((argsConsumed + 1))
518 shift
519 log=false
520 else
521 log=true
522 fi
523 else
524 log=true
525 fi
526 ;;
527 -timer )
528 argsConsumed=$((argsConsumed + 1))
529 shift
530 if [ $# -gt 0 ]
531 then
532 if [ "$1" = "true" ] || [ "$1" = "on" ]
533 then
534 argsConsumed=$((argsConsumed + 1))
535 shift
536 timer=true
537 elif [ "$1" = "false" ] || [ "$1" = "off" ]
538 then
539 argsConsumed=$((argsConsumed + 1))
540 shift
541 timer=false
542 else
543 timer=true
544 fi
545 else
546 timer=true
547 fi
548 ;;
549 -version )
550 echo "$version"
551 exit 0
552 ;;
553 -newmode | -oldmode )
554 argsConsumed=$((argsConsumed + 1))
555 shift
556 ;;
557 * )
558 # allows while loop to check for multiple flags
559 break
560 ;;
561 esac
562 done
563 }
564
565 FinishSetup() {
566
567 # adjust base URL address
568
569 case "${EXTERNAL_EDIRECT}" in
570 "" | [FfNn]* | 0 | [Oo][Ff][Ff] )
571 ;;
572 * )
573 external=true
574 ;;
575 esac
576
577 if [ "$external" = true ]
578 then
579 internal=false
580 fi
581
582 if [ -n "$basx" ]
583 then
584 base="$basx"
585 elif [ "$dev" = true ]
586 then
587 base="https://dev.ncbi.nlm.nih.gov/entrez/eutils/"
588 elif [ "$internal" = true ]
589 then
590 base="https://eutils-internal.ncbi.nlm.nih.gov/entrez/eutils/"
591 fi
592
593 # read API Key from environment variable
594
595 if [ -n "${NCBI_API_KEY}" ]
596 then
597 api_key="${NCBI_API_KEY}"
598 fi
599
600 # determine contact email address
601
602 os=$( uname -s | sed -e 's/_NT-.*$/_NT/; s/^MINGW[0-9]*/CYGWIN/' )
603
604 if [ -n "${EMAIL}" ]
605 then
606 email="${EMAIL}"
607 else
608 # Failing that, try to combine the username from USER or whoami
609 # with the contents of /etc/mailname if available or the system's
610 # qualified host name. (Its containing domain may be a better
611 # choice in many cases, but anyone contacting abusers can extract
612 # it if necessary.)
613 lhs=""
614 rhs=""
615 if [ -n "${USER}" ]
616 then
617 lhs="${USER}"
618 else
619 lhs=$( id -un )
620 fi
621 if [ -s "/etc/mailname" ]
622 then
623 rhs=$( cat /etc/mailname )
624 else
625 rhs=$( hostname -f 2>/dev/null || uname -n )
626 case "$rhs" in
627 *.* ) # already qualified
628 ;;
629 * )
630 output=$( host "$rhs" 2>/dev/null )
631 case "$output" in
632 *.*' has address '* )
633 rhs=${output% has address *}
634 ;;
635 esac
636 ;;
637 esac
638 fi
639 if [ -n "$lhs" ] && [ -n "$rhs" ]
640 then
641 # convert any spaces in user name to underscores
642 lhs=$( echo "$lhs" | sed -e 's/ /_/g' )
643 email="${lhs}@${rhs}"
644 fi
645 fi
646
647 # -email argument overrides calculated email, and Email XML field, if read later
648
649 AdjustEmailAndTool
650
651 # temporarily remove email name starting with "root@", which crashes server
652 if [ -n "$email" ]
653 then
654 case "$email" in
655 "root@"* )
656 email=""
657 ;;
658 * )
659 ;;
660 esac
661 fi
662 }
663
664 # prints query command with double quotes around multi-word arguments
665
666 PrintQuery() {
667
668 if printf "%q" >/dev/null 2>&1
669 then
670 fmt="%q"
671 else
672 fmt="%s"
673 fi
674 dlm=""
675 for elm in "$@"
676 do
677 raw="$elm"
678 num=$( printf "%s" "$elm" | wc -w | tr -cd 0-9 )
679 [ "$fmt" = "%s" ] || elm=$( printf "$fmt" "$elm" )
680 case "$elm:$num:$fmt" in
681 *[!\\][\'\"]:*:%q )
682 ;;
683 *:1:* )
684 elm=$( printf "%s" "$raw" | LC_ALL=C sed -e 's/\([]!-*<>?[\\]\)/\\\1/g' )
685 ;;
686 *:%q )
687 elm="\"$( printf "%s" "$elm" | sed -e 's/\\\([^\\"`$]\)/\1/g' )\""
688 ;;
689 * )
690 elm="\"$( printf "%s" "$raw" | sed -e 's/\([\\"`$]\)/\\\1/g' )\""
691 ;;
692 esac
693 printf "$dlm%s" "$elm"
694 dlm=" "
695 done >&2
696 printf "\n" >&2
697 }
698
699 # three attempts for EUtils requests
700
701 ErrorHead() {
702
703 wrn="$1"
704 whn="$2"
705
706 printf "${INVT} ${wrn}: ${LOUD} FAILURE ( $whn )${INIT}\n" >&2
707 # display original command in blue letters
708 printf "${BLUE}" >&2
709 }
710
711 ErrorTail() {
712
713 msg="$1"
714 whc="$2"
715
716 printf "${INIT}" >&2
717 # display reformatted result in red letters
718 lin=$( echo "${msg}" | wc -l)
719 if [ -n "$lin" ] && [ "$lin" -gt 25 ]
720 then
721 hd=$( echo "${msg}" | head -n 10 )
722 tl=$( echo "${msg}" | tail -n 10 )
723 printf "${RED}${hd}${INIT}\n" >&2
724 printf "${RED}...${INIT}\n" >&2
725 printf "${RED}${tl}${INIT}\n" >&2
726 else
727 printf "${RED}${msg}${INIT}\n" >&2
728 fi
729 if [ "$goOn" = true ] && [ "$retryAllowed" = true ]
730 then
731 printf "${BLUE}${whc} ATTEMPT" >&2
732 else
733 printf "${BLUE}QUERY FAILURE" >&2
734 fi
735 printf "${INIT}\n" >&2
736 }
737
738 RequestWithRetry() {
739
740 tries=3
741 goOn=true
742 when=$( date )
743
744 # execute query
745 res=$( "$@" )
746
747 warn="WARNING"
748 whch="SECOND"
749 while [ "$goOn" = true ]
750 do
751 tries=$(( tries - 1 ))
752 if [ "$tries" -lt 1 ]
753 then
754 goOn=false
755 warn="ERROR"
756 fi
757 case "$res" in
758 "" )
759 # empty result
760 if [ "$showErrors" = true ]
761 then
762 ErrorHead "$warn" "$when"
763 PrintQuery "$@"
764 ErrorTail "EMPTY RESULT" "$whch"
765 fi
766 sleep 1
767 when=$( date )
768 if [ "$retryAllowed" = true ]
769 then
770 # retry query
771 res=$( "$@" )
772 fi
773 ;;
774 *\<eFetchResult\>* | *\<eSummaryResult\>* | *\<eSearchResult\>* | *\<eLinkResult\>* | *\<ePostResult\>* | *\<eInfoResult\>* )
775 case "$res" in
776 *\<ERROR\>* )
777 ref=$( echo "$res" | transmute -format indent -doctype "" )
778 if [ "$showErrors" = true ]
779 then
780 ErrorHead "$warn" "$when"
781 PrintQuery "$@"
782 if [ "$goOn" = true ]
783 then
784 # asterisk prints entire selected XML subregion
785 ref=$( echo "$res" | xtract -pattern ERROR -element "*" )
786 fi
787 ErrorTail "$ref" "$whch"
788 fi
789 sleep 1
790 when=$( date )
791 if [ "$retryAllowed" = true ]
792 then
793 # retry query
794 res=$( "$@" )
795 fi
796 ;;
797 *\<error\>* )
798 ref=$( echo "$res" | transmute -format indent -doctype "" )
799 if [ "$showErrors" = true ]
800 then
801 ErrorHead "$warn" "$when"
802 PrintQuery "$@"
803 if [ "$goOn" = true ]
804 then
805 # asterisk prints entire selected XML subregion
806 ref=$( echo "$res" | xtract -pattern error -element "*" )
807 fi
808 ErrorTail "$ref" "$whch"
809 fi
810 sleep 1
811 when=$( date )
812 if [ "$retryAllowed" = true ]
813 then
814 # retry query
815 res=$( "$@" )
816 fi
817 ;;
818 *\<ErrorList\>* )
819 ref=$( echo "$res" | transmute -format indent -doctype "" )
820 # question mark prints names of heterogeneous child objects
821 errs=$( echo "$res" | xtract -pattern "ErrorList/*" -element "?" | sort -f | uniq -i )
822 if [ -n "$errs" ] && [ "$errs" = "PhraseNotFound" ]
823 then
824 goOn=false
825 else
826 if [ "$showErrors" = true ]
827 then
828 ErrorHead "$warn" "$when"
829 PrintQuery "$@"
830 if [ "$goOn" = true ]
831 then
832 # reconstruct indented ErrorList XML
833 ref=$( echo "$res" | xtract -head "<ErrorList>" -tail "<ErrorList>" \
834 -pattern "ErrorList/*" -pfx " " -element "*" )
835 fi
836 ErrorTail "$ref" "$whch"
837 fi
838 sleep 1
839 when=$( date )
840 if [ "$retryAllowed" = true ]
841 then
842 # retry query
843 res=$( "$@" )
844 fi
845 fi
846 ;;
847 *\"error\":* )
848 ref=$( echo "$res" | transmute -format indent -doctype "" )
849 if [ "$showErrors" = true ]
850 then
851 ErrorHead "$warn" "$when"
852 PrintQuery "$@"
853 ErrorTail "$ref" "$whch"
854 fi
855 sleep 1
856 when=$( date )
857 if [ "$retryAllowed" = true ]
858 then
859 # retry query
860 res=$( "$@" )
861 fi
862 ;;
863 *"<DocumentSummarySet status=\"OK\"><!--"* )
864 # 'DocSum Backend failed' message embedded in comment
865 if [ "$showErrors" = true ]
866 then
867 ErrorHead "$warn" "$when"
868 PrintQuery "$@"
869 ErrorTail "$res" "$whch"
870 fi
871 sleep 1
872 when=$( date )
873 if [ "$retryAllowed" = true ]
874 then
875 # retry query
876 res=$( "$@" )
877 fi
878 ;;
879 *\<WarningList\>* )
880 case "$res" in
881 *"<OutputMessage>No items found"* )
882 if [ "$tranquil" = true ]
883 then
884 # -tranquil flag conditionally ignores no items found message
885 goOn=false
886 else
887 ref=$( echo "$res" | transmute -format indent -doctype "" )
888 # errs=$( echo "$res" | xtract -pattern "WarningList/*" -element "?" )
889 if [ "$showErrors" = true ]
890 then
891 ErrorHead "$warn" "$when"
892 PrintQuery "$@"
893 if [ "$goOn" = true ]
894 then
895 # reconstruct indented ErrorList XML
896 ref=$( echo "$res" | xtract -head "<WarningList>" -tail "<WarningList>" \
897 -pattern "WarningList/*" -pfx " " -element "*" )
898 fi
899 ErrorTail "$ref" "$whch"
900 fi
901 sleep 1
902 when=$( date )
903 if [ "$retryAllowed" = true ]
904 then
905 # retry query
906 res=$( "$@" )
907 fi
908 fi
909 ;;
910 *"<OutputMessage>Wildcard search for"*"used only the first 600 variations"* )
911 if [ "$tranquil" = true ]
912 then
913 # -tranquil flag conditionally ignores wildcard search root too short message
914 goOn=false
915 else
916 goOn=false
917 if [ "$showErrors" = true ]
918 then
919 ErrorHead "$warn" "$when"
920 errs=$( echo "$res" | xtract -pattern "WarningList/*" -element OutputMessage )
921 ErrorTail "$errs" "$whch"
922 fi
923 sleep 1
924 fi
925 ;;
926 * )
927 ref=$( echo "$res" | transmute -format indent -doctype "" )
928 # errs=$( echo "$res" | xtract -pattern "WarningList/*" -element "?" )
929 if [ "$showErrors" = true ]
930 then
931 ErrorHead "$warn" "$when"
932 PrintQuery "$@"
933 if [ "$goOn" = true ]
934 then
935 # reconstruct indented ErrorList XML
936 ref=$( echo "$res" | xtract -head "<WarningList>" -tail "<WarningList>" \
937 -pattern "WarningList/*" -pfx " " -element "*" )
938 fi
939 ErrorTail "$ref" "$whch"
940 fi
941 sleep 1
942 when=$( date )
943 if [ "$retryAllowed" = true ]
944 then
945 # retry query
946 res=$( "$@" )
947 fi
948 ;;
949 esac
950 ;;
951 * )
952 # success - no error message detected
953 goOn=false
954 ;;
955 esac
956 ;;
957 *"<DocumentSummarySet status=\"OK\"><!--"* )
958 # docsum with comment not surrounded by wrapper
959 if [ "$showErrors" = true ]
960 then
961 ErrorHead "$warn" "$when"
962 PrintQuery "$@"
963 ErrorTail "$res" "$whch"
964 fi
965 sleep 1
966 when=$( date )
967 if [ "$retryAllowed" = true ]
968 then
969 # retry query
970 res=$( "$@" )
971 fi
972 ;;
973 * )
974 # success for non-structured or non-EUtils-XML result
975 goOn=false
976 ;;
977 esac
978 whch="LAST"
979 if [ "$retryAllowed" = false ]
980 then
981 goOn=false
982 fi
983 done
984
985 # use printf percent-s instead of echo to prevent unwanted evaluation of backslash
986 printf "%s\n" "$res" | sed -e '${/^$/d;}'
987 }
988
989 # optionally prints command, then executes it with retry on failure
990
991 RunWithLogging() {
992
993 if [ "$debug" = true ]
994 then
995 PrintQuery "$@"
996 fi
997
998 RequestWithRetry "$@"
999 }
1000
1001 # ensure date constraint argument consistency
1002
1003 FixDateConstraints() {
1004
1005 if [ -z "$datetype" ]
1006 then
1007 datetype="PDAT"
1008 fi
1009
1010 if [ -z "$reldate" ] || [ "$reldate" -lt 1 ]
1011 then
1012 reldate=""
1013 fi
1014
1015 # set default value for missing date range endpoint
1016 if [ -n "$mindate" ] && [ -z "$maxdate" ]
1017 then
1018 currentDate=$(date +%Y)
1019 maxdate="$currentDate"
1020 fi
1021 if [ -z "$mindate" ] && [ -n "$maxdate" ]
1022 then
1023 mindate="1900"
1024 fi
1025
1026 if [ -z "$mindate" ] || [ -z "$maxdate" ]
1027 then
1028 mindate=""
1029 maxdate=""
1030 fi
1031
1032 if [ -z "$reldate" ] && [ -z "$mindate" ] && [ -z "$maxdate" ]
1033 then
1034 datetype=""
1035 fi
1036 }
1037
1038 # helpers for constructing argument arrays
1039
1040 AddIfNotEmpty() {
1041
1042 if [ -n "$2" ]
1043 then
1044 ky=$1
1045 vl=$2
1046 shift 2
1047 "$@" "$ky" "$vl"
1048 else
1049 shift 2
1050 "$@"
1051 fi
1052 }
1053
1054 FlagIfNotEmpty() {
1055
1056 if [ -n "$2" ] && [ "$2" = true ]
1057 then
1058 ky=$1
1059 shift 2
1060 "$@" "$ky"
1061 else
1062 shift 2
1063 "$@"
1064 fi
1065 }
1066
1067 # helper function adds common tracking arguments
1068
1069 RunWithCommonArgs() {
1070
1071 AddIfNotEmpty -api_key "$api_key" \
1072 AddIfNotEmpty -tool "$tool" \
1073 AddIfNotEmpty -edirect "$version" \
1074 AddIfNotEmpty -edirect_os "$os" \
1075 AddIfNotEmpty -email "$email" \
1076 RunWithLogging "$@"
1077 }
1078
1079 # break Entrez history server requests into chunks
1080
1081 GenerateHistoryChunks() {
1082
1083 chnk="$1"
1084 minn="$2"
1085 maxx="$3"
1086
1087 if [ "$minn" -gt 0 ]
1088 then
1089 minn=$(( minn - 1 ))
1090 fi
1091 if [ "$maxx" -eq 0 ]
1092 then
1093 maxx="$num"
1094 fi
1095
1096 fr="$minn"
1097
1098 while [ "$fr" -lt "$maxx" ]
1099 do
1100 to=$(( fr + chnk ))
1101 if [ "$to" -gt "$maxx" ]
1102 then
1103 chnk=$(( maxx - fr ))
1104 fi
1105 echo "$fr" "$chnk"
1106 fr=$(( fr + chnk ))
1107 done
1108 }
1109
1110 # passes all possible data source arguments to ecollect
1111
1112 CallEcollect() {
1113
1114 # execute query
1115 res=$( "$@" )
1116
1117 # use printf percent-s instead of echo to prevent unwanted evaluation of backslash
1118 printf "%s\n" "$res" | sed -e '${/^$/d;}'
1119 }
1120
1121 GetFromEcollect() {
1122
1123 # ecollect -base "$base" -db "$dbase" -web "$web_env" -key "$qry_key" \
1124 # -query "$qury" -id "$ids" -rest "$rest" -input "$input" -num "$num"
1125
1126 set ecollect
1127
1128 AddIfNotEmpty -base "$base" \
1129 AddIfNotEmpty -db "$dbase" \
1130 AddIfNotEmpty -web "$web_env" \
1131 AddIfNotEmpty -key "$qry_key" \
1132 AddIfNotEmpty -query "$qury" \
1133 AddIfNotEmpty -reldate "$reldate" \
1134 AddIfNotEmpty -mindate "$mindate" \
1135 AddIfNotEmpty -maxdate "$maxdate" \
1136 AddIfNotEmpty -datetype "$datetype" \
1137 AddIfNotEmpty -id "$ids" \
1138 AddIfNotEmpty -rest "$rest" \
1139 AddIfNotEmpty -input "$input" \
1140 AddIfNotEmpty -num "$num" \
1141 CallEcollect "$@"
1142 }
1143
1144 GetUIDs() {
1145
1146 if [ -n "$web_env" ] && [ -n "$qry_key" ]
1147 then
1148 GetFromEcollect
1149 elif [ -n "$qury" ] && [ "$dbase" = "pubmed" ]
1150 then
1151 GetFromEcollect
1152 elif [ -n "$ids" ]
1153 then
1154 # LookupSpecialAccessions instantiates converted accessions into $ids variable,
1155 # so -id argument, if populated, must be used before $rest and $input
1156 echo "$ids" |
1157 # faster version of accn-at-a-time without case transformation
1158 tr -cs a-zA-Z0-9_. '\n'
1159
1160 elif [ -n "$rest" ]
1161 then
1162 # raw UIDs or instantiated UIDs extracted from ENTREZ_DIRECT message
1163 echo "$rest" |
1164 tr -cs a-zA-Z0-9_. '\n'
1165
1166 elif [ -n "$input" ]
1167 then
1168 # input file of raw UIDs
1169 cat "$input" |
1170 tr -cs a-zA-Z0-9_. '\n'
1171
1172 else
1173 DisplayError "Missing argument describing data source"
1174 exit 1
1175 fi |
1176
1177 # sort and unique final UID results
1178 sort -n | uniq
1179 }
1180
1181 # special case accession to UID lookup functions
1182
1183 ExtractPMCIds() {
1184
1185 if [ "$needHistory" = false ]
1186 then
1187 GetUIDs |
1188 while read uid
1189 do
1190 case "$uid" in
1191 PMC* )
1192 echo "$uid" | sed -e 's/^PMC//g'
1193 ;;
1194 pmc* )
1195 echo "$uid" | sed -e 's/^pmc//g'
1196 ;;
1197 * )
1198 echo "$uid"
1199 ;;
1200 esac
1201 done
1202 fi
1203 }
1204
1205 ExtractNucUids() {
1206
1207 # argument value: 1 = PACC, 2 = ACCN, 3 = integer and accession
1208 kind="$1"
1209
1210 while read uid
1211 do
1212 case "$uid" in
1213 *00000000 )
1214 notInteger=$( echo "$uid" | sed -e 's/[0-9.]//g' )
1215 if [ -n "$notInteger" ]
1216 then
1217 if [ "$kind" -eq 1 ]
1218 then
1219 echo "$uid"
1220 fi
1221 else
1222 if [ "$kind" -eq 3 ]
1223 then
1224 echo "$uid"
1225 fi
1226 fi
1227 ;;
1228 *0000000 )
1229 notInteger=$( echo "$uid" | sed -e 's/[0-9.]//g' )
1230 if [ -n "$notInteger" ]
1231 then
1232 if [ "$kind" -eq 2 ]
1233 then
1234 echo "$uid"
1235 fi
1236 else
1237 if [ "$kind" -eq 3 ]
1238 then
1239 echo "$uid"
1240 fi
1241 fi
1242 ;;
1243 * )
1244 if [ "$kind" -eq 3 ]
1245 then
1246 echo "$uid"
1247 fi
1248 ;;
1249 esac
1250 done
1251 }
1252
1253 ExtractPDB() {
1254
1255 if [ "$needHistory" = false ]
1256 then
1257 GetUIDs |
1258 while read uid
1259 do
1260 case "$uid" in
1261 [0-9][0-9][0-9][0-9] )
1262 # Four-digit UID
1263 # peel off first to avoid mistaking for a chainless PDB ID
1264 ;;
1265 [0-9][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z] | \
1266 [0-9][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z]_[A-Za-z]* )
1267 # PDB ID
1268 # properly case-sensitive only when untagged
1269 echo "$uid"
1270 ;;
1271 esac
1272 done
1273 fi
1274 }
1275
1276 ExtractNonPDB() {
1277
1278 if [ "$needHistory" = false ]
1279 then
1280 GetUIDs |
1281 while read uid
1282 do
1283 case "$uid" in
1284 [0-9][0-9][0-9][0-9] )
1285 # Four-digit UID
1286 # peel off first to avoid mistaking for a chainless PDB ID
1287 echo "$uid"
1288 ;;
1289 [0-9][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z] | \
1290 [0-9][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z]_[A-Za-z]* )
1291 # PDB ID, skip
1292 ;;
1293 *[A-Za-z]* )
1294 # accessions are already handled
1295 echo "$uid"
1296 ;;
1297 * )
1298 echo "$uid"
1299 ;;
1300 esac
1301 done
1302 fi
1303 }
1304
1305 PrepareAccnQuery() {
1306
1307 while read uid
1308 do
1309 echo "$uid+[$1]"
1310 done |
1311 join-into-groups-of "$2" |
1312 sed -e 's/,/ OR /g' |
1313 tr '+' ' '
1314 }
1315
1316 RunAccnSearch() {
1317
1318 while read qry
1319 do
1320 nquire -url "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi" \
1321 -db "$dbase" -term "$qry" -retmax "$1" < /dev/null |
1322 xtract -pattern eSearchResult -sep "\n" -element IdList/Id
1323 done
1324 }
1325
1326 PreparePDBQuery() {
1327
1328 while read uid
1329 do
1330 echo "$uid"
1331 done |
1332 join-into-groups-of 10000 |
1333 sed -e 's/,/ OR /g'
1334 }
1335
1336 PrepareSnpQuery() {
1337
1338 while read uid
1339 do
1340 case "$uid" in
1341 rs* )
1342 echo "$uid+[RS]"
1343 ;;
1344 ss* )
1345 echo "$uid+[SS]"
1346 ;;
1347 esac
1348 done |
1349 join-into-groups-of 10000 |
1350 sed -e 's/,/ OR /g' |
1351 tr '+' ' '
1352 }
1353
1354 LookupSpecialAccessions() {
1355
1356 if [ "$needHistory" = false ]
1357 then
1358 fld=""
1359 case "$dbase" in
1360 assembly | annotinfo )
1361 fld="ASAC"
1362 ;;
1363 biosample | biosystems | cdd | dbvar | ipg | medgen | proteinclusters | seqannot | sra )
1364 fld="ACCN"
1365 ;;
1366 bioproject | genome )
1367 fld="PRJA"
1368 ;;
1369 books )
1370 fld="AID"
1371 ;;
1372 clinvar )
1373 fld="VACC"
1374 ;;
1375 gds )
1376 fld="ALL"
1377 ;;
1378 geoprofiles )
1379 fld="NAME"
1380 ;;
1381 gtr )
1382 fld="GTRACC"
1383 ;;
1384 mesh )
1385 fld="MHUI"
1386 ;;
1387 pcsubstance )
1388 fld="SRID"
1389 ;;
1390 pmc* )
1391 ids=$( ExtractPMCIds | fmt -w 1 | sort -n | uniq )
1392 ;;
1393 nuc* )
1394 nucUidList=$( GetUIDs )
1395 anyNonInteger=$( echo "$nucUidList" | sed -e 's/[0-9.]//g' )
1396 if [ -n "$anyNonInteger" ]
1397 then
1398 pacc=$( echo "$nucUidList" | ExtractNucUids "1" )
1399 accn=$( echo "$nucUidList" | ExtractNucUids "2" )
1400 lcl=$( echo "$nucUidList" | ExtractNucUids "3" )
1401 pacres=""
1402 accres=""
1403 if [ -n "$pacc" ]
1404 then
1405 pacres=$( echo "$pacc" |
1406 PrepareAccnQuery "PACC" "100" |
1407 RunAccnSearch "1000" )
1408 fi
1409 if [ -n "$accn" ]
1410 then
1411 accres=$( echo "$accn" |
1412 PrepareAccnQuery "ACCN" "100" |
1413 RunAccnSearch "1000" )
1414 fi
1415 if [ -n "$pacres" ] || [ -n "$accres" ]
1416 then
1417 ids=$( echo "$pacres $accres $lcl" | fmt -w 1 | sort -n | uniq )
1418 fi
1419 else
1420 ids="$nucUidList"
1421 fi
1422 ;;
1423 protein )
1424 acc=$( ExtractPDB )
1425 lcl=$( ExtractNonPDB )
1426 if [ -n "$acc" ]
1427 then
1428 query=$( echo "$acc" | PreparePDBQuery "$fld" )
1429 rem=$( esearch -db "$dbase" -query "$query" | efetch -format uid )
1430 ids=$( echo "$rem $lcl" | fmt -w 1 | sort -n | uniq )
1431 fi
1432 ;;
1433 snp )
1434 snpUidList=$( GetUIDs )
1435 anyNonInteger=$( echo "$snpUidList" | sed -e 's/[0-9.]//g' )
1436 if [ -n "$anyNonInteger" ]
1437 then
1438 acc=$( echo "$snpUidList" | grep -v '^[0-9]*$' )
1439 lcl=$( echo "$snpUidList" | grep '^[0-9]*$' )
1440 if [ -n "$acc" ]
1441 then
1442 query=$( echo "$acc" | PrepareSnpQuery "$fld" )
1443 rem=$( esearch -db "$dbase" -query "$query" | efetch -format uid )
1444 ids=$( echo "$rem $lcl" | fmt -w 1 | sort -n | uniq )
1445 else
1446 ids=$( echo "$lcl" | fmt -w 1 | sort -n | uniq )
1447 fi
1448 else
1449 ids=$( echo "$snpUidList" | fmt -w 1 | sort -n | uniq )
1450 fi
1451 ;;
1452 taxonomy )
1453 taxUidList=$( GetUIDs )
1454 anyNonInteger=$( echo "$taxUidList" | sed -e 's/[0-9.]//g' )
1455 if [ -n "$anyNonInteger" ]
1456 then
1457 DisplayError "Taxonomy database does not index sequence accession numbers"
1458 exit 1
1459 else
1460 ids=$( echo "$taxUidList" | fmt -w 1 | sort -n | uniq )
1461 fi
1462 ;;
1463 esac
1464 if [ -n "$fld" ]
1465 then
1466 otherUidList=$( GetUIDs )
1467 anyNonInteger=$( echo "$otherUidList" | sed -e 's/[0-9.]//g' )
1468 if [ -n "$anyNonInteger" ]
1469 then
1470 acc=$( echo "$otherUidList" | grep -v '^[0-9]*$' )
1471 lcl=$( echo "$otherUidList" | grep '^[0-9]*$' )
1472 if [ -n "$acc" ]
1473 then
1474 newids=$( echo "$acc" |
1475 PrepareAccnQuery "$fld" "1000" |
1476 RunAccnSearch "10000" )
1477 if [ -n "$newids" ]
1478 then
1479 ids=$( echo "$newids $lcl" | fmt -w 1 | sort -n | uniq )
1480 else
1481 ids=$( echo "$lcl" | fmt -w 1 | sort -n | uniq )
1482 fi
1483 else
1484 ids=$( echo "$lcl" | fmt -w 1 | sort -n | uniq )
1485 fi
1486 else
1487 ids=$( echo "$otherUidList" | fmt -w 1 | sort -n | uniq )
1488 fi
1489 fi
1490 fi
1491 }
1492
1493 # write minimal ENTREZ_DIRECT message for intermediate processing
1494
1495 WriteEDirectStep() {
1496
1497 dbsx="$1"
1498 webx="$2"
1499 keyx="$3"
1500 errx="$4"
1501
1502 echo "<ENTREZ_DIRECT>"
1503
1504 if [ -n "$dbsx" ]
1505 then
1506 echo " <Db>${dbsx}</Db>"
1507 fi
1508 if [ -n "$webx" ]
1509 then
1510 echo " <WebEnv>${webx}</WebEnv>"
1511 fi
1512 if [ -n "$keyx" ]
1513 then
1514 echo " <QueryKey>${keyx}</QueryKey>"
1515 fi
1516 if [ -n "$errx" ]
1517 then
1518 echo " <Error>${errx}</Error>"
1519 fi
1520
1521 echo "</ENTREZ_DIRECT>"
1522 }
1523
1524 # write ENTREZ_DIRECT data structure
1525
1526 WriteEDirect() {
1527
1528 dbsx="$1"
1529 webx="$2"
1530 keyx="$3"
1531 numx="$4"
1532 stpx="$5"
1533 errx="$6"
1534
1535 seconds_end=$(date "+%s")
1536 seconds_elapsed=$((seconds_end - seconds_start))
1537
1538 echo "<ENTREZ_DIRECT>"
1539
1540 if [ -n "$dbsx" ]
1541 then
1542 echo " <Db>${dbsx}</Db>"
1543 fi
1544 if [ -n "$webx" ]
1545 then
1546 echo " <WebEnv>${webx}</WebEnv>"
1547 fi
1548 if [ -n "$keyx" ]
1549 then
1550 echo " <QueryKey>${keyx}</QueryKey>"
1551 fi
1552 if [ -n "$numx" ]
1553 then
1554 echo " <Count>${numx}</Count>"
1555 fi
1556
1557 if [ -n "$stpx" ]
1558 then
1559 # increment step value
1560 stpx=$(( stpx + 1 ))
1561 echo " <Step>${stpx}</Step>"
1562 fi
1563 if [ -n "$errx" ]
1564 then
1565 echo " <Error>${errx}</Error>"
1566 fi
1567 if [ -n "$toolx" ]
1568 then
1569 echo " <Tool>${toolx}</Tool>"
1570 fi
1571 if [ -n "$emailx" ]
1572 then
1573 echo " <Email>${emailx}</Email>"
1574 fi
1575
1576 if [ -n "$label" ] && [ -n "$keyx" ]
1577 then
1578 labels="<Label><Key>${label}</Key><Val>${keyx}</Val></Label>${labels}"
1579 fi
1580 if [ -n "$labels" ]
1581 then
1582 echo " <Labels>"
1583 echo "$labels" |
1584 # xtract -pattern Label -element "*"
1585 xtract -pattern Label -tab "\n" \
1586 -fwd " <Label>\n" -awd "\n </Label>" \
1587 -pfx " <Key>" -sfx "</Key>" -element Key \
1588 -pfx " <Val>" -sfx "</Val>" -element Val
1589 echo " </Labels>"
1590 fi
1591
1592 if [ "$quick" = true ] || [ "$quickx" = "Y" ]
1593 then
1594 echo " <Quick>Y</Quick>"
1595 fi
1596 if [ "$debug" = true ] || [ "$debugx" = "Y" ]
1597 then
1598 echo " <Debug>Y</Debug>"
1599 fi
1600 if [ "$log" = true ] || [ "$logx" = "Y" ]
1601 then
1602 echo " <Log>Y</Log>"
1603 fi
1604
1605 if [ "$timer" = true ] && [ -n "$seconds_elapsed" ]
1606 then
1607 echo " <Elapsed>${seconds_elapsed}</Elapsed>"
1608 fi
1609
1610 echo "</ENTREZ_DIRECT>"
1611 }
1612
1613 # check for new EDirect version on ftp site
1614
1615 NewerEntrezDirectVersion () {
1616
1617 newer=$(
1618 nquire -lst ftp://ftp.ncbi.nlm.nih.gov/entrez/entrezdirect/versions |
1619 cut -d '.' -f 1,2 | sort -t '.' -k 1,1n -k 2,2n | tail -n 1
1620 )
1621
1622 newerWhole=$( echo "$newer" | cut -d '.' -f 1 )
1623 newerFract=$( echo "$newer" | cut -d '.' -f 2 )
1624
1625 currentWhole=$( echo "$version" | cut -d '.' -f 1 )
1626 currentFract=$( echo "$version" | cut -d '.' -f 2 )
1627
1628 if [ "$newerWhole" -gt "$currentWhole" ]
1629 then
1630 echo "$newer"
1631 elif [ "$newerWhole" -eq "$currentWhole" ] && [ "$newerFract" -gt "$currentFract" ]
1632 then
1633 echo "$newer"
1634 else
1635 echo ""
1636 fi
1637 }