Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/adr/0001-leeway.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ shell line with it fails rather than lose its quotes.
**Environment variables are the transport.** They pass through `concurrently`, `tsx`, package scripts and shells to every child process
with no integration. `leeway` runs the command through the system shell: one argument is a shell line, several are an argv quoted for
the shell. Stopping leeway stops the tree: on POSIX the command gets its own process group and SIGINT, SIGTERM, SIGHUP and SIGQUIT are
forwarded to it; on Windows, which has no process groups to signal, Ctrl+C, Ctrl+Break and console close run `taskkill /T /F`.
forwarded to it, and SIGWINCH too so a resize reaches it; on Windows, which has no process groups to signal, Ctrl+C, Ctrl+Break and
console close run `taskkill /T /F`.

**Browser and vite.** `devPorts` is browser-safe. `leeway/vite` sets `server.port` and `preview.port` with `strictPort`, so a taken port
fails instead of drifting. `preview.port` uses the dev server's port name unless `preview` names another: left alone, vite previews on
Expand Down
9 changes: 6 additions & 3 deletions packages/leeway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,11 +208,14 @@ folder still claims its own range, and an explicit `--default` or `--inherit` ke
shell when needed, so `leeway node -e "console.log(1)"` runs exactly that. On Windows a `.cmd` shim re-parses its arguments, so an
argument holding both `"` and a cmd metacharacter like `&` can still break there.
- The command runs through the system shell (`sh`, `cmd.exe` on Windows).
- leeway exits with the shell's exit code (a missing command: 127 from `sh`, 1 from `cmd.exe`; a command killed by a signal: usually
128 plus the signal number from `sh`), or 1 if the shell itself died from a signal or could not start.
- The command's port variables replace any variable of the same name in leeway's environment, in any case: on Windows a `PORT_WEB` in
the shell does not shadow a `port_web` port name.
- leeway exits with the shell's exit code (a missing command: 127 from `sh`, 1 from `cmd.exe`), 128 plus the signal number when the
command or the shell died from a signal (130 for Ctrl+C), or 1 if the shell could not start.
- Stopping leeway stops the whole command tree: Ctrl+C, `Ctrl+\`, closing the terminal, or SIGINT, SIGTERM, SIGHUP
or SIGQUIT on Linux and macOS; Ctrl+C, Ctrl+Break or closing the console on Windows. On Linux and macOS the tree gets the signal
leeway got, so a command that handles it and keeps running is not stopped ([Limits](#limits)).
leeway got, so a command that handles it and keeps running is not stopped ([Limits](#limits)). A terminal resize (SIGWINCH)
reaches the command too, so a TUI redraws.

`leeway --help` (or `-h`) prints the usage, `leeway --version` the version.

Expand Down
29 changes: 19 additions & 10 deletions packages/leeway/src/os/run-with-ports.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import { spawn } from "node:child_process";
import os from "node:os";
import { ProcessTree } from "./process-tree.ts";

const WINDOWS_STOP_SIGNALS: NodeJS.Signals[] = ["SIGINT", "SIGBREAK", "SIGHUP"];

const POSIX_FORWARDED_SIGNALS: NodeJS.Signals[] = ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"];
const POSIX_FORWARDED_SIGNALS: NodeJS.Signals[] = ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT", "SIGWINCH"];

export class RunWithPorts {
static runAndExit(commandLine: string, env: Record<string, string | number>): void {
const isWindows = process.platform === "win32";
const child = spawn(commandLine, {
stdio: "inherit",
shell: true,
detached: !isWindows,
env: { ...process.env, ...Object.fromEntries(Object.entries(env).map(([name, value]) => [name, String(value)])) },
});

RunWithPorts.overrideInheritedEnv(env);

const child = spawn(commandLine, { stdio: "inherit", shell: true, detached: !isWindows });
const pid = child.pid;

if (pid === undefined) {
Expand All @@ -30,8 +29,18 @@ export class RunWithPorts {
POSIX_FORWARDED_SIGNALS.forEach(signal => process.on(signal, () => ProcessTree.signalGroup(pid, signal)));
}

child.on("exit", (code, signal) => {
process.exit(signal ? 1 : (code ?? 1));
});
child.on("exit", (code, signal) => process.exit(signal ? RunWithPorts.signalExitCode(signal) : (code ?? 1)));
}

private static overrideInheritedEnv(env: Record<string, string | number>): void {
for (const [name, value] of Object.entries(env)) {
process.env[name] = String(value);
}
}

private static signalExitCode(signal: NodeJS.Signals): number {
const signalNumber: number | undefined = os.constants.signals[signal];

return signalNumber === undefined ? 1 : 128 + signalNumber;
}
}
28 changes: 26 additions & 2 deletions packages/leeway/test/cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { type ChildProcess, spawn, spawnSync } from "node:child_process";
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { Pools } from "../src/registry/pools.ts";
Expand All @@ -13,6 +14,9 @@ const SERVER =

const PRINT_PORTS = "console.log('argument ' + process.argv[1] + ', env ' + process.env.PORT_WEB + ' ' + process.env.PORT_API)";

const RESIZE_WAITER =
"process.on('SIGWINCH', () => { console.log('resized'); process.exit(0); }); console.log('listening 0'); setInterval(() => {}, 1000);";

const FIXTURES = {
"launcher.mjs": `import { spawn } from "node:child_process";
spawn(process.execPath, ["-e", ${JSON.stringify(SERVER)}], { stdio: "inherit" });
Expand Down Expand Up @@ -303,6 +307,15 @@ describe("leeway <command>", () => {
expect(LeewayCli.run(["node", "-e", "process.exit(0)"], dir, home).status).toBe(0);
});

it("gives the command its port over a parent variable whose name differs only in case", () => {
const { dir, home } = temporaryFolder();
fs.writeFileSync(path.join(dir, "leeway.json"), JSON.stringify({ ports: { port_web: { port: 5173 } } }));

const result = LeewayCli.run(["--default", "node", "-e", "console.log(process.env.port_web)"], dir, home, { PORT_WEB: "9999" });

expect(result.stdout).toBe("5173\n");
});

it("gives the command the claimed ports, and its server answers on one", async () => {
const { dir, home } = temporaryFolder();
const leeway = startLeeway(["node", "-e", SERVER], dir, home);
Expand Down Expand Up @@ -606,7 +619,7 @@ describe("leeway errors", () => {

describe.skipIf(process.platform === "win32")("leeway <command> on a signal", () => {
it.each(["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"] as const)(
"%s stops the whole command tree, so nothing is left listening",
"%s stops the whole command tree, so nothing is left listening, and exits 128 plus the signal number",
async signal => {
const { dir, home } = temporaryFolder();
const leeway = startLeeway(["node", "launcher.mjs"], dir, home);
Expand All @@ -617,10 +630,21 @@ describe.skipIf(process.platform === "win32")("leeway <command> on a signal", ()

leeway.kill(signal);

expect(await exitCode).not.toBe(0);
expect(await exitCode).toBe(128 + os.constants.signals[signal]);
expect(await stopsAnswering(port)).toBe(true);
},
);

it("hands SIGWINCH to the command, so a TUI redraws on a terminal resize", async () => {
const { dir, home } = temporaryFolder();
const leeway = startLeeway(["node", "-e", RESIZE_WAITER], dir, home);
const result = finished(leeway);

await listeningPort(leeway);
leeway.kill("SIGWINCH");

expect(await result).toEqual({ code: 0, stdout: "listening 0\nresized\n" });
});
});

describe.runIf(process.platform === "win32")("leeway <command> on Ctrl+C in its console", () => {
Expand Down
Loading