Source

css / bin / OK

Full commit
#!/bin/sh
#
# Run command.
# Report OK or FAIL on stdout.
# If --count-regexp specified, count and strip matching lines and report
#   {OK|FAIL} <count> words...
# - Cameron Simpson <cs@zip.com.au> 24nov2010
#

set -ue

: ${TMPDIR:=/tmp}
: ${USER:=`id -un`}
: ${NOTIFY:=${MAILTO:-${EMAIL:-$USER}}}
: ${OK:=OK:}
: ${FAIL:=FAIL:}

dopfx=
pfx=
trace=${DEBUG:+set-x}
count_re=
words=
wordsep=
notifyaddr=${NOTIFY:-}
quiet=

cmd=`basename "$0"`
usage="Usage: $cmd [options...] [--] command [args...]
  --count-regexp regexp
        Regexp for output lines to count, report and discard.
  -:    Suppress colon in OK/FAIL prefix.
  --ok okpfx
        Use \"okpfx\" instead of $OK.
  --fail failpfx
        Use \"failpfx\" instead of $FAIL.
  --label label
        Recite \"label\" after OK/FAIL. Defaults to command.
  -N, --notify-on-error notifyaddr
        Email error output to notifyaddr on failure; uses mail-on-error.
        Default from \$NOTIFY or \$MAILTO: $NOTIFY
  -P    Prefix output with the label.
  --prefix pfx
        Prefix output with \"pfx\".
  -q    Quiet. Only report failures."

badopts=

while [ $# -gt 0 ]
do
  case $1 in
    --count-regexp)
      count_re=$2; shift
      ;;
    -:)
      OK=OK
      FAIL=FAIL
      ;;
    -N|--notify-on-error)
      notifyaddr=$2; shift ;;
    -P)
      dopfx=1 ;;
    -q)
      quiet=1 ;;
    --prefix)
      dopfx=1 pfx=$2; shift ;;
    --ok)
      OK=$2; shift ;;
    --fail)
      FAIL=$2; shift ;;
    --label)
      words="$words$wordsep$2"; wordsep=' '; shift ;;
    --)
      shift; break ;;
    -?*)
      echo "$cmd: unrecognised option: $1" >&2
      badopts=1
      ;;
    *)break
      ;;
  esac
  shift
done

if [ $# = 0 ]
then
  echo "$cmd: missing command" >&2
  badopts=1
fi

[ $badopts ] && { echo "$usage" >&2; exit 2; }

[ -n "$words" ] || words=$*

if [ -n "$count_re" ]
then
  matchlog=$TMPDIR/$cmd$$matches
  sedprog="\|$count_re|{ w $matchlog
          d;}"
  sedcmd=`shqstr sed "$sedprog"`
  set -- filter_fd 1 "$sedcmd" "$@"
fi

if [ -n "$notifyaddr" ]
then
  set -- mail-on-error -s "$FAIL $words" -- "$notifyaddr" "$@"
fi

if [ $dopfx ]
then
  [ -n "$pfx" ] || pfx=$words
  set -- pfx "$pfx" "$@"
fi

[ -t 2 ] && necho "$words
" >&2
xit=0
$trace "$@" || xit=$?

if [ -n "$count_re" ]
then
  set -- `wc -l <"$matchlog"`
  words="$1$wordsep$words"
  rm -f "$matchlog"
fi

if [ $xit = 0 ]
then
  [ $quiet ] || echo "$OK $words"
else
  echo "$FAIL $words"
fi

exit $xit