From 1ee919479928f1cac92ab2c76dffbbd246b65b58 Mon Sep 17 00:00:00 2001 From: Kohei Wada Date: Sun, 13 Sep 2026 12:48:29 +0900 Subject: [PATCH] feat(lua): resolve system runtime tiers so distro packages work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AUR (#375) installs to /usr/bin + /usr/share, but runtimepath only knew $TTYMAP_RUNTIME, the baked manifest dir and the two XDG dirs — a packaged ttymap would fail at startup with "runtime not found" for every user. - add /usr/local/share/ttymap then /usr/share/ttymap as the lowest- priority tiers, so a per-user `make install` always shadows a packaged copy and machines without a package see no change - split candidate enumeration out of resolve_runtime_path so the ordering is unit-testable without staging directories - Makefile: `install-system` stages $DESTDIR$PREFIX/{bin,share/ttymap} for packagers. `make install` keeps its exact per-user behaviour and still never needs sudo; the Makefile itself never calls it - packaging/PKGBUILD as the in-tree reference for the AUR copy Refs #375 Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01GFGFsYeFLqRaWUAzXonwd3 --- CLAUDE.md | 5 ++- Makefile | 51 +++++++++++++++++++-- README.md | 10 +++++ docs/lua-architecture.md | 8 +++- packaging/PKGBUILD | 55 +++++++++++++++++++++++ ttymap-lua/src/runtimepath.rs | 85 +++++++++++++++++++++++++++-------- 6 files changed, 188 insertions(+), 26 deletions(-) create mode 100644 packaging/PKGBUILD diff --git a/CLAUDE.md b/CLAUDE.md index 1826cdc..f710e3c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -162,7 +162,7 @@ ttymap-lua/ (Lua plugin runtime; mlua + Lua 5.4 vendored) bridge/ Lua spec → Rust trait adapters (Component, PaletteProvider) vm.rs mlua VM + builtin searcher registrar.rs LuaRegistry behind Rc> - runtimepath.rs layered runtime resolution (env > workspace > XDG) + runtimepath.rs layered runtime resolution (env > workspace > XDG > system) init_lua.rs bundled init.lua loader host.rs / handle.rs host-side shared state + channel plumbing map_api.rs per-frame draw surface handed to plugins @@ -185,6 +185,9 @@ ttymap-app/ (composition root + binary; ratatui + crossterm sh runtime/ bundled Lua plugins + init.lua (workspace root, shared by ttymap-lua and ttymap-cli's snap path) + +packaging/ reference PKGBUILD for the AUR (the published + copy lives in aur.archlinux.org/ttymap.git) ``` The single layering rule: **the engine crate does not depend on diff --git a/Makefile b/Makefile index 4eb16b7..8161e85 100644 --- a/Makefile +++ b/Makefile @@ -7,9 +7,19 @@ # live here, resolved via # standard `package.path`) # -# Single-user, no root. `/etc/ttymap` and `/usr/local/share/ttymap` -# layouts are intentionally unsupported — ttymap is a per-user TUI, -# system-wide installs aren't worth the path-juggling. +# Single-user, no root: `make install` never needs sudo and never +# writes outside `$HOME`. Do not run it as root to get a system-wide +# install — use the packager path below instead. +# +# Packagers (AUR, …) build a system layout with: +# +# make install-system DESTDIR="$pkgdir" PREFIX=/usr +# +# which stages `$DESTDIR$PREFIX/{bin/ttymap,share/ttymap/}` as an +# unprivileged user; the package manager does the privileged part. +# The binary resolves `/usr/local/share/ttymap` and `/usr/share/ttymap` +# as its lowest-priority runtime tiers, so a per-user `make install` +# always shadows a packaged copy. # # `cargo install` alone places only the binary; the binary fails # fast when it can't find any runtime layer (no `lua/` on disk). @@ -17,7 +27,16 @@ XDG_DATA_HOME ?= $(HOME)/.local/share DATA_DIR := $(XDG_DATA_HOME)/ttymap -.PHONY: help install install-bin install-runtime uninstall clean +# Packager-only knobs. Unset by default, so every target above +# behaves exactly as it did before these existed. +PREFIX ?= /usr/local +DESTDIR ?= +SYS_BIN_DIR := $(DESTDIR)$(PREFIX)/bin +SYS_DATA_DIR := $(DESTDIR)$(PREFIX)/share/ttymap + +.PHONY: help install install-bin install-runtime \ + install-system install-system-bin install-system-runtime \ + uninstall clean # `make` with no target lists what's available. Mirrors the "first # target is the default" make convention while making the default @@ -33,8 +52,13 @@ help: @echo ' clean cargo clean' @echo ' help show this message' @echo '' + @echo 'Packaging (not for interactive use):' + @echo ' install-system stage $$DESTDIR$$PREFIX/{bin,share/ttymap} for a distro package' + @echo '' @echo 'Variables:' @echo ' XDG_DATA_HOME install root (default: $$HOME/.local/share)' + @echo ' PREFIX packaging prefix (default: /usr/local)' + @echo ' DESTDIR packaging staging root (default: empty)' install: install-bin install-runtime @@ -59,6 +83,25 @@ install-runtime: cp -r runtime/lua/. $(DATA_DIR)/lua/ cp runtime/init.lua $(DATA_DIR)/init.lua +# ── Packaging ─────────────────────────────────────────────────────── +# +# Never invoked by a normal install. Writes only under $(DESTDIR), +# so makepkg / dpkg-buildpackage stage it unprivileged. + +install-system: install-system-bin install-system-runtime + +install-system-bin: + cargo build --release --locked + install -Dm755 target/release/ttymap $(SYS_BIN_DIR)/ttymap + +install-system-runtime: + # Same tree as the per-user install, rooted at the packaging + # prefix. No rm -rf here: the staging dir belongs to the + # package manager, which owns file removal on upgrade. + install -d $(SYS_DATA_DIR)/lua + cp -r runtime/lua/. $(SYS_DATA_DIR)/lua/ + install -Dm644 runtime/init.lua $(SYS_DATA_DIR)/init.lua + uninstall: # Try both the current name and previous names so an upgrade # path that crossed the rename boundary still cleans up. diff --git a/README.md b/README.md index c48dcb3..51b4086 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,16 @@ make install Installs `~/.cargo/bin/ttymap` + `~/.local/share/ttymap/` (bundled runtime). Single-user, no root. `cargo install` alone fails fast with a "did you `make install`?" message because the runtime needs to be placed. +### Packaging + +Distro packagers stage a system layout without root: + +```bash +make install-system DESTDIR="$pkgdir" PREFIX=/usr +``` + +That writes `$DESTDIR$PREFIX/bin/ttymap` and `$DESTDIR$PREFIX/share/ttymap/`; the package manager does the privileged part. `/usr/local/share/ttymap` and `/usr/share/ttymap` are the binary's lowest-priority runtime tiers, so a per-user `make install` always shadows a packaged copy. A reference `PKGBUILD` lives in [`packaging/`](packaging/). + ## Usage **Interactive:** diff --git a/docs/lua-architecture.md b/docs/lua-architecture.md index 21b1197..978b682 100644 --- a/docs/lua-architecture.md +++ b/docs/lua-architecture.md @@ -44,7 +44,7 @@ ttymap-lua/src/ no custom plugin searcher tick.rs dispatch_tick(bus, map) — per-frame fan-out of the "tick" bucket on the host EventBus - runtimepath.rs runtime path resolution (env / manifest / xdg) + runtimepath.rs runtime path resolution (env / manifest / xdg / system) init_lua.rs run_init_lua_chain (system → user init.lua in the shared VM); read_init_lua_config_only is the snap-only thin path @@ -368,10 +368,14 @@ Neovim-style ordered list (`runtimepath.rs`). Every layer with a 2. `/runtime` (dev — wins over stale install) 3. `$XDG_CONFIG_HOME/ttymap` (user) 4. `$XDG_DATA_HOME/ttymap` (bundled — `~/.local/share/ttymap`) +5. `/usr/local/share/ttymap`, then `/usr/share/ttymap` (distro + package — `make install-system`) Layer 2 path is the maintainer's home dir baked at compile time; on a user machine it doesn't exist and is filtered out, so user > bundled -in production. +in production. Layer 5 ranks last so a per-user `make install` always +shadows a packaged copy; on a machine with no distro package those +paths simply don't exist. Plugins resolve as **plain Lua modules** under `/lua/plugin/.lua` (or diff --git a/packaging/PKGBUILD b/packaging/PKGBUILD new file mode 100644 index 0000000..3d31a32 --- /dev/null +++ b/packaging/PKGBUILD @@ -0,0 +1,55 @@ +# Maintainer: Kohei Wada +# +# Reference PKGBUILD, kept in-tree as the source of truth; the AUR +# copy lives in aur.archlinux.org/ttymap.git. +# +# NOT PUBLISHABLE AS-IS: `make install-system` landed after v0.3.0, +# so this needs a newer tag. Bump pkgver and refresh sha256sums +# (`updpkgsums`) against that release before pushing to the AUR. + +pkgname=ttymap +pkgver=0.3.0 +pkgrel=1 +pkgdesc='Scriptable globe for the terminal — Mapbox Vector Tiles rendered as Unicode Braille' +arch=('x86_64' 'aarch64') +url='https://github.com/Kohei-Wada/ttymap' +license=('MIT' 'Apache-2.0') +depends=('gcc-libs' 'openssl') +makedepends=('cargo') +source=("$pkgname-$pkgver.tar.gz::$url/archive/refs/tags/v$pkgver.tar.gz") +sha256sums=('ef3fe9d046014fa30c26aa1eb052d1ec5ac11c6580ec362c448d64c52015780b') + +prepare() { + cd "$pkgname-$pkgver" + # Vendor dependencies up front so build() runs without network, + # as makepkg expects. + export RUSTUP_TOOLCHAIN=stable + cargo fetch --locked --target "$(rustc -vV | sed -n 's/^host: //p')" +} + +build() { + cd "$pkgname-$pkgver" + export RUSTUP_TOOLCHAIN=stable + export CARGO_TARGET_DIR=target + cargo build --frozen --release +} + +check() { + cd "$pkgname-$pkgver" + export RUSTUP_TOOLCHAIN=stable + # The IPC round-trip test spawns the built binary; no network. + cargo test --frozen --release +} + +package() { + cd "$pkgname-$pkgver" + # install-system stages bin/ + share/ttymap/ under $pkgdir; it + # never touches the live filesystem and never needs root. Its + # cargo build is a cache hit on build()'s output (same + # CARGO_TARGET_DIR), so nothing is fetched or recompiled here. + make install-system DESTDIR="$pkgdir" PREFIX=/usr + + install -Dm644 LICENSE-MIT "$pkgdir/usr/share/licenses/$pkgname/LICENSE-MIT" + install -Dm644 LICENSE-APACHE "$pkgdir/usr/share/licenses/$pkgname/LICENSE-APACHE" + install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md" +} diff --git a/ttymap-lua/src/runtimepath.rs b/ttymap-lua/src/runtimepath.rs index 5d2affd..270f3bf 100644 --- a/ttymap-lua/src/runtimepath.rs +++ b/ttymap-lua/src/runtimepath.rs @@ -25,6 +25,11 @@ //! for app config. //! 4. `$XDG_DATA_HOME/ttymap` (default `~/.local/share/ttymap`) — //! bundled scripts placed by `make install`. +//! 5. `/usr/local/share/ttymap`, then `/usr/share/ttymap` — the +//! system tiers a distro package (AUR, …) writes into. Last in +//! priority so a per-user `make install` always shadows a +//! packaged copy, and absent on a machine that has never +//! installed one. //! //! The Vec model is the foundation; `register_builtin_plugins` / //! `install_builtin_searcher` walk it in order. PR1 wires the search @@ -70,25 +75,37 @@ impl std::fmt::Display for RuntimePathError { /// (env > user > bundled > dev). On full miss, returns the candidate /// list back so the caller can render a "we tried these" failure. pub fn resolve_runtime_path(dirs: Option<&AppDirs>) -> Result, RuntimePathError> { - let mut found: Vec = Vec::new(); - let mut tried: Vec = Vec::new(); - - let mut visit = |p: PathBuf| { - if is_valid(&p) { - found.push(p); - } else { - tried.push(p); - } - }; + let (found, tried): (Vec, Vec) = candidate_layers(dirs) + .into_iter() + .partition(|p| is_valid(p)); + + if found.is_empty() { + Err(RuntimePathError { candidates: tried }) + } else { + Ok(found) + } +} + +/// System-wide tiers, highest priority first. A distro package +/// (AUR, …) installs under one of these; `make install` never +/// writes here, so on a machine without a packaged ttymap they +/// simply don't exist and drop out of the resolved list. +const SYSTEM_LAYERS: [&str; 2] = ["/usr/local/share/ttymap", "/usr/share/ttymap"]; + +/// Every layer we would consider, in priority order, before checking +/// whether any of them exists. Split out from [`resolve_runtime_path`] +/// so the ordering itself is testable without staging directories. +fn candidate_layers(dirs: Option<&AppDirs>) -> Vec { + let mut out: Vec = Vec::new(); if let Ok(p) = std::env::var("TTYMAP_RUNTIME") { - visit(PathBuf::from(p)); + out.push(PathBuf::from(p)); } if let Some(manifest) = option_env!("CARGO_MANIFEST_DIR") { // ttymap-lua/ lives under the workspace root; runtime/ sits // at that root, one level up from this crate's manifest. if let Some(workspace) = PathBuf::from(manifest).parent() { - visit(workspace.join("runtime")); + out.push(workspace.join("runtime")); } } // The user tier (`$XDG_CONFIG_HOME/ttymap`) holds the user's @@ -96,15 +113,12 @@ pub fn resolve_runtime_path(dirs: Option<&AppDirs>) -> Result, Runt // `make install` populates. Both come from the centralised // `AppDirs` resolver in `ttymap-config` (#362). if let Some(d) = dirs { - visit(d.config.clone()); - visit(d.data.clone()); + out.push(d.config.clone()); + out.push(d.data.clone()); } + out.extend(SYSTEM_LAYERS.iter().map(PathBuf::from)); - if found.is_empty() { - Err(RuntimePathError { candidates: tried }) - } else { - Ok(found) - } + out } /// Cache the resolved runtime path. Idempotent — first caller wins. @@ -179,6 +193,39 @@ mod tests { ); } + #[test] + fn system_layers_rank_below_the_per_user_tiers() { + // Order is the whole contract: a per-user `make install` + // under $XDG_DATA_HOME must shadow a distro-packaged copy + // under /usr/share, never the other way round. + let dirs = AppDirs { + config: PathBuf::from("/tmp/ttymap-test-config"), + data: PathBuf::from("/tmp/ttymap-test-data"), + cache: PathBuf::from("/tmp/ttymap-test-cache"), + state: PathBuf::from("/tmp/ttymap-test-state"), + }; + let layers = candidate_layers(Some(&dirs)); + + let pos = |p: &str| { + layers + .iter() + .position(|l| l == &PathBuf::from(p)) + .unwrap_or_else(|| panic!("{p} missing from candidates: {layers:?}")) + }; + + assert!(pos("/tmp/ttymap-test-config") < pos("/tmp/ttymap-test-data")); + assert!(pos("/tmp/ttymap-test-data") < pos("/usr/local/share/ttymap")); + assert!(pos("/usr/local/share/ttymap") < pos("/usr/share/ttymap")); + } + + #[test] + fn system_layers_are_offered_even_without_xdg_dirs() { + // `AppDirs::resolve()` can come back None (no HOME). A + // packaged install must still be reachable in that case. + let layers = candidate_layers(None); + assert!(layers.contains(&PathBuf::from("/usr/share/ttymap"))); + } + #[test] fn error_display_lists_candidates() { let err = RuntimePathError {