diff --git a/CHANGES.md b/CHANGES.md index fcf7148..460ce19 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -4,6 +4,9 @@ Notable changes to `libtmux`. ## Unreleased +- Docs: the README starts with a calculator in a private tmux pane. Run it + from standalone Lua or Neovim and read the reply over control mode. + - Runtime: `Runtime:start_server` starts a private tmux server and resolves to an `OwnedServer` with its `server` handle, its `socket_path` and `stop()`. The server lives in a new directory under `root` (the system temporary diff --git a/README.md b/README.md index d9e7874..e6cfba5 100644 --- a/README.md +++ b/README.md @@ -28,92 +28,85 @@ release may change an API: pin an exact version and read the ## Quick start -Standalone scripts run on `luv`, the event loop. It builds with a C compiler, -make and CMake: +Send `19 + 23` to a calculator in a private tmux pane and read back `42`. +The example runs `awk` in its own tmux server and stops the server afterward. +It reads the reply over control mode, which needs tmux 3.7 or newer. -- Debian and Ubuntu: `build-essential` and `cmake`. -- Fedora: `gcc`, `make` and `cmake`. -- macOS: the Xcode command line tools and `cmake`. +Clone the repository for `Runtime:start_server`. The published `0.1.1-1` +rock can run the [local query example](#packages). -If the build fails, install `lua-luv` on Debian or Ubuntu instead. It serves -only the distribution's own Lua. +```console +$ git clone https://github.com/libtmux/libtmux-lua.git && cd libtmux-lua +``` -`Runtime:start_server`, which the programs below call, is not in the published -`0.1.1-1` rock. It ships in the release after it. Until then, put this -repository's `lua/` directory ahead of the installed rock on `LUA_PATH`. +**From a shell.** Use LuaRocks configured for the Lua you run. To build +`luv`, install `build-essential` and `cmake` on Debian or Ubuntu, `gcc`, +`make` and `cmake` on Fedora, or the Xcode command line tools and `cmake` +on macOS. -Install the rock, then `luv` (skip it if you installed `lua-luv`): +On Debian or Ubuntu, you can install `lua-luv` for the distribution's Lua +and skip the `luv` command below. -```console -$ luarocks --local install libtmux -``` +If you switch to that Lua, open a new terminal in the same directory. Run +this guide's libtmux installation and LuaRocks path setup with LuaRocks +configured for the distribution's Lua. ```console $ luarocks --local install luv 1.52.1-0 ``` -Add the local rocks tree to Lua's module paths: +Build the checkout's rock and add the local rocks to Lua's search paths. ```console -$ eval "$(luarocks --local path)" +$ luarocks --local make rockspecs/libtmux-scm-1.rockspec && \ + eval "$(luarocks --local path)" ``` -Create a session and read it back. This is the whole program: +Put tmux on your `PATH`. To select a particular build, set `TMUX_BIN` to +its absolute path. - +On tmux 3.3a through 3.6b, try [typing into a pane and reading its +screen][read-screen]. On tmux 3.7 or newer, run the calculator. Change the +numbers by passing a sum such as `"7 + 8"` after the filename. -```lua -local adapter = require("libtmux.runtime.luv") +```console +$ lua examples/api/watch_pane.lua +19 + 23 = 42 +``` -local function must(value, err) - if err ~= nil then - error(tostring(err), 0) - end - return value -end +**From Neovim 0.10 or newer.** Neovim supplies the Lua runtime and event loop. +Put tmux on its `PATH` and run the example from the checkout. -must(adapter.run(function(runtime) - local owned = must(runtime:start_server():await()) - local created = must(owned.server - :new_session({ - name = "demo", - window_name = "main", - argv = { "/bin/cat" }, - }) - :await()) - local handles = created.session and created.window and created.pane - assert(handles, "creation handles are missing") - local snapshot = must(created.session:snapshot():await()) - assert(snapshot.name == "demo", "created session has the wrong name") - print("session: " .. snapshot.name) - - must(owned:stop():await()) - return true -end)) +```console +$ nvim --clean --cmd 'set runtimepath^=.' -c 'luafile examples/api/watch_pane.lua' ``` -[`Runtime:start_server`][guide-start-server] starts a private tmux server and -`owned:stop()` ends it. [`Server:new_session`][ref-server-new-session] creates -the session and [`Session:snapshot`][ref-session-snapshot] reads it back. +After `19 + 23 = 42` appears in Neovim, you can see it again in `:messages` +or enter a different sum. -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. +```text +:lua assert(loadfile("examples/api/watch_pane.lua"))("7 + 8") +``` -Put tmux on `PATH` and run one of the programs from a checkout: +The [example program](examples/api/watch_pane.lua) starts looking for new +output before typing. Sending the expression and Enter and reading the reply +share a five-second deadline. -```console -$ git clone https://github.com/libtmux/libtmux-lua.git && cd libtmux-lua -``` + -```console -$ lua examples/api/new_session.lua -session: demo +```lua +local observation = must(owned.server:observe(created.session):await()) +local watch = must(observation:watch_pane(pane):await()) + +local deadline = uv.hrtime() / 1e6 + 5000 +local send = { process = { deadline = deadline } } +must(pane:send_text(question, send):await()) +must(pane:send_keys({ "Enter" }, send):await()) +local answer = read_answer(watch, deadline) ``` -Every Lua block here comes from a program under [`examples/`](examples/). -Excerpts continue inside the same runtime body, with `server` and `must` in -hand. +The terminal may echo `19 + 23`. The example waits for a complete +`answer:` line from the calculator and checks the value before printing it. ## Start and stop a private server @@ -679,49 +672,29 @@ session (tmux 3.7 or newer). [`Observation:watch_pane`][ref-observation-watch-pane] streams pane output, [`Observation:watch_notifications`][ref-observation-watch-notifications] -streams tmux events, and [`watch:next`][ref-watch-next] reads the next event: - - +streams tmux events, and [`watch:next`][ref-watch-next] reads the next event. -```lua -local adapter = require("libtmux.runtime.luv") +The [calculator](#quick-start) reads bytes until it has a complete reply. +Events can split a line, so each read uses the same deadline and the example +caps the bytes it keeps. -local function must(value, err) - if err ~= nil then - error(tostring(err), 0) - end - return value -end - -must(adapter.run(function(runtime) - local owned = must(runtime:start_server():await()) - local created = must(owned.server - :new_session({ - name = "demo", - window_name = "main", - argv = { "/bin/cat" }, - }) - :await()) - -- Observation keeps one control-mode client open (tmux 3.7 or newer). - local observation = must(owned.server:observe(created.session):await()) - local watch = must(observation:watch_pane(created.pane):await()) + - must(created.pane:send_text("watched"):await()) +```lua +local function read_answer(watch, deadline) local output = "" - while not output:find("watched", 1, true) do - output = output .. must(watch:next({ timeout = 5000 }):await()).data + while true do + local event, err = watch:next({ deadline = deadline }):await() + assert(event, "calculator reply: " .. tostring(err)) + local bytes = assert(event.data) + assert(#output + #bytes <= 256, "calculator output exceeded 256 bytes") + output = output .. bytes + local answer = ("\n" .. output):match("\nanswer: ([^\r\n]*)\r?\n") + if answer then + return answer + end end - print("output: watched") - - must(observation:close():await()) - must(owned:stop():await()) - return true -end)) -``` - -```console -$ lua examples/api/watch_pane.lua -output: watched +end ``` Each event carries the pane's bytes and a sequence number. A slow reader loses @@ -797,12 +770,19 @@ Reference: [libtmux.org][ref-index] · Registry: [LuaRocks][luarocks-libtmux] · Changelog: [`CHANGES.md`](CHANGES.md) · Modules: [`lua/libtmux/`](lua/libtmux/README.md) -To install from a checkout instead of LuaRocks: +To try the published `0.1.1-1` rock, open a fresh shell in the checkout. +The query filters a Lua table and runs without tmux or `luv`. ```console -$ luarocks --local make rockspecs/libtmux-scm-1.rockspec +$ luarocks --local install libtmux 0.1.1-1 && \ + eval "$(luarocks --local path)" && \ + lua examples/native_query.lua +%1 nvim +%3 vim ``` +To install the checkout as a rock, follow the [shell quick start](#quick-start). + ## What it leaves out - **Starting a server on connect.** [`Runtime:connect`][ref-runtime-connect] @@ -876,6 +856,7 @@ Part of the [libtmux.org](https://libtmux.org/) family alongside Python [ref-pane-wait-for-text]: https://libtmux.org/en/lua/latest/reference/libtmux-pane-wait_for_text/ [ref-query]: https://libtmux.org/en/lua/latest/reference/libtmux-query/ [ref-query-select]: https://libtmux.org/en/lua/latest/reference/libtmux-query-select/ +[read-screen]: #type-into-a-pane-and-read-the-answer [ref-request]: https://libtmux.org/en/lua/latest/reference/libtmux-request/ [ref-request-await]: https://libtmux.org/en/lua/latest/reference/libtmux-request-await/ [ref-runtime]: https://libtmux.org/en/lua/latest/reference/libtmux-runtime/ diff --git a/examples/api/README.md b/examples/api/README.md index b310d42..8fb7f91 100644 --- a/examples/api/README.md +++ b/examples/api/README.md @@ -44,7 +44,7 @@ to select a different build. | [send_keys.lua](send_keys.lua) | Send text and press Enter | `lua input ready` | | [capture.lua](capture.lua) | Read a completed command's output | `lua capture ready` | | [wait_for_text.lua](wait_for_text.lua) | Wait for text on the visible screen | `lua wait ready` | -| [watch_pane.lua](watch_pane.lua) | Stream a pane's output over control mode (tmux 3.7 or newer) | `output: watched` | +| [watch_pane.lua](watch_pane.lua) | Send a sum to `awk` and read its reply over control mode (tmux 3.7 or newer) | `19 + 23 = 42` | | [vote_counter.lua](vote_counter.lua) | Send votes and read each tally over control mode (tmux 3.7 or newer) | Three tallies ending at `yes=2 no=1` | | [unsupported_version.lua](unsupported_version.lua) | Handle a tmux below the minimum | `unsupported_version` and its message | diff --git a/examples/api/manifest.json b/examples/api/manifest.json index 185f878..60d3660 100644 --- a/examples/api/manifest.json +++ b/examples/api/manifest.json @@ -176,9 +176,9 @@ "libtmux.Observation:watch_pane" ], "file": "examples/api/watch_pane.lua", - "description": "Stream a pane's output from a control-mode observation and wait for typed text to arrive.", + "description": "Send an addition expression to a calculator pane and read its reply over control mode.", "min_tmux": "3.7", - "stdout": "output: watched\n" + "stdout": "19 + 23 = 42\n" }, { "id": "vote_counter", diff --git a/examples/api/watch_pane.lua b/examples/api/watch_pane.lua index 1d0c0ee..d3a57c4 100644 --- a/examples/api/watch_pane.lua +++ b/examples/api/watch_pane.lua @@ -1,4 +1,17 @@ -local adapter = require("libtmux.runtime.luv") +local luv = require("libtmux.runtime.luv") +local nvim = require("libtmux.runtime.nvim") + +local editor = rawget(_G, "vim") +---@diagnostic disable-next-line: different-requires +local uv = editor and editor.uv or require("luv") +local binary = os.getenv("TMUX_BIN") + +local expression = ... or "19 + 23" +local left, right = expression:match("^(%d%d?%d?)%s*%+%s*(%d%d?%d?)$") +assert(left and right, "add two integers from 0 to 999, for example '19 + 23'") +local a, b = assert(tonumber(left)), assert(tonumber(right)) +local question = ("%d + %d"):format(a, b) +local expected = tostring(a + b) local function must(value, err) if err ~= nil then @@ -7,27 +20,52 @@ local function must(value, err) return value end -must(adapter.run(function(runtime) - local owned = must(runtime:start_server():await()) - local created = must(owned.server - :new_session({ - name = "demo", - window_name = "main", - argv = { "/bin/cat" }, - }) - :await()) - -- Observation keeps one control-mode client open (tmux 3.7 or newer). - local observation = must(owned.server:observe(created.session):await()) - local watch = must(observation:watch_pane(created.pane):await()) - - must(created.pane:send_text("watched"):await()) +local function read_answer(watch, deadline) local output = "" - while not output:find("watched", 1, true) do - output = output .. must(watch:next({ timeout = 5000 }):await()).data + while true do + local event, err = watch:next({ deadline = deadline }):await() + assert(event, "calculator reply: " .. tostring(err)) + local bytes = assert(event.data) + assert(#output + #bytes <= 256, "calculator output exceeded 256 bytes") + output = output .. bytes + local answer = ("\n" .. output):match("\nanswer: ([^\r\n]*)\r?\n") + if answer then + return answer + end end - print("output: watched") +end + +local function run(runtime) + local owned = must(runtime:start_server({ binary = binary }):await()) + local argv = { "awk", [[{ printf "answer: %d\n", $1 + $3; fflush() }]] } + local options = { name = "calculator", argv = argv } + local created = must(owned.server:new_session(options):await()) + local pane = created.pane + local observation = must(owned.server:observe(created.session):await()) + local watch = must(observation:watch_pane(pane):await()) + + local deadline = uv.hrtime() / 1e6 + 5000 + local send = { process = { deadline = deadline } } + must(pane:send_text(question, send):await()) + must(pane:send_keys({ "Enter" }, send):await()) + local answer = read_answer(watch, deadline) + local mismatch = "expected %s, calculator replied %s" + assert(answer == expected, mismatch:format(expected, answer)) must(observation:close():await()) must(owned:stop():await()) - return true -end)) + return question .. " = " .. answer +end + +if editor then + local started, failure = nvim.start(run, function(answer, err) + if err then + editor.notify(tostring(err), editor.log.levels.ERROR) + else + print(answer) + end + end) + assert(started, tostring(failure)) +else + print(must(luv.run(run))) +end diff --git a/lua/libtmux/README.md b/lua/libtmux/README.md index 4a20be9..b15cd8e 100644 --- a/lua/libtmux/README.md +++ b/lua/libtmux/README.md @@ -28,10 +28,11 @@ The [root README][root-readme] shows a first tmux program, and the ## Quick start -Install the rock and add the local rocks tree to Lua's module paths: +From a fresh shell at the repository root, install the published +`0.1.1-1` rock to run the query below. ```console -$ luarocks --local install libtmux +$ luarocks --local install libtmux 0.1.1-1 ``` ```console @@ -88,6 +89,9 @@ $ lua examples/native_query.lua `require("libtmux")` returns only the rock's `_VERSION`; the entry points are these modules. +The live examples use the checkout's `Runtime:start_server`. Standalone +Lua loads the SCM rock. Neovim loads the checkout from its runtime path. + ### [`libtmux.runtime.luv`][ref-runtime-luv]: the standalone loop [`run(body, limits)`][ref-luv-run] drives a luv loop (`luv` rock) and returns @@ -130,8 +134,8 @@ must(adapter.run(function(runtime) end)) ``` -After the [setup for the complete examples][ex-setup], run this from the -repository root: +After [installing the checkout's SCM rock and luv][ex-setup], run this +from the repository root. ```console $ lua examples/api/new_session.lua @@ -181,11 +185,11 @@ end, function(snapshot, err) end) ``` -From the repository root, with `tmux` on Neovim's `PATH`: +Run from the repository root with `tmux` on Neovim's `PATH`. ```console -$ nvim \ - --cmd 'set runtimepath+=.' \ +$ nvim --clean \ + --cmd 'set runtimepath^=.' \ -c 'luafile examples/nvim_snapshot.lua' ``` diff --git a/scripts/package/README.md b/scripts/package/README.md index da76173..2be6200 100644 --- a/scripts/package/README.md +++ b/scripts/package/README.md @@ -6,7 +6,9 @@ and imports, then runs the pure query example outside the checkout. With `luv` installed, the check runs the snapshot, quickstart and complete API examples on private tmux servers. It checks the output, cleanup and -failure propagation. Network servers and ambient Lua paths are disabled. +failure propagation. The calculator example also runs with workers that +answer incorrectly or stay silent. Network servers and ambient Lua paths +are disabled. 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 diff --git a/scripts/package/package.lua b/scripts/package/package.lua index d0369ad..bdaa85a 100644 --- a/scripts/package/package.lua +++ b/scripts/package/package.lua @@ -357,6 +357,17 @@ function M.complete_api_examples(prefix, version, lua, cwd, opts) -- 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") + local calculator + local function check_failure(name, program, message, env) + local code, output = shell.run({ lua, program }, env) + if code == 0 or not output:find(message, 1, true) then + refuse(name .. ": example failure did not propagate") + end + if #fs.list(temporary) > 0 then + refuse(name .. ": failing example left a server directory") + end + end + for _, example in ipairs(manifest.examples) do local needed = example.min_tmux local need_major, need_minor @@ -382,6 +393,9 @@ function M.complete_api_examples(prefix, version, lua, cwd, opts) example_env = with_env(child, { ENV = startup }) end local output = run({ lua, program }, example_env) + if example.id == "watch_pane" then + calculator = program + end if output ~= example.stdout then refuse( ("%s: complete example output differs: %q"):format( @@ -397,6 +411,28 @@ function M.complete_api_examples(prefix, version, lua, cwd, opts) end end end + if calculator then + local bin = directory .. "/calculator-bin" + fs.mkdir_p(bin) + local path = bin .. ":" .. (child.env.PATH or os.getenv("PATH") or "") + local env = with_env(child, { PATH = path }) + for _, case in ipairs({ + { + "wrong-answer", + "read -r line; echo 'answer: 41'; exec /bin/cat", + "expected 42, calculator replied 41", + }, + { + "silent-calculator", + "exec /bin/sleep 30", + "calculator reply: request deadline expired", + }, + }) do + files.write(bin .. "/awk", "#!/bin/sh\n" .. case[2] .. "\n") + assert(uv.fs_chmod(bin .. "/awk", 493)) + check_failure(case[1], calculator, case[3], env) + end + end local failures = { { "import", @@ -420,13 +456,7 @@ assert(ok, tostring(err)) for _, case in ipairs(failures) do local program = directory .. "/failure-" .. case[1] .. ".lua" files.write(program, case[2]) - local code, output = shell.run({ lua, program }, child) - if code == 0 or not output:find(case[3], 1, true) then - refuse(case[1] .. ": example failure did not propagate") - end - if #fs.list(temporary) > 0 then - refuse(case[1] .. ": failing example left a server directory") - end + check_failure(case[1], program, case[3], child) end end) print(("PASS %d complete API programs and import/runtime failure cleanup"):format(ran)) diff --git a/tests/integration/test_runtime.lua b/tests/integration/test_runtime.lua index 2d8e0cc..17ff15e 100644 --- a/tests/integration/test_runtime.lua +++ b/tests/integration/test_runtime.lua @@ -172,4 +172,56 @@ function M.test_neovim_example_watchdog_retires_the_daemon_and_pane() fixture.settle(ok, failure, released, release_error) end +function M.test_neovim_quick_start_calculates_the_requested_sum() + local binary = fixture.tmux() + local version = run({ binary, "-V" }) + test.assertEquals(version.code, 0, version.stderr) + if not fixture.at_least(assert(version.stdout:match("^tmux (%S+)")), 3, 7) then + test.skip("the calculator needs tmux 3.7 or newer") + end + + local root = fs.mkdtemp(sandbox.PREFIX) + local bin = fs.mkdtemp("libtmux-lua-") + local ok, failure = pcall(function() + assert(uv.fs_symlink(binary, bin .. "/tmux")) + local env = nvim_environment({ + TMPDIR = root, + XDG_RUNTIME_DIR = bin, + PATH = bin .. ":" .. (os.getenv("PATH") or ""), + }) + env.LUA_PATH, env.TMUX_BIN = nil, nil + + local wait_for_answer = ([[lua local expected = %q + local received = vim.wait(650, function() + local lines = vim.split(vim.fn.execute("messages"), "\n") + return vim.tbl_contains(lines, expected) + end) + if not received then + io.stderr:write("Neovim did not report ", expected, "\n") + end + vim.cmd(received and "qall!" or "cquit 1")]]):gsub("\n%s*", " ") + for _, case in ipairs({ + { "luafile examples/api/watch_pane.lua", "19 + 23 = 42" }, + { [[lua assert(loadfile("examples/api/watch_pane.lua"))("7 + 8")]], "7 + 8 = 15" }, + }) do + local result = run({ + fixture.nvim(), + "--headless", + "--clean", + "--cmd", + "set runtimepath^=.", + "-c", + case[1], + "-c", + wait_for_answer:format(case[2]), + }, env) + test.assertEquals(result.code, 0, result.stdout .. result.stderr) + test.assertEquals(fs.list(root), {}, "the calculator left its server directory") + end + end) + fs.remove_tree(bin) + local released = sandbox_host.release(root, binary) + return fixture.settle(ok, failure, #released.leaked == 0, sandbox_host.describe(released, root)) +end + return M