port-reclaim 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -9
- package/dist/src/args.d.ts +2 -0
- package/dist/src/args.js +22 -3
- package/dist/src/cli.js +99 -31
- package/dist/src/index.d.ts +4 -2
- package/dist/src/index.js +2 -1
- package/dist/src/process.d.ts +23 -2
- package/dist/src/process.js +208 -65
- package/dist/src/style.d.ts +5 -0
- package/dist/src/style.js +26 -0
- package/dist/tests/args.test.js +16 -11
- package/dist/tests/cli.test.js +180 -3
- package/dist/tests/process.test.js +70 -4
- package/dist/tests/style.test.d.ts +1 -0
- package/dist/tests/style.test.js +30 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -34,17 +34,18 @@ Requires Node.js 18 or newer. Supports macOS, Linux, Windows, WSL, PowerShell, a
|
|
|
34
34
|
|
|
35
35
|
```sh
|
|
36
36
|
port-reclaim <PORT> [PORT ...]
|
|
37
|
+
port-reclaim --match <REGEX>
|
|
37
38
|
```
|
|
38
39
|
|
|
39
|
-
If the port is free, the command exits successfully. If the process working directory matches the current project, the process is terminated automatically. Processes from another directory, system services, and processes whose working directory cannot be read require explicit confirmation. Confirmation prompts show the process name, working directory, and uptime.
|
|
40
|
+
If the port is free, the command verifies it by briefly binding the port, then exits successfully. If the port is in use but no owning process is visible to the current user, the command reports that instead of claiming success. If the process working directory matches the current project, the process is terminated automatically — except for known data services (`postgres`, `postmaster`, `mysqld`, `mariadbd`, `mongod`, `redis-server`, `memcached`, `etcd`), which always ask first even when they share your directory. Processes from another directory, system services, and processes whose working directory cannot be read require explicit confirmation. Confirmation prompts show the process name, working directory, and uptime.
|
|
40
41
|
|
|
41
42
|
The command uses a graceful termination signal first on Unix-like systems and falls back to a forceful signal if the process remains alive. Windows uses `taskkill /F`.
|
|
42
43
|
|
|
43
|
-
If confirmation is required in a non-interactive environment, the command declines safely and exits with status `1` (rerun with `--yes` to override).
|
|
44
|
+
If confirmation is required in a non-interactive environment, the command declines safely and exits with status `1` (rerun with `--yes` to override). `--yes` skips prompts, including the protected-service prompt, but it cannot override a refusal — list a service's port in `.reclaimignore` to make it un-killable by accident.
|
|
44
45
|
|
|
45
|
-
Ports held by Docker processes (for example `docker-proxy` or Docker Desktop) are never killed. The tool explains that the port looks like Docker and suggests stopping the container instead.
|
|
46
|
+
Ports held by Docker processes (for example `docker-proxy` or Docker Desktop) are never killed. The tool explains that the port looks like Docker and suggests stopping the container instead. The same refusal applies to operating-system PIDs (0–4, such as `System`/HTTP.sys on Windows or `systemd` on Linux), which are never signalled.
|
|
46
47
|
|
|
47
|
-
Both TCP and UDP listeners are discovered.
|
|
48
|
+
Both TCP and UDP listeners are discovered. Discovery costs one `netstat`/`lsof` call per port, with process names and uptimes fetched in a single batched query. Measured on Windows 11: ~0.1s for a free port, ~0.4s to identify a busy one, ~0.6s for a full reclaim.
|
|
48
49
|
|
|
49
50
|
### Options
|
|
50
51
|
|
|
@@ -52,9 +53,26 @@ Both TCP and UDP listeners are discovered.
|
|
|
52
53
|
| --- | --- |
|
|
53
54
|
| `-l`, `--list` | Report what is using each port without killing anything. |
|
|
54
55
|
| `-y`, `--yes` | Terminate processes from other directories without prompting. |
|
|
56
|
+
| `-m`, `--match REGEX` | Reclaim every port held by a process whose name matches REGEX, instead of naming ports. |
|
|
57
|
+
| `--no-color` | Disable coloured output. |
|
|
55
58
|
| `-h`, `--help` | Show the help message. |
|
|
56
59
|
| `-v`, `--version` | Show the installed version. |
|
|
57
60
|
|
|
61
|
+
### Reclaiming by process name
|
|
62
|
+
|
|
63
|
+
When you do not know which ports are involved, select by command name instead. `--match` scans every listening socket, keeps the processes whose name matches the regular expression (case-insensitive), and reclaims every port each one holds:
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
port-reclaim --match 'next-server|vite' --list
|
|
67
|
+
port-reclaim --match '^node$' --yes
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The same safety rules apply: refusals still block Docker and operating-system PIDs, data services still prompt, and a process holding any protected port is skipped entirely. `--match` cannot be combined with port arguments, and an invalid expression exits with status `2`.
|
|
71
|
+
|
|
72
|
+
### Colour
|
|
73
|
+
|
|
74
|
+
Successes are green, refusals and errors red, prompts yellow, and process details dim. Colour switches itself off when output is redirected, and can be forced off with `--no-color` or the `NO_COLOR` environment variable.
|
|
75
|
+
|
|
58
76
|
## Configuration
|
|
59
77
|
|
|
60
78
|
Ports can be declared once so scripts can run plain `port-reclaim` with no arguments. Add a `port-reclaim` key to `package.json`:
|
|
@@ -105,8 +123,8 @@ The same command can be used from Python, Ruby, Go, Make, or shell scripts.
|
|
|
105
123
|
|
|
106
124
|
| Code | Meaning |
|
|
107
125
|
| --- | --- |
|
|
108
|
-
| `0` | The port was free, listed with `--list`, or successfully released. |
|
|
109
|
-
| `1` | The port is still in use
|
|
126
|
+
| `0` | The port was free (verified by binding), listed with `--list`, or successfully released. |
|
|
127
|
+
| `1` | The port is still in use: the user declined, the owner is not visible to the current user, a protected process refused the kill, or an operation failed. |
|
|
110
128
|
| `2` | Invalid command-line input. |
|
|
111
129
|
|
|
112
130
|
## Programmatic Use
|
|
@@ -119,16 +137,21 @@ import { createProcessRunner } from "port-reclaim";
|
|
|
119
137
|
const runner = createProcessRunner();
|
|
120
138
|
const found = await runner.discover(3000);
|
|
121
139
|
for (const process of found) {
|
|
122
|
-
console.log(process.name, process.cwd, process.ageMs);
|
|
140
|
+
console.log(process.name, process.cwd, process.ageMs, process.refusal);
|
|
123
141
|
}
|
|
124
|
-
if (found.length > 0) {
|
|
142
|
+
if (found.length > 0 && !found[0].refusal) {
|
|
125
143
|
await runner.terminate(found[0].pid);
|
|
126
144
|
}
|
|
145
|
+
if (found.length === 0 && (await runner.probe(3000)) === "occupied") {
|
|
146
|
+
console.log("in use by a process this user cannot see");
|
|
147
|
+
}
|
|
127
148
|
```
|
|
128
149
|
|
|
150
|
+
`discover()` reports what is on a port, `terminate()` ends one PID, `probe()` answers whether the port is bindable at all — `"free"`, `"occupied"`, or `"unknown"` when the OS refuses to say — and `discoverListening(regex)` works the other way, returning every listening process whose name matches along with all the ports it holds. A `refusal` reason on a discovered process means `port-reclaim` will not kill it, whatever the caller asks; `terminate()` is still available if you decide otherwise. `alwaysConfirm` marks a process the CLI will not auto-kill just because it shares your directory.
|
|
151
|
+
|
|
129
152
|
## Security Notes
|
|
130
153
|
|
|
131
|
-
`port-reclaim` only acts on processes listening on the port you provide. It does not scan remote hosts, and it refuses to kill Docker processes — stop those containers yourself. Ports protected by `.reclaimignore` or the `ignore` config are always skipped. Review the process name and working directory before confirming a process from another project. UDP matches are heuristic: a UDP socket on a port can belong to a client as well as a server.
|
|
154
|
+
`port-reclaim` only acts on processes listening on the port you provide. It does not scan remote hosts, and it refuses to kill Docker processes and operating-system PIDs (0–4) — stop those containers and services yourself. Known data services are never auto-killed even when their working directory matches yours, but `--yes` does override that prompt, so protect the ports that matter with `.reclaimignore`. Ports protected by `.reclaimignore` or the `ignore` config are always skipped. Review the process name and working directory before confirming a process from another project. UDP matches are heuristic: a UDP socket on a port can belong to a client as well as a server. To confirm a port is free, the tool binds it momentarily and releases it, so a connection arriving in that instant can be reported as in use.
|
|
132
155
|
|
|
133
156
|
## Development
|
|
134
157
|
|
package/dist/src/args.d.ts
CHANGED
package/dist/src/args.js
CHANGED
|
@@ -2,6 +2,8 @@ const HELP_FLAGS = new Set(["--help", "-h"]);
|
|
|
2
2
|
const VERSION_FLAGS = new Set(["--version", "-v"]);
|
|
3
3
|
const YES_FLAGS = new Set(["--yes", "-y", "--force", "-f"]);
|
|
4
4
|
const LIST_FLAGS = new Set(["--list", "-l"]);
|
|
5
|
+
const NO_COLOR_FLAGS = new Set(["--no-color"]);
|
|
6
|
+
const MATCH_FLAGS = new Set(["--match", "-m"]);
|
|
5
7
|
function parsePort(value) {
|
|
6
8
|
if (!/^\d+$/.test(value))
|
|
7
9
|
return undefined;
|
|
@@ -9,9 +11,23 @@ function parsePort(value) {
|
|
|
9
11
|
return port >= 1 && port <= 65535 ? port : undefined;
|
|
10
12
|
}
|
|
11
13
|
export function parseArgs(argv) {
|
|
12
|
-
const options = { ports: [], help: false, version: false, yes: false, list: false };
|
|
13
|
-
for (
|
|
14
|
-
|
|
14
|
+
const options = { ports: [], help: false, version: false, yes: false, list: false, noColor: false };
|
|
15
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
16
|
+
const arg = argv[index];
|
|
17
|
+
if (MATCH_FLAGS.has(arg)) {
|
|
18
|
+
const value = argv[index + 1];
|
|
19
|
+
if (value === undefined || value.startsWith("-") || options.match !== undefined)
|
|
20
|
+
return undefined;
|
|
21
|
+
options.match = value;
|
|
22
|
+
index += 1;
|
|
23
|
+
}
|
|
24
|
+
else if (arg.startsWith("--match=")) {
|
|
25
|
+
const value = arg.slice("--match=".length);
|
|
26
|
+
if (!value || options.match !== undefined)
|
|
27
|
+
return undefined;
|
|
28
|
+
options.match = value;
|
|
29
|
+
}
|
|
30
|
+
else if (HELP_FLAGS.has(arg)) {
|
|
15
31
|
options.help = true;
|
|
16
32
|
}
|
|
17
33
|
else if (VERSION_FLAGS.has(arg)) {
|
|
@@ -23,6 +39,9 @@ export function parseArgs(argv) {
|
|
|
23
39
|
else if (LIST_FLAGS.has(arg)) {
|
|
24
40
|
options.list = true;
|
|
25
41
|
}
|
|
42
|
+
else if (NO_COLOR_FLAGS.has(arg)) {
|
|
43
|
+
options.noColor = true;
|
|
44
|
+
}
|
|
26
45
|
else {
|
|
27
46
|
const port = parsePort(arg);
|
|
28
47
|
if (port === undefined)
|
package/dist/src/cli.js
CHANGED
|
@@ -7,15 +7,18 @@ import { pathToFileURL } from "node:url";
|
|
|
7
7
|
import { createProcessRunner } from "./process.js";
|
|
8
8
|
import { parseArgs } from "./args.js";
|
|
9
9
|
import { loadConfig } from "./config.js";
|
|
10
|
-
|
|
10
|
+
import { paint, setColourMode } from "./style.js";
|
|
11
|
+
const USAGE = `Usage: port-reclaim [options] [PORT ...]
|
|
11
12
|
|
|
12
13
|
Safely reclaim local ports held by stale development processes.
|
|
13
14
|
|
|
14
15
|
Options:
|
|
15
|
-
-l, --list
|
|
16
|
-
-y, --yes
|
|
17
|
-
-
|
|
18
|
-
|
|
16
|
+
-l, --list Report what is using each port without killing anything.
|
|
17
|
+
-y, --yes Terminate processes without prompting (never overrides a refusal).
|
|
18
|
+
-m, --match REGEX Reclaim every port held by a process whose name matches REGEX.
|
|
19
|
+
--no-color Disable coloured output.
|
|
20
|
+
-h, --help Show this help message.
|
|
21
|
+
-v, --version Show the installed version.
|
|
19
22
|
|
|
20
23
|
Ports may also come from the "port-reclaim" key in package.json:
|
|
21
24
|
"port-reclaim": { "ports": [3000, 5173], "ignore": [5432] }
|
|
@@ -43,6 +46,13 @@ function formatAge(ageMs) {
|
|
|
43
46
|
return `${minutes}m ${totalSeconds % 60}s`;
|
|
44
47
|
return `${totalSeconds}s`;
|
|
45
48
|
}
|
|
49
|
+
function heading(ports) {
|
|
50
|
+
return ports.length > 1 ? `Ports ${ports.join(", ")}` : `Port ${ports[0]}`;
|
|
51
|
+
}
|
|
52
|
+
function lowercaseHeading(ports) {
|
|
53
|
+
const text = heading(ports);
|
|
54
|
+
return text.charAt(0).toLowerCase() + text.slice(1);
|
|
55
|
+
}
|
|
46
56
|
function describe(portProcess) {
|
|
47
57
|
const details = [`PID ${portProcess.pid}`];
|
|
48
58
|
if (portProcess.cwd)
|
|
@@ -51,18 +61,37 @@ function describe(portProcess) {
|
|
|
51
61
|
details.push(`up ${formatAge(portProcess.ageMs)}`);
|
|
52
62
|
if (portProcess.protocol === "udp")
|
|
53
63
|
details.push("udp");
|
|
54
|
-
return `'${portProcess.name}' (${details.join(", ")})`;
|
|
64
|
+
return `${paint("bold", `'${portProcess.name}'`)} (${paint("dim", details.join(", "))})`;
|
|
55
65
|
}
|
|
56
|
-
async function confirm(portProcess,
|
|
66
|
+
async function confirm(portProcess, ports) {
|
|
57
67
|
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
58
|
-
console.error(
|
|
68
|
+
console.error(`${paint("red", `${heading(ports)} is used by ${describe(portProcess)}.`)} ${paint("yellow", "Use an interactive terminal to confirm termination, or rerun with --yes.")}`);
|
|
59
69
|
return false;
|
|
60
70
|
}
|
|
61
71
|
const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
62
|
-
const answer = await prompt.question(
|
|
72
|
+
const answer = await prompt.question(paint("yellow", `${heading(ports)} is used by ${describe(portProcess)}. Kill it? (y/N) `));
|
|
63
73
|
prompt.close();
|
|
64
74
|
return /^y(es)?$/i.test(answer.trim());
|
|
65
75
|
}
|
|
76
|
+
async function resolveProcess(portProcess, runner, options, ports) {
|
|
77
|
+
if (portProcess.refusal) {
|
|
78
|
+
console.error(paint("red", `${heading(ports)} is used by ${describe(portProcess)}. Refusing to kill it — ${portProcess.refusal}`));
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
const sameProject = sameDirectory(portProcess.cwd, process.cwd()) && !portProcess.alwaysConfirm;
|
|
82
|
+
if (!(sameProject || options.yes || await confirm(portProcess, ports)))
|
|
83
|
+
return false;
|
|
84
|
+
await runner.terminate(portProcess.pid);
|
|
85
|
+
console.log(paint("green", `Released ${lowercaseHeading(ports)} from ${portProcess.name} (PID ${portProcess.pid}).`));
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
function reportProcess(portProcess, port) {
|
|
89
|
+
const origin = sameDirectory(portProcess.cwd, process.cwd())
|
|
90
|
+
? "matches the current directory"
|
|
91
|
+
: portProcess.cwd ? `'${portProcess.cwd}'` : "an unreadable working directory";
|
|
92
|
+
const refusal = portProcess.refusal ? ` ${paint("red", "[refused]")}` : "";
|
|
93
|
+
console.log(`Port ${port} is used by ${describe(portProcess)}${refusal} — ${origin}.`);
|
|
94
|
+
}
|
|
66
95
|
async function version() {
|
|
67
96
|
try {
|
|
68
97
|
const pkg = JSON.parse(await readFile(new URL("../../package.json", import.meta.url), "utf8"));
|
|
@@ -72,38 +101,65 @@ async function version() {
|
|
|
72
101
|
return "unknown";
|
|
73
102
|
}
|
|
74
103
|
}
|
|
75
|
-
async function reclaimPort(port, runner, options) {
|
|
76
|
-
const portProcesses = await runner.discover(port);
|
|
104
|
+
async function reclaimPort(port, runner, options, known) {
|
|
105
|
+
const portProcesses = known ?? await runner.discover(port);
|
|
77
106
|
if (portProcesses.length === 0) {
|
|
78
|
-
|
|
79
|
-
|
|
107
|
+
const state = await runner.probe(port);
|
|
108
|
+
if (state === "occupied") {
|
|
109
|
+
console.error(paint("red", `Port ${port} is in use by a process port-reclaim cannot see — it may belong to another user, an elevated process, or a socket still closing.`));
|
|
110
|
+
console.error(`Rerun with sudo or from an elevated PowerShell session, or inspect it with 'netstat -ano | findstr :${port}'.`);
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
if (options.list) {
|
|
114
|
+
console.log(state === "free" ? paint("green", `Port ${port} is free.`) : paint("yellow", `Port ${port} appears free but could not be verified.`));
|
|
115
|
+
}
|
|
80
116
|
return true;
|
|
81
117
|
}
|
|
82
118
|
let free = true;
|
|
83
|
-
const currentDirectory = process.cwd();
|
|
84
119
|
for (const portProcess of portProcesses) {
|
|
85
120
|
if (options.list) {
|
|
86
|
-
|
|
87
|
-
? "matches the current directory"
|
|
88
|
-
: portProcess.cwd ? `'${portProcess.cwd}'` : "an unreadable working directory";
|
|
89
|
-
const docker = portProcess.docker ? " [docker]" : "";
|
|
90
|
-
console.log(`Port ${port} is used by ${describe(portProcess)}${docker} — ${origin}.`);
|
|
121
|
+
reportProcess(portProcess, port);
|
|
91
122
|
continue;
|
|
92
123
|
}
|
|
93
|
-
if (portProcess
|
|
94
|
-
console.error(`Port ${port} is used by ${describe(portProcess)}, which appears to be a Docker process. Refusing to kill it — stop the container instead (for example 'docker stop <container>').`);
|
|
124
|
+
if (!(await resolveProcess(portProcess, runner, options, [port])))
|
|
95
125
|
free = false;
|
|
126
|
+
}
|
|
127
|
+
return free;
|
|
128
|
+
}
|
|
129
|
+
function isValidPattern(pattern) {
|
|
130
|
+
try {
|
|
131
|
+
new RegExp(pattern);
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
async function reclaimMatching(runner, options, pattern, ignored) {
|
|
139
|
+
const found = await runner.discoverListening(new RegExp(pattern, "i"));
|
|
140
|
+
const matches = found.filter((portProcess) => (portProcess.ports?.length ?? 0) > 0);
|
|
141
|
+
if (matches.length === 0) {
|
|
142
|
+
console.log(paint("dim", `No listening process matches '${pattern}'.`));
|
|
143
|
+
return 0;
|
|
144
|
+
}
|
|
145
|
+
const sorted = matches.sort((left, right) => (left.ports?.[0] ?? 0) - (right.ports?.[0] ?? 0));
|
|
146
|
+
let exitCode = 0;
|
|
147
|
+
for (const portProcess of sorted) {
|
|
148
|
+
const ports = portProcess.ports ?? [];
|
|
149
|
+
const protectedPort = ports.find((port) => ignored.has(port));
|
|
150
|
+
if (protectedPort !== undefined) {
|
|
151
|
+
console.log(paint("yellow", `Skipping ${portProcess.name} (PID ${portProcess.pid}) — port ${protectedPort} is protected by .reclaimignore or config.`));
|
|
96
152
|
continue;
|
|
97
153
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
154
|
+
if (options.list) {
|
|
155
|
+
for (const port of ports)
|
|
156
|
+
reportProcess(portProcess, port);
|
|
101
157
|
continue;
|
|
102
158
|
}
|
|
103
|
-
await
|
|
104
|
-
|
|
159
|
+
if (!(await resolveProcess(portProcess, runner, options, ports)))
|
|
160
|
+
exitCode = 1;
|
|
105
161
|
}
|
|
106
|
-
return
|
|
162
|
+
return exitCode;
|
|
107
163
|
}
|
|
108
164
|
export async function main(argv = process.argv.slice(2), runner = createProcessRunner()) {
|
|
109
165
|
const options = parseArgs(argv);
|
|
@@ -111,6 +167,7 @@ export async function main(argv = process.argv.slice(2), runner = createProcessR
|
|
|
111
167
|
printUsage();
|
|
112
168
|
return 2;
|
|
113
169
|
}
|
|
170
|
+
setColourMode(options.noColor ? "never" : "auto");
|
|
114
171
|
if (options.help) {
|
|
115
172
|
console.log(USAGE);
|
|
116
173
|
return 0;
|
|
@@ -121,6 +178,18 @@ export async function main(argv = process.argv.slice(2), runner = createProcessR
|
|
|
121
178
|
}
|
|
122
179
|
const config = await loadConfig(process.cwd());
|
|
123
180
|
const ignored = new Set(config.ignore);
|
|
181
|
+
if (options.match !== undefined) {
|
|
182
|
+
if (!isValidPattern(options.match)) {
|
|
183
|
+
console.error(paint("red", `port-reclaim: '${options.match}' is not a valid regular expression.`));
|
|
184
|
+
return 2;
|
|
185
|
+
}
|
|
186
|
+
if (options.ports.length > 0) {
|
|
187
|
+
console.error(paint("red", "port-reclaim: pass either ports or --match, not both."));
|
|
188
|
+
printUsage();
|
|
189
|
+
return 2;
|
|
190
|
+
}
|
|
191
|
+
return reclaimMatching(runner, options, options.match, ignored);
|
|
192
|
+
}
|
|
124
193
|
const ports = options.ports.length > 0 ? options.ports : config.ports;
|
|
125
194
|
if (ports.length === 0) {
|
|
126
195
|
printUsage();
|
|
@@ -129,18 +198,17 @@ export async function main(argv = process.argv.slice(2), runner = createProcessR
|
|
|
129
198
|
let exitCode = 0;
|
|
130
199
|
for (const port of ports) {
|
|
131
200
|
if (ignored.has(port)) {
|
|
132
|
-
console.log(`Port ${port} is protected by .reclaimignore or config — skipped.`);
|
|
201
|
+
console.log(paint("yellow", `Port ${port} is protected by .reclaimignore or config — skipped.`));
|
|
133
202
|
continue;
|
|
134
203
|
}
|
|
135
|
-
|
|
136
|
-
if (!free)
|
|
204
|
+
if (!(await reclaimPort(port, runner, options)))
|
|
137
205
|
exitCode = 1;
|
|
138
206
|
}
|
|
139
207
|
return exitCode;
|
|
140
208
|
}
|
|
141
209
|
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
142
210
|
main().then((code) => process.exit(code)).catch((error) => {
|
|
143
|
-
console.error(`port-reclaim: ${error.message}`);
|
|
211
|
+
console.error(paint("red", `port-reclaim: ${error.message}`));
|
|
144
212
|
process.exit(1);
|
|
145
213
|
});
|
|
146
214
|
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
export { createProcessRunner, parseEtime, parseNetstatPids, parseUnixLsof,
|
|
2
|
-
export type { NetstatPid, PortProcess, ProcessRunner, Protocol } from "./process.js";
|
|
1
|
+
export { createProcessRunner, parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, isProtectedService, refusalReason, } from "./process.js";
|
|
2
|
+
export type { ListenerRow, NetstatPid, PortProcess, PortState, ProcessRow, ProcessRunner, Protocol, } from "./process.js";
|
|
3
|
+
export { colourEnabled, paint, setColourMode } from "./style.js";
|
|
4
|
+
export type { Colour, ColourMode } from "./style.js";
|
|
3
5
|
export { loadConfig, parsePackageConfig, parseReclaimignore } from "./config.js";
|
|
4
6
|
export type { ReclaimConfig } from "./config.js";
|
|
5
7
|
export { parseArgs } from "./args.js";
|
package/dist/src/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
export { createProcessRunner, parseEtime, parseNetstatPids, parseUnixLsof,
|
|
1
|
+
export { createProcessRunner, parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, isProtectedService, refusalReason, } from "./process.js";
|
|
2
|
+
export { colourEnabled, paint, setColourMode } from "./style.js";
|
|
2
3
|
export { loadConfig, parsePackageConfig, parseReclaimignore } from "./config.js";
|
|
3
4
|
export { parseArgs } from "./args.js";
|
package/dist/src/process.d.ts
CHANGED
|
@@ -1,22 +1,43 @@
|
|
|
1
1
|
export type Protocol = "tcp" | "udp";
|
|
2
|
+
export type PortState = "free" | "occupied" | "unknown";
|
|
2
3
|
export interface PortProcess {
|
|
3
4
|
pid: number;
|
|
4
5
|
name: string;
|
|
5
6
|
cwd?: string;
|
|
6
7
|
protocol?: Protocol;
|
|
7
8
|
ageMs?: number;
|
|
8
|
-
|
|
9
|
+
ports?: number[];
|
|
10
|
+
refusal?: string;
|
|
11
|
+
alwaysConfirm?: boolean;
|
|
9
12
|
}
|
|
10
13
|
export interface ProcessRunner {
|
|
11
14
|
discover(port: number): Promise<PortProcess[]>;
|
|
15
|
+
discoverListening(match: RegExp): Promise<PortProcess[]>;
|
|
12
16
|
terminate(pid: number): Promise<void>;
|
|
17
|
+
probe(port: number): Promise<PortState>;
|
|
13
18
|
}
|
|
14
|
-
export
|
|
19
|
+
export interface ListenerRow {
|
|
20
|
+
pid: number;
|
|
21
|
+
port: number;
|
|
22
|
+
protocol: Protocol;
|
|
23
|
+
}
|
|
24
|
+
export declare function isProtectedService(name: string): boolean;
|
|
25
|
+
export declare function refusalReason(pid: number, name: string): string | undefined;
|
|
15
26
|
export declare function parseUnixLsof(output: string): number[];
|
|
16
27
|
export declare function parseEtime(value: string): number | undefined;
|
|
28
|
+
export declare function parseNetstatListeners(output: string): ListenerRow[];
|
|
29
|
+
export declare function parseUnixLsofListeners(output: string, protocol: Protocol): ListenerRow[];
|
|
17
30
|
export interface NetstatPid {
|
|
18
31
|
pid: number;
|
|
19
32
|
protocol: Protocol;
|
|
20
33
|
}
|
|
21
34
|
export declare function parseNetstatPids(output: string, port: number): NetstatPid[];
|
|
35
|
+
export interface ProcessRow {
|
|
36
|
+
pid: number;
|
|
37
|
+
name: string;
|
|
38
|
+
ageMs?: number;
|
|
39
|
+
protocol?: Protocol;
|
|
40
|
+
}
|
|
41
|
+
export declare function parsePipeTable(output: string): ProcessRow[];
|
|
42
|
+
export declare function parsePsTable(output: string): ProcessRow[];
|
|
22
43
|
export declare function createProcessRunner(): ProcessRunner;
|
package/dist/src/process.js
CHANGED
|
@@ -1,17 +1,26 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { promisify } from "node:util";
|
|
3
3
|
import process from "node:process";
|
|
4
|
+
import net from "node:net";
|
|
5
|
+
import dgram from "node:dgram";
|
|
4
6
|
import pidCwd from "pid-cwd";
|
|
5
7
|
const execFileAsync = promisify(execFile);
|
|
6
8
|
const DOCKER_PROCESS = /docker|vpnkit/i;
|
|
7
|
-
|
|
8
|
-
|
|
9
|
+
const SYSTEM_PID_CEILING = 4;
|
|
10
|
+
// Data services can legitimately run with their working directory inside a project, which is
|
|
11
|
+
// the exact condition the same-directory auto-kill shortcut trusts. They never auto-kill.
|
|
12
|
+
const PROTECTED_SERVICES = new Set(["postgres", "postmaster", "mysqld", "mariadbd", "mongod", "redis-server", "memcached", "etcd"]);
|
|
13
|
+
export function isProtectedService(name) {
|
|
14
|
+
return PROTECTED_SERVICES.has(name.trim().toLowerCase());
|
|
9
15
|
}
|
|
10
|
-
function
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
16
|
+
export function refusalReason(pid, name) {
|
|
17
|
+
if (DOCKER_PROCESS.test(name)) {
|
|
18
|
+
return "it appears to be a Docker process — stop the container instead (for example 'docker stop <container>').";
|
|
19
|
+
}
|
|
20
|
+
if (pid <= SYSTEM_PID_CEILING) {
|
|
21
|
+
return `PID ${pid} and below belong to the operating system itself — stop the service that owns the port instead.`;
|
|
22
|
+
}
|
|
23
|
+
return undefined;
|
|
15
24
|
}
|
|
16
25
|
export function parseUnixLsof(output) {
|
|
17
26
|
return [...new Set([...output.matchAll(/^p(\d+)$/gm)].map((match) => Number(match[1])))];
|
|
@@ -38,6 +47,50 @@ export function parseEtime(value) {
|
|
|
38
47
|
}
|
|
39
48
|
return (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
|
|
40
49
|
}
|
|
50
|
+
export function parseNetstatListeners(output) {
|
|
51
|
+
const rows = [];
|
|
52
|
+
const seen = new Set();
|
|
53
|
+
for (const line of output.split(/\r?\n/)) {
|
|
54
|
+
const columns = line.trim().split(/\s+/);
|
|
55
|
+
const protocol = columns[0]?.toUpperCase();
|
|
56
|
+
if (protocol !== "TCP" && protocol !== "UDP")
|
|
57
|
+
continue;
|
|
58
|
+
if (protocol === "TCP" && columns[3]?.toUpperCase() !== "LISTENING")
|
|
59
|
+
continue;
|
|
60
|
+
const port = Number(columns[1]?.split(":").at(-1));
|
|
61
|
+
const pid = Number(columns.at(-1));
|
|
62
|
+
if (!Number.isInteger(port) || port <= 0 || !Number.isInteger(pid) || pid <= 0)
|
|
63
|
+
continue;
|
|
64
|
+
const key = `${pid}:${port}:${protocol}`;
|
|
65
|
+
if (seen.has(key))
|
|
66
|
+
continue;
|
|
67
|
+
seen.add(key);
|
|
68
|
+
rows.push({ pid, port, protocol: protocol.toLowerCase() });
|
|
69
|
+
}
|
|
70
|
+
return rows;
|
|
71
|
+
}
|
|
72
|
+
export function parseUnixLsofListeners(output, protocol) {
|
|
73
|
+
const rows = [];
|
|
74
|
+
const seen = new Set();
|
|
75
|
+
let pid = 0;
|
|
76
|
+
for (const line of output.split(/\r?\n/)) {
|
|
77
|
+
if (line.startsWith("p")) {
|
|
78
|
+
pid = Number(line.slice(1));
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (!line.startsWith("n") || !Number.isInteger(pid) || pid <= 0)
|
|
82
|
+
continue;
|
|
83
|
+
const port = Number(line.slice(1).split(":").at(-1));
|
|
84
|
+
if (!Number.isInteger(port) || port <= 0)
|
|
85
|
+
continue;
|
|
86
|
+
const key = `${pid}:${port}`;
|
|
87
|
+
if (seen.has(key))
|
|
88
|
+
continue;
|
|
89
|
+
seen.add(key);
|
|
90
|
+
rows.push({ pid, port, protocol });
|
|
91
|
+
}
|
|
92
|
+
return rows;
|
|
93
|
+
}
|
|
41
94
|
export function parseNetstatPids(output, port) {
|
|
42
95
|
const results = [];
|
|
43
96
|
const seen = new Set();
|
|
@@ -58,6 +111,46 @@ export function parseNetstatPids(output, port) {
|
|
|
58
111
|
}
|
|
59
112
|
return results;
|
|
60
113
|
}
|
|
114
|
+
function readProtocol(value) {
|
|
115
|
+
const normalized = value?.trim().toLowerCase();
|
|
116
|
+
if (normalized === "tcp" || normalized === "udp")
|
|
117
|
+
return normalized;
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
function readAge(value) {
|
|
121
|
+
const ageMs = Number(value);
|
|
122
|
+
return Number.isFinite(ageMs) && ageMs > 0 ? ageMs : undefined;
|
|
123
|
+
}
|
|
124
|
+
export function parsePipeTable(output) {
|
|
125
|
+
const rows = [];
|
|
126
|
+
const seen = new Set();
|
|
127
|
+
for (const line of output.split(/\r?\n/)) {
|
|
128
|
+
const columns = line.trim().split("|");
|
|
129
|
+
if (columns.length < 2)
|
|
130
|
+
continue;
|
|
131
|
+
const pid = Number(columns[0]);
|
|
132
|
+
if (!Number.isInteger(pid) || pid <= 0 || seen.has(pid))
|
|
133
|
+
continue;
|
|
134
|
+
seen.add(pid);
|
|
135
|
+
rows.push({ pid, name: columns[1].trim() || "unknown", ageMs: readAge(columns[2]), protocol: readProtocol(columns[3]) });
|
|
136
|
+
}
|
|
137
|
+
return rows;
|
|
138
|
+
}
|
|
139
|
+
export function parsePsTable(output) {
|
|
140
|
+
const rows = [];
|
|
141
|
+
const seen = new Set();
|
|
142
|
+
for (const line of output.split(/\r?\n/)) {
|
|
143
|
+
const match = /^\s*(\d+)\s+(.+?)\s+(\S+)\s*$/.exec(line);
|
|
144
|
+
if (!match)
|
|
145
|
+
continue;
|
|
146
|
+
const pid = Number(match[1]);
|
|
147
|
+
if (!Number.isInteger(pid) || pid <= 0 || seen.has(pid))
|
|
148
|
+
continue;
|
|
149
|
+
seen.add(pid);
|
|
150
|
+
rows.push({ pid, name: match[2].trim(), ageMs: parseEtime(match[3]) });
|
|
151
|
+
}
|
|
152
|
+
return rows;
|
|
153
|
+
}
|
|
61
154
|
async function run(command, args, checked = false) {
|
|
62
155
|
try {
|
|
63
156
|
const result = await execFileAsync(command, args, { windowsHide: true, maxBuffer: 1024 * 1024 });
|
|
@@ -77,72 +170,121 @@ async function run(command, args, checked = false) {
|
|
|
77
170
|
return "";
|
|
78
171
|
}
|
|
79
172
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
return merged;
|
|
89
|
-
}
|
|
90
|
-
async function windowsPortProcesses(port) {
|
|
91
|
-
const merged = new Map();
|
|
92
|
-
const tcpScript = `$ErrorActionPreference = 'SilentlyContinue'; Get-NetTCPConnection -LocalPort ${port} -State Listen | Select-Object -ExpandProperty OwningProcess`;
|
|
93
|
-
for (const pid of parseWindowsPids(await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", tcpScript]))) {
|
|
94
|
-
merged.set(pid, "tcp");
|
|
95
|
-
}
|
|
96
|
-
const udpScript = `$ErrorActionPreference = 'SilentlyContinue'; Get-NetUDPConnection -LocalPort ${port} | Select-Object -ExpandProperty OwningProcess`;
|
|
97
|
-
for (const pid of parseWindowsPids(await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", udpScript]))) {
|
|
98
|
-
if (!merged.has(pid))
|
|
99
|
-
merged.set(pid, "udp");
|
|
100
|
-
}
|
|
101
|
-
if (merged.size > 0)
|
|
102
|
-
return merged;
|
|
103
|
-
const netstat = await run("netstat.exe", ["-ano"]);
|
|
104
|
-
for (const entry of parseNetstatPids(netstat, port)) {
|
|
105
|
-
if (!merged.has(entry.pid))
|
|
106
|
-
merged.set(entry.pid, entry.protocol);
|
|
107
|
-
}
|
|
108
|
-
return merged;
|
|
173
|
+
function byPid(rows) {
|
|
174
|
+
return new Map(rows.map((row) => [row.pid, row]));
|
|
175
|
+
}
|
|
176
|
+
function describe(pid, protocol, info) {
|
|
177
|
+
return { pid, protocol, name: info?.name ?? "unknown", ageMs: info?.ageMs };
|
|
178
|
+
}
|
|
179
|
+
function powershell(script) {
|
|
180
|
+
return run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
|
|
109
181
|
}
|
|
110
|
-
async function
|
|
182
|
+
async function processNames(pids) {
|
|
183
|
+
if (pids.length === 0)
|
|
184
|
+
return new Map();
|
|
111
185
|
if (process.platform === "win32") {
|
|
112
|
-
|
|
113
|
-
const output = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
|
|
114
|
-
const [name, age] = output.split(/\r?\n/);
|
|
115
|
-
const ageMs = Number(age?.trim());
|
|
116
|
-
return { name: name?.trim() || "unknown", ageMs: Number.isFinite(ageMs) && ageMs > 0 ? ageMs : undefined };
|
|
186
|
+
return byPid(parsePipeTable(await powershell(windowsNamesScript(pids))));
|
|
117
187
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
188
|
+
return byPid(parsePsTable(await run("ps", ["-p", pids.join(","), "-o", "pid=,comm=,etime="])));
|
|
189
|
+
}
|
|
190
|
+
async function discoverUnix(port) {
|
|
191
|
+
const protocols = new Map();
|
|
192
|
+
for (const pid of parseUnixLsof(await run("lsof", ["-nP", "-iUDP:" + port, "-Fp"])))
|
|
193
|
+
protocols.set(pid, "udp");
|
|
194
|
+
for (const pid of parseUnixLsof(await run("lsof", ["-nP", "-a", "-iTCP:" + port, "-sTCP:LISTEN", "-Fp"])))
|
|
195
|
+
protocols.set(pid, "tcp");
|
|
196
|
+
if (protocols.size === 0)
|
|
197
|
+
return [];
|
|
198
|
+
const infos = await processNames([...protocols.keys()]);
|
|
199
|
+
return [...protocols].map(([pid, protocol]) => describe(pid, protocol, infos.get(pid)));
|
|
200
|
+
}
|
|
201
|
+
function windowsNameLoop(protocol) {
|
|
202
|
+
// StartTime is local-time, so compare against Now rather than UtcNow or the age comes out negative.
|
|
203
|
+
return `foreach ($id in $pids) { $proc = Get-Process -Id $id; if ($proc) { $age = ''; try { $age = [DateTime]::Now.Subtract($proc.StartTime).TotalMilliseconds } catch { }; Write-Output "$id|$($proc.ProcessName)|$age|${protocol}" } else { Write-Output "$id|unknown||${protocol}" } }`;
|
|
204
|
+
}
|
|
205
|
+
function windowsNamesScript(pids) {
|
|
206
|
+
return [`$pids = @(${pids.join(",")})`, windowsNameLoop("")].join("; ");
|
|
207
|
+
}
|
|
208
|
+
async function discoverWindows(port) {
|
|
209
|
+
// netstat is an order of magnitude cheaper than a PowerShell cold start, so it decides
|
|
210
|
+
// whether anything is on the port; PowerShell is only paid for when a name is needed.
|
|
211
|
+
const entries = parseNetstatPids(await run("netstat.exe", ["-ano"]), port);
|
|
212
|
+
if (entries.length === 0)
|
|
213
|
+
return [];
|
|
214
|
+
const infos = await processNames(entries.map((entry) => entry.pid));
|
|
215
|
+
return entries.map((entry) => describe(entry.pid, entry.protocol, infos.get(entry.pid)));
|
|
216
|
+
}
|
|
217
|
+
async function listUnixSockets() {
|
|
218
|
+
const tcp = await run("lsof", ["-nP", "-iTCP", "-sTCP:LISTEN", "-Fpn"]);
|
|
219
|
+
const udp = await run("lsof", ["-nP", "-iUDP", "-Fpn"]);
|
|
220
|
+
return [...parseUnixLsofListeners(tcp, "tcp"), ...parseUnixLsofListeners(udp, "udp")];
|
|
221
|
+
}
|
|
222
|
+
async function discoverListening(match) {
|
|
223
|
+
const rows = process.platform === "win32"
|
|
224
|
+
? parseNetstatListeners(await run("netstat.exe", ["-ano"]))
|
|
225
|
+
: await listUnixSockets();
|
|
226
|
+
const sockets = new Map();
|
|
227
|
+
for (const row of rows) {
|
|
228
|
+
const entry = sockets.get(row.pid);
|
|
229
|
+
if (!entry) {
|
|
230
|
+
sockets.set(row.pid, { ports: [row.port], protocol: row.protocol });
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
if (!entry.ports.includes(row.port))
|
|
234
|
+
entry.ports.push(row.port);
|
|
235
|
+
if (row.protocol === "tcp")
|
|
236
|
+
entry.protocol = "tcp";
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
const infos = await processNames([...sockets.keys()]);
|
|
240
|
+
const candidates = [...infos].filter(([, info]) => match.test(info.name));
|
|
241
|
+
return Promise.all(candidates.map(async ([pid, info]) => ({
|
|
242
|
+
pid,
|
|
243
|
+
name: info.name,
|
|
244
|
+
protocol: sockets.get(pid)?.protocol,
|
|
245
|
+
ageMs: info.ageMs,
|
|
246
|
+
ports: sockets.get(pid)?.ports.sort((left, right) => left - right),
|
|
247
|
+
cwd: (await pidCwd(pid)) ?? undefined,
|
|
248
|
+
refusal: refusalReason(pid, info.name),
|
|
249
|
+
alwaysConfirm: isProtectedService(info.name),
|
|
250
|
+
})));
|
|
126
251
|
}
|
|
127
|
-
|
|
128
|
-
return
|
|
252
|
+
function probePort(port, protocol) {
|
|
253
|
+
return new Promise((resolve) => {
|
|
254
|
+
if (protocol === "tcp") {
|
|
255
|
+
const server = net.createServer();
|
|
256
|
+
server.once("error", (error) => resolve(error.code === "EADDRINUSE" ? "occupied" : "unknown"));
|
|
257
|
+
server.once("listening", () => server.close(() => resolve("free")));
|
|
258
|
+
server.listen(port);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const socket = dgram.createSocket("udp4");
|
|
262
|
+
socket.once("error", (error) => resolve(error.code === "EADDRINUSE" ? "occupied" : "unknown"));
|
|
263
|
+
socket.once("listening", () => socket.close(() => resolve("free")));
|
|
264
|
+
socket.bind(port);
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
async function probePortState(port) {
|
|
268
|
+
const tcp = await probePort(port, "tcp");
|
|
269
|
+
if (tcp === "occupied")
|
|
270
|
+
return "occupied";
|
|
271
|
+
const udp = await probePort(port, "udp");
|
|
272
|
+
if (udp === "occupied")
|
|
273
|
+
return "occupied";
|
|
274
|
+
return tcp === "free" && udp === "free" ? "free" : "unknown";
|
|
129
275
|
}
|
|
130
276
|
export function createProcessRunner() {
|
|
131
277
|
return {
|
|
132
278
|
async discover(port) {
|
|
133
|
-
const
|
|
134
|
-
return Promise.all(
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
cwd: await processCwd(pid),
|
|
141
|
-
ageMs: info.ageMs,
|
|
142
|
-
docker: isDockerProcess(info.name),
|
|
143
|
-
};
|
|
144
|
-
}));
|
|
279
|
+
const discovered = process.platform === "win32" ? await discoverWindows(port) : await discoverUnix(port);
|
|
280
|
+
return Promise.all(discovered.map(async (entry) => ({
|
|
281
|
+
...entry,
|
|
282
|
+
cwd: (await pidCwd(entry.pid)) ?? undefined,
|
|
283
|
+
refusal: refusalReason(entry.pid, entry.name),
|
|
284
|
+
alwaysConfirm: isProtectedService(entry.name),
|
|
285
|
+
})));
|
|
145
286
|
},
|
|
287
|
+
discoverListening,
|
|
146
288
|
async terminate(pid) {
|
|
147
289
|
if (process.platform === "win32") {
|
|
148
290
|
// Without /F, taskkill cannot end console processes such as node dev servers.
|
|
@@ -158,6 +300,7 @@ export function createProcessRunner() {
|
|
|
158
300
|
catch {
|
|
159
301
|
// The process exited after SIGTERM.
|
|
160
302
|
}
|
|
161
|
-
}
|
|
303
|
+
},
|
|
304
|
+
probe: probePortState,
|
|
162
305
|
};
|
|
163
306
|
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type Colour = "bold" | "dim" | "red" | "green" | "yellow";
|
|
2
|
+
export type ColourMode = "auto" | "always" | "never";
|
|
3
|
+
export declare function setColourMode(next: ColourMode): void;
|
|
4
|
+
export declare function colourEnabled(): boolean;
|
|
5
|
+
export declare function paint(colour: Colour, text: string): string;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import process from "node:process";
|
|
2
|
+
const CODES = {
|
|
3
|
+
bold: "\u001b[1m",
|
|
4
|
+
dim: "\u001b[2m",
|
|
5
|
+
red: "\u001b[31m",
|
|
6
|
+
green: "\u001b[32m",
|
|
7
|
+
yellow: "\u001b[33m",
|
|
8
|
+
};
|
|
9
|
+
const RESET = "\u001b[0m";
|
|
10
|
+
let mode = "auto";
|
|
11
|
+
export function setColourMode(next) {
|
|
12
|
+
mode = next;
|
|
13
|
+
}
|
|
14
|
+
export function colourEnabled() {
|
|
15
|
+
if (mode === "never")
|
|
16
|
+
return false;
|
|
17
|
+
if (mode === "always")
|
|
18
|
+
return true;
|
|
19
|
+
if (process.env.NO_COLOR)
|
|
20
|
+
return false;
|
|
21
|
+
return Boolean(process.stdout.isTTY);
|
|
22
|
+
}
|
|
23
|
+
// Wraps a whole segment rather than interpolating inside one, so message text stays greppable.
|
|
24
|
+
export function paint(colour, text) {
|
|
25
|
+
return colourEnabled() ? `${CODES[colour]}${text}${RESET}` : text;
|
|
26
|
+
}
|
package/dist/tests/args.test.js
CHANGED
|
@@ -1,20 +1,21 @@
|
|
|
1
1
|
import test from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
3
|
import { parseArgs } from "../src/args.js";
|
|
4
|
+
const EMPTY = { ports: [], help: false, version: false, yes: false, list: false, noColor: false };
|
|
4
5
|
test("parses multiple ports and deduplicates", () => {
|
|
5
|
-
assert.deepEqual(parseArgs(["3000", "5173", "3000"]), {
|
|
6
|
-
ports: [3000, 5173],
|
|
7
|
-
help: false,
|
|
8
|
-
version: false,
|
|
9
|
-
yes: false,
|
|
10
|
-
list: false,
|
|
11
|
-
});
|
|
6
|
+
assert.deepEqual(parseArgs(["3000", "5173", "3000"]), { ...EMPTY, ports: [3000, 5173] });
|
|
12
7
|
});
|
|
13
8
|
test("parses flags", () => {
|
|
14
|
-
assert.deepEqual(parseArgs(["-l", "--yes"]), {
|
|
15
|
-
assert.deepEqual(parseArgs(["--list", "-y", "-f"]), {
|
|
16
|
-
assert.deepEqual(parseArgs(["--help"]), {
|
|
17
|
-
assert.deepEqual(parseArgs(["-v"]), {
|
|
9
|
+
assert.deepEqual(parseArgs(["-l", "--yes"]), { ...EMPTY, yes: true, list: true });
|
|
10
|
+
assert.deepEqual(parseArgs(["--list", "-y", "-f"]), { ...EMPTY, yes: true, list: true });
|
|
11
|
+
assert.deepEqual(parseArgs(["--help"]), { ...EMPTY, help: true });
|
|
12
|
+
assert.deepEqual(parseArgs(["-v"]), { ...EMPTY, version: true });
|
|
13
|
+
assert.deepEqual(parseArgs(["--no-color", "3000"]), { ...EMPTY, noColor: true, ports: [3000] });
|
|
14
|
+
});
|
|
15
|
+
test("parses --match with a pattern", () => {
|
|
16
|
+
assert.deepEqual(parseArgs(["--match", "next-server"]), { ...EMPTY, match: "next-server" });
|
|
17
|
+
assert.deepEqual(parseArgs(["-m", "^node$"]), { ...EMPTY, match: "^node$" });
|
|
18
|
+
assert.deepEqual(parseArgs(["--match=vue-cli"]), { ...EMPTY, match: "vue-cli" });
|
|
18
19
|
});
|
|
19
20
|
test("rejects invalid input", () => {
|
|
20
21
|
assert.equal(parseArgs(["abc"]), undefined);
|
|
@@ -22,4 +23,8 @@ test("rejects invalid input", () => {
|
|
|
22
23
|
assert.equal(parseArgs(["65536"]), undefined);
|
|
23
24
|
assert.equal(parseArgs(["3000", "--nope"]), undefined);
|
|
24
25
|
assert.equal(parseArgs(["-1"]), undefined);
|
|
26
|
+
assert.equal(parseArgs(["--match"]), undefined);
|
|
27
|
+
assert.equal(parseArgs(["--match", "--yes"]), undefined);
|
|
28
|
+
assert.equal(parseArgs(["--match", "a", "--match", "b"]), undefined);
|
|
29
|
+
assert.equal(parseArgs(["--match="]), undefined);
|
|
25
30
|
});
|
package/dist/tests/cli.test.js
CHANGED
|
@@ -5,8 +5,9 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { main } from "../src/cli.js";
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
import { refusalReason, isProtectedService } from "../src/process.js";
|
|
9
|
+
function fakeRunner(byPort, probeState = "free", listening = []) {
|
|
10
|
+
const calls = { discovered: [], terminated: [], probed: [], patterns: [] };
|
|
10
11
|
return {
|
|
11
12
|
calls,
|
|
12
13
|
runner: {
|
|
@@ -14,9 +15,17 @@ function fakeRunner(byPort) {
|
|
|
14
15
|
calls.discovered.push(port);
|
|
15
16
|
return byPort[port] ?? [];
|
|
16
17
|
},
|
|
18
|
+
async discoverListening(match) {
|
|
19
|
+
calls.patterns.push(match.source);
|
|
20
|
+
return listening;
|
|
21
|
+
},
|
|
17
22
|
async terminate(pid) {
|
|
18
23
|
calls.terminated.push(pid);
|
|
19
24
|
},
|
|
25
|
+
async probe(port) {
|
|
26
|
+
calls.probed.push(port);
|
|
27
|
+
return probeState;
|
|
28
|
+
},
|
|
20
29
|
},
|
|
21
30
|
};
|
|
22
31
|
}
|
|
@@ -48,6 +57,30 @@ test("exits 0 when all ports are free", async () => {
|
|
|
48
57
|
output.restore();
|
|
49
58
|
}
|
|
50
59
|
});
|
|
60
|
+
test("reports a port held by a process it cannot see and exits 1", async () => {
|
|
61
|
+
const { runner, calls } = fakeRunner({}, "occupied");
|
|
62
|
+
const output = capture();
|
|
63
|
+
try {
|
|
64
|
+
assert.equal(await main(["3000"], runner), 1);
|
|
65
|
+
assert.deepEqual(calls.probed, [3000]);
|
|
66
|
+
assert.match(output.error.join("\n"), /cannot see/);
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
output.restore();
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
test("does not probe ports that already have visible processes", async () => {
|
|
73
|
+
const { runner, calls } = fakeRunner({ 3000: [{ pid: 42, name: "node", cwd: process.cwd() }] });
|
|
74
|
+
const output = capture();
|
|
75
|
+
try {
|
|
76
|
+
assert.equal(await main(["3000"], runner), 0);
|
|
77
|
+
assert.deepEqual(calls.probed, []);
|
|
78
|
+
assert.deepEqual(calls.terminated, [42]);
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
output.restore();
|
|
82
|
+
}
|
|
83
|
+
});
|
|
51
84
|
test("terminates processes from the current directory without prompting", async () => {
|
|
52
85
|
const { runner, calls } = fakeRunner({ 3000: [{ pid: 42, name: "node", cwd: process.cwd() }] });
|
|
53
86
|
const output = capture();
|
|
@@ -59,6 +92,31 @@ test("terminates processes from the current directory without prompting", async
|
|
|
59
92
|
output.restore();
|
|
60
93
|
}
|
|
61
94
|
});
|
|
95
|
+
test("prompts before killing a database even when it shares the project directory", async () => {
|
|
96
|
+
const postgres = { pid: 4242, name: "postgres", cwd: process.cwd(), alwaysConfirm: isProtectedService("postgres") };
|
|
97
|
+
const { runner, calls } = fakeRunner({ 5432: [postgres] });
|
|
98
|
+
const output = capture();
|
|
99
|
+
try {
|
|
100
|
+
assert.equal(await main(["5432"], runner), 1);
|
|
101
|
+
assert.deepEqual(calls.terminated, []);
|
|
102
|
+
assert.match(output.error.join("\n"), /interactive terminal/);
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
output.restore();
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
test("--yes still overrides the protected-service prompt", async () => {
|
|
109
|
+
const postgres = { pid: 4242, name: "postgres", cwd: process.cwd(), alwaysConfirm: isProtectedService("postgres") };
|
|
110
|
+
const { runner, calls } = fakeRunner({ 5432: [postgres] });
|
|
111
|
+
const output = capture();
|
|
112
|
+
try {
|
|
113
|
+
assert.equal(await main(["5432", "--yes"], runner), 0);
|
|
114
|
+
assert.deepEqual(calls.terminated, [4242]);
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
output.restore();
|
|
118
|
+
}
|
|
119
|
+
});
|
|
62
120
|
test("declines foreign processes when not interactive", async () => {
|
|
63
121
|
const { runner, calls } = fakeRunner({ 3000: [{ pid: 7, name: "node", cwd: "/somewhere/else" }] });
|
|
64
122
|
const output = capture();
|
|
@@ -102,7 +160,7 @@ test("--list reports without terminating", async () => {
|
|
|
102
160
|
}
|
|
103
161
|
});
|
|
104
162
|
test("refuses to kill Docker processes even with --yes", async () => {
|
|
105
|
-
const { runner, calls } = fakeRunner({ 3000: [{ pid: 9, name: "docker-proxy",
|
|
163
|
+
const { runner, calls } = fakeRunner({ 3000: [{ pid: 9, name: "docker-proxy", refusal: refusalReason(9, "docker-proxy") }] });
|
|
106
164
|
const output = capture();
|
|
107
165
|
try {
|
|
108
166
|
assert.equal(await main(["3000", "--yes"], runner), 1);
|
|
@@ -113,6 +171,18 @@ test("refuses to kill Docker processes even with --yes", async () => {
|
|
|
113
171
|
output.restore();
|
|
114
172
|
}
|
|
115
173
|
});
|
|
174
|
+
test("refuses to kill operating-system PIDs even with --yes", async () => {
|
|
175
|
+
const { runner, calls } = fakeRunner({ 8080: [{ pid: 4, name: "System", refusal: refusalReason(4, "System") }] });
|
|
176
|
+
const output = capture();
|
|
177
|
+
try {
|
|
178
|
+
assert.equal(await main(["8080", "--yes"], runner), 1);
|
|
179
|
+
assert.deepEqual(calls.terminated, []);
|
|
180
|
+
assert.match(output.error.join("\n"), /operating system/);
|
|
181
|
+
}
|
|
182
|
+
finally {
|
|
183
|
+
output.restore();
|
|
184
|
+
}
|
|
185
|
+
});
|
|
116
186
|
test("skips ports protected by .reclaimignore in the current directory", async () => {
|
|
117
187
|
const dir = await mkdtemp(path.join(tmpdir(), "port-reclaim-"));
|
|
118
188
|
const originalCwd = process.cwd();
|
|
@@ -142,3 +212,110 @@ test("invalid input exits 2", async () => {
|
|
|
142
212
|
output.restore();
|
|
143
213
|
}
|
|
144
214
|
});
|
|
215
|
+
function staleServer() {
|
|
216
|
+
return [{ pid: 77, name: "next-server", cwd: "/elsewhere", ports: [3000, 5173] }];
|
|
217
|
+
}
|
|
218
|
+
test("--match reclaims every port a matching process holds and kills it once", async () => {
|
|
219
|
+
const { runner, calls } = fakeRunner({}, "free", staleServer());
|
|
220
|
+
const output = capture();
|
|
221
|
+
try {
|
|
222
|
+
assert.equal(await main(["--match", "next-server", "--yes"], runner), 0);
|
|
223
|
+
assert.deepEqual(calls.patterns, ["next-server"]);
|
|
224
|
+
assert.deepEqual(calls.discovered, []);
|
|
225
|
+
assert.deepEqual(calls.terminated, [77]);
|
|
226
|
+
assert.match(output.log.join("\n"), /Released ports 3000, 5173 from next-server \(PID 77\)/);
|
|
227
|
+
}
|
|
228
|
+
finally {
|
|
229
|
+
output.restore();
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
test("--match honours refusals for protected processes", async () => {
|
|
233
|
+
const docker = { pid: 9, name: "docker-proxy", ports: [8080], refusal: refusalReason(9, "docker-proxy") };
|
|
234
|
+
const { runner, calls } = fakeRunner({}, "free", [docker]);
|
|
235
|
+
const output = capture();
|
|
236
|
+
try {
|
|
237
|
+
assert.equal(await main(["--match", "docker", "--yes"], runner), 1);
|
|
238
|
+
assert.deepEqual(calls.terminated, []);
|
|
239
|
+
assert.match(output.error.join("\n"), /Docker/);
|
|
240
|
+
}
|
|
241
|
+
finally {
|
|
242
|
+
output.restore();
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
test("--match skips a process holding a protected port", async () => {
|
|
246
|
+
const dir = await mkdtemp(path.join(tmpdir(), "port-reclaim-"));
|
|
247
|
+
const originalCwd = process.cwd();
|
|
248
|
+
const postgres = { pid: 4242, name: "postgres", cwd: "/var/lib/postgresql", ports: [5432], alwaysConfirm: isProtectedService("postgres") };
|
|
249
|
+
const { runner, calls } = fakeRunner({}, "free", [postgres]);
|
|
250
|
+
const output = capture();
|
|
251
|
+
try {
|
|
252
|
+
await writeFile(path.join(dir, ".reclaimignore"), "5432\n");
|
|
253
|
+
process.chdir(dir);
|
|
254
|
+
assert.equal(await main(["--match", "postgres", "--yes"], runner), 0);
|
|
255
|
+
assert.deepEqual(calls.terminated, []);
|
|
256
|
+
assert.match(output.log.join("\n"), /protected/);
|
|
257
|
+
}
|
|
258
|
+
finally {
|
|
259
|
+
process.chdir(originalCwd);
|
|
260
|
+
await rm(dir, { recursive: true, force: true });
|
|
261
|
+
output.restore();
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
test("--match reports when nothing listens under that name", async () => {
|
|
265
|
+
const { runner, calls } = fakeRunner({}, "free", []);
|
|
266
|
+
const output = capture();
|
|
267
|
+
try {
|
|
268
|
+
assert.equal(await main(["--match", "nothing-here", "--yes"], runner), 0);
|
|
269
|
+
assert.deepEqual(calls.terminated, []);
|
|
270
|
+
assert.match(output.log.join("\n"), /No listening process matches/);
|
|
271
|
+
}
|
|
272
|
+
finally {
|
|
273
|
+
output.restore();
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
test("an invalid --match pattern exits 2", async () => {
|
|
277
|
+
const { runner } = fakeRunner({});
|
|
278
|
+
const output = capture();
|
|
279
|
+
try {
|
|
280
|
+
assert.equal(await main(["--match", "("], runner), 2);
|
|
281
|
+
assert.match(output.error.join("\n"), /not a valid regular expression/);
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
output.restore();
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
test("--match cannot be combined with ports", async () => {
|
|
288
|
+
const { runner } = fakeRunner({});
|
|
289
|
+
const output = capture();
|
|
290
|
+
try {
|
|
291
|
+
assert.equal(await main(["3000", "--match", "node"], runner), 2);
|
|
292
|
+
assert.match(output.error.join("\n"), /either ports or --match/);
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
output.restore();
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
test("colour codes reach a terminal and --no-color suppresses them", async () => {
|
|
299
|
+
const originalTty = process.stdout.isTTY;
|
|
300
|
+
const originalNoColor = process.env.NO_COLOR;
|
|
301
|
+
delete process.env.NO_COLOR;
|
|
302
|
+
Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true });
|
|
303
|
+
const byPort = { 3000: [{ pid: 42, name: "node", cwd: process.cwd() }] };
|
|
304
|
+
try {
|
|
305
|
+
const coloured = capture();
|
|
306
|
+
await main(["3000"], fakeRunner(byPort).runner);
|
|
307
|
+
coloured.restore();
|
|
308
|
+
const plain = capture();
|
|
309
|
+
await main(["3000", "--no-color"], fakeRunner(byPort).runner);
|
|
310
|
+
plain.restore();
|
|
311
|
+
assert.match(coloured.log.join("\n"), /\u001b\[32m/);
|
|
312
|
+
assert.doesNotMatch(plain.log.join("\n"), /\u001b\[/);
|
|
313
|
+
}
|
|
314
|
+
finally {
|
|
315
|
+
Object.defineProperty(process.stdout, "isTTY", { value: originalTty, configurable: true });
|
|
316
|
+
if (originalNoColor === undefined)
|
|
317
|
+
delete process.env.NO_COLOR;
|
|
318
|
+
else
|
|
319
|
+
process.env.NO_COLOR = originalNoColor;
|
|
320
|
+
}
|
|
321
|
+
});
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import test from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import { parseEtime, parseNetstatPids, parseUnixLsof,
|
|
4
|
-
test("parses unique Windows PIDs", () => {
|
|
5
|
-
assert.deepEqual(parseWindowsPids("1234\r\n5678\r\n1234\r\n"), [1234, 5678]);
|
|
6
|
-
});
|
|
3
|
+
import { parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, isProtectedService, refusalReason, } from "../src/process.js";
|
|
7
4
|
test("parses lsof PID records", () => {
|
|
8
5
|
assert.deepEqual(parseUnixLsof("p1234\ncnode\np5678\np1234\n"), [1234, 5678]);
|
|
9
6
|
});
|
|
@@ -16,6 +13,75 @@ test("parses ps etime durations", () => {
|
|
|
16
13
|
assert.equal(parseEtime("abc"), undefined);
|
|
17
14
|
assert.equal(parseEtime("1:2:3:4"), undefined);
|
|
18
15
|
});
|
|
16
|
+
test("parses one batched ps table, keeping spaces in command names", () => {
|
|
17
|
+
const output = [
|
|
18
|
+
" 1234 node 01:02:03",
|
|
19
|
+
" 5678 Google Chrome 45:00",
|
|
20
|
+
"ps: unknown process 9999",
|
|
21
|
+
].join("\n");
|
|
22
|
+
assert.deepEqual(parsePsTable(output), [
|
|
23
|
+
{ pid: 1234, name: "node", ageMs: 3723000 },
|
|
24
|
+
{ pid: 5678, name: "Google Chrome", ageMs: 2700000 },
|
|
25
|
+
]);
|
|
26
|
+
});
|
|
27
|
+
test("parses pipe-delimited process rows", () => {
|
|
28
|
+
assert.deepEqual(parsePipeTable("7|node|1500.5|udp\r\n8|python||\r\n"), [
|
|
29
|
+
{ pid: 7, name: "node", ageMs: 1500.5, protocol: "udp" },
|
|
30
|
+
{ pid: 8, name: "python", ageMs: undefined, protocol: undefined },
|
|
31
|
+
]);
|
|
32
|
+
});
|
|
33
|
+
test("drops PID 0, keeps PID 4 for the refusal layer, and deduplicates rows", () => {
|
|
34
|
+
assert.deepEqual(parsePipeTable(["0|Idle|10|", "4|System|20|", "77|node|30|", "77|node|30|", "junk"].join("\r\n")), [
|
|
35
|
+
{ pid: 4, name: "System", ageMs: 20, protocol: undefined },
|
|
36
|
+
{ pid: 77, name: "node", ageMs: 30, protocol: undefined },
|
|
37
|
+
]);
|
|
38
|
+
});
|
|
39
|
+
test("parses every listener from a full netstat table", () => {
|
|
40
|
+
const output = [
|
|
41
|
+
" Proto Local Address Foreign Address State PID",
|
|
42
|
+
" TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 4",
|
|
43
|
+
" TCP 127.0.0.1:3000 127.0.0.1:51234 ESTABLISHED 9999",
|
|
44
|
+
" TCP [::]:5173 [::]:0 LISTENING 2222",
|
|
45
|
+
" TCP 0.0.0.0:5173 0.0.0.0:0 LISTENING 2222",
|
|
46
|
+
" UDP 0.0.0.0:5353 *:* 3333",
|
|
47
|
+
" UDP [::]:54321 *:* 0",
|
|
48
|
+
].join("\r\n");
|
|
49
|
+
assert.deepEqual(parseNetstatListeners(output), [
|
|
50
|
+
{ pid: 4, port: 135, protocol: "tcp" },
|
|
51
|
+
{ pid: 2222, port: 5173, protocol: "tcp" },
|
|
52
|
+
{ pid: 3333, port: 5353, protocol: "udp" },
|
|
53
|
+
]);
|
|
54
|
+
});
|
|
55
|
+
test("parses grouped lsof field output into listeners", () => {
|
|
56
|
+
const output = [
|
|
57
|
+
"p4242",
|
|
58
|
+
"n127.0.0.1:5432",
|
|
59
|
+
"n[::1]:5432",
|
|
60
|
+
"p77",
|
|
61
|
+
"n*:3000",
|
|
62
|
+
"n/tcp",
|
|
63
|
+
"n/var/run/docker.sock",
|
|
64
|
+
].join("\n");
|
|
65
|
+
assert.deepEqual(parseUnixLsofListeners(output, "tcp"), [
|
|
66
|
+
{ pid: 4242, port: 5432, protocol: "tcp" },
|
|
67
|
+
{ pid: 77, port: 3000, protocol: "tcp" },
|
|
68
|
+
]);
|
|
69
|
+
});
|
|
70
|
+
test("recognises data services that must never auto-kill", () => {
|
|
71
|
+
assert.equal(isProtectedService("postgres"), true);
|
|
72
|
+
assert.equal(isProtectedService("Redis-Server"), true);
|
|
73
|
+
assert.equal(isProtectedService(" mysqld "), true);
|
|
74
|
+
assert.equal(isProtectedService("node"), false);
|
|
75
|
+
assert.equal(isProtectedService("redis-cli"), false);
|
|
76
|
+
assert.equal(isProtectedService("mongo"), false);
|
|
77
|
+
});
|
|
78
|
+
test("refuses Docker-named processes and operating-system PIDs", () => {
|
|
79
|
+
assert.match(refusalReason(9, "docker-proxy") ?? "", /Docker/);
|
|
80
|
+
assert.match(refusalReason(9, "vpnkit") ?? "", /Docker/);
|
|
81
|
+
assert.match(refusalReason(4, "System") ?? "", /operating system/);
|
|
82
|
+
assert.match(refusalReason(1, "systemd") ?? "", /operating system/);
|
|
83
|
+
assert.equal(refusalReason(4242, "node"), undefined);
|
|
84
|
+
});
|
|
19
85
|
test("parses netstat TCP listeners and UDP sockets for an exact port", () => {
|
|
20
86
|
const output = [
|
|
21
87
|
"Active Connections",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import process from "node:process";
|
|
4
|
+
import { colourEnabled, paint, setColourMode } from "../src/style.js";
|
|
5
|
+
test("paint wraps text only when colour is enabled", () => {
|
|
6
|
+
setColourMode("always");
|
|
7
|
+
assert.equal(paint("green", "ok"), "\u001b[32mok\u001b[0m");
|
|
8
|
+
assert.equal(paint("dim", "PID 7"), "\u001b[2mPID 7\u001b[0m");
|
|
9
|
+
setColourMode("never");
|
|
10
|
+
assert.equal(paint("green", "ok"), "ok");
|
|
11
|
+
});
|
|
12
|
+
test("auto mode defers to NO_COLOR and never mode always strips", () => {
|
|
13
|
+
const original = process.env.NO_COLOR;
|
|
14
|
+
try {
|
|
15
|
+
process.env.NO_COLOR = "1";
|
|
16
|
+
setColourMode("auto");
|
|
17
|
+
assert.equal(colourEnabled(), false);
|
|
18
|
+
setColourMode("never");
|
|
19
|
+
assert.equal(colourEnabled(), false);
|
|
20
|
+
setColourMode("always");
|
|
21
|
+
assert.equal(colourEnabled(), true);
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
if (original === undefined)
|
|
25
|
+
delete process.env.NO_COLOR;
|
|
26
|
+
else
|
|
27
|
+
process.env.NO_COLOR = original;
|
|
28
|
+
setColourMode("auto");
|
|
29
|
+
}
|
|
30
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "port-reclaim",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Free up a port already in use: find and kill the process holding it (EADDRINUSE). Cross-platform, zero-config, Docker-safe.",
|
|
5
5
|
"author": "princegoel0",
|
|
6
6
|
"license": "MIT",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
},
|
|
32
32
|
"scripts": {
|
|
33
33
|
"build": "tsc",
|
|
34
|
-
"test": "npm run build && node --test dist/tests/process.test.js dist/tests/args.test.js dist/tests/config.test.js dist/tests/cli.test.js",
|
|
34
|
+
"test": "npm run build && node --test dist/tests/process.test.js dist/tests/args.test.js dist/tests/config.test.js dist/tests/style.test.js dist/tests/cli.test.js",
|
|
35
35
|
"prepublishOnly": "npm test"
|
|
36
36
|
},
|
|
37
37
|
"keywords": [
|