Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: ignore an empty or relative XDG_*_HOME across every XDG base-directory read (#4104)
Worktrunk Bot3f91d5f2d13e
diff --git a/src/commands/config/opencode.rs b/src/commands/config/opencode.rsindex b64c153f1..352f182e4 100644--- a/src/commands/config/opencode.rs+++ b/src/commands/config/opencode.rs@@ -10,6 +10,7 @@use std::path::PathBuf;use anyhow::{Context, Result};+use etcetera::base_strategy::{BaseStrategy, Xdg};/// The plugin source, embedded at compile time.const PLUGIN_SOURCE: &str = include_str!("../../../dev/opencode-plugin.ts");@@ -22,25 +23,25 @@ const PLUGIN_SOURCE: &str = include_str!("../../../dev/opencode-plugin.ts");/// not where OpenCode looks for user plugins, so we deliberately avoid `dirs::config_dir()`/// here — it would put the plugin in the wrong place on macOS.///-/// Both overrides read an exported-but-empty value as unset, matching+/// `OPENCODE_CONFIG_DIR` reads an exported-but-empty value as unset, matching/// `CLAUDE_CONFIG_DIR` in `config::show` and `PI_CONFIG_DIR` in `config::pi`./// An empty value taken at face value yields the relative path `plugins/`, so/// the install writes the plugin into whatever directory `wt` was run from.+///+/// The two lower rungs are etcetera's XDG strategy — `$XDG_CONFIG_HOME` when+/// absolute, `~/.config` otherwise — which rules out the same mistake for that+/// variable. `Xdg` rather than `choose_base_strategy` keeps `~/.config` on+/// Windows too, for the same reason the macOS path is avoided above.fn opencode_plugins_dir() -> Result<PathBuf> {let config_dir = if let Some(dir) = std::env::var("OPENCODE_CONFIG_DIR").ok().filter(|s| !s.is_empty()){PathBuf::from(dir)- } else if let Some(xdg) = std::env::var("XDG_CONFIG_HOME")- .ok()- .filter(|s| !s.is_empty())- {- PathBuf::from(xdg).join("opencode")} else {- worktrunk::path::home_dir()+ Xdg::new().context("Could not determine home directory")?- .join(".config")+ .config_dir().join("opencode")};Ok(config_dir.join("plugins"))diff --git a/src/git/remote_ref/gitea.rs b/src/git/remote_ref/gitea.rsindex 2c025c18b..f43c4c7fb 100644--- a/src/git/remote_ref/gitea.rs+++ b/src/git/remote_ref/gitea.rs@@ -32,6 +32,7 @@//! resolves its own context.use anyhow::{Context, bail};+use etcetera::base_strategy::{BaseStrategy, Xdg};use serde::Deserialize;use super::{@@ -369,27 +370,28 @@ fn content_has_any_login(content: &str) -> bool {/// Read tea's config.yml, honoring `$XDG_CONFIG_HOME` and the legacy/// `~/.tea/tea.yml` fallback. Returns None if neither file is readable.+///+/// The base directory comes from etcetera's XDG strategy — the crate worktrunk+/// already resolves its own config with — so the spec's exclusions apply: an+/// exported-but-empty or relative value falls back to `~/.config` instead of+/// resolving `tea/config.yml` against whatever directory `wt` was invoked+/// from, which would leave the user's tea logins unread and silently drop the+/// Gitea CI column from `wt list --full` and send `wt switch pr:<n>` to GitHub.+///+/// `Xdg` specifically, not `choose_base_strategy`: tea honors `$XDG_CONFIG_HOME`+/// on every platform and this keeps that. Its *default* is+/// `github.com/adrg/xdg`'s — `~/Library/Application Support` on macOS,+/// `%LOCALAPPDATA%` on Windows, `~/.config` elsewhere — so only the Linux+/// default is matched here; `choose_base_strategy` would pick+/// `~/Library/Preferences` and `%APPDATA%`, matching tea on neither.fn read_tea_config() -> Option<String> {- let xdg = std::env::var_os("XDG_CONFIG_HOME").map(std::path::PathBuf::from);- let home = crate::path::home_dir();-- let primary = xdg- .clone()- .or_else(|| home.as_ref().map(|h| h.join(".config")))- .map(|base| base.join("tea").join("config.yml"));- if let Some(path) = primary- && let Ok(content) = std::fs::read_to_string(&path)- {- return Some(content);- }-- let legacy = home.map(|h| h.join(".tea").join("tea.yml"));- if let Some(path) = legacy- && let Ok(content) = std::fs::read_to_string(&path)- {- return Some(content);- }- None+ let xdg = Xdg::new().ok()?;+ [+ xdg.config_dir().join("tea").join("config.yml"),+ xdg.home_dir().join(".tea").join("tea.yml"),+ ]+ .into_iter()+ .find_map(|path| std::fs::read_to_string(path).ok())}#[cfg(test)]diff --git a/src/shell/paths.rs b/src/shell/paths.rsindex da9342e48..21f1ca7f5 100644--- a/src/shell/paths.rs+++ b/src/shell/paths.rs@@ -94,16 +94,22 @@ fn nu_dirs() -> NuDirs {/// Fallback for Nushell's `$nu.data-dir` when `nu` can't be queried.///-/// Mirrors `nu_path::data_dir`: `XDG_DATA_HOME` (when absolute) wins on every-/// platform, otherwise `dirs::data_dir()` (`~/Library/Application Support` on-/// macOS, `%APPDATA%` on Windows, `~/.local/share` on Linux). Nushell appends-/// `nushell`.+/// Mirrors Nushell's own `resolve_xdg_base` (`crates/nu-config/src/resolve.rs`):+/// `XDG_DATA_HOME` wins on every platform when it is absolute, otherwise+/// `dirs::data_dir()` (`~/Library/Application Support` on macOS, `%APPDATA%` on+/// Windows, `~/.local/share` on Linux). Nushell appends `nushell`.+///+/// The one XDG read worktrunk still spells out, because it is Nushell's rule+/// rather than the spec's: etcetera's `Xdg::data_dir()` applies the same+/// absolute-only filter but falls back to `~/.local/share` everywhere, which is+/// the wrong directory on macOS and Windows, and the native strategies that get+/// those right ignore `XDG_DATA_HOME`.fn nushell_data_dir_fallback(home: &std::path::Path) -> PathBuf {- if let Ok(xdg) = std::env::var("XDG_DATA_HOME") {- let path = PathBuf::from(xdg);- if path.is_absolute() {- return path.join("nushell");- }+ if let Some(xdg) = std::env::var_os("XDG_DATA_HOME")+ .map(PathBuf::from)+ .filter(|path| path.is_absolute())+ {+ return xdg.join("nushell");}dirs::data_dir().unwrap_or_else(|| home.join(".local").join("share"))@@ -141,8 +147,11 @@ fn legacy_nushell_autoload_dirs(if let Some(dir) = default_config {dirs.push(dir.to_path_buf());}- if let Ok(xdg_config) = std::env::var("XDG_CONFIG_HOME") {- dirs.push(PathBuf::from(xdg_config).join("nushell"));+ // etcetera's XDG strategy: `$XDG_CONFIG_HOME` when absolute, `~/.config`+ // otherwise. `~/.config` stays listed on its own because an absolute+ // `$XDG_CONFIG_HOME` displaces it, and older worktrunk wrote there too.+ if let Ok(xdg) = Xdg::new() {+ dirs.push(xdg.config_dir().join("nushell"));}dirs.push(home.join(".config").join("nushell"));if let Ok(strategy) = choose_base_strategy() {diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex 32d67c34d..02352acf2 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -2757,6 +2757,55 @@ fn test_opencode_install_treats_empty_config_dir_as_unset(temp_home: TempDir) {);}+/// A relative `$XDG_CONFIG_HOME` is ignored, as the XDG base directory spec+/// requires, rather than resolved against the invocation directory.+///+/// Regression guard for the same shape as the empty `OPENCODE_CONFIG_DIR`+/// above, one rung down the precedence: `$XDG_CONFIG_HOME` filtered only the+/// empty string, so `XDG_CONFIG_HOME=relative-config` made the install target+/// `relative-config/opencode/plugins/worktrunk.ts` — written under whatever+/// directory `wt` was run from, and read back from there by+/// `is_plugin_installed()`, so the install reported success while OpenCode+/// never saw the plugin.+///+/// Out-of-process, so `.env()` sets the child's environment and this races+/// nothing else in the binary.+#[rstest]+fn test_opencode_install_ignores_relative_xdg_config_home(temp_home: TempDir) {+ let run_dir = temp_home.path().join("run-from-here");+ fs::create_dir_all(&run_dir).unwrap();++ let mut cmd = wt_command();+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env_remove("OPENCODE_CONFIG_DIR");+ cmd.env("XDG_CONFIG_HOME", "relative-config");+ cmd.current_dir(&run_dir);+ cmd.args(["config", "plugins", "opencode", "install", "--yes"]);++ let output = cmd.output().expect("install command should run");+ assert!(+ output.status.success(),+ "install failed: stdout={}, stderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let canonical_home =+ crate::common::canonicalize(temp_home.path()).unwrap_or_else(|_| temp_home.path().into());+ // The relative value is discarded, so the `$HOME/.config/opencode` default+ // applies — the same target the unset case reaches.+ let plugin_path = canonical_home.join(".config/opencode/plugins/worktrunk.ts");+ assert!(+ plugin_path.exists(),+ "Plugin should fall through to $HOME/.config, but not found at: {}",+ plugin_path.display(),+ );+ assert!(+ !run_dir.join("relative-config").exists(),+ "Plugin must not be written relative to the invocation directory"+ );+}+/// Install prompt declined (no `--yes`, piped stdin → empty → declined)./// Exercises the `return Ok(())` branch at lines 83-84 of opencode.rs.#[rstest]diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rsindex 863911643..3f0ca59d0 100644--- a/tests/integration_tests/configure_shell.rs+++ b/tests/integration_tests/configure_shell.rs@@ -2925,6 +2925,68 @@ fn test_uninstall_nushell_cleans_all_candidate_locations(repo: TestRepo, temp_ho);}+/// Uninstall finds a wrapper under `$XDG_DATA_HOME`, the data-dir candidate+/// `nushell_data_dir_fallback` derives when `nu` can't be queried.+///+/// An absolute `XDG_DATA_HOME` wins over `dirs::data_dir()` on every platform,+/// matching `nu_path::data_dir`. Only macOS and Windows discriminate: `dirs`+/// reads the variable itself on Linux, so there the assertion holds with or+/// without `nushell_data_dir_fallback`'s own branch, while on macOS it+/// separates `$XDG_DATA_HOME` from `~/Library/Application Support`.+#[rstest]+fn test_uninstall_nushell_finds_wrapper_under_xdg_data_home(repo: TestRepo, temp_home: TempDir) {+ let home = canonical_temp_home(&temp_home);+ // Distinct from the pinned canonical dir, so the stranded wrapper can only+ // be found by way of the data-dir candidate.+ let xdg_data = home.join("xdg-data");+ let canonical_dir = home.join(".local/share/nushell/vendor/autoload");+ let canonical = canonical_dir.join("wt.nu");++ let configure = |cmd: &mut std::process::Command| {+ repo.configure_wt_cmd(cmd);+ set_temp_home_env(cmd, temp_home.path());+ cmd.env("XDG_DATA_HOME", &xdg_data);+ cmd.env("WORKTRUNK_TEST_NU_VENDOR_AUTOLOAD_DIR", &canonical_dir);+ cmd.env("SHELL", "/bin/nu");+ };++ // Install to the pinned canonical dir, then strand a copy under+ // `$XDG_DATA_HOME` — the shape an older worktrunk, or a `nu` that was+ // queryable at install time and isn't now, leaves behind.+ let mut install_cmd = wt_command();+ configure(&mut install_cmd);+ install_cmd+ .args(["config", "shell", "install", "nu", "--yes"])+ .current_dir(repo.root_path());+ let install_output = install_cmd.output().expect("Failed to execute install");+ assert!(+ install_output.status.success(),+ "Install should succeed:\nstderr: {}",+ String::from_utf8_lossy(&install_output.stderr)+ );++ let stranded_dir = xdg_data.join("nushell/vendor/autoload");+ fs::create_dir_all(&stranded_dir).unwrap();+ let stranded = stranded_dir.join("wt.nu");+ fs::copy(&canonical, &stranded).unwrap();++ let mut cmd = wt_command();+ configure(&mut cmd);+ cmd.args(["config", "shell", "uninstall", "nu", "--yes"])+ .current_dir(repo.root_path());+ let output = cmd.output().expect("Failed to execute uninstall");+ assert!(+ output.status.success(),+ "Uninstall should succeed:\nstderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ assert!(+ !stranded.exists(),+ "Wrapper under $XDG_DATA_HOME should be deleted: {stranded:?}"+ );+}+/// Test that WORKTRUNK_TEST_POWERSHELL_ENV=1 triggers PowerShell auto-detection./// This simulates the Windows behavior where we detect PowerShell when SHELL is not set.#[rstest]