DEV Community

Arthur031221
Arthur031221

Posted on

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.

Terminal demo of worktree-port-check finding a listener in another Git worktree

What the command checks

The command asks lsof for TCP listeners on the selected port. It reads the cwd for each visible process, then asks Git for the checkout root and common directory at that path. It repeats the listener query and reports if the process and file descriptor set changes while it runs.

A matching root means the listener cwd resolves to the same checkout. A different root with the same Git common directory means another linked worktree in the same repository. A different common directory means another repository. A cwd outside Git gets a separate result.

Branch names appear in the report for context. They do not decide the comparison. Git commands run without inherited GIT_* environment variables, with optional index locks disabled.

Try it

The project needs Node.js 20 or newer, Git, and lsof on macOS or Linux.

npx --yes --package=github:Arthur031221/worktree-port-check worktree-port-check 3000
Enter fullscreen mode Exit fullscreen mode

Use --json for structured output. Exit code 1 means a visible listener belongs to another checkout. Exit code 4 means the inspection did not have enough information to reach a complete result.

What it cannot tell you

The process cwd is not proof of what files a server loaded earlier or what code it serves. A process may change directories after startup, and OS permissions can hide a listener or its cwd. The tool reports those limits instead of sending a request to the application or stopping a process.

I would appreciate feedback on macOS process lookup, permission cases, and whether the report gives enough context to find the right server.

Source and tests: https://github.com/Arthur031221/worktree-port-check

Top comments (0)