From de4d6f327a0e852e0eaafffd460ea63e05c1fe9f Mon Sep 17 00:00:00 2001 From: bowenliang123 Date: Sat, 29 Aug 2026 00:46:32 +0800 Subject: [PATCH] build: kill previous watch instance when starting pnpm watch Track the tsdown watcher pid in .tmp/watch.pid; a new watch kills the previous instance first and the pid file is cleaned up on exit. --- package.json | 2 +- scripts/watch.sh | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100755 scripts/watch.sh diff --git a/package.json b/package.json index f9ef120..321e327 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,7 @@ "build": "tsdown", "lint": "oxlint", "lint:fix": "oxlint --fix", - "watch": "tsdown --watch", + "watch": "bash scripts/watch.sh", "register": "bash scripts/register.sh", "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.tests.json", "test": "pnpm run typecheck && vitest run --coverage", diff --git a/scripts/watch.sh b/scripts/watch.sh new file mode 100755 index 0000000..b771edc --- /dev/null +++ b/scripts/watch.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Starts tsdown --watch, killing the previous watch instance (pid tracked in .tmp/watch.pid) first. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +PID_FILE="$ROOT/.tmp/watch.pid" +mkdir -p "$ROOT/.tmp" + +if [[ -f "$PID_FILE" ]]; then + old_pid="$(cat "$PID_FILE" 2>/dev/null || true)" + if [[ "$old_pid" =~ ^[0-9]+$ ]] && kill -0 "$old_pid" 2>/dev/null; then + echo "killing previous watch (pid $old_pid)" + kill "$old_pid" 2>/dev/null || true + for _ in {1..50}; do + kill -0 "$old_pid" 2>/dev/null || break + sleep 0.1 + done + fi + rm -f "$PID_FILE" +fi + +tsdown --watch & +child=$! +echo "$child" > "$PID_FILE" + +cleanup() { + kill "$child" 2>/dev/null || true + if [[ "$(cat "$PID_FILE" 2>/dev/null)" == "$child" ]]; then + rm -f "$PID_FILE" + fi +} +trap cleanup EXIT INT TERM + +wait "$child"