| #!/bin/bash |
| |
| set -eufo pipefail |
| |
| # Kill background processes on script exit. |
| trap '[[ -n "$(jobs -p)" ]] && kill $(jobs -p) &> /dev/null' EXIT |
| |
| usage() { |
| cat <<EOS |
| Usage: $0 [-hbd] |
| |
| This script watches code in frontend/ and backend/ for changes, automatically |
| rebuilding and (for backend changes) restarting the server. |
| |
| Options: |
| |
| -h Display this help message. |
| -b Backend-only (do not watch frontend/). |
| -d Run the server with DEPLOYMENT=1 (see 'make help' for details). |
| EOS |
| } |
| |
| die() { |
| echo "$0: $*" >&2 |
| exit 1 |
| } |
| |
| # Prefix output with "$1: " using bold ANSI color $2. |
| prefix() { |
| sed "s/^/\x1b[$2;1m$1:\x1b[0m /" |
| } |
| |
| prefix_watch() { |
| prefix "WATCH" 32 # green |
| } |
| |
| prefix_npm() { |
| prefix "NPM" 33 # yellow |
| } |
| |
| prefix_server() { |
| prefix "SERVER" 34 # blue |
| } |
| |
| watch_frontend=true |
| deployment=0 |
| |
| while getopts "hbd" opt; do |
| case $opt in |
| h) usage; exit 0 ;; |
| b) watch_frontend=false ;; |
| d) deployment=1 ;; |
| *) exit 1 ;; |
| esac |
| done |
| shift $((OPTIND - 1)) |
| if [[ $# -gt 0 ]]; then |
| die "unexpected arguments: $*" |
| fi |
| |
| if ! command -v inotifywait &> /dev/null; then |
| die "inotifywait not found" |
| fi |
| |
| cd "$(dirname "$0")" |
| |
| if [[ "$watch_frontend" == true ]]; then |
| # Unless NO_COLOR is set, pass FORCE_COLOR to npm (which would otherwise |
| # disable color because its output is piped). |
| color=1 |
| [[ -n "${NO_COLOR+x}" ]] && color=0 |
| FORCE_COLOR=$color npm run --prefix frontend watch 2>&1 | prefix_npm & |
| fi |
| |
| rebuild() { |
| # Kill the "make run" process whose parent is this script. |
| pkill -x make -P $$ 2>&1 | prefix_watch || : |
| if make backend 2>&1 | prefix_watch; then |
| make run DEPLOYMENT=$deployment 2>&1 | prefix_server & |
| fi |
| } |
| |
| rebuild |
| while read -r _ _ event_filename; do |
| echo "$event_filename changed" | prefix_watch |
| rebuild |
| done < <(inotifywait -m -e close_write backend 2> >(prefix_watch > /dev/tty)) |