#!/bin/zsh
setopt extendedglob

autoload -Uz colors; colors

typeset -ga test_args
typeset -g run evt fname
# typeset -gT PYTHONPATH pythonpath
# pythonpath=( $0:h ~/.local/bzr/*/python(/N) /usr/local/bzr/*/python(/N) $pythonpath )
# export PYTHONPATH

test_args=( "$@" )

do_test() {
	shelltest *.test -c "$test_args[@]"
	# time py.test "$test_args"
}

trigger_check() {
	local ret show
	ret=0; show=1
	case $fname in
		(*.py[co])      ret=1;;
		(*.sw[px])      ret=1; show=0;;
		(*.swpx)        ret=1;;
		(*.tmp)        ret=1;;
		(*'~')          ret=1;;
		(*__pycache__*) ret=1;;
		(*/bin/[0-9]*) ret=1;;
		(*/.hypothesis*) ret=1; show=0;;
		(*/tests/*) ret=1; show=0;;
		(*/test_error.sql) ret=1;;
		(*/commlog/*)   ret=1; show=0;;
		(*/.bzr/*)      ret=1; show=0;;
	esac
	[[ $fname =~ '.*/[0-9]+$' ]] && ret=1
	if (($ret)); then
		(($show)) && print -r - "$fname  $evt"
	else
		print -r "$fg[green]$fname  $evt$reset_color"
	fi
	return $ret
}

coproc inotifywait -m -q -e create,move,close_write --format '%e %w%f' -r \
	--exclude='\.bzr/' --exclude='/commlog/' \
	.

while read -prt 0.5 evt fname; do
	print -r "$fg[blue]$fname  $evt$reset_color"
done
do_test
while read -pr evt fname; do
	trigger_check || continue
	while read -prt 0.5 evt fname; do
		print -r "$fg[blue]$fname  $evt$reset_color"
	done
	do_test
done

#while inotifywait -q --exclude='.*sw[p-z]' --exclude='.*commlog.*' -e create,move,close_write **/*~commlog*~*__pycache__(/) **/*.py || (($? == 2)); do