Skills › Compound Engineering › ce-test-browser › resolve-port.sh
resolve-port.sh
41 lines · skills/ce-test-browser/scripts/resolve-port.sh at 3449230
1#!/usr/bin/env bash
2# Resolve the dev-server port for ce-test-browser and print it alone on stdout, so a
3# caller can capture it with $(...) instead of transcribing it out of prose.
4#
5# Usage: resolve-port.sh [--free] [EXPLICIT_PORT]
6# --free after resolving, scan upward to the first port with no listener
7# EXPLICIT_PORT a port the caller already knows (the user's --port, or an in-context
8# project instruction that states the dev-server port)
9#
10# Resolution order: EXPLICIT_PORT, a --port flag in package.json, PORT= in .env /
11# .env.local / .env.development, then 3000.
12set -u
14free=0
15explicit=""
16for arg in "$@"; do
17 case "$arg" in
18 --free) free=1 ;;
19 "") ;;
20 *[!0-9]*) ;;
21 *) explicit="$arg" ;;
22 esac
23done
25port="$explicit"
26if [ -z "$port" ]; then
27 port=$(grep -Eo -- '--port[= ]+[0-9]{2,5}' package.json 2>/dev/null | grep -Eo '[0-9]{2,5}' | head -1)
28fi
29if [ -z "$port" ]; then
30 # take the first digit run after PORT=, so quotes and a trailing "# comment" drop out
31 port=$(grep -h '^PORT=' .env .env.local .env.development 2>/dev/null | tail -1 | grep -Eo '[0-9]+' | head -1)
32fi
33port="${port:-3000}"
35if [ "$free" = 1 ]; then
36 while lsof -i ":$port" -sTCP:LISTEN -t >/dev/null 2>&1; do
37 port=$((port + 1))
38 done
39fi
41echo "$port"