phpstan-watch 1.63 KiB
#!/usr/bin/env bash
set -e

if [[ $1 = "-h" ]]; then
    echo "Usage: $0 [source] !" >&2
    exit 1
fi

if ! INOTIFYWAIT="$(which inotifywait)"; then
    echo "inotifywait introuvable !" >&2
    if [[ -x /usr/lib/command-not-found ]]; then
        /usr/lib/command-not-found inotifywait
    fi
    exit 1
fi

findProjectRoot() {
    local DIR="$1"
    if [[ $DIR = / ]]; then
        echo "phpstan.neon introuvable !" >&2
        return 1
    fi

    if [[ -e $DIR/phpstan.neon ]]; then
        echo $DIR
        return 0
    fi
    findProjectRoot "$(dirname $DIR)"
}

HERE="$(findProjectRoot $(readlink -f $PWD))"

if [[ -x $HERE/vendor/bin/phpstan ]]; then
    PHPSTAN="$HERE/vendor/bin/phpstan"
else
    if [[ -x $HERE/bin/phpstan ]]; then
        PHPSTAN="$HERE/bin/phpstan"
    else
        if ! PHPSTAN=$(which phpstan); then
            echo "phpstan introuvable !" >&2
            exit 1
        fi
    fi
fi

TARGET="${1:-$HERE/src}"
if [[ ! -e "$TARGET" ]]; then
    echo "$TARGET n'existe pas !" >&2
    exit 1
fi

DIR="$(mktemp -d)"
FIFO="$DIR/fifo"
mkfifo "$FIFO"

$INOTIFYWAIT --monitor --quiet --recursive --event=close_write --format=%w%f --outfile="$FIFO" "$TARGET" &
WATCHER_PID=$!
trap "kill ${WATCHER_PID} >/dev/null 2>&1; rm -rf $DIR" EXIT

work() {
    clear
    echo "== Level $1 =="
    echo "> $PHPSTAN analyse -n --ansi --level=$1 $2"
    $PHPSTAN analyse -n --ansi --level="$1" "$2"
    return $?
}

for LEVEL in $(seq 1 7); do

    while ! work "$LEVEL" "$TARGET"; do
        while read FNAME; do
            if work "$LEVEL" "$FNAME"; then
                break
            fi
        done < "$FIFO"
    done

done

kill ${WATCHER_PID}

wait