aboutsummaryrefslogtreecommitdiffstats
path: root/bib-convert
blob: ef4c0b037f27ca93e84146a495f1f51cc864ef84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/bin/sh
# bib-convert - convert between bibtex and refer database formats
#
# usage: bib-convert [-b | -r] [file]   (stdin if no file given)
#   -b  force refer -> bibtex
#   -r  force bibtex -> refer
#
# Without a flag the direction is detected from the input: text whose
# first record starts with @ is taken as bibtex, with % as refer.

usage() {
  printf 'usage: bib-convert [-b | -r] [file]\n' >&2
  exit 2
}

if [ -n "$BIBUTILS_LIB" ]; then
  LIB=$BIBUTILS_LIB
elif [ -d "$(dirname "$0")/lib" ]; then
  LIB=$(dirname "$0")/lib
else
  LIB=/usr/local/share/bibutils
fi

bibkey=$(dirname "$0")/bib-key
[ -x "$bibkey" ] || bibkey=bib-key

mode=auto
while getopts br opt; do
  case $opt in
    b) mode=tobib ;;
    r) mode=toref ;;
    *) usage ;;
  esac
done
shift $((OPTIND - 1))
[ $# -le 1 ] || usage

tmp=$(mktemp) || exit 1
trap 'rm -f "$tmp"' EXIT INT TERM
cat "$@" > "$tmp"

if [ "$mode" = auto ]; then
  first=$(awk 'NF { sub(/^[ \t]+/, ""); print substr($0, 1, 1); exit }' "$tmp")
  case $first in
    @) mode=toref ;;
    %) mode=tobib ;;
    *) printf 'bib-convert: cannot detect input format\n' >&2; exit 1 ;;
  esac
fi

if [ "$mode" = toref ]; then
  exec awk -f "$LIB/bib-parse.awk" -f "$LIB/bib-canon.awk" \
           -f "$LIB/bib2ref.awk" "$tmp"
else
  awk -f "$LIB/ref2bib.awk" "$tmp" | "$bibkey"
fi