When a preview port belongs to the wrong Git worktree
A development server can answer on the port you expect while its process runs from a different Git checkout. I ran into this after opening a linked worktree. The page loaded, but it was not the checkout I meant to inspect. I built worktree-port-check to compare the checkout in my terminal with the current directory of every visible process listening on one TCP port. What the command checks The…
A development server may resolve to the correct port, even when its process runs from a separate Git checkout. The author experienced this issue after opening a linked worktree. Upon opening a worktree, the page loaded, but it was not the intended checkout. To address this problem, the author created a tool called worktree-port-check.
This tool compares the current working directory (cwd) of each visible process listening on a specific TCP port with the checkout root and common directory of Git. To use the tool, one needs Node.js 20 or newer, Git, and lsof on macOS or Linux. After executing the command with the desired port, the tool analyzes the listeners, Git roots, and common directories.
If the root matches, it indicates the listener's cwd belongs to the same checkout. If the root is different but shares the same common directory, it suggests another linked worktree within the same repository. A different common directory signifies a separate repository altogether. Additionally, the tool displays branch names for reference, but they do not influence the comparison.
The author runs Git commands without inherited GIT_* environment variables and disables index locks. To employ the tool, run npx --yes --package = github:Arthur031221/worktree-port-check worktree-port-check 3000. Using the --json flag provides structured output. An exit code of 1 signifies a listener belonging to a different checkout, while an exit code of 4 indicates insufficient information to generate a complete result.
It is essential to note that a process's cwd does not guarantee the files it loaded earlier or the code it serves. A process may change directories after startup, and OS permissions can obscure a listener or its cwd. The tool reports these limitations instead of attempting to communicate with the application or terminate the process.
The author seeks feedback regarding macOS process lookup, permission cases, and whether the report provides adequate context to identify the correct server. The full source code and tests can be found at https://github.com/Arthur031221/worktree-port-check.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.