From 511cc508a8b5159ef6344837859be78bba2f0d2f Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 11:59:34 -0600 Subject: [PATCH 1/2] Runtime(feat): Find tmux on PATH why: A caller starting a tmux server should be able to use the executable on its PATH and still select an exact binary when needed. what: - Resolve the program before spawning tmux and update library callers, tests and examples to use the public selection rule. --- README.md | 46 +--- docs/environment.md | 2 +- docs/runtime.md | 15 +- docs/snapshots.md | 5 +- examples/api/README.md | 7 +- examples/api/capture.lua | 5 +- examples/api/connect.lua | 7 +- examples/api/explain.lua | 5 +- examples/api/group.lua | 5 +- examples/api/new_session.lua | 5 +- examples/api/new_window.lua | 5 +- examples/api/query.lua | 5 +- examples/api/refresh.lua | 5 +- examples/api/resize.lua | 5 +- examples/api/send_keys.lua | 5 +- examples/api/snapshot.lua | 5 +- examples/api/start_server.lua | 5 +- examples/api/unsupported_version.lua | 5 +- examples/api/wait_for_text.lua | 5 +- examples/api/watch_pane.lua | 5 +- examples/api/with_server.lua | 5 +- examples/nvim_snapshot.lua | 3 +- examples/quickstart.lua | 5 +- examples/snapshot.lua | 5 +- lua/libtmux/README.md | 8 +- lua/libtmux/_internal/endpoint.lua | 142 +++++++++++- lua/libtmux/_internal/runtime.lua | 16 +- lua/libtmux/_internal/server.lua | 263 +++++++++++++--------- scripts/package/README.md | 9 +- scripts/package/package.lua | 63 +++--- tests/integration/path_discovery.lua | 218 ++++++++++++++++++ tests/integration/test_path_discovery.lua | 46 ++++ tests/integration/test_runtime.lua | 2 +- tests/unit/owned_server.lua | 3 +- 34 files changed, 665 insertions(+), 275 deletions(-) create mode 100644 tests/integration/path_discovery.lua create mode 100644 tests/integration/test_path_discovery.lua diff --git a/README.md b/README.md index 6e13e083..d9e78740 100644 --- a/README.md +++ b/README.md @@ -72,11 +72,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local created = must(owned.server :new_session({ name = "demo", @@ -103,8 +100,7 @@ Live calls return [Requests][ref-request]. [`:await()`][ref-request-await] yields inside the [runtime][ref-runtime] body and returns `value, err`; `must` raises the error. -The programs use `/usr/bin/tmux`. Set `TMUX_BIN` to another absolute path to -change that. Run one from a checkout: +Put tmux on `PATH` and run one of the programs from a checkout: ```console $ git clone https://github.com/libtmux/libtmux-lua.git && cd libtmux-lua @@ -139,12 +135,9 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) -- The server is private: its own directory, socket and environment. - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local server = owned.server local before = must(server:snapshot():await()) @@ -185,11 +178,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local server = owned.server must(server:new_session({ name = "demo", argv = { "/bin/cat" } }):await()) local snapshot = must(server:snapshot({ strict = true }):await()) @@ -385,11 +375,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local created = must(owned.server :new_session({ name = "demo", @@ -471,11 +458,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local session = { name = "demo", argv = { "/bin/sh" } } local created = must(owned.server:new_session(session):await()) local pane = created.pane @@ -583,11 +567,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local session = { name = "demo", argv = { "/bin/cat" } } local created = must(owned.server:new_session(session):await()) local split_opts = { direction = "right", argv = { "/bin/cat" } } @@ -654,11 +635,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) -- One tmux process runs all four commands, in order. local done = must(owned.server :group({ @@ -715,11 +693,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local created = must(owned.server :new_session({ name = "demo", @@ -769,8 +744,7 @@ did not create stay open: local adapter = require("libtmux.runtime.nvim") return adapter.start(function(runtime) - local binary = vim.fn.exepath("tmux") - local owned, err = runtime:start_server({ binary = binary }):await() + local owned, err = runtime:start_server():await() if not owned then return nil, err end diff --git a/docs/environment.md b/docs/environment.md index d5768868..652a00be 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -11,7 +11,7 @@ session stores. ```lua local adapter = require("libtmux.runtime.luv") local result, err = adapter.run(function(runtime) - local owned = assert(runtime:start_server({ binary = "/usr/bin/tmux" }):await()) + local owned = assert(runtime:start_server():await()) local server = owned.server local created = assert(server:new_session({ name = "demo", argv = { "/bin/cat" } }):await()) local session = created.session diff --git a/docs/runtime.md b/docs/runtime.md index 0e9c5123..2c54c7b6 100644 --- a/docs/runtime.md +++ b/docs/runtime.md @@ -18,6 +18,19 @@ Choose an adapter: callbacks outside fast events. `on_done(value, err)` runs after owned cleanup; unrelated host handles stay open. +## Choose the tmux executable + +`connect`, `start_server` and `with_server` use the first executable regular +file named `tmux` on the caller's `PATH`. Each request captures `PATH` and the +current directory at submission and reuses the selected absolute path. With +`PATH` unset, the lookup checks `/usr/bin` and `/bin`. An empty entry checks the +captured working directory. + +Pass an absolute `binary` to select a particular build. Use +`runtime:find_tmux():await()` to get the path without launching tmux or +contacting a server. A search with no executable returns `invalid_endpoint` +before sending a command. + ## Start a private server `runtime:start_server(options):await()` starts a tmux server this runtime owns @@ -28,7 +41,7 @@ that already runs. The tested programs are | Option | Default | Meaning | | --- | --- | --- | -| `binary` | required | Absolute tmux executable | +| `binary` | tmux on `PATH` | Absolute tmux executable override | | `config` | `/dev/null` | Absolute configuration file; the default loads none | | `root` | system temporary directory | Absolute directory that holds the private one | | `environment` | none | `NAME = value` entries for the daemon and its panes | diff --git a/docs/snapshots.md b/docs/snapshots.md index 32323dc1..b9df273a 100644 --- a/docs/snapshots.md +++ b/docs/snapshots.md @@ -7,8 +7,9 @@ and prints each pane and its window ID. ## Connect to a server -- Pass an absolute `binary` and, usually, an absolute `socket_path`. - `config_path` defaults to `/dev/null`. +- Pass an absolute `socket_path` to select the daemon. The client uses + [tmux on `PATH`](runtime.md#choose-the-tmux-executable) unless you pass + an absolute `binary`. `config_path` defaults to `/dev/null`. - `connect` never starts a server; [`start_server`](runtime.md#start-a-private-server) starts a private one. Importing the library and reading captured records do no I/O. diff --git a/examples/api/README.md b/examples/api/README.md index b781464c..799b62e1 100644 --- a/examples/api/README.md +++ b/examples/api/README.md @@ -4,10 +4,9 @@ Each Lua file is a standalone program. It starts its own private tmux server with `Runtime:start_server`, uses it and stops it, even when the program fails. No existing session is needed. -Needs Lua, LuaRocks, Git, tmux 3.3a or newer, a C compiler and CMake on Linux. -The programs use `/usr/bin/tmux`; set `TMUX_BIN` to another absolute path to -change that. From the repository root, install the library and its standalone -runtime dependency into a local tree: +Needs Lua, LuaRocks, Git, tmux 3.3a or newer on `PATH`, a C compiler and +CMake on Linux. From the repository root, install the library and its +standalone runtime dependency into a local tree: ```console $ luarocks --tree ./rocks install luv 1.52.1-0 && \ diff --git a/examples/api/capture.lua b/examples/api/capture.lua index 18772c0b..bf483b48 100644 --- a/examples/api/capture.lua +++ b/examples/api/capture.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local session = { name = "demo", argv = { "/bin/sh" } } local created = must(owned.server:new_session(session):await()) local pane = created.pane diff --git a/examples/api/connect.lua b/examples/api/connect.lua index ca00f843..b4d8a06c 100644 --- a/examples/api/connect.lua +++ b/examples/api/connect.lua @@ -7,16 +7,13 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local session = { name = "demo", argv = { "/bin/cat" } } must(owned.server:new_session(session):await()) -- A second handle reaches the same daemon and leaves it running on close. - local target = { binary = binary, socket_path = owned.socket_path } + local target = { socket_path = owned.socket_path } local server = must(runtime:connect(target):await()) local snapshot = must(server:snapshot({ strict = true }):await()) local demo = snapshot.sessions:where({ name = "demo" }) diff --git a/examples/api/explain.lua b/examples/api/explain.lua index 854722c3..d60cdc2c 100644 --- a/examples/api/explain.lua +++ b/examples/api/explain.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local server = owned.server local where = { active = true, current_command = "cat" } for _, mode in ipairs({ "never", "auto" }) do diff --git a/examples/api/group.lua b/examples/api/group.lua index ff5d23f8..c77148c5 100644 --- a/examples/api/group.lua +++ b/examples/api/group.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) -- One tmux process runs all four commands, in order. local done = must(owned.server :group({ diff --git a/examples/api/new_session.lua b/examples/api/new_session.lua index 5accf63e..629de13c 100644 --- a/examples/api/new_session.lua +++ b/examples/api/new_session.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local created = must(owned.server :new_session({ name = "demo", diff --git a/examples/api/new_window.lua b/examples/api/new_window.lua index 27ce4c99..d347d7ba 100644 --- a/examples/api/new_window.lua +++ b/examples/api/new_window.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local created = must(owned.server :new_session({ name = "demo", diff --git a/examples/api/query.lua b/examples/api/query.lua index 7847faaf..e086893e 100644 --- a/examples/api/query.lua +++ b/examples/api/query.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local server = owned.server must(server :new_session({ diff --git a/examples/api/refresh.lua b/examples/api/refresh.lua index 128da909..d5be297f 100644 --- a/examples/api/refresh.lua +++ b/examples/api/refresh.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local created = must(owned.server :new_session({ name = "demo", diff --git a/examples/api/resize.lua b/examples/api/resize.lua index ed4297bd..7683131e 100644 --- a/examples/api/resize.lua +++ b/examples/api/resize.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local session = { name = "demo", argv = { "/bin/cat" } } local created = must(owned.server:new_session(session):await()) local split_opts = { direction = "right", argv = { "/bin/cat" } } diff --git a/examples/api/send_keys.lua b/examples/api/send_keys.lua index 9d8d4dc8..bbfb0e26 100644 --- a/examples/api/send_keys.lua +++ b/examples/api/send_keys.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local session = { name = "demo", argv = { "/bin/sh" } } local created = must(owned.server:new_session(session):await()) local pane = created.pane diff --git a/examples/api/snapshot.lua b/examples/api/snapshot.lua index 7a699776..10b50506 100644 --- a/examples/api/snapshot.lua +++ b/examples/api/snapshot.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local server = owned.server must(server :new_session({ diff --git a/examples/api/start_server.lua b/examples/api/start_server.lua index 09f3c68c..fe953fec 100644 --- a/examples/api/start_server.lua +++ b/examples/api/start_server.lua @@ -7,12 +7,9 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) -- The server is private: its own directory, socket and environment. - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local server = owned.server local before = must(server:snapshot():await()) diff --git a/examples/api/unsupported_version.lua b/examples/api/unsupported_version.lua index b5473e3a..2e15e3c1 100644 --- a/examples/api/unsupported_version.lua +++ b/examples/api/unsupported_version.lua @@ -9,9 +9,6 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - -- A stand-in for a tmux 3.1 server: a Lua script that answers the version -- check with the usage error that release prints, so the refusal needs no old -- tmux build. Its first line runs it with the interpreter running this program. @@ -26,7 +23,7 @@ assert(uv.fs_chmod(stand_in, 448)) local ok, failure = pcall(function() must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local target = { binary = stand_in, socket_path = owned.socket_path } local server, err = runtime:connect(target):await() assert(server == nil, "a tmux before 3.2 was accepted") diff --git a/examples/api/wait_for_text.lua b/examples/api/wait_for_text.lua index dbdd902f..7afe937c 100644 --- a/examples/api/wait_for_text.lua +++ b/examples/api/wait_for_text.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local session = { name = "demo", argv = { "/bin/sh" } } local created = must(owned.server:new_session(session):await()) local pane = created.pane diff --git a/examples/api/watch_pane.lua b/examples/api/watch_pane.lua index 53dfc9fb..1d0c0ee9 100644 --- a/examples/api/watch_pane.lua +++ b/examples/api/watch_pane.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local created = must(owned.server :new_session({ name = "demo", diff --git a/examples/api/with_server.lua b/examples/api/with_server.lua index 12baa68f..a994743b 100644 --- a/examples/api/with_server.lua +++ b/examples/api/with_server.lua @@ -7,13 +7,10 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) -- The server stops when the body returns, fails or raises. local count = must(runtime - :with_server({ binary = binary }, function(server) + :with_server({}, function(server) local session = { name = "demo", argv = { "/bin/cat" } } must(server:new_session(session):await()) local snapshot = must(server:snapshot():await()) diff --git a/examples/nvim_snapshot.lua b/examples/nvim_snapshot.lua index 8c480feb..99b53121 100644 --- a/examples/nvim_snapshot.lua +++ b/examples/nvim_snapshot.lua @@ -1,8 +1,7 @@ local adapter = require("libtmux.runtime.nvim") return adapter.start(function(runtime) - local binary = vim.fn.exepath("tmux") - local owned, err = runtime:start_server({ binary = binary }):await() + local owned, err = runtime:start_server():await() if not owned then return nil, err end diff --git a/examples/quickstart.lua b/examples/quickstart.lua index 0d2bc3fb..87f14ab2 100644 --- a/examples/quickstart.lua +++ b/examples/quickstart.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - local result = must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local server = owned.server -- docs:begin main diff --git a/examples/snapshot.lua b/examples/snapshot.lua index 45ca5541..cf61db1d 100644 --- a/examples/snapshot.lua +++ b/examples/snapshot.lua @@ -7,11 +7,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local server = owned.server must(server:new_session({ name = "demo", argv = { "/bin/cat" } }):await()) local snapshot = must(server:snapshot({ strict = true }):await()) diff --git a/lua/libtmux/README.md b/lua/libtmux/README.md index eece465f..4a20be90 100644 --- a/lua/libtmux/README.md +++ b/lua/libtmux/README.md @@ -110,11 +110,8 @@ local function must(value, err) return value end --- tmux is /usr/bin/tmux unless TMUX_BIN names another absolute path. -local binary = os.getenv("TMUX_BIN") or "/usr/bin/tmux" - must(adapter.run(function(runtime) - local owned = must(runtime:start_server({ binary = binary }):await()) + local owned = must(runtime:start_server():await()) local created = must(owned.server :new_session({ name = "demo", @@ -156,8 +153,7 @@ session and shows the pane count: local adapter = require("libtmux.runtime.nvim") return adapter.start(function(runtime) - local binary = vim.fn.exepath("tmux") - local owned, err = runtime:start_server({ binary = binary }):await() + local owned, err = runtime:start_server():await() if not owned then return nil, err end diff --git a/lua/libtmux/_internal/endpoint.lua b/lua/libtmux/_internal/endpoint.lua index 52aaa5ce..65174bc7 100644 --- a/lua/libtmux/_internal/endpoint.lua +++ b/lua/libtmux/_internal/endpoint.lua @@ -33,7 +33,7 @@ local function absolute(value) and not value:find("\000", 1, true) end -local function options_copy(options) +local function options_copy(options, captured) if not plain(options) then return nil, failure("invalid_endpoint", "endpoint options must be a plain table") end @@ -47,7 +47,7 @@ local function options_copy(options) end copied[key] = value end - if not copied.binary then + if copied.binary == nil and not captured then return nil, failure("invalid_endpoint", "endpoint needs an explicit executable path") end if copied.socket and copied.socket:sub(-1) == "/" then @@ -111,8 +111,114 @@ local function native(uv, method, args, callback) end) if not called and (not ok or not result) then called = true - callback(ok and err or result) + callback(ok and err or result, nil, true) end + if not called then + return result + end +end + +---@class libtmux._internal.ExecutableSearch +---@field path string +---@field cwd? string +---@field cwd_error? string + +--- Record the caller's search context before another task can change it. +---@return libtmux._internal.ExecutableSearch +function M.capture_executable(runtime) + local uv = runtime._driver.uv + local cwd, cause + if uv and uv.cwd then + cwd, cause = uv.cwd() + end + return { path = os.getenv("PATH") or "/usr/bin:/bin", cwd = cwd, cwd_error = cause } +end + +local function lookup_failure(code, message, operation, cause) + return errors.new(code, message, { operation = operation, effect = "not_sent", cause = cause }) +end + +local function inspect_executable(runtime, operation, path, method, ...) + local uv, args = runtime._driver.uv, { path, ... } + return runtime + :_request({ + bytes = #path, + operation = operation, + effect = "not_sent", + start = function(settle, retire) + local pending = native(uv, method, args, function(err, value, failed_to_start) + if failed_to_start then + settle( + nil, + lookup_failure( + "filesystem_error", + "cannot inspect tmux executable", + operation, + err + ) + ) + else + settle(not err and value or false) + end + retire() + end) + if pending and uv.cancel then + -- The native callback retires the request even if cancellation loses the race. + return function() + pcall(uv.cancel, pending) + end + end + end, + }) + :await() +end + +local function child_path(directory, name) + return directory .. (directory:sub(-1) == "/" and "" or "/") .. name +end + +--- Search one candidate at a time. stat follows links and access checks executability. +---@param captured libtmux._internal.ExecutableSearch +---@param operation string +---@return string?, libtmux.Error? +function M.find_executable(runtime, captured, operation) + local uv = runtime._driver.uv + if not (uv and uv.fs_stat and uv.fs_access) then + return nil, + lookup_failure("unsupported", "runtime cannot look up tmux executables", operation) + end + for entry in (captured.path .. ":"):gmatch("(.-):") do + local directory = entry + if entry:sub(1, 1) ~= "/" then + if not captured.cwd then + return nil, + lookup_failure( + "invalid_endpoint", + "cannot resolve a relative PATH entry", + operation, + captured.cwd_error + ) + end + directory = entry == "" and captured.cwd or child_path(captured.cwd, entry) + end + local candidate = child_path(directory, "tmux") + local stat, err = inspect_executable(runtime, operation, candidate, "fs_stat") + if err then + return nil, err + end + if stat and stat.type == "file" then + local accepted + accepted, err = inspect_executable(runtime, operation, candidate, "fs_access", "X") + if err then + return nil, err + end + if accepted then + return candidate + end + end + end + return nil, + lookup_failure("invalid_endpoint", "cannot find an executable tmux on PATH", operation) end local cleanup @@ -551,11 +657,17 @@ local function pin(state) end ---@param getenv? fun(name: string): string? Reads the process environment; tests replace it. -function M.bind(runtime, options, getenv) - local copied, validation_error = options_copy(options) +---@param context? {operation: string, executable?: libtmux._internal.ExecutableSearch} +function M.bind(runtime, options, getenv, context) + local captured = context and context.executable + local operation_name = context and context.operation or "endpoint.bind" + local copied, validation_error = options_copy(options, captured) if copied then copied, validation_error = choose_socket(copied, getenv or os.getenv) end + if context and validation_error then + validation_error.operation = operation_name + end local state = { runtime = runtime, uv = runtime._driver.uv, @@ -569,8 +681,20 @@ function M.bind(runtime, options, getenv) if not copied then return nil, validation_error end - if not state.uv then - return nil, failure("unsupported", "endpoint requires asynchronous filesystem support") + local binary = copied.binary + if captured then + local err + binary, err = M.find_executable(rt, captured, operation_name) + if not binary then + return nil, err + end + elseif not state.uv then + return nil, + lookup_failure( + "unsupported", + "endpoint requires asynchronous filesystem support", + operation_name + ) end local lease, err = rt:_resource(function(done) invalidate(state, "endpoint resource closed", "endpoint_closed") @@ -589,7 +713,7 @@ function M.bind(runtime, options, getenv) end end state.endpoint = { - binary = copied.binary, + binary = binary, socket = state.alias, name = copied.name, config = copied.config, @@ -616,7 +740,7 @@ function M.bind(runtime, options, getenv) }) bindings[bound], state.bound = state, true return bound - end, { operation = "endpoint.bind", effect = "not_sent" }) + end, { operation = operation_name, effect = "not_sent" }) request:_on_retire(function() if state.lease and not state.bound then state.lease:close() diff --git a/lua/libtmux/_internal/runtime.lua b/lua/libtmux/_internal/runtime.lua index 07833abd..b8747180 100644 --- a/lua/libtmux/_internal/runtime.lua +++ b/lua/libtmux/_internal/runtime.lua @@ -1052,6 +1052,14 @@ function Runtime:stats() } end +function Runtime:find_tmux() + local endpoints = require("libtmux._internal.endpoint") + local captured = endpoints.capture_executable(self) + return self:_operation(function(runtime) + return endpoints.find_executable(runtime, captured, "find_tmux") + end, { operation = "find_tmux", effect = "not_sent" }) +end + function Runtime:connect(options) return require("libtmux._internal.server").connect(self, options) end @@ -1100,14 +1108,16 @@ end ---@field dispatch_budget? integer ---@class libtmux.Runtime +--- Finds the first executable tmux on the caller's PATH without starting a process. +---@field find_tmux fun(self:libtmux.Runtime):libtmux.Request ---@field connect fun(self:libtmux.Runtime, ---- options:libtmux.ConnectOptions):libtmux.Request +--- options?:libtmux.ConnectOptions):libtmux.Request --- Starts a private tmux server and resolves to the `libtmux.OwnedServer` that owns it. ---@field start_server fun(self:libtmux.Runtime, ---- options:libtmux.StartServerOptions):libtmux.Request +--- options?:libtmux.StartServerOptions):libtmux.Request --- Starts a private server, runs `body(server, owned)` and stops the server --- however the body ends. The request resolves to what the body returns. ----@field with_server fun(self:libtmux.Runtime, options:libtmux.StartServerOptions, +---@field with_server fun(self:libtmux.Runtime, options:libtmux.StartServerOptions?, --- body:fun(server:libtmux.Server, owned:libtmux.OwnedServer):T?, --- libtmux.Error?):libtmux.Request ---@field spawn fun(self:libtmux.Runtime, diff --git a/lua/libtmux/_internal/server.lua b/lua/libtmux/_internal/server.lua index 6300467f..a39fd484 100644 --- a/lua/libtmux/_internal/server.lua +++ b/lua/libtmux/_internal/server.lua @@ -40,15 +40,20 @@ local function integer(value, maximum) return type(value) == "number" and value >= 1 and value <= maximum and value % 1 == 0 end +local function invalid_connection(message) + return errors.new("invalid_options", message, { operation = "connect", effect = "not_sent" }) +end + local function connection_options(options) + options = options == nil and {} or options if not plain(options) then - return nil, failure("invalid_options", "connection options must be a plain record") + return nil, invalid_connection("connection options must be a plain record") end local copied, mapping = {}, { binary = "binary", socket_path = "socket", config_path = "config" } for key, value in next, options do if not mapping[key] then - return nil, failure("invalid_options", "unknown connection option") + return nil, invalid_connection("unknown connection option") end copied[mapping[key]] = value end @@ -516,12 +521,16 @@ end function M.connect(runtime, options) local copied, validation_error = connection_options(options) + local context = { operation = "connect" } + if copied and copied.binary == nil then + context.executable = endpoints.capture_executable(runtime) + end local binding local request = runtime:_operation(function(rt) if not copied then return nil, validation_error end - binding = endpoints.bind(rt, copied) + binding = endpoints.bind(rt, copied, nil, context) local bound, err = binding:await() if not bound then return nil, err @@ -587,7 +596,8 @@ local NO_LISTENER = { ECONNREFUSED = true, ENOENT = true, ENOTSOCK = true } local function start_failure(code, message, details) details = details or {} - details.operation, details.effect = "start_server", details.effect or "not_sent" + details.operation = details.operation or "start_server" + details.effect = details.effect or "not_sent" return errors.new(code, message, details) end @@ -628,6 +638,7 @@ local function environment_overlay(overlay) end local function start_options(options) + options = options == nil and {} or options if not plain(options) then return nil, start_failure("invalid_options", "start options must be a plain record") end @@ -638,7 +649,7 @@ local function start_options(options) return nil, start_failure("invalid_options", "unknown start option") end end - if not absolute_path(options.binary) then + if options.binary ~= nil and not absolute_path(options.binary) then return nil, start_failure("invalid_endpoint", "start needs an absolute tmux executable path") end @@ -672,7 +683,7 @@ local function socket_path_limit(uv) return (uname and BSD_SYSTEMS[uname.sysname] or not uname) and 103 or 107 end -local function choose_root(uv, requested) +local function choose_root(uv, requested, operation) local limit = socket_path_limit(uv) local function needed(root) return #root + #DIRECTORY_TEMPLATE + endpoints.PIN_BYTES @@ -688,7 +699,8 @@ local function choose_root(uv, requested) ( "root leaves no room for a socket path: the longest path under it " .. "has %d bytes, and the platform allows %d" - ):format(needed(requested), limit) + ):format(needed(requested), limit), + { operation = operation } ) end return requested @@ -705,7 +717,9 @@ local function choose_root(uv, requested) end end return nil, - start_failure("invalid_endpoint", "no temporary directory leaves room for a socket path") + start_failure("invalid_endpoint", "no temporary directory leaves room for a socket path", { + operation = operation, + }) end -- The caller's environment, less what selects another server, plus the overlay. @@ -1058,120 +1072,154 @@ local function scope_guard(state) return guard end ----@param options libtmux.StartServerOptions ----@return libtmux.Request -function M.start(runtime, options) - local copied, validation_error = start_options(options) - return runtime:_operation(function(rt, operation) - if not copied then - return nil, validation_error +local function prepare_start(runtime, options, operation) + local copied, err = start_options(options) + if copied then + if copied.binary == nil then + copied.executable = endpoints.capture_executable(runtime) end - local uv = rt._driver.uv - local root, err = choose_root(uv, copied.root) - if not root then + elseif err then + err.operation = operation + end + return copied, err +end + +local function start(rt, operation, copied, validation_error, operation_name) + if not copied then + return nil, validation_error + end + local binary = copied.binary + if copied.executable then + local err + binary, err = endpoints.find_executable(rt, copied.executable, operation_name) + if not binary then return nil, err end - if not (uv and uv.fs_mkdtemp and uv.os_environ and uv.spawn and uv.new_pipe) then - return nil, - start_failure( - "unsupported", - "start_server needs a driver with filesystem and process support" - ) - end - local env = inherited_environment(uv, copied.environment) - local directory, cause = uv.fs_mkdtemp(root .. DIRECTORY_TEMPLATE) - if not directory then - return nil, - start_failure( - "filesystem_error", - "cannot create the private directory", - { cause = cause } - ) - end - env[#env + 1] = "TMUX_TMPDIR=" .. directory - local state = { - runtime = rt, - uv = uv, - driver = rt._driver, - binary = copied.binary, - config = copied.config, - timeout = copied.timeout, - directory = directory, - socket = directory .. "/tmux.sock", - env = env, - waiters = {}, - } - state.lease, err = rt:_resource(function(done) - stop(state, function(stopped) - if stopped ~= nil and stopped == state.final and state.final_reported then - stopped = nil - end - done(stopped) - end) + end + local uv = rt._driver.uv + local root, err = choose_root(uv, copied.root, operation_name) + if not root then + return nil, err + end + if not (uv and uv.fs_mkdtemp and uv.os_environ and uv.spawn and uv.new_pipe) then + return nil, + start_failure( + "unsupported", + operation_name .. " needs a driver with filesystem and process support", + { operation = operation_name } + ) + end + local env = inherited_environment(uv, copied.environment) + local directory, cause = uv.fs_mkdtemp(root .. DIRECTORY_TEMPLATE) + if not directory then + return nil, + start_failure( + "filesystem_error", + "cannot create the private directory", + { operation = operation_name, cause = cause } + ) + end + env[#env + 1] = "TMUX_TMPDIR=" .. directory + local state = { + runtime = rt, + uv = uv, + driver = rt._driver, + binary = binary, + config = copied.config, + timeout = copied.timeout, + directory = directory, + socket = directory .. "/tmux.sock", + env = env, + waiters = {}, + } + state.lease, err = rt:_resource(function(done) + stop(state, function(stopped) + if stopped ~= nil and stopped == state.final and state.final_reported then + stopped = nil + end + done(stopped) end) - if not state.lease then - remove_tree(uv, directory) + end) + if not state.lease then + remove_tree(uv, directory) + return nil, err + end + local guard = scope_guard(state) + guard.ready() + local function fail(reason) + state.final_reported = true + stop_request(state):await() + guard.release() + return nil, reason + end + operation:_set_effect("unknown") + local started, started_error = command + .group(rt, { binary = state.binary, socket = state.socket, config = state.config }, { + { "start-server" }, + { "set-option", "-s", "exit-empty", "off" }, + }, { timeout = state.timeout, env = state.env }) + :await() + if not started then + return fail(start_failure("start_failed", "tmux did not start a server", { + operation = operation_name, + effect = started_error.effect, + cause = started_error, + })) + end + local server, connect_error = M.connect(rt, { + binary = state.binary, + socket_path = state.socket, + config_path = state.config, + }):await() + if not server then + return fail(connect_error) + end + state.server = server + local owned = setmetatable({ server = server, socket_path = state.socket }, { + __index = Owned, + __metatable = "libtmux.OwnedServer", + }) + owned_servers[owned] = state + return { owned = owned, guard = guard } +end + +---@param options? libtmux.StartServerOptions +---@return libtmux.Request +function M.start(runtime, options) + local copied, validation_error = prepare_start(runtime, options, "start_server") + return runtime:_operation(function(rt, operation) + local started, err = start(rt, operation, copied, validation_error, "start_server") + if not started then return nil, err end - local guard = scope_guard(state) - guard.ready() - local function fail(reason) - state.final_reported = true - stop_request(state):await() - guard.release() - return nil, reason - end - operation:_set_effect("unknown") - local started, started_error = command - .group(rt, { binary = state.binary, socket = state.socket, config = state.config }, { - { "start-server" }, - { "set-option", "-s", "exit-empty", "off" }, - }, { timeout = state.timeout, env = state.env }) - :await() - if not started then - return fail(start_failure("start_failed", "tmux did not start a server", { - effect = started_error.effect, - cause = started_error, - })) - end - local server, connect_error = M.connect(rt, { - binary = state.binary, - socket_path = state.socket, - config_path = state.config, - }):await() - if not server then - return fail(connect_error) - end - state.server = server - guard.release() - local owned = setmetatable({ server = server, socket_path = state.socket }, { - __index = Owned, - __metatable = "libtmux.OwnedServer", - }) - owned_servers[owned] = state - return owned + started.guard.release() + return started.owned end, { operation = "start_server", effect = "not_sent" }) end ----@param options libtmux.StartServerOptions +---@param options? libtmux.StartServerOptions ---@param body fun(server:libtmux.Server, owned:libtmux.OwnedServer):unknown?, libtmux.Error? ---@return libtmux.Request function M.scoped(runtime, options, body) - return runtime:_operation(function(rt) + local copied, validation_error = prepare_start(runtime, options, "with_server") + return runtime:_operation(function(rt, operation) if type(body) ~= "function" then - return nil, start_failure("invalid_callback", "with_server needs a body function") + return nil, + errors.new("invalid_callback", "with_server needs a body function", { + operation = "with_server", + effect = "not_sent", + }) end - local owned, err = M.start(rt, options):await() - if not owned then + local started, err = start(rt, operation, copied, validation_error, "with_server") + if not started then return nil, err end - local guard = scope_guard(owned_servers[owned]) - guard.ready() + local owned = started.owned -- The body runs in this task, so it may await. A raised error cancels the -- task, and the guard stops the server on the way out. local value, body_error = body(owned.server, owned) local _, stop_error = owned:stop():await() - guard.release() + started.guard.release() if body_error ~= nil then return nil, body_error end @@ -1188,7 +1236,8 @@ end --- Options for `libtmux.Runtime:start_server`. --- ---- `binary` is the only required field. The server lives in a fresh directory +--- When `binary` is omitted, the runtime looks for tmux on the caller's PATH. +--- The server lives in a fresh directory --- under `root`, with its socket inside, so `root` plus about 45 bytes must fit --- a socket path (`sun_path`: 107 bytes on Linux, 103 on macOS and the BSDs); --- a longer root fails with `invalid_endpoint` before anything is created. The @@ -1200,7 +1249,7 @@ end --- set those names or `TMUX_TMPDIR`. The daemon runs with `exit-empty off`, so --- it stays up with no session. ---@class libtmux.StartServerOptions ----@field binary string Absolute tmux executable path. +---@field binary? string Absolute tmux executable path. Defaults to lookup on PATH. --- Absolute configuration path. Defaults to `/dev/null`, which loads none. ---@field config? string --- Absolute directory that holds the private one. Defaults to the system @@ -1256,7 +1305,7 @@ end --- daemon's pid, start time and release. A socket name or tmux's own choice has --- no path to pin, so that check is the only identity there. ---@class libtmux.ConnectOptions ----@field binary string Absolute tmux executable path. +---@field binary? string Absolute tmux executable path. Defaults to lookup on PATH. ---@field socket_path? string Absolute existing daemon socket path. ---@field config_path? string Absolute configuration path. @@ -1310,8 +1359,8 @@ end --- A tmux server does a great many things, so this class has a great many --- methods. They fall into a few groups: --- ---- **Connecting.** `libtmux.Runtime:connect` takes `libtmux.ConnectOptions`: an ---- absolute path to the tmux binary and, optionally, to the daemon's socket. +--- **Connecting.** `libtmux.Runtime:connect` takes `libtmux.ConnectOptions` +--- with optional absolute paths to the tmux binary and the daemon's socket. --- `Server:close` closes the connections the handle owns. `Server:observe` --- takes a session handle and resolves to a `libtmux.Observation`, a --- control-mode view of that session whose watches report pane output, diff --git a/scripts/package/README.md b/scripts/package/README.md index 697a1625..da761732 100644 --- a/scripts/package/README.md +++ b/scripts/package/README.md @@ -12,8 +12,13 @@ The development build copies every file under `lua/`. In a Git checkout, a release rockspec must list the tracked and unignored Lua modules that go into the source rock. Leave ignored scratch modules out of that list. -The `package` gate of [check.lua](../check/README.md) runs this check. Set -`LIBTMUX_TEST_TMUX` to select the tmux binary. `TMUX_BIN` is the fallback. +The `package` gate of [check.lua](../check/README.md) runs this check. + +## Run it + +`LIBTMUX_TEST_TMUX` selects the tmux the examples use (`TMUX_BIN` is accepted as +a fallback). The selected executable comes first on `PATH` for the +installed examples. ```console $ luajit scripts/package/main.lua --lua lua diff --git a/scripts/package/package.lua b/scripts/package/package.lua index a0dbebd5..1b22ce2d 100644 --- a/scripts/package/package.lua +++ b/scripts/package/package.lua @@ -9,7 +9,9 @@ local release = require("release.release") local repo = require("support.repo") local runtime = require("support.runtime") local sandbox = require("tests.support.sandbox") +local sandbox_host = require("tests.support.sandbox_host") local shell = require("support.shell") +local uv = require("support.uv") local M = {} @@ -282,15 +284,40 @@ function M.import_installed(name, prefix, version, lua, opts, source_version) end end ---- Runs the installed snapshot and quickstart examples, each on a private server of its own. -function M.live_example(prefix, version, lua, opts) - local temporary = fs.mkdtemp("libtmux-lua-live-") +local function with_live_examples(prefix, version, opts, body) local binary = M.tmux_binary() - local child = with_env(opts, installed_paths(prefix, version)) - child.env.TMPDIR = temporary - child.env.LIBTMUX_TEST_TMUX = binary - child.env.TMUX_BIN = binary + local directory = fs.mkdtemp(sandbox.PREFIX) local ok, failure = pcall(function() + local bin, servers = directory .. "/bin", directory .. "/servers" + fs.mkdir_p(bin) + fs.mkdir_p(servers) + assert(uv.fs_symlink(binary, bin .. "/tmux")) + + local child = with_env(opts, installed_paths(prefix, version)) + child.env.PATH = bin .. ":" .. (child.env.PATH or os.getenv("PATH") or "") + child.env.TMPDIR = servers + child.env.LIBTMUX_TEST_TMUX = binary + child.env.TMUX_BIN = nil + child.unset = { unpack(child.unset or {}) } + child.unset[#child.unset + 1] = "TMUX_BIN" + body(child, servers, binary) + end) + local released = sandbox_host.release(directory, binary) + if #released.leaked > 0 then + local message = sandbox_host.describe(released, directory) + if not ok then + message = message .. "\n" .. tostring(failure) + end + refuse(message) + end + if not ok then + error(failure, 0) + end +end + +--- Runs the installed snapshot and quickstart examples, each on a private server of its own. +function M.live_example(prefix, version, lua, opts) + with_live_examples(prefix, version, opts, function(child, temporary) local snapshot = run({ lua, "snapshot.lua" }, child) if snapshot ~= "%0\t@0\n" then refuse("installed snapshot example returned unexpected output") @@ -303,10 +330,6 @@ function M.live_example(prefix, version, lua, opts) refuse("installed examples left a private server directory") end end) - fs.remove_tree(temporary) - if not ok then - error(failure, 0) - end print("PASS installed public snapshot/quickstart examples and private-server cleanup") end @@ -326,18 +349,10 @@ function M.complete_api_examples(prefix, version, lua, cwd, opts) local manifest = api_examples.load_examples(ROOT) local directory = cwd .. "/complete-api-examples" fs.mkdir_p(directory) - -- Each program starts a private server under TMPDIR; its directory and socket alias must fit - -- sun_path. - local temporary = fs.mkdtemp("libtmux-lua-api-check-") - local binary = M.tmux_binary() - local child = with_env(opts, installed_paths(prefix, version)) - child.cwd = directory - child.env.TMPDIR = temporary - child.env.LIBTMUX_TEST_TMUX = binary - child.env.TMUX_BIN = binary - local major, minor = M.tmux_release(binary) local ran = 0 - local ok, failure = pcall(function() + with_live_examples(prefix, version, opts, function(child, temporary, binary) + child.cwd = directory + local major, minor = M.tmux_release(binary) -- Input can reach the terminal before the interactive shell draws its prompt. local startup = directory .. "/capture-startup" files.write(startup, "sleep 0.2\nPS1='capture-prompt> '\n") @@ -410,10 +425,6 @@ function M.complete_api_examples(prefix, version, lua, cwd, opts) end end end) - fs.remove_tree(temporary) - if not ok then - error(failure, 0) - end print(("PASS %d complete API programs and import/runtime failure cleanup"):format(ran)) end diff --git a/tests/integration/path_discovery.lua b/tests/integration/path_discovery.lua new file mode 100644 index 00000000..dbabc12e --- /dev/null +++ b/tests/integration/path_discovery.lua @@ -0,0 +1,218 @@ +local host = rawget(_G, "vim") +local adapter = require(host and "libtmux.runtime.nvim" or "libtmux.runtime.luv") +---@diagnostic disable-next-line: different-requires +local uv = host and (host.uv or host.loop) or require("luv") +local mode = assert(os.getenv("LIBTMUX_PATH_CASE")) +local directory = assert(os.getenv("LIBTMUX_PATH_DIRECTORY")) +local binary = directory .. "/bin/tmux" +local real = assert(os.getenv("LIBTMUX_TEST_TMUX")) + +local function must(value, err) + assert(value, tostring(err)) + return value +end + +-- Change both inputs before the operation can start. +local function submitted(submit) + local cwd = assert(uv.cwd()) + assert(uv.chdir(directory)) + assert(uv.os_setenv("PATH", "directory:no-execute:bin")) + local request = submit() + assert(uv.chdir(cwd)) + assert(uv.os_setenv("PATH", directory .. "/missing")) + return request +end + +local function refused(request, code, operation, effect) + local value, err = request:await() + assert(value == nil and err, "expected an error from " .. operation) + assert(err.code == code, tostring(err)) + assert(err.operation == operation, "unexpected operation " .. tostring(err.operation)) + assert(err.effect == effect, "unexpected effect " .. tostring(err.effect)) +end + +local function count_selected() + local spawn, calls = uv.spawn, 0 + uv.spawn = function(path, ...) + if path == binary then + calls = calls + 1 + end + return spawn(path, ...) + end + return function() + uv.spawn = spawn + assert(calls > 0, "the captured executable was never used") + end +end + +local cases = {} + +function cases.lookup(rt) + assert(type(rt.find_tmux) == "function", "the runtime has no public tmux lookup") + local found = submitted(function() + return rt:find_tmux() + end) + assert(must(found:await()) == binary) + local cwd = assert(uv.cwd()) + assert(uv.chdir(directory .. "/bin")) + assert(uv.os_setenv("PATH", "")) + local local_tmux = rt:find_tmux() + assert(uv.chdir(cwd)) + assert(uv.os_setenv("PATH", directory .. "/missing")) + assert(must(local_tmux:await()) == binary) +end + +function cases.start(rt) + local observed = count_selected() + local request = submitted(function() + return rt:start_server() + end) + local owned = must(request:await()) + must(owned:stop():await()) + observed() +end + +function cases.connect(rt) + local owned = must(rt:start_server({ binary = real }):await()) + local observed = count_selected() + local options = { socket_path = owned.socket_path } + local request = submitted(function() + return rt:connect(options) + end) + options.binary = "tmux" + local server = must(request:await()) + must(server:close():await()) + observed() + must(owned:stop():await()) +end + +function cases.scope(rt) + local observed = count_selected() + local options = {} + local socket + local request = submitted(function() + return rt:with_server(options, function(server, owned) + socket = owned.socket_path + return must(server:snapshot():await()).sessions + end) + end) + options.binary = "tmux" + assert(#must(request:await()) == 0) + assert(socket and uv.fs_stat(socket) == nil, "the scope left its socket") + observed() +end + +function cases.errors(rt) + assert(uv.os_setenv("PATH", directory .. "/missing")) + local spawn = uv.spawn + uv.spawn = function() + error("binary selection failure tried to send a tmux command", 0) + end + refused(rt:start_server({}), "invalid_endpoint", "start_server", "not_sent") + refused( + rt:with_server({}, function() + error("missing executable entered the body", 0) + end), + "invalid_endpoint", + "with_server", + "not_sent" + ) + refused(rt:connect({}), "invalid_endpoint", "connect", "not_sent") + refused(rt:find_tmux(), "invalid_endpoint", "find_tmux", "not_sent") + refused(rt:connect(false), "invalid_options", "connect", "not_sent") + refused(rt:start_server({ binary = "tmux" }), "invalid_endpoint", "start_server", "not_sent") + refused(rt:connect({ binary = "tmux" }), "invalid_endpoint", "connect", "not_sent") + refused( + rt:with_server({ binary = "tmux" }, function() end), + "invalid_endpoint", + "with_server", + "not_sent" + ) + uv.spawn = spawn + local owned = must(rt:start_server({ binary = real }):await()) + local peer = must(rt:connect({ binary = real, socket_path = owned.socket_path }):await()) + must(peer:close():await()) + must(owned:stop():await()) +end + +function cases.cancel_lookup(rt) + local spawn, stat = uv.spawn, uv.fs_stat + uv.spawn = function() + error("cancelled lookup tried to send a tmux command", 0) + end + local function cancel(operation, submit) + local request, seen + uv.fs_stat = function(path, callback) + if path ~= binary then + return stat(path, callback) + end + assert(type(callback) == "function", "executable search blocked on stat") + return stat(path, function(err, value) + seen = true + assert(request:cancel()) + callback(err, value) + end) + end + request = submitted(submit) + refused(request, "cancelled", operation, "not_sent") + uv.fs_stat = stat + assert(seen, "no native lookup was cancelled") + end + cancel("start_server", function() + return rt:start_server({}) + end) + cancel("with_server", function() + return rt:with_server({}, function() + error("cancelled lookup entered the body", 0) + end) + end) + cancel("connect", function() + return rt:connect({}) + end) + cancel("find_tmux", function() + return rt:find_tmux() + end) + uv.spawn = spawn +end + +function cases.cancel_started(rt) + local spawn = uv.spawn + local request, saw_start + uv.spawn = function(path, options, callback) + for _, argument in ipairs(options.args or {}) do + if argument == "start-server" then + return spawn(path, options, function(code, signal) + callback(code, signal) + saw_start = code == 0 + assert(request:cancel()) + end) + end + end + return spawn(path, options, callback) + end + request = rt:with_server({ binary = real }, function() + error("cancelled startup entered the body", 0) + end) + refused(request, "cancelled", "with_server", "unknown") + uv.spawn = spawn + assert(saw_start, "tmux did not complete the startup command") +end + +local function work(runtime) + assert(cases[mode])(runtime) + return mode .. " passed" +end + +if host then + adapter.start(work, function(value, err) + if err then + io.stderr:write(tostring(err), "\n") + host.cmd("cquit 1") + else + io.stdout:write(value, "\n") + host.cmd("qa!") + end + end) +else + print(must(adapter.run(work))) +end diff --git a/tests/integration/test_path_discovery.lua b/tests/integration/test_path_discovery.lua new file mode 100644 index 00000000..f41c9b3a --- /dev/null +++ b/tests/integration/test_path_discovery.lua @@ -0,0 +1,46 @@ +-- Run the public executable lookup and its callers on both host loops. +local test = require("luaunit") +local files = require("support.files") +local fixture = require("tests.support.fixture") +local fs = require("support.fs") +local sandbox = require("tests.support.sandbox") +local uv = require("support.uv") +local M = {} + +local directory + +function M.setUp() + directory = fs.mkdtemp("libtmux-lua-path-") + for _, name in ipairs({ "directory/tmux", "no-execute", "bin" }) do + fs.mkdir_p(directory .. "/" .. name) + end + local regular = directory .. "/no-execute/tmux" + files.write(regular, "") + assert(uv.fs_chmod(regular, 420)) + local binary = fixture.tmux() + assert(uv.fs_symlink(binary, directory .. "/bin/tmux")) +end + +function M.tearDown() + fs.remove_tree(directory) +end + +local function register(name, case) + fixture.each_host(M, name, function(host) + local result = fixture.program(host, "path_discovery", { + LIBTMUX_PATH_CASE = case, + LIBTMUX_PATH_DIRECTORY = directory, + TMPDIR = assert(os.getenv(sandbox.MARKER)), + }) + test.assertEquals(result.stdout, case .. " passed\n") + end) +end + +register("lookup_captures_path_and_cwd_and_skips_nonexecutables", "lookup") +register("start_uses_the_captured_executable", "start") +register("connect_uses_the_captured_executable", "connect") +register("scope_uses_the_captured_executable_and_stops_the_server", "scope") +register("missing_and_relative_executables_name_the_public_operation", "errors") +register("cancellation_during_executable_lookup_sends_nothing", "cancel_lookup") +register("cancellation_after_scoped_start_reports_an_unknown_effect", "cancel_started") +return M diff --git a/tests/integration/test_runtime.lua b/tests/integration/test_runtime.lua index 1ada6a2a..2d8e0ccd 100644 --- a/tests/integration/test_runtime.lua +++ b/tests/integration/test_runtime.lua @@ -61,7 +61,7 @@ function M.test_neovim_example_starts_its_own_server_and_reports_the_pane_count( local bin = fs.mkdtemp("libtmux-lua-") local binary = fixture.tmux() local ok, failure = pcall(function() - -- The example finds tmux with exepath, so name the selected build "tmux" on PATH. + -- Put the selected build on the PATH the example inherits. assert(uv.fs_symlink(binary, bin .. "/tmux")) local env = nvim_environment({ TMPDIR = root, PATH = bin .. ":" .. (os.getenv("PATH") or "") }) diff --git a/tests/unit/owned_server.lua b/tests/unit/owned_server.lua index 88534534..8c01ec15 100644 --- a/tests/unit/owned_server.lua +++ b/tests/unit/owned_server.lua @@ -58,9 +58,8 @@ function M.test_rejects_malformed_options_before_any_effect() local f = fixture() f.run(function(rt) for _, case in ipairs({ - { nil, "invalid_options" }, { false, "invalid_options" }, - { {}, "invalid_endpoint" }, + { { binary = false }, "invalid_endpoint" }, { { binary = "tmux" }, "invalid_endpoint" }, { { binary = "/bin/tmux", config = "relative" }, "invalid_endpoint" }, { { binary = "/bin/tmux", root = "relative" }, "invalid_endpoint" }, From 7651143da86f897f3e4d7ae274ba54eef63eeb3f Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 11:59:34 -0600 Subject: [PATCH 2/2] Changelog: Let Lua callers select tmux from PATH why: A caller starting a tmux server should be able to use the executable on its PATH and still select an exact binary when needed. what: - Record the change under Unreleased. --- CHANGES.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index efaeef5b..8b42e02f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -15,10 +15,13 @@ Notable changes to `libtmux`. its body returns, fails or is cancelled. (#103) - Runtime: `Runtime:with_server(options, body)` runs the body on a private server and stops it however the body ends. (#103) +- Runtime requests find tmux on the caller's `PATH` when `binary` is omitted. + Pass an absolute `binary` to select another build. `Runtime:find_tmux` + returns the discovered path as a Request. (#109) - Examples: each program starts and stops its own server, so `examples/api/run.sh`, which needed `sh` and `perl`, is removed. Run a program - with `lua examples/api/connect.lua`; `TMUX_BIN` still selects another tmux, - and `TMUX_SOCKET` is no longer read. (#103) + with `lua examples/api/connect.lua`. The programs find tmux on `PATH` + and no longer read `TMUX_SOCKET`. (#103, #109) - Docs: the README shows `Pane:resize` and `Window:resize` with a new tested program, `examples/api/resize.lua`, and links the kill, option and hook methods.