diff --git a/.github/picker.png b/.github/picker.png new file mode 100644 index 0000000..f556d40 Binary files /dev/null and b/.github/picker.png differ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8ac83a4..17d321b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -23,10 +23,7 @@ jobs: runs-on: ${{ matrix.runner }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 - with: - node-version: '24' - - name: Verify runner architecture and release version + - name: Verify runner architecture shell: bash run: | case "${{ matrix.platform }}" in @@ -37,10 +34,6 @@ jobs: if [[ "${{ matrix.platform }}" == linux-x64 ]]; then printf '2.42.0\n%s\n' "$(git version | cut -d' ' -f3)" | sort -V -C fi - if [[ "$GITHUB_REF" == refs/tags/* ]]; then - version="$(node -p 'require("./package.json").version')" - test "$GITHUB_REF_NAME" = "v$version" - fi - name: Install verified JJ 0.46.0 shell: bash run: | @@ -94,13 +87,6 @@ jobs: echo 'Malformed JSON was accepted' >&2 exit 1 fi - - name: Smoke npm artifact without publishing - if: matrix.platform == 'macos-arm64' - shell: bash - run: | - set -euo pipefail - GITHUB_REF_NAME="v$(node -p 'require("./package.json").version')" npm pack --ignore-scripts --json > pack.json - GITHUB_REF_NAME="v$(node -p 'require("./package.json").version')" node scripts/publish-npm.mjs --dry-run - name: Pack platform release if: startsWith(github.ref, 'refs/tags/v') shell: bash @@ -122,46 +108,6 @@ jobs: if-no-files-found: error retention-days: 7 - publish-npm: - if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') - needs: check - runs-on: ubuntu-24.04 - permissions: - contents: read - id-token: write - concurrency: - group: npm-release - cancel-in-progress: false - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - name: macos-arm64-release - - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 - with: - node-version: '24' - registry-url: https://registry.npmjs.org - package-manager-cache: false - - run: npm install --global npm@11.21.0 --ignore-scripts --registry=https://registry.npmjs.org - - name: Pack the verified macOS executable - shell: bash - run: | - set -euo pipefail - test "$(git rev-parse HEAD)" = "$GITHUB_SHA" - test "$GITHUB_REF_NAME" = "v$(node -p 'require("./package.json").version')" - sha256sum -c rex-worktrees-macos-arm64.sha256 - mkdir -p npm-package/dist - tar -xzf rex-worktrees-macos-arm64.tar.gz -C npm-package - mv npm-package/rex-worktrees npm-package/dist/ - cp package.json npm-package/ - cd npm-package - npm pack --ignore-scripts --json > pack.json - - name: Publish with OIDC and verify registry integrity - working-directory: npm-package - run: node ../scripts/publish-npm.mjs - publish: if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') needs: check diff --git a/Makefile b/Makefile index e16c43c..633a4d9 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ .PHONY: build check test clean -LUA_PATH := $(CURDIR)/src/?.lua;$(CURDIR)/.build/modules/?.lua;$(CURDIR)/.build/modules/?/init.lua;$(CURDIR)/.build/src/terminal/src/?.lua;$(CURDIR)/.build/src/terminal/src/?/init.lua;; +LUA_PATH := $(CURDIR)/src/?.lua;$(CURDIR)/.build/modules/?.lua;$(CURDIR)/.build/modules/?/init.lua;; LUA_CPATH := $(CURDIR)/.build/lib/?.so;; export LUA_PATH LUA_CPATH diff --git a/README.md b/README.md index 80e47e6..67f2911 100644 --- a/README.md +++ b/README.md @@ -2,27 +2,19 @@ A keyboard-driven [Rex](https://www.superlogical.com/rex/docs) plugin for opening and creating **Git worktrees** and **Jujutsu (JJ) workspaces**. Pick a project, machine, session, and worktree; it opens a shell there. No agent or model required. -image +![Native Open Worktree picker](https://raw.githubusercontent.com/samuelho-dev/rex-worktrees/main/.github/picker.png) ## Install -Requires Rex and its CLI, a running Rex server, and Git 2.42+. JJ projects also need Jujutsu 0.46+. Standalone builds support Apple Silicon macOS 15+ and Linux x64; no separately installed Lua runtime is needed. +Requires Rex API 17 or newer, its CLI, a running Rex server, and Git 2.42+. JJ projects also need Jujutsu 0.46+. The native picker requires the standalone executable backend on each execution machine. Builds support Apple Silicon macOS 15+ and Linux x64; no separately installed Lua runtime is needed. -**Install or update on macOS (Apple Silicon):** - -```sh -npx --yes rex-worktrees@latest setup && rex config reload -``` - -The command installs the standalone executable and registers the Lua plugin with Rex. No executable path or global npm installation is needed. Run it from a shell that can find `rex`, `git`, and optionally `jj`; unrelated Rex settings are preserved. Rerun the command to update. - -**Without npm / Linux:** download your platform's archive from [GitHub Releases](https://github.com/samuelho-dev/rex-worktrees/releases/latest), verify it against `SHA256SUMS`, and extract it. From the extracted directory: +On either platform, download its archive from [GitHub Releases](https://github.com/samuelho-dev/rex-worktrees/releases/latest), verify it against `SHA256SUMS`, and extract it. From the extracted directory, with `rex`, `git`, and optionally `jj` on your PATH: ```sh ./rex-worktrees setup && rex config reload ``` -Setup copies the executable to the same stable location, so the extracted directory is not needed afterward. `setup --bin /absolute/path/to/rex-worktrees` is only for keeping an executable at a custom or package-managed location. +Setup installs the executable to a stable location and registers the Lua plugin with Rex, preserving unrelated Rex settings. The extracted directory is not needed afterward. Repeat these steps to update. `setup --bin /absolute/path/to/rex-worktrees` is for keeping an executable at a custom or package-managed location. ## Use @@ -32,35 +24,25 @@ Open **Open Worktree…** from the Rex palette, or run: rex do worktrees_open ``` -The popup detects the source terminal's project, current worktree, branch or revision, and full directory path. Git worktrees are separate checkout directories sharing one repository—not separate repositories or branch names. +The native summary picker detects the source terminal's project, current worktree, branch or revision, and full directory path. Select a field to edit it, then return to the summary. Escape returns from an editor or confirmation to the summary; Escape at the summary cancels without checkout changes. Git worktrees are separate checkout directories sharing one repository—not separate repositories or branch names. + +Type a new worktree name in the summary and press Enter on **Create or clone & open** to create and open it immediately, using the selected project, machine, session, mode, and worktree directory settings. Git uses the name for its branch and starts from the selected checkout's HEAD; JJ uses it for the workspace and keeps the selected starting revision. Alternatively, enter a GitHub repository clone URL to clone its primary checkout on the selected machine and open it in the selected session. The destination is the machine's configured or remembered clone root plus the repository name; Git or JJ uses the remote default. No project needs to be selected, and Git is used when no project or clone is selected. Existing checkouts are never switched or reset. You can still filter and select a setting or use **Open worktree / Create worktree & open**. The current repository loads first; the full configured project scan runs when you open **Project**. 1. **Project:** select a discovered project or type an absolute repository path. -2. **Machine:** choose this machine or an existing Rex host. +2. **Machine:** choose a named Rex machine; **Current terminal** identifies the source server, not the machine hosting the native picker. 3. **Session:** select an existing session, or type a name to create one. 4. **Worktree / Workspace:** select an existing one, or choose **Create new worktree… / Create new workspace…**. This list contains worktrees, not branches or clone actions. -5. **Branch:** **Create new worktree…** opens the branch editor directly, without another click on the form. Select an unused existing branch or type a new branch name. JJ uses **Start from** instead; a valid `trunk()` is selected automatically. +5. **Branch:** **Create new worktree…** opens the branch editor directly. Select an unused existing branch or type a new branch name. JJ uses **Start from** instead; a valid `trunk()` is selected automatically. 6. **Directory:** new worktrees get a proposed absolute path; change it only if needed. A new JJ workspace takes its name from the directory's final component. -7. Choose **Open worktree / Create worktree & open**, or press **Ctrl+S** from the form. Accepting a field only updates the form; creation happens on submission. +7. Choose **Open worktree / Create worktree & open** in the summary. Editing fields only updates the draft; creation happens on submission. Safety warnings may require confirmation. **Mode** reuses a matching tab by default; choose a new tab or split instead. -For an **existing worktree**, Branch (or Revision) and Directory describe the detected checkout. They remain readable and **read-only—not disabled**; Tab skips them. Select a different worktree to open another checkout. For a **new worktree**, Branch and Directory are editable. - -The underlined `REX / WORKTREES` header, fields, and footer keep fixed positions. Editors and messages reuse the same details area, so only choice lists and long details scroll. +For an **existing worktree**, Branch (or Revision) and Directory describe the detected checkout and are read-only. Select a different worktree to open another checkout. For a **new worktree**, Branch and Directory are editable. Shells and interactive Git/JJ clones stay attached to the destination terminal. The shell comes from `$SHELL`, falling back to `/bin/sh`. -Rex owns terminal placement, focus, and popup cleanup. New sessions and their first terminal are created together; checkout/clone work then runs in that terminal independently of the chooser. -Connection and review snapshots are operation-local: new sessions and forced new tabs skip reuse scans, and submission still checks fresh host and checkout state. - -| Key | Action | -| ----------------- | ----------------------------------------------------------------- | -| Tab / Shift+Tab | Move between fields and buttons | -| ↑ / ↓ | Navigate fields or choices | -| Enter | Edit a field, accept its value, or activate a focused button | -| Ctrl+S | Submit the form; inside an editor, only accept that field | -| Esc | Return from an editor to the form; from the form, close the popup | -| PageUp / PageDown | Scroll long details | +Rex owns terminal placement and focus. New sessions and their first terminal are created together; checkout/clone work then runs in that terminal independently of the chooser. Submission checks fresh host and checkout state. Optional shortcut—add outside the managed section of your Rex config, then reload: @@ -83,9 +65,9 @@ Both settings are optional. `projects` lists repositories explicitly; `roots` di ### Other machines -Install and run setup on each execution machine, with matching plugin versions and local Git/JJ tools. Connect the host through Rex first. Paths and configuration belong to the selected machine. The helper protocol is v5; update all execution machines together. +Install and run setup on each execution machine, with matching plugin versions and local Git/JJ tools. Connect the host through Rex first. Paths and configuration belong to the selected machine. The helper protocol is v5; when a protocol upgrade requires it, upgrade both execution machines together. -If the selected machine lacks the project, the form proposes cloning it and shows the repository destination explicitly. **Directory** edits that path, and submission becomes **Clone & open**. Changing a field never starts a clone. The Worktree picker can also create a separate worktree after cloning; Directory then controls that worktree's path. Cloning opens a new tab. Only pushed history transfers—not uncommitted work, unpublished changes, or credentials. Cross-host execution and cloning are experimental; live remote Linux destinations have not been verified. +If the selected machine lacks the project, the picker proposes cloning it and shows the repository destination explicitly. **Directory** edits that path, and submission becomes **Clone & open**. Changing a field never starts a clone. The Worktree picker can also create a separate worktree after cloning; Directory then controls that worktree's path. Cloning opens a new tab. Only pushed history transfers—not uncommitted work, unpublished changes, or credentials. Cross-host execution and cloning are experimental; live remote Linux destinations have not been verified. ## Safety @@ -96,11 +78,10 @@ If the selected machine lacks the project, the form proposes cloning it and show ## CLI and development -Run `rex-worktrees --help` for direct `open` commands and host/session options. `rex-worktrees popup` runs the chooser in the current terminal. +Run `rex-worktrees --help` for direct `open` commands and host/session options. Source builds require a C compiler, make, curl, tar, a SHA-256 utility, and network access to download pinned dependencies. Lua and native modules are built locally; an installed Lua is not required. -Regression tests also require Git, JJ, and Python 3; Python is used only by the terminal test drivers. -Compiled popup scenarios disable `LUA_PATH` and `LUA_CPATH` to catch missing bundled modules. +Regression tests also require Git, JJ, and Python 3. ```sh make check @@ -112,9 +93,7 @@ rex config reload Source-build setup installs to `~/.local/bin/rex-worktrees`. To uninstall, remove the `BEGIN rex-worktrees` / `END rex-worktrees` section and adjacent `rex-worktrees.lua` from your active Rex config (`rex config check --json`), remove the executable, and reload. Repositories are retained. -Releases publish the tested macOS archive to npm through GitHub Actions OIDC, then verify registry version and tarball integrity. The npm trusted publisher must authorize `samuelho-dev/rex-worktrees`, workflow `release.yml`, for direct publishing; no npm token is used. Tag a matching package version (`vX.Y.Z`) to release. - -Registry verification allows up to 120 checks, ten seconds apart, for npm processing. Publishing is not retried; an integrity mismatch still fails the release. +Releases publish both tested platform archives and `SHA256SUMS` to GitHub. A Git version tag (`vX.Y.Z`) is the release authority. ## License diff --git a/licenses/THIRD-PARTY-NOTICES b/licenses/THIRD-PARTY-NOTICES index cb5bf9a..0418366 100644 --- a/licenses/THIRD-PARTY-NOTICES +++ b/licenses/THIRD-PARTY-NOTICES @@ -3,9 +3,6 @@ This executable bundles the following MIT-licensed software: Lua 5.4.8 — https://www.lua.org/ Copyright (C) 1994–2025 Lua.org, PUC-Rio. -terminal.lua 0.1.0 — https://github.com/lunarmodules/terminal.lua -Copyright (c) 2024-2026 Thijs Schreijer - LuaSystem 0.7.1 — https://github.com/lunarmodules/luasystem Copyright (c) 2016-2024, Oscar Lim Copyright (c) 2024-2026, the luasystem project authors. diff --git a/lua/rex-worktrees.lua b/lua/rex-worktrees.lua index 8e1f0a5..1922ffd 100644 --- a/lua/rex-worktrees.lua +++ b/lua/rex-worktrees.lua @@ -66,44 +66,202 @@ function M.setup(opts) run = function() return settings end, } + local function chooser(request) + local result, run_err = rex.exec({ bin, "chooser" }, exec_options(rex.json.encode(request))) + if not result then error("rex-worktrees chooser: " .. tostring(run_err), 0) end + if not result.ok then + error("rex-worktrees chooser failed: " .. + ((result.stderr and result.stderr ~= "") and result.stderr or result.stdout or ""), 0) + end + local response, decode_err = rex.json.decode(result.stdout) + if type(response) ~= "table" then + error("rex-worktrees chooser returned invalid JSON: " .. tostring(decode_err), 0) + end + if response.error ~= nil and type(response.error) ~= "string" or + response.notice ~= nil and type(response.notice) ~= "string" or + response.done ~= nil and type(response.done) ~= "boolean" then + error("rex-worktrees chooser returned invalid status", 0) + end + if response.done then + if response.result ~= nil and type(response.result) ~= "table" then + error("rex-worktrees chooser returned invalid result", 0) + end + return response + end + if type(response.state) ~= "string" or type(response.rows) ~= "table" or #response.rows ~= 7 or + type(response.submitLabel) ~= "string" or type(response.submitDisabled) ~= "boolean" then + error("rex-worktrees chooser returned invalid summary", 0) + end + local fields = { project = true, machine = true, session = true, destination = true, + branch = true, checkoutName = true, mode = true } + local seen = {} + for _, row in ipairs(response.rows) do + if type(row) ~= "table" or not fields[row.id] or seen[row.id] or + type(row.label) ~= "string" or type(row.value) ~= "string" or + row.detail ~= nil and type(row.detail) ~= "string" or + row.disabled ~= nil and type(row.disabled) ~= "boolean" or + row.isReadOnly ~= nil and type(row.isReadOnly) ~= "boolean" then + error("rex-worktrees chooser returned invalid row", 0) + end + seen[row.id] = true + end + local editor = response.editor + if editor ~= nil then + if type(editor) ~= "table" or (editor.kind ~= "pick" and editor.kind ~= "input") or + type(editor.title) ~= "string" or type(editor.items) ~= "table" or + type(editor.allowOther) ~= "boolean" or + editor.value ~= nil and type(editor.value) ~= "string" then + error("rex-worktrees chooser returned invalid editor", 0) + end + local ids = {} + for _, item in ipairs(editor.items) do + if type(item) ~= "table" or type(item.id) ~= "string" or ids[item.id] or + type(item.title) ~= "string" or + item.subtitle ~= nil and type(item.subtitle) ~= "string" or + item.detail ~= nil and type(item.detail) ~= "string" then + error("rex-worktrees chooser returned invalid editor item", 0) + end + ids[item.id] = true + end + end + if response.confirmation ~= nil and + (type(response.confirmation) ~= "table" or type(response.confirmation.title) ~= "string" or + type(response.confirmation.detail) ~= "string") then + error("rex-worktrees chooser returned invalid confirmation", 0) + end + return response + end + + local function no_answer(why, detail) + if why == "cancelled" then return end + error("rex-worktrees prompt failed: " .. tostring(why) .. + (detail and (": " .. tostring(detail)) or ""), 0) + end + rex.action{ name = "worktrees_open", title = "Open Worktree…", description = "Choose a project, Rex machine, checkout, and exact session", run = function(ctx) - local session_id = ctx.session_id or rex.session_id - if type(session_id) ~= "string" then error("Select a Rex session first", 0) end - if ctx.server then - local response, call_err = rex.server(ctx.server).call("client.action", { - action = "worktrees_open", session_id = session_id, block_id = ctx.block_id, - }) - if not response then error(call_err, 0) end - return response.result - end - local command = { bin, "launch-popup", "--session", session_id } - local block_id = ctx.block_id or (session_id == rex.session_id and rex.block_id or nil) - if type(block_id) == "string" then - table.insert(command, "--origin-block") - table.insert(command, block_id) - else - table.insert(command, "--no-context") - end - if type(ctx.client_id) == "string" then - table.insert(command, "--origin-client") - table.insert(command, ctx.client_id) + if type(rex.ui) ~= "table" or type(rex.ui.pick) ~= "function" or type(rex.ui.input) ~= "function" then + error("rex-worktrees requires Rex control API revision 17 or newer with native UI prompts; upgrade Rex and its connected app", 0) end - local result, run_err = rex.exec(command, exec_options()) - if not result then error(run_err, 0) end - if not result.ok then - error("rex-worktrees launch-popup failed: " .. - ((result.stderr and result.stderr ~= "") and result.stderr or result.stdout or ""), 0) - end - local layer, decode_err = rex.json.decode(result.stdout) - if not layer or type(layer.layer_id) ~= "string" or type(layer.block_ids) ~= "table" or - type(layer.block_ids[1]) ~= "string" then - error("rex-worktrees launch-popup returned invalid JSON: " .. tostring(decode_err or result.stdout), 0) + local session_id = ctx.session_id or (not ctx.server and rex.session_id) + if type(session_id) ~= "string" then error("Select a Rex session first", 0) end + local response = chooser({ op = "start", origin = { + sessionId = session_id, + blockId = ctx.block_id or (not ctx.server and session_id == rex.session_id and rex.block_id or nil), + clientId = ctx.client_id, + server = ctx.server, + } }) + while true do + if response.done then + if response.error then error(response.error, 0) end + if response.notice then + local acknowledged, why, detail = rex.ui.pick{ + title = response.notice, items = { { id = "ok", title = "OK" } }, + } + if acknowledged == nil then no_answer(why, detail) + elseif acknowledged ~= "ok" then error("rex-worktrees prompt returned an invalid acknowledgement", 0) end + end + return response.result + end + local request = { state = response.state } + if response.confirmation then + local choice, why, detail = rex.ui.pick{ + title = response.confirmation.title, + items = { { id = "confirm", title = "Continue", subtitle = response.confirmation.detail } }, + } + if choice == nil then + no_answer(why, detail) + request.op = "cancel" + elseif choice == "confirm" then + request.op = "confirm" + else + error("rex-worktrees prompt returned an invalid confirmation", 0) + end + elseif response.editor then + local editor = response.editor + local answer, why, detail + if editor.kind == "input" then + answer, why, detail = rex.ui.input{ title = editor.title, value = editor.value } + if answer ~= nil then request.text = answer end + else + local page, page_size = 1, 1998 + while true do + local items, choices = {}, {} + local first = (page - 1) * page_size + 1 + local last = math.min(first + page_size - 1, #editor.items) + if page > 1 then items[#items + 1] = { id = "previous", title = "Previous page" } end + for i = first, last do + local item, id = editor.items[i], "item:" .. i + items[#items + 1] = { id = id, title = item.title, subtitle = item.subtitle, detail = item.detail } + choices[id] = item.id + end + if last < #editor.items then items[#items + 1] = { id = "next", title = "Next page" } end + answer, why, detail = rex.ui.pick{ + title = #editor.items > page_size and (editor.title .. " (" .. page .. "/" .. + math.ceil(#editor.items / page_size) .. ")") or editor.title, + items = items, allow_other = editor.allowOther, value = editor.value, + } + if answer == "previous" then + page = page - 1 + elseif answer == "next" then + page = page + 1 + else + if type(answer) == "table" and editor.allowOther and type(answer.text) == "string" then + request.text = answer.text + elseif answer ~= nil then + request.id = choices[answer] + if request.id == nil then error("rex-worktrees prompt returned an invalid choice", 0) end + end + break + end + end + end + if answer == nil then + no_answer(why, detail) + request.op = "cancel" + else + if request.text ~= nil and type(request.text) ~= "string" then + error("rex-worktrees prompt returned invalid text", 0) + end + request.op = "accept" + end + else + local items, rows = {}, {} + for _, row in ipairs(response.rows) do + local status = row.disabled and "Disabled" or (row.isReadOnly and "Read only" or nil) + items[#items + 1] = { + id = "field:" .. row.id, title = row.label .. ": " .. row.value, + subtitle = row.detail, detail = status, + } + rows["field:" .. row.id] = row + end + if not response.submitDisabled then + items[#items + 1] = { id = "submit", title = response.submitLabel } + end + local title = response.error or response.notice or "Open Worktree" + local choice, why, detail = rex.ui.pick{ + title = title, items = items, allow_other = true, + placeholder = "Type a worktree name or GitHub URL, or select a setting", confirm = "Create or clone & open", + } + if choice == nil then no_answer(why, detail); return end + if type(choice) == "table" and type(choice.text) == "string" then + request.op, request.text = "submit", choice.text + elseif choice == "submit" and not response.submitDisabled then + request.op = "submit" + elseif rows[choice] then + local row = rows[choice] + if not row.disabled and not row.isReadOnly then + request.op, request.field = "edit", row.id + end + else + error("rex-worktrees prompt returned an invalid field", 0) + end + end + if request.op then response = chooser(request) end end - return layer end, } diff --git a/package.json b/package.json deleted file mode 100644 index bf636e5..0000000 --- a/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "rex-worktrees", - "version": "0.5.0", - "description": "Git worktrees and Jujutsu workspaces for Rex", - "license": "MIT", - "author": "Samuel Ho", - "repository": { "type": "git", "url": "git+https://github.com/samuelho-dev/rex-worktrees.git" }, - "homepage": "https://github.com/samuelho-dev/rex-worktrees#readme", - "bugs": { "url": "https://github.com/samuelho-dev/rex-worktrees/issues" }, - "os": ["darwin"], - "cpu": ["arm64"], - "files": ["dist/rex-worktrees", "licenses/THIRD-PARTY-NOTICES", "LICENSE", "README.md"], - "bin": { "rex-worktrees": "dist/rex-worktrees" } -} diff --git a/scripts/build.sh b/scripts/build.sh index 402d3bc..e3984d6 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -23,13 +23,12 @@ unpack() { fi } fetch lua.tar.gz https://www.lua.org/ftp/lua-5.4.8.tar.gz 4f18ddae154e793e46eeab727c59ef1c0c0c2b744e7b94219710d76f530629ae -fetch terminal.tar.gz https://codeload.github.com/lunarmodules/terminal.lua/tar.gz/55e433c79b4549b505edc55f11228d975b67e383 8b414514961e3a44cbf5f27afc8c30e6a410590486d277d6d8c93e38e469091d fetch system.tar.gz https://codeload.github.com/lunarmodules/luasystem/tar.gz/edeec63394684c9281d0a28a8f50c70f39a78e62 1689056786266ead115094c5182423d44933bbc2cf59f87b2f392c064bd1957a fetch utf8.tar.gz https://codeload.github.com/starwing/luautf8/tar.gz/0.3.0 90dfd94fa051978167b36edeb744b0751bedfc53f73d2609fd11124c31a9a1c3 fetch posix.tar.gz https://codeload.github.com/luaposix/luaposix/tar.gz/e6b94b37c19c4bd19a7dc475a4f4cb56f61f5da9 7af5edde30c790490e71bb7e84c0055f138c53321928fd65ceab4743502d21f3 fetch luastatic.tar.gz https://codeload.github.com/ers35/luastatic/tar.gz/c3e1b2ef8f998230fb4c47935e4bdcb1610abab5 ee38d5ccc24bc914fd8536315b47f5f112add63c448244485b47ef4c71088d74 fetch lunajson.tar.gz https://codeload.github.com/grafi-tt/lunajson/tar.gz/250afac121df831f449d6370ddf406673f6f9c2b 4b5e780558fbd843941323aa9fa293fdff1ba73d43124e98aa243ec2e6da19da -for name in lua terminal system utf8 posix luastatic lunajson; do unpack "$name" "$name.tar.gz"; done +for name in lua system utf8 posix luastatic lunajson; do unpack "$name" "$name.tar.gz"; done case "$(uname -s):$(uname -m)" in Linux:x86_64) platform=linux; shared='-shared'; extra='-ldl -lm -lrt';; Darwin:arm64) platform=macosx; shared='-bundle -undefined dynamic_lookup'; extra='-lm';; @@ -86,13 +85,10 @@ STAGE="$BUILD/stage" rm -rf "$STAGE" mkdir -p "$STAGE" cp "$ROOT"/src/*.lua "$STAGE/" -for module in init input/init input/keymap output clear scroll/init sequence utils \ - cursor/init cursor/position/init cursor/shape/init cursor/visible/init \ - text/init text/color text/width draw/init draw/line progress/init; do - mkdir -p "$STAGE/terminal/$(dirname "$module")" - cp "$BUILD/src/terminal/src/terminal/$module.lua" "$STAGE/terminal/$module.lua" -done -cp -R "$BUILD/modules/". "$STAGE/" +mkdir -p "$STAGE/system" "$STAGE/lunajson" +cp "$BUILD/modules/system/init.lua" "$STAGE/system/init.lua" +cp "$BUILD/modules/lunajson/"*.lua "$STAGE/lunajson/" +cp "$BUILD/modules/assets.lua" "$BUILD/modules/lua-utf8.lua" "$STAGE/" printf '%s\n' 'REX_WORKTREES_COMPILED = true' 'require("main")' > "$STAGE/entry.lua" cd "$STAGE" # All module paths are relative, so luastatic registers clean module names. diff --git a/scripts/publish-npm.mjs b/scripts/publish-npm.mjs deleted file mode 100644 index c2ebd22..0000000 --- a/scripts/publish-npm.mjs +++ /dev/null @@ -1,68 +0,0 @@ -import { createHash } from "node:crypto"; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { basename, join } from "node:path"; -import { tmpdir } from "node:os"; -import { execFileSync } from "node:child_process"; -import { setTimeout as delay } from "node:timers/promises"; - -const metadata = JSON.parse(readFileSync("package.json", "utf8")); -const [packed] = JSON.parse(readFileSync("pack.json", "utf8")); -if (metadata.name !== "rex-worktrees" || packed.name !== metadata.name || packed.version !== metadata.version || - process.env.GITHUB_REF_NAME !== `v${metadata.version}` || basename(packed.filename) !== packed.filename) { - throw new Error("Package identity does not match the release tag"); -} -const integrity = `sha512-${createHash("sha512").update(readFileSync(packed.filename)).digest("base64")}`; -if (packed.integrity !== integrity) throw new Error("Packed archive integrity mismatch"); -const expectedFiles = ["package.json", "README.md", "LICENSE", "licenses/THIRD-PARTY-NOTICES", "dist/rex-worktrees"].sort(); -if (JSON.stringify(packed.files.map(file => file.path).sort()) !== JSON.stringify(expectedFiles)) { - throw new Error("Unexpected npm package contents"); -} -if (process.argv.includes("--dry-run")) { - execFileSync("npm", ["publish", packed.filename, "--dry-run", "--ignore-scripts", "--access", "public"], { stdio: "inherit" }); - process.exit(0); -} -if (process.env.GITHUB_REPOSITORY !== "samuelho-dev/rex-worktrees" || - process.env.GITHUB_REF !== `refs/tags/v${metadata.version}` || - process.env.GITHUB_WORKFLOW_REF !== `samuelho-dev/rex-worktrees/.github/workflows/release.yml@refs/tags/v${metadata.version}` || - !process.env.ACTIONS_ID_TOKEN_REQUEST_URL || !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) { - throw new Error("Publishing requires GitHub Actions OIDC; local tokens are not supported"); -} -const url = `https://registry.npmjs.org/${encodeURIComponent(metadata.name)}/${metadata.version}`; -const lookup = async () => { - const response = await fetch(url, { signal: AbortSignal.timeout(15000) }); - if (response.status === 404) return undefined; - if (!response.ok) throw new Error(`Registry lookup failed: HTTP ${response.status}`); - return response.json(); -}; -const verify = record => { - if (record.name !== metadata.name || record.version !== metadata.version || record.dist?.integrity !== integrity) { - throw new Error("Registry package does not match the accepted archive"); - } -}; -const existing = await lookup(); -if (existing) { - verify(existing); - console.log(`${metadata.name}@${metadata.version} already contains the accepted archive`); -} else { - const directory = mkdtempSync(join(tmpdir(), "rex-npm-auth-")); - try { - const userConfig = join(directory, "user.npmrc"), globalConfig = join(directory, "global.npmrc"); - writeFileSync(userConfig, ""); - writeFileSync(globalConfig, ""); - execFileSync("npm", ["publish", packed.filename, "--ignore-scripts", "--access", "public", "--provenance", "--registry=https://registry.npmjs.org"], { - stdio: "inherit", - env: { ...process.env, NODE_AUTH_TOKEN: "", NPM_TOKEN: "", NPM_CONFIG_USERCONFIG: userConfig, NPM_CONFIG_GLOBALCONFIG: globalConfig } - }); - } finally { - rmSync(directory, { recursive: true, force: true }); - } - let published; - for (let attempt = 0; attempt < 120; attempt++) { - published = await lookup(); - if (published) break; - await delay(10000); - } - if (!published) throw new Error("Published version is not visible in the registry"); - verify(published); - console.log(`Verified ${metadata.name}@${metadata.version}: ${integrity}`); -} diff --git a/src/chooser.lua b/src/chooser.lua new file mode 100644 index 0000000..4438f78 --- /dev/null +++ b/src/chooser.lua @@ -0,0 +1,781 @@ +local runtime = require("runtime") +local git = require("git") +local unicode = runtime.unicode +local path = runtime.path +local M = {} +local function copy(t) + local r = {} + for k, v in pairs(t) do + r[k] = v + end + return r +end +local function trim(s) return (s:gsub("^%s+", ""):gsub("%s+$", "")) end +local function present(v) return v ~= nil and not runtime.isNull(v) end +local function safe(s, whitespace) return unicode.sanitize(tostring(s or ""), whitespace) end +local function directoryFor(d) + if d.destination and present(d.destination.path) then return d.destination.path end + if d.clone and not d.isCreating then return d.clone.repo end + if d.directory then return d.directory end + local repo = d.clone and d.clone.repo or d.project and d.project.path + local name = d.worktreeName or d.destination and d.destination.branch + if repo and name then return (d.worktreeRoot or repo .. ".worktrees"):gsub("/$", "") .. "/" .. name end +end +function M.generatedName(d) + return d.clone and not d.isCreating and (d.projectChoice and d.projectChoice.name or "Project") + or d.worktreeName + or d.destination and d.destination.label + or d.projectChoice and d.projectChoice.name + or "Worktree" +end +function M.inputFor(d) + if not (d.host and d.project and d.projectChoice and d.destination and d.session) then return end + local result = { + repo = d.project.vcs == "jj" and (d.sourcePath or d.project.path) or d.project.path, + session = d.session, + name = M.generatedName(d), + clientId = d.clientId, + additional = d.mode == "new-tab", + split = d.mode == "split", + vcs = d.project.vcs, + } + if present(d.destination.path) then + result.path = d.destination.path + return result + end + result.directory = directoryFor(d) + if not result.directory then return end + if d.project.vcs == "jj" then + if not (d.worktreeName and d.destination.revision) then return end + result.worktreeName, result.revision = d.worktreeName, d.destination.revision + else + if not d.destination.branch then return end + result.branch, result.worktreeName = d.destination.branch, d.worktreeName + end + return result +end +function M.changeProjectChoice(d, choice) + local r = copy(d) + r.projectChoice = choice + r.project, r.clone, r.destination, r.worktreeName, r.directory, r.worktreeRoot, r.sourcePath = + nil, nil, nil, nil, nil, nil, nil + r.isCreating = false + return r +end +function M.changeProject(d, candidate) + local r = copy(d) + local same = d.project and d.project.vcs == candidate.vcs and d.project.commonDir == candidate.commonDir + r.project, r.clone = candidate, nil + if not same then + r.destination, r.worktreeName, r.directory, r.sourcePath = nil, nil, nil, nil + end + r.isCreating = not not (same and d.isCreating) + if candidate.vcs ~= "jj" then r.sourcePath = nil end + return r +end +function M.changeDestination(d, candidate, name) + local r = copy(d) + r.destination = candidate + r.worktreeName = name + if present(candidate.path) then + r.worktreeName, r.directory, r.isCreating = nil, nil, false + end + return r +end +function M.selectWorktree(d, tree) + if not present(tree.path) or tree.vcs == "jj" and not tree.present then + runtime.fail( + "Workspace " + .. (tree.vcs == "jj" and tree.name or tostring(tree.path)) + .. " is unavailable; inspect its registered location before opening" + ) + end + local r = M.changeDestination( + d, + { path = tree.path, worktree = tree, label = tree.vcs == "jj" and tree.name or path.basename(tree.path) } + ) + if tree.vcs == "jj" then + r.sourcePath = tree.path + if d.projectChoice and d.projectChoice.source and d.host and d.projectChoice.source.hostId == d.host.hostId then + r.projectChoice = copy(d.projectChoice) + r.projectChoice.source = copy(d.projectChoice.source) + r.projectChoice.source.checkoutPath = tree.path + end + end + return r +end +function M.selectRevision(d, choice) + return M.changeDestination(d, { revision = choice.revision.commitId, label = choice.label }, d.worktreeName) +end +function M.cloneInputFor(d) + if not (d.host and d.clone and d.session and path.isAbsolute(d.clone.repo)) then return end + local directory = d.isCreating and directoryFor(d) or nil + if + d.isCreating + and (not directory or d.clone.vcs == "git" and d.destination and d.destination.branch == d.clone.branch) + then + return + end + local result = { + vcs = d.clone.vcs, + repo = d.clone.repo, + session = d.session, + clientId = d.clientId, + checkout = d.isCreating and "worktree" or "primary", + directory = directory, + name = M.generatedName(d), + worktreeName = d.isCreating and d.worktreeName or nil, + } + local source = { vcs = d.clone.vcs, url = d.clone.url, sourceHostId = d.clone.sourceHostId } + result.source = source + if d.clone.vcs == "jj" then + local revision = d.destination and d.destination.revision + if revision then + if d.clone.revision and d.clone.revision.commitId == revision then + source.revision = d.clone.revision + else + for _, choice in ipairs(d.clone.revisions or {}) do + if choice.revision.commitId == revision then + source.revision = choice.revision + break + end + end + end + end + source.revisions = runtime.json.array() + result.revision = revision + else + if not (d.destination and d.destination.branch) then + if d.isCreating or d.clone.sourceHostId then return end + result.branchMode = "default" + source.branches = runtime.json.array() + return result + end + result.branch = d.destination.branch + result.branchMode = "create" + for _, branch in ipairs(d.clone.branches or {}) do + if branch == result.branch then + result.branchMode = "existing" + break + end + end + source.branches, source.branch = runtime.json.array(), d.clone.branch + end + return result +end + +local client = require("client") +local rex = require("rex") +local contracts = require("contracts") +local json = runtime.json + +local function known(host, repo, checkout) + local source = { machineKey = host.key, hostId = host.hostId, repository = repo } + if repo.vcs == "jj" and present(checkout) and checkout.vcs == "jj" and checkout.commonDir == repo.commonDir then + source.checkoutPath = checkout.path + end + return { name = repo.name, source = source } +end + +local function clonePath(state, choice) + if choice.name and choice.name ~= "." and choice.name ~= ".." and not choice.name:find("[/\\%c]") + and safe(choice.name) == choice.name and state.cloneRoot ~= "" then + return state.cloneRoot:gsub("/$", "") .. "/" .. choice.name + end +end + +local function originDirectory(machine, origin) + if not (origin.sessionId and origin.blockId) then return nil end + if machine["local"] then return rex.originDirectory(origin.sessionId, origin.blockId) end + local host = client.connectMachine(machine) + local function call(method, schema) + return contracts.decode(schema, rex.remoteRex(host.selector, + { "block", "call", "-s", origin.sessionId, "-b", origin.blockId, method })) + end + local ok, info = pcall(call, "process", "RexProcess") + local cwd = ok and info.foreground and not runtime.isNull(info.foreground) and info.foreground.cwd + if type(cwd) == "string" and path.isAbsolute(cwd) and not cwd:find("\0", 1, true) then return cwd end + local got, pwd = pcall(call, "pwd", "RexDirectory") + if got and type(pwd.pwd) == "string" then + local authority = pwd.pwd:match("^file://([^/]*)/") + if pwd.pwd:sub(1, 1) == "/" or authority == "" or authority == "localhost" then + return rex.localDirectoryUri(pwd.pwd) + end + end +end + +local function focusClient(state, clients) + local d = state.draft + for _, item in ipairs(clients or {}) do + if item.id == d.clientId then return item.id end + end + if state.originMachine == d.machine.key then + for _, item in ipairs(clients or {}) do + if item.id == state.origin.clientId then return item.id end + end + end + if #(clients or {}) == 1 then return clients[1].id end +end + +local function bind(state, command, choice, host, available) + local source = choice.source + local same = source and source.machineKey == host.key and source.hostId == host.hostId + local matches = {} + for _, repo in ipairs(available) do + if repo.name == choice.name and (not source or repo.vcs == source.repository.vcs) then + matches[#matches + 1] = repo + end + end + local directory = same and (source.checkoutPath or source.repository.path) or choice.path + if not directory and #matches == 1 then directory = matches[1].path end + if not directory and #matches > 1 then + runtime.fail("Multiple projects named " .. choice.name .. " on this machine; select its exact project directory") + end + directory = directory or (source and clonePath(state, choice)) + local function clone(repo) + if not source then runtime.fail("Choose a known source project before cloning") end + local machine + for _, item in ipairs(client.listMachines()) do + if item.key == source.machineKey then machine = item end + end + if not machine then runtime.fail("Source Rex machine is no longer registered") end + local sourceHost = client.connectMachine(machine) + if sourceHost.hostId ~= source.hostId then runtime.fail("Source Rex host identity changed; select the project again") end + local inventory = client.sourceForClone(sourceHost, command, source.checkoutPath or source.repository.path) + inventory.repo = repo + return { clone = inventory } + end + if not directory then + if source then return clone("") end + runtime.fail("Select a known project or enter its absolute directory on this machine") + end + if not path.isAbsolute(directory) then runtime.fail("Project directory must be an absolute path on this machine") end + local ok, found = pcall(client.inspectProject, host, command, directory) + if not ok then + if source and runtime.message(found):find("Project directory does not exist:", 1, true) == 1 then + return clone(directory) + end + error(found, 0) + end + if same and (found.project.vcs ~= source.repository.vcs or found.project.commonDir ~= source.repository.commonDir) then + runtime.fail("Project directory changed; select the exact project directory again") + end + return { found = found } +end + +local function applyBinding(state, choice, result, preserve) + local d = state.draft + if not preserve then d = M.changeProjectChoice(d, choice) end + if result.clone then + if not preserve then + d.clone = result.clone + if d.clone.vcs == "git" and present(d.clone.branch) then + d.destination = { branch = d.clone.branch, label = d.clone.branch } + end + end + else + local found = result.found + d = M.changeProject(d, found.project) + d.worktreeRoot = found.worktreeRoot + if found.checkout.vcs == "jj" and not d.sourcePath then d.sourcePath = found.checkout.path end + if not d.destination then + for _, tree in ipairs(found.worktrees) do + if tree.path == found.checkout.path + and (tree.vcs == "jj" and tree.present or tree.vcs == "git" and not tree.bare and not tree.prunable) then + d = M.selectWorktree(d, tree) + break + end + end + end + end + state.draft = d +end + +local function activate(state, command, machine, context) + local previous = state.draft + local found, initial + if context then + local host = client.connectMachine(machine) + local ok, value = pcall(client.inspectProject, host, command, context) + if ok then + initial = value + found = client.inspectSessions(host, command) + found.host, found.checkout, found.projects = host, value.checkout, json.array({ value.project }) + end + end + found = found or client.connectAndDiscover(machine, command, context) + state.projectsLoaded = initial == nil + local host = found.host + local preserve = previous.machine and previous.machine.key == machine.key and previous.host + and previous.host.hostId == host.hostId + state.draft = preserve and copy(previous) or { machine = machine, projectChoice = previous.projectChoice, mode = previous.mode } + if not preserve and previous.clone and not previous.clone.sourceHostId then + state.draft = copy(previous) + state.draft.clone = copy(previous.clone) + end + local d = state.draft + d.machine, d.host = machine, host + state.cloneRoot, state.sessions = present(found.cloneRoot) and found.cloneRoot or "", found.sessions or json.array() + if not preserve and d.clone and not d.clone.sourceHostId then + d.clone.repo = clonePath(state, d.projectChoice) or "" + end + local retained = json.array() + for _, item in ipairs(state.projects) do + if not item.source or item.source.machineKey ~= machine.key or item.source.hostId ~= host.hostId then + retained[#retained + 1] = item + end + end + for _, repo in ipairs(found.projects or {}) do retained[#retained + 1] = known(host, repo, found.checkout) end + state.projects = retained + local valid = d.session and d.session.kind == "new" + for _, item in ipairs(state.sessions) do + if d.session and d.session.kind == "existing" and item.id == d.session.id then valid = true end + end + if not valid then + d.session = nil + if state.originMachine == machine.key then + for _, item in ipairs(state.sessions) do + if item.id == state.origin.sessionId then d.session = { kind = "existing", id = item.id } end + end + end + if not d.session and #state.sessions == 1 then d.session = { kind = "existing", id = state.sessions[1].id } end + end + d.clientId = focusClient(state, found.clients) + local choice = not (d.clone and not d.clone.sourceHostId) and previous.projectChoice or nil + local result + if not choice and present(found.checkout) and context then + result = { found = initial or client.inspectProject(host, command, found.checkout.path) } + choice = known(host, result.found.project, result.found.checkout) + elseif choice then + result = bind(state, command, choice, host, found.projects or {}) + end + if choice and result then applyBinding(state, choice, result, preserve and previous.projectChoice ~= nil) end +end + +local function view(state) + local d = state.draft + local jj = (d.clone and d.clone.vcs or d.project and d.project.vcs) == "jj" + local tree = d.destination and present(d.destination.path) and d.destination.worktree + local ready = d.host and (d.project or d.clone) + local directory = directoryFor(d) + local session = d.session and d.session.kind == "new" and "New: " .. d.session.name or nil + if not session and d.session then + for _, item in ipairs(state.sessions) do if item.id == d.session.id then session = item.label end end + end + local branch + if tree and tree.vcs == "jj" then + branch = tree.changeId:sub(1, 12) .. " · " .. tree.head:sub(1, 12) + elseif tree then + branch = present(tree.branch) and tree.branch or "Detached HEAD · " .. tree.head:sub(1, 12) + elseif jj then + branch = d.destination and d.destination.revision and d.destination.label or d.clone and "Remote default" or "Choose a starting revision" + else + branch = d.destination and d.destination.branch or d.clone and "Remote default" or "Select or type branch" + end + local rows = json.array({ + { id = "project", label = "Project", value = d.projectChoice and d.projectChoice.name or "Choose a project" }, + { id = "machine", label = "Machine", value = d.machine and d.machine.label or "Choose Rex host", + detail = d.host and "Host ID: " .. d.host.hostId or d.machine and d.machine.selector }, + { id = "session", label = "Session", value = session or d.session and d.session.id or "Choose or type new session", + detail = d.session and (d.session.kind == "existing" and d.session.id or "Create on submit"), disabled = not d.host }, + { id = "destination", label = jj and "Workspace" or "Worktree", + value = d.clone and not d.isCreating and "Project checkout (after clone)" + or d.isCreating and (jj and "Create new workspace…" or "Create new worktree…") + or d.destination and d.destination.label or (jj and "Choose a workspace" or "Choose a worktree"), + disabled = not ready }, + { id = "branch", label = tree and tree.vcs == "jj" and "Revision" or jj and "Start from" or "Branch", + value = branch, isReadOnly = not not tree, disabled = not ready or not tree and not d.clone and not d.isCreating }, + { id = "checkoutName", label = "Directory", value = directory and directory ~= "" and directory + or (d.clone and "Choose an absolute directory" or "Choose a branch first"), + detail = directory, isReadOnly = not not tree, disabled = not ready or not d.clone and not directory }, + { id = "mode", label = "Mode", value = d.clone and "New tab (cloning)" + or d.mode == "auto" and "Reuse matching tab, otherwise new tab" + or d.mode == "new-tab" and "Always new tab" or "Split matching tab, otherwise new tab", + isReadOnly = not not d.clone, disabled = not d.host }, + }) + local response = { + rows = rows, + submitLabel = d.clone and "Clone & open" or tree and (jj and "Open workspace" or "Open worktree") + or jj and "Create workspace & open" or "Create worktree & open", + submitDisabled = not not (state.blocked or not d.host or not (M.cloneInputFor(d) or M.inputFor(d))), + error = state.error, + notice = d.clone and ("This project will be cloned onto this machine: " + .. (d.clone.repo ~= "" and d.clone.repo or "choose its Directory") .. ". Only pushed history transfers.") or nil, + } + return response +end + +local function addChoice(choices, value, title, detail) + choices[#choices + 1] = { id = tostring(#choices + 1), value = value, title = title, detail = detail } +end + +local function editor(state, field, title, choices, allowOther) + state.editor = { field = field, kind = "pick", title = title, choices = choices, allowOther = allowOther } +end + +local function openField(state, command, field) + local d, choices = state.draft, json.array() + for _, row in ipairs(view(state).rows) do + if row.id == field and (row.disabled or row.isReadOnly) then runtime.fail("This field is not editable") end + end + if field == "project" then + if not state.projectsLoaded then activate(state, command, d.machine) end + for _, item in ipairs(state.projects) do + addChoice(choices, item, item.name, (item.source and item.source.repository.path or item.path or "") .. " · Source machine") + end + editor(state, field, "Project", choices, true) + elseif field == "machine" then + for _, item in ipairs(client.listMachines(state.originMachine)) do + addChoice(choices, item, item.label, item.key == state.originMachine and "Current terminal" or "Rex host · " .. item.label) + end + editor(state, field, "Execution machine", choices, false) + elseif field == "session" then + local found = client.inspectSessions(d.host, command) + state.sessions, d.clientId = found.sessions, focusClient(state, found.clients) + for _, item in ipairs(state.sessions) do addChoice(choices, item.id, item.label, item.id) end + editor(state, field, "Session", choices, true) + elseif field == "mode" then + addChoice(choices, "auto", "Reuse matching tab", "Focus existing task, otherwise open new tab") + addChoice(choices, "new-tab", "Always new tab") + addChoice(choices, "split", "Split matching task", "Opens new tab when no live target exists") + editor(state, field, "Open mode", choices, false) + elseif field == "checkoutName" then + local proposed = d.clone and not d.isCreating and d.projectChoice and clonePath(state, d.projectChoice) + or directoryFor(setmetatable({ directory = false }, { __index = d })) + if proposed then addChoice(choices, proposed, "Use proposed directory", proposed) end + editor(state, field, "Directory (absolute path on selected machine)", choices, true) + elseif field == "destination" or field == "branch" then + local jj = (d.clone and d.clone.vcs or d.project.vcs) == "jj" + local found = d.clone and { worktrees = {}, branches = d.clone.branches or {}, revisions = d.clone.revisions or {} } + or client.inspectWorktrees(d.host, command, jj and (d.sourcePath or d.project.path) or d.project.path) + if field == "destination" then + local trees = json.array() + for _, tree in ipairs(found.worktrees or {}) do + if tree.vcs == "jj" or not tree.bare and not tree.prunable then + trees[#trees + 1] = tree + addChoice(choices, tree, tree.vcs == "jj" and ((tree.present and "" or "Unavailable: ") .. tree.name) + or path.basename(tree.path), present(tree.path) and tree.path or "Location unknown") + end + end + if d.clone then addChoice(choices, "primary", "Project checkout (after clone)", d.clone.repo) end + addChoice(choices, "create", jj and "Create new workspace…" or "Create new worktree…") + editor(state, field, jj and "Workspace" or "Worktree", choices, false) + state.editor.trees, state.editor.revisions, state.editor.worktreeRoot = trees, found.revisions or json.array(), found.worktreeRoot + elseif jj then + if d.clone then addChoice(choices, json.null, "Remote default") end + for _, choice in ipairs(found.revisions or {}) do + addChoice(choices, choice, choice.label, choice.expression .. " · " .. choice.revision.commitId:sub(1, 12)) + end + editor(state, field, "Start from revision", choices, true) + else + local occupied = {} + if d.clone and not d.clone.sourceHostId and not d.isCreating then + addChoice(choices, json.null, "Remote default") + end + for _, tree in ipairs(found.worktrees or {}) do + if tree.vcs == "git" and present(tree.branch) then occupied[tree.branch] = true end + end + if d.clone and d.isCreating and present(d.clone.branch) then occupied[d.clone.branch] = true end + for _, branch in ipairs(found.branches or {}) do + if not occupied[branch] then addChoice(choices, branch, branch, d.clone and "Published branch" or "Existing branch") end + end + editor(state, field, "Branch", choices, true) + state.editor.occupied = occupied + end + else + runtime.fail("Unknown chooser field") + end +end + +local function accept(state, command, request) + local e, d = state.editor, state.draft + if not e then runtime.fail("No active editor") end + if (request.id == nil) == (request.text == nil) then runtime.fail("Select one choice or enter text") end + local value + if request.id then + local selected + for _, choice in ipairs(e.choices) do if choice.id == request.id then selected = choice end end + if not selected then runtime.fail("Choice is no longer available") end + value = selected.value + elseif e.allowOther then + value = trim(request.text) + if value == "" then runtime.fail("A value is required") end + else + runtime.fail("Select an available choice") + end + state.editor = nil + if e.field == "machine" then + activate(state, command, value) + elseif e.field == "project" then + local choice = request.id and value or { name = path.basename(value), path = path.isAbsolute(value) and value or nil } + if choice.name == "" then runtime.fail("Project name is required") end + if not d.host then + state.draft = M.changeProjectChoice(d, choice) + else + local available = {} + for _, item in ipairs(state.projects) do + if item.source and item.source.machineKey == d.host.key and item.source.hostId == d.host.hostId then + available[#available + 1] = item.source.repository + end + end + applyBinding(state, choice, bind(state, command, choice, d.host, available)) + end + elseif e.field == "session" then + d.session = request.id and { kind = "existing", id = value } or { kind = "new", name = value } + elseif e.field == "mode" then + d.mode = value + elseif e.field == "checkoutName" then + if not path.isAbsolute(value) or value:find("[%z\1-\31\127]") + or path.dirname(path.resolve(value)) == path.resolve(value) then + runtime.fail("Directory must be an absolute non-root path on this machine") + end + local directory = path.resolve(value) + if d.clone and not d.isCreating then + d.clone.repo = directory + else + d.directory = directory + if (d.clone and d.clone.vcs or d.project.vcs) == "jj" then d.worktreeName = path.basename(directory) end + end + elseif e.field == "destination" then + local jj = (d.clone and d.clone.vcs or d.project.vcs) == "jj" + if value == "primary" then + d.isCreating, d.directory, d.worktreeName = false, nil, nil + d.destination = present(d.clone.branch) and { branch = d.clone.branch, label = d.clone.branch } or nil + elseif value == "create" then + local name, suffix = "workspace", 2 + if jj then + local used = {} + for _, tree in ipairs(e.trees) do used[tree.name] = true end + while used[name] do name, suffix = "workspace-" .. suffix, suffix + 1 end + end + local mainline + for _, choice in ipairs(e.revisions) do if choice.expression == "trunk()" then mainline = choice break end end + d.isCreating, d.directory, d.worktreeName = true, nil, jj and name or nil + d.worktreeRoot = e.worktreeRoot or d.worktreeRoot + d.destination = jj and mainline and { revision = mainline.revision.commitId, label = mainline.label } + or { label = jj and "Create new workspace…" or "Create new worktree…" } + if not jj then openField(state, command, "branch") end + else + state.draft = M.selectWorktree(d, value) + end + elseif e.field == "branch" then + local jj = (d.clone and d.clone.vcs or d.project.vcs) == "jj" + if jj then + if request.id and not present(value) then + d.destination = nil + else + local choice = value + if not request.id then + local host, repo = d.host, d.sourcePath or d.project and d.project.path + if d.clone then + if not (d.projectChoice and d.projectChoice.source) then + runtime.fail("Cannot inspect a revision without a source Rex checkout; use Remote default") + end + local source, machine = d.projectChoice.source + for _, item in ipairs(client.listMachines()) do if item.key == source.machineKey then machine = item end end + if not machine then runtime.fail("Clone source machine is no longer registered") end + host = client.connectMachine(machine) + if host.hostId ~= source.hostId or host.hostId ~= d.clone.sourceHostId then + runtime.fail("Clone source host identity changed; reselect the project") + end + repo = source.checkoutPath or source.repository.path + end + choice = { expression = value, label = value, revision = client.inspectRevision(host, command, repo, value) } + end + state.draft = M.selectRevision(d, choice) + if d.clone then state.draft.clone.revision = choice.revision end + end + elseif request.id and not present(value) then + d.destination = nil + else + if value == "" or value:sub(1, 1) == "-" or value:find("[%z\1-\31\127]") then + runtime.fail("Branch name must be a valid Git branch") + end + if e.occupied[value] then runtime.fail("Branch " .. value .. " is already checked out; select its existing worktree instead") end + d.destination = { branch = value, label = value } + end + end +end + +local function namedWorktree(d, text) + if not (d.host and (d.project or d.clone) and d.session) then + runtime.fail("Select a project, machine, and session before creating a worktree") + end + local name = trim(text) + if name == "" then runtime.fail("A new worktree name is required") end + local r, selected = copy(d), d.destination or {} + local jj = (d.clone and d.clone.vcs or d.project.vcs) == "jj" + local revision = selected.revision or selected.worktree and selected.worktree.head + or d.clone and d.clone.revision and d.clone.revision.commitId + r.isCreating, r.worktreeName = true, jj and name or nil + r.directory = d.directory and path.join(path.dirname(d.directory), name) or nil + r.destination = jj and { revision = revision, label = selected.revision and selected.label or revision and revision:sub(1, 12) } + or { branch = name, label = name } + if not jj and selected.worktree then + r.worktreeRoot = d.worktreeRoot or d.project.path .. ".worktrees" + r.project = copy(d.project) + r.project.path = selected.worktree.path + end + return r +end + +local function typedDraft(state, command, text) + local value = trim(text) + local repository = git.githubRepository(value) + if not repository then + if value:match("^[%a][%w+.-]*:") or value:match("^[^/%s]+@[^/%s]+:") + or value:lower():match("^github%.com/") or value:lower():match("^www%.github%.com/") then + runtime.fail("Enter a valid GitHub repository clone URL") + end + return namedWorktree(state.draft, text) + end + local d = state.draft + if not (d.machine and d.host and d.session) then + runtime.fail("Select a machine and session before cloning a repository") + end + local found = client.connectAndDiscover(d.machine, command) + if found.host.hostId ~= d.host.hostId then + runtime.fail("Rex host identity changed; select the machine again") + end + state.cloneRoot = present(found.cloneRoot) and found.cloneRoot or "" + local repo = clonePath(state, repository) + if not repo or not path.isAbsolute(repo) then + runtime.fail("No clone root is configured on the selected machine") + end + local vcs = d.clone and d.clone.vcs or d.project and d.project.vcs or "git" + local result = M.changeProjectChoice(d, { name = repository.name }) + result.clone = { vcs = vcs, url = repository.url, repo = repo } + return result +end + +local function submit(state, command, confirmed) + if state.blocked then runtime.fail("Inspect the destination and session before opening again") end + local d = state.draft + local input = M.cloneInputFor(d) or M.inputFor(d) + if not input then runtime.fail("Complete the required fields before submitting") end + local clone = not not d.clone + local plan = (clone and client.reviewClone or client.review)(d.host, command, input) + if plan.hostId ~= d.host.hostId + or clone and (plan.repo ~= input.repo or plan.input.checkout ~= input.checkout or plan.input.directory ~= input.directory) + or not clone and (input.path and plan.path ~= input.path or input.directory and plan.path ~= input.directory) then + runtime.fail("Destination changed; select the machine and destination again") + end + if confirmed and (not state.confirmation or state.confirmation.warning ~= plan.warning) then + runtime.fail("Safety warning changed; review the destination again") + end + if plan.warning and not confirmed then + state.confirmation = { warning = plan.warning } + return + end + state.confirmation = nil + local ok, result = pcall(clone and client.submitClone or client.submit, d.host, command, input, plan) + if not ok then + state.blocked = true + state.error = runtime.message(result) .. " · Destination: " .. (clone and plan.repo or plan.path) + .. " · The checkout or Rex tab may already have changed. Inspect the destination and session before opening again." + return + end + state.done, state.result = true, result + state.notice = result.warning or plan.warning +end + +function M.request(request, command) + contracts.validate("ChooserRequest", request) + local state + if request.op == "start" then + if request.state then runtime.fail("Start does not accept state") end + state = { draft = { mode = "auto" }, origin = request.origin or json.object(), projects = json.array(), + sessions = json.array(), cloneRoot = "" } + local machines = client.listMachines() + local function find(selected) + for _, machine in ipairs(machines) do + if selected and (machine.key == selected or machine.selector == selected or machine.label == selected) + or not selected and machine["local"] then return machine end + end + end + local source = find(state.origin.server) + local target = source + if request.machine then target = find(request.machine) end + if source then + state.originMachine = source.key + local ok, err = pcall(function() + local context = request.context + if context and not path.isAbsolute(context) then runtime.fail("Context must be an absolute path") end + context = context or originDirectory(source, state.origin) + activate(state, command, source, context) + if target and target.key ~= source.key then activate(state, command, target) end + end) + if not ok then state.error = runtime.message(err) end + else + state.error = "Origin machine " .. tostring(state.origin.server) .. " is not in Rex hosts. Select a connected machine." + end + if request.machine and not target then + state.error = "Machine " .. request.machine .. " is not in Rex hosts. Select a connected machine." + end + else + if not request.state then runtime.fail("Chooser state is required") end + state = contracts.decode("ChooserState", request.state) + if state.done then runtime.fail("Chooser is already complete") end + local before = json.encode(state) + state.error = nil + local ok, err = pcall(function() + if request.op == "edit" then + if state.editor or state.confirmation then runtime.fail("Finish or cancel the current prompt first") end + openField(state, command, request.field) + elseif request.op == "accept" then + accept(state, command, request) + elseif request.op == "cancel" then + state.editor, state.confirmation = nil, nil + elseif request.op == "submit" then + if state.editor or state.confirmation then runtime.fail("Finish or cancel the current prompt first") end + if request.text ~= nil then state.draft = typedDraft(state, command, request.text) end + submit(state, command, false) + elseif request.op == "confirm" then + if not state.confirmation then runtime.fail("No safety confirmation is pending") end + submit(state, command, true) + end + end) + if not ok then + state = contracts.decode("ChooserState", before) + state.error = runtime.message(err) + end + end + local response = view(state) + if state.editor then + local items = json.array() + for _, choice in ipairs(state.editor.choices) do + items[#items + 1] = { id = choice.id, title = choice.title, detail = choice.detail } + end + response.editor = { kind = state.editor.kind, title = state.editor.title, items = items, allowOther = state.editor.allowOther } + end + if state.confirmation then response.confirmation = { title = "Confirm safety warning", detail = state.confirmation.warning } end + if state.done then + response.done, response.result, response.notice = true, state.result, state.notice + else + response.state = json.encode(state) + end + for _, row in ipairs(response.rows) do + row.label, row.value = safe(row.label), safe(row.value) + if row.detail then row.detail = safe(row.detail) end + end + if response.error then response.error = safe(response.error) end + if response.notice then response.notice = safe(response.notice) end + if response.editor then + response.editor.title = safe(response.editor.title) + for _, item in ipairs(response.editor.items) do + item.title = safe(item.title) + if item.detail then item.detail = safe(item.detail) end + end + end + if response.confirmation then + response.confirmation.title = safe(response.confirmation.title) + response.confirmation.detail = safe(response.confirmation.detail) + end + return contracts.validate("ChooserResponse", response) +end +local request = M.request +function M.request(args, command) + return rex.withOperation(function() return request(args, command) end) +end + +return M diff --git a/src/client.lua b/src/client.lua index fab992d..4700f97 100644 --- a/src/client.lua +++ b/src/client.lua @@ -4,7 +4,7 @@ local rex = require("rex") local json = system.json local M = {} local function machinesIn(registry) - local label = registry.home.this_machine and registry.home.label ~= "" and registry.home.label or "This machine" + local label = registry.home.this_machine and registry.home.label ~= "" and registry.home.label or system.hostname() local result = json.array({ { key = "local", @@ -19,7 +19,28 @@ local function machinesIn(registry) end return result end -function M.listMachines() return machinesIn(rex.machinesRegistry()) end +function M.listMachines(originKey) + local machines = machinesIn(rex.machinesRegistry()) + if originKey and originKey ~= "local" then + local origin + for _, machine in ipairs(machines) do if machine.key == originKey then origin = machine end end + if origin then + local source = M.connectMachine(origin) + local aliases = contracts.decode("RexHosts", rex.remoteRex(source.selector, { "api", "call", "hosts.list" })) + local localHost = rex.localHost() + if not system.isNull(aliases.hosts) then + for _, alias in ipairs(aliases.hosts) do + local matches = alias.host_id == localHost.id + for _, endpoint in ipairs(alias.endpoints) do + if endpoint == localHost.endpoint then matches = true end + end + if matches then machines[1].label = alias.label; break end + end + end + end + end + return machines +end function M.connectMachine(machine) local registry = rex.machinesRegistry() local current @@ -52,7 +73,7 @@ function M.connectMachine(machine) if not found then system.fail("Rex machine " .. current.label .. " resolved to an unexpected server; refusing to route remotely") end - local actions = contracts.decode("RexActions", rex.remoteRex(current.selector, { "actions", "--json" })) + local actions = rex.remoteActions(current.selector) local helper for _, action in ipairs(actions.actions) do if action.name == "worktrees_request" then @@ -119,7 +140,7 @@ function M.connectAndDiscover(machine, command, context) return rex.withOperation(function() local host = M.connectMachine(machine) local body = { kind = "discover" } - if host["local"] and context then body.context = context end + if context then body.context = context end local result = connectedRequest(host, command, body) result.host = host return result diff --git a/src/contracts.lua b/src/contracts.lua index 4662164..5943ac1 100644 --- a/src/contracts.lua +++ b/src/contracts.lua @@ -121,11 +121,11 @@ local session = schemas.SessionSelection = session local target = shape({ id = S, label = S }) local gitSource = - shape({ vcs = literal("git"), url = S, sourceHostId = S, branches = optional(array(S)), branch = optional(S) }) + shape({ vcs = literal("git"), url = S, sourceHostId = optional(S), branches = optional(array(S)), branch = optional(S) }) local jjSource = shape({ vcs = literal("jj"), url = S, - sourceHostId = S, + sourceHostId = optional(S), revisions = optional(array(choice)), revision = optional(revision), }) @@ -150,11 +150,13 @@ local jjInput = shape(extend(commonInput, { local input = union(gitInput, jjInput) local cloneCommon = extend(commonInput, { worktreeName = optional(S), checkout = optional(literal("primary", "worktree")) }) -local gitClone = shape( - extend( - cloneCommon, - { vcs = literal("git"), source = gitSource, branch = S, branchMode = literal("existing", "create") } - ) +local defaultGitClone = + shape(extend(cloneCommon, { vcs = literal("git"), source = gitSource, branchMode = literal("default"), checkout = literal("primary") })) +local gitClone = union( + shape(extend(cloneCommon, { vcs = literal("git"), source = gitSource, branch = S, branchMode = literal("existing", "create") })), + { predicate = function(v) + return check(defaultGitClone, v) and v.branch == nil and v.worktreeName == nil and v.directory == nil + end } ) local jjClone = shape(extend(cloneCommon, { vcs = literal("jj"), source = jjSource, revision = optional(S) })) local cloneInput = union(gitClone, jjClone) @@ -299,7 +301,52 @@ local function variants(entries) end schemas.Request = variants(req) schemas.Response = variants(res) -define("RexIdentity", { host_id = S, endpoint = S, principal = shape({ transport = S }) }) +local chooserField = literal("project", "machine", "session", "destination", "branch", "checkoutName", "mode") +define("ChooserRequest", { + op = literal("start", "edit", "accept", "cancel", "submit", "confirm"), + state = optional(S), + origin = optional(shape({ sessionId = optional(S), blockId = optional(S), clientId = optional(S), server = optional(S) })), + context = optional(S), + machine = optional(S), + field = optional(chooserField), + id = optional(S), + text = optional(S), +}) +define("ChooserState", { + draft = shape({ mode = literal("auto", "new-tab", "split") }), + origin = shape({ sessionId = optional(S), blockId = optional(S), clientId = optional(S), server = optional(S) }), + originMachine = optional(S), + projects = array(A), + projectsLoaded = optional(B), + sessions = array(A), + cloneRoot = S, + editor = optional(shape({ + field = chooserField, kind = literal("pick", "input"), title = S, + choices = array(shape({ id = S, value = A, title = S, detail = optional(S) })), allowOther = B, + })), + confirmation = optional(shape({ warning = S })), + blocked = optional(B), done = optional(B), error = optional(S), notice = optional(S), +}) +define("ChooserResponse", { + state = optional(S), + rows = array(shape({ id = chooserField, label = S, value = S, detail = optional(S), + disabled = optional(B), isReadOnly = optional(B) })), + submitLabel = S, submitDisabled = B, error = optional(S), notice = optional(S), + editor = optional(shape({ + kind = literal("pick", "input"), title = S, + items = array(shape({ id = S, title = S, subtitle = optional(S), detail = optional(S) })), + allowOther = B, value = optional(S), + })), + confirmation = optional(shape({ title = S, detail = S })), + done = optional(B), result = optional(union(launchResult, cloneResult)), +}) +define("RexIdentity", { + host_id = S, endpoint = S, principal = shape({ transport = S }), + tailscale = optional(nullable(shape({ https = optional(nullable(shape({ url = optional(S) }))) }))), +}) +define("RexHosts", { + hosts = nullable(array(shape({ label = S, endpoints = array(S), host_id = optional(S) }))), +}) define("RexSessions", { sessions = array(shape({ session_id = S, label = S })) }) define("RexCreated", { window_id = S, block_ids = array(S) }) define("RexSplitCreated", { block_ids = array(S) }) @@ -370,5 +417,4 @@ end return { validate = validate, decode = function(name, text) return validate(name, json.decode(text)) end, - popupSize = { columns = 80, rows = 16 }, } diff --git a/src/git.lua b/src/git.lua index b407523..2f46577 100644 --- a/src/git.lua +++ b/src/git.lua @@ -35,6 +35,18 @@ function M.gitContext(directory) local out = optional(function() return git(directory, "rev-parse", "--absolute-git-dir") end, M.notRepository) return out and trim(out) end +function M.githubRepository(value) + if type(value) ~= "string" then return nil end + local repo = value:match("^https://github%.com/([^/]+/[^/]+)/?$") + or value:match("^git@github%.com:([^/]+/[^/]+)$") + or value:match("^ssh://git@github%.com/([^/]+/[^/]+)$") + if not repo then return nil end + local owner, name = repo:match("^([A-Za-z0-9_.%-]+)/([A-Za-z0-9_.%-]+)$") + if not owner or owner == "." or owner == ".." then return nil end + name = name:gsub("%.git$", "") + if name == "" or name == "." or name == ".." then return nil end + return { url = value:gsub("/$", ""), name = name, identity = (owner .. "/" .. name):lower() } +end function M.safeOrigin(raw, sameHost, base) local function unsafe() system.fail("Unsafe origin URL") end if diff --git a/src/main.lua b/src/main.lua index 50a041f..ac3970f 100644 --- a/src/main.lua +++ b/src/main.lua @@ -6,10 +6,7 @@ local path = system.path local help = [=[rex-worktrees — Git worktrees and JJ workspaces on existing Rex machines setup [--bin /absolute/path/rex-worktrees] [--config /absolute/path/init.lua] install Lua module; copy binary to ~/.local/bin unless --bin is set - popup [--host HOST] [--context PATH | --no-context] [--origin-session ID [--origin-block ID]] [--origin-client ID] - interactive terminal chooser - launch-popup [--session ID] [--origin-block ID | --no-context] [--origin-client ID] [--host HOST] - open a floating chooser in the source window + chooser read a JSON chooser request on stdin, write a JSON response open --repo PATH --session ID --name NAME (--branch NAME | --worktree PATH) [--worktree-name NAME] Git: branch checkout or existing worktree open --repo PATH --session ID --name NAME (--worktree PATH | --worktree-name NAME --revision EXPR) @@ -19,7 +16,7 @@ local help = [=[rex-worktrees — Git worktrees and JJ workspaces on existing Re help --host selects an existing Rex host label or registry ID. Install setup separately on each destination.]=] -local booleans = { ["--additional"] = true, ["--split"] = true, ["--no-context"] = true } +local booleans = { ["--additional"] = true, ["--split"] = true } local strings = { ["--bin"] = true, ["--config"] = true, @@ -32,10 +29,6 @@ local strings = { ["--worktree"] = true, ["--worktree-name"] = true, ["--client"] = true, - ["--context"] = true, - ["--origin-session"] = true, - ["--origin-block"] = true, - ["--origin-client"] = true, } local function parseFlags(args) local flags, index = {}, 1 @@ -48,12 +41,10 @@ local function parseFlags(args) index = index + 1 local value = args[index] if not value or value == "" or value:sub(1, 2) == "--" then system.fail("Missing value for " .. flag) end - if flag == "--session" or flag == "--origin-session" then + if flag == "--session" then contracts.validate("SessionId", value) - elseif flag == "--client" or flag == "--origin-client" then + elseif flag == "--client" then contracts.validate("ClientId", value) - elseif flag == "--origin-block" then - contracts.validate("BlockId", value) end flags[flag] = value else @@ -68,11 +59,6 @@ local function only(flags, allowed, message) if not allowed[flag] then system.fail(message) end end end -local function envId(name, schema) - local value = system.getenv(name) - if value ~= nil then contracts.validate(schema, value) end - return value -end local function machineFor(selected) for _, machine in ipairs(client.listMachines()) do if @@ -118,90 +104,16 @@ local function main() return end local executable = system.command() - if verb == "popup" then - local flags = parseFlags(argv) - only( - flags, - { - ["--host"] = true, - ["--context"] = true, - ["--origin-session"] = true, - ["--origin-block"] = true, - ["--origin-client"] = true, - ["--no-context"] = true, - }, - "Invalid popup flags" - ) - if flags["--context"] and flags["--no-context"] then - system.fail("--context and --no-context are mutually exclusive") - end - if flags["--origin-block"] and not flags["--origin-session"] then - system.fail("--origin-block requires --origin-session") - end - local envSession = envId("REX_SESSION", "SessionId") - local sessionId = flags["--origin-session"] or envSession - local blockId = flags["--origin-block"] - or (not flags["--no-context"] and sessionId == envSession and envId("REX_BLOCK", "BlockId") or nil) - local origin = { - sessionId = sessionId, - blockId = blockId, - clientId = flags["--origin-client"] or envId("REX_CLIENT", "ClientId"), - } - local function context() - if flags["--context"] then return path.resolve(flags["--context"]) end - if flags["--no-context"] then return nil end - if #argv > 0 and sessionId and blockId then return rex.originDirectory(sessionId, blockId) end - return system.cwd() - end - require("ui").popup(executable, context, origin, flags["--host"]) - return - end - if verb == "launch-popup" then - local flags = parseFlags(argv) - only( - flags, - { ["--session"] = true, ["--host"] = true, ["--origin-block"] = true, ["--origin-client"] = true, ["--no-context"] = true }, - "Invalid launch-popup flags" - ) - if flags["--origin-block"] and flags["--no-context"] then - system.fail("--origin-block and --no-context are mutually exclusive") - end - local envSession = envId("REX_SESSION", "SessionId") - local sessionId = flags["--session"] or envSession - if not sessionId then system.fail("Specify --session ID or run inside a Rex terminal") end - local blockId = flags["--origin-block"] or (sessionId == envSession and envId("REX_BLOCK", "BlockId") or nil) - local clientId = flags["--origin-client"] or (sessionId == envSession and envId("REX_CLIENT", "ClientId") or nil) - if flags["--host"] and not machineFor(flags["--host"]) then - system.fail("Rex host " .. flags["--host"] .. " is not registered") - end - local command = { table.unpack(executable) } - command[#command + 1] = "popup" - command[#command + 1] = "--origin-session" - command[#command + 1] = sessionId - if flags["--origin-block"] and blockId then - local context = rex.originDirectory(sessionId, blockId) - command[#command + 1] = "--origin-block" - command[#command + 1] = blockId - command[#command + 1] = context and "--context" or "--no-context" - if context then command[#command + 1] = context end - elseif flags["--no-context"] then - command[#command + 1] = "--no-context" - else - command[#command + 1] = "--context" - command[#command + 1] = system.cwd() - end - if flags["--host"] then - command[#command + 1] = "--host" - command[#command + 1] = flags["--host"] - end - print(system.json.encode(rex.openPopup(command, sessionId, { blockId = blockId, clientId = clientId }))) + if verb == "chooser" then + if #argv > 0 then system.fail("chooser reads JSON from stdin") end + local raw = io.read("*a") + if not raw then system.fail("Failed reading stdin") end + local request = contracts.decode("ChooserRequest", raw) + print(system.json.encode(require("chooser").request(request, executable))) return end if verb == "open" then local flags = parseFlags(argv) - for _, key in ipairs({ "--context", "--origin-session", "--origin-block", "--origin-client", "--no-context" }) do - if flags[key] then system.fail("Context flags are only supported by popup") end - end if flags["--bin"] then system.fail("--bin is only supported by setup") end if not flags["--repo"] or not flags["--session"] or not flags["--name"] then system.fail("open requires --repo PATH --session ID --name NAME") diff --git a/src/rex.lua b/src/rex.lua index 5a2345c..4f8fd26 100644 --- a/src/rex.lua +++ b/src/rex.lua @@ -14,6 +14,12 @@ function M.withOperation(fn) return table.unpack(result, 2, result.n) end +local function cached(key, read, ...) + if not operation or operation.pid ~= system.pid() then return read(...) end + if operation[key] == nil then operation[key] = read(...) end + return operation[key] +end + local function name(value) return value:lower():gsub("%.$", ""):gsub("%.local$", "") end function M.localDirectoryUri(raw) if type(raw) ~= "string" or raw:find("\0", 1, true) then return nil end @@ -50,7 +56,8 @@ local function append(into, from) end return into end -function M.machinesRegistry() return contracts.decode("RexRegistry", run({ "hosts", "list", "--json" })) end +local function readRegistry() return contracts.decode("RexRegistry", run({ "hosts", "list", "--json" })) end +function M.machinesRegistry() return cached("registry", readRegistry) end local function readLocalIdentity() local endpoint = system.getenv("REX_WORKTREES_LOCAL_ENDPOINT") if endpoint and endpoint:sub(1, 8) ~= "unix:///" then @@ -70,11 +77,7 @@ local function readLocalIdentity() end return identity end -local function localIdentity() - if not operation or operation.pid ~= system.pid() then return readLocalIdentity() end - if not operation.identity then operation.identity = readLocalIdentity() end - return operation.identity -end +local function localIdentity() return cached("identity", readLocalIdentity) end function M.rex(args) local endpoint = system.getenv("REX_WORKTREES_LOCAL_ENDPOINT") if endpoint and endpoint:sub(1, 8) ~= "unix:///" then @@ -88,10 +91,20 @@ end function M.remoteRex(selector, args) return run(append({ "-S", selector, "--autostart=false", "--timeout", "30s" }, args)) end -function M.remoteIdentity(selector) +local function remoteIdentity(selector) return contracts.decode("RexIdentity", M.remoteRex(selector, { "whoami", "--json" })) end -function M.localHost() return { id = localIdentity().host_id, label = "This machine" } end +function M.remoteIdentity(selector) return cached("identity:" .. selector, remoteIdentity, selector) end +local function remoteActions(selector) + return contracts.decode("RexActions", M.remoteRex(selector, { "actions", "--json" })) +end +function M.remoteActions(selector) return cached("actions:" .. selector, remoteActions, selector) end +function M.localHost() + local identity = localIdentity() + local https = identity.tailscale and not system.isNull(identity.tailscale) and identity.tailscale.https + return { id = identity.host_id, label = "This machine", + endpoint = https and not system.isNull(https) and https.url or identity.endpoint } +end function M.listSessions() local result = json.array() for _, item in ipairs(contracts.decode("RexSessions", M.rex({ "ls", "--json" })).sessions) do @@ -138,7 +151,7 @@ function M.originDirectory(sessionId, blockId) local cwd = info.foreground and info.foreground ~= json.null and info.foreground.cwd if type(cwd) == "string" and cwd:sub(1, 1) == "/" and not cwd:find("\0", 1, true) then return cwd end end -local function terminalLayout(command, cwd, label, completion, size) +local function terminalLayout(command, cwd, label) local argv = json.array() local path, config = system.getenv("PATH"), system.getenv("REX_WORKTREES_CONFIG") if path or config then @@ -147,8 +160,7 @@ local function terminalLayout(command, cwd, label, completion, size) if config then argv[#argv + 1] = "REX_WORKTREES_CONFIG=" .. config end end append(argv, command) - local options = { command = argv, shell = "none", cwd = cwd, exit = { on_completion = completion or false } } - if size then options.size = size end + local options = { command = argv, shell = "none", cwd = cwd, exit = { on_completion = false } } return { block = { flavor = "com.superlogical.terminal.shell", label = label, options = options } } end function M.openTerminal(session, label, cwd, command, target) @@ -236,102 +248,7 @@ function M.focus(sessionId, windowId, blockId, clientId) end if #warnings > 0 then return table.concat(warnings, "; ") end end -local function findPane(node, blockId) - if not node or node == json.null then return nil end - if node.block_id == blockId then return node end - if node.split and node.split ~= json.null then - return findPane(node.split.before, blockId) or findPane(node.split.after, blockId) - end -end -function M.openPopup(command, sessionId, origin) - origin = origin or {} - local view = contracts.decode( - "RexView", - M.rex({ "api", "call", "-s", sessionId, "session.view", json.encode({ session_id = sessionId }) }) - ) - local source, owner - for _, window in ipairs(view.windows) do - for _, layer in ipairs(window.layers) do - for _, block in ipairs(layer.blocks) do - if block.block_id == origin.blockId then - source, owner = window, block.owner - end - end - end - end - if origin.blockId and not source then system.fail("Source pane is no longer in the selected Rex session") end - local windowId = source and source.window_id or view.active_window_id - local window - for _, item in ipairs(view.windows) do - if item.window_id == windowId then - window = item - break - end - end - if not window then system.fail("No active Rex window for the popup") end - local clients, clientId = M.listClients() - for _, id in ipairs({ owner or false, origin.clientId or false }) do - for _, client in ipairs(clients) do - if id and id == client.id then - clientId = id - break - end - end - if clientId then break end - end - local popupCommand = json.array() - append(popupCommand, command) - if clientId then append(popupCommand, { "--origin-client", clientId }) end - local first, focused, selected - for _, layer in ipairs(window.layers) do - for _, block in ipairs(layer.blocks) do - if block.flavor == "com.superlogical.terminal.shell" then - first = first or block - if block.block_id == window.focused_block_id then focused = block end - if block.block_id == origin.blockId then selected = block end - end - end - end - local terminal = selected or focused or first - local width, height = 1, 1 - local size = contracts.popupSize - if terminal then - local pane - for _, layer in ipairs(window.layers) do - pane = findPane(layer.layout, terminal.block_id) - if pane then break end - end - if not pane then system.fail("Rex terminal geometry changed before opening the popup") end - local actual = - contracts.decode("RexTerminalSize", M.rex({ "block", "call", "-s", sessionId, "-b", terminal.block_id, "size" })) - local zoomed = window.zoomed_block_id == terminal.block_id - width = math.min(1, (size.columns + 2) * (zoomed and 1 or pane.rect[3]) / actual.columns) - height = math.min(1, (size.rows + 3) * (zoomed and 1 or pane.rect[4]) / actual.rows) - end - local request = { - session_id = sessionId, - window_id = windowId, - bounds = json.array({ (1 - width) / 2, (1 - height) / 2, width, height }), - layout = terminalLayout(popupCommand, system.cwd(), "Worktrees", true, size), - focus = true, - } - local created = - contracts.decode("RexLayer", M.rex({ "api", "call", "-s", sessionId, "session.new_layer", json.encode(request) })) - local hasBlock = false - if created.block_ids and not system.isNull(created.block_ids) then - for _, id in ipairs(created.block_ids) do - if id and not system.isNull(id) then - hasBlock = true - break - end - end - end - if not created.layer_id or system.isNull(created.layer_id) or not hasBlock then - system.fail("Rex did not return a floating terminal layer") - end - return created -end -for _, key in ipairs({ "localBlocks", "originDirectory", "openPopup", "taskContext", "focus" }) do +for _, key in ipairs({ "localBlocks", "originDirectory", "taskContext", "focus" }) do local fn = M[key] M[key] = function(...) local args = table.pack(...) diff --git a/src/runtime.lua b/src/runtime.lua index 5bdb05f..6edc6d5 100644 --- a/src/runtime.lua +++ b/src/runtime.lua @@ -422,160 +422,7 @@ function M.run(program, args, cwd, env) end return r.stdout end -function M.background(fn) - local rd, wr = pipe() - local pid = checked(unistd.fork()) - if pid == 0 then - unistd.close(rd) - unistd.setpid("p", 0, 0) - local ok, value = pcall(fn) - local envelope = ok and { ok = true, value = value } - or { ok = false, message = M.message(value), code = type(value) == "table" and value.code or nil } - local encoded = json.encode(envelope) - pcall(writeAll, wr, encoded) - unistd.close(wr) - unistd._exit(0) - end - unistd.close(wr) - unistd.setpid("p", pid, pid) - local job = { pid = pid, fd = rd, chunks = {}, done = false } - function job:poll() - if self.done then return true, self.ok, self.value end - local ready = poll.rpoll(self.fd, 0) - if ready and ready > 0 then - local data = unistd.read(self.fd, 65536) - if data and data ~= "" then - self.chunks[#self.chunks + 1] = data - else - unistd.close(self.fd) - wait.wait(self.pid) - self.done = true - local ok, v = pcall(json.decode, table.concat(self.chunks)) - if ok then - self.ok = v.ok - if v.ok then - self.value = v.value - else - self.value = setmetatable({ message = v.message, code = v.code }, errorMeta) - end - else - self.ok = false - self.value = v - end - end - end - return self.done, self.ok, self.value - end - function job:wait() - while not self.done do - self:poll() - if not self.done then poll.rpoll(self.fd, 100) end - end - if not self.ok then error(self.value, 0) end - return self.value - end - function job:kill() - if not self.done then - signal.kill(-self.pid, signal.SIGKILL) - unistd.close(self.fd) - wait.wait(self.pid) - self.done = true - self.ok = false - self.value = setmetatable({ message = "Cancelled" }, errorMeta) - end - end - return job -end local unicode = {} -local function graphemeWidth(segment) - local first, joined, variation, keycap, regional - local modifiers = 0 - for _, cp in utf.codes(segment) do - first = first or cp - if cp == 0x200d then - joined = true - elseif cp == 0xfe0f then - variation = true - elseif cp == 0x20e3 then - keycap = true - elseif cp >= 0x1f1e6 and cp <= 0x1f1ff then - regional = (regional or 0) + 1 - elseif cp >= 0x1f3fb and cp <= 0x1f3ff then - modifiers = modifiers + utf.width(cp) - end - end - if keycap and first and (first == 0x23 or first == 0x2a or (first >= 0x30 and first <= 0x39)) then return 2 end - if regional == 2 then return 2 end - local width = utf.width(segment) - if first and (joined or variation or modifiers > 0) then - -- GB11 joins an extended pictograph after an existing pictograph and ZWJ. - local probe = "👩‍" .. utf.char(first) - local count = 0 - for _ in utf.grapheme_indices(probe) do - count = count + 1 - end - if count == 1 then - if joined then return 2 end - width = width - modifiers - if variation then width = math.max(width, 2) end - end - end - return width -end -function unicode.width(text) - local width = 0 - for a, b in utf.grapheme_indices(text) do - width = width + graphemeWidth(text:sub(a, b)) - end - return width -end -function unicode.dropLastGrapheme(text) - local last - for start in utf.grapheme_indices(text) do - last = start - end - return last and text:sub(1, last - 1) or "" -end -function unicode.fit(text, columns, ellipsis) - if columns <= 0 then return "" end - if unicode.width(text) <= columns then return text end - ellipsis = ellipsis or "" - if unicode.width(ellipsis) > columns then ellipsis = "" end - local left = math.max(0, columns - unicode.width(ellipsis)) - local parts = {} - local width = 0 - for a, b in utf.grapheme_indices(text) do - local segment = text:sub(a, b) - local w = graphemeWidth(segment) - if width + w > left then break end - parts[#parts + 1] = segment - width = width + w - end - return table.concat(parts) .. ellipsis -end -function unicode.wrap(text, columns) - local lines = json.array() - local current = "" - local width = 0 - for a, b in utf.grapheme_indices(text) do - local segment = text:sub(a, b) - local w = graphemeWidth(segment) - if segment == "\n" then - lines[#lines + 1] = current - current = "" - width = 0 - elseif width + w > columns and current ~= "" then - lines[#lines + 1] = current - current = segment - width = w - else - current = current .. segment - width = width + w - end - end - lines[#lines + 1] = current - return lines -end function unicode.sanitize(text, preserveWhitespace) text = utf.clean(text) text = text:gsub("\27%[[0-?]*[ -/]*[@-~]", ""):gsub("\27%][^\7]*\7", "") @@ -602,6 +449,5 @@ function unicode.sanitize(text, preserveWhitespace) if not preserveWhitespace then value = value:gsub("%s+", " "):gsub("^%s+", ""):gsub("%s+$", "") end return value end -unicode.fold = utf.fold M.unicode = unicode return M diff --git a/src/ui.lua b/src/ui.lua deleted file mode 100644 index 765258c..0000000 --- a/src/ui.lua +++ /dev/null @@ -1,1188 +0,0 @@ -local runtime = require("runtime") -local unicode = runtime.unicode -local path = runtime.path -local M = {} -local rowCount = 7 -local minRows = require("contracts").popupSize.rows -local function copy(t) - local r = {} - for k, v in pairs(t) do - r[k] = v - end - return r -end -local function trim(s) return (s:gsub("^%s+", ""):gsub("%s+$", "")) end -local function present(v) return v ~= nil and not runtime.isNull(v) end -local function safe(s, whitespace) return unicode.sanitize(tostring(s or ""), whitespace) end -local function pad(s, n) return s .. string.rep(" ", math.max(0, n - unicode.width((s:gsub("\27%[[%d;]*m", ""))))) end -local codes = { cyan = "\27[36m", amber = "\27[33m", muted = "\27[90m", red = "\27[31m", bold = "\27[1m" } -local function color(s, tone, enabled) return enabled and codes[tone] .. s .. "\27[0m" or s end -function M.renderFormFrame(view, focused, columns, rows, colors, options) - if colors == nil then colors = not runtime.getenv("NO_COLOR") end - options = options or {} - local width = math.max(2, columns) - if rows < minRows then - return unicode.fit(("Rex Worktrees needs %d terminal rows. Resize this pane; Esc closes."):format(minRows), width) - end - local screen = {} - local function add(s) - local remaining, out, pos = width, {}, 1 - while pos <= #s do - local first, last = s:find("\27%[[%d;]*m", pos) - local text = s:sub(pos, first and first - 1 or #s) - local part = unicode.fit(text, remaining, "…") - out[#out + 1] = part - remaining = math.max(0, remaining - unicode.width(part)) - if not first then break end - out[#out + 1] = s:sub(first, last) - pos = last + 1 - end - screen[#screen + 1] = pad(table.concat(out), width) - end - add(color("REX", "cyan", colors) .. " " .. color("/ WORKTREES", "bold", colors)) - add(color(string.rep("─", width), "muted", colors)) - local current, destination - for _, row in ipairs(view.rows) do - if row.id == focused then current = row end - if row.id == "destination" then destination = row end - local active = focused == row.id - local tone = row.disabled and "muted" or active and "cyan" or "bold" - local value = safe(row.value) - if value == "" then value = "—" end - add( - color(active and "›" or " ", tone, colors) - .. " " - .. color(pad(unicode.fit(safe(row.label):upper(), 13), 13), tone, colors) - .. " " - .. color(unicode.fit(value, math.max(1, width - 17), "…"), tone, colors) - ) - end - local heading = - unicode.fit(safe(options.editor and options.editor.title or current and current.label or "Details") .. " ", width) - add(color(heading .. string.rep("─", math.max(0, width - unicode.width(heading))), "muted", colors)) - local lines = {} - local subtitle = current and current.detail or destination and destination.detail - for _, message in ipairs({ view.error or false, view.notice or false, subtitle or false }) do - if message then - for _, line in ipairs(unicode.wrap(safe(message), math.max(1, width - 8))) do - lines[#lines + 1] = line - end - end - end - local count = rows - rowCount - 4 - local visible = options.editor and 1 or count - local offset = math.max(0, math.min(options.detailOffset or 0, #lines - visible)) - local function detail(i) - return (i == 1 and offset > 0 and "↑ " or "") - .. (lines[offset + i] or "") - .. (i == visible and offset + visible < #lines and " ↓ PgDn" or "") - end - if options.editor then - for i = 1, count - 1 do - add(options.editor.lines[i] or "") - end - add(view.error and color(detail(1), "red", colors) or "") - else - for i = 1, count do - add(color(detail(i), view.error and "red" or view.notice and "amber" or "muted", colors)) - end - end - local function hint(k, label) return color(k, "bold", colors) .. " " .. color(label, "muted", colors) end - local function button(label, active, primary, disabled) - return color( - (active and "›" or " ") .. "[ " .. safe(label) .. " ]", - disabled and "muted" or active and "cyan" or primary and "bold" or "muted", - colors - ) - end - add( - options.footer and color(options.footer, "muted", colors) - or options.editor and (hint("Enter", "accept") .. " · " .. hint("Esc", "back") .. " · " .. hint( - "↑↓", - "choices" - ) .. " · " .. hint("PgUp/PgDn", "details")) - or ( - button((view.submitLabel or "Open") .. " · Ctrl+S", focused == "submit", true, view.submitDisabled) - .. " " - .. button("Cancel · Esc", focused == "cancel") - .. " " - .. hint("Tab", "next") - ) - ) - return table.concat(screen, "\r\n") -end -local function matches(choices, text) - local result, query = {}, unicode.fold(text) - for i, choice in ipairs(choices) do - if unicode.fold(choice.title .. " " .. (choice.description or "")):find(query, 1, true) then - result[#result + 1] = i - 1 - end - end - return result -end --- Choice indexes deliberately remain zero-based, as in the original pure API. -function M.advanceInputChoice(state, name, text, choices, selectionOnly) - local function nextstate(value, selected) return { _tag = "NextFrame", state = { text = value, selected = selected } } end - if name == "escape" or name == "ctrl_c" then return { _tag = "Submit", value = runtime.json.null } end - if name == "ctrl_u" then return nextstate("", selectionOnly and state.selected or nil) end - local found = matches(choices, state.text) - if name == "up" or name == "down" or name == "tab" then - if #found == 0 then return { _tag = "Beep" } end - local current = name == "up" and 1 or 0 - if present(state.selected) then - current = 0 - for i, v in ipairs(found) do - if v == state.selected then - current = i - break - end - end - end - return nextstate(state.text, found[(current + (name == "up" and -1 or 1) - 1) % #found + 1]) - end - if name == "enter" or name == "ctrl_s" then - if present(state.selected) then - for _, i in ipairs(found) do - if i == state.selected then - return { _tag = "Submit", value = { kind = "selected", value = choices[i + 1].value } } - end - end - end - if not selectionOnly and trim(state.text) ~= "" then - return { _tag = "Submit", value = { kind = "typed", text = state.text } } - end - return { _tag = "Beep" } - end - if name == "backspace" or name == "delete" then - return nextstate(unicode.dropLastGrapheme(state.text), selectionOnly and state.selected or nil) - end - if text == "" or text:find("[%z\1-\31\127]") then return { _tag = "Beep" } end - return nextstate(state.text .. text, selectionOnly and state.selected or nil) -end -function M.renderInputChoice(state, choices, columns, colors, selectionOnly, count) - if colors == nil then colors = not runtime.getenv("NO_COLOR") end - count = count or minRows - rowCount - 6 - local width, found = math.max(20, columns), matches(choices, state.text) - local selected = 0 - for i, index in ipairs(found) do - if index == state.selected then - selected = i - break - end - end - local start = selected == 0 and 1 or math.max(1, math.min(selected, #found - count + 1)) - local text = safe(state.text, true) - if text == "" then text = selectionOnly and "Filter exact choices…" or "Type new value…" end - local lines = { color("›", "cyan", colors) .. " " .. unicode.fit(text, width - 2) } - for n = start, math.min(#found, start + count - 1) do - local index = found[n] - local choice = choices[index + 1] - lines[#lines + 1] = unicode.fit( - (state.selected == index and "›" or " ") - .. " " - .. safe(choice.title) - .. (choice.description and " · " .. safe(choice.description) or ""), - width - ) - end - return lines -end -local function directoryFor(d) - if d.destination and present(d.destination.path) then return d.destination.path end - if d.clone and not d.isCreating then return d.clone.repo end - if d.directory then return d.directory end - local repo = d.clone and d.clone.repo or d.project and d.project.path - local name = d.worktreeName or d.destination and d.destination.branch - if repo and name then return (d.worktreeRoot or repo .. ".worktrees"):gsub("/$", "") .. "/" .. name end -end -function M.generatedName(d) - return d.clone and not d.isCreating and (d.projectChoice and d.projectChoice.name or "Project") - or d.worktreeName - or d.destination and d.destination.label - or d.projectChoice and d.projectChoice.name - or "Worktree" -end -function M.inputFor(d) - if not (d.host and d.project and d.projectChoice and d.destination and d.session) then return end - local result = { - repo = d.project.vcs == "jj" and (d.sourcePath or d.project.path) or d.project.path, - session = d.session, - name = M.generatedName(d), - clientId = d.clientId, - additional = d.mode == "new-tab", - split = d.mode == "split", - vcs = d.project.vcs, - } - if present(d.destination.path) then - result.path = d.destination.path - return result - end - result.directory = directoryFor(d) - if not result.directory then return end - if d.project.vcs == "jj" then - if not (d.worktreeName and d.destination.revision) then return end - result.worktreeName, result.revision = d.worktreeName, d.destination.revision - else - if not d.destination.branch then return end - result.branch, result.worktreeName = d.destination.branch, d.worktreeName - end - return result -end -function M.changeProjectChoice(d, choice) - local r = copy(d) - r.projectChoice = choice - r.project, r.clone, r.destination, r.worktreeName, r.directory, r.worktreeRoot, r.sourcePath = - nil, nil, nil, nil, nil, nil, nil - r.isCreating = false - return r -end -function M.changeProject(d, candidate) - local r = copy(d) - local same = d.project and d.project.vcs == candidate.vcs and d.project.commonDir == candidate.commonDir - r.project, r.clone = candidate, nil - if not same then - r.destination, r.worktreeName, r.directory, r.sourcePath = nil, nil, nil, nil - end - r.isCreating = not not (same and d.isCreating) - if candidate.vcs ~= "jj" then r.sourcePath = nil end - return r -end -function M.changeDestination(d, candidate, name) - local r = copy(d) - r.destination = candidate - r.worktreeName = name - if present(candidate.path) then - r.worktreeName, r.directory, r.isCreating = nil, nil, false - end - return r -end -function M.selectWorktree(d, tree) - if not present(tree.path) or tree.vcs == "jj" and not tree.present then - runtime.fail( - "Workspace " - .. (tree.vcs == "jj" and tree.name or tostring(tree.path)) - .. " is unavailable; inspect its registered location before opening" - ) - end - local r = M.changeDestination( - d, - { path = tree.path, worktree = tree, label = tree.vcs == "jj" and tree.name or path.basename(tree.path) } - ) - if tree.vcs == "jj" then - r.sourcePath = tree.path - if d.projectChoice and d.projectChoice.source and d.host and d.projectChoice.source.hostId == d.host.hostId then - r.projectChoice = copy(d.projectChoice) - r.projectChoice.source = copy(d.projectChoice.source) - r.projectChoice.source.checkoutPath = tree.path - end - end - return r -end -function M.selectRevision(d, choice) - return M.changeDestination(d, { revision = choice.revision.commitId, label = choice.label }, d.worktreeName) -end -function M.cloneInputFor(d) - if not (d.host and d.clone and d.session and path.isAbsolute(d.clone.repo)) then return end - local directory = d.isCreating and directoryFor(d) or nil - if - d.isCreating - and (not directory or d.clone.vcs == "git" and d.destination and d.destination.branch == d.clone.branch) - then - return - end - local result = { - vcs = d.clone.vcs, - repo = d.clone.repo, - session = d.session, - clientId = d.clientId, - checkout = d.isCreating and "worktree" or "primary", - directory = directory, - name = M.generatedName(d), - worktreeName = d.isCreating and d.worktreeName or nil, - } - local source = { vcs = d.clone.vcs, url = d.clone.url, sourceHostId = d.clone.sourceHostId } - result.source = source - if d.clone.vcs == "jj" then - local revision = d.destination and d.destination.revision - if revision then - if d.clone.revision and d.clone.revision.commitId == revision then - source.revision = d.clone.revision - else - for _, choice in ipairs(d.clone.revisions or {}) do - if choice.revision.commitId == revision then - source.revision = choice.revision - break - end - end - end - end - source.revisions = runtime.json.array() - result.revision = revision - else - if not (d.destination and d.destination.branch) then return end - result.branch = d.destination.branch - result.branchMode = "create" - for _, branch in ipairs(d.clone.branches or {}) do - if branch == result.branch then - result.branchMode = "existing" - break - end - end - source.branches, source.branch = runtime.json.array(), d.clone.branch - end - return result -end - -function M.popup(command, contextFn, origin, preferredMachine) - local terminal = require("terminal") - local client = require("client") - origin = origin or {} - local draft, machines, projects, sessions = { mode = "auto" }, {}, {}, {} - local focus, errorText, blocked, cloneRoot = "project", nil, false, "" - local editor, notice, pending, detailOffset, branchPending = nil, nil, nil, 0, false - local function failure(message) runtime.fail(message) end - local function known(host, repository, checkout) - local source = { machineKey = host.key, hostId = host.hostId, repository = repository } - if - repository.vcs == "jj" - and present(checkout) - and checkout.vcs == "jj" - and checkout.commonDir == repository.commonDir - then - source.checkoutPath = checkout.path - end - return { name = repository.name, source = source } - end - local function focusClient(clients) - for _, item in ipairs(clients or {}) do - if item.id == draft.clientId then return item.id end - end - if draft.host and draft.host["local"] then - for _, item in ipairs(clients or {}) do - if item.id == origin.clientId then return item.id end - end - end - if #(clients or {}) == 1 then return clients[1].id end - end - local function useProject(found) - draft = M.changeProject(draft, found.project) - draft.worktreeRoot = found.worktreeRoot - if found.checkout.vcs == "jj" and not draft.sourcePath then draft.sourcePath = found.checkout.path end - if not draft.destination then - for _, tree in ipairs(found.worktrees) do - if - tree.path == found.checkout.path - and (tree.vcs == "jj" and tree.present or tree.vcs == "git" and not tree.bare and not tree.prunable) - then - draft = M.selectWorktree(draft, tree) - break - end - end - end - end - local function clonePath(choice) - if - choice.name - and choice.name ~= "." - and choice.name ~= ".." - and not choice.name:find("[/\\%c]") - and safe(choice.name) == choice.name - and cloneRoot ~= "" - then - return cloneRoot:gsub("/$", "") .. "/" .. choice.name - end - end - local function bind(choice, host, available) - local source = choice.source - local same = source and source.machineKey == host.key and source.hostId == host.hostId - local matches = {} - for _, repo in ipairs(available) do - if repo.name == choice.name and (not source or repo.vcs == source.repository.vcs) then - matches[#matches + 1] = repo - end - end - local directory = same and (source.checkoutPath or source.repository.path) or choice.path - if not directory and #matches == 1 then directory = matches[1].path end - if not directory and #matches > 1 then - failure("Multiple projects named " .. choice.name .. " on this machine; select its exact project directory") - end - directory = directory or (source and clonePath(choice)) - local function clone(repo) - if not source then failure("Choose a known source project before cloning") end - local machine - for _, item in ipairs(machines) do - if item.key == source.machineKey then - machine = item - break - end - end - if not machine then failure("Source Rex machine is no longer registered") end - local sourceHost = client.connectMachine(machine) - if sourceHost.hostId ~= source.hostId then - failure("Source Rex host identity changed; select the project again") - end - local inventory = client.sourceForClone(sourceHost, command, source.checkoutPath or source.repository.path) - inventory.repo = repo - return { clone = inventory } - end - if not directory then - if source then return clone("") end - failure("Select a known project or enter its absolute directory on this machine") - end - if not path.isAbsolute(directory) then failure("Project directory must be an absolute path on this machine") end - local ok, found = pcall(client.inspectProject, host, command, directory) - if not ok then - if source and runtime.message(found):find("Project directory does not exist:", 1, true) == 1 then - return clone(directory) - end - error(found, 0) - end - if - same and (found.project.vcs ~= source.repository.vcs or found.project.commonDir ~= source.repository.commonDir) - then - failure("Project directory changed; select the exact project directory again") - end - return { found = found } - end - local function applyBinding(choice, result, preserve) - if result.clone then - if not preserve then - draft = M.changeProjectChoice(draft, choice) - draft.clone = result.clone - if draft.clone.vcs == "git" and present(draft.clone.branch) then - draft.destination = { branch = draft.clone.branch, label = draft.clone.branch } - end - end - else - if not preserve then draft = M.changeProjectChoice(draft, choice) end - useProject(result.found) - end - end - local function view(initializing) - local jj = (draft.clone and draft.clone.vcs or draft.project and draft.project.vcs) == "jj" - local tree = draft.destination and present(draft.destination.path) and draft.destination.worktree - local ready = draft.host and (draft.project or draft.clone) - local directory = directoryFor(draft) - local session = draft.session and draft.session.kind == "new" and "New: " .. draft.session.name or nil - if not session and draft.session then - for _, item in ipairs(sessions) do - if item.id == draft.session.id then - session = item.label - break - end - end - end - local branch - if tree and tree.vcs == "jj" then - branch = tree.changeId:sub(1, 12) .. " · " .. tree.head:sub(1, 12) - elseif tree then - branch = present(tree.branch) and tree.branch or "Detached HEAD · " .. tree.head:sub(1, 12) - elseif jj then - branch = draft.destination and draft.destination.revision and draft.destination.label - or draft.clone and "Cloned default" - or "Choose a starting revision" - else - branch = draft.destination and draft.destination.branch or "Select or type branch" - end - local rows = { - { - id = "project", - label = "Project", - value = draft.projectChoice and draft.projectChoice.name or "Choose a project", - }, - { - id = "machine", - label = "Machine", - value = draft.machine and draft.machine.label or "Choose Rex host", - detail = draft.host and "Host ID: " .. draft.host.hostId or draft.machine and draft.machine.selector, - }, - { - id = "session", - label = "Session", - value = session or draft.session and draft.session.id or "Choose or type new session", - detail = draft.session and (draft.session.kind == "existing" and draft.session.id or "Create on submit"), - disabled = not draft.host, - }, - { - id = "destination", - label = jj and "Workspace" or "Worktree", - value = draft.clone and not draft.isCreating and "Project checkout (after clone)" - or draft.isCreating and (jj and "Create new workspace…" or "Create new worktree…") - or draft.destination and draft.destination.label - or (jj and "Choose a workspace" or "Choose a worktree"), - detail = tree and "Branch and Directory describe this worktree; select another worktree to change them." - or draft.isCreating - and (jj and "Choose the starting revision and directory for the new workspace." or "Choose an unused branch or a new branch name, then its directory."), - disabled = not ready, - }, - { - id = "branch", - label = tree and tree.vcs == "jj" and "Revision" or jj and "Start from" or "Branch", - value = branch, - detail = not tree - and ( - jj and "Revision for the new workspace; the source workspace is not moved." - or "Select an unused existing branch, or type the name of a new branch." - ), - isReadOnly = not not tree, - disabled = not ready or not tree and not draft.clone and not draft.isCreating, - }, - { - id = "checkoutName", - label = "Directory", - value = directory ~= "" and directory - or (draft.clone and "Choose an absolute directory" or "Choose a branch first"), - detail = directory, - isReadOnly = not not tree, - disabled = not ready or not draft.clone and not directory, - }, - { - id = "mode", - label = "Mode", - value = draft.clone and "New tab (cloning)" - or draft.mode == "auto" and "Reuse matching tab, otherwise new tab" - or draft.mode == "new-tab" and "Always new tab" - or "Split matching tab, otherwise new tab", - isReadOnly = not not draft.clone, - disabled = not draft.host, - }, - } - if initializing then - for _, row in ipairs(rows) do - row.disabled = true - end - end - local problem = errorText - or ( - not draft.projectChoice and "Select a project" - or not draft.machine and "Select a Rex machine" - or not draft.host and "Connect to the selected machine and install its worktrees helper if missing" - or not ready and "Select the exact project directory on this machine" - or not draft.destination and not draft.clone and "Choose an existing worktree or Create new worktree…" - or not jj and not tree and not (draft.destination and draft.destination.branch) and "Choose a branch" - or jj and draft.isCreating and not (draft.destination and draft.destination.revision) and not draft.clone and "Choose a starting revision" - or not directory and "Choose an absolute directory" - or not draft.session and "Choose an existing Rex session or type a new name" - ) - return { - rows = rows, - submitLabel = draft.clone and "Clone & open" - or tree and (jj and "Open workspace" or "Open worktree") - or jj and "Create workspace & open" - or "Create worktree & open", - submitDisabled = initializing or blocked or not draft.host or not (M.cloneInputFor(draft) or M.inputFor(draft)), - notice = initializing and "Discovering projects and Rex sessions…" - or draft.clone - and ("This project will be cloned onto this machine: " .. (draft.clone.repo ~= "" and draft.clone.repo or "choose its Directory") .. ". Only pushed history transfers."), - error = not initializing and problem or nil, - } - end - local function start(fn, done, label) pending = { job = runtime.background(fn), done = done, label = label } end - local function activate(machine, context) - local previous, previousHost = draft, draft.host and draft.host.hostId - draft = { machine = machine, projectChoice = draft.projectChoice, mode = draft.mode } - sessions = {} - cloneRoot = "" - errorText = nil - start(function() - local found = client.connectAndDiscover(machine, command, context) - local choice = previous.projectChoice - local inspected - if not choice and present(found.checkout) and present(context) then - inspected = { found = client.inspectProject(found.host, command, found.checkout.path) } - choice = known(found.host, inspected.found.project, inspected.found.checkout) - elseif choice then - cloneRoot = present(found.cloneRoot) and found.cloneRoot or "" - inspected = bind(choice, found.host, found.projects) - end - return { discovered = found, choice = choice, inspected = inspected } - end, function(result) - local found, host = result.discovered, result.discovered.host - if previous.machine and previous.machine.key == machine.key and previousHost == host.hostId then - draft = copy(previous) - draft.machine, draft.host = machine, host - else - draft.host = host - end - cloneRoot, sessions = present(found.cloneRoot) and found.cloneRoot or "", found.sessions or {} - local retained = {} - for _, item in ipairs(projects) do - if not item.source or item.source.machineKey ~= machine.key or item.source.hostId ~= host.hostId then - retained[#retained + 1] = item - end - end - for _, repo in ipairs(found.projects or {}) do - retained[#retained + 1] = known(host, repo, found.checkout) - end - projects = retained - local valid = draft.session and draft.session.kind == "new" - for _, item in ipairs(sessions) do - if draft.session and draft.session.kind == "existing" and item.id == draft.session.id then valid = true end - end - if not valid then - draft.session = nil - if host["local"] then - for _, item in ipairs(sessions) do - if item.id == origin.sessionId then draft.session = { kind = "existing", id = item.id } end - end - end - if not draft.session and #sessions == 1 then draft.session = { kind = "existing", id = sessions[1].id } end - end - draft.clientId = focusClient(found.clients) - if result.choice and result.inspected then - applyBinding( - result.choice, - result.inspected, - previous.machine - and previous.machine.key == machine.key - and previousHost == host.hostId - and previous.projectChoice ~= nil - ) - end - errorText = nil - end, "Connecting to " .. machine.label .. "…") - end - local function choose(title, choices, exact, onAccept) - local selectedIndex - for i, choice in ipairs(choices) do - if choice.selected then - selectedIndex = i - 1 - break - end - end - editor = { - title = title, - choices = choices, - selectionOnly = exact, - state = { text = "", selected = selectedIndex }, - accept = onAccept, - } - detailOffset = 0 - end - local function selected(value, isSelected, title, description) - return { value = value, selected = isSelected, title = title, description = description } - end - local function operate(fn, done, label) start(fn, done, label or "Loading…") end - local function openField(field) - if field == "project" then - local choices = {} - for _, item in ipairs(projects) do - choices[#choices + 1] = selected( - item, - false, - item.name, - (item.source and item.source.repository.path or item.path or "") .. " · Source machine" - ) - end - choose("Project (select known or type name / absolute path)", choices, false, function(picked) - local text = picked.text and trim(picked.text) - local choice = picked.kind == "selected" and picked.value - or { name = path.basename(text), path = path.isAbsolute(text) and text or nil } - if choice.name == "" then failure("Project name is required") end - if not draft.host then - draft = M.changeProjectChoice(draft, choice) - return - end - local available = {} - for _, item in ipairs(projects) do - if item.source and item.source.machineKey == draft.host.key and item.source.hostId == draft.host.hostId then - available[#available + 1] = item.source.repository - end - end - operate( - function() return bind(choice, draft.host, available) end, - function(result) applyBinding(choice, result) end - ) - end) - elseif field == "machine" then - operate(client.listMachines, function(found) - machines = found - if #machines == 0 then failure("No Rex machines available") end - local choices = {} - for _, item in ipairs(machines) do - choices[#choices + 1] = selected( - item, - draft.machine and item.key == draft.machine.key, - item.label, - item["local"] and "This machine" or "Rex host · " .. item.selector - ) - end - choose("Execution machine", choices, true, function(picked) activate(picked.value) end) - end) - elseif field == "session" then - operate(function() return client.inspectSessions(draft.host, command) end, function(found) - sessions = found.sessions - draft.clientId = focusClient(found.clients) - local choices = {} - for _, item in ipairs(sessions) do - choices[#choices + 1] = selected(item.id, false, item.label, item.id) - end - choose( - "Session (select existing or type new name)", - choices, - false, - function(picked) - draft.session = picked.kind == "selected" and { kind = "existing", id = picked.value } - or { kind = "new", name = picked.text } - end - ) - end) - elseif field == "mode" then - choose("Open mode", { - selected("auto", draft.mode == "auto", "Reuse matching tab", "Focus existing task, otherwise open new tab"), - selected("new-tab", draft.mode == "new-tab", "Always new tab"), - selected("split", draft.mode == "split", "Split matching task", "Opens new tab when no live target exists"), - }, true, function(picked) draft.mode = picked.value end) - elseif field == "checkoutName" then - local proposed = draft.clone and not draft.isCreating and draft.projectChoice and clonePath(draft.projectChoice) - or directoryFor(setmetatable({ directory = false }, { __index = draft })) - local choices = proposed and { selected(proposed, false, "Use proposed directory", proposed) } or {} - choose("Directory (absolute path on selected machine)", choices, false, function(picked) - local text = trim(picked.kind == "selected" and picked.value or picked.text) - if - not path.isAbsolute(text) - or text:find("[%z\1-\31\127]") - or path.dirname(path.resolve(text)) == path.resolve(text) - then - failure("Directory must be an absolute non-root path on this machine") - end - local directory = path.resolve(text) - if draft.clone and not draft.isCreating then - draft.clone.repo = directory - else - draft.directory = directory - if (draft.clone and draft.clone.vcs or draft.project.vcs) == "jj" then - draft.worktreeName = path.basename(directory) - end - end - end) - elseif field == "destination" or field == "branch" then - local jj = (draft.clone and draft.clone.vcs or draft.project.vcs) == "jj" - operate( - function() - return draft.clone - and { worktrees = {}, branches = draft.clone.branches or {}, revisions = draft.clone.revisions or {} } - or client.inspectWorktrees( - draft.host, - command, - jj and (draft.sourcePath or draft.project.path) or draft.project.path - ) - end, - function(found) - if field == "destination" then - local choices, trees = {}, {} - for _, tree in ipairs(found.worktrees or {}) do - if tree.vcs == "jj" or not tree.bare and not tree.prunable then - trees[#trees + 1] = tree - local title = tree.vcs == "jj" and ((tree.present and "" or "Unavailable: ") .. tree.name) - or path.basename(tree.path) - local description = tree.vcs == "jj" - and (tree.present and present(tree.path) and tree.changeId:sub(1, 12) .. " · " .. tree.path or "Unavailable · " .. (present( - tree.path - ) and tree.path or "location unknown")) - or (present(tree.branch) and tree.branch or "Detached HEAD") .. " · " .. tree.path - choices[#choices + 1] = - selected(tree, draft.destination and tree.path == draft.destination.path, title, description) - end - end - if draft.clone then - choices[#choices + 1] = - selected("primary", not draft.isCreating, "Project checkout (after clone)", draft.clone.repo) - end - choices[#choices + 1] = selected( - "create", - draft.isCreating, - jj and "Create new workspace…" or "Create new worktree…", - jj and "Choose starting revision and directory" or "Choose branch and directory" - ) - choose( - jj and "Workspace (select existing or create new)" or "Worktree (select existing or create new)", - choices, - true, - function(picked) - local value = picked.value - if value == "primary" then - draft.isCreating, draft.directory, draft.worktreeName = false, nil, nil - draft.destination = present(draft.clone.branch) - and { branch = draft.clone.branch, label = draft.clone.branch } - or nil - elseif value == "create" then - local name, suffix = "workspace", 2 - if jj then - local used = {} - for _, tree in ipairs(trees) do - used[tree.name] = true - end - while used[name] do - name = "workspace-" .. suffix - suffix = suffix + 1 - end - end - local mainline - for _, choice in ipairs(found.revisions or {}) do - if choice.expression == "trunk()" then - mainline = choice - break - end - end - draft.isCreating, draft.directory, draft.worktreeName = true, nil, jj and name or nil - draft.worktreeRoot = found.worktreeRoot or draft.worktreeRoot - draft.destination = jj - and mainline - and { revision = mainline.revision.commitId, label = mainline.label } - or { label = jj and "Create new workspace…" or "Create new worktree…" } - branchPending = not jj - else - draft = M.selectWorktree(draft, value) - end - end - ) - elseif jj then - local choices = {} - if draft.clone then - choices[#choices + 1] = - selected(runtime.json.null, false, "Cloned default", "Use the clone's native default") - end - for _, choice in ipairs(found.revisions or {}) do - choices[#choices + 1] = selected( - choice, - false, - choice.label, - choice.expression .. " · " .. choice.revision.commitId:sub(1, 12) - ) - end - choose( - draft.clone and "Start from source revision (or cloned default)" - or "Start from revision for new workspace", - choices, - false, - function(picked) - if picked.kind == "selected" and not present(picked.value) then - draft.destination = nil - return - end - local function apply(choice) - draft = M.selectRevision(draft, choice) - if draft.clone then draft.clone.revision = choice.revision end - end - if picked.kind == "selected" then - apply(picked.value) - return - end - local expression = trim(picked.text) - operate(function() - local host, repo = draft.host, draft.sourcePath or draft.project and draft.project.path - if draft.clone then - local source = draft.projectChoice.source - local machine - for _, item in ipairs(machines) do - if item.key == source.machineKey then machine = item end - end - if not machine then failure("Clone source machine is no longer registered") end - host = client.connectMachine(machine) - if host.hostId ~= source.hostId or host.hostId ~= draft.clone.sourceHostId then - failure("Clone source host identity changed; reselect the project") - end - repo = source.checkoutPath or source.repository.path - end - return client.inspectRevision(host, command, repo, expression) - end, function(revision) - apply({ expression = expression, label = expression, revision = revision }) - end) - end - ) - else - local occupied = {} - for _, tree in ipairs(found.worktrees or {}) do - if tree.vcs == "git" and present(tree.branch) then occupied[tree.branch] = true end - end - if draft.clone and draft.isCreating and present(draft.clone.branch) then - occupied[draft.clone.branch] = true - end - local choices = {} - for _, branch in ipairs(found.branches or {}) do - if not occupied[branch] then - choices[#choices + 1] = selected( - branch, - false, - branch, - draft.clone and "Published branch" or "Existing branch · new worktree" - ) - end - end - choose("Branch (select unused or type new name)", choices, false, function(picked) - local branch = picked.kind == "selected" and picked.value or trim(picked.text) - if branch == "" or branch:sub(1, 1) == "-" or branch:find("[%z\1-\31\127]") then - failure("Branch name must be a valid Git branch") - end - if occupied[branch] then - failure("Branch " .. branch .. " is already checked out; select its existing worktree instead") - end - draft.destination = { branch = branch, label = branch } - end) - end - end - ) - end - end - local function submit() - local input = M.cloneInputFor(draft) or M.inputFor(draft) - if not input then return end - local clone = not not draft.clone - operate( - function() - return clone and client.reviewClone(draft.host, command, input) or client.review(draft.host, command, input) - end, - function(plan) - if - plan.hostId ~= draft.host.hostId - or clone and (plan.repo ~= input.repo or plan.input.checkout ~= input.checkout or plan.input.directory ~= input.directory) - or not clone - and (input.path and plan.path ~= input.path or input.directory and plan.path ~= input.directory) - then - errorText = plan.hostId ~= draft.host.hostId and "Rex target changed; select the machine again" - or clone and ("Clone destination changed; edit the destination: " .. plan.repo) - or ("Destination changed; select the worktree again: " .. plan.path) - blocked = true - return - end - start( - function() return (clone and client.submitClone or client.submit)(draft.host, command, input, plan) end, - function(result) - if result.warning or not clone and plan.warning then - notice = { - title = clone and "Clone task submitted with warning" or "Opened with warning", - text = "Session: " - .. result.sessionId - .. " · Destination: " - .. (clone and result.repo or result.path) - .. " · " - .. (result.warning or plan.warning), - exit = true, - } - else - notice = { exit = true, immediate = true } - end - end, - "Submitting task…" - ) - pending.submitted = true - pending.fail = function(err) - notice = { - title = clone and "Clone needs inspection" or "Launch needs inspection", - text = runtime.message(err) - .. " · Destination: " - .. (clone and plan.repo or plan.path) - .. " · The checkout or Rex tab may already have changed. Inspect the destination and session before opening again.", - err = err, - } - end - end, - "Reviewing destination…" - ) - end - local keymap = terminal.input.keymap.get_keymap({ - ["\r"] = "enter", - ["\n"] = "enter", - ["\t"] = "tab", - ["\8"] = "backspace", - ["\127"] = "backspace", - ["\27"] = "escape", - ["\27[Z"] = "backtab", - }) - local function loop() - local system = require("system") - assert( - system.tcsetattr( - io.stdin, - system.TCSANOW, - { iflag = system.tcgetattr(io.stdin).iflag - system.I_IXON - system.I_IXOFF } - ) - ) - start(function() return { context = contextFn(), machines = client.listMachines() } end, function(result) - machines = result.machines - local initial - for _, machine in ipairs(machines) do - if - preferredMachine - and (machine.key == preferredMachine or machine.selector == preferredMachine or machine.label == preferredMachine) - or not preferredMachine and machine["local"] - then - initial = machine - break - end - end - if initial then - activate(initial, initial["local"] and result.context or nil) - elseif preferredMachine then - errorText = "Machine " .. preferredMachine .. " is not in Rex hosts. Select a connected machine." - end - end, "Discovering projects and Rex sessions…") - local lastRows, lastColumns, current - local redraw = true - while true do - if pending then - local done, ok, result = pending.job:poll() - if done then - redraw = true - local completed = pending - pending = nil - if ok then - local applied, err = pcall(completed.done, result) - if not applied then errorText = runtime.message(err) end - elseif completed.fail then - completed.fail(result) - elseif completed.label == "Discovering projects and Rex sessions…" then - notice = { title = "Could not open worktrees", text = runtime.message(result), err = result } - else - errorText = runtime.message(result) - end - end - end - if notice and notice.immediate then return end - if branchPending and not pending and not editor then - branchPending = false - focus = "branch" - local ok, err = pcall(openField, "branch") - if not ok then errorText = runtime.message(err) end - end - local rows, columns = terminal.size() - rows, columns = rows or minRows, columns or 80 - if redraw or rows ~= lastRows or columns ~= lastColumns then - current = view(pending ~= nil) - if pending then current.notice = pending.label end - if notice then - current.error = notice.title .. " · " .. notice.text - current.notice = nil - end - local options = { detailOffset = detailOffset } - if editor then - options.editor = { - title = editor.title, - lines = M.renderInputChoice( - editor.state, - editor.choices, - columns, - nil, - editor.selectionOnly, - math.max(1, rows - rowCount - 6) - ), - } - end - if notice then options.footer = "Enter / Space close · Esc close · PgUp/PgDn details" end - terminal.output.write( - "\27[?25l\27[H\27[2J", - M.renderFormFrame(current, focus, columns, rows, nil, options), - "\27[0J" - ) - lastRows, lastColumns = rows, columns - redraw = false - end - local raw, typ = terminal.input.readansi(0.1) - if raw then - redraw = true - local key = keymap[raw] or raw - if notice then - if key == "pageup" or key == "pagedown" then - detailOffset = math.max(0, detailOffset + (key == "pageup" and -1 or 1)) - elseif key == "enter" or key == "escape" or raw == " " or key == "ctrl_c" then - if notice.err then error(notice.err, 0) end - return - end - elseif editor then - if rows >= minRows or key == "escape" or key == "ctrl_c" then - if key == "pageup" or key == "pagedown" then - detailOffset = math.max(0, detailOffset + (key == "pageup" and -1 or 1)) - else - local action = M.advanceInputChoice( - editor.state, - key, - typ == "char" and raw or "", - editor.choices, - editor.selectionOnly - ) - if action._tag == "NextFrame" then - editor.state = action.state - elseif action._tag == "Submit" then - local accepting = editor - editor = nil - if present(action.value) then - local ok, err = pcall(accepting.accept, action.value) - if ok then - blocked = false - else - errorText = runtime.message(err) - end - end - else - terminal.bell() - end - end - end - elseif key == "escape" or key == "ctrl_c" or key == "ctrl_d" then - if pending and pending.submitted then - terminal.bell() - else - if pending then - pending.job:kill() - pending = nil - end - return - end - elseif rows >= minRows then - if key == "pageup" or key == "pagedown" then - detailOffset = math.max(0, detailOffset + (key == "pageup" and -1 or 1)) - elseif pending and not pending.submitted and (key == "backtab" or key == "tab") then - focus = "cancel" - elseif pending and not pending.submitted and key == "enter" and focus == "cancel" then - pending.job:kill() - pending = nil - return - elseif not pending then - local fields = {} - for _, row in ipairs(current.rows) do - if not row.disabled and not row.isReadOnly then fields[#fields + 1] = row.id end - end - fields[#fields + 1], fields[#fields + 2] = "submit", "cancel" - local index = 1 - for i, field in ipairs(fields) do - if field == focus then - index = i - break - end - end - if key == "ctrl_s" or key == "enter" and focus == "submit" then - if not current.submitDisabled then - submit() - else - terminal.bell() - end - elseif key == "enter" and focus == "cancel" then - return - elseif key == "enter" then - errorText = nil - local ok, err = pcall(openField, focus) - if not ok then errorText = runtime.message(err) end - elseif key == "up" or key == "backtab" or key == "k" then - focus = fields[(index - 2) % #fields + 1] - elseif key == "down" or key == "tab" or key == "j" then - focus = fields[index % #fields + 1] - end - end - end - end - end - end - local ok, result = - pcall(terminal.initwrap(loop, { displaybackup = true, disable_sigint = true, skip_width_detection = true })) - if pending then - if pending.submitted then - pcall(function() pending.job:wait() end) - else - pending.job:kill() - end - end - if not ok then error(result, 0) end -end - -return M diff --git a/src/worktrees.lua b/src/worktrees.lua index 0db56ae..b91afd9 100644 --- a/src/worktrees.lua +++ b/src/worktrees.lua @@ -76,10 +76,8 @@ local function liveBlock(sessionId, blockId, destination) then return false end - local reported = call("pwd", "RexDirectory") - if not reported or not reported.pwd or reported.pwd == system.json.null then return false end - local directory = rex.localDirectoryUri(reported.pwd) - if not directory then return false end + local directory = process.foreground.cwd + if type(directory) ~= "string" or not path.isAbsolute(directory) or directory:find("\0", 1, true) then return false end local ok, result = system.try(function() return fs.realPath(directory) end) if not ok then if system.missing(result) then return false end @@ -436,6 +434,12 @@ function M.task(request) end) end +local function sameOrigin(actual, requested) + if actual == requested then return true end + local a, b = git.githubRepository(actual), git.githubRepository(requested) + return a ~= nil and b ~= nil and a.identity == b.identity +end + function M.cloneDestination(destination, url, vcs, sourceHostId) vcs = vcs or "git" normalizedDirectory(destination, "Clone destination must be a normalized absolute directory") @@ -476,7 +480,7 @@ function M.cloneDestination(destination, url, vcs, sourceHostId) end local actual = repo.vcs == "git" and git.origin(current) or jj.cloneSource(current, sourceHostId or rex.localHost().id, repo, false).url - if actual ~= url then system.fail("Clone destination belongs to a different origin: " .. current) end + if not sameOrigin(actual, url) then system.fail("Clone destination belongs to a different origin: " .. current) end return repo.commonDir end if parent == current then system.fail("Invalid clone destination") end @@ -512,6 +516,17 @@ local function validateCloneDestination(input) if input.checkout == "primary" and input.worktreeName then system.fail("Primary checkout cannot have a worktree name") end + if input.vcs == "git" then + if input.branchMode == "default" then + if input.checkout ~= "primary" or input.branch ~= nil or input.worktreeName ~= nil or input.directory ~= nil then + system.fail("Default branch mode requires a primary checkout without a branch or worktree") + end + elseif input.branchMode == "existing" or input.branchMode == "create" then + git.validCloneBranch(input.branch, input.worktreeName) + else + system.fail("Invalid Git clone branch mode") + end + end if input.checkout == "worktree" and input.vcs == "jj" and not input.directory and not input.worktreeName then system.fail("JJ worktree checkout requires a workspace name or directory") end @@ -533,9 +548,7 @@ function M.planClone(input, expectedHostId) system.fail("Requested Rex app client is not connected") end validName(input.name, "tab") - if input.vcs == "git" then - git.validCloneBranch(input.branch, input.worktreeName) - elseif input.worktreeName and not input.worktreeName:match("%S") then + if input.vcs == "jj" and input.worktreeName and not input.worktreeName:match("%S") then system.fail("JJ workspace name cannot be blank") end local ok, url = system.try( @@ -549,6 +562,7 @@ function M.planClone(input, expectedHostId) existing and input.checkout == "primary" and input.vcs == "git" + and input.branchMode ~= "default" and (input.branchMode ~= "existing" or git.repositoryHead(input.repo).branch ~= input.branch) then system.fail("Existing primary checkout is not on the requested branch") @@ -659,9 +673,8 @@ function M.prepareCloneCheckout(plan) local input = plan.input validateCloneDestination(input) if plan.repo ~= input.repo then system.fail("Clone destination changed since review") end - if plan.vcs == "git" then git.validCloneBranch(input.branch, input.worktreeName) end local ok, url = system.try( - function() return git.safeOrigin(input.source.url, input.source.sourceHostId == plan.hostId) end + function() return git.safeOrigin(input.source.url, input.source.sourceHostId ~= nil and input.source.sourceHostId == plan.hostId) end ) if not ok then system.fail("Clone source URL is unsafe or local to another Rex host") end if url ~= input.source.url or input.vcs ~= plan.vcs then system.fail("Clone source changed since review") end @@ -724,7 +737,7 @@ function M.prepareCloneCheckout(plan) system.fail("Clone repository changed; retained at " .. plan.repo) end local actual = repo.vcs == "git" and git.origin(repo.path) or jj.cloneSource(repo.path, plan.hostId, repo, false).url - if actual ~= url then system.fail("Clone origin changed; retained at " .. plan.repo) end + if not sameOrigin(actual, url) then system.fail("Clone origin changed; retained at " .. plan.repo) end local cwd if plan.vcs == "jj" then local base = plan.base or jj.resolveRevision(repo.path, "@-") @@ -760,7 +773,7 @@ function M.prepareCloneCheckout(plan) local branch, mode = input.branch, input.branchMode if input.checkout == "primary" then if plan.existing then - if mode ~= "existing" or git.repositoryHead(repo.path).branch ~= branch then + if mode ~= "default" and (mode ~= "existing" or git.repositoryHead(repo.path).branch ~= branch) then system.fail("Existing primary checkout is not on the requested branch") end elseif mode == "create" then @@ -768,7 +781,7 @@ function M.prepareCloneCheckout(plan) system.fail("Branch " .. branch .. " already exists; clone retained at " .. plan.repo) end git.createPrimaryBranch(repo.path, branch) - elseif git.repositoryHead(repo.path).branch ~= branch then + elseif mode ~= "default" and git.repositoryHead(repo.path).branch ~= branch then system.fail("Cloned primary checkout is not on " .. branch .. "; clone retained at " .. plan.repo) end cwd = repo.path diff --git a/test/clone.test.lua b/test/clone.test.lua index 7c0049a..f8265fb 100644 --- a/test/clone.test.lua +++ b/test/clone.test.lua @@ -26,6 +26,63 @@ return function(root) fs.writeFileString(source .. "/tracked", "staged\n") at("add", "tracked") fs.writeFileString(source .. "/tracked", "dirty\n") + for _, url in ipairs({ + "https://github.com/Owner/Repo.git/", "git@github.com:Owner/Repo.git", "ssh://git@github.com/Owner/Repo", + }) do + local parsed = assert(git.githubRepository(url)) + assert(parsed.name == "Repo" and parsed.identity == "owner/repo" and parsed.url == url:gsub("/$", "")) + end + for _, url in ipairs({ + "https://user@github.com/a/b", "https://github.com/a/b/tree/main", "https://github.com/a/b?x=1", + "https://github.com/a/b#fragment", "https://github.com/../b", "https://github.com/a/.git", + "ssh://other@github.com/a/b", "git@github.com:a/b/", "https://github.com/a/b//", + }) do + assert(not git.githubRepository(url), url) + end + cmd("--git-dir", bare, "symbolic-ref", "HEAD", "refs/heads/published") + local defaultRepo = dir .. "/remote-default" + local defaultPlan = { + vcs = "git", hostId = "fixture-host", repo = defaultRepo, existing = false, label = "Clone & Open", + input = { + vcs = "git", source = { vcs = "git", url = bare, sourceHostId = "fixture-host" }, + repo = defaultRepo, session = { kind = "existing", id = "session" }, name = "Task", + checkout = "primary", branchMode = "default", + }, + } + assert(worktrees.prepareCloneCheckout(defaultPlan).cwd == defaultRepo) + assert(cmd("-C", defaultRepo, "branch", "--show-current"):match("%S+") == "published") + cmd("-C", defaultRepo, "checkout", "--detach") + local detachedHead = cmd("-C", defaultRepo, "rev-parse", "HEAD") + defaultPlan.existing, defaultPlan.commonDir = true, git.repository(defaultRepo).commonDir + assert(worktrees.prepareCloneCheckout(defaultPlan).cwd == defaultRepo) + assert(not cmd("-C", defaultRepo, "branch", "--show-current"):match("%S")) + assert(cmd("-C", defaultRepo, "rev-parse", "HEAD") == detachedHead) + for _, invalid in ipairs({ + { branch = "main" }, { worktreeName = "task" }, { directory = dir .. "/tree" }, { checkout = "worktree" }, + }) do + local input = {} + for key, value in pairs(defaultPlan.input) do input[key] = value end + for key, value in pairs(invalid) do input[key] = value end + local invalidPlan = {} + for key, value in pairs(defaultPlan) do invalidPlan[key] = value end + invalidPlan.input = input + assert(not pcall(worktrees.prepareCloneCheckout, invalidPlan)) + end + local externalPlan = {} + for key, value in pairs(defaultPlan) do externalPlan[key] = value end + externalPlan.input = {} + for key, value in pairs(defaultPlan.input) do externalPlan.input[key] = value end + for _, url in ipairs({ bare, "file://" .. bare }) do + externalPlan.input.source = { vcs = "git", url = url } + assert(not pcall(worktrees.prepareCloneCheckout, externalPlan)) + end + cmd("-C", defaultRepo, "remote", "set-url", "origin", "git@github.com:Owner/Repo.git") + assert(worktrees.cloneDestination(defaultRepo, "https://github.com/owner/repo", "git") == defaultPlan.commonDir) + assert(not pcall(worktrees.cloneDestination, defaultRepo, "https://github.com/owner/other", "git")) + defaultPlan.input.source = { vcs = "git", url = "ssh://git@github.com/OWNER/REPO" } + assert(worktrees.prepareCloneCheckout(defaultPlan).cwd == defaultRepo) + assert(cmd("-C", defaultRepo, "remote", "get-url", "origin") == "git@github.com:Owner/Repo.git\n") + cmd("--git-dir", bare, "symbolic-ref", "HEAD", "refs/heads/main") local before, head = at("status", "--porcelain=v1", "-z"), at("rev-parse", "HEAD") local described = git.cloneSource(source, "fixture-host") assert(described.url == bare) diff --git a/test/form.test.lua b/test/form.test.lua index 5a1835d..37c0127 100644 --- a/test/form.test.lua +++ b/test/form.test.lua @@ -1,121 +1,5 @@ return function() - local ui, s = require("ui"), require("runtime") - local rows = { - { id = "project", label = "Project", value = "atelier" }, - { id = "machine", label = "Machine", value = "Homelab", detail = "Host ID: host-remote" }, - { id = "session", label = "Session", value = "session-123" }, - { id = "destination", label = "Worktree", value = "feature", detail = "Destination details" }, - { id = "branch", label = "Branch", value = "feature" }, - { id = "checkoutName", label = "Directory", value = "/projects/atelier.worktrees/feature" }, - { id = "mode", label = "Mode", value = "Auto" }, - } - local view = { rows = rows, submitLabel = "Create worktree & open" } - local function lines(frame) - local out = {} - for line in (frame .. "\r\n"):gmatch("(.-)\r\n") do - out[#out + 1] = line - end - return out - end - for _, dimensions in ipairs({ { 80, 16 }, { 82, 18 } }) do - local rendered = lines(ui.renderFormFrame(view, "machine", dimensions[1], dimensions[2], false)) - assert(#rendered == dimensions[2]) - assert(rendered[1]:find("REX / WORKTREES", 1, true)) - for i, label in ipairs({ "PROJECT", "MACHINE", "SESSION", "WORKTREE", "BRANCH", "DIRECTORY", "MODE" }) do - assert(rendered[i + 2]:find(label, 1, true)) - end - for _, line in ipairs(rendered) do - assert(s.unicode.width(line) == dimensions[1]) - end - assert(rendered[#rendered]:find("Tab next", 1, true)) - end - assert(ui.renderFormFrame(view, "submit", 80, 16, false):find("Destination details", 1, true)) - local malicious = "\27[2J\27]0;hijack\7\226\128\174VISIBLE\nNEXT" - local frame = ui.renderFormFrame({ rows = rows, submitLabel = "Open", error = malicious }, "machine", 60, 20, false) - assert(not frame:find("\27", 1, true) and not frame:find("\7", 1, true) and not frame:find("\226\128\174", 1, true)) - assert(frame:find("NEXT", 1, true)) - local longError = "Cannot open " .. string.rep("details ", 60) .. "END OF ERROR" - local first = - lines(ui.renderFormFrame({ rows = rows, submitLabel = "Open", error = longError }, "project", 80, 16, false)) - local last = lines( - ui.renderFormFrame( - { rows = rows, submitLabel = "Open", error = longError }, - "mode", - 80, - 16, - false, - { detailOffset = 999 } - ) - ) - assert(table.concat(first, " "):find("PgDn", 1, true)) - assert(table.concat(last, " "):find("END OF ERROR", 1, true)) - assert(first[5]:find("SESSION", 1, true) and last[9]:find("MODE", 1, true)) - local choices = { { value = "one", title = "One" }, { value = "feature", title = "feature" } } - local typed = ui.advanceInputChoice({ text = "", selected = nil }, "f", "feature", choices) - assert(typed._tag == "NextFrame" and typed.state.text == "feature" and typed.state.selected == nil) - local submitted = ui.advanceInputChoice(typed.state, "enter", "", choices) - assert(submitted._tag == "Submit" and submitted.value.kind == "typed" and submitted.value.text == "feature") - local picked = ui.advanceInputChoice(typed.state, "down", "", choices) - submitted = ui.advanceInputChoice(picked.state, "enter", "", choices) - assert(submitted._tag == "Submit" and submitted.value.kind == "selected" and submitted.value.value == "feature") - local deleted = ui.advanceInputChoice({ text = "a👩‍💻" }, "backspace", "", choices) - assert(deleted.state.text == "a") - assert(ui.advanceInputChoice({ text = "" }, "paste", "\0", choices)._tag == "Beep") - assert(ui.advanceInputChoice({ text = "custom" }, "enter", "", choices, true)._tag == "Beep") - local exact = ui.advanceInputChoice({ text = "", selected = 1 }, "ctrl_s", "", choices, true) - assert(exact._tag == "Submit" and exact.value.kind == "selected" and exact.value.value == "feature") - assert(ui.advanceInputChoice({ text = "missing" }, "ctrl_s", "", choices, true)._tag == "Beep") - assert(ui.advanceInputChoice(typed.state, "alt_x", "", choices)._tag == "Beep") - assert(ui.advanceInputChoice(typed.state, "ctrl_d", "", choices)._tag == "Beep") - local editor = ui.renderInputChoice( - { text = "", selected = 0 }, - { { value = "base", title = "main\27]2;hijack\7\nnext", description = "commit\27[2J\nsecond" } }, - 60, - false - ) - assert(not table.concat(editor):find("\27", 1, true) and not table.concat(editor):find("\7", 1, true)) - for _, line in ipairs(editor) do - assert(s.unicode.width(line) <= 60) - end - local items = {} - for i = 0, 19 do - items[#items + 1] = { value = i, title = "Choice " .. i } - end - for _, selectedIndex in ipairs({ 0, 19 }) do - local dock = ui.renderInputChoice({ text = "", selected = selectedIndex }, items, 80, false) - local rendered = - lines(ui.renderFormFrame(view, "project", 80, 16, false, { editor = { title = "Project", lines = dock } })) - assert(#rendered == 16 and rendered[11]:find("Type new value", 1, true)) - for i = 12, 14 do - assert(rendered[i]:find("Choice", 1, true)) - end - assert(table.concat(rendered, " "):find("› Choice " .. selectedIndex, 1, true)) - assert(rendered[16]:find("Esc back", 1, true)) - end - local unsafeRows = {} - for i, row in ipairs(rows) do - unsafeRows[i] = { id = row.id, label = row.label, value = malicious, detail = malicious } - end - local unsafeFrame = ui.renderFormFrame( - { rows = unsafeRows, error = malicious }, - "machine", - 60, - 20, - false, - { editor = { title = malicious, lines = editor } } - ) - assert( - not unsafeFrame:find("\27", 1, true) - and not unsafeFrame:find("\7", 1, true) - and not unsafeFrame:find("\226\128\174", 1, true) - ) - assert(ui.renderFormFrame(view, "project", 80, 8, false):find("Resize", 1, true)) - assert(ui.advanceInputChoice({ text = "" }, "paste", "\127", choices)._tag == "Beep") - assert(ui.advanceInputChoice({ text = "" }, "paste", "\194\128", choices).state.text == "\194\128") - assert(ui.advanceInputChoice(picked.state, "paste", "é/木", choices).state.text == "featureé/木") - assert(ui.advanceInputChoice(typed.state, "ctrl_u", "", choices).state.text == "") - local escaped = ui.advanceInputChoice(typed.state, "escape", "", choices) - assert(escaped._tag == "Submit" and (escaped.value == nil or s.isNull(escaped.value))) + local ui, s = require("chooser"), require("runtime") local host = { key = "local", selector = "", label = "local", ["local"] = true, hostId = "host" } local repo = { vcs = "git", path = "/projects/alpha", commonDir = "/git/alpha", name = "alpha" } local draft = { @@ -252,4 +136,65 @@ return function() assert(#s.json.encode({ request = s.json.encode(request) }) < 65536) local switched = ui.changeProjectChoice(draft, { name = "beta" }) assert(switched.project == nil and switched.destination == nil and switched.session.id == "session") + local state = s.json.encode({ + draft = { mode = "auto", host = host, machine = host }, origin = s.json.object(), projects = s.json.array(), + sessions = s.json.array(), cloneRoot = "", + }) + local editing = ui.request({ op = "edit", state = state, field = "mode" }, {}) + assert(#editing.rows == 7 and editing.editor and #editing.editor.items == 3) + local invalid = ui.request({ op = "accept", state = editing.state, id = "missing" }, {}) + assert(invalid.error and invalid.editor and invalid.submitDisabled) + local accepted = ui.request({ op = "accept", state = editing.state, id = editing.editor.items[2].id }, {}) + assert(not accepted.editor and accepted.rows[7].value == "Always new tab") + local cancelled = ui.request({ op = "cancel", state = editing.state }, {}) + assert(not cancelled.editor and cancelled.rows[7].value == "Reuse matching tab, otherwise new tab") + + local client = require("client") + local discover, review, reviewClone = client.connectAndDiscover, client.review, client.reviewClone + local ok, err = xpcall(function() + local reviewed + client.connectAndDiscover = function(machine) + assert(machine.key == "local") + return { host = host, cloneRoot = "/remote/projects" } + end + client.reviewClone = function(selectedHost, _, request) + assert(selectedHost.hostId == "host") + reviewed = request + return { hostId = "host", repo = request.repo, input = request, warning = "Review" } + end + local function chooserState(project) + return s.json.encode({ + draft = { mode = "auto", host = host, machine = host, project = project, + projectChoice = project and { name = project.name } or nil, + session = { kind = "existing", id = "session" } }, + origin = s.json.object(), projects = s.json.array(), sessions = s.json.array(), cloneRoot = "/stale", + }) + end + for _, value in ipairs({ "https://github.com/owner", "git@github.com:owner/", "https://example.com/a/b", + "github.com/owner/repo", "ssh:/github.com/owner/repo" }) do + local rejected = ui.request({ op = "submit", state = chooserState(repo), text = value }, {}) + assert(rejected.error and rejected.error:find("repository clone URL", 1, true)) + end + local response = ui.request({ op = "submit", state = chooserState(), text = "https://github.com/owner/example.git" }, {}) + assert(response.confirmation and reviewed.repo == "/remote/projects/example" and reviewed.session.id == "session") + assert(reviewed.checkout == "primary" and reviewed.branchMode == "default" and reviewed.branch == nil) + assert(reviewed.source.url == "https://github.com/owner/example.git" and reviewed.source.sourceHostId == nil) + assert(response.rows[5].value == "Remote default") + response = ui.request({ op = "submit", state = chooserState(jjrepo), text = "git@github.com:owner/example.git" }, {}) + assert(response.confirmation and reviewed.vcs == "jj" and reviewed.revision == nil and reviewed.source.revision == nil) + local cancelledConfirmation = ui.request({ op = "cancel", state = response.state }, {}) + local revisionEditor = ui.request({ op = "edit", state = cancelledConfirmation.state, field = "branch" }, {}) + local invalidRevision = ui.request({ op = "accept", state = revisionEditor.state, text = "trunk()" }, {}) + assert(invalidRevision.error and invalidRevision.error:find("without a source Rex checkout", 1, true)) + client.review = function(selectedHost, _, input) + return { hostId = selectedHost.hostId, path = input.directory, warning = "Review" } + end + local named = ui.request({ op = "submit", state = chooserState(repo), text = "topic@work" }, {}) + assert(named.confirmation and named.rows[5].value == "topic@work") + client.connectAndDiscover = function() return { host = { hostId = "changed" }, cloneRoot = "/other" } end + local changed = ui.request({ op = "submit", state = chooserState(), text = "https://github.com/owner/example" }, {}) + assert(changed.error and changed.error:find("identity changed", 1, true)) + end, debug.traceback) + client.connectAndDiscover, client.review, client.reviewClone = discover, review, reviewClone + assert(ok, err) end diff --git a/test/native-ui.test.lua b/test/native-ui.test.lua new file mode 100644 index 0000000..b0448b0 --- /dev/null +++ b/test/native-ui.test.lua @@ -0,0 +1,75 @@ +return function() + local old_rex = rex + local actions, pending, calls = {}, nil, {} + local rows = {} + for _, id in ipairs({ "project", "machine", "session", "destination", "branch", "checkoutName", "mode" }) do + rows[#rows + 1] = { id = id, label = id, value = id, isReadOnly = id == "branch" } + end + local function summary(state, editor) + return { state = state, rows = rows, submitLabel = "Open", submitDisabled = false, editor = editor } + end + local pick_count, quick = 0, false + rex = { + session_id = "local-session", block_id = "local-block", + json = { + encode = function(value) pending = value; return "encoded" end, + decode = function() return pending end, + }, + action = function(action) actions[action.name] = action.run end, + bind = function() end, + exec = function(command, options) + assert(command[1] == "/test/rex-worktrees" and command[2] == "chooser") + assert(options.stdin == "encoded") + local request = pending + calls[#calls + 1] = request + if request.op == "start" then + assert(request.origin.sessionId == "remote-session" and request.origin.server == "remote") + assert(request.origin.blockId == "remote-block" and request.origin.clientId == "client") + pending = summary("draft-1") + elseif request.op == "edit" then + assert(request.field == "destination" and request.state == "draft-1") + pending = summary("editor-1", { kind = "pick", title = "Worktree", allowOther = false, + items = { { id = "new", title = "Create" } } }) + elseif request.op == "accept" then + assert(request.state == "editor-1" and request.id == "new") + pending = summary("editor-2", { kind = "input", title = "Branch", allowOther = true, + value = "feature", items = {} }) + elseif request.op == "cancel" then + assert(request.state == "editor-2") + pending = summary("draft-2") + elseif request.op == "submit" then + assert(request.state == (quick and "draft-1" or "draft-2")) + if quick then assert(request.text == "new-feature") end + pending = { done = true, result = { opened = true } } + else error("unexpected operation " .. tostring(request.op)) end + return { ok = true, stdout = "response" } + end, + ui = { + pick = function(prompt) + pick_count = pick_count + 1 + if quick then return { text = "new-feature" } end + if pick_count == 1 then + assert(#prompt.items == 8 and prompt.items[5].detail == "Read only") + return "field:branch" + elseif pick_count == 2 then return "field:destination" + elseif pick_count == 3 then return "item:1" + elseif pick_count == 4 then return "submit" end + error("unexpected picker") + end, + input = function(prompt) + assert(prompt.title == "Branch" and prompt.value == "feature") + return nil, "cancelled" + end, + }, + } + local module = dofile("lua/rex-worktrees.lua") + module.setup({ bin = "/test/rex-worktrees" }) + local result = actions.worktrees_open({ session_id = "remote-session", block_id = "remote-block", + client_id = "client", server = "remote" }) + assert(result.opened and #calls == 5 and calls[5].op == "submit") + quick = true + result = actions.worktrees_open({ session_id = "remote-session", block_id = "remote-block", + client_id = "client", server = "remote" }) + assert(result.opened and calls[#calls].op == "submit" and calls[#calls].text == "new-feature") + rex = old_rex +end diff --git a/test/popup-clone.py b/test/popup-clone.py deleted file mode 100644 index d26d267..0000000 --- a/test/popup-clone.py +++ /dev/null @@ -1,187 +0,0 @@ -import json -import os -import sys - -from terminal import Terminal - -# Only the Rex transport is faked. Discovery and clone-source on the local host are real. -if len(sys.argv) > 1 and sys.argv[1] == '--rex': - args = sys.argv[2:] - root, scenario = os.environ['POPUP_ROOT'], os.environ['POPUP_SCENARIO'] - remote = '-S' in args and args[args.index('-S') + 1] == 'Remote machine' - def emit(value): - print(json.dumps(value)) - if args[-2:] == ['list', '--json'] and 'hosts' in args: - emit({'home': {'label': 'Local', 'endpoint': 'unix:///fixture.sock', 'this_machine': True}, - 'hosts': [{'host': {'id': 'remote', 'label': 'Remote machine', 'endpoints': ['tcp://remote']}}]}) - elif 'whoami' in args: - emit({'host_id': 'host-remote' if remote else 'host-local', 'endpoint': 'tcp://remote' if remote else 'unix:///fixture.sock', 'principal': {'transport': 'tcp' if remote else 'unix'}}) - elif 'actions' in args: - emit({'actions': [{'name': 'worktrees_request', 'args': {'properties': {'request': {'type': 'string'}}}}]}) - elif 'worktrees_request' in args: - request = json.loads(json.loads(args[args.index('--args') + 1])['request']) - with open(os.environ['POPUP_LOG'], 'a') as log: - log.write(json.dumps(request) + '\n') - kind = request['kind'] - base = {'version': 5, 'hostId': 'host-remote', 'kind': kind} - remote_path = root + '/remote/alpha' - project = {'vcs': 'jj', 'path': remote_path, 'commonDir': remote_path + '/.jj/repo', 'name': 'alpha'} - tree = {'vcs': 'jj', 'path': remote_path, 'name': 'alpha', 'head': 'c' * 40, 'changeId': 'm' * 32, 'present': True} - revisions = [{'expression': 'trunk()', 'label': 'trunk()', 'revision': {'commitId': 'a' * 40, 'changeId': 'k' * 32, 'description': 'mainline'}}, - {'expression': 'candidate', 'label': 'candidate', 'revision': {'commitId': 'b' * 40, 'changeId': 'n' * 32, 'description': 'candidate'}}] - if kind == 'discover': - base.update(sessions=[{'id': 'remote-session', 'label': 'Remote session'}], clients=[], - projects=[project] if scenario.startswith('jj-') else [], - roots=[root + '/remote-clones'], cloneRoot=root + '/remote-clones') - elif kind == 'project': - if scenario.startswith('jj-') and request['path'] == remote_path: - base.update(project=project, checkout=project, worktrees=[tree], branches=[], revisions=revisions, worktreeRoot=remote_path + '.worktrees') - else: - base.update(kind='project-missing', path=request['path']) - elif kind == 'worktrees': - base.update(repository=project, worktrees=[tree], branches=[], revisions=revisions, worktreeRoot=remote_path + '.worktrees') - elif kind == 'plan': - value = request['input'] - base['plan'] = {'vcs': 'jj', 'input': value, 'hostId': 'host-remote', 'path': value['directory'], 'action': 'new-tab', 'checkout': 'create', 'workspaceName': value['worktreeName'], 'nameRole': 'tab', 'name': value['name'], 'label': 'Create workspace & open'} - elif kind == 'launch': - base['result'] = {'hostId': 'host-remote', 'sessionId': 'remote-session', 'windowId': 'window', 'blockId': 'block', 'pending': False, 'path': request['reviewed']['path'], 'action': 'new-tab'} - elif kind == 'clone-plan': - value = request['input'] - base['plan'] = {'vcs': 'git', 'input': value, 'hostId': 'host-remote', 'repo': value['repo'], 'existing': False, 'label': 'Clone & Open'} - elif kind == 'clone-launch': - if scenario == 'failure': - print('Destination request rejected', file=sys.stderr) - sys.exit(4) - base['result'] = {'hostId': 'host-remote', 'sessionId': 'remote-session', 'windowId': 'window', 'blockId': 'block', 'pending': True, 'repo': request['reviewed']['repo']} - else: - raise AssertionError(request) - emit(json.dumps(base)) - elif 'ls' in args: - emit({'sessions': [{'session_id': 'local-session', 'label': 'Local session'}]}) - elif 'client.list' in args: - emit({'clients': []}) - elif 'session.list_blocks' in args: - emit({'blocks': []}) - else: - raise AssertionError(args) - sys.exit(0) - -root, binary = sys.argv[1:] -bin_dir = root + '/bin' -os.makedirs(bin_dir, exist_ok=True) -with open(bin_dir + '/rex', 'w') as script: - script.write('#!/bin/sh\nexec ' + json.dumps(sys.executable) + ' ' + json.dumps(os.path.abspath(__file__)) + ' --rex "$@"\n') -os.chmod(bin_dir + '/rex', 0o755) - -class Popup(Terminal): - def __init__(self, scenario): - self.log = root + '/' + scenario + '.jsonl' - home = root + '/home-' + scenario - os.makedirs(home, exist_ok=True) - env = {k: v for k, v in os.environ.items() if not k.startswith('GIT_') and k not in ('REX_SESSION', 'REX_BLOCK', 'REX_CLIENT', 'REX_SERVER', 'REX_HOST')} - env.update(HOME=home, XDG_CONFIG_HOME=home + '/config', XDG_STATE_HOME=home + '/state', - GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL=home + '/gitconfig', NO_COLOR='1', - REX_BIN_DIR=bin_dir, REX_WORKTREES_LOCAL_ENDPOINT='unix:///fixture.sock', - REX_WORKTREES_CONFIG=json.dumps({'directory': home, 'config': {'roots': [home + '/local-clones']}}), - POPUP_ROOT=root, POPUP_LOG=self.log, POPUP_SCENARIO=scenario) - repo = root + ('/jj/alpha' if scenario.startswith('jj-') else '/detached/alpha' if scenario == 'detached' else '/git/alpha') - super().__init__(scenario, self.log, binary, repo, env, 24, 110, normalize=False) - - def switch(self): - self.frame('alpha', 'Local session', 'Tab next') - self.send(b'\t\r') - self.frame('Execution machine', 'Esc back') - self.send(b'\x1b[B\r') - - def directory(self, value, tabs): - self.send(b'\t' * tabs + b'\r') - self.frame('Directory (absolute path', 'Esc back') - self.send(b'\x15' + value.encode() + b'\r') - self.frame(value[:35], 'DIRECTORY', 'Tab next') - - -def workspace(p): - p.switch() - p.frame('alpha', 'Remote session', 'Tab next') - p.send(b'\t\t\r') - p.frame('Workspace (select existing or create new)', 'Create new workspace') - p.send('Create new workspace'.encode() + b'\x1b[B\r') - default = root + '/remote/alpha.worktrees/workspace' - frame = p.frame('Create new workspace', 'trunk()', 'DIRECTORY') - assert 'START FROM' in frame and 'DIRECTORY' in frame - expected, revision, name = default, 'a' * 40, 'workspace' - if p.scenario == 'jj-custom': - p.send(b'\t\r') - p.frame('Start from revision for new workspace') - p.send(b'candidate\x1b[B\r') - p.frame('candidate', 'Tab next') - expected, revision, name = root + '/custom/task-space', 'b' * 40, 'task-space' - p.directory(expected, 1) - assert not p.requests('plan') and not p.requests('launch') - p.send(b'\x13') - p.finish() - plans, launches = p.requests('plan'), p.requests('launch') - assert len(plans) == len(launches) == 1 - value = launches[0]['input'] - assert value['vcs'] == 'jj' and value['repo'] == root + '/remote/alpha' - assert value['directory'] == expected and value['worktreeName'] == name and value['revision'] == revision - assert value['session'] == {'kind': 'existing', 'id': 'remote-session'} - assert plans[0]['input'] == value and launches[0]['reviewed']['path'] == expected - - -def clone(p): - p.switch() - destination = root + '/remote-clones/alpha' - frame = p.frame('DIRECTORY', 'Project checkout (after clone)', 'New tab (cloning)') - assert ('Select or type branch' if p.scenario == 'detached' else 'main') in frame - if p.scenario == 'detached': - p.send(b'\t\t\t\r') - p.frame('Branch (select unused or type new name)', 'main') - p.send(b'\x1b[B\r') - p.frame('main', 'Tab next') - p.directory(root + '/remote-safe/alpha', 1) - elif p.scenario == 'worktree': - p.send(b'\t\t\r') - p.frame('Worktree (select existing or create new)', 'Project checkout (after clone)', 'Create new worktree') - p.send(b'Create new worktree\x1b[B\r') - p.frame('Branch (select unused or type new name)') - p.send(b'feature/new\r') - p.frame('feature/new', 'Tab next') - p.directory(root + '/remote-checkouts/task', 1) - else: - p.directory(root + '/remote-safe/alpha', 4) - assert not p.requests('clone-plan') and not p.requests('clone-launch') - p.send(b'\x13') - if p.scenario == 'failure': - frame = p.frame('Clone needs inspection', 'Destination request rejected', 'Enter / Space close') - assert 'exited 4' in frame and root[:35] in frame - p.send(b'\x13') - p.frame('Clone needs inspection', 'Enter / Space close') - assert 'request-body-' not in frame - assert len(p.requests('clone-plan')) == len(p.requests('clone-launch')) == 1 - p.send(b'\r') - p.finish(False) - else: - p.finish() - plans, launches = p.requests('clone-plan'), p.requests('clone-launch') - assert len(plans) == len(launches) == 1 - value = launches[0]['input'] - assert plans[0]['input'] == value and launches[0]['reviewed']['repo'] == value['repo'] - assert value['source']['url'] == 'https://example.test/alpha.git' and value['source']['sourceHostId'] == 'host-local' - assert value['session'] == {'kind': 'existing', 'id': 'remote-session'} - if p.scenario == 'detached': assert 'branch' not in value['source'] - if p.scenario == 'worktree': - assert value['repo'] == destination and value['directory'] == root + '/remote-checkouts/task' - assert value['checkout'] == 'worktree' and value['branch'] == 'feature/new' and value['branchMode'] == 'create' - else: - assert value['repo'] == root + '/remote-safe/alpha' and value['checkout'] == 'primary' - assert 'directory' not in value and value['branch'] == 'main' and value['branchMode'] == 'existing' - assert not os.path.exists(value['repo']) - - -for scenario in ('jj-default', 'jj-custom', 'detached', 'primary', 'worktree', 'failure'): - popup = Popup(scenario) - try: - (workspace if scenario.startswith('jj-') else clone)(popup) - finally: - popup.close() diff --git a/test/popup-clone.test.lua b/test/popup-clone.test.lua deleted file mode 100644 index 7b0ab0c..0000000 --- a/test/popup-clone.test.lua +++ /dev/null @@ -1,24 +0,0 @@ -return function(root) - local runtime = require("runtime") - local base = root .. "/popup-clone" - local function run(args) - local result = runtime.capture(args, { timeout = 120 }) - assert(result.ok, result.stderr .. result.stdout) - end - for _, kind in ipairs({ "git", "detached" }) do - local repo = base .. "/" .. kind .. "/alpha" - runtime.fs.makeDirectory(repo, { recursive = true }) - run({ "git", "-C", repo, "init", "-b", "main" }) - run({ "git", "-C", repo, "config", "user.name", "Rex Tests" }) - run({ "git", "-C", repo, "config", "user.email", "rex@example.test" }) - runtime.fs.writeFileString(repo .. "/tracked", "base\n") - run({ "git", "-C", repo, "add", "tracked" }) - run({ "git", "-C", repo, "commit", "-m", "base" }) - run({ "git", "-C", repo, "remote", "add", "origin", "https://example.test/alpha.git" }) - if kind == "detached" then run({ "git", "-C", repo, "checkout", "--detach" }) end - end - local jj = base .. "/jj/alpha" - runtime.fs.makeDirectory(jj, { recursive = true }) - run({ "jj", "git", "init", "--no-colocate", jj }) - run({ "python3", "test/popup-clone.py", base, runtime.path.resolve("dist/rex-worktrees") }) -end diff --git a/test/popup-form.py b/test/popup-form.py deleted file mode 100644 index 5b107fd..0000000 --- a/test/popup-form.py +++ /dev/null @@ -1,219 +0,0 @@ -import json -import os -import sys - -from terminal import Terminal - -# Rex is the protocol boundary; the popup and local repository are real. -if len(sys.argv) > 1 and sys.argv[1] == '--rex': - args = sys.argv[2:] - scenario = os.environ['POPUP_SCENARIO'] - root = os.environ['POPUP_ROOT'] - remote = '-S' in args and args[args.index('-S') + 1] == 'Remote machine' - def emit(value): - print(json.dumps(value)) - if args[-2:] == ['list', '--json'] and 'hosts' in args: - emit({'home': {'label': 'Local', 'endpoint': 'unix:///fixture.sock', 'this_machine': True}, - 'hosts': [{'host': {'id': 'remote', 'label': 'Remote machine', 'endpoints': ['tcp://remote']}}]}) - elif 'whoami' in args: - emit({'host_id': 'host-remote' if remote else 'host-local', 'endpoint': 'tcp://remote' if remote else 'unix:///fixture.sock', 'principal': {'transport': 'tcp' if remote else 'unix'}}) - elif 'actions' in args: - emit({'actions': [{'name': 'worktrees_request', 'args': {'properties': {'request': {'type': 'string'}}}}]}) - elif 'worktrees_request' in args: - request = json.loads(json.loads(args[args.index('--args') + 1])['request']) - with open(os.environ['POPUP_LOG'], 'a') as log: - log.write(json.dumps(request) + '\n') - kind = request['kind'] - assert request['version'] == 5 - base = {'version': 5, 'hostId': 'host-remote', 'kind': kind} - remote_path = root + '/remote/' + ('nested/' * 25 if scenario == 'long' else '') + 'alpha' - project = {'vcs': 'git', 'path': remote_path, 'commonDir': remote_path + '/.git', 'name': 'alpha'} - tree = {'vcs': 'git', 'path': remote_path, 'branch': 'main', 'head': 'abc', 'bare': False, 'locked': False, 'prunable': False} - if kind == 'discover': - base.update(sessions=[{'id': 'remote-session', 'label': 'Remote session'}], clients=[], projects=[project], roots=[root + '/clones'], cloneRoot=root + '/clones') - elif kind == 'project': - assert request['path'] == remote_path - base.update(project=project, checkout=project, worktrees=[tree], branches=['main', 'feature/free'], revisions=[], worktreeRoot=remote_path + '.worktrees') - elif kind == 'worktrees': - base.update(repository=project, worktrees=[tree], branches=['main', 'feature/free'], revisions=[], worktreeRoot=remote_path + '.worktrees') - elif kind == 'sessions': - base.update(sessions=[{'id': 'remote-session', 'label': 'Remote session'}], clients=[]) - elif kind == 'plan': - value = request['input'] - destination = value.get('path', value.get('directory')) - plan = {'vcs': 'git', 'input': value, 'hostId': 'host-remote', 'path': destination + ('.changed' if scenario == 'redirect' else ''), - 'action': 'new-tab', 'checkout': 'existing' if 'path' in value else 'create', - 'branch': value.get('branch', 'main'), 'nameRole': 'tab', 'name': value['name'], 'label': 'Open tab'} - if scenario == 'warning': plan['warning'] = 'Multiple Rex apps are connected' - base['plan'] = plan - elif kind == 'launch': - base['result'] = {'hostId': 'host-remote', 'sessionId': 'remote-session', 'windowId': 'window', 'blockId': 'block', - 'pending': False, 'path': request['reviewed']['path'], 'action': 'new-tab'} - else: - raise AssertionError(request) - emit(json.dumps(base)) - elif 'ls' in args: - emit({'sessions': [{'session_id': 'local-session', 'label': 'Local session'}]}) - elif 'client.list' in args: - emit({'clients': []}) - elif 'session.list_blocks' in args: - emit({'blocks': []}) - else: - raise AssertionError(args) - sys.exit(0) - -root, binary, repo = sys.argv[1:] -bin_dir = root + '/bin' -os.makedirs(bin_dir, exist_ok=True) -with open(bin_dir + '/rex', 'w') as script: - script.write('#!/bin/sh\nexec ' + json.dumps(sys.executable) + ' ' + json.dumps(os.path.abspath(__file__)) + ' --rex "$@"\n') -os.chmod(bin_dir + '/rex', 0o755) - -class Popup(Terminal): - def __init__(self, scenario): - self.log = root + '/' + scenario + '.jsonl' - home = root + '/home-' + scenario - os.makedirs(home, exist_ok=True) - env = {k: v for k, v in os.environ.items() if not k.startswith('GIT_') and k not in ('REX_SESSION', 'REX_BLOCK', 'REX_CLIENT', 'REX_SERVER', 'REX_HOST')} - env.update(HOME=home, XDG_CONFIG_HOME=home + '/config', XDG_STATE_HOME=home + '/state', - GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL=home + '/gitconfig', NO_COLOR='1', - REX_BIN_DIR=bin_dir, REX_WORKTREES_LOCAL_ENDPOINT='unix:///fixture.sock', - REX_WORKTREES_CONFIG=json.dumps({'directory': home, 'config': {}}), - POPUP_ROOT=root, POPUP_LOG=self.log, POPUP_SCENARIO=scenario) - super().__init__(scenario, self.log, binary, repo, env, 20, 60 if scenario == 'long' else 110) - - def switch(self): - self.frame('alpha', 'Local session', 'Tab next') - self.send(b'\t\r') - self.frame('Execution machine', 'Esc back') - self.send(b'\x1b[B\r') - return self.frame('Remote session', 'Tab next') - - def no_submit(self): - assert not self.requests('plan') and not self.requests('launch') - - def launched(self, path, additional=False, split=False): - plans, launches = self.requests('plan'), self.requests('launch') - assert len(plans) == len(launches) == 1, (plans, launches) - value = plans[0]['input'] - assert value['session'] == {'kind': 'existing', 'id': 'remote-session'} - assert value['additional'] is additional and value['split'] is split - assert value.get('path', value.get('directory')) == path - assert launches[0]['input'] == value and launches[0]['reviewed']['path'] == path - return value - - -def run(scenario, fn): - popup = Popup(scenario) - try: - fn(popup) - finally: - popup.close() - - -def project(p, accept): - p.switch() - p.send(b'\x1b[Z\r') - p.frame('Project (select known', 'Esc back') - p.send(b'\x1b[B\x1b[B') - frame = p.frame('Project (select known', '› alpha', 'Esc back') - assert 'Tab next' not in frame - p.send(accept) - frame = p.frame('Remote session', 'WORKTREE', 'Tab next', absent=('Loading…',)) - assert 'alpha' in frame - p.no_submit() - p.send(b'\x13') - p.finish() - p.launched(root + '/remote/alpha') - - -def mode(p, choice, text, additional, split): - initial = p.switch() - p.send(b'\t\t\t\r') - editor = p.frame('Open mode', 'Esc back') - for label in ('PROJECT', 'MACHINE', 'SESSION', 'WORKTREE', 'BRANCH', 'DIRECTORY', 'MODE'): - assert initial.splitlines().index(next(line for line in initial.splitlines() if label in line)) == editor.splitlines().index(next(line for line in editor.splitlines() if label in line)) - p.send(choice + b'\x13') - p.frame(text, 'Tab next') - p.no_submit() - p.send(b'\x13') - p.finish() - p.launched(root + '/remote/alpha', additional, split) - - -def occupied(p): - p.switch() - p.send(b'\t\t\r') - p.frame('Worktree (select existing or create new)', 'Esc back') - p.send(b'Create new worktree\x1b[B\r') - p.frame('Branch (select unused or type new name)', 'Esc back') - p.send(b'main\r') - p.frame('Branch main is already checked out', 'Tab next') - p.send(b'\x13') - p.frame('Branch main is already checked out', 'Tab next') - p.no_submit() - p.send(b'\r') - p.frame('Branch (select unused or type new name)', 'Esc back') - p.send(b'feature/new\r') - p.frame('feature/new', 'Tab next') - p.no_submit() - p.send(b'\x13') - p.finish() - value = p.launched(root + '/remote/alpha.worktrees/feature/new') - assert value['branch'] == 'feature/new' and 'path' not in value - - -def redirect(p): - p.switch() - p.send(b'\x13') - p.frame('Destination changed; select the worktree again:', 'Tab next') - p.send(b'\x13') - p.frame('Destination changed; select the worktree again:', 'Tab next') - assert len(p.requests('plan')) == 1 and not p.requests('launch') - p.send(b'\x1b') - p.finish() - assert len(p.requests('plan')) == 1 and not p.requests('launch') - - -def warning(p): - p.switch() - p.send(b'\x13') - p.frame('Opened with warning', 'Multiple Rex apps are connected', 'Enter / Space close') - p.launched(root + '/remote/alpha') - p.send(b'\r') - p.finish() - p.launched(root + '/remote/alpha') - - -def long_path(p): - frame = p.switch() - path = root + '/remote/' + 'nested/' * 25 + 'alpha' - lines = frame.splitlines() - branch = next(line for line in lines if 'BRANCH' in line) - directory = next(line for line in lines if 'DIRECTORY' in line) - assert 'main' in branch and '…' in directory and path not in directory - p.send(b'\t\t\r') - p.frame('Worktree (select existing or create new)', 'Esc back') - p.send(b'\x1b') - p.frame('DIRECTORY', 'Tab next') - p.no_submit() - p.send(b'\t\r') - p.frame('Open mode', 'Esc back') - p.send(b'\x1b') - p.frame('DIRECTORY', 'Tab next') - p.no_submit() - p.send(b'\x13') - p.finish() - p.launched(path) - - -for name, accept in [('project-enter', b'\r'), ('project-ctrls', b'\x13')]: - run(name, lambda p, accept=accept: project(p, accept)) -for name, choice, text, additional, split in [ - ('mode-auto', b'', 'Reuse matching tab, otherwise new tab', False, False), - ('mode-new-tab', b'\x1b[B', 'Always new tab', True, False), - ('mode-split', b'\x1b[B\x1b[B', 'Split matching tab, otherwise new tab', False, True), -]: - run(name, lambda p, choice=choice, text=text, additional=additional, split=split: mode(p, choice, text, additional, split)) -for name, fn in [('occupied', occupied), ('redirect', redirect), ('warning', warning), ('long', long_path)]: - run(name, fn) diff --git a/test/popup-form.test.lua b/test/popup-form.test.lua deleted file mode 100644 index 12ebfe3..0000000 --- a/test/popup-form.test.lua +++ /dev/null @@ -1,16 +0,0 @@ -return function(root) - local runtime = require("runtime") - local repo = root .. "/popup-form/alpha" - runtime.fs.makeDirectory(repo, { recursive = true }) - local function run(args) - local result = runtime.capture(args, { timeout = 180 }) - assert(result.ok, result.stderr .. result.stdout) - end - run({ "git", "-C", repo, "init", "-b", "main" }) - run({ "git", "-C", repo, "config", "user.name", "Rex Tests" }) - run({ "git", "-C", repo, "config", "user.email", "rex@example.test" }) - runtime.fs.writeFileString(repo .. "/tracked", "base\n") - run({ "git", "-C", repo, "add", "tracked" }) - run({ "git", "-C", repo, "commit", "-m", "base" }) - run({ "python3", "test/popup-form.py", root .. "/popup-form", runtime.path.resolve("dist/rex-worktrees"), repo }) -end diff --git a/test/popup-remote.py b/test/popup-remote.py deleted file mode 100644 index ce5864a..0000000 --- a/test/popup-remote.py +++ /dev/null @@ -1,258 +0,0 @@ -import json -import os -import signal -import sys - -from terminal import Terminal - -# The executable below is only the Rex protocol boundary; the popup and local Git are real. -if len(sys.argv) > 1 and sys.argv[1] == '--rex': - args = sys.argv[2:] - scenario = os.environ['POPUP_SCENARIO'] - root = os.environ['POPUP_ROOT'] - remote = '-S' in args and args[args.index('-S') + 1] == 'Remote machine' - def emit(value): - print(json.dumps(value)) - if args[-2:] == ['list', '--json'] and 'hosts' in args: - emit({'home': {'label': 'Local', 'endpoint': 'unix:///fixture.sock', 'this_machine': True}, - 'hosts': [{'host': {'id': 'remote', 'label': 'Remote machine', 'endpoints': ['tcp://remote']}}]}) - elif 'whoami' in args: - emit({'host_id': 'host-remote' if remote else 'host-local', 'endpoint': 'tcp://remote' if remote else 'unix:///fixture.sock', 'principal': {'transport': 'tcp' if remote else 'unix'}}) - elif 'actions' in args: - if scenario == 'connect': - print('Remote helper unavailable; install and reload Rex', file=sys.stderr) - sys.exit(4) - emit({'actions': [{'name': 'worktrees_request', 'args': {'properties': {'request': {'type': 'string'}}}}]}) - elif 'worktrees_request' in args: - request = json.loads(json.loads(args[args.index('--args') + 1])['request']) - with open(os.environ['POPUP_LOG'], 'a') as log: - log.write(json.dumps(request) + '\n') - kind = request['kind'] - if scenario == 'pending' and kind == 'discover': - signal.pause() - sys.exit(1) - base = {'version': 5, 'hostId': 'host-remote', 'kind': kind} - remote_path = root + '/remote/alpha' - project = {'vcs': 'git', 'path': remote_path, 'commonDir': remote_path + '/.git', 'name': 'alpha'} - tree = {'vcs': 'git', 'path': remote_path, 'branch': 'main', 'head': 'abc', 'bare': False, 'locked': False, 'prunable': False} - if kind == 'discover': - base.update(sessions=[{'id': 'remote-session', 'label': 'Remote session'}], clients=[], - projects=[project] if scenario in ('existing', 'redirect', 'warning') else [], - roots=[root + '/clones'], cloneRoot=root + '/clones') - elif kind == 'project': - if scenario in ('existing', 'redirect', 'warning') and request['path'] == remote_path: - base.update(project=project, checkout=project, worktrees=[tree], branches=['main', 'feature/free'], revisions=[], worktreeRoot=remote_path + '.worktrees') - else: - base.update(kind='project-missing', path=request['path']) - elif kind == 'worktrees': - base.update(repository=project, worktrees=[tree], branches=['main', 'feature/free'], revisions=[], worktreeRoot=remote_path + '.worktrees') - elif kind == 'sessions': - base.update(sessions=[{'id': 'remote-session', 'label': 'Remote session'}], clients=[]) - elif kind in ('plan', 'clone-plan'): - value = request['input'] - if kind == 'clone-plan': - if scenario in ('collision', 'permission') and value['repo'] == root + '/clones/alpha': - print('Clone destination already exists and is not a repository' if scenario == 'collision' else 'Cannot write clone destination parent', file=sys.stderr) - sys.exit(4) - plan = {'vcs': 'git', 'input': value, 'hostId': 'host-remote', 'repo': value['repo'] + ('.changed' if scenario == 'clone-changed' else ''), 'existing': False, 'label': 'Clone & Open'} - else: - plan = {'vcs': 'git', 'input': value, 'hostId': 'host-remote', 'path': remote_path + ('.changed' if scenario == 'redirect' else ''), 'action': 'new-tab', 'checkout': 'existing', 'branch': 'main', 'nameRole': 'tab', 'name': value['name'], 'label': 'Open tab'} - if scenario == 'warning': plan['warning'] = 'Multiple Rex apps are connected' - base['plan'] = plan - elif kind in ('launch', 'clone-launch'): - if scenario == 'clone-failure': - print('Destination request rejected', file=sys.stderr) - sys.exit(4) - result = {'hostId': 'host-remote', 'sessionId': 'remote-session', 'windowId': 'window', 'blockId': 'block', 'pending': kind == 'clone-launch'} - if kind == 'clone-launch': - result['repo'] = request['reviewed']['repo'] - if scenario == 'clone-warning': result['warning'] = 'Multiple Rex apps are connected' - else: - result.update(path=request['reviewed']['path'], action='new-tab') - base['result'] = result - else: - raise AssertionError(request) - emit(json.dumps(base)) - elif 'ls' in args: - emit({'sessions': [{'session_id': 'local-session', 'label': 'Local session'}]}) - elif 'client.list' in args: - emit({'clients': []}) - elif 'session.list_blocks' in args: - emit({'blocks': []}) - else: - print('unexpected Rex call ' + repr(args), file=sys.stderr) - sys.exit(1) - sys.exit(0) - -root, binary, repo = sys.argv[1:] -bin_dir = root + '/bin' -os.makedirs(bin_dir, exist_ok=True) -with open(bin_dir + '/rex', 'w') as script: - script.write('#!/bin/sh\nexec ' + json.dumps(sys.executable) + ' ' + json.dumps(os.path.abspath(__file__)) + ' --rex "$@"\n') -os.chmod(bin_dir + '/rex', 0o755) - -class Popup(Terminal): - def __init__(self, scenario): - self.log = root + '/' + scenario + '.jsonl' - env = {k: v for k, v in os.environ.items() if not k.startswith('GIT_') and k not in ('REX_SESSION', 'REX_BLOCK', 'REX_CLIENT', 'REX_SERVER', 'REX_HOST')} - home = root + '/home-' + scenario - os.makedirs(home, exist_ok=True) - env.update(HOME=home, XDG_CONFIG_HOME=home + '/config', XDG_STATE_HOME=home + '/state', - GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL=home + '/gitconfig', NO_COLOR='1', - REX_BIN_DIR=bin_dir, REX_WORKTREES_LOCAL_ENDPOINT='unix:///fixture.sock', - REX_WORKTREES_CONFIG=json.dumps({'directory': home, 'config': {}}), - POPUP_ROOT=root, POPUP_LOG=self.log, POPUP_SCENARIO=scenario) - super().__init__(scenario, self.log, binary, repo, env, 20, 110) - - def switch(self): - self.frame('alpha', 'Local session', 'Tab next') - self.send(b'\t\r') - self.frame('Execution machine', 'Esc back') - self.send(b'\x1b[B\r') - - def directory(self, value, tabs): - self.send(b'\t' * tabs + b'\r') - self.frame('Directory (absolute path', 'Esc back') - self.send(b'\x15' + value.encode() + b'\r') - self.frame(value, 'Tab next') - - -def run(scenario, fn): - popup = Popup(scenario) - try: - fn(popup) - finally: - popup.close() - - -def existing(p): - p.switch() - path = root + '/remote/alpha' - p.frame('alpha', 'Remote session', 'Tab next') - assert not p.requests('clone-plan') - p.send(b'\x13') - p.finish() - review, launch = p.requests('plan'), p.requests('launch') - assert len(review) == len(launch) == 1 - assert review[0]['input']['path'] == path and launch[0]['reviewed']['path'] == path - assert review[0]['input']['session'] == {'kind': 'existing', 'id': 'remote-session'} - assert review[0]['input']['additional'] is False and review[0]['input']['split'] is False - assert not p.requests('clone-source') and not p.requests('clone-launch') - - -def pending(p): - p.switch() - frame = p.frame('Remote machine', 'Connecting to Remote machine', 'Tab next') - assert 'WORKTREE alpha' not in frame and 'Local session' not in frame and 'host-local' not in frame - p.send(b'\x13') - p.send(b'\x1b') - p.finish() - assert not p.requests('plan') and not p.requests('launch') - - -def connect(p): - p.switch() - frame = p.frame('Remote helper unavailable', 'Tab next') - assert 'Remote machine' in frame and 'Local session' not in frame and 'host-local' not in frame - p.send(b'\x1b') - p.finish() - assert not p.requests('launch') - - -def clone(p): - p.switch() - destination = root + '/clones/alpha' - frame = p.frame('Remote session', 'Project checkout (after clone)', 'Tab next') - assert 'main' in frame and 'New tab (cloning)' in frame - if p.scenario in ('collision', 'permission'): - p.send(b'\x13') - p.frame('Clone destination already exists' if p.scenario == 'collision' else 'Cannot write clone destination', 'Tab next') - assert not p.requests('clone-launch') - p.directory(root + '/safe/alpha', 4) - elif p.scenario == 'worktree': - p.send(b'\t\t\r') - p.frame('Worktree (select existing or create new)', 'Esc back') - p.send('Create new worktree'.encode() + b'\x1b[B\r') - p.frame('Branch (select unused or type new name)', 'Esc back') - p.send(b'feature/new\r') - p.frame('feature/new', 'Tab next') - p.directory(root + '/custom/task', 1) - else: - p.directory(root + '/safe/alpha', 4) - p.send(b'\x13') - if p.scenario == 'clone-changed': - p.frame('Clone destination changed; edit the destination:', 'Tab next') - p.send(b'\x13\x1b') - p.finish() - assert len(p.requests('clone-plan')) == 1 and not p.requests('clone-launch') - return - if p.scenario == 'clone-failure': - frame = p.frame('Clone needs inspection', 'Destination request rejected', 'Enter / Space close') - assert 'exited 4' in frame - assert p.requests('clone-launch')[0]['input']['repo'] == root + '/safe/alpha' - p.send(b'\r') - p.finish(False) - return - if p.scenario == 'clone-warning': - p.frame('Clone task submitted with warning', 'Multiple Rex apps are connected', 'Enter / Space close') - p.send(b'\r') - p.finish() - plans, launches = p.requests('clone-plan'), p.requests('clone-launch') - assert len(launches) == 1 and len(plans) == (2 if p.scenario in ('collision', 'permission') else 1) - value = launches[0]['input'] - assert value['source']['url'] == 'https://example.test/alpha.git' and value['source']['sourceHostId'] == 'host-local' - assert value['session'] == {'kind': 'existing', 'id': 'remote-session'} - if p.scenario == 'worktree': - assert value['repo'] == destination and value['directory'] == root + '/custom/task' - assert value['checkout'] == 'worktree' and value['branch'] == 'feature/new' and value['branchMode'] == 'create' - else: - assert value['repo'] == root + '/safe/alpha' and value['checkout'] == 'primary' - assert value['branch'] == 'main' and value['branchMode'] == 'existing' - assert launches[0]['reviewed']['repo'] == value['repo'] - assert not os.path.exists(value['repo']) - - -def redirect(p): - p.switch() - p.frame('alpha', 'Remote session', 'Tab next') - p.send(b'\x13') - p.frame('Destination changed; select the worktree again:', 'Tab next') - p.send(b'\x13\x1b') - p.finish() - assert len(p.requests('plan')) == 1 and not p.requests('launch') - - -def warning(p): - p.switch() - p.frame('alpha', 'Remote session', 'Tab next') - p.send(b'\x13') - p.frame('Opened with warning', 'Multiple Rex apps are connected', 'Enter / Space close') - assert len(p.requests('launch')) == 1 - p.send(b'\r') - p.finish() - - -def editor_cancel(p): - p.frame('alpha', 'Local session', 'Tab next') - p.send(b'\t\r') - p.frame('Execution machine', 'Esc back') - p.send(b'\x1b') - p.frame('alpha', 'Tab next') - p.send(b'\r') - p.frame('Execution machine', 'Esc back') - p.send(b'\x1b') - p.frame('alpha', 'Tab next') - p.send(b'\x1b[Z\r') - p.frame('Project (select known', 'Esc back') - p.send(b'\x1b') - p.frame('alpha', 'Tab next') - p.send(b'\x1b') - p.finish() - assert not p.requests('plan') and not p.requests('launch') - - -for scenario, fn in [('existing', existing), ('pending', pending), ('connect', connect), - ('collision', clone), ('permission', clone), ('worktree', clone), - ('clone-changed', clone), ('clone-warning', clone), ('clone-failure', clone), - ('redirect', redirect), ('warning', warning), ('editor-cancel', editor_cancel)]: - run(scenario, fn) diff --git a/test/popup-remote.test.lua b/test/popup-remote.test.lua deleted file mode 100644 index 5b8705c..0000000 --- a/test/popup-remote.test.lua +++ /dev/null @@ -1,17 +0,0 @@ -return function(root) - local runtime = require("runtime") - local repo = root .. "/popup-remote/alpha" - runtime.fs.makeDirectory(repo, { recursive = true }) - local function run(args) - local result = runtime.capture(args, { timeout = 120 }) - assert(result.ok, result.stderr .. result.stdout) - end - run({ "git", "-C", repo, "init", "-b", "main" }) - run({ "git", "-C", repo, "config", "user.name", "Rex Tests" }) - run({ "git", "-C", repo, "config", "user.email", "rex@example.test" }) - runtime.fs.writeFileString(repo .. "/tracked", "base\n") - run({ "git", "-C", repo, "add", "tracked" }) - run({ "git", "-C", repo, "commit", "-m", "base" }) - run({ "git", "-C", repo, "remote", "add", "origin", "https://example.test/alpha.git" }) - run({ "python3", "test/popup-remote.py", root .. "/popup-remote", runtime.path.resolve("dist/rex-worktrees"), repo }) -end diff --git a/test/protocol.test.lua b/test/protocol.test.lua index 2654081..272e5e8 100644 --- a/test/protocol.test.lua +++ b/test/protocol.test.lua @@ -151,6 +151,23 @@ return function() branchMode = "existing", }, } + local external = copy(clone) + external.input.source = { vcs = "git", url = "https://github.com/owner/repo" } + external.input.branch, external.input.branchMode, external.input.checkout = nil, "default", "primary" + local cloneRequest = { version = 5, hostId = "target", kind = "clone-plan", input = external.input } + assert(contracts.validate("Request", cloneRequest).input.source.sourceHostId == nil) + assert(contracts.validate("CloneTaskRequest", { plan = external }).plan.input.branch == nil) + for _, mutate in ipairs({ + function(p) p.branch = "main" end, + function(p) p.checkout = "worktree" end, + function(p) p.checkout = nil end, + function(p) p.directory = "/tree" end, + function(p) p.worktreeName = "task" end, + }) do + local invalid = copy(cloneRequest) + mutate(invalid.input) + assert(not pcall(contracts.validate, "Request", invalid)) + end changed = copy(clone) changed.warning = "informational" assert(worktrees.sameClonePlan(clone, changed)) diff --git a/test/rex-boundary.test.lua b/test/rex-boundary.test.lua index 89c3d33..2012cb0 100644 --- a/test/rex-boundary.test.lua +++ b/test/rex-boundary.test.lua @@ -11,21 +11,24 @@ for arg in "$@"; do last="$arg"; done printf '%s\n' "$last" >> "$REX_TEST_LOG" case " $* " in *' -S Remote '*' whoami '*) printf '{"host_id":"%s","endpoint":"%s","principal":{"transport":"unix"}}\n' "${REX_TEST_REMOTE_HOST:-remote-host}" "${REX_TEST_REMOTE_ENDPOINT:-unix:///remote-one}" ;; + *' hosts.list '*) echo '{"hosts":[{"label":"Mac","endpoints":["https://fixture.test"]}]}' ;; *' hosts list '*) printf '{"home":{"label":"Local","endpoint":"unix:///fixture.sock","this_machine":true},"hosts":[{"host":{"id":"remote-id","label":"Remote","endpoints":["%s"]}}]}\n' "${REX_TEST_REGISTERED_ENDPOINT:-unix:///remote-one}" ;; *' actions '*) echo '{"actions":[{"name":"worktrees_request","args":{"properties":{"request":{"type":"string"}}}}]}' ;; - *' whoami '*) echo '{"host_id":"fixture-host","endpoint":"unix:///fixture.sock","principal":{"transport":"unix"}}' ;; + *' whoami '*) echo '{"host_id":"fixture-host","endpoint":"unix:///fixture.sock","principal":{"transport":"unix"},"tailscale":{"https":{"url":"https://fixture.test"}}}' ;; *' session.list_blocks '*) printf '{"blocks":[{"block_id":"block","host_id":"%s","placement":"%s","window_id":"%s"}]}\n' "${REX_TEST_BLOCK_HOST:-fixture-host}" "${REX_TEST_PLACEMENT:-placed}" "${REX_TEST_WINDOW:-window}" ;; *' ls '*) echo '{"sessions":[{"session_id":"session","label":"Same label"}]}' ;; *' session.focus_block '*) echo '{}' ;; *' process '*) if [ "$REX_TEST_PROCESS_ERROR" = missing ]; then echo 'Error: block target "block" not found' >&2; exit 3; fi if [ "$REX_TEST_PROCESS_ERROR" = denied ]; then echo 'permission denied' >&2; exit 3; fi + if [ "$REX_TEST_NO_CWD" = 1 ]; then echo '{"last_exit":null,"foreground":{}}'; exit 0; fi printf '{"last_exit":%s,"foreground":{"cwd":"%s"}}\n' "${REX_TEST_EXIT:-null}" "${REX_TEST_CWD:-/projects/current}" ;; *' pwd '*) printf '{"pwd":"%s"}\n' "${REX_TEST_PWD:-file://foreign.invalid/projects/current}" ;; - *' client.list '*) echo '{"clients":[]}' ;; - *' session.view '*) printf '{"active_window_id":"window","windows":[{"window_id":"window","focused_block_id":"block","zoomed_block_id":%s,"layers":[{"layout":{"rect":[0,0,1,%s],"block_id":"block"},"blocks":[{"block_id":"block","flavor":"com.superlogical.terminal.shell"}]}]}]}\n' "${REX_TEST_ZOOM:-null}" "${REX_TEST_FRACTION:-1}" ;; - *' size '*) printf '{"columns":160,"rows":%s}\n' "${REX_TEST_ROWS:-80}" ;; - *' session.new_layer '*) echo '{"layer_id":"popup","block_ids":["popup-block"],"revision":1}' ;; + *' client.list '*) + if [ "$REX_TEST_MULTIPLE_APPS" = 1 ]; then + echo '{"clients":[{"client_id":"one","info":{"kind":"app"},"connection_state":"connected"},{"client_id":"two","info":{"kind":"app"},"connection_state":"connected"}]}' + else echo '{"clients":[]}'; fi ;; + *' session.view '*) echo '{"active_window_id":"window","windows":[{"window_id":"window","focused_block_id":"block","zoomed_block_id":null,"layers":[{"layout":{"rect":[0,0,1,1],"block_id":"block"},"blocks":[{"block_id":"block","flavor":"com.superlogical.terminal.shell"}]}]}]}' ;; *' session.new_split '*) echo '{"block_ids":["new-pane"]}' ;; *' session.create '*) echo '{"session_id":"created","initial_windows":[{"window_id":"new-window","block_ids":["new-block"]}]}' ;; *) echo "unexpected rex call: $*" >&2; exit 1 ;; @@ -38,15 +41,27 @@ esac assert(posix.setenv("REX_WORKTREES_LOCAL_ENDPOINT", "unix:///fixture.sock", true)) local client = require("client") local remote = { key = "remote-id", label = "Remote", ["local"] = false, selector = "Remote" } - assert(client.connectMachine(remote).hostId == "remote-host") + local function connected() return rex.withOperation(function() return client.connectMachine(remote) end) end + assert(connected().hostId == "remote-host") assert(posix.setenv("REX_TEST_REMOTE_ENDPOINT", "unix:///remote-two", true)) assert(posix.setenv("REX_TEST_REMOTE_HOST", "remote-host-2", true)) - assert(not pcall(client.connectMachine, remote)) + assert(not pcall(connected)) assert(posix.setenv("REX_TEST_REGISTERED_ENDPOINT", "unix:///remote-two", true)) - assert(client.connectMachine(remote).hostId == "remote-host-2") + assert(connected().hostId == "remote-host-2") assert(posix.setenv("REX_TEST_REMOTE_ENDPOINT", nil)) assert(posix.setenv("REX_TEST_REGISTERED_ENDPOINT", nil)) assert(posix.setenv("REX_TEST_REMOTE_HOST", nil)) + local chooser = require("chooser") + local machineDraft = s.json.encode({ + draft = { mode = "auto" }, origin = s.json.object(), originMachine = "remote-id", + projects = s.json.array(), sessions = s.json.array(), cloneRoot = "", + }) + local machines = chooser.request({ op = "edit", field = "machine", state = machineDraft }, {}) + assert(not machines.error and machines.editor.items[1].title == "Mac") + assert(machines.editor.items[2].title == "Remote" and machines.editor.items[2].detail == "Current terminal") + local selected = chooser.request({ op = "accept", state = machines.state, id = machines.editor.items[1].id }, {}) + assert(not selected.error and selected.rows[2].value == "Mac") + assert(s.json.decode(selected.state).draft.host.hostId == "fixture-host") assert(rex.originDirectory("session", "block") == "/projects/current") assert(posix.setenv("REX_TEST_PWD", "file://localhost/projects/reported", true)) assert(rex.originDirectory("session", "block") == "/projects/reported") @@ -70,25 +85,12 @@ esac assert(split.sessionId == "session" and split.windowId == "anchor-window" and split.blockId == "new-pane") local created = rex.openTerminal({ kind = "new", name = "Same label" }, "Task", "/repo", { "/bin/sh" }) assert(created.sessionId == "created" and created.windowId == "new-window" and created.blockId == "new-block") - rex.openPopup({ "/plugin", "popup" }, "session", { blockId = "block" }) - assert(posix.setenv("REX_TEST_FRACTION", "0.5", true)) - assert(posix.setenv("REX_TEST_ROWS", "40", true)) - rex.openPopup({ "/plugin", "popup" }, "session", { blockId = "block" }) - assert(posix.setenv("REX_TEST_ZOOM", '"block"', true)) - assert(posix.setenv("REX_TEST_ROWS", "80", true)) - rex.openPopup({ "/plugin", "popup" }, "session", { blockId = "block" }) - assert(posix.setenv("REX_TEST_FRACTION", nil)) - assert(posix.setenv("REX_TEST_ROWS", nil)) - assert(posix.setenv("REX_TEST_ZOOM", nil)) local calls = s.fs.readFileString(log) local found = false for line in calls:gmatch("[^\n]+") do local ok, value = pcall(s.json.decode, line) - if ok and type(value) == "table" and value.bounds then - assert(math.abs(value.bounds[3] - 82 / 160) < 1e-9 and math.abs(value.bounds[4] - 19 / 80) < 1e-9) - assert(value.layout.block.options.size.columns == 80 and value.layout.block.options.size.rows == 16) + if ok and type(value) == "table" and value.initial_windows then found = true - elseif ok and type(value) == "table" and value.initial_windows then assert(value.label == "Same label" and #value.initial_windows == 1) assert(value.initial_windows[1].layout.block.options.cwd == "/repo") end @@ -116,6 +118,67 @@ esac s.fs.writeFileString(repo .. "/tracked", "base\n") git("add", "tracked") git("commit", "-m", "base") + local previousConfig = s.getenv("REX_WORKTREES_CONFIG") + local scanRoot = root .. "/projects" + s.fs.makeDirectory(scanRoot .. "/broken", { recursive = true }) + s.fs.writeFileString(scanRoot .. "/broken/.git", "invalid gitfile\n") + assert(posix.setenv("REX_WORKTREES_CONFIG", s.json.encode({ + directory = root, config = { roots = s.json.array({ scanRoot }) }, + }), true)) + local started = chooser.request({ op = "start", context = repo }, {}) + assert(not started.error and not started.submitDisabled) + assert(started.rows[5].value == "main" and started.rows[6].value == repo) + local unavailable = chooser.request({ op = "edit", field = "project", state = started.state }, {}) + assert(unavailable.error and not unavailable.editor) + s.fs.remove(scanRoot .. "/broken/.git") + s.run("git", { "init", "-b", "main", scanRoot .. "/other" }) + local projects = chooser.request({ op = "edit", field = "project", state = started.state }, {}) + assert(not projects.error and projects.editor) + local hasOther = false + for _, item in ipairs(projects.editor.items) do if item.title == "other" then hasOther = true end end + assert(hasOther and projects.rows[5].value == "main" and projects.rows[6].value == repo) + assert(posix.setenv("REX_WORKTREES_CONFIG", previousConfig, true)) + local sourceCheckout, jjRepo = root .. "/source-context", root .. "/quick-jj" + git("worktree", "add", "-b", "source-context", sourceCheckout) + s.fs.writeFileString(sourceCheckout .. "/context-only", "selected checkout\n") + s.run("git", { "-C", sourceCheckout, "add", "context-only" }) + s.run("git", { "-C", sourceCheckout, "commit", "-m", "source context" }) + s.run("jj", { "git", "init", "--no-colocate", jjRepo }) + s.run("jj", { "-R", jjRepo, "describe", "-m", "source context" }) + local quickRoot = root .. "/quick-checkouts" + assert(posix.setenv("REX_WORKTREES_CONFIG", s.json.encode({ + directory = root, config = { projects = { + { path = repo, worktreeRoot = quickRoot }, { path = jjRepo, worktreeRoot = quickRoot }, + } }, + }), true)) + assert(posix.setenv("REX_TEST_MULTIPLE_APPS", "1", true)) + for _, source in ipairs({ sourceCheckout, jjRepo }) do + local ready = chooser.request({ op = "start", context = source }, {}) + assert(not ready.error) + local mode = chooser.request({ op = "edit", field = "mode", state = ready.state }, {}) + ready = chooser.request({ op = "accept", state = mode.state, id = mode.editor.items[2].id }, {}) + local original = s.json.decode(ready.state).draft.destination.worktree + local name = original.vcs == "git" and "quick-git" or "quick-jj" + local named = chooser.request({ op = "submit", state = ready.state, text = name }, {}) + assert(not named.error and named.confirmation and not named.done) + assert(named.rows[3].value == "Same label" and named.rows[6].value == quickRoot .. "/" .. name) + assert(named.rows[7].value == "Always new tab") + local input = chooser.inputFor(s.json.decode(named.state).draft) + local plan = worktrees.planLaunch(input, "fixture-host") + assert((plan.base.head or plan.base.commitId) == original.head and input.repo == source) + for _, invalid in ipairs({ "", "../escape", "-bad", "bad\nname" }) do + local rejected = chooser.request({ op = "submit", state = ready.state, text = invalid }, {}) + assert(rejected.error and not rejected.done and not rejected.confirmation) + assert(rejected.rows[6].value == source) + end + end + assert(not s.fs.exists(quickRoot)) + assert(posix.setenv("REX_WORKTREES_CONFIG", previousConfig, true)) + local default = chooser.request({ op = "start", context = sourceCheckout }, {}) + local namedDefault = chooser.request({ op = "submit", state = default.state, text = "default-root" }, {}) + assert(not namedDefault.error and namedDefault.confirmation) + assert(namedDefault.rows[6].value == repo .. ".worktrees/default-root") + assert(posix.setenv("REX_TEST_MULTIPLE_APPS", nil)) local redirected = { vcs = "git", repo = repo, @@ -139,11 +202,18 @@ esac blockId = "block", }) assert(posix.setenv("REX_TEST_CWD", repo, true)) - assert(posix.setenv("REX_TEST_PWD", repo, true)) + assert(posix.setenv("REX_TEST_PWD", "file://localhost/stale", true)) local existingInput = { vcs = "git", repo = repo, path = repo, name = "Task", session = { kind = "existing", id = "session" } } local reuse = worktrees.planLaunch(existingInput, "fixture-host") assert(reuse.action == "focus" and reuse.target.blockId == "block" and reuse.target.windowId == "window") + assert(posix.setenv("REX_TEST_PWD", repo, true)) + assert(posix.setenv("REX_TEST_CWD", root, true)) + assert(worktrees.planLaunch(existingInput, "fixture-host").action == "new-tab") + assert(posix.setenv("REX_TEST_CWD", repo, true)) + assert(posix.setenv("REX_TEST_NO_CWD", "1", true)) + assert(worktrees.planLaunch(existingInput, "fixture-host").action == "new-tab") + assert(posix.setenv("REX_TEST_NO_CWD", nil)) local splitInput = { vcs = "git", repo = repo, diff --git a/test/terminal-driver.py b/test/terminal-driver.py index 74e9782..ed5adf4 100644 --- a/test/terminal-driver.py +++ b/test/terminal-driver.py @@ -1,12 +1,9 @@ -import fcntl import json import os import pty import select import signal -import struct import sys -import termios import time root, binary, lua, repo, git_bin, jj_bin = sys.argv[1:] @@ -24,12 +21,10 @@ f.write('''#!/bin/sh for arg in "$@"; do last="$arg"; done printf '%s\\n' "$last" >> "$REX_PTY_LOG" -if [ "$REX_TEST_PENDING" = 1 ]; then echo "$$" > "$HOME/pending-rex.pid"; exec tail -f /dev/null; fi -if [ "$REX_TEST_FAIL" = 1 ]; then echo "synthetic startup failure" >&2; exit 1; fi case " $* " in *' hosts list '*) echo '{"home":{"label":"Local","endpoint":"unix:///fixture.sock","this_machine":true},"hosts":[]}' ;; *' whoami '*) echo '{"host_id":"fixture-host","endpoint":"unix:///fixture.sock","principal":{"transport":"unix"}}' ;; - *' ls '*) if [ "$REX_DUP_SESSIONS" = 1 ]; then echo '{"sessions":[{"session_id":"first","label":"Same label"},{"session_id":"second","label":"Same label"}]}'; else echo '{"sessions":[{"session_id":"session","label":"Session"}]}'; fi ;; + *' ls '*) echo '{"sessions":[{"session_id":"session","label":"Session"}]}' ;; *' client.list '*) echo '{"clients":[]}' ;; *' session.list_blocks '*) if [ "$REX_TASK_MODE" = 1 ]; then echo '{"blocks":[{"block_id":"block","host_id":"fixture-host","placement":"placed","window_id":"window"}]}'; else echo '{"blocks":[]}'; fi ;; *' session.create '*) echo '{"session_id":"created","initial_windows":[{"window_id":"new-window","block_ids":["new-block"]}]}' ;; @@ -44,209 +39,43 @@ def start(argv, env): pid, fd = pty.fork() if pid == 0: os.execve(argv[0], argv, env) - fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack('HHHH', 20, 96, 0, 0)) return pid, fd -def frame(fd, needle, offset, buffer): - deadline = time.monotonic() + 15 - while True: - start_at = buffer.rfind(b'\x1b[H\x1b[2J', offset) - if start_at >= offset: - end = buffer.find(b'\x1b[0J', start_at) - if end >= 0 and all(part in buffer[start_at:end] for part in (needle if isinstance(needle, tuple) else (needle,))): - return buffer, end + 4 - remaining = deadline - time.monotonic() - if remaining <= 0: raise AssertionError('timeout waiting for frame '+repr(needle)+': '+repr(buffer[-1800:])) - if select.select([fd], [], [], remaining)[0]: - chunk = os.read(fd, 65536) - if not chunk: raise AssertionError('PTY closed: '+repr(buffer[-1800:])) - buffer += chunk - -def finish(pid, fd, success=True): +def finish(pid, fd, prompts): deadline = time.monotonic() + 15 output = b'' + pending = b'' + answered = 0 while True: done, status = os.waitpid(pid, os.WNOHANG) if done: os.close(fd) - if not os.WIFEXITED(status) or (os.WEXITSTATUS(status) == 0) != success: + if not os.WIFEXITED(status) or os.WEXITSTATUS(status) != 0: raise AssertionError('PTY process failed: '+repr(output[-3000:])) + assert answered == prompts, (answered, prompts, output[-3000:]) return remaining = deadline - time.monotonic() if remaining <= 0: os.kill(pid, signal.SIGKILL); os.waitpid(pid, 0); raise AssertionError('PTY timeout') if select.select([fd], [], [], remaining)[0]: - try: output += os.read(fd, 65536) - except OSError: pass - -pending_env = env.copy() -pending_env['REX_TEST_PENDING'] = '1' -pid, fd = start([binary, 'popup', '--context', repo], pending_env) -try: - data, at = frame(fd, b'Discovering', 0, b'') - os.write(fd, b'\x13\x1b') - finish(pid, fd) -except BaseException: - try: os.kill(pid, signal.SIGKILL); os.waitpid(pid, 0) - except (ProcessLookupError, ChildProcessError): pass - raise -finally: - pidfile = root + '/pending-rex.pid' - if os.path.exists(pidfile): - with open(pidfile) as f: pending_pid = int(f.read()) - try: os.kill(pending_pid, signal.SIGKILL) - except ProcessLookupError: pass - -failure_env = env.copy() -failure_env['REX_TEST_FAIL'] = '1' -pid, fd = start([binary, 'popup', '--context', repo], failure_env) -try: - data, at = frame(fd, b'synthetic startup failure', 0, b'') - assert b'Could not open worktrees' in data - os.write(fd, b'\r') - finish(pid, fd, success=False) -except BaseException: - try: os.kill(pid, signal.SIGKILL); os.waitpid(pid, 0) - except (ProcessLookupError, ChildProcessError): pass - raise - -pid, fd = start([binary, 'popup', '--context', repo], env) -try: - data, at = frame(fd, (b'pty-source', b'Tab next'), 0, b'') - os.write(fd, b'\r') - data, at = frame(fd, b'Esc back', at, data) - for byte in '木👩\u200d💻'.encode(): - os.write(fd, bytes([byte])) - data, at = frame(fd, '木👩\u200d💻'.encode(), at, data) - os.write(fd, b'\x7f') - data, at = frame(fd, '木'.encode(), at, data) - os.write(fd, b'\x1b') - data, at = frame(fd, b'Tab next', at, data) - os.write(fd, b'\r') - data, at = frame(fd, b'Esc back', at, data) - fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack('HHHH', 10, 60, 0, 0)) - os.kill(pid, signal.SIGWINCH) - data, at = frame(fd, b'Resize', at, data) - fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack('HHHH', 22, 100, 0, 0)) - os.kill(pid, signal.SIGWINCH) - data, at = frame(fd, b'Esc back', at, data) - os.write(fd, b'\x1b[B') - data, at = frame(fd, b'Esc back', at, data) - os.write(fd, b'\x13') - data, at = frame(fd, b'Tab next', at, data) - os.write(fd, b'\x1b') - finish(pid, fd) -except BaseException: - try: os.kill(pid, signal.SIGKILL); os.waitpid(pid, 0) - except (ProcessLookupError, ChildProcessError): pass - raise -pid, fd = start([binary, 'popup', '--context', repo], env) -try: - data, at = frame(fd, (b'pty-source', b'Session', b'Tab next'), 0, b'') - os.write(fd, b'\x13') - finish(pid, fd) -except BaseException: - try: os.kill(pid, signal.SIGKILL); os.waitpid(pid, 0) - except (ProcessLookupError, ChildProcessError): pass - raise -with open(env['REX_PTY_LOG']) as f: - requests = [] - for line in f: - try: requests.append(json.loads(line)) - except ValueError: pass -created = [item for item in requests if isinstance(item, dict) and 'window_label' in item and 'layout' in item] -assert len(created) == 1 and created[0]['session_id'] == 'session' -args = created[0]['layout']['block']['options']['command'] -assert 'task' in args and json.loads(args[args.index('task')+1])['path'] == repo - - -pid, fd = start([binary, 'popup', '--context', repo], env) -try: - data, at = frame(fd, (b'pty-source', b'Session', b'Tab next'), 0, b'') - os.write(fd, b'\t\t\r') - data, at = frame(fd, b'Esc back', at, data) - os.write(fd, b'Session\r') - data, at = frame(fd, (b'New: Session', b'Tab next'), at, data) - os.write(fd, b'\x13') - finish(pid, fd) -except BaseException: - try: os.kill(pid, signal.SIGKILL); os.waitpid(pid, 0) - except (ProcessLookupError, ChildProcessError): pass - raise -with open(env['REX_PTY_LOG']) as f: - requests = [] - for line in f: - try: requests.append(json.loads(line)) - except ValueError: pass -new_sessions = [item for item in requests if isinstance(item, dict) and 'initial_windows' in item] -assert len(new_sessions) == 1 and new_sessions[0]['label'] == 'Session' -args = new_sessions[0]['initial_windows'][0]['layout']['block']['options']['command'] -assert 'task' in args and json.loads(args[args.index('task')+1])['session'] == {'kind': 'new', 'name': 'Session'} - -pid, fd = start([binary, 'popup', '--context', repo], env) -try: - data, at = frame(fd, (b'pty-source', b'Session', b'Tab next'), 0, b'') - os.write(fd, b'\t\t\t\r') - data, at = frame(fd, b'Create new worktree', at, data) - os.write(fd, b'Create new worktree\x1b[B\r') - data, at = frame(fd, b'Branch (', at, data) - os.write(fd, b'feature/topic\r') - data, at = frame(fd, (b'feature/topic', b'Tab next'), at, data) - os.write(fd, b'\t\r') - data, at = frame(fd, b'Directory (', at, data) - checkout = root + '/custom-checkout' - os.write(fd, b'\x15' + checkout.encode() + b'\r') - data, at = frame(fd, (b'DIRECTORY', b'Tab next'), at, data) - os.write(fd, b'\x13') - finish(pid, fd) -except BaseException: - try: os.kill(pid, signal.SIGKILL); os.waitpid(pid, 0) - except (ProcessLookupError, ChildProcessError): pass - raise -with open(env['REX_PTY_LOG']) as f: - requests = [] - for line in f: - try: requests.append(json.loads(line)) - except ValueError: pass -created = [item for item in requests if isinstance(item, dict) and 'window_label' in item and 'layout' in item] -assert len(created) == 2 -args = created[-1]['layout']['block']['options']['command'] -task = json.loads(args[args.index('task')+1]) -assert task['branch'] == 'feature/topic' and task['path'] == checkout -assert not os.path.exists(checkout) - -duplicate_env = env.copy() -duplicate_env['REX_DUP_SESSIONS'] = '1' -pid, fd = start([binary, 'popup', '--context', repo], duplicate_env) -try: - data, at = frame(fd, (b'pty-source', b'Tab next'), 0, b'') - os.write(fd, b'\t\t\r') - data, at = frame(fd, b'Esc back', at, data) - os.write(fd, b'\x1b[B\x1b[B\r') - data, at = frame(fd, (b'Same label', b'Tab next'), at, data) - os.write(fd, b'\x13') - finish(pid, fd) -except BaseException: - try: os.kill(pid, signal.SIGKILL); os.waitpid(pid, 0) - except (ProcessLookupError, ChildProcessError): pass - raise -with open(env['REX_PTY_LOG']) as f: - requests = [] - for line in f: - try: requests.append(json.loads(line)) - except ValueError: pass -created = [item for item in requests if isinstance(item, dict) and 'window_label' in item and 'layout' in item] -assert created[-1]['session_id'] == 'second' -args = created[-1]['layout']['block']['options']['command'] -assert json.loads(args[args.index('task')+1])['session'] == {'kind':'existing', 'id':'second'} + try: + chunk = os.read(fd, 65536) + output += chunk + pending += chunk + while b'PTY_AUTH_PROMPT:' in pending: + pending = pending.split(b'PTY_AUTH_PROMPT:', 1)[1] + os.write(fd, b'fixture-credential\n') + answered += 1 + except OSError: + pass for name, target in [('git', git_bin), ('jj', jj_bin)]: with open(root+'/pty-bin/'+name, 'w') as f: - f.write('#!/bin/sh\ncase "$1 $2" in "clone "*|"git clone") exec 3<>/dev/tty || exit 1;; esac\nexec '+json.dumps(target)+' "$@"\n') + f.write('#!/bin/sh\ncase "$1 $2" in "clone "*|"git clone") exec 3<>/dev/tty || exit 1; printf PTY_AUTH_PROMPT: >&3; IFS= read -r answer <&3; [ "$answer" = fixture-credential ] || exit 1;; esac\nexec '+json.dumps(target)+' "$@"\n') os.chmod(root+'/pty-bin/'+name, 0o755) env['PATH'] = root+'/pty-bin:' + env.get('PATH', '') pid, fd = start([lua, 'test/pty-child.lua', repo, root+'/pty-git-clone', root+'/pty-jj-clone'], env) -finish(pid, fd) +finish(pid, fd, 2) for name in ('pty-git-clone', 'pty-jj-clone'): with open(root+'/'+name+'/tracked') as f: assert f.read() == 'base\n' task_repo = root + '/pty-clone-task' @@ -258,6 +87,6 @@ def finish(pid, fd, success=True): plan = {'vcs':'git', 'hostId':'fixture-host', 'repo':task_repo, 'existing':False, 'label':'Clone & Open', 'input':clone_input} request = {'plan':plan, 'rexBinDir':root+'/pty-bin', 'rexLocalEndpoint':'unix:///fixture.sock'} pid, fd = start([binary, 'clone-task', json.dumps(request)], task_env) -finish(pid, fd) +finish(pid, fd, 1) with open(task_repo+'/tracked') as f: assert f.read() == 'base\n' with open(root+'/state/rex-worktrees/clone-root.json') as f: assert json.load(f)['cloneRoot'] == root diff --git a/test/terminal.py b/test/terminal.py deleted file mode 100644 index 9115f9a..0000000 --- a/test/terminal.py +++ /dev/null @@ -1,90 +0,0 @@ -import errno -import fcntl -import json -import os -import pty -import re -import select -import signal -import struct -import termios -import time - - -class Terminal: - def __init__(self, scenario, log, binary, repo, env, rows, columns, normalize=True): - self.scenario, self.log, self.normalize = scenario, log, normalize - self.pid, self.fd = pty.fork() - if self.pid == 0: - os.execve(binary, [binary, 'popup', '--context', repo], {**env, 'LUA_PATH': '', 'LUA_CPATH': ''}) - fcntl.ioctl(self.fd, termios.TIOCSWINSZ, struct.pack('HHHH', rows, columns, 0, 0)) - self.data, self.offset = b'', 0 - - def send(self, data): - os.write(self.fd, data if isinstance(data, bytes) else data.encode()) - - def read(self, deadline): - remaining = deadline - time.monotonic() - if remaining <= 0 or not select.select([self.fd], [], [], remaining)[0]: - raise AssertionError(self.scenario + ' PTY timeout: ' + repr(self.data[-5000:])) - try: - chunk = os.read(self.fd, 65536) - except OSError as error: - if error.errno == errno.EIO: return False - raise - previous = len(self.data) - self.data += chunk - start = max(0, previous - 3) - for query in re.finditer(b'\x1b\\[(?:6n|0?c)', self.data[start:]): - if start + query.end() > previous: - self.send(b'\x1b[1;1R' if query.group() == b'\x1b[6n' else b'\x1b[?1;2c') - return bool(chunk) - - def frame(self, *needles, absent=()): - deadline = time.monotonic() + 20 - needles = [n.encode() if isinstance(n, str) else n for n in needles] - while True: - start = self.data.find(b'\x1b[H\x1b[2J', self.offset) - if start >= 0: - end = self.data.find(b'\x1b[0J', start) - next_start = self.data.find(b'\x1b[H\x1b[2J', start + 1) - if next_start >= 0 and (end < 0 or next_start < end): - self.offset = next_start - continue - if end >= 0: - frame = self.data[start:end + 4] - self.offset = end + 4 - text = frame.decode('utf-8') - match = b''.join(frame.split()) if self.normalize else frame - if all((b''.join(n.split()) if self.normalize else n) in match for n in needles) and not any(n.encode() in frame for n in absent): - return text - continue - if not self.read(deadline): - raise AssertionError(self.scenario + ' PTY closed: ' + repr(self.data[-5000:])) - - def requests(self, kind=None): - try: - with open(self.log) as log: rows = [json.loads(line) for line in log] - except FileNotFoundError: - rows = [] - return [row for row in rows if kind is None or row['kind'] == kind] - - def finish(self, success=True): - deadline = time.monotonic() + 20 - while True: - pid, status = os.waitpid(self.pid, os.WNOHANG) - if not pid: - if self.read(deadline): - continue - _, status = os.waitpid(self.pid, 0) - self.pid = None - assert os.WIFEXITED(status) and (os.WEXITSTATUS(status) == 0) == success, (self.scenario, status, self.data[-5000:]) - return - - def close(self): - if self.pid: - try: os.kill(self.pid, signal.SIGKILL) - except ProcessLookupError: pass - os.waitpid(self.pid, 0) - self.pid = None - os.close(self.fd) diff --git a/test/unicode.test.lua b/test/unicode.test.lua deleted file mode 100644 index 74b1324..0000000 --- a/test/unicode.test.lua +++ /dev/null @@ -1,27 +0,0 @@ -return function() - local unicode = require("runtime").unicode - local cases = { - { "é", 1 }, - { "👩‍💻", 2 }, - { "👨‍👩‍👧‍👦", 2 }, - { "🇺🇸", 2 }, - { "1️⃣", 2 }, - { "❤️", 2 }, - { "क्ष", 2 }, - { "क्‍ष", 2 }, - { "각", 4 }, - { "a️", 1 }, - } - for _, case in ipairs(cases) do - local glyph, width = case[1], case[2] - assert(unicode.width(glyph) == width, glyph) - assert(unicode.dropLastGrapheme("x" .. glyph) == "x", glyph) - assert(unicode.fit(glyph, width) == glyph, glyph) - assert(unicode.fit(glyph .. "z", width, "") == glyph, glyph) - local truncated = unicode.fit("x" .. glyph .. "z", width + 1, "…") - assert(unicode.width(truncated) <= width + 1, glyph) - assert(not truncated:find("�", 1, true), glyph) - local wrapped = unicode.wrap(glyph .. "x", width) - assert(wrapped[1] == glyph and wrapped[2] == "x", glyph) - end -end