Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: argv panic, format-flag, state-write enforcement, deprecated-config preservation (#2788)
Maximilian Roos5cbc5b461490
diff --git a/src/cli/config.rs b/src/cli/config.rsindex 590291e5a..47aa7203c 100644--- a/src/cli/config.rs+++ b/src/cli/config.rs@@ -1288,6 +1288,59 @@ $ wt config state hints clear worktree-path},}+/// Write-ness of a state action, co-located with the action enums so a new+/// variant cannot be added without classifying it.+///+/// `--format` is `global = true` on the state-cache parents so the bareword and+/// `get` read forms accept it; clap therefore also accepts it on write actions,+/// where it has no effect. The dispatcher guards against that+/// (`guard_format_on_write`). Deriving the verb from this trait — rather than+/// hand-placing the guard at each write arm — means the exhaustive match below+/// fails to compile until a newly added write variant declares itself, so a+/// write action can't silently bypass the guard.+pub(crate) trait StateWrite {+ /// `Some(verb)` for write actions (verb names the action in the conflict+ /// error); `None` for reads.+ fn write_verb(&self) -> Option<&'static str>;+}++impl StateWrite for CiStatusAction {+ fn write_verb(&self) -> Option<&'static str> {+ match self {+ Self::Get { .. } => None,+ Self::Clear { .. } => Some("clear"),+ }+ }+}++impl StateWrite for MarkerAction {+ fn write_verb(&self) -> Option<&'static str> {+ match self {+ Self::Get { .. } => None,+ Self::Set { .. } => Some("set"),+ Self::Clear { .. } => Some("clear"),+ }+ }+}++impl StateWrite for LogsAction {+ fn write_verb(&self) -> Option<&'static str> {+ match self {+ Self::Get => None,+ Self::Clear => Some("clear"),+ }+ }+}++impl StateWrite for HintsAction {+ fn write_verb(&self) -> Option<&'static str> {+ match self {+ Self::Get => None,+ Self::Clear { .. } => Some("clear"),+ }+ }+}+// Ordering: reads before writes — get, list, set, clear.#[derive(Subcommand)]pub enum VarsAction {diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 4705eddb0..8bc7a4995 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -7,7 +7,7 @@ pub(crate) use config::{ApprovalsCommand, CiStatusAction, ConfigAliasCommand, ConfigCommand,ConfigPluginsClaudeCommand, ConfigPluginsCodexCommand, ConfigPluginsCommand,ConfigPluginsOpencodeCommand, ConfigShellCommand, DefaultBranchAction, HintsAction, LogsAction,- MarkerAction, PreviousBranchAction, StateCommand, VarsAction,+ MarkerAction, PreviousBranchAction, StateCommand, StateWrite, VarsAction,};pub(crate) use hook::{HOOK_TYPE_NAMES, HookCommand, HookOptions};pub(crate) use list::ListSubcommand;diff --git a/src/config/deprecation.rs b/src/config/deprecation.rsindex 0ad79103d..c5cfd89a0 100644--- a/src/config/deprecation.rs+++ b/src/config/deprecation.rs@@ -445,6 +445,14 @@ fn is_table_like(item: &toml_edit::Item) -> bool {)}+/// Whether a slot can host a freshly-inserted subtable: absent, or already a+/// (possibly inline) table. A scalar/array occupant blocks insertion — the+/// migration would remove the deprecated source but have nowhere to put+/// `[parent.child]`, silently dropping the user's data.+fn can_host_subtable(item: Option<&toml_edit::Item>) -> bool {+ item.is_none_or(is_table_like)+}+/// Convert a table-like TOML item into a `Table`. Returns `None` for other shapes.fn into_table(item: toml_edit::Item) -> Option<toml_edit::Table> {match item {@@ -470,8 +478,12 @@ fn migrate_commit_generation_doc(doc: &mut toml_edit::DocumentMut) -> bool {// Handle both regular tables and inline tables. Peek before removing so a// malformed value (e.g., a bare string) is left in place rather than// silently dropped when a sibling migration also serializes the doc.+ // Also require `commit` be absent or a table — a scalar `commit = "x"`+ // blocks insertion of `[commit.generation]`; removing the source then+ // would silently drop the deprecated section.if !has_new_section&& doc.get("commit-generation").is_some_and(is_table_like)+ && can_host_subtable(doc.get("commit"))&& let Some(old_section) = doc.remove("commit-generation"){let mut table = into_table(old_section).expect("checked is_table_like above");@@ -508,10 +520,12 @@ fn migrate_commit_generation_doc(doc: &mut toml_edit::DocumentMut) -> bool {.is_some_and(|g| g.is_table() || g.is_inline_table());// Peek before removing so a malformed value is preserved.+ // Same scalar-parent guard as the top-level case above.if !has_new_project_section&& project_table.get("commit-generation").is_some_and(is_table_like)+ && can_host_subtable(project_table.get("commit"))&& let Some(old_section) = project_table.remove("commit-generation"){let mut table = into_table(old_section).expect("checked is_table_like above");@@ -715,6 +729,12 @@ fn migrate_select_table(table: &mut toml_edit::Table, modified: &mut bool) {return;}+ // A scalar `switch = "x"` blocks insertion of `[switch.picker]`; removing+ // `select` then would silently drop the user's picker config.+ if !can_host_subtable(table.get("switch")) {+ return;+ }+let select_table =into_table(table.remove("select").unwrap()).expect("checked is_table_like above");@@ -1144,8 +1164,13 @@ pub fn copy_approved_commands_to_approvals_file(/// - `command` is missing or not a string/// - `args` is not an arrayfn merge_args_into_command(table: &mut toml_edit::Table) {- // Validate preconditions before removing args- let can_merge = table.get("args").is_some_and(|a| a.as_array().is_some())+ // Validate preconditions before removing args. Every element must be a+ // string — a single non-string (e.g. `args = [1, "--ok"]`) would otherwise+ // be silently filtered out while `args` was removed, dropping user data.+ let can_merge = table+ .get("args")+ .and_then(|a| a.as_array())+ .is_some_and(|a| a.iter().all(|v| v.as_str().is_some()))&& table.get("command").and_then(|c| c.as_value())@@ -1164,7 +1189,8 @@ fn merge_args_into_command(table: &mut toml_edit::Table) {.unwrap();let cmd_str = command.as_str().unwrap();- // Filter to string args only (non-strings are dropped)+ // `can_merge` guarantees every element is a string; `filter_map` here just+ // extracts them.let args_str: Vec<&str> = args_array.iter().filter_map(|a| a.as_str()).collect();if !args_str.is_empty() {// Only add space if command is non-empty@@ -2712,6 +2738,91 @@ no-ff = true);}+ /// Scalar `commit = "x"` blocks `[commit.generation]` insertion. The+ /// migration must NOT remove `[commit-generation]` — doing so previously+ /// dropped the section since the new key could not be written under a+ /// scalar parent.+ #[test]+ fn test_commit_generation_preserved_when_commit_is_scalar() {+ let content = r#"commit = "x"++[commit-generation]+template = "tpl"++[merge]+no-ff = true+"#;+ let result = migrate_content(content);+ assert!(+ result.contains("[commit-generation]") && result.contains(r#"template = "tpl""#),+ "[commit-generation] must survive when scalar `commit` blocks the new key; got:\n{result}"+ );+ // Source must still be the scalar — nothing inserted under it.+ assert!(+ result.contains(r#"commit = "x""#),+ "scalar `commit` must be preserved unchanged; got:\n{result}"+ );+ // Sibling migration still applies.+ assert!(+ result.contains("ff = false"),+ "merge.no-ff should have migrated; got:\n{result}"+ );+ }++ /// Same shape for `[select]` when `switch = "x"` is scalar.+ #[test]+ fn test_select_preserved_when_switch_is_scalar() {+ let content = r#"switch = "x"++[select]+preview = "p"++[merge]+no-ff = true+"#;+ let result = migrate_content(content);+ assert!(+ result.contains("[select]") && result.contains(r#"preview = "p""#),+ "[select] must survive when scalar `switch` blocks the new key; got:\n{result}"+ );+ assert!(+ result.contains(r#"switch = "x""#),+ "scalar `switch` must be preserved unchanged; got:\n{result}"+ );+ assert!(+ result.contains("ff = false"),+ "merge.no-ff should have migrated; got:\n{result}"+ );+ }++ /// `args = [1, "--ok"]`: a single non-string element would previously be+ /// filtered out while `args` was removed, dropping user data. The whole+ /// `args` array must be preserved unchanged when any element isn't a+ /// string.+ #[test]+ fn test_commit_generation_args_preserved_when_non_string_element() {+ let content = r#"[commit-generation]+command = "echo"+args = [1, "--ok"]+"#;+ let result = migrate_content(content);+ // Section migrated to [commit.generation], but `args` preserved+ // because it contains a non-string element.+ assert!(+ result.contains("[commit.generation]"),+ "section should still migrate; got:\n{result}"+ );+ assert!(+ result.contains("args = [1, \"--ok\"]") || result.contains("args = [ 1, \"--ok\" ]"),+ "args must be preserved unchanged when any element is non-string; got:\n{result}"+ );+ // command must NOT have been mutated to include the partial join.+ assert!(+ result.contains(r#"command = "echo""#),+ "command must not be mutated when args is preserved; got:\n{result}"+ );+ }+/// `[ci]` migration only owns `platform`; other keys in the same section/// must be preserved, not dropped along with the section.#[test]diff --git a/src/help.rs b/src/help.rsindex b5933f38d..ad6b67e2e 100644--- a/src/help.rs+++ b/src/help.rs@@ -45,6 +45,7 @@//! which strips Zola syntax (terminal shortcodes, badge `<span>` → `[experimental]`)//! for plain-markdown consumption.+use std::ffi::OsString;use std::process;use ansi_str::AnsiStr;@@ -159,7 +160,11 @@ impl PageMode {/// spliced into the rendered output — at the top level for `wt --help`, or/// under the Aliases section for `wt step --help`.pub fn maybe_handle_help_with_pager(alias_help_context: Option<crate::commands::HelpContext>) {- let args: Vec<String> = std::env::args().collect();+ let args_os: Vec<OsString> = std::env::args_os().collect();+ let args: Vec<String> = args_os+ .iter()+ .map(|arg| arg.to_string_lossy().into_owned())+ .collect();// --help uses pager, -h prints directly (git convention)let use_pager = args.iter().any(|a| a == "--help");@@ -216,7 +221,7 @@ pub fn maybe_handle_help_with_pager(alias_help_context: Option<crate::commands::cmd = crate::completion::inject_hook_subcommands(cmd);cmd = cmd.color(clap::ColorChoice::Always); // Force clap to emit ANSI codes- if let Err(err) = cmd.try_get_matches_from_mut(&args) {+ if let Err(err) = cmd.try_get_matches_from_mut(args_os) {match err.kind() {ErrorKind::DisplayHelp | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand => {// err.render() returns a StyledStr containing ANSI codes.diff --git a/src/invocation.rs b/src/invocation.rsindex 17d6b1a8a..25f01877f 100644--- a/src/invocation.rs+++ b/src/invocation.rs@@ -11,7 +11,7 @@/// When invoked as `git-wt`, returns "git-wt"; when invoked as `wt`, returns "wt"./// On Windows, strips `.exe` extension — users should use `wt` not `wt.exe` in aliases.pub fn binary_name() -> String {- std::env::args()+ std::env::args_os().next().and_then(|arg0| {std::path::Path::new(&arg0)@@ -40,9 +40,9 @@ pub fn is_git_subcommand() -> bool {/// Returns the full invocation path (e.g., `target/debug/wt`, `./wt`, `wt`)./// Backslashes are normalized to forward slashes on Windows for consistent display.pub fn invocation_path() -> String {- std::env::args()+ std::env::args_os().next()- .map(|s| s.replace('\\', "/"))+ .map(|s| s.to_string_lossy().replace('\\', "/")).unwrap_or_else(|| "wt".to_string())}@@ -105,8 +105,11 @@ pub fn invocation_path() -> String {/// The argv\[0\] heuristic is simple, fast, and catches all cases where shell/// integration won't work because the shell wrapper wasn't invoked.pub fn was_invoked_with_explicit_path() -> bool {- std::env::args()+ std::env::args_os().next()- .map(|arg0| arg0.contains('/') || arg0.contains('\\'))+ .map(|arg0| {+ let arg0 = arg0.to_string_lossy();+ arg0.contains('/') || arg0.contains('\\')+ }).unwrap_or(false)}diff --git a/src/main.rs b/src/main.rsindex ffc6c523b..76b165811 100644--- a/src/main.rs+++ b/src/main.rs@@ -70,8 +70,8 @@ use cli::{ConfigPluginsClaudeCommand, ConfigPluginsCodexCommand, ConfigPluginsCommand,ConfigPluginsOpencodeCommand, ConfigShellCommand, DefaultBranchAction, HintsAction,HookCommand, HookOptions, ListArgs, ListSubcommand, LogsAction, MarkerAction, MergeArgs,- PreviousBranchAction, RemoveArgs, StateCommand, StepCommand, SwitchArgs, SwitchFormat,- VarsAction,+ PreviousBranchAction, RemoveArgs, StateCommand, StateWrite, StepCommand, SwitchArgs,+ SwitchFormat, VarsAction,};/// Render a clap error to stderr, appending a wt-specific nested-subcommand@@ -416,7 +416,7 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {}}-/// Exit with a clap-style `ArgumentConflict` error when `--format` is combined+/// Return a clap-style `ArgumentConflict` error when `--format` is combined/// with a write action (set/clear) on the state subcommands where it has no/// effect. Clap accepts the flag because `--format` is declared `global = true`/// on the parent so the bareword and `get` forms work, but write actions don't@@ -425,9 +425,9 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {/// Populates `InvalidArg` / `PriorArg` context rather than passing a raw/// message so clap renders the arg name and subcommand with its own `invalid`/// style, matching native conflict errors byte-for-byte.-fn guard_format_on_write(action_name: &str, format: SwitchFormat) {+fn guard_format_on_write(action_name: &str, format: SwitchFormat) -> anyhow::Result<()> {if format == SwitchFormat::Text {- return;+ return Ok(());}let mut cmd = cli::build_command();let usage = cmd.render_usage();@@ -444,7 +444,7 @@ fn guard_format_on_write(action_name: &str, format: SwitchFormat) {clap::error::ContextKind::Usage,clap::error::ContextValue::StyledStr(usage),);- err.exit()+ Err(enhance_clap_error(err))}fn handle_state_command(action: StateCommand) -> anyhow::Result<()> {@@ -467,40 +467,53 @@ fn handle_state_command(action: StateCommand) -> anyhow::Result<()> {}Some(PreviousBranchAction::Clear) => handle_state_clear("previous-branch", None, false),},- StateCommand::CiStatus { action, format } => match action {- Some(CiStatusAction::Get { branch }) => handle_state_get("ci-status", branch, format),- None => handle_state_get("ci-status", None, format),- Some(CiStatusAction::Clear { branch, all }) => {- guard_format_on_write("clear", format);- handle_state_clear("ci-status", branch, all)+ StateCommand::CiStatus { action, format } => {+ if let Some(verb) = action.as_ref().and_then(StateWrite::write_verb) {+ guard_format_on_write(verb, format)?;}- },- StateCommand::Marker { action, format } => match action {- Some(MarkerAction::Get { branch }) => handle_state_get("marker", branch, format),- None => handle_state_get("marker", None, format),- Some(MarkerAction::Set { value, branch }) => {- guard_format_on_write("set", format);- handle_state_set("marker", value, branch)+ match action {+ Some(CiStatusAction::Get { branch }) => {+ handle_state_get("ci-status", branch, format)+ }+ None => handle_state_get("ci-status", None, format),+ Some(CiStatusAction::Clear { branch, all }) => {+ handle_state_clear("ci-status", branch, all)+ }}- Some(MarkerAction::Clear { branch, all }) => {- guard_format_on_write("clear", format);- handle_state_clear("marker", branch, all)+ }+ StateCommand::Marker { action, format } => {+ if let Some(verb) = action.as_ref().and_then(StateWrite::write_verb) {+ guard_format_on_write(verb, format)?;}- },- StateCommand::Logs { action, format } => match action {- Some(LogsAction::Get) | None => handle_logs_list(format),- Some(LogsAction::Clear) => {- guard_format_on_write("clear", format);- handle_state_clear("logs", None, false)+ match action {+ Some(MarkerAction::Get { branch }) => handle_state_get("marker", branch, format),+ None => handle_state_get("marker", None, format),+ Some(MarkerAction::Set { value, branch }) => {+ handle_state_set("marker", value, branch)+ }+ Some(MarkerAction::Clear { branch, all }) => {+ handle_state_clear("marker", branch, all)+ }}- },- StateCommand::Hints { action, format } => match action {- Some(HintsAction::Get) | None => handle_hints_get(format),- Some(HintsAction::Clear { name }) => {- guard_format_on_write("clear", format);- handle_hints_clear(name)+ }+ StateCommand::Logs { action, format } => {+ if let Some(verb) = action.as_ref().and_then(StateWrite::write_verb) {+ guard_format_on_write(verb, format)?;}- },+ match action {+ Some(LogsAction::Get) | None => handle_logs_list(format),+ Some(LogsAction::Clear) => handle_state_clear("logs", None, false),+ }+ }+ StateCommand::Hints { action, format } => {+ if let Some(verb) = action.as_ref().and_then(StateWrite::write_verb) {+ guard_format_on_write(verb, format)?;+ }+ match action {+ Some(HintsAction::Get) | None => handle_hints_get(format),+ Some(HintsAction::Clear { name }) => handle_hints_clear(name),+ }+ }StateCommand::Vars { action } => match action {VarsAction::Get { key, branch } => handle_vars_get(&key, branch),VarsAction::Set {@@ -1595,7 +1608,10 @@ fn main() {// on-demand callers unchanged.Repository::prewarm();- let command_line = std::env::args().collect::<Vec<_>>().join(" ");+ let command_line = std::env::args_os()+ .map(|arg| arg.to_string_lossy().into_owned())+ .collect::<Vec<_>>()+ .join(" ");{let _span = worktrunk::trace::Span::new("init_command_log");init_command_log(&command_line);diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rsindex 88289a9e7..efe703fd2 100644--- a/tests/integration_tests/config_state.rs+++ b/tests/integration_tests/config_state.rs@@ -2341,3 +2341,37 @@ fn test_format_rejected_on_write_actions();}}++#[rstest]+fn test_format_rejected_on_write_action_writes_verbose_diagnostic(repo: TestRepo) {+ let output = repo+ .wt_command()+ .args([+ "-vv",+ "config",+ "state",+ "marker",+ "set",+ "foo",+ "--format=json",+ ])+ .output()+ .unwrap();++ assert_eq!(output.status.code(), Some(2));+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("--format <FORMAT>"),+ "stderr should include the clap conflict: {stderr}"+ );+ assert!(+ stderr.contains("Diagnostic saved"),+ "stderr should mention the verbose diagnostic: {stderr}"+ );++ let diagnostic_path = repo.root_path().join(".git/wt/logs/diagnostic.md");+ assert!(+ diagnostic_path.exists(),+ "diagnostic should be written for post-dispatch clap errors"+ );+}diff --git a/tests/integration_tests/custom.rs b/tests/integration_tests/custom.rsindex d348d7f1c..da3617446 100644--- a/tests/integration_tests/custom.rs+++ b/tests/integration_tests/custom.rs@@ -54,6 +54,34 @@ fn custom_subcommand_runs_wt_prefixed_binary_on_path() {assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "custom ran");}+#[cfg(unix)]+#[test]+fn custom_subcommand_accepts_non_utf8_forwarded_arg() {+ use std::ffi::OsString;+ use std::os::unix::ffi::OsStringExt;+ use std::os::unix::fs::PermissionsExt;++ let dir = TempDir::new().unwrap();+ let script = dir.path().join("wt-wt-test-extcmd-raw");+ std::fs::write(&script, "#!/bin/sh\nprintf 'custom ran\\n'\n").unwrap();+ let mut perms = std::fs::metadata(&script).unwrap().permissions();+ perms.set_mode(0o755);+ std::fs::set_permissions(&script, perms).unwrap();++ let mut cmd = wt_command();+ prepend_path(&mut cmd, dir.path());+ cmd.arg("wt-test-extcmd-raw")+ .arg(OsString::from_vec(vec![0xff]));++ let output = cmd.output().expect("failed to run wt");+ assert!(+ output.status.success(),+ "expected success, stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "custom ran");+}+#[test]fn custom_subcommand_not_found_prints_clap_error() {let mut cmd = wt_command();