Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

refactor(cli): dedupe the config state --format flag; fix width-sentinel bugs (#3040)

Maximilian Roos4c2aeba95f70
diff --git a/src/cli/config.rs b/src/cli/config.rs
index 786a22a27..fe724a420 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -1,8 +1,25 @@
-use clap::Subcommand;
+use clap::{Args, Subcommand};
use super::SwitchFormat;
use crate::commands::Shell;
+/// Shared global `--format` flag for the `wt config state` subcommands whose
+/// action subcommands inherit it (`cache`, `logs`, `hints`, `ci-status`,
+/// `marker`).
+#[derive(Args)]
+pub struct GlobalFormatFlag {
+ /// Output format (text, json) [default: text]
+ #[arg(
+ long,
+ default_value = "text",
+ global = true,
+ hide_possible_values = true,
+ hide_default_value = true,
+ help_heading = "Output"
+ )]
+ pub format: SwitchFormat,
+}
+
// Ordering: primitive (init prints the code) → convenience (install writes
// it) → inverse (uninstall removes it), then unrelated utilities. Hidden
// commands last.
@@ -737,16 +754,8 @@ $ wt config state cache clear
#[command(subcommand)]
action: Option<CacheAction>,
- /// Output format (text, json) [default: text]
- #[arg(
- long,
- default_value = "text",
- global = true,
- hide_possible_values = true,
- hide_default_value = true,
- help_heading = "Output"
- )]
- format: SwitchFormat,
+ #[command(flatten)]
+ format: GlobalFormatFlag,
},
/// Default branch detection and override
@@ -890,16 +899,8 @@ $ wt config state logs clear
#[command(subcommand)]
action: Option<LogsAction>,
- /// Output format (text, json) [default: text]
- #[arg(
- long,
- default_value = "text",
- global = true,
- hide_possible_values = true,
- hide_default_value = true,
- help_heading = "Output"
- )]
- format: SwitchFormat,
+ #[command(flatten)]
+ format: GlobalFormatFlag,
},
/// One-time hints shown in this repo
@@ -929,16 +930,8 @@ $ wt config state hints clear NAME # re-show specific hint
#[command(subcommand)]
action: Option<HintsAction>,
- /// Output format (text, json) [default: text]
- #[arg(
- long,
- default_value = "text",
- global = true,
- hide_possible_values = true,
- hide_default_value = true,
- help_heading = "Output"
- )]
- format: SwitchFormat,
+ #[command(flatten)]
+ format: GlobalFormatFlag,
},
/// CI status cache
@@ -974,16 +967,8 @@ Without a subcommand, runs `get` for the current branch. Use `clear` to reset ca
#[command(subcommand)]
action: Option<CiStatusAction>,
- /// Output format (text, json) [default: text]
- #[arg(
- long,
- default_value = "text",
- global = true,
- hide_possible_values = true,
- hide_default_value = true,
- help_heading = "Output"
- )]
- format: SwitchFormat,
+ #[command(flatten)]
+ format: GlobalFormatFlag,
},
/// Branch markers
@@ -1019,16 +1004,8 @@ Without a subcommand, runs `get` for the current branch. For `--branch`, use `ge
#[command(subcommand)]
action: Option<MarkerAction>,
- /// Output format (text, json) [default: text]
- #[arg(
- long,
- default_value = "text",
- global = true,
- hide_possible_values = true,
- hide_default_value = true,
- help_heading = "Output"
- )]
- format: SwitchFormat,
+ #[command(flatten)]
+ format: GlobalFormatFlag,
},
/// \[experimental\] Custom variables per branch
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index a2d32d0b3..936bd6c73 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -6,8 +6,9 @@ mod step;
pub(crate) use config::{
ApprovalsCommand, CacheAction, CiStatusAction, ConfigAliasCommand, ConfigCommand,
ConfigPluginsClaudeCommand, ConfigPluginsCodexCommand, ConfigPluginsCommand,
- ConfigPluginsOpencodeCommand, ConfigShellCommand, DefaultBranchAction, HintsAction, LogsAction,
- MarkerAction, PreviousBranchAction, StateCommand, StateWrite, VarsAction,
+ ConfigPluginsOpencodeCommand, ConfigShellCommand, DefaultBranchAction, GlobalFormatFlag,
+ HintsAction, LogsAction, MarkerAction, PreviousBranchAction, StateCommand, StateWrite,
+ VarsAction,
};
pub(crate) use hook::{HOOK_TYPE_NAMES, HookCommand, HookOptions, parse_hook_type};
pub(crate) use list::ListSubcommand;
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index a00c9e72c..78ef8fc5a 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -178,17 +178,18 @@ pub(crate) fn force_serial_concurrent() -> bool {
/// * `range` - The commit range to diff (e.g., "HEAD~1..HEAD" or "main..HEAD")
pub(crate) fn show_diffstat(repo: &worktrunk::git::Repository, range: &str) -> anyhow::Result<()> {
let term_width = crate::display::terminal_width();
- let stat_width = term_width.saturating_sub(worktrunk::styling::GUTTER_OVERHEAD);
- let diff_stat = repo
- .run_command(&[
- "diff",
- "--color=always",
- "--stat",
- &format!("--stat-width={}", stat_width),
- range,
- ])?
- .trim_end()
- .to_string();
+ let mut args = vec!["diff", "--color=always", "--stat"];
+ // `terminal_width()` returns a `usize::MAX` sentinel when no width is
+ // detectable (no TTY, no COLUMNS); git mangles a sentinel-sized
+ // `--stat-width`, so omit the flag and let git use its default width.
+ let stat_width_arg;
+ if term_width != usize::MAX {
+ let stat_width = term_width.saturating_sub(worktrunk::styling::GUTTER_OVERHEAD);
+ stat_width_arg = format!("--stat-width={stat_width}");
+ args.push(&stat_width_arg);
+ }
+ args.push(range);
+ let diff_stat = repo.run_command(&args)?.trim_end().to_string();
if !diff_stat.is_empty() {
eprintln!("{}", format_with_gutter(&diff_stat, None));
diff --git a/src/help.rs b/src/help.rs
index e9ba05c43..bd37fa797 100644
--- a/src/help.rs
+++ b/src/help.rs
@@ -239,9 +239,15 @@ pub fn maybe_handle_help_with_pager(alias_help_context: Option<crate::commands::
// Render markdown sections (tables, code blocks, prose) with proper wrapping.
// Since we disabled clap's wrapping above, our renderer controls all line breaks.
+ // `terminal_width()` returns a `usize::MAX` sentinel when no
+ // width is detectable (no TTY, no COLUMNS); map it to `None`
+ // so the renderer uses its own defaults instead of e.g.
+ // repeating a rule character `usize::MAX` times.
let width = worktrunk::styling::terminal_width();
- let help =
- crate::md_help::render_markdown_in_help_with_width(&clap_output, Some(width));
+ let help = crate::md_help::render_markdown_in_help_with_width(
+ &clap_output,
+ (width != usize::MAX).then_some(width),
+ );
// show_help_in_pager checks if stdout or stderr is a TTY.
// If neither is a TTY (e.g., `wt --help &>file`), it skips the pager.
diff --git a/src/main.rs b/src/main.rs
index 7c1c642ec..181558243 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -68,9 +68,9 @@ use worktrunk::git::BranchDeletionMode;
use cli::{
ApprovalsCommand, CacheAction, CiStatusAction, Cli, Commands, ConfigAliasCommand,
ConfigCommand, ConfigPluginsClaudeCommand, ConfigPluginsCodexCommand, ConfigPluginsCommand,
- ConfigPluginsOpencodeCommand, ConfigShellCommand, DefaultBranchAction, HintsAction,
- HookCommand, HookOptions, ListArgs, ListSubcommand, LogsAction, MarkerAction, MergeArgs,
- PreviousBranchAction, RemoveArgs, StateCommand, StateWrite, StepCommand, SwitchArgs,
+ ConfigPluginsOpencodeCommand, ConfigShellCommand, DefaultBranchAction, GlobalFormatFlag,
+ HintsAction, HookCommand, HookOptions, ListArgs, ListSubcommand, LogsAction, MarkerAction,
+ MergeArgs, PreviousBranchAction, RemoveArgs, StateCommand, StateWrite, StepCommand, SwitchArgs,
SwitchFormat, VarsAction,
};
@@ -460,7 +460,10 @@ fn guard_format_on_write(action_name: &str, format: SwitchFormat) -> anyhow::Res
fn handle_state_command(action: StateCommand, yes: bool) -> anyhow::Result<()> {
match action {
- StateCommand::Cache { action, format } => {
+ StateCommand::Cache {
+ action,
+ format: GlobalFormatFlag { format },
+ } => {
if let Some(verb) = action.as_ref().and_then(StateWrite::write_verb) {
guard_format_on_write(verb, format)?;
}
@@ -492,7 +495,10 @@ fn handle_state_command(action: StateCommand, yes: bool) -> anyhow::Result<()> {
}
}
}
- StateCommand::CiStatus { action, format } => {
+ StateCommand::CiStatus {
+ action,
+ format: GlobalFormatFlag { format },
+ } => {
warn_state_subcommand_deprecated("ci-status");
if let Some(verb) = action.as_ref().and_then(StateWrite::write_verb) {
guard_format_on_write(verb, format)?;
@@ -507,7 +513,10 @@ fn handle_state_command(action: StateCommand, yes: bool) -> anyhow::Result<()> {
}
}
}
- StateCommand::Marker { action, format } => {
+ StateCommand::Marker {
+ action,
+ format: GlobalFormatFlag { format },
+ } => {
if let Some(verb) = action.as_ref().and_then(StateWrite::write_verb) {
guard_format_on_write(verb, format)?;
}
@@ -522,7 +531,10 @@ fn handle_state_command(action: StateCommand, yes: bool) -> anyhow::Result<()> {
}
}
}
- StateCommand::Logs { action, format } => {
+ StateCommand::Logs {
+ action,
+ format: GlobalFormatFlag { format },
+ } => {
if let Some(verb) = action.as_ref().and_then(StateWrite::write_verb) {
guard_format_on_write(verb, format)?;
}
@@ -531,7 +543,10 @@ fn handle_state_command(action: StateCommand, yes: bool) -> anyhow::Result<()> {
Some(LogsAction::Clear) => handle_state_clear("logs", None, false),
}
}
- StateCommand::Hints { action, format } => {
+ StateCommand::Hints {
+ action,
+ format: GlobalFormatFlag { format },
+ } => {
warn_state_subcommand_deprecated("hints");
if let Some(verb) = action.as_ref().and_then(StateWrite::write_verb) {
guard_format_on_write(verb, format)?;
diff --git a/tests/integration_tests/help.rs b/tests/integration_tests/help.rs
index a3c692540..b2621d2b3 100644
--- a/tests/integration_tests/help.rs
+++ b/tests/integration_tests/help.rs
@@ -227,6 +227,25 @@ fn test_help_list_narrow_terminal() {
});
}
+/// With no detectable width (piped output, no COLUMNS), `terminal_width()`
+/// returns its `usize::MAX` "don't truncate" sentinel. Help rendering must
+/// map that to "no width" rather than treating it as a real width —
+/// `wt list --help` used to panic with a capacity overflow trying to render
+/// a `---` rule `usize::MAX` characters wide.
+#[test]
+fn test_help_without_detectable_width() {
+ let mut cmd = wt_command();
+ cmd.env_remove("COLUMNS");
+ cmd.args(["list", "--help"]);
+ let output = cmd.output().expect("failed to run command");
+ assert!(
+ output.status.success(),
+ "wt list --help without COLUMNS failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(!output.stdout.is_empty(), "help output should not be empty");
+}
+
/// Tests --help-description outputs the meta description for docs frontmatter.
#[rstest]
#[case("switch", "Switch to a worktree; create if needed.")]
diff --git a/tests/integration_tests/push.rs b/tests/integration_tests/push.rs
index 16555c086..d15d71d7b 100644
--- a/tests/integration_tests/push.rs
+++ b/tests/integration_tests/push.rs
@@ -30,6 +30,32 @@ fn test_push_fast_forward(mut repo: TestRepo) {
snapshot_push("push_fast_forward", &repo, &["main"], Some(&feature_wt));
}
+/// With no detectable width (piped output, no COLUMNS), the diffstat omits
+/// `--stat-width` instead of passing `terminal_width()`'s `usize::MAX`
+/// sentinel to git, which used to make git truncate filenames to ~10 chars.
+#[rstest]
+fn test_push_diffstat_without_detectable_width(mut repo: TestRepo) {
+ repo.add_main_worktree();
+ let feature_wt = repo.add_worktree_with_commit(
+ "feature",
+ "a-reasonably-long-filename.txt",
+ "test content",
+ "Add test file",
+ );
+
+ let mut cmd = repo.wt_command();
+ cmd.args(["step", "push", "main"])
+ .current_dir(&feature_wt)
+ .env_remove("COLUMNS");
+ let output = cmd.output().expect("failed to run command");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(output.status.success(), "push failed: {stderr}");
+ assert!(
+ stderr.contains("a-reasonably-long-filename.txt"),
+ "diffstat should show the full filename, got: {stderr}"
+ );
+}
+
#[rstest]
fn test_push_not_fast_forward(mut repo: TestRepo) {
// Create commits in both worktrees