swaydots

my dotfiles
git clone https://git.awy.one/swaydots.git
Log | Files | Refs | README | LICENSE

getbib (1907B)


      1 #!/bin/sh
      2 
      3 BIB_FILE="${HOME}/latex/uni.bib"
      4 [ -f "${BIB_FILE}" ] || BIB_FILE="${2:-$(find "${HOME}" -path "${HOME}/.*" \
      5 	-prune -o -type "f" -name "*.bib" -print -quit)}"
      6 
      7 { [ -f "${BIB_FILE}" ] || [ "${2}" ]; } || {
      8 	printf "%s\n" "Create a .bib file or provide as \$2." && exit "1"
      9 }
     10 
     11 filter() {
     12 	sed -n -E 's/.*((DOI|doi)((\.(org))?\/?|:? *))([^: ]+[^ .]).*/\6/p; T; q'
     13 }
     14 
     15 fpdf() {
     16         pdf="${1}"
     17 	doi="$(pdfinfo "${pdf}" 2> "/dev/null" | filter)"
     18 
     19 	[ "${doi}" ] || doi="$(pdftotext -q -l "2" "${pdf}" - 2> "/dev/null" | filter)"
     20 
     21 	[ "${doi}" ] || printf "%s\n" "No DOI found for PDF: ${pdf}" >&2
     22 
     23 	printf "%s\n" "${doi}"
     24 }
     25 
     26 arrange() {
     27 	sed 's/\}, /\},\n	/g
     28 		s/, /,\n	/
     29 		s/ }/\n}/
     30 		s/,\s*pages=/,\n\tpages=/' |
     31         sed '1s/^ *//
     32         	1s/[0-9]*\([0-9]\{2\}\)/\1/
     33         	1s/_//
     34         	1s/.*/\L&/
     35 		s/.*=/\L&/
     36 		s/=/ = /'
     37 }
     38 
     39 doi2bib() {
     40         doi="${1#doi:}"
     41 	url="https://api.crossref.org/works/${doi}/transform/application/x-bibtex"
     42         entry="$(curl -kLsS --no-fail "${url}" | arrange)"
     43         red='\033[0;31m'
     44         reset='\033[0m'
     45 
     46         printf "${red}%s${reset}\n" "${entry}"
     47 
     48 	[ "${entry%"${entry#?}"}" != "@" ] && {
     49 		printf "%s\n" "Failed to fetch bibtex entry for DOI: ${doi}"
     50 		return "1"
     51 	}
     52 
     53 	grep -iFq "doi = {${doi}}" "${BIB_FILE}" 2> "/dev/null" && {
     54 		printf "%s\n" "Bibtex entry for DOI: ${doi} already exists in the file."
     55 	} || {
     56 		[ -s "${BIB_FILE}" ] && printf "\n" >> "${BIB_FILE}"
     57 		printf "%s\n" "${entry}" >> "${BIB_FILE}"
     58 		printf "%s\n" "Added bibtex entry for DOI: ${doi}"
     59         }
     60 }
     61 
     62 [ "${1}" ] || {
     63 	printf "%s\n" "Give either a pdf file or a DOI or a directory path that has PDFs as an argument."
     64 	exit "1"
     65 }
     66 
     67 [ -f "${1}" ] && doi="$(fpdf "${1}")" && doi2bib "${doi}" && exit "0"
     68 
     69 [ -d "${1}" ] && for i in "${1}"/*.pdf; do doi="$(fpdf "${i}")" && doi2bib "${doi}"; done && exit "0"
     70 
     71 doi="$(printf "%s\n" "${1}" | filter)" && doi2bib "${doi}"