Skip to content

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

feat(list): Implement progressive rendering with aligned columns and enhanced status display

Maximilian Roos2b1ae78a9b43
diff --git a/CLAUDE.md b/CLAUDE.md
index 3b96e9d31..3a3e92376 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -325,6 +325,24 @@ output::gutter(format_with_gutter(&log, "", None))?;
output::progress(format!("{CYAN}Merging...{CYAN:#}\n"))?;
```
+### Table Column Alignment
+
+**Principle: Headers and values align consistently within each column type.**
+
+Column alignment follows standard tabular data conventions:
+
+1. **Text columns** (Branch, Path, Message, Commit):
+ - Headers: Left-aligned
+ - Values: Left-aligned
+
+2. **Diff/numeric columns** (HEAD±, main↕, main…±, Remote⇅):
+ - Headers: Right-aligned
+ - Values: Right-aligned
+
+**Why:** Right-aligning numeric data allows visual scanning by magnitude (rightmost digits align vertically). Left-aligning text data prioritizes readability from the start. Matching header and value alignment within each column creates a consistent visual grid.
+
+**Implementation:** Headers are positioned within their column width using the same alignment strategy as their values (render.rs).
+
### Snapshot Testing Requirement
Every command output must have a snapshot test (`tests/integration_tests/`). Use this pattern:
diff --git a/Cargo.lock b/Cargo.lock
index ab7c57710..02738d841 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -58,22 +58,22 @@ dependencies = [
[[package]]
name = "anstyle-query"
-version = "1.1.4"
+version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2"
+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
name = "anstyle-wincon"
-version = "3.0.10"
+version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a"
+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -148,12 +148,6 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
-[[package]]
-name = "base64"
-version = "0.21.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
-
[[package]]
name = "beef"
version = "0.5.2"
@@ -343,9 +337,9 @@ checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
[[package]]
name = "config"
-version = "0.15.18"
+version = "0.15.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "180e549344080374f9b32ed41bf3b6b57885ff6a289367b3dbc10eea8acc1918"
+checksum = "b30fa8254caad766fc03cb0ccae691e14bf3bd72bfff27f72802ce729551b3d6"
dependencies = [
"async-trait",
"convert_case",
@@ -373,6 +367,19 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "console"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b430743a6eb14e9764d4260d4c0d8123087d504eeb9c48f2b2a5e810dd369df4"
+dependencies = [
+ "encode_unicode",
+ "libc",
+ "once_cell",
+ "unicode-width",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "const-random"
version = "0.1.18"
@@ -514,9 +521,9 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "crypto-common"
-version = "0.1.6"
+version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
@@ -557,6 +564,20 @@ dependencies = [
"syn",
]
+[[package]]
+name = "dashmap"
+version = "6.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf"
+dependencies = [
+ "cfg-if",
+ "crossbeam-utils",
+ "hashbrown 0.14.5",
+ "lock_api",
+ "once_cell",
+ "parking_lot_core",
+]
+
[[package]]
name = "defer-drop"
version = "1.3.0"
@@ -748,9 +769,9 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "erased-serde"
-version = "0.4.8"
+version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "259d404d09818dec19332e31d94558aeb442fea04c817006456c24b5460bbd4b"
+checksum = "89e8918065695684b2b0702da20382d5ae6065cf3327bc2d6436bd49a71ce9f3"
dependencies = [
"serde",
"serde_core",
@@ -876,9 +897,9 @@ dependencies = [
[[package]]
name = "generic-array"
-version = "0.14.9"
+version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
@@ -1008,13 +1029,26 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "indicatif"
+version = "0.18.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9375e112e4b463ec1b1c6c011953545c65a30164fbab5b581df32b3abf0dcb88"
+dependencies = [
+ "console 0.16.1",
+ "portable-atomic",
+ "unicode-width",
+ "unit-prefix",
+ "web-time",
+]
+
[[package]]
name = "insta"
version = "1.43.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46fdb647ebde000f43b5b53f773c30cf9b0cb4300453208713fa38b2c70935a0"
dependencies = [
- "console",
+ "console 0.15.11",
"once_cell",
"pest",
"pest_derive",
@@ -1066,22 +1100,22 @@ checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
[[package]]
name = "jiff"
-version = "0.2.15"
+version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "be1f93b8b1eb69c77f24bbb0afdf66f54b632ee39af40ca21c4365a1d7347e49"
+checksum = "49cce2b81f2098e7e3efc35bc2e0a6b7abec9d34128283d7a26fa8f32a6dbb35"
dependencies = [
"jiff-static",
"log",
"portable-atomic",
"portable-atomic-util",
- "serde",
+ "serde_core",
]
[[package]]
name = "jiff-static"
-version = "0.2.15"
+version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "03343451ff899767262ec32146f6d559dd759fdadf42ff0e227c7c48f72594b4"
+checksum = "980af8b43c3ad5d8d349ace167ec8170839f753a42d233ba19e08afe1850fa69"
dependencies = [
"proc-macro2",
"quote",
@@ -1137,6 +1171,15 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
[[package]]
name = "log"
version = "0.4.28"
@@ -1264,6 +1307,19 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b2d2086a3a477709f0208181e65857a9c062064ab2b3bb9abaf64f17d148bf3"
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
[[package]]
name = "pathdiff"
version = "0.2.3"
@@ -1503,6 +1559,15 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags 2.10.0",
+]
+
[[package]]
name = "redox_users"
version = "0.4.6"
@@ -1562,14 +1627,16 @@ checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"
[[package]]
name = "ron"
-version = "0.8.1"
+version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b91f7eff05f748767f183df4320a63d6936e9c6107d97c9e6bdd9784f4289c94"
+checksum = "fd490c5b18261893f14449cbd28cb9c0b637aebf161cd77900bfdedaff21ec32"
dependencies = [
- "base64",
"bitflags 2.10.0",
+ "once_cell",
"serde",
"serde_derive",
+ "typeid",
+ "unicode-ident",
]
[[package]]
@@ -1660,6 +1727,12 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
[[package]]
name = "semver"
version = "1.0.27"
@@ -1869,6 +1942,12 @@ version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589"
+[[package]]
+name = "smallvec"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
+
[[package]]
name = "streaming-iterator"
version = "0.1.9"
@@ -2214,6 +2293,12 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+[[package]]
+name = "unit-prefix"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "323402cff2dd658f39ca17c789b502021b3f18707c91cdf22e3838e1b4023817"
+
[[package]]
name = "utf8parse"
version = "0.2.2"
@@ -2363,6 +2448,16 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
[[package]]
name = "which"
version = "7.0.3"
@@ -2662,17 +2757,22 @@ dependencies = [
"clap",
"clap_complete",
"config",
+ "console 0.16.1",
"criterion",
+ "crossbeam-channel",
+ "dashmap",
"directories",
"env_logger",
"etcetera",
"fs2",
"indexmap",
+ "indicatif",
"insta",
"insta-cmd",
"log",
"minijinja",
"nix 0.30.1",
+ "once_cell",
"osc8",
"portable-pty",
"rayon",
diff --git a/Cargo.toml b/Cargo.toml
index aed547cfa..b744e0475 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -40,9 +40,14 @@ chrono = "0.4"
clap = { version = "4.5", features = ["derive", "unstable-ext"] }
clap_complete = { version = "4.5", features = ["unstable-dynamic"] }
config = "0.15"
+console = "0.16"
+crossbeam-channel = "0.5"
+dashmap = "6.1"
directories = "6.0"
env_logger = "0.11"
indexmap = { version = "2.12", features = ["serde"] }
+indicatif = "0.18"
+once_cell = "1.21"
etcetera = "0.11"
log = "0.4"
minijinja = "2.12"
diff --git a/ISSUE.md b/ISSUE.md
deleted file mode 100644
index 72ed2050e..000000000
--- a/ISSUE.md
+++ /dev/null
@@ -1,667 +0,0 @@
-# Concurrent Test Failures: SIGKILL During Cargo Lock Contention
-
-## Executive Summary
-
-When running integration tests concurrently (8-10 parallel `cargo test` processes), approximately 29% of test runs fail with processes being killed by SIGKILL (signal 9). The failures occur during `cargo run -p dev-detach` invocations that are blocking on cargo's package cache lock. We implemented a workaround that eliminates the problem by avoiding concurrent cargo invocations, but **we don't understand what is sending SIGKILL or why**.
-
-## Environment
-
-- **OS**: macOS (Darwin 25.0.0)
-- **Hardware**: Apple Silicon (aarch64-apple-darwin)
-- **Cargo**: 1.90.0 (840b83a10 2025-07-30)
-- **Rustc**: 1.90.0 (1159e78c4 2025-09-14)
-- **Test Framework**: libtest (standard `cargo test`, NOT nextest)
-- **Process Limits**:
- - `kern.maxproc: 12000`
- - `kern.maxprocperuid: 8000`
- - `ulimit -u: 8000`
- - `ulimit -n: unlimited` (file descriptors)
-
-## Goals
-
-1. **Primary**: Understand what is sending SIGKILL to cargo processes waiting on locks
-2. **Secondary**: Determine if this is expected behavior or a bug
-3. **Tertiary**: Understand if there's a better solution than avoiding concurrent cargo invocations
-
-## System Architecture
-
-### Test Infrastructure
-
-Our integration tests need to execute shell scripts in isolated environments. We use a helper binary called `dev-detach` to isolate processes from the controlling terminal (prevents PTY-related hangs).
-
-**Original implementation** (`tests/common/shell.rs`):
-
-```rust
-fn build_shell_command(repo: &TestRepo, shell: &str, script: &str) -> Command {
- // Get absolute path to workspace Cargo.toml (tests run from workspace root)
- let manifest = std::env::current_dir()
- .expect("Failed to get current directory")
- .join("Cargo.toml");
-
- let mut cmd = Command::new("cargo");
- cmd.args(["run", "--manifest-path"])
- .arg(&manifest)
- .args(["-p", "dev-detach", "--"]);
-
- // ... configure shell and arguments ...
-
- cmd
-}
-```
-
-This function is called **hundreds of times** during test execution (each shell test invokes it multiple times).
-
-### The dev-detach Binary
-
-`tests/helpers/dev-detach/src/main.rs`:
-
-```rust
-#[cfg(unix)]
-use nix::unistd::{execvp, setsid};
-use std::ffi::CString;
-
-fn main() {
- #[cfg(unix)]
- {
- // Become a new session leader with no controlling terminal
- if let Err(e) = setsid() {
- eprintln!("dev-detach: setsid failed: {}", e);
- process::exit(1);
- }
-
- // Get command and arguments from our argv
- let args: Vec<String> = env::args().skip(1).collect();
- let prog = CString::new(args[0].clone()).unwrap();
- let cargs: Vec<CString> = args
- .iter()
- .map(|a| CString::new(a.as_str()).unwrap())
- .collect();
-
- // Replace this process with the target command
- let _ = execvp(prog.as_c_str(), &cargs);
- eprintln!("dev-detach: execvp failed");
- process::exit(127);
- }
-}
-```
-
-**Key point**: This is a simple wrapper that calls `setsid()` then `execvp()`. It doesn't interact with cargo locks.
-
-## Observed Behavior
-
-### Test Execution Pattern
-
-When running `cargo test` with high concurrency:
-
-```bash
-# 8 parallel test processes, 3 iterations = 24 total runs
-PARALLEL_RUNS=8
-ITERATIONS=3
-
-for iter in 1..3; do
- for i in 1..8; do
- cargo test integration_tests::e2e_shell -- --test-threads=8 &
- done
- wait
-done
-```
-
-### Failure Rate
-
-**Without fix**: 7/24 failures (29%)
-**With fix**: 0/50 failures (0%) across 10 parallel × 5 iterations
-
-### Actual Failure Examples
-
-#### Example 1: SIGKILL During Lock Wait
-
-```
-thread 'integration_tests::e2e_shell_post_start::test_bash_post_create_blocks' panicked at tests/common/shell.rs:112:9:
-Shell script failed (killed by signal 9 (SIGKILL)):
-Command: cargo run --manifest-path <workspace>/Cargo.toml -p dev-detach -- bash [shell-flags...] -c <script>
-stdout:
-stderr: Blocking waiting for file lock on package cache
- Blocking waiting for file lock on package cache
- Blocking waiting for file lock on package cache
- Blocking waiting for file lock on package cache
- Blocking waiting for file lock on build directory
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.52s
- Running `/Users/maximilian/workspace/worktrunk.concurrent-tests/target/debug/dev-detach bash --noprofile --norc -c '
- export PATH="/Users/maximilian/workspace/worktrunk.concurrent-tests/target/debug:$PATH"
-```
-
-**Critical observation**: The stderr shows:
-1. Multiple "Blocking waiting for file lock" messages
-2. Successfully completes: "Finished `dev` profile"
-3. Starts executing: "Running `/path/to/dev-detach ...`"
-4. Then gets SIGKILL
-
-#### Example 2: SIGKILL Before Build Completion
-
-```
-thread 'integration_tests::e2e_shell::test_e2e_switch_and_remove_roundtrip::case_2' panicked at tests/common/shell.rs:112:9:
-Shell script failed (killed by signal 9 (SIGKILL)):
-Command: cargo run --manifest-path <workspace>/Cargo.toml -p dev-detach -- fish [shell-flags...] -c <script>
-stdout:
-stderr: Blocking waiting for file lock on package cache
- Blocking waiting for file lock on package cache
- Blocking waiting for file lock on package cache
- Blocking waiting for file lock on package cache
- Blocking waiting for file lock on build directory
-```
-
-**Critical observation**: No "Finished" message - the process was killed **while waiting for the lock**.
-
-### CPU and Resource Usage
-
-During concurrent execution (without fix):
-
-```bash
-# From test run observations:
-- CPU usage: 909% (9+ cores saturated)
-- Active cargo processes: ~20-30 concurrent
-- Shell processes: ~50-80 concurrent (including dev-detach, bash, fish, zsh)
-```
-
-## What We Tried
-
-### Attempt 1: Using get_cargo_bin() with Once Guard
-
-**Hypothesis**: `insta_cmd::get_cargo_bin()` might invoke cargo every time. Let's call it once and cache the result.
-
-```rust
-use std::sync::Once;
-static BUILD_DEV_DETACH: Once = Once::new();
-
-fn ensure_dev_detach_built() {
- BUILD_DEV_DETACH.call_once(|| {
- let status = Command::new("cargo")
- .args(["build", "-p", "dev-detach"])
- .status()
- .expect("Failed to run cargo build for dev-detach");
-
- if !status.success() {
- panic!("Failed to build dev-detach binary");
- }
- });
-}
-
-fn build_shell_command(repo: &TestRepo, shell: &str, script: &str) -> Command {
- ensure_dev_detach_built();
- let mut cmd = Command::new(get_cargo_bin("dev-detach"));
- // ...
-}
-```
-
-**Result**: Failures reduced from 29% to 12.5% (7/24 → 3/24), but still failing.
-
-**Analysis**: Each test process has its own `Once` instance, so we still had 8 concurrent builds at startup.
-
-### Attempt 2: Using OnceLock to Cache Binary Path
-
-**Hypothesis**: `get_cargo_bin()` itself might be invoking cargo. Let's cache the PathBuf.
-
-```rust
-use std::sync::OnceLock;
-static DEV_DETACH_BIN: OnceLock<PathBuf> = OnceLock::new();
-
-fn get_dev_detach_bin() -> &'static PathBuf {
- DEV_DETACH_BIN.get_or_init(|| {
- let status = Command::new("cargo")
- .args(["build", "-p", "dev-detach"])
- .status()
- .expect("Failed to run cargo build");
-
- if !status.success() {
- panic!("Failed to build dev-detach binary");
- }
-
- get_cargo_bin("dev-detach")
- })
-}
-```
-
-**Result**: Still ~12-29% failure rate.
-
-**Analysis**: Each test process still has independent static storage, so 8 concurrent builds still occur.
-
-### Attempt 3: Direct Path Construction + Pre-build (THE FIX)
-
-**Hypothesis**: Avoid ALL cargo invocations during test execution by:
-1. Building dev-detach once before running tests
-2. Using direct path construction instead of calling any cargo-related functions
-
-```rust
-/// Get path to dev-detach binary.
-/// Assumes the binary has been built (e.g., by `cargo build -p dev-detach` before tests).
-fn get_dev_detach_bin() -> PathBuf {
- // Construct path manually: target/debug/dev-detach
- let manifest_dir = std::env::current_dir().expect("Failed to get current directory");
- manifest_dir.join("target/debug/dev-detach")
-}
-
-fn build_shell_command(repo: &TestRepo, shell: &str, script: &str) -> Command {
- // Use pre-built dev-detach binary (no cargo invocation)
- let mut cmd = Command::new(get_dev_detach_bin());
- // ...
-}
-```
-
-**Pre-build in test script**:
-```bash
-# Build dev-detach once before running tests
-cargo build -p dev-detach --quiet
-
-# Now run concurrent tests
-for iter in 1..5; do
- for i in 1..10; do
- cargo test integration_tests::e2e_shell -- --test-threads=8 &
- done
- wait
-done
-```
-
-**Result**: ✅ **100% success rate** - 50/50 runs passed (10 parallel × 5 iterations)
-
-**Verification**:
-```bash
-$ cargo build -p dev-detach --quiet && cargo test --test integration -- --test-threads=12
-...
-test result: ok. 321 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 13.81s
-```
-
-## Key Findings
-
-### 1. SIGKILL Timing is Inconsistent
-
-From our failure logs, SIGKILL happens at two different points:
-
-**Point A**: While waiting for lock (no "Finished" message)
-```
- Blocking waiting for file lock on build directory
-[Process killed here - no "Finished" message]
-```
-
-**Point B**: After successful build, during execution
-```
- Blocking waiting for file lock on build directory
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.52s
- Running `/path/to/dev-detach bash ...`
-[Process killed here - mid-execution]
-```
-
-### 2. No Evidence of Timeout Configuration
-
-We checked:
-- ❌ No `RUST_TEST_TIME_*` environment variables set
-- ❌ No `.nextest.toml` configuration (and we're not using nextest anyway)
-- ❌ No timeout flags in `cargo test --help`
-- ❌ libtest has `--report-time` and `--ensure-time`, but these don't kill processes
-- ❌ No cargo lock timeout documented in cargo source or documentation
-
-### 3. System Limits are Not Exhausted
-
-```bash
-$ ulimit -a
--u: processes 8000
--n: file descriptors unlimited
-
-$ sysctl kern.maxproc kern.maxprocperuid
-kern.maxproc: 12000
-kern.maxprocperuid: 8000
-
-# During test execution:
-$ ps aux | grep -E "bash|zsh|fish|dev-detach" | wc -l
-53
-
-$ ps aux | grep -c "[c]argo"
-21
-```
-
-We're using ~74 processes out of 8000 limit - well within bounds.
-
-### 4. No OOM Killer Evidence
-
-```bash
-$ dmesg 2>&1 | grep -i "killed\|oom"
-[No output - dmesg not available on macOS by default]
-```
-
-macOS doesn't have a traditional OOM killer like Linux. Process termination under memory pressure is handled differently.
-
-## Our Assumptions (UNPROVEN)
-
-### Assumption 1: macOS is Sending SIGKILL
-
-**Reasoning**:
-- SIGKILL (signal 9) cannot be caught or blocked by the process
-- It's typically sent by the kernel or system management
-- User processes rarely send SIGKILL (they use SIGTERM first)
-
-**Unproven**: We haven't traced which process/kernel subsystem sends the signal.
-
-**How to verify**:
-- Use `sudo dtruss -p <cargo_pid>` to trace system calls
-- Monitor Console.app for system messages during failures
-- Check if cargo itself has watchdog timers in source code
-
-### Assumption 2: High Lock Contention Triggers System Intervention
-
-**Reasoning**:
-- Failures correlate with "Blocking waiting for file lock" messages
-- Eliminating concurrent cargo invocations eliminates SIGKILL
-- macOS might detect processes in prolonged wait states as "stuck"
-
-**Unproven**: We don't know macOS's specific heuristics for killing processes.
-
-**How to verify**:
-- Research macOS process management policies
-- Check if macOS has configurable thresholds for process wait states
-- Look for Apple documentation on system resource management
-
-### Assumption 3: Cargo Lock Implementation Doesn't Have Timeouts
-
-**Reasoning**:
-- No timeout configuration found in cargo documentation
-- `cargo build --help` has no timeout flags
-- Cargo source code (github.com/rust-lang/cargo) would show timeout logic
-
-**Unproven**: We haven't audited cargo's source code for lock timeout mechanisms.
-
-**How to verify**:
-- Search cargo source for lock timeout implementations
-- Check cargo issue tracker for lock-related SIGKILL reports
-- Review cargo's `util/config` module for hidden timeout settings
-
-### Assumption 4: The Problem is Lock-Specific, Not Load-Specific
-
-**Reasoning**:
-- The fix (pre-building) eliminates concurrent cargo invocations
-- Pre-building doesn't reduce total system load (tests still run concurrently)
-- SIGKILL stops happening despite similar CPU/memory usage
-
-**Counter-evidence**:
-- We observed 909% CPU during original runs (high load)
-- With fix, CPU usage is still high during test execution
-- Maybe the difference is **duration** of high load, not peak?
-
-**Unproven**: We haven't compared system metrics (CPU, I/O, memory pressure) between failing and passing runs.
-
-**How to verify**:
-- Monitor system pressure metrics during both scenarios
-- Use `powermetrics` or Activity Monitor to compare resource usage
-- Check if macOS's App Nap or other power management features are involved
-
-## Open Questions
-
-### Question 1: What Process/Subsystem Sends SIGKILL?
-
-**What we need to know**:
-- Is it the kernel?
-- Is it cargo itself (internal watchdog)?
-- Is it macOS's process management daemon (e.g., `kernel_task`, `launchd`)?
-- Is it a resource governor (memory pressure, thermal throttling)?
-
-**Research directions**:
-1. Search for "macOS SIGKILL blocked processes" or "macOS kill waiting processes"
-2. Look for cargo source code related to subprocess management and timeouts
-3. Check Apple documentation on process lifecycle management
-4. Search for similar reports in Rust/cargo communities
-5. Look for macOS system calls that can trigger SIGKILL (`kill(2)`, `killpg(2)`)
-
-### Question 2: Is This Expected macOS Behavior?
-
-**What we need to know**:
-- Does macOS have documented policies for killing processes in wait states?
-- Are there system-wide timeout thresholds we're exceeding?
-- Is this a feature or a bug?
-
-**Research directions**:
-1. Apple Developer Documentation on process management
-2. Darwin kernel source code (open source) for process scheduler
-3. XNU (kernel) documentation on process states and lifecycle
-4. Search for "macOS kill blocking process" or "macOS I/O wait timeout"
-
-### Question 3: Why is the Timing Inconsistent?
-
-Some processes get killed while waiting for lock, others after build completion. Why?
-
-**Hypotheses**:
-- Different cargo subprocesses have different wait times
-- macOS uses cumulative metrics (total time in wait state)
-- Race condition in detection logic
-- Different code paths have different watchdogs
-
-**Research directions**:
-1. Map cargo's subprocess tree during `cargo run`
-2. Understand which process gets SIGKILL (parent cargo or child rustc?)
-3. Check if cargo uses process groups and how SIGKILL propagates
-
-### Question 4: Are There Hidden Cargo Configuration Options?
-
-**What we need to know**:
-- Does cargo have undocumented timeout settings?
-- Are there environment variables we're not aware of?
-- Does cargo have different behavior in "test mode"?
-
-**Research directions**:
-1. Review `cargo --list` for all subcommands and options
-2. Search cargo source for `CARGO_*` environment variables
-3. Check if `cargo test` sets special environment for child processes
-4. Look for `.cargo/config.toml` options related to timeouts or locks
-
-### Question 5: Why Does Lock Contention Occur at All?
-
-**What we need to know**:
-- What is cargo locking when building dev-detach?
-- Why does building a simple helper binary require multiple locks?
-- Can we configure cargo to use different lock granularity?
-
-**From our observations**:
-```
-Blocking waiting for file lock on package cache
-Blocking waiting for file lock on build directory
-```
-
-This suggests at least two separate locks. Why multiple locks for a simple build?
-
-**Research directions**:
-1. Understand cargo's lock hierarchy (package cache → dependency resolution → build directory)
-2. Check if `cargo build -p` (workspace member build) has different locking than `cargo build`
-3. Research cargo's concurrent build architecture
-4. Look for cargo RFC/documentation on lock implementation
-
-### Question 6: Could This Be Related to `insta_cmd`?
-
-**What we need to know**:
-- What does `insta_cmd::get_cargo_bin()` actually do?
-- Does it invoke cargo, or just locate the binary?
-- Could it be interacting with cargo in unexpected ways?
-
-**Research directions**:
-1. Review insta_cmd source code for `get_cargo_bin()` implementation
-2. Check if it caches binary locations
-3. See if it has any lock files or state that could conflict
-
-## Detailed Code Context
-
-### Complete Test Execution Flow
-
-1. **Test harness** runs `cargo test integration_tests::e2e_shell`
-2. **Test function** (e.g., `test_bash_e2e_switch_existing_worktree`) calls:
- ```rust
- let output = execute_shell_script(&repo, "bash", &script);
- ```
-3. **`execute_shell_script`** (in `tests/common/shell.rs:59`) calls:
- ```rust
- let mut cmd = build_shell_command(repo, shell, script);
- let output = cmd.current_dir(repo.root_path()).output().unwrap();
- ```
-4. **`build_shell_command`** (original version) constructs:
- ```rust
- Command::new("cargo")
- .args(["run", "--manifest-path", &manifest, "-p", "dev-detach", "--"])
- .arg(shell)
- .args([shell_flags...])
- .arg("-c")
- .arg(script)
- ```
-5. **Cargo** receives this and must:
- - Acquire package cache lock
- - Check if dev-detach needs rebuilding
- - Acquire build directory lock
- - Build dev-detach (if needed)
- - Execute dev-detach with remaining arguments
-
-When 8-10 test processes do this concurrently, step 5 becomes a bottleneck.
-
-### Signal Handling Code
-
-We added signal number reporting to diagnose the issue:
-
-```rust
-/// Convert signal number to human-readable name
-#[cfg(unix)]
-fn signal_name(sig: i32) -> &'static str {
- match sig {
- 1 => "SIGHUP",
- 2 => "SIGINT",
- 3 => "SIGQUIT",
- 6 => "SIGABRT",
- 9 => "SIGKILL",
- 11 => "SIGSEGV",
- 13 => "SIGPIPE",
- 15 => "SIGTERM",
- _ => "UNKNOWN",
- }
-}
-
-// In execute_shell_script:
-if !output.status.success() {
- let exit_info = match output.status.code() {
- Some(code) => format!("exit code {}", code),
- None => {
- #[cfg(unix)]
- {
- use std::os::unix::process::ExitStatusExt;
- match output.status.signal() {
- Some(sig) => format!("killed by signal {} ({})", sig, signal_name(sig)),
- None => "killed by signal (unknown)".to_string(),
- }
- }
- #[cfg(not(unix))]
- {
- "killed by signal".to_string()
- }
- }
- };
- panic!("Shell script failed ({}):\n...", exit_info);
-}
-```
-
-This confirmed all failures were **signal 9 (SIGKILL)**, not other signals like SIGTERM or SIGPIPE.
-
-## What Success Looks Like
-
-The workaround successfully eliminates the problem:
-
-```bash
-$ cargo build -p dev-detach --quiet
-$ cargo test --test integration -- --test-threads=12
-...
-test result: ok. 321 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 13.81s
-
-# Stress test: 10 parallel × 5 iterations = 50 runs
-$ for iter in 1..5; do
- for i in 1..10; do
- cargo test integration_tests::e2e_shell -- --test-threads=8 &
- done
- wait
-done
-
-Result: ✅ All 50 runs passed (0 failures)
-```
-
-## Priority Research Questions
-
-**Highest Priority (Critical to Understanding)**:
-
-1. **Who sends SIGKILL?** - Trace the actual source of the signal
-2. **Is there a cargo lock timeout?** - Audit cargo source code or find documentation
-3. **Does macOS have process wait state policies?** - Find Apple documentation on process lifecycle
-
-**Medium Priority (Nice to Know)**:
-
-4. Why is timing inconsistent (kill during wait vs. after build)?
-5. What exactly triggers the decision to send SIGKILL?
-6. Are there configuration options to adjust thresholds?
-
-**Lower Priority (Optimization)**:
-
-7. Could cargo's locking be more granular for workspace members?
-8. Is there a way to pre-warm cargo's cache to avoid lock contention?
-9. Should we file a bug report with cargo or macOS?
-
-## Potential Alternative Solutions
-
-If we understood the root cause, we might be able to:
-
-1. **Configure a timeout** (if one exists) to be longer
-2. **Adjust system policies** (if macOS has configurable thresholds)
-3. **Use cargo's jobserver** to coordinate builds (if that's relevant)
-4. **File a bug report** if this is unintended behavior
-5. **Document the workaround** as best practice for test infrastructure
-
-## Current Workaround (Implemented)
-
-```rust
-// In tests/common/shell.rs:
-fn get_dev_detach_bin() -> PathBuf {
- std::env::current_dir()
- .expect("Failed to get current directory")
- .join("target/debug/dev-detach")
-}
-
-fn build_shell_command(repo: &TestRepo, shell: &str, script: &str) -> Command {
- let mut cmd = Command::new(get_dev_detach_bin());
- // ... rest of setup
-}
-```
-
-**Requirements**:
-- Must run `cargo build -p dev-detach` before running tests
-- Binary must exist at `target/debug/dev-detach`
-
-**Advantages**:
-- ✅ 100% reliable (no failures in 50+ runs)
-- ✅ Faster test execution (no cargo overhead)
-- ✅ Simple implementation
-
-**Disadvantages**:
-- ❌ Requires explicit pre-build step
-- ❌ Won't automatically rebuild if source changes
-- ❌ Doesn't solve the underlying mystery
-
-## Summary
-
-We have a **reliable workaround** but **no understanding of root cause**. The key mystery is: **What sends SIGKILL to cargo processes waiting on locks, and why?**
-
-The evidence strongly suggests it's not:
-- Process/FD limits (we're well within limits)
-- OOM killer (no memory pressure observed)
-- Test framework timeouts (libtest doesn't kill processes)
-- Cargo configuration (no timeout options found)
-
-The most likely explanation is **macOS system-level process management** responding to prolonged wait states under high load, but we have no concrete evidence or documentation to support this.
-
-**We need research into**:
-1. macOS process lifecycle policies
-2. Cargo's subprocess and lock management
-3. Darwin/XNU kernel behavior for I/O-blocked processes
-4. Similar reports in the Rust/cargo community
-
-The goal is to determine if this is:
-- **Expected behavior** we should work around (as we have)
-- **A bug** in cargo's lock management
-- **A system limitation** we can configure
-- **Something else** we haven't considered
diff --git a/STATUS-ALTERNATIVES.md b/STATUS-ALTERNATIVES.md
new file mode 100644
index 000000000..2a97b91ff
--- /dev/null
+++ b/STATUS-ALTERNATIVES.md
@@ -0,0 +1,446 @@
+# Status Column: Compact Representations With Same Information
+
+Analysis of how to display the **same information** in the Status column using **fewer characters** through more compact symbols, combined indicators, or overloaded meanings.
+
+**Goal:** Keep Status as a comprehensive summary, reduce space usage from 16 chars while preserving all information.
+
+## Current Status Column Layout (16 chars)
+
+```
+Position 0: working_tree (5 chars) - ?!+»✘
+Position 1: conflicts (1 char) - =
+Position 2: git_operation (1 char) - ↻⋈
+Position 3: main_divergence (1 char) - ↑↓↕
+Position 4: upstream_div (1 char) - ⇡⇣⇅
+Position 5: branch_state (1 char) - ≡∅
+Position 6: worktree_attrs (3 chars) - ◇⊠⚠
+Position 7: user_status (3 chars) - emoji/labels
+ ─────────
+Total: 16 characters
+```
+
+**Typical usage:** 0-3 chars, **Maximum possible:** 11 chars (`?!+»✘=⊠↕⇅🤖`)
+
+---
+
+## Strategy 1: Verify Mutual Exclusivity
+
+**Observation:** Some positions contain mutually exclusive symbols (enforced by enums within each field). Need to verify if positions can be combined.
+
+### 1A. Git Operation + Branch State - Can they combine? ❌ NO
+
+**Analysis from code review** (`src/commands/list/collect.rs:99-109, 270-295`):
+
+**Git operation** (↻⋈) = **process state** - ongoing git operation
+- `↻` when `.git/rebase-merge` or `.git/rebase-apply` exists
+- `⋈` when `.git/MERGE_HEAD` exists
+
+**Branch state** (≡∅) = **content state** - relationship to main
+- `≡` when matches main exactly (no commits ahead, working tree matches)
+- `∅` when no commits but doesn't match main
+
+**These are orthogonal dimensions** and can occur simultaneously:
+
+**Example scenario:**
+```bash
+wt switch feature # At main's HEAD, matches exactly (≡)
+git rebase other # Conflict occurs (↻)
+# Result: Both ≡ and ↻ are set
+```
+
+**Verdict:** ❌ **Cannot combine** - represent independent dimensions (process vs content state)
+
+---
+
+### 1B. Conflicts + Branch State - Can they combine? ✅ YES
+
+**Analysis from code review** (`src/commands/list/collect.rs:270-295, 420-428`):
+
+**Conflicts** (=) = **would conflict if merged into main**
+- Set when `repo.has_merge_conflicts(base, commit_sha)` returns true
+- Indicates the worktree has changes that would conflict with main
+
+**Branch state** (≡∅) = **relationship to main**
+- `≡` when matches main exactly (no commits ahead, working tree matches)
+- `∅` when no commits ahead and clean working tree
+
+**These are mutually exclusive states:**
+
+**Logical analysis:**
+```
+= (conflicts) → Has changes that conflict with main
+≡ (matches) → IS main (identical, no changes)
+∅ (no commits) → Has nothing ahead of main, clean
+(none) → Normal working branch (changes but no conflicts)
+```
+
+**Why mutually exclusive:**
+- `≡` (matches main): Cannot have conflicts if you ARE main (identical trees)
+- `∅` (no commits): Cannot have conflicts if you have nothing ahead of main
+- `=` (conflicts): Implies you have changes that differ from main
+
+**Scenarios:**
+```bash
+# Scenario 1: Matches main (≡)
+wt switch feature
+# At main's HEAD, no changes
+# branch_state = MatchesMain (≡)
+# has_conflicts = false (can't conflict if identical)
+
+# Scenario 2: No commits (∅)
+wt switch -c empty
+# No commits, clean working tree
+# branch_state = NoCommits (∅)
+# has_conflicts = false (nothing to conflict)
+
+# Scenario 3: Conflicts (=)
+# Feature has commits that would conflict with main
+# branch_state = None (has commits ahead)
+# has_conflicts = true
+```
+
+**Verdict:** ✅ **Can combine** - mutually exclusive states that can share one position
+
+**Proposed combined position:**
+```
+Position: conflicts_or_branch_state (1 char)
+ = ← has merge conflicts with main
+ ≡ ← matches main exactly
+ ∅ ← no commits, clean
+```
+
+**Savings: 1 char** (combines positions 1 and 5)
+
+---
+
+## Strategy 2: Compress Multi-Char Positions
+
+### 2A. Working Tree: Use Combined Symbols (saves 2-3 chars)
+
+**Current:** Up to 5 separate symbols
+```
+?!+»✘ (5 chars max)
+```
+
+**Proposed Option 1: Compound symbols for common combinations**
+```
+Common patterns as single symbols:
+ ⊗ ← ?! (untracked + modified) - most common "dirty" state
+ ⊕ ← !+ (modified + staged) - common workflow state
+ ? ← untracked only
+ ! ← modified only
+ + ← staged only
+ » ← renamed (rare, stays separate)
+ ✘ ← deleted (rare, stays separate)
+```
+
+**Analysis:**
+- ⚠️ Saves 1 char in common case (`?!` → `⊗`)
+- ❌ Requires learning new symbols
+- ❌ Doesn't save space when have `?!+` (3 symbols) vs `⊗+` (2 symbols) = saves 1 char only
+- ❌ Edge cases with all 5 types still take 4-5 chars
+
+**Verdict:** ⚠️ Marginal savings, added complexity
+
+---
+
+**Proposed Option 2: Single symbol with styling**
+```
+Use base symbol modified by color/style:
+ ∗ ← base "changes" symbol
+
+Variants:
+ ∗ CYAN ← untracked
+ ∗ YELLOW ← modified
+ ∗ GREEN ← staged
+ ∗ BOLD ← has multiple types
+```
+
+**Analysis:**
+- ✅ Saves 4 chars (5 → 1)
+- ❌ **Major information loss** - can't distinguish which types when multiple
+- ❌ Color dependency
+
+**Verdict:** ❌ Too much information loss
+
+---
+
+**Proposed Option 3: Abbreviated symbols**
+```
+?!+»✘ (5 chars) → ?!+RD (5 chars, no savings)
+ → ?!+rd (5 chars, no savings)
+```
+
+Single-char alternatives that are more compact:
+```
+? → . (dot for untracked)
+! → m (modified)
++ → s (staged)
+» → r (renamed)
+✘ → d (deleted)
+
+Result: ".msr" instead of "?!+»" (same width, less visual)
+```
+
+**Analysis:**
+- ❌ No space savings
+- ❌ Less scannable (. less visible than ?)
+- ❌ Letters require reading, not instant recognition
+
+**Verdict:** ❌ No benefit
+
+---
+
+### 2B. Worktree Attributes: Bare is Dead Code! (saves 1 char immediately)
+
+**Current allocation:** 3 chars for `◇⊠⚠`
+
+**Discovery from code review** (`src/git/mod.rs:88`):
+
+```rust
+// WorktreeList filters out bare worktrees automatically
+let worktrees: Vec<_> = raw_worktrees.into_iter().filter(|wt| !wt.bare).collect();
+```
+
+**Analysis:**
+- `◇` (bare) is **never shown** - bare worktrees are filtered out before display
+- Only `⊠` (locked) and `⚠` (prunable) can actually appear
+- The code that renders `◇` is unreachable
+
+**Why bare is filtered:**
+- Git worktrees can be "bare" (no working directory)
+- This applies to bare repositories themselves
+- Worktrunk filters these out because they're not useful to display (can't work in them)
+- Only actual worktrees with working directories are shown
+
+**Verdict:** ✅ **Remove bare entirely** - it's dead code
+
+**New maximum:** `⊠⚠` (2 chars: locked + prunable simultaneously)
+
+---
+
+**Proposed Option 1: Keep 2-char allocation**
+```
+Current max: ⊠⚠ (2 chars - locked + prunable)
+Allocation: 2 chars
+```
+
+**Analysis:**
+- ✅ No information loss
+- ✅ Handles the rare case of locked+prunable
+- ✅ Simple implementation
+
+**Verdict:** ✅ **Good default** - just reduce allocation from 3→2
+
+---
+
+**Proposed Option 2: Priority symbol only (saves 1 more char)**
+```
+Priority: ⚠ > ⊠
+
+⚠ ← prunable (with or without locked)
+⊠ ← locked only
+```
+
+**Analysis:**
+- ✅ Saves 1 additional char (2→1)
+- ⚠️ Can't distinguish "prunable only" from "prunable + locked"
+- ⚠️ How often are both set? If rare, loss is minimal
+
+**Verdict:** ⚠️ Possible if combinations are very rare
+
+---
+
+### 2C. User Status: Reduce Allocation (saves 1 char)
+
+**Current:** 3 chars allocated
+
+**Typical usage:**
+- `🤖` (2 chars visual width)
+- `💬` (2 chars)
+- `WIP` (3 chars)
+- `🔥` (2 chars)
+
+**Proposed:** 2 chars allocation
+```
+Emoji fit fine (most are 2 chars)
+Text labels truncated: "WIP" → "WI" or "WP"
+```
+
+**Analysis:**
+- ✅ Saves 1 char
+- ⚠️ Text labels truncated (but emoji are more common)
+- ⚠️ Rare 3+ char emoji sequences truncated
+
+**Verdict:** ✅ Reasonable - most users use emoji (2 chars), text truncation acceptable
+
+---
+
+## Strategy 3: Use Color/Style to Overload Meaning
+
+### 3A. Color-Code Conflicts Symbol
+
+**Current:** `=` (red symbol)
+
+**Proposed:** Use color to indicate conflict severity
+```
+= RED ← merge conflicts
+= YELLOW ← resolved but uncommitted
+= GRAY ← (unused - conflicts are binary)
+```
+
+**Analysis:**
+- ❌ Conflicts are binary (exist or don't exist)
+- ❌ No additional information to encode
+- ❌ No space savings
+
+**Verdict:** ❌ No benefit
+
+---
+
+### 3B. Style Divergence Arrows
+
+**Proposed:** Use arrow style attributes to double-encode information
+```
+↑ BOLD ← many commits ahead (>10)
+↑ NORMAL ← few commits ahead
+↓ RED ← many commits behind (>10)
+↓ YELLOW ← few commits behind
+```
+
+**Analysis:**
+- ⚠️ Numbers are already shown in `main↕` column
+- ❌ Duplicates information, doesn't save space
+- ❌ Doesn't address the core issue
+
+**Verdict:** ❌ Not applicable
+
+---
+
+## Strategy 4: Reorder Positions to Allow Sharing Space
+
+### 4A. Group Related Symbols to Share Context
+
+**Observation:** Some symbols have implied spacing/positioning
+
+**Current positions:**
+```
+[working_tree:5] [conflicts:1] [git_op:1] [main_div:1] [upstream_div:1] [branch_state:1] [attrs:3] [user:3]
+```
+
+**Proposed:** Reorder to group related items
+```
+[working_tree:5] [conflicts:1] [git_op:1] [branch_state:1] [main_div:1] [upstream_div:1] [attrs:1+] [user:2]
+
+Where:
+- attrs use priority + "more" indicator
+- user reduced to 2 chars
+```
+
+**Savings calculation:**
+- attrs: 3 → 2 (save 1)
+- user: 3 → 2 (save 1)
+**Total: Save 2 chars**
+
+---
+
+## Summary: Viable Compact Representations
+
+| Change | Saves | Information Loss | Viability |
+|--------|-------|------------------|-----------|
+| Remove bare (dead code) | 1 char | ✅ None (never shown) | ✅ **Immediate win** |
+| Combine conflicts + branch_state | 1 char | ✅ None (mutually exclusive) | ✅ Good |
+| Combine git_op + branch_state | - | ❌ Can co-occur (verified) | ❌ No |
+| Compound working_tree symbols | 1 char | ⚠️ Learn new symbols | ⚠️ Marginal |
+| Abbreviated working_tree | 0 chars | Less scannable | ❌ No |
+| Worktree attrs: priority only | 1 char | ⚠️ Lose ⊠⚠ distinction | ⚠️ If rare |
+| User status: reduce to 2 chars | 1 char | Text truncation | ✅ Good |
+
+**Conclusion:** Can achieve meaningful compaction through dead code removal and combining mutually exclusive symbols.
+
+---
+
+## Recommended Compact Layout: 13 chars
+
+**Conservative approach with no information loss:**
+
+```
+Position 0: working_tree (5 chars) - ?!+»✘ [keep all]
+Position 1: conflicts_or_branch_state (1 char) - =≡∅ [combined, mutually exclusive]
+Position 2: git_operation (1 char) - ↻⋈
+Position 3: main_divergence (1 char) - ↑↓↕
+Position 4: upstream_divergence (1 char) - ⇡⇣⇅
+Position 5: worktree_attrs (2 chars) - ⊠⚠ [bare removed - dead code]
+Position 6: user_status (2 chars) - 🤖 [reduced]
+ ─────────
+Total: 13 chars (saves 3)
+
+Examples:
+ "" ← clean
+ "?!+" ← changes
+ "?!+ ≡" ← changes + matches main
+ "= ↻" ← conflicts + rebasing
+ "?!+ = ↻ ↕ ⇅" ← changes + conflicts + rebase + divergences
+ "∅ 🤖" ← no commits + user status
+ " ⊠⚠ 🤖" ← locked + prunable + user status
+```
+
+**Information preserved:**
+- ✅ All working tree change types
+- ✅ Conflicts (=), matches main (≡), or no commits (∅) - mutually exclusive
+- ✅ Git operation (full detail)
+- ✅ Main divergence (full detail)
+- ✅ Upstream divergence (full detail)
+- ✅ Worktree attributes (locked, prunable) - bare removed as dead code
+- ✅ User status (emoji fit, text truncated)
+
+**Changes from current (16 chars):**
+1. **Conflicts + branch_state: 2 → 1 char** (combined, mutually exclusive)
+2. **Worktree attrs: 3 → 2 chars** (removed bare - dead code)
+3. **User status: 3 → 2 chars** (reduced allocation)
+
+---
+
+## First Step: Just Remove Bare (15 chars, saves 1)
+
+**Minimal change with zero information loss:**
+
+```
+Position 0: working_tree (5 chars) - ?!+»✘
+Position 1: conflicts (1 char) - =
+Position 2: git_operation (1 char) - ↻⋈
+Position 3: branch_state (1 char) - ≡∅
+Position 4: main_divergence (1 char) - ↑↓↕
+Position 5: upstream_divergence (1 char) - ⇡⇣⇅
+Position 6: worktree_attrs (2 chars) - ⊠⚠ [bare removed]
+Position 7: user_status (3 chars) - 🤖
+ ─────────
+Total: 15 chars (saves 1)
+
+Changes:
+- Remove bare symbol (◇) - it's never rendered (dead code)
+- Reduce allocation: 3 → 2 chars for worktree_attrs
+```
+
+This is a **safe first step** - removes dead code with zero behavioral change.
+
+---
+
+## Alternative: More Aggressive (12 chars)
+
+**If we accept losing locked+prunable distinction:**
+
+```
+Position 0: working_tree (5 chars) - ?!+»✘
+Position 1: conflicts_or_branch_state (1 char) - =≡∅
+Position 2: git_operation (1 char) - ↻⋈
+Position 3: main_divergence (1 char) - ↑↓↕
+Position 4: upstream_divergence (1 char) - ⇡⇣⇅
+Position 5: worktree_attrs (1 char) - ⊠⚠ [priority: ⚠ > ⊠]
+Position 6: user_status (2 chars) - 🤖
+ ─────────
+Total: 12 chars (saves 4)
+
+Additional loss:
+- ⚠️ Can't see when both locked AND prunable (rare edge case)
+```
diff --git a/src/cli.rs b/src/cli.rs
index 27d32ce99..48c3343e6 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -349,7 +349,7 @@ Docs: https://llm.datasette.io/ | https://github.com/sigoden/aichat
Age: Time since last commit (relative)
Message: Last commit message (truncated)
-STATUS SYMBOLS (order: =≠ ≡∅ ↻⋈ ◇⊠⚠ ↑↓ ⇡⇣ ?!+»✘):
+STATUS SYMBOLS (order: =≠ ≡∅ ↻⋈ ⊠⚠ ↑↓ ⇡⇣ ?!+»✘):
· Branch without worktree (no working directory to check)
\x1b[31m=\x1b[0m Merge conflicts (unmerged paths in working tree)
\x1b[33m≠\x1b[0m Potential conflicts with main (--full only, detected via git merge-tree)
@@ -357,7 +357,6 @@ STATUS SYMBOLS (order: =≠ ≡∅ ↻⋈ ◇⊠⚠ ↑↓ ⇡⇣ ?!+»✘):
∅ No commits (no commits ahead AND no uncommitted changes)
↻ Rebase in progress
⋈ Merge in progress
- ◇ Bare worktree (no working directory)
⊠ Locked worktree
⚠ Prunable worktree
↑ Ahead of main branch
@@ -387,6 +386,14 @@ Rows are dimmed when no unique work (≡ matches main OR ∅ no commits).")]
/// Requires network requests and git merge-tree operations.
#[arg(long, verbatim_doc_comment)]
full: bool,
+
+ /// Show rows progressively (auto-detects TTY)
+ #[arg(long, verbatim_doc_comment, conflicts_with = "no_progressive")]
+ progressive: bool,
+
+ /// Disable progressive rendering
+ #[arg(long)]
+ no_progressive: bool,
},
/// Switch to a worktree
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
new file mode 100644
index 000000000..12173331c
--- /dev/null
+++ b/src/commands/list/collect.rs
@@ -0,0 +1,806 @@
+//! Worktree data collection with parallelized git operations.
+//!
+//! This module provides an efficient approach to collecting worktree data:
+//! - Parallel collection across worktrees (using Rayon)
+//! - Parallel operations within each worktree (using scoped threads)
+//! - Progressive updates via channels (update UI as each worktree completes)
+//!
+//! ## Unified Collection Architecture
+//!
+//! Both progressive (with progress bars) and buffered (silent) modes use the same
+//! `collect_internal()` function. The only difference is whether progress bars are
+//! created and shown. This ensures a single canonical collection implementation.
+//!
+//! **Parallelism at two levels**:
+//! - Across worktrees: Multiple worktrees collected concurrently via Rayon
+//! - Within worktrees: Git operations (ahead/behind, diffs, CI) run concurrently via scoped threads
+//!
+//! This ensures fast operations don't wait for slow ones (e.g., CI doesn't block ahead/behind counts)
+use crossbeam_channel as chan;
+use rayon::prelude::*;
+use worktrunk::git::{GitError, LineDiff, Repository, Worktree};
+use worktrunk::styling::INFO_EMOJI;
+
+use super::ci_status::PrStatus;
+use super::model::{
+ AheadBehind, BranchDiffTotals, BranchState, CommitDetails, GitOperation, ItemKind, ListItem,
+ MainDivergence, StatusSymbols, UpstreamDivergence, UpstreamStatus,
+};
+
+/// Cell update messages sent as each git operation completes.
+/// These enable progressive rendering - update UI as data arrives.
+#[derive(Debug, Clone)]
+pub(super) enum CellUpdate {
+ /// Commit timestamp and message
+ CommitDetails {
+ item_idx: usize,
+ commit: CommitDetails,
+ },
+ /// Ahead/behind counts vs main
+ AheadBehind {
+ item_idx: usize,
+ counts: AheadBehind,
+ },
+ /// Line diff vs main branch
+ BranchDiff {
+ item_idx: usize,
+ branch_diff: BranchDiffTotals,
+ },
+ /// Working tree diff and symbols (?, !, +, », ✘)
+ WorkingTreeDiff {
+ item_idx: usize,
+ working_tree_diff: LineDiff,
+ working_tree_diff_with_main: Option<LineDiff>,
+ /// Symbols for uncommitted changes (?, !, +, », ✘)
+ working_tree_symbols: String,
+ is_dirty: bool,
+ },
+ /// Merge conflicts with main
+ Conflicts {
+ item_idx: usize,
+ has_conflicts: bool,
+ },
+ /// Git operation in progress (rebase/merge)
+ WorktreeState {
+ item_idx: usize,
+ worktree_state: Option<String>,
+ },
+ /// User-defined status from git config
+ UserStatus {
+ item_idx: usize,
+ user_status: Option<String>,
+ },
+ /// Upstream tracking status
+ Upstream {
+ item_idx: usize,
+ upstream: UpstreamStatus,
+ },
+ /// CI/PR status (slow operation)
+ CiStatus {
+ item_idx: usize,
+ pr_status: Option<PrStatus>,
+ },
+}
+
+impl CellUpdate {
+ /// Get the item index for this update
+ fn item_idx(&self) -> usize {
+ match self {
+ CellUpdate::CommitDetails { item_idx, .. } => *item_idx,
+ CellUpdate::AheadBehind { item_idx, .. } => *item_idx,
+ CellUpdate::BranchDiff { item_idx, .. } => *item_idx,
+ CellUpdate::WorkingTreeDiff { item_idx, .. } => *item_idx,
+ CellUpdate::Conflicts { item_idx, .. } => *item_idx,
+ CellUpdate::WorktreeState { item_idx, .. } => *item_idx,
+ CellUpdate::UserStatus { item_idx, .. } => *item_idx,
+ CellUpdate::Upstream { item_idx, .. } => *item_idx,
+ CellUpdate::CiStatus { item_idx, .. } => *item_idx,
+ }
+ }
+}
+
+/// Detect if a worktree is in the middle of a git operation (rebase/merge).
+pub(super) fn detect_worktree_state(repo: &Repository) -> Option<String> {
+ let git_dir = repo.git_dir().ok()?;
+
+ if git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists() {
+ Some("rebase".to_string())
+ } else if git_dir.join("MERGE_HEAD").exists() {
+ Some("merge".to_string())
+ } else {
+ None
+ }
+}
+
+/// Compute status symbols from individual components (for progressive rendering).
+///
+/// This is a simplified version of compute_status_symbols that works with individual fields
+/// rather than StatusInfo struct. Used during progressive rendering when fields arrive separately.
+#[allow(clippy::too_many_arguments)]
+fn compute_status_symbols_from_parts(
+ working_tree_symbols: &str,
+ counts: &AheadBehind,
+ upstream: &UpstreamStatus,
+ has_conflicts: bool,
+ worktree_state: Option<&str>,
+ wt: &Worktree,
+ working_tree_diff: &LineDiff,
+ working_tree_diff_with_main: Option<&LineDiff>,
+ is_primary: bool,
+ base_branch: Option<&str>,
+ user_status: Option<String>,
+) -> StatusSymbols {
+ // Build main divergence
+ let main_divergence = match (counts.ahead, counts.behind) {
+ (0, 0) => MainDivergence::None,
+ (a, 0) if a > 0 => MainDivergence::Ahead,
+ (0, b) if b > 0 => MainDivergence::Behind,
+ _ => MainDivergence::Diverged,
+ };
+
+ // Build upstream divergence
+ let (upstream_ahead, upstream_behind) =
+ upstream.active().map(|(_, a, b)| (a, b)).unwrap_or((0, 0));
+ let upstream_divergence = match (upstream_ahead, upstream_behind) {
+ (0, 0) => UpstreamDivergence::None,
+ (a, 0) if a > 0 => UpstreamDivergence::Ahead,
+ (0, b) if b > 0 => UpstreamDivergence::Behind,
+ _ => UpstreamDivergence::Diverged,
+ };
+
+ // Determine branch state (only for non-primary worktrees with base branch)
+ let branch_state = if !is_primary && base_branch.is_some() {
+ // Check for MatchesMain (requires mdiff to confirm working tree matches main's tree)
+ if let Some(mdiff) = working_tree_diff_with_main {
+ if mdiff.added == 0 && mdiff.deleted == 0 && counts.ahead == 0 {
+ BranchState::MatchesMain
+ } else if counts.ahead == 0
+ && working_tree_diff.added == 0
+ && working_tree_diff.deleted == 0
+ {
+ BranchState::NoCommits
+ } else {
+ BranchState::None
+ }
+ } else {
+ // mdiff is None (optimization when trees differ)
+ // Can still determine NoCommits without computing diff
+ if counts.ahead == 0 && working_tree_diff.added == 0 && working_tree_diff.deleted == 0 {
+ BranchState::NoCommits
+ } else {
+ BranchState::None
+ }
+ }
+ } else {
+ BranchState::None
+ };
+
+ // Determine git operation
+ let git_operation = match worktree_state {
+ Some("rebase") => GitOperation::Rebase,
+ Some("merge") => GitOperation::Merge,
+ _ => GitOperation::None,
+ };
+
+ // Worktree attributes
+ let mut worktree_attrs = String::new();
+ // Note: wt.bare is always false here because WorktreeList filters out bare worktrees
+ // See src/git/mod.rs:88 - bare worktrees are removed before reaching this code
+ if wt.locked.is_some() {
+ worktree_attrs.push('⊠');
+ }
+ if wt.prunable.is_some() {
+ worktree_attrs.push('⚠');
+ }
+
+ StatusSymbols {
+ has_conflicts,
+ has_potential_conflicts: false, // Not computed in fast path
+ branch_state,
+ git_operation,
+ worktree_attrs,
+ main_divergence,
+ upstream_divergence,
+ working_tree: working_tree_symbols.to_string(),
+ user_status,
+ }
+}
+
+/// Compute status_symbols for all worktrees after data collection is complete.
+/// Compute status symbols for a single item (worktree only).
+/// Returns true if status was computed, false if item is not a worktree or already has status.
+fn compute_item_status_symbols(
+ item: &mut ListItem,
+ sorted_worktrees: &[Worktree],
+ primary: &Worktree,
+ worktree_idx: usize,
+) -> bool {
+ // Skip if already computed
+ if item.status_symbols.is_some() {
+ return false;
+ }
+
+ if let ItemKind::Worktree(data) = &item.kind {
+ let wt = &sorted_worktrees[worktree_idx];
+ let base_branch = primary
+ .branch
+ .as_deref()
+ .filter(|_| wt.path != primary.path);
+
+ item.status_symbols = Some(compute_status_symbols_from_parts(
+ data.working_tree_symbols.as_deref().unwrap_or(""),
+ item.counts.as_ref().unwrap_or(&AheadBehind::default()),
+ item.upstream.as_ref().unwrap_or(&UpstreamStatus::default()),
+ item.has_conflicts.unwrap_or(false),
+ data.worktree_state.as_deref(),
+ wt,
+ data.working_tree_diff
+ .as_ref()
+ .unwrap_or(&LineDiff::default()),
+ data.working_tree_diff_with_main
+ .as_ref()
+ .and_then(|opt| opt.as_ref()),
+ data.is_primary,
+ base_branch,
+ item.user_status.clone(),
+ ));
+ true
+ } else {
+ false
+ }
+}
+
+fn compute_all_status_symbols(
+ all_items: &mut [ListItem],
+ sorted_worktrees: &[Worktree],
+ primary: &Worktree,
+) {
+ let mut worktree_idx = 0;
+ for item in all_items.iter_mut() {
+ if compute_item_status_symbols(item, sorted_worktrees, primary, worktree_idx) {
+ worktree_idx += 1;
+ }
+ }
+}
+
+/// Drain cell updates from the channel and apply them to worktree_items.
+///
+/// This is the shared logic between progressive and buffered collection modes.
+/// The `on_update` callback is called after each update is processed with the
+/// item index and a reference to the updated info, allowing progressive mode
+/// to update progress bars while buffered mode does nothing.
+fn drain_cell_updates(
+ rx: chan::Receiver<CellUpdate>,
+ worktree_items: &mut [ListItem],
+ mut on_update: impl FnMut(usize, &mut ListItem),
+) {
+ // Process cell updates as they arrive
+ while let Ok(update) = rx.recv() {
+ let item_idx = update.item_idx();
+
+ match update {
+ CellUpdate::CommitDetails { item_idx, commit } => {
+ worktree_items[item_idx].commit = Some(commit);
+ }
+ CellUpdate::AheadBehind { item_idx, counts } => {
+ worktree_items[item_idx].counts = Some(counts);
+ }
+ CellUpdate::BranchDiff {
+ item_idx,
+ branch_diff,
+ } => {
+ worktree_items[item_idx].branch_diff = Some(branch_diff);
+ }
+ CellUpdate::WorkingTreeDiff {
+ item_idx,
+ working_tree_diff,
+ working_tree_diff_with_main,
+ working_tree_symbols,
+ is_dirty,
+ } => {
+ if let ItemKind::Worktree(data) = &mut worktree_items[item_idx].kind {
+ data.working_tree_diff = Some(working_tree_diff);
+ data.working_tree_diff_with_main = Some(working_tree_diff_with_main);
+ data.working_tree_symbols = Some(working_tree_symbols);
+ data.is_dirty = Some(is_dirty);
+ }
+ }
+ CellUpdate::Conflicts {
+ item_idx,
+ has_conflicts,
+ } => {
+ worktree_items[item_idx].has_conflicts = Some(has_conflicts);
+ }
+ CellUpdate::WorktreeState {
+ item_idx,
+ worktree_state,
+ } => {
+ if let ItemKind::Worktree(data) = &mut worktree_items[item_idx].kind {
+ data.worktree_state = worktree_state;
+ }
+ }
+ CellUpdate::UserStatus {
+ item_idx,
+ user_status,
+ } => {
+ worktree_items[item_idx].user_status = user_status;
+ }
+ CellUpdate::Upstream { item_idx, upstream } => {
+ worktree_items[item_idx].upstream = Some(upstream);
+ }
+ CellUpdate::CiStatus {
+ item_idx,
+ pr_status,
+ } => {
+ // Wrap in Some() to indicate "loaded" (Some(None) = no CI, Some(Some(status)) = has CI)
+ worktree_items[item_idx].pr_status = Some(pr_status);
+ }
+ }
+
+ // Invoke rendering callback (progressive mode re-renders rows, buffered mode does nothing)
+ on_update(item_idx, &mut worktree_items[item_idx]);
+ }
+}
+
+/// Get branches that don't have worktrees.
+///
+/// Returns (branch_name, commit_sha) pairs for all branches without associated worktrees.
+fn get_branches_without_worktrees(
+ repo: &Repository,
+ worktrees: &[Worktree],
+) -> Result<Vec<(String, String)>, GitError> {
+ // Get all local branches
+ let all_branches = repo.list_local_branches()?;
+
+ // Build a set of branch names that have worktrees
+ let worktree_branches: std::collections::HashSet<String> = worktrees
+ .iter()
+ .filter_map(|wt| wt.branch.clone())
+ .collect();
+
+ // Filter to branches without worktrees
+ let branches_without_worktrees: Vec<_> = all_branches
+ .into_iter()
+ .filter(|(branch_name, _)| !worktree_branches.contains(branch_name))
+ .collect();
+
+ Ok(branches_without_worktrees)
+}
+
+/// Collect worktree data with optional progressive rendering.
+///
+/// When `show_progress` is true, renders a skeleton immediately and updates as data arrives.
+/// When false, silently collects all data and returns it for external rendering.
+pub fn collect(
+ repo: &Repository,
+ show_branches: bool,
+ show_full: bool,
+ fetch_ci: bool,
+ check_conflicts: bool,
+ show_progress: bool,
+) -> Result<Option<super::model::ListData>, GitError> {
+ use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
+ use std::time::Duration;
+
+ let worktrees = repo.list_worktrees()?;
+ if worktrees.worktrees.is_empty() {
+ return Ok(None);
+ }
+
+ let primary = worktrees.worktrees[0].clone();
+ let current_worktree_path = repo.worktree_root().ok();
+
+ // Sort worktrees for display order
+ let sorted_worktrees = sort_worktrees(
+ &worktrees.worktrees,
+ &primary,
+ current_worktree_path.as_ref(),
+ );
+
+ // Get branches early for layout calculation and skeleton creation (when --branches is used)
+ let branches_without_worktrees = if show_branches {
+ get_branches_without_worktrees(repo, &worktrees.worktrees)?
+ } else {
+ Vec::new()
+ };
+
+ let branch_names: Vec<String> = branches_without_worktrees
+ .iter()
+ .map(|(name, _sha)| name.clone())
+ .collect();
+
+ // Calculate layout from basic worktree info + branch names
+ let layout = super::layout::calculate_layout_from_basics(
+ &sorted_worktrees,
+ &branch_names,
+ show_full,
+ fetch_ci,
+ );
+
+ // Single-line invariant: compute width from the draw target (stderr) with right guard
+ // to prevent line wrapping (which breaks indicatif's line-based cursor math).
+ // Keep 2 columns free: off-by-one terminal behavior + emoji width safety margin.
+ let (_, term_cols) = console::Term::stderr().size();
+ let max_width = term_cols.saturating_sub(2) as usize;
+
+ let clamp = |s: &str| -> String {
+ if console::measure_text_width(s) > max_width {
+ console::truncate_str(s, max_width, "…").into_owned()
+ } else {
+ s.to_owned()
+ }
+ };
+
+ // Create MultiProgress with explicit draw target and cursor mode
+ // Use stderr for progress bars so they don't interfere with stdout directives
+ let multi = if show_progress {
+ let mp = MultiProgress::with_draw_target(indicatif::ProgressDrawTarget::stderr_with_hz(10));
+ mp.set_move_cursor(true); // Stable since bar count is fixed
+ mp
+ } else {
+ MultiProgress::new()
+ };
+
+ let message_style = ProgressStyle::with_template("{msg}").unwrap();
+
+ // Create header progress bar (part of transient UI, cleared with finish_and_clear)
+ let header_pb = if show_progress {
+ let pb = multi.add(ProgressBar::hidden());
+ pb.set_style(message_style.clone());
+ pb.set_message(clamp(&layout.format_header_line()));
+ Some(pb)
+ } else {
+ None
+ };
+
+ // Initialize worktree items with identity fields and None for computed fields
+ let mut all_items: Vec<super::model::ListItem> = sorted_worktrees
+ .iter()
+ .map(|wt| super::model::ListItem {
+ // Common fields
+ head: wt.head.clone(),
+ branch: wt.branch.clone(),
+ commit: None,
+ counts: None,
+ branch_diff: None,
+ upstream: None,
+ pr_status: None,
+ has_conflicts: None,
+ user_status: None,
+ status_symbols: None,
+ display: super::model::DisplayFields::default(),
+ // Type-specific data
+ kind: super::model::ItemKind::Worktree(Box::new(
+ super::model::WorktreeData::from_worktree(wt, wt.path == primary.path),
+ )),
+ })
+ .collect();
+
+ // Initialize branch items with identity fields and None for computed fields
+ let branch_start_idx = all_items.len();
+ for (branch_name, commit_sha) in &branches_without_worktrees {
+ all_items.push(super::model::ListItem {
+ // Common fields
+ head: commit_sha.clone(),
+ branch: Some(branch_name.clone()),
+ commit: None,
+ counts: None,
+ branch_diff: None,
+ upstream: None,
+ pr_status: None,
+ has_conflicts: None,
+ user_status: None,
+ status_symbols: None,
+ display: super::model::DisplayFields::default(),
+ // Type-specific data
+ kind: super::model::ItemKind::Branch,
+ });
+ }
+
+ // Create progress bars for all items (worktrees + branches)
+ let progress_bars: Vec<_> = all_items
+ .iter()
+ .enumerate()
+ .map(|(idx, item)| {
+ let pb = multi.add(ProgressBar::new_spinner());
+ if show_progress {
+ pb.set_style(message_style.clone());
+
+ // Render skeleton immediately with clamping
+ let skeleton = if idx < sorted_worktrees.len() {
+ // Worktree skeleton
+ let wt = &sorted_worktrees[idx];
+ let is_primary = wt.path == primary.path;
+ let is_current = current_worktree_path
+ .as_ref()
+ .map(|cp| &wt.path == cp)
+ .unwrap_or(false);
+ layout.format_skeleton_row(wt, is_primary, is_current)
+ } else {
+ // Branch skeleton
+ layout.format_list_item_line(item, current_worktree_path.as_ref())
+ };
+ pb.set_message(clamp(&skeleton));
+ pb.enable_steady_tick(Duration::from_millis(100));
+ }
+ pb
+ })
+ .collect();
+
+ // Cache last rendered message per row to avoid redundant updates
+ let mut last_lines: Vec<String> = vec![String::new(); all_items.len()];
+
+ // Footer progress bar with loading status
+ // Uses determinate bar (no spinner) with {wide_msg} to prevent clearing artifacts
+ let total_cells = all_items.len() * layout.columns.len();
+ let num_worktrees = sorted_worktrees.len();
+ let num_branches = branches_without_worktrees.len();
+ let footer_base = if show_branches && num_branches > 0 {
+ format!(
+ "Showing {} worktrees, {} branches",
+ num_worktrees, num_branches
+ )
+ } else {
+ let plural = if num_worktrees == 1 { "" } else { "s" };
+ format!("Showing {} worktree{}", num_worktrees, plural)
+ };
+
+ // Spacer: single-line blank between the table rows and the footer (no multiline messages)
+ let spacer_style = ProgressStyle::with_template("{wide_msg}").unwrap();
+ let spacer_pb = if show_progress {
+ let gap = multi.add(ProgressBar::new(1));
+ gap.set_style(spacer_style.clone());
+ gap.set_message(" "); // padded blank line
+ Some(gap)
+ } else {
+ None
+ };
+
+ // Footer is single-line; no '\n'. Will be replaced with final summary on finish.
+ let footer_style = ProgressStyle::with_template("{wide_msg}").unwrap();
+
+ let footer_pb = if show_progress {
+ use anstyle::Style;
+ let dim = Style::new().dimmed();
+
+ // Footer with determinate bar (no spinner/tick)
+ let footer = multi.add(ProgressBar::new(total_cells as u64));
+ footer.set_style(footer_style);
+ footer.set_message(format!(
+ "{INFO_EMOJI} {dim}{footer_base} (0/{total_cells} cells loaded){dim:#}"
+ ));
+ Some(footer)
+ } else {
+ None
+ };
+
+ // Create channel for cell updates
+ let (tx, rx) = chan::unbounded();
+
+ // Spawn worktree collection in background thread
+ let sorted_worktrees_clone = sorted_worktrees.clone();
+ let primary_clone = primary.clone();
+ let tx_worktrees = tx.clone();
+ std::thread::spawn(move || {
+ sorted_worktrees_clone
+ .par_iter()
+ .enumerate()
+ .for_each(|(idx, wt)| {
+ super::collect_progressive_impl::collect_worktree_progressive(
+ wt,
+ &primary_clone,
+ idx,
+ fetch_ci,
+ check_conflicts,
+ tx_worktrees.clone(),
+ );
+ });
+ });
+
+ // Spawn branch collection in background thread (if requested)
+ if show_branches {
+ let branches_clone = branches_without_worktrees.clone();
+ let primary_clone = primary.clone();
+ let tx_branches = tx.clone();
+ std::thread::spawn(move || {
+ branches_clone
+ .par_iter()
+ .enumerate()
+ .for_each(|(idx, (branch_name, commit_sha))| {
+ let item_idx = branch_start_idx + idx;
+ super::collect_progressive_impl::collect_branch_progressive(
+ branch_name,
+ commit_sha,
+ &primary_clone,
+ item_idx,
+ fetch_ci,
+ check_conflicts,
+ tx_branches.clone(),
+ );
+ });
+ });
+ }
+
+ // Drop the original sender so drain_cell_updates knows when all spawned threads are done
+ drop(tx);
+
+ // Track completed cells for footer progress and worktree index for status computation
+ let mut completed_cells = 0;
+ let mut worktree_idx_map = vec![None; all_items.len()];
+ {
+ let mut wt_idx = 0;
+ for (item_idx, item) in all_items.iter().enumerate() {
+ if matches!(item.kind, ItemKind::Worktree(_)) {
+ worktree_idx_map[item_idx] = Some(wt_idx);
+ wt_idx += 1;
+ }
+ }
+ }
+
+ // Drain cell updates with conditional progressive rendering
+ drain_cell_updates(rx, &mut all_items, |item_idx, info| {
+ if show_progress {
+ use anstyle::Style;
+ let dim = Style::new().dimmed();
+
+ completed_cells += 1;
+
+ // Compute status symbols progressively once we have working_tree_symbols
+ // (that indicates we have the core data needed for status computation)
+ if info.status_symbols.is_none()
+ && let (ItemKind::Worktree(data), Some(wt_idx)) =
+ (&info.kind, worktree_idx_map[item_idx])
+ && data.working_tree_symbols.is_some()
+ {
+ compute_item_status_symbols(info, &sorted_worktrees, &primary, wt_idx);
+ }
+
+ // Update footer progress
+ if let Some(pb) = footer_pb.as_ref() {
+ pb.set_position(completed_cells as u64);
+ pb.set_message(format!(
+ "{INFO_EMOJI} {dim}{footer_base} ({completed_cells}/{total_cells} cells loaded){dim:#}"
+ ));
+ }
+
+ // Re-render the row with caching and clamping (now includes status if computed)
+ if let Some(pb) = progress_bars.get(item_idx) {
+ let rendered = layout.format_list_item_line(info, current_worktree_path.as_ref());
+ let clamped = clamp(&rendered);
+
+ // Only update if content changed
+ if clamped != last_lines[item_idx] {
+ last_lines[item_idx] = clamped.clone();
+ pb.set_message(clamped);
+ }
+ }
+ }
+ });
+
+ // Finalize progress bars: no clearing race; footer morphs into summary on TTY
+ if show_progress {
+ use std::io::IsTerminal;
+ let is_tty = std::io::stderr().is_terminal(); // Check stderr, not stdout ✅
+
+ // Build final summary string once using helper function
+ let final_msg =
+ super::format_summary_message(&all_items, show_branches, layout.hidden_nonempty_count);
+
+ if is_tty {
+ // Interactive: morph footer → summary, keep rows in place
+ if let Some(pb) = spacer_pb.as_ref() {
+ pb.finish(); // leave the blank line
+ }
+ if let Some(pb) = footer_pb.as_ref() {
+ pb.finish_with_message(final_msg.clone());
+ }
+ if let Some(pb) = header_pb {
+ pb.finish();
+ }
+ for pb in progress_bars {
+ pb.finish();
+ }
+ } else {
+ // Non-TTY: clear progress bars and print final table to stderr
+ if let Some(pb) = spacer_pb {
+ pb.finish_and_clear();
+ }
+ if let Some(pb) = footer_pb {
+ pb.finish_and_clear();
+ }
+ if let Some(pb) = header_pb {
+ pb.finish_and_clear();
+ }
+ for pb in progress_bars {
+ pb.finish_and_clear();
+ }
+ // Ensure atomicity w.r.t. indicatif's draw thread
+ multi.suspend(|| {
+ // Redraw static table
+ crate::output::raw_terminal(layout.format_header_line())?;
+ for item in &all_items {
+ crate::output::raw_terminal(
+ layout.format_list_item_line(item, current_worktree_path.as_ref()),
+ )?;
+ }
+ // Blank line + summary (rendered here in non-tty mode)
+ crate::output::raw_terminal("")?;
+ crate::output::raw_terminal(final_msg.clone())
+ })?;
+ }
+ } else {
+ for pb in progress_bars {
+ pb.finish();
+ }
+ }
+
+ // Compute status_symbols for any items that didn't get computed during progressive loading
+ // (fallback for buffered mode or if progressive computation was skipped for some reason)
+ compute_all_status_symbols(&mut all_items, &sorted_worktrees, &primary);
+
+ // Buffered mode: compute display fields (progressive mode doesn't need this as rendering uses raw data)
+ if !show_progress {
+ for info in &mut all_items {
+ info.display = super::model::DisplayFields::from_common_fields(
+ &info.counts,
+ &info.branch_diff,
+ &info.upstream,
+ &info.pr_status,
+ );
+
+ if let super::model::ItemKind::Worktree(ref mut wt_data) = info.kind
+ && let Some(ref working_tree_diff) = wt_data.working_tree_diff
+ {
+ wt_data.working_diff_display = super::columns::ColumnKind::WorkingDiff
+ .format_diff_plain(working_tree_diff.added, working_tree_diff.deleted);
+ }
+ }
+ }
+
+ // all_items now contains both worktrees and branches (if requested)
+ let items = all_items;
+
+ // Progressive mode: table already rendered via progress bars (finished in place for TTY,
+ // or explicitly printed to stderr for non-TTY in the finalization code above)
+ // Buffered mode: table will be rendered in mod.rs
+ // Both modes: summary will be rendered in mod.rs
+
+ Ok(Some(super::model::ListData {
+ items,
+ current_worktree_path,
+ }))
+}
+
+/// Sort worktrees for display (primary first, then current, then by timestamp descending).
+fn sort_worktrees(
+ worktrees: &[Worktree],
+ primary: &Worktree,
+ current_path: Option<&std::path::PathBuf>,
+) -> Vec<Worktree> {
+ let timestamps: Vec<i64> = worktrees
+ .par_iter()
+ .map(|wt| {
+ Repository::at(&wt.path)
+ .commit_timestamp(&wt.head)
+ .unwrap_or(0)
+ })
+ .collect();
+
+ let mut indexed: Vec<_> = worktrees.iter().enumerate().collect();
+ indexed.sort_by_key(|(idx, wt)| {
+ let is_primary = wt.path == primary.path;
+ let is_current = current_path.map(|cp| &wt.path == cp).unwrap_or(false);
+
+ let priority = if is_primary {
+ 0
+ } else if is_current {
+ 1
+ } else {
+ 2
+ };
+
+ (priority, std::cmp::Reverse(timestamps[*idx]))
+ });
+
+ indexed.into_iter().map(|(_, wt)| wt.clone()).collect()
+}
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
new file mode 100644
index 000000000..f3fbdf2e2
--- /dev/null
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -0,0 +1,489 @@
+//! Progressive worktree collection with parallel git operations.
+//!
+//! This module contains the implementation of cell-by-cell progressive rendering.
+//! Git operations run in parallel and send updates as they complete.
+//!
+//! TODO(error-handling): Current implementation silently swallows git errors
+//! and logs warnings to stderr. Consider whether failures should:
+//! - Propagate to user (fail-fast)
+//! - Show error placeholder in UI
+//! - Continue silently (current behavior)
+
+use crossbeam_channel::Sender;
+use worktrunk::git::{LineDiff, Repository, Worktree};
+
+use super::ci_status::PrStatus;
+use super::collect::{CellUpdate, detect_worktree_state};
+use super::model::{AheadBehind, BranchDiffTotals, CommitDetails, UpstreamStatus};
+
+/// Collect worktree data progressively, sending cell updates as each task completes.
+///
+/// Spawns 9 parallel git operations:
+/// 1. Commit details (timestamp, message)
+/// 2. Ahead/behind counts
+/// 3. Branch diff stats
+/// 4. Working tree diff + status symbols
+/// 5. Conflicts check
+/// 6. Worktree state detection
+/// 7. User status from git config
+/// 8. Upstream tracking status
+/// 9. CI/PR status
+///
+/// Each task sends a CellUpdate when it completes, enabling progressive UI updates.
+/// Errors are handled with TODO for simplicity (simplest thing for now).
+pub fn collect_worktree_progressive(
+ wt: &Worktree,
+ primary: &Worktree,
+ item_idx: usize,
+ fetch_ci: bool,
+ check_conflicts: bool,
+ tx: Sender<CellUpdate>,
+) {
+ let base_branch = primary
+ .branch
+ .as_deref()
+ .filter(|_| wt.path != primary.path);
+
+ // Clone data needed across threads
+ let wt_path = wt.path.clone();
+ let wt_head = wt.head.clone();
+ let wt_branch = wt.branch.clone();
+ let base_branch_owned = base_branch.map(String::from);
+
+ // Spawn all tasks in parallel using scoped threads
+ std::thread::scope(|s| {
+ // Task 1: Commit details
+ {
+ let tx = tx.clone();
+ let head = wt_head.clone();
+ let path = wt_path.clone();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ // TODO: Handle errors - for now, simplest thing is to skip on error
+ if let (Ok(timestamp), Ok(commit_message)) =
+ (repo.commit_timestamp(&head), repo.commit_message(&head))
+ {
+ let _ = tx.send(CellUpdate::CommitDetails {
+ item_idx,
+ commit: CommitDetails {
+ timestamp,
+ commit_message,
+ },
+ });
+ }
+ });
+ }
+
+ // Task 2: Ahead/behind counts
+ if let Some(base) = base_branch_owned.as_deref() {
+ let tx = tx.clone();
+ let head = wt_head.clone();
+ let path = wt_path.clone();
+ let base = base.to_string();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ // TODO: Handle errors
+ if let Ok((ahead, behind)) = repo.ahead_behind(&base, &head) {
+ let _ = tx.send(CellUpdate::AheadBehind {
+ item_idx,
+ counts: AheadBehind { ahead, behind },
+ });
+ }
+ });
+ }
+
+ // Task 3: Branch diff
+ if let Some(base) = base_branch_owned.as_deref() {
+ let tx = tx.clone();
+ let head = wt_head.clone();
+ let path = wt_path.clone();
+ let base = base.to_string();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ // TODO: Handle errors
+ if let Ok(diff) = repo.branch_diff_stats(&base, &head) {
+ let _ = tx.send(CellUpdate::BranchDiff {
+ item_idx,
+ branch_diff: BranchDiffTotals { diff },
+ });
+ }
+ });
+ }
+
+ // Task 4: Working tree diff + status symbols
+ {
+ let tx = tx.clone();
+ let path = wt_path.clone();
+ let base = base_branch_owned.clone();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ // TODO: Handle errors
+ if let Ok(status_output) = repo.run_command(&["status", "--porcelain"]) {
+ // Parse status to get symbols and is_dirty
+ let (working_tree_symbols, is_dirty) = parse_status_for_symbols(&status_output);
+
+ // Get working tree diff
+ let working_tree_diff = if is_dirty {
+ repo.working_tree_diff_stats().unwrap_or_default()
+ } else {
+ LineDiff::default()
+ };
+
+ // Get diff with main
+ let working_tree_diff_with_main = repo
+ .working_tree_diff_with_base(base.as_deref(), is_dirty)
+ .ok()
+ .flatten();
+
+ let _ = tx.send(CellUpdate::WorkingTreeDiff {
+ item_idx,
+ working_tree_diff,
+ working_tree_diff_with_main,
+ working_tree_symbols,
+ is_dirty,
+ });
+ }
+ });
+ }
+
+ // Task 5: Conflicts check (always send, even if not checking)
+ {
+ let tx = tx.clone();
+ if check_conflicts && let Some(base) = base_branch_owned.as_deref() {
+ let head = wt_head.clone();
+ let path = wt_path.clone();
+ let base = base.to_string();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ // TODO: Handle errors
+ let has_conflicts = repo.has_merge_conflicts(&base, &head).unwrap_or(false);
+ let _ = tx.send(CellUpdate::Conflicts {
+ item_idx,
+ has_conflicts,
+ });
+ });
+ } else {
+ // Send default value when not checking conflicts
+ let _ = tx.send(CellUpdate::Conflicts {
+ item_idx,
+ has_conflicts: false,
+ });
+ }
+ }
+
+ // Task 6: Worktree state detection
+ {
+ let tx = tx.clone();
+ let path = wt_path.clone();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ let worktree_state = detect_worktree_state(&repo);
+ let _ = tx.send(CellUpdate::WorktreeState {
+ item_idx,
+ worktree_state,
+ });
+ });
+ }
+
+ // Task 7: User status
+ {
+ let tx = tx.clone();
+ let path = wt_path.clone();
+ let branch = wt_branch.clone();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ let user_status = repo.user_status(branch.as_deref());
+ let _ = tx.send(CellUpdate::UserStatus {
+ item_idx,
+ user_status,
+ });
+ });
+ }
+
+ // Task 8: Upstream status (always sends)
+ {
+ let tx = tx.clone();
+ let branch = wt_branch.clone();
+ let head = wt_head.clone();
+ let path = wt_path.clone();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ let upstream = if let Some(branch) = branch.as_deref() {
+ match repo.upstream_branch(branch) {
+ Ok(Some(upstream_branch)) => {
+ let remote =
+ upstream_branch.split_once('/').map(|(r, _)| r.to_string());
+ match repo.ahead_behind(&upstream_branch, &head) {
+ Ok((ahead, behind)) => Some(UpstreamStatus {
+ remote,
+ ahead,
+ behind,
+ }),
+ Err(e) => {
+ eprintln!(
+ "Warning: ahead_behind failed for {}: {}",
+ path.display(),
+ e
+ );
+ None
+ }
+ }
+ }
+ Ok(None) => None, // No upstream configured
+ Err(e) => {
+ eprintln!(
+ "Warning: upstream_branch failed for {}: {}",
+ path.display(),
+ e
+ );
+ None
+ }
+ }
+ } else {
+ None // No branch (detached HEAD)
+ };
+ let upstream = upstream.unwrap_or_default();
+ let _ = tx.send(CellUpdate::Upstream { item_idx, upstream });
+ });
+ }
+
+ // Task 9: CI status
+ if fetch_ci {
+ let tx = tx.clone();
+ let branch = wt_branch.clone();
+ let head = wt_head.clone();
+ let path = wt_path.clone();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ // TODO: Handle errors
+ if let Ok(repo_path) = repo.worktree_root() {
+ let pr_status = branch
+ .as_deref()
+ .and_then(|branch| PrStatus::detect(branch, &head, &repo_path));
+ let _ = tx.send(CellUpdate::CiStatus {
+ item_idx,
+ pr_status,
+ });
+ }
+ });
+ }
+ });
+}
+
+/// Parse git status output to extract working tree symbols.
+/// Returns (symbols, is_dirty).
+fn parse_status_for_symbols(status_output: &str) -> (String, bool) {
+ let mut has_untracked = false;
+ let mut has_modified = false;
+ let mut has_staged = false;
+ let mut has_renamed = false;
+ let mut has_deleted = false;
+ let mut is_dirty = false;
+
+ for line in status_output.lines() {
+ if line.len() < 2 {
+ continue;
+ }
+
+ is_dirty = true;
+
+ let bytes = line.as_bytes();
+ let index_status = bytes[0] as char;
+ let worktree_status = bytes[1] as char;
+
+ if index_status == '?' && worktree_status == '?' {
+ has_untracked = true;
+ }
+
+ if worktree_status == 'M' {
+ has_modified = true;
+ }
+
+ if index_status == 'A' || index_status == 'M' || index_status == 'C' {
+ has_staged = true;
+ }
+
+ if index_status == 'R' {
+ has_renamed = true;
+ }
+
+ if index_status == 'D' || worktree_status == 'D' {
+ has_deleted = true;
+ }
+ }
+
+ // Build working tree string
+ let mut working_tree = String::new();
+ if has_untracked {
+ working_tree.push('?');
+ }
+ if has_modified {
+ working_tree.push('!');
+ }
+ if has_staged {
+ working_tree.push('+');
+ }
+ if has_renamed {
+ working_tree.push('»');
+ }
+ if has_deleted {
+ working_tree.push('✘');
+ }
+
+ (working_tree, is_dirty)
+}
+
+/// Collect branch data progressively, sending cell updates as each task completes.
+///
+/// Spawns 6 parallel git operations (similar to worktrees but without working tree operations):
+/// 1. Commit details (timestamp, message)
+/// 2. Ahead/behind counts
+/// 3. Branch diff stats
+/// 4. Upstream tracking status
+/// 5. Conflicts check
+/// 6. CI/PR status
+pub fn collect_branch_progressive(
+ branch_name: &str,
+ commit_sha: &str,
+ primary: &Worktree,
+ item_idx: usize,
+ fetch_ci: bool,
+ check_conflicts: bool,
+ tx: Sender<CellUpdate>,
+) {
+ let base_branch = primary.branch.as_deref();
+ let repo_path = primary.path.clone();
+
+ // Clone data needed across threads
+ let branch_name_owned = branch_name.to_string();
+ let commit_sha_owned = commit_sha.to_string();
+
+ // Spawn all tasks in parallel using scoped threads
+ std::thread::scope(|s| {
+ // Task 1: Commit details
+ {
+ let tx = tx.clone();
+ let sha = commit_sha_owned.clone();
+ let path = repo_path.clone();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ // TODO: Handle errors - for now, simplest thing is to skip on error
+ if let (Ok(timestamp), Ok(commit_message)) =
+ (repo.commit_timestamp(&sha), repo.commit_message(&sha))
+ {
+ let _ = tx.send(CellUpdate::CommitDetails {
+ item_idx,
+ commit: CommitDetails {
+ timestamp,
+ commit_message,
+ },
+ });
+ }
+ });
+ }
+
+ // Task 2: Ahead/behind counts
+ if let Some(base) = base_branch {
+ let tx = tx.clone();
+ let sha = commit_sha_owned.clone();
+ let path = repo_path.clone();
+ let base = base.to_string();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ // TODO: Handle errors
+ if let Ok((ahead, behind)) = repo.ahead_behind(&base, &sha) {
+ let _ = tx.send(CellUpdate::AheadBehind {
+ item_idx,
+ counts: AheadBehind { ahead, behind },
+ });
+ }
+ });
+ }
+
+ // Task 3: Branch diff
+ if let Some(base) = base_branch {
+ let tx = tx.clone();
+ let sha = commit_sha_owned.clone();
+ let path = repo_path.clone();
+ let base = base.to_string();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ // TODO: Handle errors
+ if let Ok(diff) = repo.branch_diff_stats(&base, &sha) {
+ let _ = tx.send(CellUpdate::BranchDiff {
+ item_idx,
+ branch_diff: BranchDiffTotals { diff },
+ });
+ }
+ });
+ }
+
+ // Task 4: Upstream status
+ {
+ let tx = tx.clone();
+ let branch = branch_name_owned.clone();
+ let sha = commit_sha_owned.clone();
+ let path = repo_path.clone();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ let upstream = match repo.upstream_branch(&branch) {
+ Ok(Some(upstream_branch)) => {
+ let remote = upstream_branch.split_once('/').map(|(r, _)| r.to_string());
+ match repo.ahead_behind(&upstream_branch, &sha) {
+ Ok((ahead, behind)) => Some(UpstreamStatus {
+ remote,
+ ahead,
+ behind,
+ }),
+ Err(_) => None,
+ }
+ }
+ Ok(None) => None, // No upstream configured
+ Err(_) => None,
+ };
+
+ let _ = tx.send(CellUpdate::Upstream {
+ item_idx,
+ upstream: upstream.unwrap_or(UpstreamStatus {
+ remote: None,
+ ahead: 0,
+ behind: 0,
+ }),
+ });
+ });
+ }
+
+ // Task 5: Conflicts check
+ if check_conflicts && let Some(base) = base_branch {
+ let tx = tx.clone();
+ let sha = commit_sha_owned.clone();
+ let path = repo_path.clone();
+ let base = base.to_string();
+ s.spawn(move || {
+ let repo = Repository::at(&path);
+ // TODO: Handle errors
+ if let Ok(has_conflicts) = repo.has_merge_conflicts(&base, &sha) {
+ let _ = tx.send(CellUpdate::Conflicts {
+ item_idx,
+ has_conflicts,
+ });
+ }
+ });
+ }
+
+ // Task 6: CI/PR status
+ if fetch_ci {
+ let tx = tx.clone();
+ let branch = branch_name_owned.clone();
+ let sha = commit_sha_owned.clone();
+ let path = repo_path.clone();
+ s.spawn(move || {
+ let pr_status = PrStatus::detect(&branch, &sha, &path);
+ let _ = tx.send(CellUpdate::CiStatus {
+ item_idx,
+ pr_status,
+ });
+ });
+ }
+ });
+}
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index c42a37aaf..51d6ffc75 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -15,7 +15,7 @@
//! - Position 0a: Conflicts (=)
//! - Position 0b: Branch state (≡, ∅)
//! - Position 0c: Git operation (↻, ⋈)
-//! - Position 0d: Worktree attributes (◇, ⊠, ⚠)
+//! - Position 0d: Worktree attributes (⊠, ⚠)
//! - Position 1: Main divergence (↑, ↓, ↕)
//! - Position 2: Upstream divergence (⇡, ⇣, ⇅)
//! - Position 3: Working tree (?, !, +, », ✘)
@@ -197,6 +197,20 @@ pub const HEADER_CI: &str = "CI";
pub const HEADER_COMMIT: &str = "Commit";
pub const HEADER_MESSAGE: &str = "Message";
+/// Calculate maximum display width for a value using compact notation.
+/// Returns the character width (including suffix) when the value is formatted.
+///
+/// Invariant: All values return either 1 or 2, ensuring consistent column width.
+///
+/// Examples: 0 -> 1, 5 -> 1, 42 -> 2, 100 -> 2 (displays as "1C"), 1000 -> 2 (displays as "1K")
+fn max_display_width(value: usize) -> usize {
+ if value < 10 {
+ 1 // Single digit (0-9)
+ } else {
+ 2 // All values >= 10 display as 2 chars (either "42" or "4C" or "4K")
+ }
+}
+
/// Ensures a column width is at least as wide as its header.
///
/// This is the general solution for preventing header overflow: pass the header
@@ -489,25 +503,22 @@ pub fn calculate_column_widths(items: &[ListItem], fetch_ci: bool) -> LayoutMeta
let mut max_upstream_behind_digits = 0;
// Track which status positions are used across all items
- let mut status_position_mask = super::model::PositionMask::default();
+ // Always use PositionMask::FULL for consistent spacing with progressive mode
+ // (progressive mode uses FULL because it doesn't have all data upfront)
for item in items {
let commit = item.commit_details();
let counts = item.counts();
let branch_diff = item.branch_diff().diff;
let upstream = item.upstream();
- let worktree_info = item.worktree_info();
+ let worktree_info = item.worktree_data();
// Branch name
max_branch = max_branch.max(item.branch_name().width());
// Status column: git status symbols (worktrees only)
- // Position mask is collected here for selective rendering
- if let Some(info) = worktree_info {
- // Collect position usage from this item's status symbols
- let item_mask = info.status_symbols.position_mask();
- status_position_mask.merge(&item_mask);
- }
+ // Note: We always use PositionMask::FULL for rendering (see below),
+ // so we don't need to collect position masks from items anymore.
// Time
let time_str = crate::display::format_relative_time(commit.timestamp);
@@ -519,33 +530,34 @@ pub fn calculate_column_widths(items: &[ListItem], fetch_ci: bool) -> LayoutMeta
// Ahead/behind (only for non-primary items) - track digits separately
if !item.is_primary() && (counts.ahead > 0 || counts.behind > 0) {
- max_ahead_digits = max_ahead_digits.max(counts.ahead.to_string().len());
- max_behind_digits = max_behind_digits.max(counts.behind.to_string().len());
+ max_ahead_digits = max_ahead_digits.max(max_display_width(counts.ahead));
+ max_behind_digits = max_behind_digits.max(max_display_width(counts.behind));
}
// Working tree diff (worktrees only) - track digits separately
if let Some(info) = worktree_info
- && !info.working_tree_diff.is_empty()
+ && let Some(ref working_tree_diff) = info.working_tree_diff
+ && !working_tree_diff.is_empty()
{
max_wt_added_digits =
- max_wt_added_digits.max(info.working_tree_diff.added.to_string().len());
+ max_wt_added_digits.max(max_display_width(working_tree_diff.added));
max_wt_deleted_digits =
- max_wt_deleted_digits.max(info.working_tree_diff.deleted.to_string().len());
+ max_wt_deleted_digits.max(max_display_width(working_tree_diff.deleted));
}
// Branch diff (only for non-primary items) - track digits separately
if !item.is_primary() && !branch_diff.is_empty() {
- max_br_added_digits = max_br_added_digits.max(branch_diff.added.to_string().len());
+ max_br_added_digits = max_br_added_digits.max(max_display_width(branch_diff.added));
max_br_deleted_digits =
- max_br_deleted_digits.max(branch_diff.deleted.to_string().len());
+ max_br_deleted_digits.max(max_display_width(branch_diff.deleted));
}
// Upstream tracking - track digits only (not remote name yet)
if let Some((_remote_name, upstream_ahead, upstream_behind)) = upstream.active() {
max_upstream_ahead_digits =
- max_upstream_ahead_digits.max(upstream_ahead.to_string().len());
+ max_upstream_ahead_digits.max(max_display_width(upstream_ahead));
max_upstream_behind_digits =
- max_upstream_behind_digits.max(upstream_behind.to_string().len());
+ max_upstream_behind_digits.max(max_display_width(upstream_behind));
}
}
@@ -570,41 +582,22 @@ pub fn calculate_column_widths(items: &[ListItem], fetch_ci: bool) -> LayoutMeta
max_upstream_behind_digits,
);
- // Calculate Status column width: maximum rendered width across all items
- // Now that user_status is Position 4 in the grid, render_with_mask() includes it
- // Note: render_with_mask() returns styled strings with ANSI codes, so we need to
- // strip them before calculating visual width
- let status_data_width = items
- .iter()
- .filter_map(|item| {
- if let Some(info) = item.worktree_info() {
- // Worktrees: render all symbols including user_status
- let rendered = info.status_symbols.render_with_mask(&status_position_mask);
- Some(worktrunk::styling::strip_ansi_codes(&rendered).width())
- } else if let ListItem::Branch(branch_info) = item {
- // Branches: create minimal StatusSymbols with just user_status
- branch_info.user_status.as_ref().map(|user_status| {
- use crate::commands::list::model::StatusSymbols;
- let branch_symbols = StatusSymbols {
- user_status: Some(user_status.clone()),
- ..Default::default()
- };
- let rendered = branch_symbols.render_with_mask(&status_position_mask);
- worktrunk::styling::strip_ansi_codes(&rendered).width()
- })
- } else {
- None
- }
- })
- .max()
- .unwrap_or(0);
-
- // For Status column: always fit header to prevent header overflow
- // Even though we want narrow columns, we can't make them narrower than the header
- let has_status_data = status_data_width > 0;
- let final_status = fit_header(HEADER_STATUS, status_data_width);
-
- // CI status column: Always 2 chars wide
+ // Status column: Must match PositionMask::FULL width for consistent alignment with progressive mode
+ // PositionMask::FULL allocates: 5+1+1+1+1+1+2+2 = 14 chars
+ // (working_tree=5, conflicts=1, git_op=1, main_div=1, upstream_div=1,
+ // branch_state=1, worktree_attrs=2, user_status=2)
+ // This ensures buffered and progressive modes produce identical column layouts.
+ //
+ // User status is limited to single emoji or two characters (2 visual width allocation).
+ let has_status_data = items.iter().any(|item| {
+ item.status_symbols
+ .as_ref()
+ .map(|s| !s.is_empty())
+ .unwrap_or(false)
+ });
+ let final_status = fit_header(HEADER_STATUS, 14);
+
+ // CI status column: Always 2 chars wide (single symbol "●")
// Only show if we attempted to fetch CI data (regardless of whether any items have status)
let has_ci_status = fetch_ci && items.iter().any(|item| item.pr_status().is_some());
let ci_status_width = 2; // Fixed width
@@ -633,47 +626,27 @@ pub fn calculate_column_widths(items: &[ListItem], fetch_ci: bool) -> LayoutMeta
LayoutMetadata {
widths,
data_flags,
- status_position_mask,
+ status_position_mask: super::model::PositionMask::FULL,
}
}
-/// Calculate responsive layout based on terminal width
-pub fn calculate_responsive_layout(
- items: &[ListItem],
+/// Allocate columns using priority-based allocation logic.
+///
+/// This is the core allocation algorithm used by both `calculate_responsive_layout()`
+/// (with actual data-based widths) and `calculate_layout_from_basics()` (with estimated widths).
+fn allocate_columns_with_priority(
+ metadata: &LayoutMetadata,
show_full: bool,
fetch_ci: bool,
+ max_path_width: usize,
+ commit_width: usize,
+ terminal_width: usize,
+ common_prefix: PathBuf,
) -> LayoutConfig {
- let terminal_width = get_terminal_width();
- let paths: Vec<&Path> = items
- .iter()
- .filter_map(|item| item.worktree_path().map(|path| path.as_path()))
- .collect();
- let common_prefix = find_common_prefix(&paths);
-
- // Calculate ideal column widths and track which columns have data
- let metadata = calculate_column_widths(items, fetch_ci);
- let ideal_widths = metadata.widths;
- let data_flags = metadata.data_flags;
- let status_position_mask = metadata.status_position_mask;
-
- // Calculate actual maximum path width (after common prefix removal)
- let path_data_width = items
- .iter()
- .filter_map(|item| item.worktree_path())
- .map(|path| {
- use crate::display::shorten_path;
- use unicode_width::UnicodeWidthStr;
- shorten_path(path.as_path(), &common_prefix).width()
- })
- .max()
- .unwrap_or(0);
- let max_path_width = fit_header(HEADER_PATH, path_data_width);
-
- let commit_width = fit_header(HEADER_COMMIT, COMMIT_HASH_WIDTH);
-
let spacing = 2;
let mut remaining = terminal_width;
+ // Build candidates with priorities
let mut candidates: Vec<ColumnCandidate> = COLUMN_SPECS
.iter()
.filter(|spec| {
@@ -681,7 +654,7 @@ pub fn calculate_responsive_layout(
})
.map(|spec| ColumnCandidate {
spec,
- priority: if spec.kind.has_data(&data_flags) {
+ priority: if spec.kind.has_data(&metadata.data_flags) {
spec.base_priority
} else {
spec.base_priority + EMPTY_PENALTY
@@ -694,7 +667,7 @@ pub fn calculate_responsive_layout(
// Store which candidates have data for later calculation of hidden columns
let candidates_with_data: Vec<_> = candidates
.iter()
- .map(|c| (c.spec.kind, c.spec.kind.has_data(&data_flags)))
+ .map(|c| (c.spec.kind, c.spec.kind.has_data(&metadata.data_flags)))
.collect();
const MIN_MESSAGE: usize = 20;
@@ -703,9 +676,11 @@ pub fn calculate_responsive_layout(
let mut pending: Vec<PendingColumn> = Vec::new();
+ // Allocate columns in priority order
for candidate in candidates {
let spec = candidate.spec;
+ // Special handling for Message column
if spec.kind == ColumnKind::Message {
let is_first = pending.is_empty();
let spacing_cost = if is_first { 0 } else { spacing };
@@ -718,9 +693,9 @@ pub fn calculate_responsive_layout(
let mut message_width = 0;
if available >= PREFERRED_MESSAGE {
- message_width = PREFERRED_MESSAGE.min(ideal_widths.message);
+ message_width = PREFERRED_MESSAGE.min(metadata.widths.message);
} else if available >= MIN_MESSAGE {
- message_width = available.min(ideal_widths.message);
+ message_width = available.min(metadata.widths.message);
}
if message_width > 0 {
@@ -735,7 +710,8 @@ pub fn calculate_responsive_layout(
continue;
}
- let Some(ideal) = ideal_for_column(spec, &ideal_widths, max_path_width, commit_width)
+ // For non-message columns
+ let Some(ideal) = ideal_for_column(spec, &metadata.widths, max_path_width, commit_width)
else {
continue;
};
@@ -750,6 +726,7 @@ pub fn calculate_responsive_layout(
}
}
+ // Expand message column with leftover space
let mut max_message_len = 0;
if let Some(message_col) = pending
.iter_mut()
@@ -762,8 +739,10 @@ pub fn calculate_responsive_layout(
max_message_len = message_col.width;
}
+ // Sort by display index to maintain correct visual order
pending.sort_by_key(|col| col.spec.display_index);
+ // Build final column layouts with positions
let gap = 2;
let mut position = 0;
let mut columns = Vec::new();
@@ -798,10 +777,188 @@ pub fn calculate_responsive_layout(
common_prefix,
max_message_len,
hidden_nonempty_count,
- status_position_mask,
+ status_position_mask: metadata.status_position_mask,
}
}
+/// Calculate responsive layout based on terminal width
+pub fn calculate_responsive_layout(
+ items: &[ListItem],
+ show_full: bool,
+ fetch_ci: bool,
+) -> LayoutConfig {
+ let terminal_width = get_terminal_width();
+ let paths: Vec<&Path> = items
+ .iter()
+ .filter_map(|item| item.worktree_path().map(|path| path.as_path()))
+ .collect();
+ let common_prefix = find_common_prefix(&paths);
+
+ // Calculate ideal column widths and track which columns have data
+ let metadata = calculate_column_widths(items, fetch_ci);
+
+ // Calculate actual maximum path width (after common prefix removal)
+ let path_data_width = items
+ .iter()
+ .filter_map(|item| item.worktree_path())
+ .map(|path| {
+ use crate::display::shorten_path;
+ use unicode_width::UnicodeWidthStr;
+ shorten_path(path.as_path(), &common_prefix).width()
+ })
+ .max()
+ .unwrap_or(0);
+ let max_path_width = fit_header(HEADER_PATH, path_data_width);
+
+ let commit_width = fit_header(HEADER_COMMIT, COMMIT_HASH_WIDTH);
+
+ allocate_columns_with_priority(
+ &metadata,
+ show_full,
+ fetch_ci,
+ max_path_width,
+ commit_width,
+ terminal_width,
+ common_prefix,
+ )
+}
+
+/// Calculate responsive layout from basic worktree info with estimated column widths.
+///
+/// This is used for progressive rendering where we want to show the layout immediately
+/// before collecting full data. We use:
+/// - Actual branch names and paths from worktree list (fast operation)
+/// - Branch names from branches without worktrees (when --branches is used)
+/// - Estimated widths for columns that require expensive git operations
+///
+/// The estimates are generous to minimize truncation:
+/// - Status: 5 chars (covers "≡ 🔧" and most common patterns)
+/// - HEAD±: 6 chars (covers "+12 -5" and similar)
+/// - main↕: 6 chars (covers "↑23 ↓5")
+/// - Remote⇅: 7 chars (header width, covers most cases)
+/// - Age: 15 chars (covers "3 months ago")
+/// - Commit: 8 chars (fixed)
+/// - Message: flexible (20-100 chars)
+///
+/// Note: This is work-in-progress for improved progressive rendering.
+pub fn calculate_layout_from_basics(
+ worktrees: &[worktrunk::git::Worktree],
+ branch_names: &[String],
+ show_full: bool,
+ fetch_ci: bool,
+) -> LayoutConfig {
+ let terminal_width = get_terminal_width();
+
+ // Calculate common prefix from paths
+ let paths: Vec<&Path> = worktrees.iter().map(|wt| wt.path.as_path()).collect();
+ let common_prefix = find_common_prefix(&paths);
+
+ // Calculate actual widths for things we know
+ // Include both worktree branch names AND branch names without worktrees
+ let max_worktree_branch = worktrees
+ .iter()
+ .filter_map(|wt| wt.branch.as_deref())
+ .map(|b| b.width())
+ .max()
+ .unwrap_or(0);
+
+ let max_standalone_branch = branch_names.iter().map(|b| b.width()).max().unwrap_or(0);
+
+ let max_branch = fit_header(
+ HEADER_BRANCH,
+ max_worktree_branch.max(max_standalone_branch),
+ );
+
+ let path_data_width = worktrees
+ .iter()
+ .map(|wt| {
+ use crate::display::shorten_path;
+ shorten_path(wt.path.as_path(), &common_prefix).width()
+ })
+ .max()
+ .unwrap_or(0);
+ let max_path_width = fit_header(HEADER_PATH, path_data_width);
+
+ // Fixed widths for slow columns (require expensive git operations)
+ // These are predetermined widths, not based on actual data
+ // Values exceeding these widths will be shown with K/M suffixes
+ //
+ // Status column: Must match PositionMask::FULL width for consistent alignment
+ // PositionMask::FULL allocates: 5+1+1+1+1+1+2+2 = 14 chars
+ // (working_tree=5, conflicts=1, git_op=1, main_div=1, upstream_div=1,
+ // branch_state=1, worktree_attrs=2, user_status=2)
+ let status_fixed = fit_header(HEADER_STATUS, 14);
+ let working_diff_fixed = fit_header(HEADER_WORKING_DIFF, 9); // "+999 -999" (9 chars)
+ let ahead_behind_fixed = fit_header(HEADER_AHEAD_BEHIND, 7); // "↑99 ↓99" (7 chars)
+ let branch_diff_fixed = fit_header(HEADER_BRANCH_DIFF, 9); // "+999 -999" (9 chars)
+ let upstream_fixed = fit_header(HEADER_UPSTREAM, 7); // "↑99 ↓99" (7 chars)
+ let age_estimate = 15; // "3 months ago" (fast to compute)
+ let commit_width = fit_header(HEADER_COMMIT, COMMIT_HASH_WIDTH); // Fixed 8 chars
+ // CI column shows only indicator symbol (●/○/◐)
+ let ci_estimate = fit_header(HEADER_CI, 1);
+
+ // For progressive rendering, assume columns will have data
+ // (better to show and hide than to not show)
+ let data_flags = ColumnDataFlags {
+ status: true,
+ working_diff: true,
+ ahead_behind: true,
+ branch_diff: show_full,
+ upstream: true,
+ ci_status: fetch_ci,
+ };
+
+ // Build ColumnWidths with fixed widths for slow columns
+ let estimated_widths = ColumnWidths {
+ branch: max_branch,
+ status: status_fixed,
+ time: age_estimate,
+ ci_status: ci_estimate,
+ message: 50, // Will be flexible later
+ ahead_behind: DiffWidths {
+ total: ahead_behind_fixed,
+ added_digits: 2, // Compact notation at 100+
+ deleted_digits: 2,
+ },
+ working_diff: DiffWidths {
+ total: working_diff_fixed,
+ added_digits: 2, // Compact notation at 100+
+ deleted_digits: 2,
+ },
+ branch_diff: DiffWidths {
+ total: branch_diff_fixed,
+ added_digits: 2, // Compact notation at 100+
+ deleted_digits: 2,
+ },
+ upstream: DiffWidths {
+ total: upstream_fixed,
+ added_digits: 2, // Compact notation at 100+
+ deleted_digits: 2,
+ },
+ };
+
+ // Use full position mask for progressive rendering
+ // (we don't know which positions will be needed until data is collected)
+ let status_position_mask = super::model::PositionMask::FULL;
+
+ // Build metadata for allocation
+ let metadata = LayoutMetadata {
+ widths: estimated_widths,
+ data_flags,
+ status_position_mask,
+ };
+
+ allocate_columns_with_priority(
+ &metadata,
+ show_full,
+ fetch_ci,
+ max_path_width,
+ commit_width,
+ terminal_width,
+ common_prefix,
+ )
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -812,42 +969,47 @@ mod tests {
#[test]
fn test_column_width_calculation_with_unicode() {
use crate::commands::list::model::{
- AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, StatusSymbols,
- UpstreamStatus, WorktreeInfo,
+ AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, ItemKind, StatusSymbols,
+ UpstreamStatus, WorktreeData,
};
- let info1 = WorktreeInfo {
- path: PathBuf::from("/test"),
+ let item1 = super::ListItem {
head: "abc123".to_string(),
branch: Some("main".to_string()),
- bare: false,
- detached: false,
- locked: None,
- prunable: None,
- commit: CommitDetails {
+ commit: Some(CommitDetails {
timestamp: 0,
commit_message: "Test".to_string(),
- },
- counts: AheadBehind {
+ }),
+ counts: Some(AheadBehind {
ahead: 3,
behind: 2,
- },
- working_tree_diff: LineDiff::from((100, 50)),
- working_tree_diff_with_main: Some(LineDiff::default()),
- branch_diff: BranchDiffTotals {
+ }),
+ branch_diff: Some(BranchDiffTotals {
diff: LineDiff::from((200, 30)),
- },
- is_primary: false,
- upstream: UpstreamStatus::from_parts(Some("origin".to_string()), 4, 0),
- worktree_state: None,
+ }),
+ upstream: Some(UpstreamStatus::from_parts(Some("origin".to_string()), 4, 0)),
pr_status: None,
- has_conflicts: false,
- status_symbols: StatusSymbols::default(),
+ has_conflicts: Some(false),
+ user_status: None,
+ status_symbols: Some(StatusSymbols::default()),
display: DisplayFields::default(),
- working_diff_display: None,
+ kind: ItemKind::Worktree(Box::new(WorktreeData {
+ path: PathBuf::from("/test"),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ working_tree_diff: Some(LineDiff::from((100, 50))),
+ working_tree_diff_with_main: Some(Some(LineDiff::default())),
+ worktree_state: None,
+ is_primary: false,
+ working_tree_symbols: Some(String::new()),
+ is_dirty: Some(false),
+ working_diff_display: None,
+ })),
};
- let metadata = calculate_column_widths(&[super::ListItem::Worktree(info1)], false);
+ let metadata = calculate_column_widths(&[item1], false);
let widths = metadata.widths;
// "↑3 ↓2" has format "↑3 ↓2" = 1+1+1+1+1 = 5, header "main↕" is also 5
@@ -855,24 +1017,39 @@ mod tests {
widths.ahead_behind.total, 5,
"Ahead/behind column should fit header 'main↕' (width 5)"
);
- assert_eq!(widths.ahead_behind.added_digits, 1, "3 has 1 digit");
- assert_eq!(widths.ahead_behind.deleted_digits, 1, "2 has 1 digit");
+ assert_eq!(widths.ahead_behind.added_digits, 1, "3 displays as 1 digit");
+ assert_eq!(
+ widths.ahead_behind.deleted_digits, 1,
+ "2 displays as 1 digit"
+ );
- // "+100 -50" has width 8, but header "HEAD±" is 5, so column width is 8
+ // "+1C -50" has width 7 (compact notation), header "HEAD±" is 5, so column width is 7
assert_eq!(
- widths.working_diff.total, 8,
- "Working diff column should fit header 'HEAD±' (width 5)"
+ widths.working_diff.total, 7,
+ "Working diff column should fit data '+1C -50' (width 7)"
+ );
+ assert_eq!(
+ widths.working_diff.added_digits, 2,
+ "100 displays as 2 digits (1C)"
+ );
+ assert_eq!(
+ widths.working_diff.deleted_digits, 2,
+ "50 displays as 2 digits"
);
- assert_eq!(widths.working_diff.added_digits, 3, "100 has 3 digits");
- assert_eq!(widths.working_diff.deleted_digits, 2, "50 has 2 digits");
- // "+200 -30" has width 8, header "main…±" is 6, so column width is 8
+ // "+2C -30" has width 7 (compact notation), header "main…±" is 6, so column width is 7
+ assert_eq!(
+ widths.branch_diff.total, 7,
+ "Branch diff column should fit data '+2C -30' (width 7)"
+ );
+ assert_eq!(
+ widths.branch_diff.added_digits, 2,
+ "200 displays as 2 digits (2C)"
+ );
assert_eq!(
- widths.branch_diff.total, 8,
- "Branch diff column should fit header 'main…±' (width 6)"
+ widths.branch_diff.deleted_digits, 2,
+ "30 displays as 2 digits"
);
- assert_eq!(widths.branch_diff.added_digits, 3, "200 has 3 digits");
- assert_eq!(widths.branch_diff.deleted_digits, 2, "30 has 2 digits");
// Upstream: "↑4 ↓0" = "↑" (1) + "4" (1) + " " (1) + "↓" (1) + "0" (1) = 5, but header "Remote⇅" = 7
assert_eq!(
@@ -883,46 +1060,98 @@ mod tests {
assert_eq!(widths.upstream.deleted_digits, 1, "0 has 1 digit");
}
+ #[test]
+ fn test_max_display_width_edge_cases() {
+ // Single digits (0-9) display as 1 character
+ assert_eq!(max_display_width(0), 1, "0 displays as '0' (1 char)");
+ assert_eq!(max_display_width(5), 1, "5 displays as '5' (1 char)");
+ assert_eq!(max_display_width(9), 1, "9 displays as '9' (1 char)");
+
+ // Two digits (10-99) display as 2 characters
+ assert_eq!(max_display_width(10), 2, "10 displays as '10' (2 chars)");
+ assert_eq!(max_display_width(42), 2, "42 displays as '42' (2 chars)");
+ assert_eq!(max_display_width(99), 2, "99 displays as '99' (2 chars)");
+
+ // Hundreds (100-999) display as 2 characters with C suffix
+ assert_eq!(max_display_width(100), 2, "100 displays as '1C' (2 chars)");
+ assert_eq!(max_display_width(648), 2, "648 displays as '6C' (2 chars)");
+ assert_eq!(max_display_width(999), 2, "999 displays as '9C' (2 chars)");
+
+ // Thousands (1000-9999) display as 2 characters with K suffix
+ assert_eq!(
+ max_display_width(1000),
+ 2,
+ "1000 displays as '1K' (2 chars)"
+ );
+ assert_eq!(
+ max_display_width(1500),
+ 2,
+ "1500 displays as '1K' (2 chars)"
+ );
+ assert_eq!(
+ max_display_width(9999),
+ 2,
+ "9999 displays as '9K' (2 chars)"
+ );
+
+ // Large values (10000+) cap at 2 characters
+ assert_eq!(
+ max_display_width(10000),
+ 2,
+ "10000 displays as '9K' (capped at 2 chars)"
+ );
+ assert_eq!(
+ max_display_width(100000),
+ 2,
+ "100000 displays as '9K' (capped at 2 chars)"
+ );
+ }
+
#[test]
fn test_visible_columns_follow_gap_rule() {
use crate::commands::list::model::{
- AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, StatusSymbols,
- UpstreamStatus, WorktreeInfo,
+ AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, ItemKind, StatusSymbols,
+ UpstreamStatus, WorktreeData,
};
// Create test data with specific widths to verify position calculation
- let info = WorktreeInfo {
- path: PathBuf::from("/test/path"),
+ let item = super::ListItem {
head: "abc12345".to_string(),
branch: Some("feature".to_string()),
- bare: false,
- detached: false,
- locked: None,
- prunable: None,
- commit: CommitDetails {
+ commit: Some(CommitDetails {
timestamp: 1234567890,
commit_message: "Test commit message".to_string(),
- },
- counts: AheadBehind {
+ }),
+ counts: Some(AheadBehind {
ahead: 5,
behind: 10,
- },
- working_tree_diff: LineDiff::from((100, 50)),
- working_tree_diff_with_main: Some(LineDiff::default()),
- branch_diff: BranchDiffTotals {
+ }),
+ branch_diff: Some(BranchDiffTotals {
diff: LineDiff::from((200, 30)),
- },
- is_primary: false,
- upstream: UpstreamStatus::from_parts(Some("origin".to_string()), 4, 2),
- worktree_state: None,
+ }),
+ upstream: Some(UpstreamStatus::from_parts(Some("origin".to_string()), 4, 2)),
pr_status: None,
- has_conflicts: false,
- status_symbols: StatusSymbols::default(),
+ has_conflicts: Some(false),
+ user_status: None,
+ status_symbols: Some(StatusSymbols::default()),
display: DisplayFields::default(),
- working_diff_display: None,
+ kind: ItemKind::Worktree(Box::new(WorktreeData {
+ path: PathBuf::from("/test/path"),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ working_tree_diff: Some(LineDiff::from((100, 50))),
+ working_tree_diff_with_main: Some(Some(LineDiff::default())),
+ worktree_state: None,
+ is_primary: false,
+ working_tree_symbols: Some(String::new()),
+ is_dirty: Some(false),
+ working_diff_display: None,
+ })),
};
- let items = vec![super::ListItem::Worktree(info)];
+ let items = vec![item];
let layout = calculate_responsive_layout(&items, false, false);
assert!(
@@ -960,43 +1189,48 @@ mod tests {
#[test]
fn test_column_positions_with_empty_columns() {
use crate::commands::list::model::{
- AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, StatusSymbols,
- UpstreamStatus, WorktreeInfo,
+ AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, ItemKind, StatusSymbols,
+ UpstreamStatus, WorktreeData,
};
// Create minimal data - most columns will be empty
- let info = WorktreeInfo {
- path: PathBuf::from("/test"),
+ let item = super::ListItem {
head: "abc12345".to_string(),
branch: Some("main".to_string()),
- bare: false,
- detached: false,
- locked: None,
- prunable: None,
- commit: CommitDetails {
+ commit: Some(CommitDetails {
timestamp: 1234567890,
commit_message: "Test".to_string(),
- },
- counts: AheadBehind {
+ }),
+ counts: Some(AheadBehind {
ahead: 0,
behind: 0,
- },
- working_tree_diff: LineDiff::default(),
- working_tree_diff_with_main: Some(LineDiff::default()),
- branch_diff: BranchDiffTotals {
+ }),
+ branch_diff: Some(BranchDiffTotals {
diff: LineDiff::default(),
- },
- is_primary: true, // Primary worktree: no ahead/behind shown
- upstream: UpstreamStatus::default(),
- worktree_state: None,
+ }),
+ upstream: Some(UpstreamStatus::default()),
pr_status: None,
- has_conflicts: false,
- status_symbols: StatusSymbols::default(),
+ has_conflicts: Some(false),
+ user_status: None,
+ status_symbols: Some(StatusSymbols::default()),
display: DisplayFields::default(),
- working_diff_display: None,
+ kind: ItemKind::Worktree(Box::new(WorktreeData {
+ path: PathBuf::from("/test"),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ working_tree_diff: Some(LineDiff::default()),
+ working_tree_diff_with_main: Some(Some(LineDiff::default())),
+ worktree_state: None,
+ is_primary: true, // Primary worktree: no ahead/behind shown
+ working_tree_symbols: Some(String::new()),
+ is_dirty: Some(false),
+ working_diff_display: None,
+ })),
};
- let items = vec![super::ListItem::Worktree(info)];
+ let items = vec![item];
let layout = calculate_responsive_layout(&items, false, false);
assert!(
@@ -1023,45 +1257,50 @@ mod tests {
#[test]
fn test_consecutive_empty_columns_have_low_priority() {
use crate::commands::list::model::{
- AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, StatusSymbols,
- UpstreamStatus, WorktreeInfo,
+ AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, ItemKind, StatusSymbols,
+ UpstreamStatus, WorktreeData,
};
// Create data where multiple consecutive columns are empty:
// visible(branch) → empty(working_diff) → empty(ahead_behind) → empty(branch_diff)
// → empty(states) → visible(path)
- let info = WorktreeInfo {
- path: PathBuf::from("/test/worktree"),
+ let item = super::ListItem {
head: "abc12345".to_string(),
branch: Some("feature-x".to_string()),
- bare: false,
- detached: false,
- locked: None,
- prunable: None,
- commit: CommitDetails {
+ commit: Some(CommitDetails {
timestamp: 1234567890,
commit_message: "Test commit".to_string(),
- },
- counts: AheadBehind {
+ }),
+ counts: Some(AheadBehind {
ahead: 0,
behind: 0,
- },
- working_tree_diff: LineDiff::default(), // Empty: no dirty changes
- working_tree_diff_with_main: Some(LineDiff::default()),
- branch_diff: BranchDiffTotals {
+ }),
+ branch_diff: Some(BranchDiffTotals {
diff: LineDiff::default(),
- }, // Empty: no diff
- is_primary: true, // Empty: no ahead/behind for primary
- upstream: UpstreamStatus::default(), // Empty: no upstream
- worktree_state: None, // Empty: no state
+ }), // Empty: no diff
+ upstream: Some(UpstreamStatus::default()), // Empty: no upstream
pr_status: None,
- has_conflicts: false,
- status_symbols: StatusSymbols::default(),
+ has_conflicts: Some(false),
+ user_status: None,
+ status_symbols: Some(StatusSymbols::default()),
display: DisplayFields::default(),
- working_diff_display: None,
+ kind: ItemKind::Worktree(Box::new(WorktreeData {
+ path: PathBuf::from("/test/worktree"),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ working_tree_diff: Some(LineDiff::default()), // Empty: no dirty changes
+ working_tree_diff_with_main: Some(Some(LineDiff::default())),
+ worktree_state: None, // Empty: no state
+ is_primary: true, // Empty: no ahead/behind for primary
+ working_tree_symbols: Some(String::new()),
+ is_dirty: Some(false),
+ working_diff_display: None,
+ })),
};
- let items = vec![super::ListItem::Worktree(info)];
+ let items = vec![item];
let layout = calculate_responsive_layout(&items, false, false);
let path_visible = layout
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 6205faaf7..d209bf2d9 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -75,39 +75,64 @@
//! - Minimize uncommitted changes across worktrees (each dirty worktree adds diff overhead)
mod ci_status;
+pub(crate) mod collect;
+mod collect_progressive_impl;
mod columns;
mod layout;
pub mod model;
+mod progressive;
mod render;
#[cfg(test)]
mod spacing_test;
-#[cfg(test)]
-mod status_column_tests;
-use super::repository_ext::RepositoryCliExt;
-use columns::ColumnKind;
use layout::{LayoutConfig, calculate_responsive_layout};
-use model::{DisplayFields, ListData, ListItem};
+use model::{ListData, ListItem};
+use progressive::RenderMode;
use worktrunk::git::{GitError, Repository};
-use worktrunk::styling::{INFO_EMOJI, println};
pub fn handle_list(
format: crate::OutputFormat,
show_branches: bool,
show_full: bool,
+ progressive: bool,
+ no_progressive: bool,
+ directive_mode: bool,
) -> Result<(), GitError> {
let repo = Repository::current();
+
+ let fetch_ci = show_full; // Only fetch CI with --full (expensive)
+ let check_conflicts = show_full; // Only check conflicts with --full (expensive)
+
+ // Detect whether to show progress bars (only for table format)
+ let show_progress = match format {
+ crate::OutputFormat::Table => {
+ RenderMode::detect(progressive, no_progressive, directive_mode)
+ == RenderMode::Progressive
+ }
+ crate::OutputFormat::Json => false, // JSON never shows progress
+ };
+
+ let list_data = collect::collect(
+ &repo,
+ show_branches,
+ show_full,
+ fetch_ci,
+ check_conflicts,
+ show_progress,
+ )?;
+
let Some(ListData {
items,
current_worktree_path,
- }) = repo.gather_list_data(show_branches, show_full, show_full)?
+ }) = list_data
else {
return Ok(());
};
match format {
crate::OutputFormat::Json => {
+ // Enrich with formatted display fields for JSON output
let enriched_items: Vec<_> = items
.into_iter()
.map(ListItem::with_display_fields)
@@ -116,15 +141,28 @@ pub fn handle_list(
let json = serde_json::to_string_pretty(&enriched_items).map_err(|e| {
GitError::CommandFailed(format!("Failed to serialize to JSON: {}", e))
})?;
- println!("{}", json);
+ crate::output::raw(json)?;
}
crate::OutputFormat::Table => {
- let layout = calculate_responsive_layout(&items, show_full, show_full);
- layout.format_header_line();
- for item in &items {
- layout.format_list_item_line(item, current_worktree_path.as_ref());
+ let layout = calculate_responsive_layout(&items, show_full, fetch_ci);
+
+ // Progressive mode renders table during collection; buffered mode renders here
+ if !show_progress {
+ crate::output::raw_terminal(layout.format_header_line())?;
+ for item in &items {
+ crate::output::raw_terminal(
+ layout.format_list_item_line(item, current_worktree_path.as_ref()),
+ )?;
+ }
+ }
+
+ // Summary:
+ // - progressive + TTY: already shown via footer.finish_with_message
+ // - progressive + non-TTY: already shown via multi.suspend() in collect.rs
+ // - buffered: render here
+ if !show_progress {
+ layout.render_summary(&items, show_branches)?;
}
- layout.render_summary(&items, show_branches);
}
}
@@ -132,7 +170,7 @@ pub fn handle_list(
}
#[derive(Default)]
-struct SummaryMetrics {
+pub(super) struct SummaryMetrics {
worktrees: usize,
branches: usize,
dirty_worktrees: usize,
@@ -140,7 +178,7 @@ struct SummaryMetrics {
}
impl SummaryMetrics {
- fn from_items(items: &[ListItem]) -> Self {
+ pub(super) fn from_items(items: &[ListItem]) -> Self {
let mut metrics = Self::default();
for item in items {
metrics.update(item);
@@ -149,9 +187,14 @@ impl SummaryMetrics {
}
fn update(&mut self, item: &ListItem) {
- if let Some(info) = item.worktree_info() {
+ if let Some(info) = item.worktree_data() {
self.worktrees += 1;
- if !info.working_tree_diff.is_empty() {
+ if info
+ .working_tree_diff
+ .as_ref()
+ .map(|d| !d.is_empty())
+ .unwrap_or(false)
+ {
self.dirty_worktrees += 1;
}
} else {
@@ -164,7 +207,11 @@ impl SummaryMetrics {
}
}
- fn summary_parts(&self, include_branches: bool, hidden_columns: usize) -> Vec<String> {
+ pub(super) fn summary_parts(
+ &self,
+ include_branches: bool,
+ hidden_columns: usize,
+ ) -> Vec<String> {
let mut parts = Vec::new();
if include_branches {
@@ -198,63 +245,76 @@ impl SummaryMetrics {
}
}
+/// Format a summary message for the given items (used by both collect.rs and mod.rs)
+pub(crate) fn format_summary_message(
+ items: &[ListItem],
+ show_branches: bool,
+ hidden_nonempty_count: usize,
+) -> String {
+ use anstyle::Style;
+ use worktrunk::styling::INFO_EMOJI;
+
+ let metrics = SummaryMetrics::from_items(items);
+ let dim = Style::new().dimmed();
+ let summary = metrics
+ .summary_parts(show_branches, hidden_nonempty_count)
+ .join(", ");
+ format!("{INFO_EMOJI} {dim}Showing {summary}{dim:#}")
+}
+
impl LayoutConfig {
- fn render_summary(&self, items: &[ListItem], include_branches: bool) {
- use anstyle::Style;
+ fn render_summary(&self, items: &[ListItem], include_branches: bool) -> Result<(), GitError> {
+ use worktrunk::styling::{HINT, INFO_EMOJI};
if items.is_empty() {
- println!();
- use worktrunk::styling::{HINT, HINT_EMOJI};
- println!("{HINT_EMOJI} {HINT}No worktrees found{HINT:#}");
- println!("{HINT_EMOJI} {HINT}Create one with: wt switch --create <branch>{HINT:#}");
- return;
+ crate::output::raw_terminal("")?;
+ crate::output::hint(format!("{HINT}No worktrees found{HINT:#}"))?;
+ crate::output::hint(format!(
+ "{HINT}Create one with: wt switch --create <branch>{HINT:#}"
+ ))?;
+ return Ok(());
}
let metrics = SummaryMetrics::from_items(items);
- println!();
+ use anstyle::Style;
let dim = Style::new().dimmed();
let summary = metrics
.summary_parts(include_branches, self.hidden_nonempty_count)
.join(", ");
- println!("{INFO_EMOJI} {dim}Showing {summary}{dim:#}");
+
+ crate::output::raw_terminal("")?;
+ crate::output::raw_terminal(format!("{INFO_EMOJI} {dim}Showing {summary}{dim:#}"))?;
+ Ok(())
}
}
impl ListItem {
- /// Enrich a ListItem with display fields for json-pretty format.
+ /// Enrich a ListItem with formatted display fields for JSON output.
+ ///
+ /// This converts the progressive display format (None = use actual data)
+ /// into fully formatted ANSI strings for all fields.
fn with_display_fields(mut self) -> Self {
- match &mut self {
- ListItem::Worktree(info) => {
- let mut display = DisplayFields::from_common_fields(
- &info.counts,
- &info.branch_diff,
- &info.upstream,
- &info.pr_status,
- );
- // Preserve status_display that was set in constructor
- display.status_display = info.display.status_display.clone();
- info.display = display;
-
- // Working tree specific field
- info.working_diff_display = ColumnKind::WorkingDiff.format_diff_plain(
- info.working_tree_diff.added,
- info.working_tree_diff.deleted,
- );
- }
- ListItem::Branch(info) => {
- let mut display = DisplayFields::from_common_fields(
- &info.counts,
- &info.branch_diff,
- &info.upstream,
- &info.pr_status,
- );
- // Preserve status_display that was set in constructor
- display.status_display = info.display.status_display.clone();
- info.display = display;
- }
+ // Create formatted display fields from common fields
+ let mut display = model::DisplayFields::from_common_fields(
+ &self.counts,
+ &self.branch_diff,
+ &self.upstream,
+ &self.pr_status,
+ );
+
+ // Preserve status_display (git symbols + user status)
+ display.status_display = self.display.status_display.clone();
+
+ // Handle worktree-specific field
+ if let model::ItemKind::Worktree(data) = &mut self.kind {
+ data.working_diff_display = data.working_tree_diff.as_ref().and_then(|diff| {
+ columns::ColumnKind::WorkingDiff.format_diff_plain(diff.added, diff.deleted)
+ });
}
+
+ self.display = display;
self
}
}
diff --git a/src/commands/list/model.rs b/src/commands/list/model.rs
index a9cf44299..9aae164c8 100644
--- a/src/commands/list/model.rs
+++ b/src/commands/list/model.rs
@@ -1,12 +1,12 @@
use std::path::PathBuf;
-use worktrunk::git::{GitError, LineDiff, Repository};
+use worktrunk::git::LineDiff;
use super::ci_status::PrStatus;
use super::columns::ColumnKind;
/// Display fields shared between WorktreeInfo and BranchInfo
/// These contain formatted strings with ANSI colors for json-pretty output
-#[derive(serde::Serialize, Default)]
+#[derive(Clone, serde::Serialize, Default)]
pub struct DisplayFields {
#[serde(skip_serializing_if = "Option::is_none")]
pub commits_display: Option<String>,
@@ -22,25 +22,28 @@ pub struct DisplayFields {
impl DisplayFields {
pub(crate) fn from_common_fields(
- counts: &AheadBehind,
- branch_diff: &BranchDiffTotals,
- upstream: &UpstreamStatus,
- pr_status: &Option<PrStatus>,
+ counts: &Option<AheadBehind>,
+ branch_diff: &Option<BranchDiffTotals>,
+ upstream: &Option<UpstreamStatus>,
+ _pr_status: &Option<Option<PrStatus>>,
) -> Self {
- let commits_display =
- ColumnKind::AheadBehind.format_diff_plain(counts.ahead, counts.behind);
+ let commits_display = counts
+ .as_ref()
+ .and_then(|c| ColumnKind::AheadBehind.format_diff_plain(c.ahead, c.behind));
- let branch_diff_display = ColumnKind::BranchDiff
- .format_diff_plain(branch_diff.diff.added, branch_diff.diff.deleted);
+ let branch_diff_display = branch_diff.as_ref().and_then(|bd| {
+ ColumnKind::BranchDiff.format_diff_plain(bd.diff.added, bd.diff.deleted)
+ });
- let upstream_display =
- upstream
- .active()
- .and_then(|(_, upstream_ahead, upstream_behind)| {
- ColumnKind::Upstream.format_diff_plain(upstream_ahead, upstream_behind)
- });
+ let upstream_display = upstream.as_ref().and_then(|u| {
+ u.active().and_then(|(_, upstream_ahead, upstream_behind)| {
+ ColumnKind::Upstream.format_diff_plain(upstream_ahead, upstream_behind)
+ })
+ });
- let ci_status_display = pr_status.as_ref().map(PrStatus::format_plain);
+ // CI column shows only the indicator (●/○/◐), not text
+ // Let render.rs handle it via render_indicator()
+ let ci_status_display = None;
Self {
commits_display,
@@ -52,165 +55,94 @@ impl DisplayFields {
}
}
-#[derive(serde::Serialize)]
-pub struct WorktreeInfo {
- // Worktree identity fields (flattened from worktrunk::git::Worktree)
+/// Type-specific data for worktrees
+#[derive(Clone, serde::Serialize, Default)]
+pub struct WorktreeData {
pub path: PathBuf,
- #[serde(rename = "head_sha")]
- pub head: String,
- pub branch: Option<String>,
pub bare: bool,
pub detached: bool,
pub locked: Option<String>,
pub prunable: Option<String>,
-
- // Commit details
- #[serde(flatten)]
- pub commit: CommitDetails,
-
- // Divergence from main
- #[serde(flatten)]
- pub counts: AheadBehind,
- #[serde(flatten)]
- pub branch_diff: BranchDiffTotals,
-
- // Working tree state
- pub working_tree_diff: LineDiff,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub working_tree_diff: Option<LineDiff>,
/// Diff between working tree and main branch.
- /// `None` means "not computed" (optimization: skipped when trees differ).
- /// `Some((0, 0))` means working tree matches main exactly.
- /// `Some((a, d))` means a lines added, d deleted vs main.
+ /// `None` means "not computed yet" or "not computed" (optimization: skipped when trees differ).
+ /// `Some(Some((0, 0)))` means working tree matches main exactly.
+ /// `Some(Some((a, d)))` means a lines added, d deleted vs main.
+ /// `Some(None)` means computation was skipped.
#[serde(skip_serializing_if = "Option::is_none")]
- pub working_tree_diff_with_main: Option<LineDiff>,
+ pub working_tree_diff_with_main: Option<Option<LineDiff>>,
pub worktree_state: Option<String>,
- pub has_conflicts: bool,
-
- // Metadata
pub is_primary: bool,
-
- // Remote/upstream
- #[serde(flatten)]
- pub upstream: UpstreamStatus,
-
- // Status
- pub pr_status: Option<PrStatus>,
- /// Git status symbols (=, ↑, ↓, ⇡, ⇣, ?, !, +, », ✘) including user-defined status
- pub status_symbols: StatusSymbols,
-
- // Display fields for json-pretty format (with ANSI colors)
- #[serde(flatten)]
- pub display: DisplayFields,
+ /// Working tree symbols (?, !, +, », ✘) - used for status computation, not serialized
+ #[serde(skip)]
+ pub(crate) working_tree_symbols: Option<String>,
+ /// is_dirty flag - used for status computation, not serialized
+ #[serde(skip)]
+ pub(crate) is_dirty: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub working_diff_display: Option<String>,
}
-#[derive(serde::Serialize)]
-pub struct BranchInfo {
- pub name: String,
- #[serde(rename = "head_sha")]
- pub head: String,
- #[serde(flatten)]
- pub commit: CommitDetails,
- #[serde(flatten)]
- pub counts: AheadBehind,
- #[serde(flatten)]
- pub branch_diff: BranchDiffTotals,
- #[serde(flatten)]
- pub upstream: UpstreamStatus,
- pub pr_status: Option<PrStatus>,
- pub has_conflicts: bool,
- /// User-defined status from `worktrunk.status.<branch>` git config
- #[serde(skip_serializing_if = "Option::is_none")]
- pub user_status: Option<String>,
+impl WorktreeData {
+ /// Create WorktreeData from a Worktree, with all computed fields set to None.
+ pub(crate) fn from_worktree(wt: &worktrunk::git::Worktree, is_primary: bool) -> Self {
+ Self {
+ // Identity fields (known immediately from worktree list)
+ path: wt.path.clone(),
+ bare: wt.bare,
+ detached: wt.detached,
+ locked: wt.locked.clone(),
+ prunable: wt.prunable.clone(),
+ is_primary,
- // Display fields for json-pretty format (with ANSI colors)
- #[serde(flatten)]
- pub display: DisplayFields,
+ // Computed fields start as None (filled progressively)
+ ..Default::default()
+ }
+ }
+}
+
+/// Discriminator for item type (worktree vs branch)
+///
+/// WorktreeData is boxed to reduce the size of ItemKind enum (304 bytes → 24 bytes).
+/// This reduces stack pressure when passing ListItem by value and improves cache locality
+/// in `Vec<ListItem>` by keeping the discriminant and common fields together.
+#[derive(serde::Serialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum ItemKind {
+ Worktree(Box<WorktreeData>),
+ Branch,
}
-#[derive(serde::Serialize, Clone)]
+#[derive(serde::Serialize, Clone, Default, Debug)]
pub struct CommitDetails {
pub timestamp: i64,
pub commit_message: String,
}
-impl CommitDetails {
- fn gather(repo: &Repository, head: &str) -> Result<Self, GitError> {
- Ok(Self {
- timestamp: repo.commit_timestamp(head)?,
- commit_message: repo.commit_message(head)?,
- })
- }
-}
-
-#[derive(serde::Serialize, Default, Clone)]
+#[derive(serde::Serialize, Default, Clone, Debug)]
pub struct AheadBehind {
pub ahead: usize,
pub behind: usize,
}
-impl AheadBehind {
- fn compute(repo: &Repository, base: Option<&str>, head: &str) -> Result<Self, GitError> {
- let Some(base) = base else {
- return Ok(Self::default());
- };
-
- let (ahead, behind) = repo.ahead_behind(base, head)?;
- Ok(Self { ahead, behind })
- }
-}
-
-#[derive(serde::Serialize, Default, Clone)]
+#[derive(serde::Serialize, Default, Clone, Debug)]
pub struct BranchDiffTotals {
#[serde(rename = "branch_diff")]
pub diff: LineDiff,
}
-impl BranchDiffTotals {
- fn compute(repo: &Repository, base: Option<&str>, head: &str) -> Result<Self, GitError> {
- let Some(base) = base else {
- return Ok(Self::default());
- };
-
- let diff = repo.branch_diff_stats(base, head)?;
- Ok(Self { diff })
- }
-}
-
-#[derive(serde::Serialize, Default, Clone)]
+#[derive(serde::Serialize, Default, Clone, Debug)]
pub struct UpstreamStatus {
#[serde(rename = "upstream_remote")]
- remote: Option<String>,
+ pub(super) remote: Option<String>,
#[serde(rename = "upstream_ahead")]
- ahead: usize,
+ pub(super) ahead: usize,
#[serde(rename = "upstream_behind")]
- behind: usize,
+ pub(super) behind: usize,
}
impl UpstreamStatus {
- fn calculate(repo: &Repository, branch: Option<&str>, head: &str) -> Result<Self, GitError> {
- let Some(branch) = branch else {
- return Ok(Self::default());
- };
-
- match repo.upstream_branch(branch) {
- Ok(Some(upstream_branch)) => {
- let remote = upstream_branch
- .split_once('/')
- .map(|(remote, _)| remote)
- .unwrap_or("origin")
- .to_string();
- let (ahead, behind) = repo.ahead_behind(&upstream_branch, head)?;
- Ok(Self {
- remote: Some(remote),
- ahead,
- behind,
- })
- }
- _ => Ok(Self::default()),
- }
- }
-
pub fn active(&self) -> Option<(&str, usize, usize)> {
self.remote
.as_deref()
@@ -218,7 +150,7 @@ impl UpstreamStatus {
}
#[cfg(test)]
- pub fn from_parts(remote: Option<String>, ahead: usize, behind: usize) -> Self {
+ pub(crate) fn from_parts(remote: Option<String>, ahead: usize, behind: usize) -> Self {
Self {
remote,
ahead,
@@ -227,13 +159,48 @@ impl UpstreamStatus {
}
}
-/// Unified type for displaying worktrees and branches in the same table
+/// Unified item for displaying worktrees and branches in the same table
#[derive(serde::Serialize)]
-#[serde(tag = "type", rename_all = "lowercase")]
-#[allow(clippy::large_enum_variant)]
-pub enum ListItem {
- Worktree(WorktreeInfo),
- Branch(BranchInfo),
+pub struct ListItem {
+ // Common fields (present for both worktrees and branches)
+ #[serde(rename = "head_sha")]
+ pub head: String,
+ /// Branch name - None for detached worktrees
+ pub branch: Option<String>,
+ #[serde(flatten, skip_serializing_if = "Option::is_none")]
+ pub commit: Option<CommitDetails>,
+
+ // TODO: Evaluate if skipping these fields in JSON when None is correct behavior.
+ // Currently, primary worktree omits counts/branch_diff (since it doesn't compare to itself),
+ // but consumers may expect these fields to always be present (even if zero).
+ // Consider: always include with default values vs current "omit when not computed" approach.
+ #[serde(flatten, skip_serializing_if = "Option::is_none")]
+ pub counts: Option<AheadBehind>,
+ #[serde(flatten, skip_serializing_if = "Option::is_none")]
+ pub branch_diff: Option<BranchDiffTotals>,
+
+ // TODO: Same concern as counts/branch_diff above - should upstream fields always be present?
+ #[serde(flatten, skip_serializing_if = "Option::is_none")]
+ pub upstream: Option<UpstreamStatus>,
+
+ /// CI/PR status: None = not loaded, Some(None) = no CI, Some(Some(status)) = has CI
+ pub pr_status: Option<Option<PrStatus>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub has_conflicts: Option<bool>,
+ /// User-defined status from git config
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub user_status: Option<String>,
+ /// Git status symbols - None until all dependencies are ready
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub status_symbols: Option<StatusSymbols>,
+
+ // Display fields for json-pretty format (with ANSI colors)
+ #[serde(flatten)]
+ pub display: DisplayFields,
+
+ // Type-specific data (worktree vs branch)
+ #[serde(flatten)]
+ pub kind: ItemKind,
}
pub struct ListData {
@@ -243,74 +210,46 @@ pub struct ListData {
impl ListItem {
pub fn branch_name(&self) -> &str {
- match self {
- ListItem::Worktree(wt) => wt.branch.as_deref().unwrap_or("(detached)"),
- ListItem::Branch(br) => &br.name,
- }
+ self.branch.as_deref().unwrap_or("(detached)")
}
pub fn is_primary(&self) -> bool {
- matches!(self, ListItem::Worktree(wt) if wt.is_primary)
- }
-
- pub fn commit_timestamp(&self) -> i64 {
- match self {
- ListItem::Worktree(info) => info.commit.timestamp,
- ListItem::Branch(info) => info.commit.timestamp,
- }
+ matches!(&self.kind, ItemKind::Worktree(data) if data.is_primary)
}
pub fn head(&self) -> &str {
- match self {
- ListItem::Worktree(info) => &info.head,
- ListItem::Branch(info) => &info.head,
- }
+ &self.head
}
- pub fn commit_details(&self) -> &CommitDetails {
- match self {
- ListItem::Worktree(info) => &info.commit,
- ListItem::Branch(info) => &info.commit,
- }
+ pub fn commit_details(&self) -> CommitDetails {
+ self.commit.clone().unwrap_or_default()
}
- pub fn counts(&self) -> &AheadBehind {
- match self {
- ListItem::Worktree(info) => &info.counts,
- ListItem::Branch(info) => &info.counts,
- }
+ pub fn counts(&self) -> AheadBehind {
+ self.counts.clone().unwrap_or_default()
}
- pub fn branch_diff(&self) -> &BranchDiffTotals {
- match self {
- ListItem::Worktree(info) => &info.branch_diff,
- ListItem::Branch(info) => &info.branch_diff,
- }
+ pub fn branch_diff(&self) -> BranchDiffTotals {
+ self.branch_diff.clone().unwrap_or_default()
}
- pub fn upstream(&self) -> &UpstreamStatus {
- match self {
- ListItem::Worktree(info) => &info.upstream,
- ListItem::Branch(info) => &info.upstream,
- }
+ pub fn upstream(&self) -> UpstreamStatus {
+ self.upstream.clone().unwrap_or_default()
}
- pub fn worktree_info(&self) -> Option<&WorktreeInfo> {
- match self {
- ListItem::Worktree(info) => Some(info),
- ListItem::Branch(_) => None,
+ pub fn worktree_data(&self) -> Option<&WorktreeData> {
+ match &self.kind {
+ ItemKind::Worktree(data) => Some(data),
+ ItemKind::Branch => None,
}
}
pub fn worktree_path(&self) -> Option<&PathBuf> {
- self.worktree_info().map(|info| &info.path)
+ self.worktree_data().map(|data| &data.path)
}
- pub fn pr_status(&self) -> Option<&PrStatus> {
- match self {
- ListItem::Worktree(info) => info.pr_status.as_ref(),
- ListItem::Branch(info) => info.pr_status.as_ref(),
- }
+ pub fn pr_status(&self) -> Option<Option<&PrStatus>> {
+ self.pr_status.as_ref().map(|opt| opt.as_ref())
}
/// Determine if the item contains no unique work and can likely be removed.
@@ -321,11 +260,18 @@ impl ListItem {
let counts = self.counts();
- if let Some(info) = self.worktree_info() {
- let no_commits_and_clean = counts.ahead == 0 && info.working_tree_diff.is_empty();
- let matches_main = info
+ if let Some(data) = self.worktree_data() {
+ let no_commits_and_clean = counts.ahead == 0
+ && data
+ .working_tree_diff
+ .as_ref()
+ .map(|d| d.is_empty())
+ .unwrap_or(true);
+ let matches_main = data
.working_tree_diff_with_main
- .is_some_and(|diff| diff.is_empty());
+ .and_then(|opt_diff| opt_diff)
+ .map(|diff| diff.is_empty())
+ .unwrap_or(false);
no_commits_and_clean || matches_main
} else {
counts.ahead == 0
@@ -333,68 +279,6 @@ impl ListItem {
}
}
-impl BranchInfo {
- /// Create BranchInfo from a branch name, enriching it with git metadata
- pub(crate) fn from_branch(
- branch: &str,
- repo: &Repository,
- primary_branch: Option<&str>,
- fetch_ci: bool,
- check_conflicts: bool,
- ) -> Result<Self, GitError> {
- // Get the commit SHA for this branch
- let head = repo.run_command(&["rev-parse", branch])?.trim().to_string();
-
- let commit = CommitDetails::gather(repo, &head)?;
- let counts = AheadBehind::compute(repo, primary_branch, &head)?;
- let branch_diff = BranchDiffTotals::compute(repo, primary_branch, &head)?;
- let upstream = UpstreamStatus::calculate(repo, Some(branch), &head)?;
-
- let pr_status = if fetch_ci {
- // Use worktree_root() which returns an absolute path
- let repo_path = repo.worktree_root()?;
- PrStatus::detect(branch, &head, &repo_path)
- } else {
- None
- };
-
- let has_conflicts = if check_conflicts {
- if let Some(base) = primary_branch {
- repo.has_merge_conflicts(base, &head)?
- } else {
- false
- }
- } else {
- false
- };
-
- // Read user-defined status from git config (branch-keyed only, no worktree)
- let user_status = repo.branch_keyed_status(branch);
-
- // Create display fields with status
- // For branches without worktrees, status is just user status or "·"
- let status_display = Some(user_status.clone().unwrap_or_else(|| "·".to_string()));
-
- let display = DisplayFields {
- status_display,
- ..Default::default()
- };
-
- Ok(BranchInfo {
- name: branch.to_string(),
- head,
- commit,
- counts,
- branch_diff,
- upstream,
- pr_status,
- has_conflicts,
- user_status,
- display,
- })
- }
-}
-
/// Main branch divergence state
///
/// Represents relationship to the main/primary branch.
@@ -561,24 +445,23 @@ impl PositionMask {
const POS_0D_WORKTREE_ATTRS: usize = 6;
const POS_4_USER_STATUS: usize = 7;
- /// Full mask with all positions enabled (for JSON output)
- /// Uses width of 1 for each position as a placeholder
- pub const FULL: Self = Self { widths: [1; 8] };
-
- /// Merge this mask with another, keeping the maximum width for each position
- pub fn merge(&mut self, other: &Self) {
- for (i, &other_width) in other.widths.iter().enumerate() {
- self.widths[i] = self.widths[i].max(other_width);
- }
- }
-
- /// Check if a position is included in the mask (width > 0)
- fn includes(&self, pos: usize) -> bool {
- self.widths[pos] > 0
- }
+ /// Full mask with all positions enabled (for JSON output and progressive rendering)
+ /// Allocates realistic widths based on common symbol sizes to ensure proper grid alignment
+ pub const FULL: Self = Self {
+ widths: [
+ 5, // POS_3_WORKING_TREE: ?!+»✘ (max 5 symbols)
+ 1, // POS_0A_CONFLICTS: = (1 char)
+ 1, // POS_0C_GIT_OPERATION: ↻ or ⋈ (1 char)
+ 1, // POS_1_MAIN_DIVERGENCE: ↑, ↓, ↕ (1 char)
+ 1, // POS_2_UPSTREAM_DIVERGENCE: ⇡, ⇣, ⇅ (1 char)
+ 1, // POS_0B_BRANCH_STATE: ≡ or ∅ (1 char)
+ 2, // POS_0D_WORKTREE_ATTRS: ⊠⚠ (max 2 symbols - bare filtered out)
+ 2, // POS_4_USER_STATUS: single emoji or two chars (allocate 2)
+ ],
+ };
- /// Get the width allocated for a position
- fn width(&self, pos: usize) -> usize {
+ /// Get the allocated width for a position
+ pub(crate) fn width(&self, pos: usize) -> usize {
self.widths[pos]
}
}
@@ -589,7 +472,7 @@ impl PositionMask {
/// - Position 0a: Conflicts (=)
/// - Position 0b: Branch state (≡, ∅)
/// - Position 0c: Git operation (↻, ⋈)
-/// - Position 0d: Worktree attributes (◇, ⊠, ⚠)
+/// - Position 0d: Worktree attributes (⊠, ⚠)
/// - Position 1: Main branch divergence (↑, ↓, ↕)
/// - Position 2: Remote/upstream divergence (⇡, ⇣, ⇅)
/// - Position 3: Working tree symbols (?, !, +, », ✘)
@@ -605,7 +488,7 @@ impl PositionMask {
///
/// **NOT mutually exclusive (can co-occur):**
/// - = can occur with any other symbol
-/// - ◇, ⊠, ⚠: Worktree can be bare+locked, bare+prunable, etc.
+/// - ⊠, ⚠: Worktree can be locked+prunable (bare is filtered out)
/// - All working tree symbols (?!+»✘): Can have multiple types of changes
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct StatusSymbols {
@@ -625,8 +508,8 @@ pub struct StatusSymbols {
/// Position 0c - MUTUALLY EXCLUSIVE (enforced by enum)
pub(crate) git_operation: GitOperation,
- /// Worktree attributes: ◇, ⊠, ⚠
- /// Position 0d - NOT mutually exclusive (can combine like "◇⊠")
+ /// Worktree attributes: ⊠, ⚠
+ /// Position 0d - NOT mutually exclusive (can combine like "⊠⚠")
pub(crate) worktree_attrs: String,
/// Main branch divergence state
@@ -662,7 +545,7 @@ impl StatusSymbols {
/// - Position 0a: Conflicts (= or space)
/// - Position 0b: Branch state (≡, ∅, or space)
/// - Position 0c: Git operation (↻, ⋈, or space)
- /// - Position 0d: Worktree attributes (◇⊠⚠ or space)
+ /// - Position 0d: Worktree attributes (⊠⚠ or space)
/// - Position 1: Main divergence (↑, ↓, ↕, or space)
/// - Position 2: Upstream divergence (⇡, ⇣, ⇅, or space)
/// - Position 3: Working tree symbols (?, !, +, », ✘)
@@ -671,6 +554,7 @@ impl StatusSymbols {
/// This ensures vertical scannability - each symbol type appears at the same
/// column position across all rows, while minimizing wasted space.
pub fn render_with_mask(&self, mask: &PositionMask) -> String {
+ use unicode_width::UnicodeWidthStr;
use worktrunk::styling::{CYAN, ERROR, HINT, WARNING};
let mut result = String::with_capacity(12);
@@ -682,11 +566,10 @@ impl StatusSymbols {
// Build list of (position_index, content, has_data) tuples
// Ordered by importance/actionability
// Apply colors based on semantic meaning:
- // - Red (ERROR): Actual conflicts (blocking problems requiring immediate action)
- // - Yellow (WARNING): Potential conflicts, git operations, locked/prunable (warnings)
+ // - Red (ERROR): Conflicts (blocking problems)
+ // - Yellow (WARNING): Git operations, locked/prunable (active/stuck states)
// - Cyan: Working tree changes (activity)
// - Dimmed (HINT): Branch state symbols that indicate removability
- // Conflicts: actual (=) and potential (≠) are mutually exclusive
let conflicts_str = if self.has_conflicts {
format!("{ERROR}={ERROR:#}")
} else if self.has_potential_conflicts {
@@ -720,6 +603,10 @@ impl StatusSymbols {
// Track (position, styled_content, visual_width, has_data)
// visual_width is the actual display width without ANSI codes
+ //
+ // CRITICAL: Display order is working_tree first, then other symbols.
+ // NEVER change this order - it ensures progressive and final rendering match exactly.
+ // Tests will break if you change this, but that's expected - update the tests, not this order.
let positions_data: [(usize, &str, usize, bool); 8] = [
(
PositionMask::POS_3_WORKING_TREE,
@@ -737,12 +624,24 @@ impl StatusSymbols {
},
self.has_conflicts || self.has_potential_conflicts,
),
+ (
+ PositionMask::POS_0B_BRANCH_STATE,
+ branch_state_str.as_str(),
+ self.branch_state.to_string().width(),
+ self.branch_state != BranchState::None,
+ ),
(
PositionMask::POS_0C_GIT_OPERATION,
git_operation_str.as_str(),
self.git_operation.to_string().width(),
self.git_operation != GitOperation::None,
),
+ (
+ PositionMask::POS_0D_WORKTREE_ATTRS,
+ worktree_attrs_str.as_str(),
+ self.worktree_attrs.width(),
+ !self.worktree_attrs.is_empty(),
+ ),
(
PositionMask::POS_1_MAIN_DIVERGENCE,
main_divergence_str.as_str(),
@@ -755,18 +654,6 @@ impl StatusSymbols {
self.upstream_divergence.to_string().width(),
self.upstream_divergence != UpstreamDivergence::None,
),
- (
- PositionMask::POS_0B_BRANCH_STATE,
- branch_state_str.as_str(),
- self.branch_state.to_string().width(),
- self.branch_state != BranchState::None,
- ),
- (
- PositionMask::POS_0D_WORKTREE_ATTRS,
- worktree_attrs_str.as_str(),
- self.worktree_attrs.width(),
- !self.worktree_attrs.is_empty(),
- ),
(
PositionMask::POS_4_USER_STATUS,
user_status_str.as_str(),
@@ -775,28 +662,22 @@ impl StatusSymbols {
),
];
- // Grid-based rendering with padding: each position gets a fixed-width column
- // - If row has content at position: append content, then pad to allocated width
- // - If row has no content at position: fill with spaces to allocated width
- use unicode_width::UnicodeWidthStr;
-
+ // Grid-based rendering: each position gets a fixed width for vertical alignment.
+ // CRITICAL: Always use PositionMask::FULL for consistent spacing between progressive and final rendering.
+ // The mask provides the maximum width needed for each position across all rows.
+ // Accept wider Status column with whitespace as tradeoff for perfect alignment.
for (pos, styled_content, visual_width, has_data) in positions_data.iter() {
- if !mask.includes(*pos) {
- continue; // Skip positions not in mask
- }
-
let allocated_width = mask.width(*pos);
if *has_data {
result.push_str(styled_content);
- // Pad to allocated width (use saturating_sub to handle edge cases)
- // Use visual_width (without ANSI codes) for padding calculation
+ // Pad to allocated width for alignment
let padding = allocated_width.saturating_sub(*visual_width);
for _ in 0..padding {
result.push(' ');
}
} else {
- // Fill empty column with spaces
+ // Fill empty position with spaces for alignment
for _ in 0..allocated_width {
result.push(' ');
}
@@ -806,31 +687,6 @@ impl StatusSymbols {
result
}
- /// Derive a position mask that tracks which symbol slots contain data.
- pub fn position_mask(&self) -> PositionMask {
- use unicode_width::UnicodeWidthStr;
-
- let mut widths = [0; 8];
-
- widths[PositionMask::POS_3_WORKING_TREE] = self.working_tree.width();
- widths[PositionMask::POS_0A_CONFLICTS] =
- if self.has_conflicts || self.has_potential_conflicts {
- 1
- } else {
- 0
- };
- widths[PositionMask::POS_0C_GIT_OPERATION] = self.git_operation.to_string().width();
- widths[PositionMask::POS_1_MAIN_DIVERGENCE] = self.main_divergence.to_string().width();
- widths[PositionMask::POS_2_UPSTREAM_DIVERGENCE] =
- self.upstream_divergence.to_string().width();
- widths[PositionMask::POS_0B_BRANCH_STATE] = self.branch_state.to_string().width();
- widths[PositionMask::POS_0D_WORKTREE_ATTRS] = self.worktree_attrs.width();
- widths[PositionMask::POS_4_USER_STATUS] =
- self.user_status.as_ref().map(|s| s.width()).unwrap_or(0);
-
- PositionMask { widths }
- }
-
/// Check if symbols are empty
pub fn is_empty(&self) -> bool {
!self.has_conflicts
@@ -844,263 +700,3 @@ impl StatusSymbols {
&& self.user_status.is_none()
}
}
-
-/// Git status information parsed from `git status --porcelain`
-struct GitStatusInfo {
- /// Whether the working tree has any changes (staged or unstaged)
- is_dirty: bool,
- /// Status symbols (structured for alignment)
- symbols: StatusSymbols,
-}
-
-/// Parse git status --porcelain output to determine dirty state and status symbols
-/// This combines the dirty check and symbol computation in a single git command
-fn parse_git_status(
- repo: &Repository,
- main_ahead: usize,
- main_behind: usize,
- upstream_ahead: usize,
- upstream_behind: usize,
-) -> Result<GitStatusInfo, GitError> {
- let status_output = repo.run_command(&["status", "--porcelain"])?;
-
- let mut has_conflicts = false;
- let mut has_untracked = false;
- let mut has_modified = false;
- let mut has_staged = false;
- let mut has_renamed = false;
- let mut has_deleted = false;
- let mut is_dirty = false;
-
- for line in status_output.lines() {
- if line.len() < 2 {
- continue;
- }
-
- is_dirty = true; // Any line means changes exist
-
- // Get status codes (first two bytes for ASCII compatibility)
- let bytes = line.as_bytes();
- let index_status = bytes[0] as char;
- let worktree_status = bytes[1] as char;
-
- // Unmerged paths (actual conflicts in working tree)
- // U = unmerged, D = both deleted, A = both added
- if index_status == 'U'
- || worktree_status == 'U'
- || (index_status == 'D' && worktree_status == 'D')
- || (index_status == 'A' && worktree_status == 'A')
- {
- has_conflicts = true;
- }
-
- // Untracked files
- if index_status == '?' && worktree_status == '?' {
- has_untracked = true;
- }
-
- // Modified (unstaged changes in working tree)
- if worktree_status == 'M' {
- has_modified = true;
- }
-
- // Staged files (changes in index)
- // Includes: A (added), M (modified), C (copied), but excludes D/R
- if index_status == 'A' || index_status == 'M' || index_status == 'C' {
- has_staged = true;
- }
-
- // Renamed files (staged rename)
- if index_status == 'R' {
- has_renamed = true;
- }
-
- // Deleted files (staged or unstaged)
- if index_status == 'D' || worktree_status == 'D' {
- has_deleted = true;
- }
- }
-
- // Build working tree string
- let mut working_tree = String::new();
- if has_untracked {
- working_tree.push('?');
- }
- if has_modified {
- working_tree.push('!');
- }
- if has_staged {
- working_tree.push('+');
- }
- if has_renamed {
- working_tree.push('»');
- }
- if has_deleted {
- working_tree.push('✘');
- }
-
- // Build structured symbols for aligned rendering
- let symbols = StatusSymbols {
- has_conflicts,
- main_divergence: match (main_ahead > 0, main_behind > 0) {
- (true, true) => MainDivergence::Diverged, // Both ahead and behind
- (true, false) => MainDivergence::Ahead, // Ahead only
- (false, true) => MainDivergence::Behind, // Behind only
- (false, false) => MainDivergence::None, // Up to date
- },
- upstream_divergence: match (upstream_ahead > 0, upstream_behind > 0) {
- (true, true) => UpstreamDivergence::Diverged, // Both ahead and behind
- (true, false) => UpstreamDivergence::Ahead, // Ahead only
- (false, true) => UpstreamDivergence::Behind, // Behind only
- (false, false) => UpstreamDivergence::None, // Up to date
- },
- working_tree,
- ..Default::default()
- };
-
- Ok(GitStatusInfo { is_dirty, symbols })
-}
-
-impl WorktreeInfo {
- /// Create WorktreeInfo from a Worktree, enriching it with git metadata
- pub(crate) fn from_worktree(
- wt: &worktrunk::git::Worktree,
- primary: &worktrunk::git::Worktree,
- fetch_ci: bool,
- check_conflicts: bool,
- ) -> Result<Self, GitError> {
- let wt_repo = Repository::at(&wt.path);
- let is_primary = wt.path == primary.path;
-
- let commit = CommitDetails::gather(&wt_repo, &wt.head)?;
- let base_branch = primary.branch.as_deref().filter(|_| !is_primary);
- let counts = AheadBehind::compute(&wt_repo, base_branch, &wt.head)?;
- let upstream = UpstreamStatus::calculate(&wt_repo, wt.branch.as_deref(), &wt.head)?;
-
- // Parse git status once for both dirty check and status symbols
- // Pass both main and upstream ahead/behind counts
- let (upstream_ahead, upstream_behind) = upstream
- .active()
- .map(|(_, ahead, behind)| (ahead, behind))
- .unwrap_or((0, 0));
- let status_info = parse_git_status(
- &wt_repo,
- counts.ahead,
- counts.behind,
- upstream_ahead,
- upstream_behind,
- )?;
-
- let working_tree_diff = if status_info.is_dirty {
- wt_repo.working_tree_diff_stats()?
- } else {
- LineDiff::default() // Clean working tree
- };
-
- // Use tree equality check instead of expensive diff for "matches main"
- let working_tree_diff_with_main =
- wt_repo.working_tree_diff_with_base(base_branch, status_info.is_dirty)?;
- let branch_diff = BranchDiffTotals::compute(&wt_repo, base_branch, &wt.head)?;
-
- // Get worktree state (merge/rebase/etc)
- let worktree_state = wt_repo.worktree_state()?;
-
- let pr_status = if fetch_ci {
- wt.branch
- .as_deref()
- .and_then(|branch| PrStatus::detect(branch, &wt.head, &wt.path))
- } else {
- None
- };
-
- let has_conflicts = if check_conflicts {
- if let Some(base) = base_branch {
- wt_repo.has_merge_conflicts(base, &wt.head)?
- } else {
- false
- }
- } else {
- false
- };
-
- // Build complete status symbols with type-safe enums
- // Order: =≠ ≡∅ ↻⋈ ◇⊠⚠ | ↑↓ | ⇡⇣ | ?!+»✘
- // ^0a 0b 0c 0d^ ^1^ ^2^ ^3+^
- let mut symbols = status_info.symbols;
-
- // Add potential conflicts indicator if this branch has conflicts with base (--full only)
- // This is separate from actual unmerged files which are already in has_conflicts
- if has_conflicts {
- symbols.has_potential_conflicts = true;
- }
-
- // Branch state: ≡ matches main, ∅ no commits (mutually exclusive)
- if !is_primary {
- if working_tree_diff_with_main.is_some_and(|diff| diff.is_empty()) {
- symbols.branch_state = BranchState::MatchesMain;
- } else if counts.ahead == 0 && working_tree_diff.is_empty() {
- symbols.branch_state = BranchState::NoCommits;
- }
- }
-
- // Git operation: ↻ rebase, ⋈ merge (mutually exclusive)
- if let Some(state) = &worktree_state {
- if state.contains("rebase") {
- symbols.git_operation = GitOperation::Rebase;
- } else if state.contains("merge") {
- symbols.git_operation = GitOperation::Merge;
- }
- }
-
- // Worktree attributes: ◇ bare, ⊠ locked, ⚠ prunable (can combine)
- if wt.bare {
- symbols.worktree_attrs.push('◇');
- }
- if wt.locked.is_some() {
- symbols.worktree_attrs.push('⊠');
- }
- if wt.prunable.is_some() {
- symbols.worktree_attrs.push('⚠');
- }
-
- // Add user-defined status from git config to symbols (Position 4)
- symbols.user_status = wt_repo.user_status(wt.branch.as_deref());
-
- // Create display fields with rendered status
- let status_display = if !symbols.is_empty() {
- Some(symbols.render())
- } else {
- None
- };
-
- let display = DisplayFields {
- status_display,
- ..Default::default()
- };
-
- Ok(WorktreeInfo {
- // Flatten worktree fields
- path: wt.path.clone(),
- head: wt.head.clone(),
- branch: wt.branch.clone(),
- bare: wt.bare,
- detached: wt.detached,
- locked: wt.locked.clone(),
- prunable: wt.prunable.clone(),
- // Remaining fields
- commit,
- counts,
- branch_diff,
- working_tree_diff,
- working_tree_diff_with_main,
- worktree_state,
- has_conflicts,
- is_primary,
- upstream,
- pr_status,
- status_symbols: symbols,
- display,
- working_diff_display: None,
- })
- }
-}
diff --git a/src/commands/list/progressive.rs b/src/commands/list/progressive.rs
new file mode 100644
index 000000000..6e476ac2b
--- /dev/null
+++ b/src/commands/list/progressive.rs
@@ -0,0 +1,68 @@
+/// Rendering mode for list command
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RenderMode {
+ /// Buffered: collect all data, then render (traditional)
+ Buffered,
+ /// Progressive: show rows immediately, update as data arrives
+ Progressive,
+}
+
+impl RenderMode {
+ /// Determine rendering mode based on CLI flags and TTY status
+ ///
+ /// # Arguments
+ ///
+ /// * `progressive_flag` - Explicit --progressive flag
+ /// * `no_progressive_flag` - Explicit --no-progressive flag
+ /// * `directive_mode` - True if in directive mode (--internal), affects which stream to check
+ ///
+ /// In directive mode, table output goes to stderr, so we check stderr's TTY status.
+ /// In interactive mode, table output goes to stdout, so we check stdout's TTY status.
+ pub fn detect(progressive_flag: bool, no_progressive_flag: bool, directive_mode: bool) -> Self {
+ // Priority 1: Explicit CLI flags
+ if progressive_flag {
+ return RenderMode::Progressive;
+ }
+ if no_progressive_flag {
+ return RenderMode::Buffered;
+ }
+
+ // Priority 2: Auto-detect based on TTY
+ // Check the appropriate stream based on output mode:
+ // - Directive mode: check stderr (where table output goes via output::raw())
+ // - Interactive mode: check stdout (where table output goes)
+ use std::io::IsTerminal;
+ let is_tty = if directive_mode {
+ std::io::stderr().is_terminal()
+ } else {
+ std::io::stdout().is_terminal()
+ };
+
+ if is_tty {
+ // TODO: Check for pager in environment
+ RenderMode::Progressive
+ } else {
+ RenderMode::Buffered
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_render_mode_detect_explicit_flags() {
+ // Explicit flags should work regardless of directive mode
+ assert_eq!(
+ RenderMode::detect(true, false, false),
+ RenderMode::Progressive
+ );
+ assert_eq!(RenderMode::detect(false, true, false), RenderMode::Buffered);
+ assert_eq!(
+ RenderMode::detect(true, false, true),
+ RenderMode::Progressive
+ );
+ assert_eq!(RenderMode::detect(false, true, true), RenderMode::Buffered);
+ }
+}
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index 2c1300462..e158e4a6d 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -1,7 +1,8 @@
use crate::display::{format_relative_time, shorten_path, truncate_at_word_boundary};
use anstyle::{AnsiColor, Color, Style};
use std::path::Path;
-use worktrunk::styling::{CURRENT, StyledLine, println};
+use unicode_width::UnicodeWidthStr;
+use worktrunk::styling::{CURRENT, StyledLine};
use super::ci_status::{CiSource, CiStatus, PrStatus};
use super::columns::{ColumnKind, DiffVariant};
@@ -9,7 +10,7 @@ use super::layout::{
ColumnFormat, ColumnLayout, DiffColumnConfig, DiffDisplayConfig, LayoutConfig,
};
use super::model::{
- AheadBehind, CommitDetails, ListItem, PositionMask, UpstreamStatus, WorktreeInfo,
+ AheadBehind, CommitDetails, ListItem, PositionMask, UpstreamStatus, WorktreeData,
};
use worktrunk::git::LineDiff;
@@ -97,30 +98,6 @@ impl PrStatus {
(indicator, style)
}
- /// Format CI status as plain text with ANSI colors (for json-pretty)
- pub fn format_plain(&self) -> String {
- let status_str = match self.ci_status {
- CiStatus::Passed => "passed",
- CiStatus::Running => "running",
- CiStatus::Failed => "failed",
- CiStatus::Conflicts => "conflicts",
- CiStatus::NoCI => "no-ci",
- };
-
- let (indicator, style) = self.indicator_and_style();
-
- let text = format!("{} {}", indicator, status_str);
-
- let content = if let Some(ref url) = self.url {
- use worktrunk::styling::hyperlink;
- hyperlink(&text, url)
- } else {
- text
- };
-
- format!("{}{}{}", style, content, style.render_reset())
- }
-
fn render_indicator(&self) -> StyledLine {
let mut segment = StyledLine::new();
let (indicator, style) = self.indicator_and_style();
@@ -142,17 +119,10 @@ impl PrStatus {
}
}
-#[derive(Clone, Copy)]
-enum ValueAlign {
- Left,
- Right,
-}
-
#[derive(Clone, Copy)]
struct DiffRenderConfig {
positive_symbol: &'static str,
negative_symbol: &'static str,
- align: ValueAlign,
}
impl DiffVariant {
@@ -161,22 +131,95 @@ impl DiffVariant {
DiffVariant::Signs => DiffRenderConfig {
positive_symbol: "+",
negative_symbol: "-",
- align: ValueAlign::Right,
},
DiffVariant::Arrows => DiffRenderConfig {
positive_symbol: "↑",
negative_symbol: "↓",
- align: ValueAlign::Left,
},
}
}
}
impl DiffColumnConfig {
+ /// Check if a value exceeds the allocated digit width
+ fn exceeds_width(value: usize, digits: usize) -> bool {
+ if digits == 0 {
+ return value > 0;
+ }
+ let max_value = 10_usize.pow(digits as u32) - 1;
+ value > max_value
+ }
+
+ /// Check if a subcolumn value should be rendered (non-zero or explicitly showing zeros)
+ fn should_render(value: usize, always_show_zeros: bool) -> bool {
+ value > 0 || (value == 0 && always_show_zeros)
+ }
+
+ /// Format a value using compact notation (C for hundreds, K for thousands)
+ /// Ensures the result never exceeds 2 characters
+ ///
+ /// Note: Uses integer division for approximation (intentional truncation):
+ /// - 648 / 100 = 6 → "6C" (represents ~600)
+ /// - 1999 / 1000 = 1 → "1K" (represents ~1000)
+ ///
+ /// This provides approximate values optimized for readability over precision.
+ ///
+ /// Examples: 5 -> "5", 42 -> "42", 100 -> "1C", 648 -> "6C", 1000 -> "1K", 15000 -> "9K"
+ fn format_overflow(value: usize) -> String {
+ if value >= 10_000 {
+ // Cap at 9K to maintain 2-char limit (indicates "very large")
+ "9K".to_string()
+ } else if value >= 1_000 {
+ format!("{}K", value / 1_000)
+ } else if value >= 100 {
+ format!("{}C", value / 100)
+ } else {
+ value.to_string()
+ }
+ }
+
+ /// Render a subcolumn value with symbol and padding to fixed width
+ /// Numbers are right-aligned on the ones column (e.g., " +2", "+53")
+ /// For overflow, renders bold with C/K suffix (e.g., bold "+6C", bold "+5K")
+ fn render_subcolumn(
+ segment: &mut StyledLine,
+ symbol: &str,
+ value: usize,
+ width: usize,
+ style: Style,
+ overflow: bool,
+ ) {
+ let value_str = if overflow {
+ Self::format_overflow(value)
+ } else {
+ value.to_string()
+ };
+ let content_len = 1 + value_str.len(); // symbol + digits
+ let padding_needed = width.saturating_sub(content_len);
+
+ // Add left padding for right-alignment
+ if padding_needed > 0 {
+ segment.push_raw(" ".repeat(padding_needed));
+ }
+
+ // Add styled content - bold entire value if using compact notation
+ if overflow {
+ // When overflow is true, format_overflow() uses compact notation (C/K suffix)
+ // Make entire value bold to emphasize approximation
+ segment.push_styled(format!("{}{}", symbol, value_str), style.bold());
+ } else {
+ segment.push_styled(format!("{}{}", symbol, value_str), style);
+ }
+ }
+
fn render_segment(&self, positive: usize, negative: usize) -> StyledLine {
let render_config = self.display.variant.render_config();
let mut segment = StyledLine::new();
+ // Check for overflow
+ let positive_overflow = Self::exceeds_width(positive, self.digits.added);
+ let negative_overflow = Self::exceeds_width(negative, self.digits.deleted);
+
if positive == 0 && negative == 0 && !self.display.always_show_zeros {
segment.push_raw(" ".repeat(self.total_width));
return segment;
@@ -184,45 +227,49 @@ impl DiffColumnConfig {
let positive_width = 1 + self.digits.added;
let negative_width = 1 + self.digits.deleted;
+
+ // Fixed content width ensures vertical alignment of subcolumns
let content_width = positive_width + 1 + negative_width;
- let extra_padding = self.total_width.saturating_sub(content_width);
+ let total_padding = self.total_width.saturating_sub(content_width);
- if matches!(render_config.align, ValueAlign::Right) && extra_padding > 0 {
- segment.push_raw(" ".repeat(extra_padding));
+ // Add leading padding for right-alignment
+ if total_padding > 0 {
+ segment.push_raw(" ".repeat(total_padding));
}
- if positive > 0 || (positive == 0 && self.display.always_show_zeros) {
- let value = format!("{}{}", render_config.positive_symbol, positive);
- let formatted = match render_config.align {
- ValueAlign::Right => format!("{:>width$}", value, width = positive_width),
- ValueAlign::Left => format!("{:<width$}", value, width = positive_width),
- };
- segment.push_styled(formatted, self.display.positive_style);
+ // Render positive (added) subcolumn
+ if Self::should_render(positive, self.display.always_show_zeros) {
+ Self::render_subcolumn(
+ &mut segment,
+ render_config.positive_symbol,
+ positive,
+ positive_width,
+ self.display.positive_style,
+ positive_overflow,
+ );
} else {
+ // Empty positive subcolumn - add spaces to maintain alignment
segment.push_raw(" ".repeat(positive_width));
}
+ // Always add separator to maintain fixed layout (early return handles empty case)
segment.push_raw(" ");
- if negative > 0 || (negative == 0 && self.display.always_show_zeros) {
- let value = format!("{}{}", render_config.negative_symbol, negative);
- let formatted = match render_config.align {
- ValueAlign::Right => format!("{:>width$}", value, width = negative_width),
- ValueAlign::Left => format!("{:<width$}", value, width = negative_width),
- };
- segment.push_styled(formatted, self.display.negative_style);
+ // Render negative (deleted) subcolumn
+ if Self::should_render(negative, self.display.always_show_zeros) {
+ Self::render_subcolumn(
+ &mut segment,
+ render_config.negative_symbol,
+ negative,
+ negative_width,
+ self.display.negative_style,
+ negative_overflow,
+ );
} else {
+ // Empty negative subcolumn - add spaces to maintain alignment
segment.push_raw(" ".repeat(negative_width));
}
- if matches!(render_config.align, ValueAlign::Left) && extra_padding > 0 {
- segment.pad_to(segment.width() + extra_padding);
- }
-
- if segment.width() < self.total_width {
- segment.pad_to(self.total_width);
- }
-
segment
}
}
@@ -241,34 +288,64 @@ impl LayoutConfig {
for (index, column) in self.columns.iter().enumerate() {
line.pad_to(column.start);
- line.extend(render_cell(column));
+ let cell = render_cell(column);
+ let cell_width = cell.width();
+
+ // Debug: Log if cell exceeds its allocated width
+ if cell_width > column.width {
+ log::debug!(
+ "Cell overflow: column={:?} allocated={} actual={} excess={}",
+ column.kind,
+ column.width,
+ cell_width,
+ cell_width - column.width
+ );
+ }
+
+ line.extend(cell);
+ // Pad to end of column (unless it's the last column)
if index != last_index {
line.pad_to(column.start + column.width);
}
}
+ let final_width = line.width();
+ log::debug!("Rendered line width: {}", final_width);
+
line
}
- pub fn format_header_line(&self) {
+ pub fn format_header_line(&self) -> String {
let style = Style::new().bold();
let line = self.render_line(|column| {
let mut cell = StyledLine::new();
if !column.header.is_empty() {
+ // Diff columns have right-aligned values, so right-align headers too
+ let is_diff_column = matches!(column.format, ColumnFormat::Diff(_));
+
+ if is_diff_column {
+ // Right-align header within column width
+ let header_width = column.header.width();
+ if header_width < column.width {
+ let padding = column.width - header_width;
+ cell.push_raw(" ".repeat(padding));
+ }
+ }
+
cell.push_styled(column.header.to_string(), style);
}
cell
});
- println!("{}", line.render());
+ line.render()
}
pub fn format_list_item_line(
&self,
item: &ListItem,
current_worktree_path: Option<&std::path::PathBuf>,
- ) {
+ ) -> String {
let ctx = ListRowContext::new(item, current_worktree_path);
let line = self.render_line(|column| {
column.render_cell(
@@ -279,24 +356,100 @@ impl LayoutConfig {
)
});
- println!("{}", line.render());
+ line.render()
+ }
+
+ /// Render a skeleton row showing known data (branch, path) with placeholders for other columns
+ pub fn format_skeleton_row(
+ &self,
+ wt: &worktrunk::git::Worktree,
+ is_primary: bool,
+ is_current: bool,
+ ) -> String {
+ use crate::display::shorten_path;
+ use unicode_width::UnicodeWidthStr;
+
+ let branch = wt.branch.as_deref().unwrap_or("(detached)");
+ let shortened_path = shorten_path(&wt.path, &self.common_prefix);
+
+ let dim = Style::new().dimmed();
+ let spinner = "⋯"; // Placeholder character
+
+ let line = self.render_line(|col| {
+ let mut cell = StyledLine::new();
+
+ match col.kind {
+ ColumnKind::Branch => {
+ // Show actual branch name
+ let style = if is_current {
+ CURRENT.bold()
+ } else if is_primary {
+ Style::new()
+ .fg_color(Some(Color::Ansi(AnsiColor::Cyan)))
+ .bold()
+ } else {
+ dim
+ };
+ cell.push_styled(branch, style);
+ // Pad to column width
+ let branch_width = branch.width();
+ if branch_width < col.width {
+ cell.push_raw(" ".repeat(col.width - branch_width));
+ }
+ }
+ ColumnKind::Path => {
+ // Show actual path
+ let style = if is_current {
+ CURRENT.bold()
+ } else if is_primary {
+ Style::new()
+ .fg_color(Some(Color::Ansi(AnsiColor::Cyan)))
+ .bold()
+ } else {
+ dim
+ };
+ cell.push_styled(&shortened_path, style);
+ // Pad to column width
+ let path_width = shortened_path.width();
+ if path_width < col.width {
+ cell.push_raw(" ".repeat(col.width - path_width));
+ }
+ }
+ ColumnKind::Commit => {
+ // Show actual commit hash (always available)
+ let short_head = &wt.head[..8.min(wt.head.len())];
+ cell.push_styled(short_head, dim);
+ }
+ _ => {
+ // Show spinner for data columns
+ cell.push_styled(spinner, dim);
+ if spinner.width() < col.width {
+ cell.push_raw(" ".repeat(col.width - spinner.width()));
+ }
+ }
+ }
+
+ cell
+ });
+
+ line.render()
}
}
struct ListRowContext<'a> {
item: &'a ListItem,
- worktree_info: Option<&'a WorktreeInfo>,
- counts: &'a AheadBehind,
+ worktree_info: Option<&'a WorktreeData>,
+ counts: AheadBehind,
branch_diff: LineDiff,
- upstream: &'a UpstreamStatus,
- commit: &'a CommitDetails,
+ upstream: UpstreamStatus,
+ commit: CommitDetails,
head: &'a str,
text_style: Option<Style>,
}
impl<'a> ListRowContext<'a> {
fn new(item: &'a ListItem, current_worktree_path: Option<&std::path::PathBuf>) -> Self {
- let worktree_info = item.worktree_info();
+ let worktree_info = item.worktree_data();
let counts = item.counts();
let commit = item.commit_details();
let branch_diff = item.branch_diff().diff;
@@ -366,36 +519,38 @@ impl ColumnLayout {
match self.kind {
ColumnKind::Branch => {
let mut cell = StyledLine::new();
- let text = ctx.item.branch_name().to_string();
+ let text = ctx.item.branch.as_deref().unwrap_or("(detached)");
if let Some(style) = ctx.text_style {
- cell.push_styled(text, style);
+ cell.push_styled(text.to_string(), style);
} else {
- cell.push_raw(text);
+ cell.push_raw(text.to_string());
}
cell
}
ColumnKind::Status => {
let mut cell = StyledLine::new();
- if let Some(info) = ctx.worktree_info {
- // Render all status symbols including user status (Position 4)
- cell.push_raw(info.status_symbols.render_with_mask(status_mask));
- } else if let ListItem::Branch(branch_info) = ctx.item
- && let Some(ref user_status) = branch_info.user_status
- {
- // For branches, create a minimal StatusSymbols with just user_status
- use crate::commands::list::model::StatusSymbols;
- let branch_symbols = StatusSymbols {
- user_status: Some(user_status.clone()),
- ..Default::default()
- };
- cell.push_raw(branch_symbols.render_with_mask(status_mask));
+ // Render status symbols (works for both worktrees and branches)
+ if let Some(ref status_symbols) = ctx.item.status_symbols {
+ cell.push_raw(status_symbols.render_with_mask(status_mask));
+ } else if ctx.worktree_info.is_some() {
+ // Show spinner while status is being computed (worktrees only)
+ cell.push_styled("⋯", Style::new().dimmed());
+ }
+
+ // Pad to column width
+ let status_width = cell.width();
+ if status_width < self.width {
+ cell.push_raw(" ".repeat(self.width - status_width));
}
cell
}
ColumnKind::WorkingDiff => {
- let Some(diff) = ctx.worktree_info.map(|info| info.working_tree_diff) else {
+ let Some(diff) = ctx
+ .worktree_info
+ .and_then(|info| info.working_tree_diff.as_ref())
+ else {
return StyledLine::new();
};
self.render_diff_cell(diff.added, diff.deleted)
@@ -438,15 +593,48 @@ impl ColumnLayout {
}
ColumnKind::Time => {
let mut cell = StyledLine::new();
- let time_str = format_relative_time(ctx.commit.timestamp);
- cell.push_styled(time_str, Style::new().dimmed());
+
+ // Show spinner if commit details haven't loaded yet
+ if ctx.worktree_info.is_some() && ctx.item.commit.is_none() {
+ cell.push_styled("⋯", Style::new().dimmed());
+ } else {
+ let time_str = format_relative_time(ctx.commit.timestamp);
+ cell.push_styled(time_str, Style::new().dimmed());
+ }
+
cell
}
ColumnKind::CiStatus => {
- let Some(pr_status) = ctx.item.pr_status() else {
- return StyledLine::new();
- };
- pr_status.render_indicator()
+ // Check display field first for pending indicators during progressive rendering
+ if ctx.worktree_info.is_some()
+ && let Some(ref ci_display) = ctx.item.display.ci_status_display
+ {
+ let mut cell = StyledLine::new();
+ // ci_status_display contains pre-formatted ANSI text (either actual status or "⋯")
+ cell.push_raw(ci_display.clone());
+ return cell;
+ }
+
+ // pr_status is Option<Option<PrStatus>>:
+ // - None = not loaded yet (show spinner)
+ // - Some(None) = loaded, no CI (show nothing)
+ // - Some(Some(status)) = loaded with CI (show status)
+ match ctx.item.pr_status() {
+ None => {
+ // Not loaded yet - show spinner
+ let mut cell = StyledLine::new();
+ cell.push_styled("⋯", Style::new().dimmed());
+ cell
+ }
+ Some(None) => {
+ // Loaded, no CI - show nothing
+ StyledLine::new()
+ }
+ Some(Some(pr_status)) => {
+ // Loaded with CI - show status
+ pr_status.render_indicator()
+ }
+ }
}
ColumnKind::Commit => {
let mut cell = StyledLine::new();
@@ -455,8 +643,16 @@ impl ColumnLayout {
}
ColumnKind::Message => {
let mut cell = StyledLine::new();
- let msg = truncate_at_word_boundary(&ctx.commit.commit_message, max_message_len);
- cell.push_styled(msg, Style::new().dimmed());
+
+ // Show spinner if commit details haven't loaded yet
+ if ctx.worktree_info.is_some() && ctx.item.commit.is_none() {
+ cell.push_styled("⋯", Style::new().dimmed());
+ } else {
+ let msg =
+ truncate_at_word_boundary(&ctx.commit.commit_message, max_message_len);
+ cell.push_styled(msg, Style::new().dimmed());
+ }
+
cell
}
}
@@ -854,7 +1050,10 @@ mod tests {
assert_eq!(with.width(), total);
let rendered_with = with.render();
let clean_with = strip_ansi_escapes::strip_str(&rendered_with);
- assert_eq!(clean_with, "↑0 ↓0 ", "Should render ↑0 ↓0 with padding");
+ assert_eq!(
+ clean_with, " ↑0 ↓0",
+ "Should render ↑0 ↓0 with padding (right-aligned)"
+ );
}
#[test]
@@ -917,4 +1116,283 @@ mod tests {
assert_eq!(line3.width(), 10, "Complex status should pad to 10");
}
+
+ #[test]
+ fn test_diff_column_numeric_right_alignment() {
+ use super::super::columns::DiffVariant;
+
+ // Test that numbers are right-aligned on the ones column
+ // When we have 2-digit allocation but use 1-digit values, they should have leading space
+ let digits = DiffDigits {
+ added: 2, // Allocates 3 chars: "+NN"
+ deleted: 2,
+ };
+ let total = 8; // 3 (added) + 1 (separator) + 3 (deleted) + 1 (leading padding)
+
+ // Test case 1: (53, 7) - large added, small deleted
+ let result1 = format_diff_like_column(
+ 53,
+ 7,
+ DiffColumnConfig {
+ digits,
+ total_width: total,
+ display: DiffDisplayConfig {
+ variant: DiffVariant::Signs,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ },
+ },
+ );
+ let rendered1 = result1.render();
+ let clean1 = strip_ansi_escapes::strip_str(&rendered1);
+ assert_eq!(clean1, " +53 -7", "Should be ' +53 -7'");
+
+ // Test case 2: (33, 23) - both medium
+ let result2 = format_diff_like_column(
+ 33,
+ 23,
+ DiffColumnConfig {
+ digits,
+ total_width: total,
+ display: DiffDisplayConfig {
+ variant: DiffVariant::Signs,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ },
+ },
+ );
+ let rendered2 = result2.render();
+ let clean2 = strip_ansi_escapes::strip_str(&rendered2);
+ assert_eq!(clean2, " +33 -23", "Should be ' +33 -23'");
+
+ // Test case 3: (2, 2) - both small (needs padding)
+ let result3 = format_diff_like_column(
+ 2,
+ 2,
+ DiffColumnConfig {
+ digits,
+ total_width: total,
+ display: DiffDisplayConfig {
+ variant: DiffVariant::Signs,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ },
+ },
+ );
+ let rendered3 = result3.render();
+ let clean3 = strip_ansi_escapes::strip_str(&rendered3);
+ assert_eq!(clean3, " +2 -2", "Should be ' +2 -2'");
+
+ // Verify vertical alignment: the ones digits should be in the same column
+ // The ones digit should be at position 3 for all cases (with 2-digit allocation)
+ // ' +53 -7' -> position 3 is '3'
+ // ' +33 -23' -> position 3 is '3' (second '3', the ones digit)
+ // ' +2 -2' -> position 3 is '2'
+ let ones_pos = 3;
+ assert_eq!(
+ clean1.chars().nth(ones_pos).unwrap(),
+ '3',
+ "Ones digit of 53 should be at position {ones_pos}"
+ );
+ assert_eq!(
+ clean2.chars().nth(ones_pos).unwrap(),
+ '3',
+ "Ones digit of 33 should be at position {ones_pos}"
+ );
+ assert_eq!(
+ clean3.chars().nth(ones_pos).unwrap(),
+ '2',
+ "Ones digit of 2 should be at position {ones_pos}"
+ );
+ }
+
+ #[test]
+ fn test_diff_column_overflow_handling() {
+ use super::super::columns::DiffVariant;
+
+ // Test overflow with Signs variant (+ and -)
+ // Allocated: 3 digits for added, 3 digits for deleted (total width 9)
+ // Max value: 999
+ let digits = DiffDigits {
+ added: 3,
+ deleted: 3,
+ };
+ let total = 9;
+
+ // Case 1: Value just within limit (should render normally)
+ let result = format_diff_like_column(
+ 999,
+ 999,
+ DiffColumnConfig {
+ digits,
+ total_width: total,
+ display: DiffDisplayConfig {
+ variant: DiffVariant::Signs,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ },
+ },
+ );
+ assert_eq!(result.width(), total);
+ assert!(result.render().contains("999"));
+
+ // Case 2: Positive overflow (1000 exceeds 3 digits)
+ // Should show: "+1K -500" (positive with K suffix, negative normal)
+ let overflow_result = format_diff_like_column(
+ 1000,
+ 500,
+ DiffColumnConfig {
+ digits,
+ total_width: total,
+ display: DiffDisplayConfig {
+ variant: DiffVariant::Signs,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ },
+ },
+ );
+ assert_eq!(overflow_result.width(), total);
+ let rendered = overflow_result.render();
+ assert!(
+ rendered.contains("+1") && rendered.contains('K'),
+ "Positive overflow should show +1K (may have styling), got: {}",
+ rendered
+ );
+ assert!(
+ rendered.contains("500"),
+ "Negative value should show normally when positive overflows, got: {}",
+ rendered
+ );
+
+ // Case 3: Negative overflow
+ // Should show: "+500 -1K" (positive normal, negative with K suffix)
+ let overflow_result2 = format_diff_like_column(
+ 500,
+ 1000,
+ DiffColumnConfig {
+ digits,
+ total_width: total,
+ display: DiffDisplayConfig {
+ variant: DiffVariant::Signs,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ },
+ },
+ );
+ assert_eq!(overflow_result2.width(), total);
+ let rendered2 = overflow_result2.render();
+ assert!(
+ rendered2.contains("500"),
+ "Positive value should show normally when negative overflows, got: {}",
+ rendered2
+ );
+ assert!(
+ rendered2.contains("-1") && rendered2.contains('K'),
+ "Negative overflow should show -1K (may have styling), got: {}",
+ rendered2
+ );
+
+ // Case 4: Extreme overflow (>= 10K values cap at 9K for 2-char limit)
+ let extreme_overflow = format_diff_like_column(
+ 100_000,
+ 200_000,
+ DiffColumnConfig {
+ digits,
+ total_width: total,
+ display: DiffDisplayConfig {
+ variant: DiffVariant::Signs,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ },
+ },
+ );
+ assert_eq!(
+ extreme_overflow.width(),
+ total,
+ "100K overflow should fit in allocated width"
+ );
+ let extreme_rendered = extreme_overflow.render();
+ assert!(
+ extreme_rendered.contains("+9") && extreme_rendered.contains('K'),
+ "100K+ overflow should cap at +9K (may have styling), got: {}",
+ extreme_rendered
+ );
+ assert!(
+ extreme_rendered.contains("-9") && extreme_rendered.contains('K'),
+ "100K+ overflow should cap at -9K (may have styling), got: {}",
+ extreme_rendered
+ );
+
+ // Test overflow with Arrows variant (↑ and ↓)
+ let arrow_digits = DiffDigits {
+ added: 2,
+ deleted: 2,
+ };
+ let arrow_total = 7;
+
+ // Case 5: Arrow positive overflow (100 exceeds 2 digits, max is 99)
+ // Should show with K suffix (not repeated symbols)
+ let arrow_overflow = format_diff_like_column(
+ 1000, // Use larger value to show K suffix
+ 50,
+ DiffColumnConfig {
+ digits: arrow_digits,
+ total_width: arrow_total,
+ display: DiffDisplayConfig {
+ variant: DiffVariant::Arrows,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ },
+ },
+ );
+ assert_eq!(arrow_overflow.width(), arrow_total);
+ let arrow_rendered = arrow_overflow.render();
+ assert!(
+ arrow_rendered.contains("↑1") && arrow_rendered.contains('K'),
+ "Arrow positive overflow should show ↑1K (may have styling), got: {}",
+ arrow_rendered
+ );
+ assert!(
+ arrow_rendered.contains("50"),
+ "Negative value should show normally when positive overflows, got: {}",
+ arrow_rendered
+ );
+
+ // Case 6: Arrow negative overflow
+ // Should show with K suffix
+ let arrow_overflow2 = format_diff_like_column(
+ 50,
+ 1000, // Use larger value to show K suffix
+ DiffColumnConfig {
+ digits: arrow_digits,
+ total_width: arrow_total,
+ display: DiffDisplayConfig {
+ variant: DiffVariant::Arrows,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ },
+ },
+ );
+ assert_eq!(arrow_overflow2.width(), arrow_total);
+ let arrow_rendered2 = arrow_overflow2.render();
+ assert!(
+ arrow_rendered2.contains("50"),
+ "Positive value should show normally when negative overflows, got: {}",
+ arrow_rendered2
+ );
+ assert!(
+ arrow_rendered2.contains("↓1") && arrow_rendered2.contains('K'),
+ "Arrow negative overflow should show ↓1K (may have styling), got: {}",
+ arrow_rendered2
+ );
+ }
}
diff --git a/src/commands/list/spacing_test.rs b/src/commands/list/spacing_test.rs
index 589bf3c94..9cce8cd85 100644
--- a/src/commands/list/spacing_test.rs
+++ b/src/commands/list/spacing_test.rs
@@ -19,11 +19,6 @@ fn test_header_data_alignment_with_and_without_styling() {
let age_header = format!("{:width$}", "Age", width = 14);
header.push_styled(age_header, Style::new().dimmed());
- println!(
- "Header visual: |{}|",
- header.render().replace("\x1b", "\\x1b")
- );
-
// Data row 1: with styling (styled cell)
let mut row1 = StyledLine::new();
let branch1_text = format!("{:width$}", "main", width = branch_width);
@@ -35,16 +30,6 @@ fn test_header_data_alignment_with_and_without_styling() {
let time1_text = format!("{:width$}", "23 minutes ago", width = 14);
row1.push_styled(time1_text, Style::new().dimmed());
- println!(
- "Row 1 styled visual: |{}|",
- row1.render().replace("\x1b", "\\x1b")
- );
- println!(
- "Row 1 styled: branch_text='{}' len={}",
- branch1_text,
- branch1_text.len()
- );
-
// Data row 2: without styling (raw cell)
let mut row2 = StyledLine::new();
let branch2_text = format!("{:width$}", "foo", width = branch_width);
@@ -53,28 +38,11 @@ fn test_header_data_alignment_with_and_without_styling() {
let time2_text = format!("{:width$}", "23 minutes ago", width = 14);
row2.push_styled(time2_text, Style::new().dimmed());
- println!(
- "Row 2 unstyled visual: |{}|",
- row2.render().replace("\x1b", "\\x1b")
- );
- println!(
- "Row 2 unstyled: branch_text='{}' len={}",
- branch2_text,
- branch2_text.len()
- );
-
// Check that all rows have the same width up to the time column
let header_width_before_time = branch_width + 2; // branch + separator
let row1_width_before_time = branch_width + 2;
let row2_width_before_time = branch_width + 2;
- println!(
- "\nExpected width before time column: {}",
- header_width_before_time
- );
- println!("Row 1 width before time: {}", row1_width_before_time);
- println!("Row 2 width before time: {}", row2_width_before_time);
-
assert_eq!(
header_width_before_time, row1_width_before_time,
"Header and styled row should align"
diff --git a/src/commands/list/status_column_tests.rs b/src/commands/list/status_column_tests.rs
deleted file mode 100644
index 96f14b473..000000000
--- a/src/commands/list/status_column_tests.rs
+++ /dev/null
@@ -1,469 +0,0 @@
-//! Unit tests for Status column git symbol rendering
-//!
-//! These tests verify the grid-based rendering of git status symbols in `StatusSymbols.render_with_mask()`.
-//!
-//! ## Grid-Based Rendering Model
-//!
-//! - Each symbol type has a fixed position (0a, 0b, 0c, 0d, 1, 2, 3, 4)
-//! - Position 4 is user-defined status (custom labels, emoji)
-//! - Only positions used by at least one row are included (position mask)
-//! - Rendering creates a grid: first position in mask = column 0
-//! - Each position maps to exactly one column
-//! - **Multiple symbols from the same position** appear together in that column (e.g., "?!+" all at position 3)
-//! - Symbols fill their position's column, empty positions get spaces
-//! - Example: mask [0b, 3, 4] creates 3-column grid:
-//! - Row with ≡ at 0b: "≡ " (≡ at col 0, space at col 1 and 2)
-//! - Row with ! at 3: " ! " (space at col 0, ! at col 1, space at col 2)
-//! - Row with 🤖 at 4: " 🤖" (space at col 0 and 1, 🤖 at col 2)
-//!
-//! User status is now part of the unified grid system (Position 4) and aligns vertically
-//! with all other status indicators. Integration tests verify user status behavior.
-//!
-//! Each test specifies the exact expected output to make the target behavior explicit.
-
-#[cfg(test)]
-mod status_column_rendering_tests {
- use worktrunk::styling::strip_ansi_codes;
-
- /// Helper to check visual output (strips ANSI codes for comparison)
- fn assert_visual_eq(actual: &str, expected_visual: &str) {
- let actual_visual = strip_ansi_codes(actual);
- assert_eq!(
- actual_visual, expected_visual,
- "Visual output mismatch:\n actual (with ANSI): {:?}\n actual (visual): {:?}\n expected (visual): {:?}",
- actual, actual_visual, expected_visual
- );
- }
-
- /// Test 1: Single symbol at position 0b (branch state)
- // Row 1: ≡ (synced with remote)
- // Expected: "≡" (dimmed)
- #[test]
- fn test_single_symbol_position_0b() {
- use super::super::model::{BranchState, StatusSymbols};
-
- // Symbols: [≡]
- // Max git width: 1
- // User status: None
- // Expected: dimmed "≡" (no padding, no user status)
- let symbols = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- ..Default::default()
- };
-
- let mask = symbols.position_mask();
- let result = symbols.render_with_mask(&mask);
-
- // Check visual output (symbols should be styled, but we compare visual content)
- assert_visual_eq(&result, "≡");
- }
-
- /// Test 2: Single symbol at position 3 (working tree)
- // Row 1: ! (uncommitted changes)
- // Expected: "!" (cyan)
- #[test]
- fn test_single_symbol_position_3() {
- use super::super::model::StatusSymbols;
-
- // Symbols: [!]
- // Max git width: 1
- // User status: None
- // Expected: cyan "!" (no padding, no user status)
- let symbols = StatusSymbols {
- working_tree: "!".to_string(),
- ..Default::default()
- };
-
- let mask = symbols.position_mask();
- let result = symbols.render_with_mask(&mask);
-
- // Check visual output (symbols should be styled, but we compare visual content)
- assert_visual_eq(&result, "!");
- }
-
- /// Test 3: Two symbols at different positions create alignment grid
- /// Mask [0b, 3] creates 2-column grid:
- /// - Column 0 = position 0b
- /// - Column 1 = position 3
- // Row 1: ≡ (position 0b)
- // Row 2: ! (position 3)
- // Expected:
- // Row 1: "≡ " (≡ in col 0, space in col 1)
- // Row 2: " !" (space in col 0, ! in col 1)
- #[test]
- fn test_two_different_positions_align() {
- use super::super::model::{BranchState, StatusSymbols};
-
- // Position mask: [0 (working tree), 5 (branch state)] → 2-column grid
- // Row 1: symbol at position 5 (col 1)
- // Row 2: symbol at position 0 (col 0)
-
- // Create mask from row that has both positions
- let mask_builder = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- working_tree: "!".to_string(),
- ..Default::default()
- };
- let mask = mask_builder.position_mask();
-
- // Row 1: only position 5 (branch state)
- let row1 = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- ..Default::default()
- };
- assert_visual_eq(&row1.render_with_mask(&mask), " ≡");
-
- // Row 2: only position 0 (working tree)
- let row2 = StatusSymbols {
- working_tree: "!".to_string(),
- ..Default::default()
- };
- assert_visual_eq(&row2.render_with_mask(&mask), "! ");
- }
-
- /// Test 4: Same position symbols - single column grid
- /// Mask [3] creates 1-column grid:
- /// - Column 0 = position 3
- // Row 1: ! (position 3)
- // Row 2: ? (position 3)
- // Expected:
- // Row 1: "!" (col 0 filled with !)
- // Row 2: "?" (col 0 filled with ?)
- #[test]
- fn test_same_position_symbols_no_padding() {
- use super::super::model::StatusSymbols;
-
- // Position mask: [3] → 1-column grid
- // Both rows have symbol at position 3 (col 0)
-
- // Mask includes only position 3
- let mask_builder = StatusSymbols {
- working_tree: "!".to_string(),
- ..Default::default()
- };
- let mask = mask_builder.position_mask();
-
- // Row 1: ! at position 3
- let row1 = StatusSymbols {
- working_tree: "!".to_string(),
- ..Default::default()
- };
- assert_visual_eq(&row1.render_with_mask(&mask), "!");
-
- // Row 2: ? at position 3
- let row2 = StatusSymbols {
- working_tree: "?".to_string(),
- ..Default::default()
- };
- assert_visual_eq(&row2.render_with_mask(&mask), "?");
- }
-
- /// Test 5: Multiple symbols in one row fill multiple columns
- /// Mask [0 (working tree), 5 (branch state)] creates 2-column grid:
- /// - Column 0 = position 0 (working tree)
- /// - Column 1 = position 5 (branch state)
- // Row 1: ?≡ (both positions filled)
- // Expected: "?≡" (col 0=?, col 1=≡)
- #[test]
- fn test_multiple_symbols_one_row() {
- use super::super::model::{BranchState, StatusSymbols};
-
- // Position mask: [0 (working tree), 5 (branch state)] → 2-column grid
- // Row 1: symbols at both positions
- // Expected: "?≡" (both columns filled, no spaces)
- let row = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- working_tree: "?".to_string(),
- ..Default::default()
- };
-
- let mask = row.position_mask();
- assert_visual_eq(&row.render_with_mask(&mask), "?≡");
- }
-
- /// Test 6: Grid with some columns empty
- /// Mask [0 (working tree), 5 (branch state)] creates 2-column grid:
- /// - Column 0 = position 0 (working tree)
- /// - Column 1 = position 5 (branch state)
- // Row 1: ≡ (only position 5)
- // Row 2: !≡ (both positions)
- // Expected:
- // Row 1: " ≡" (col 0=space, col 1=≡)
- // Row 2: "!≡" (col 0=!, col 1=≡)
- #[test]
- fn test_multiple_symbols_with_position_gap() {
- use super::super::model::{BranchState, StatusSymbols};
-
- // Position mask: [0 (working tree), 5 (branch state)] → 2-column grid
- // Row 1: col 1 filled, col 0 empty
- // Row 2: both columns filled
-
- // Create mask from row with both positions
- let mask_builder = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- working_tree: "!".to_string(),
- ..Default::default()
- };
- let mask = mask_builder.position_mask();
-
- // Row 1: only position 5 (branch state)
- let row1 = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- ..Default::default()
- };
- assert_visual_eq(&row1.render_with_mask(&mask), " ≡");
-
- // Row 2: both positions
- let row2 = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- working_tree: "!".to_string(),
- ..Default::default()
- };
- assert_visual_eq(&row2.render_with_mask(&mask), "!≡");
- }
-
- /// Test 12: Empty status (no symbols, no user status)
- // Expected: ""
- #[test]
- fn test_empty_status() {
- use super::super::model::StatusSymbols;
-
- // Git symbols: None
- // User status: None
- // Expected: "" (empty string)
- let symbols = StatusSymbols::default();
- let mask = symbols.position_mask();
-
- assert_visual_eq(&symbols.render_with_mask(&mask), "");
- }
-
- /// Test 14: Three positions create 3-column grid
- /// Mask [0 (working tree), 3 (main divergence), 5 (branch state)] creates 3-column grid:
- /// - Column 0 = position 0 (working tree)
- /// - Column 1 = position 3 (main divergence)
- /// - Column 2 = position 5 (branch state)
- // Row 1: ≡ (position 5)
- // Row 2: ↓ (position 3)
- // Row 3: ! (position 0)
- // Expected:
- // Row 1: " ≡" (col 0=space, col 1=space, col 2=≡)
- // Row 2: " ↓ " (col 0=space, col 1=↓, col 2=space)
- // Row 3: "! " (col 0=!, col 1=space, col 2=space)
- #[test]
- fn test_three_different_positions() {
- use super::super::model::{BranchState, MainDivergence, StatusSymbols};
-
- // Position mask: [0 (working tree), 3 (main divergence), 5 (branch state)] → 3-column grid
- // Create mask from all three positions
- let mask_builder = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- main_divergence: MainDivergence::Behind,
- working_tree: "!".to_string(),
- ..Default::default()
- };
- let mask = mask_builder.position_mask();
-
- // Row 1: only position 5 (branch state)
- let row1 = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- ..Default::default()
- };
- assert_visual_eq(&row1.render_with_mask(&mask), " ≡");
-
- // Row 2: only position 3 (main divergence)
- let row2 = StatusSymbols {
- main_divergence: MainDivergence::Behind,
- ..Default::default()
- };
- assert_visual_eq(&row2.render_with_mask(&mask), " ↓ ");
-
- // Row 3: only position 0 (working tree)
- let row3 = StatusSymbols {
- working_tree: "!".to_string(),
- ..Default::default()
- };
- assert_visual_eq(&row3.render_with_mask(&mask), "! ");
- }
-
- /// Test 15: Adjacent positions (2 git_operation and 5 branch_state)
- // Row 1: ↻≡ (position 2 + 5, git operation first in render order)
- // Expected: "↻≡"
- #[test]
- fn test_adjacent_positions_no_space() {
- use super::super::model::{BranchState, GitOperation, StatusSymbols};
-
- // Symbols: [↻≡]
- // Position mask: 2 (git_operation) + 5 (branch_state)
- // Expected: "↻≡" (git operation renders before branch state)
- let row = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- git_operation: GitOperation::Rebase,
- ..Default::default()
- };
-
- let mask = row.position_mask();
- assert_visual_eq(&row.render_with_mask(&mask), "↻≡");
- }
-
- /// Test 16: Non-adjacent positions with all filled
- // Row 1: !+≡ (position 0 working tree + position 5 branch state)
- // Expected: "!+≡"
- #[test]
- fn test_all_positions_filled() {
- use super::super::model::{BranchState, StatusSymbols};
-
- // Symbols: [!+≡]
- // Position mask: 0 (working tree) + 5 (branch state)
- // Expected: "!+≡" (no spaces, all positions filled, working tree renders first)
- let row = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- working_tree: "!+".to_string(), // Multiple symbols at position 0
- ..Default::default()
- };
-
- let mask = row.position_mask();
- assert_visual_eq(&row.render_with_mask(&mask), "!+≡");
- }
-
- /// Test 17: Real-world complex case 1
- /// 3-column grid: [0 (working tree), 3 (main divergence), 5 (branch state)]
- /// - Column 0 = position 0 (working tree, max width=2 for "!+")
- /// - Column 1 = position 3 (main divergence, width=1)
- /// - Column 2 = position 5 (branch state, width=1)
- // Row 1: ? ≡ (working tree + branch state, no main divergence)
- // Row 2: ! (working tree only)
- // Row 3: !+↓ (working tree + main divergence, no branch state)
- // Expected:
- // Row 1: "? ≡" (col 0=? padded to 2, col 1=space, col 2=≡)
- // Row 2: "! " (col 0=! padded to 2, col 1=space, col 2=space)
- // Row 3: "!+↓ " (col 0=!+ width 2, col 1=↓, col 2=space)
- #[test]
- fn test_real_world_complex_1() {
- use super::super::model::{BranchState, MainDivergence, StatusSymbols};
-
- // Position mask: 0 (working tree) + 3 (main divergence) + 5 (branch state) (3-column grid)
- // Row 1: 0=?, 5=≡, user=🤖 (user status tested separately)
- // Row 2: 0=!
- // Row 3: 0=!+, 3=↓
-
- // Create mask from all positions
- let mask_builder = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- main_divergence: MainDivergence::Behind,
- working_tree: "!+".to_string(),
- ..Default::default()
- };
- let mask = mask_builder.position_mask();
-
- // Row 1: position 0 (working tree) and 5 (branch state) (note: user status alignment tested separately)
- let row1 = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- working_tree: "?".to_string(),
- ..Default::default()
- };
- assert_visual_eq(&row1.render_with_mask(&mask), "? ≡");
-
- // Row 2: only position 0 (working tree)
- let row2 = StatusSymbols {
- working_tree: "!".to_string(),
- ..Default::default()
- };
- assert_visual_eq(&row2.render_with_mask(&mask), "! ");
-
- // Row 3: position 0 (working tree) and 3 (main divergence)
- let row3 = StatusSymbols {
- main_divergence: MainDivergence::Behind,
- working_tree: "!+".to_string(),
- ..Default::default()
- };
- assert_visual_eq(&row3.render_with_mask(&mask), "!+↓ ");
- }
-
- /// Test 18: THE FAILING TEST - 2-column grid with partial fills
- /// Mask [0 (working tree), 5 (branch state)] creates 2-column grid:
- /// - Column 0 = position 0 (working tree)
- /// - Column 1 = position 5 (branch state)
- // Row 1: ?≡ (untracked + synced)
- // Row 2: ! (uncommitted only)
- // Expected:
- // Row 1: "?≡" (col 0=?, col 1=≡)
- // Row 2: "! " (col 0=!, col 1=space)
- #[test]
- fn test_real_world_extreme_diffs() {
- use super::super::model::{BranchState, StatusSymbols};
-
- // This is the actual failing test case from spacing_edge_cases
- // Position mask: [0 (working tree), 5 (branch state)] → 2-column grid
- // Row 1 (huge): symbols at positions 0 (?) and 5 (≡)
- // Row 2 (tiny): symbol at position 0 (!) only
-
- // Create mask from row with both positions
- let mask_builder = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- working_tree: "?".to_string(),
- ..Default::default()
- };
- let mask = mask_builder.position_mask();
-
- // Row 1: both columns filled
- let row1 = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- working_tree: "?".to_string(),
- ..Default::default()
- };
- assert_visual_eq(&row1.render_with_mask(&mask), "?≡");
-
- // Row 2: only position 0 (working tree) (col 0 filled, col 1 empty→space)
- let row2 = StatusSymbols {
- working_tree: "!".to_string(),
- ..Default::default()
- };
- assert_visual_eq(&row2.render_with_mask(&mask), "! ");
- }
-
- /// Test 20: Position mask creates minimal grid
- /// All positions available: 0, 1, 2, 3, 4, 5, 6, 7 (8 total)
- /// Used positions: 0 (working tree), 5 (branch state) (2 used)
- /// Mask [0, 5] creates 2-column grid (NOT 8-column):
- /// - Column 0 = position 0 (working tree)
- /// - Column 1 = position 5 (branch state)
- // Row 1: ≡ (only position 5 used)
- // Row 2: ! (only position 0 used)
- // Expected:
- // Row 1: " ≡" (2 chars: col 0=space, col 1=≡)
- // Row 2: "! " (2 chars: col 0=!, col 1=space)
- // NOT:
- // Row 1: " ≡" (8 chars with spaces for all positions)
- #[test]
- fn test_position_mask_removes_unused_positions() {
- use super::super::model::{BranchState, StatusSymbols};
-
- // Position mask: [0 (working tree), 5 (branch state)] → 2-column grid
- // Only used positions create columns
- // Expected: 2-char width (NOT 8-char for all possible positions)
-
- // Create mask from positions 0 and 5 only
- let mask_builder = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- working_tree: "!".to_string(),
- ..Default::default()
- };
- let mask = mask_builder.position_mask();
-
- // Row 1: only position 5 (branch state)
- let row1 = StatusSymbols {
- branch_state: BranchState::MatchesMain,
- ..Default::default()
- };
- let result1 = row1.render_with_mask(&mask);
- assert_visual_eq(&result1, " ≡");
-
- // Row 2: only position 0 (working tree)
- let row2 = StatusSymbols {
- working_tree: "!".to_string(),
- ..Default::default()
- };
- let result2 = row2.render_with_mask(&mask);
- assert_visual_eq(&result2, "! ");
- }
-}
diff --git a/src/commands/list/timing.rs b/src/commands/list/timing.rs
new file mode 100644
index 000000000..fe48986f8
--- /dev/null
+++ b/src/commands/list/timing.rs
@@ -0,0 +1,147 @@
+use std::collections::HashMap;
+use std::env;
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+const DEBUG_ENV_VAR: &str = "WT_LIST_DEBUG";
+const DEBUG_ENV_VALUE: &str = "1";
+
+/// Operation names for tracking timing
+#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
+pub enum OpName {
+ CommitDetails,
+ AheadBehind,
+ UpstreamStatus,
+ GitStatus,
+ WorkingTreeDiff,
+ WorkingTreeDiffWithMain,
+ BranchDiff,
+ WorktreeState,
+ // TODO(timing): Add PrStatus timing when CI/PR status collection is instrumented
+ PrStatus,
+ MergeConflicts,
+ UserStatus,
+}
+
+impl OpName {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ OpName::CommitDetails => "commit_details",
+ OpName::AheadBehind => "ahead_behind",
+ OpName::UpstreamStatus => "upstream_status",
+ OpName::GitStatus => "git_status",
+ OpName::WorkingTreeDiff => "working_tree_diff",
+ OpName::WorkingTreeDiffWithMain => "working_tree_diff_with_main",
+ OpName::BranchDiff => "branch_diff",
+ OpName::WorktreeState => "worktree_state",
+ OpName::PrStatus => "pr_status",
+ OpName::MergeConflicts => "merge_conflicts",
+ OpName::UserStatus => "user_status",
+ }
+ }
+}
+
+/// Collects timing data for list operations.
+/// Thread-safe for use with parallel iterators (rayon).
+#[derive(Clone)]
+pub struct TimingCollector {
+ inner: Option<Arc<Mutex<TimingData>>>,
+}
+
+#[derive(Default)]
+struct TimingData {
+ timings: HashMap<OpName, Vec<Duration>>,
+}
+
+impl TimingCollector {
+ /// Create a new collector if WT_LIST_DEBUG=1 is set
+ pub fn new() -> Self {
+ let enabled = env::var(DEBUG_ENV_VAR).ok().as_deref() == Some(DEBUG_ENV_VALUE);
+ Self {
+ inner: if enabled {
+ Some(Arc::new(Mutex::new(TimingData::default())))
+ } else {
+ None
+ },
+ }
+ }
+
+ /// Execute a closure and record its timing
+ pub fn measure<F, R>(&self, op: OpName, f: F) -> R
+ where
+ F: FnOnce() -> R,
+ {
+ if self.inner.is_none() {
+ return f();
+ }
+
+ let start = Instant::now();
+ let result = f();
+ let duration = start.elapsed();
+
+ if let Some(ref data) = self.inner {
+ let mut guard = data.lock().unwrap();
+ guard.timings.entry(op).or_default().push(duration);
+ }
+
+ result
+ }
+
+ /// Print timing summary to stderr
+ pub fn print_summary(&self) {
+ let Some(ref data) = self.inner else {
+ return;
+ };
+
+ let guard = data.lock().unwrap();
+ if guard.timings.is_empty() {
+ return;
+ }
+
+ log::debug!("WT_LIST_DEBUG timing summary:");
+
+ let mut ops: Vec<_> = guard.timings.iter().collect();
+ ops.sort_by_key(|(op, _)| op.as_str());
+
+ for (op, durations) in ops {
+ let stats = compute_stats(durations);
+ log::debug!(
+ " {:<30} median: {:>6.1}ms p95: {:>6.1}ms count: {}",
+ op.as_str(),
+ stats.median_ms,
+ stats.p95_ms,
+ durations.len()
+ );
+ }
+ }
+}
+
+struct Stats {
+ median_ms: f64,
+ p95_ms: f64,
+}
+
+fn compute_stats(durations: &[Duration]) -> Stats {
+ let mut sorted: Vec<_> = durations.iter().map(|d| d.as_secs_f64() * 1000.0).collect();
+ sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
+
+ let median_ms = if sorted.is_empty() {
+ 0.0
+ } else {
+ let mid = sorted.len() / 2;
+ if sorted.len() % 2 == 0 {
+ (sorted[mid - 1] + sorted[mid]) / 2.0
+ } else {
+ sorted[mid]
+ }
+ };
+
+ let p95_ms = if sorted.is_empty() {
+ 0.0
+ } else {
+ let idx = ((sorted.len() - 1) as f64 * 0.95).round() as usize;
+ sorted[idx]
+ };
+
+ Stats { median_ms, p95_ms }
+}
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 0c0b5fa7d..5c5717074 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -1,15 +1,13 @@
-use rayon::prelude::*;
use std::path::{Path, PathBuf};
use std::process;
use std::time::{SystemTime, UNIX_EPOCH};
-use super::list::model::{BranchInfo, ListData, ListItem, WorktreeInfo};
use super::worktree::RemoveResult;
use worktrunk::config::ProjectConfig;
use worktrunk::git::{GitError, GitResultExt, Repository};
use worktrunk::styling::{
CYAN, CYAN_BOLD, ERROR, ERROR_EMOJI, HINT, HINT_BOLD, HINT_EMOJI, WARNING, WARNING_BOLD,
- WARNING_EMOJI, format_with_gutter, println,
+ format_with_gutter,
};
/// CLI-only helpers implemented on [`Repository`] via an extension trait so we can keep orphan
@@ -24,18 +22,7 @@ pub trait RepositoryCliExt {
/// Warn about untracked files being auto-staged.
fn warn_if_auto_staging_untracked(&self) -> Result<(), GitError>;
- /// Gather enriched list data for worktrees (and optional branches).
- fn gather_list_data(
- &self,
- show_branches: bool,
- fetch_ci: bool,
- check_conflicts: bool,
- ) -> Result<Option<ListData>, GitError>;
-
/// Remove a worktree identified by branch name.
- ///
- /// When removing the current worktree from the main repo, automatically checks if
- /// already on default branch or switches to it first.
fn remove_worktree_by_name(
&self,
branch_name: &str,
@@ -83,89 +70,6 @@ impl RepositoryCliExt for Repository {
AutoStageWarning::from_status(&status).emit()
}
- fn gather_list_data(
- &self,
- show_branches: bool,
- fetch_ci: bool,
- check_conflicts: bool,
- ) -> Result<Option<ListData>, GitError> {
- let worktrees = self.list_worktrees()?;
-
- if worktrees.worktrees.is_empty() {
- return Ok(None);
- }
-
- let primary = worktrees.worktrees[0].clone();
- let current_worktree_path = self.worktree_root().ok();
-
- let worktree_results: Vec<Result<WorktreeInfo, GitError>> = worktrees
- .worktrees
- .par_iter()
- .map(|wt| WorktreeInfo::from_worktree(wt, &primary, fetch_ci, check_conflicts))
- .collect();
-
- let mut items = Vec::new();
- for result in worktree_results {
- match result {
- Ok(info) => items.push(ListItem::Worktree(info)),
- Err(e) => return Err(e),
- }
- }
-
- if show_branches {
- let available_branches = self.available_branches()?;
- let primary_branch = primary.branch.as_deref();
-
- let branch_results: Vec<(String, Result<BranchInfo, GitError>)> = available_branches
- .par_iter()
- .map(|branch| {
- let result = BranchInfo::from_branch(
- branch,
- self,
- primary_branch,
- fetch_ci,
- check_conflicts,
- );
- (branch.clone(), result)
- })
- .collect();
-
- for (branch, result) in branch_results {
- match result {
- Ok(info) => items.push(ListItem::Branch(info)),
- Err(e) => {
- println!(
- "{WARNING_EMOJI} {WARNING}Failed to enrich branch {WARNING_BOLD}{branch}{WARNING_BOLD:#}{WARNING}: {e} (will show with limited information){WARNING:#}"
- );
- }
- }
- }
- }
-
- items.sort_by_key(|item| {
- let is_primary = item.is_primary();
- let is_current = item
- .worktree_path()
- .and_then(|p| current_worktree_path.as_ref().map(|cp| p == cp))
- .unwrap_or(false);
-
- let priority = if is_primary {
- 0
- } else if is_current {
- 1
- } else {
- 2
- };
-
- (priority, std::cmp::Reverse(item.commit_timestamp()))
- });
-
- Ok(Some(ListData {
- items,
- current_worktree_path,
- }))
- }
-
fn remove_worktree_by_name(
&self,
branch_name: &str,
@@ -192,11 +96,6 @@ impl RepositoryCliExt for Repository {
let current_worktree = self.worktree_root()?;
let removing_current = current_worktree == worktree_path;
- // Error if trying to remove main worktree (align with git behavior)
- if removing_current && !self.is_in_worktree()? {
- return Err(GitError::CannotRemoveMainWorktree);
- }
-
let (primary_path, changed_directory) = if removing_current {
let worktrees = self.list_worktrees()?;
(worktrees.worktrees[0].path.clone(), true)
diff --git a/src/commands/select.rs b/src/commands/select.rs
index 13495d0f9..5b0009ab0 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -6,8 +6,8 @@ use std::sync::{Arc, OnceLock};
use worktrunk::config::WorktrunkConfig;
use worktrunk::git::{GitError, GitResultExt, Repository};
+use super::list::collect;
use super::list::model::ListItem;
-use super::repository_ext::RepositoryCliExt;
use super::worktree::handle_switch;
use crate::output::{blank_line, handle_switch_output};
@@ -146,7 +146,7 @@ impl WorktreeSkimItem {
/// Render Mode 1: Working tree preview (uncommitted changes vs HEAD)
/// Matches `wt list` "HEAD±" column
fn render_working_tree_preview(&self) -> String {
- let Some(wt_info) = self.item.worktree_info() else {
+ let Some(wt_info) = self.item.worktree_data() else {
return "No worktree (branch only)\n".to_string();
};
@@ -248,8 +248,15 @@ pub fn handle_select() -> Result<(), GitError> {
// Initialize preview mode state file (auto-cleanup on drop)
let _state = PreviewState::new();
- // Gather list data using existing logic
- let Some(list_data) = repo.gather_list_data(false, false, false)? else {
+ // Gather list data using simplified collection (buffered mode)
+ let Some(list_data) = collect::collect(
+ &repo, false, // show_branches (select only shows worktrees, not branches)
+ false, // show_full (no full layout needed)
+ false, // fetch_ci (no CI with select command)
+ false, // check_conflicts (no conflict checking with select command)
+ false, // show_progress (no progress bars)
+ )?
+ else {
return Ok(());
};
@@ -267,19 +274,15 @@ pub fn handle_select() -> Result<(), GitError> {
.into_iter()
.map(|item| {
let branch_name = item.branch_name().to_string();
- let commit_msg = item
- .commit_details()
- .commit_message
- .lines()
- .next()
- .unwrap_or("");
+ let commit_details = item.commit_details();
+ let commit_msg = commit_details.commit_message.lines().next().unwrap_or("");
// Build display text with aligned columns
let mut display_text = format!("{:<width$}", branch_name, width = max_branch_len);
- // Add status symbols for worktrees (fixed width)
- let status = if let Some(wt_info) = item.worktree_info() {
- format!("{:<8}", wt_info.status_symbols.render())
+ // Add status symbols (fixed width)
+ let status = if let Some(ref status_symbols) = item.status_symbols {
+ format!("{:<8}", status_symbols.render())
} else {
" ".to_string()
};
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index e76f8fd73..42ff21908 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -579,27 +579,55 @@ impl Repository {
/// Returns (ahead, behind) where ahead is commits in head not in base,
/// and behind is commits in base not in head.
pub fn ahead_behind(&self, base: &str, head: &str) -> Result<(usize, usize), GitError> {
- // Acquire permit once for both rev-list operations to avoid nested acquisition
- let _guard = super::HEAVY_OPS_SEMAPHORE.acquire();
-
- let range_ahead = format!("{}..{}", base, head);
- let range_behind = format!("{}..{}", head, base);
-
- let stdout_ahead = self.run_command(&["rev-list", "--count", &range_ahead])?;
- let stdout_behind = self.run_command(&["rev-list", "--count", &range_behind])?;
+ // Use single git call with --left-right --count for better performance
+ let range = format!("{}...{}", base, head);
+ let output = self.run_command(&["rev-list", "--left-right", "--count", &range])?;
+
+ // Parse output: "<behind>\t<ahead>" format
+ // Example: "5\t3" means 5 commits behind, 3 commits ahead
+ // git rev-list --left-right outputs left (base) first, then right (head)
+ let parts: Vec<&str> = output.trim().split('\t').collect();
+ if parts.len() != 2 {
+ return Err(GitError::CommandFailed(format!(
+ "Unexpected rev-list output format: {}",
+ output
+ )));
+ }
- let ahead = stdout_ahead
- .trim()
+ let behind: usize = parts[0]
.parse()
- .map_err(|e| GitError::ParseError(format!("Failed to parse ahead count: {}", e)))?;
- let behind = stdout_behind
- .trim()
+ .map_err(|e| GitError::CommandFailed(format!("Failed to parse behind count: {}", e)))?;
+ let ahead: usize = parts[1]
.parse()
- .map_err(|e| GitError::ParseError(format!("Failed to parse behind count: {}", e)))?;
+ .map_err(|e| GitError::CommandFailed(format!("Failed to parse ahead count: {}", e)))?;
Ok((ahead, behind))
}
+ /// List all local branches with their HEAD commit SHA.
+ /// Returns a vector of (branch_name, commit_sha) tuples.
+ pub fn list_local_branches(&self) -> Result<Vec<(String, String)>, GitError> {
+ let output = self.run_command(&[
+ "for-each-ref",
+ "--format=%(refname:short) %(objectname)",
+ "refs/heads/",
+ ])?;
+
+ let branches: Vec<(String, String)> = output
+ .lines()
+ .filter_map(|line| {
+ let parts: Vec<&str> = line.split_whitespace().collect();
+ if parts.len() == 2 {
+ Some((parts[0].to_string(), parts[1].to_string()))
+ } else {
+ None
+ }
+ })
+ .collect();
+
+ Ok(branches)
+ }
+
/// Get line diff statistics for working tree changes (unstaged + staged).
pub fn working_tree_diff_stats(&self) -> Result<LineDiff, GitError> {
// Limit concurrent diff operations to reduce mmap thrash on pack files
@@ -774,11 +802,10 @@ impl Repository {
/// # Ok::<(), worktrunk::git::GitError>(())
/// ```
pub fn has_merge_conflicts(&self, base: &str, head: &str) -> Result<bool, GitError> {
- let merge_base = self.merge_base(base, head)?;
-
- // git merge-tree exits with 0 for clean merge, 1 for conflicts
+ // Use modern merge-tree --write-tree mode which exits with 1 when conflicts exist
+ // (the old 3-argument deprecated mode always exits with 0)
// run_command_check returns true for exit 0, false otherwise
- let clean_merge = self.run_command_check(&["merge-tree", &merge_base, base, head])?;
+ let clean_merge = self.run_command_check(&["merge-tree", "--write-tree", base, head])?;
Ok(!clean_merge)
}
diff --git a/src/main.rs b/src/main.rs
index 899329011..07062662c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -211,7 +211,16 @@ fn main() {
format,
branches,
full,
- } => handle_list(format, branches, full),
+ progressive,
+ no_progressive,
+ } => handle_list(
+ format,
+ branches,
+ full,
+ progressive,
+ no_progressive,
+ cli.internal,
+ ),
Commands::Switch {
branch,
create,
diff --git a/src/output/directive.rs b/src/output/directive.rs
index d050419d7..a72acad23 100644
--- a/src/output/directive.rs
+++ b/src/output/directive.rs
@@ -105,6 +105,22 @@ impl DirectiveOutput {
io::stderr().flush()
}
+ pub fn raw(&mut self, content: String) -> io::Result<()> {
+ // Raw output without emoji decoration - for structured data like JSON
+ // In directive mode, even JSON goes to stderr (stdout is reserved for directives)
+ use worktrunk::styling::eprintln;
+ eprintln!("{content}");
+ io::stderr().flush()
+ }
+
+ pub fn raw_terminal(&mut self, content: String) -> io::Result<()> {
+ // Raw output to stderr - for table output
+ // In directive mode, this is the same as raw() since everything goes to stderr
+ use worktrunk::styling::eprintln;
+ eprintln!("{content}");
+ io::stderr().flush()
+ }
+
pub fn change_directory(&mut self, path: &Path) -> io::Result<()> {
write!(io::stdout(), "__WORKTRUNK_CD__{}\0", path.display())?;
io::stdout().flush()
diff --git a/src/output/global.rs b/src/output/global.rs
index 2a18c5b2a..5367b9e17 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -177,6 +177,51 @@ pub fn gutter(content: impl Into<String>) -> io::Result<()> {
})
}
+/// Emit raw output without emoji decoration
+///
+/// Used for structured data like JSON. Goes to stdout in interactive mode,
+/// stderr in directive mode (where stdout is reserved for directives).
+///
+/// Example:
+/// ```rust,ignore
+/// output::raw(json_string)?;
+/// ```
+pub fn raw(content: impl Into<String>) -> io::Result<()> {
+ OUTPUT_CONTEXT.with(|ctx| {
+ let c = content.into();
+ match &mut *ctx.borrow_mut() {
+ OutputHandler::Interactive(i) => i.raw(c),
+ OutputHandler::Directive(d) => d.raw(c),
+ }
+ })
+}
+
+/// Emit raw terminal output to stderr
+///
+/// Used for table output that should appear on the same stream as progress bars.
+/// Goes to stderr in both interactive and directive modes.
+///
+/// TODO: This split between raw() and raw_terminal() is messy. Consider unifying
+/// the output system to have a clearer separation between structured data (JSON)
+/// and terminal UI (tables, progress bars).
+///
+/// Example:
+/// ```rust,ignore
+/// output::raw_terminal(layout.format_header_line())?;
+/// for item in items {
+/// output::raw_terminal(layout.format_item_line(item))?;
+/// }
+/// ```
+pub fn raw_terminal(content: impl Into<String>) -> io::Result<()> {
+ OUTPUT_CONTEXT.with(|ctx| {
+ let c = content.into();
+ match &mut *ctx.borrow_mut() {
+ OutputHandler::Interactive(i) => i.raw_terminal(c),
+ OutputHandler::Directive(d) => d.raw_terminal(c),
+ }
+ })
+}
+
/// Request directory change (for shell integration)
pub fn change_directory(path: impl AsRef<Path>) -> io::Result<()> {
OUTPUT_CONTEXT.with(|ctx| {
diff --git a/src/output/interactive.rs b/src/output/interactive.rs
index e8c0c01c2..79fb2c9e3 100644
--- a/src/output/interactive.rs
+++ b/src/output/interactive.rs
@@ -86,6 +86,24 @@ impl InteractiveOutput {
Ok(())
}
+ pub fn raw(&mut self, content: String) -> io::Result<()> {
+ // Raw output without emoji decoration - for structured data like JSON
+ println!("{content}");
+ stdout().flush()?;
+ Ok(())
+ }
+
+ pub fn raw_terminal(&mut self, content: String) -> io::Result<()> {
+ // Raw output to stderr - for table output that should match progressive bars stream
+ // TODO: This split between raw() and raw_terminal() is messy. Consider unifying
+ // the output system to have a clearer separation between structured data (JSON)
+ // and terminal UI (tables, progress bars).
+ use worktrunk::styling::eprintln;
+ eprintln!("{content}");
+ stderr().flush()?;
+ Ok(())
+ }
+
pub fn change_directory(&mut self, path: &Path) -> io::Result<()> {
// In interactive mode, we can't actually change directory
// Just store the target for execute commands
diff --git a/src/output/mod.rs b/src/output/mod.rs
index cc2ab2c30..9deebeb0f 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -63,7 +63,8 @@ pub mod interactive;
// Re-export the public API
pub use global::{
OutputMode, change_directory, error, execute, flush, flush_for_stderr_prompt, gutter, hint,
- info, initialize, progress, shell_integration_hint, success, terminate_output, warning,
+ info, initialize, progress, raw, raw_terminal, shell_integration_hint, success,
+ terminate_output, warning,
};
// blank_line is only used by select command which is Unix-only
diff --git a/src/styling/highlighting.rs b/src/styling/highlighting.rs
index f0b4620d8..95b4bb807 100644
--- a/src/styling/highlighting.rs
+++ b/src/styling/highlighting.rs
@@ -11,14 +11,17 @@ use synoptic::{TokOpt, from_extension};
/// Maps bash token kinds to anstyle styles
///
-/// Token names come from tree-sitter-bash's highlight queries.
-/// Common tokens include:
-/// - "function": commands like npm, git, cargo, echo, cd
+/// Token names come from tree-sitter-bash 0.25's highlight queries.
+/// Must match the @-names in highlights.scm:
+/// - "function": commands (command_name nodes)
/// - "keyword": bash keywords (if, then, for, while, do, done, etc.)
/// - "string": quoted strings
/// - "comment": hash-prefixed comments
-/// - "operator": operators like &&, ||, |, $, -, etc.
-/// - "constant": flags (arguments starting with -)
+/// - "operator": operators (&&, ||, |, $, -, etc.)
+/// - "property": variables (variable_name nodes)
+/// - "constant": constants/flags
+/// - "number": numeric values
+/// - "embedded": embedded content
#[cfg(feature = "syntax-highlighting")]
pub(super) fn bash_token_style(kind: &str) -> Option<Style> {
match kind {
@@ -45,15 +48,18 @@ pub(super) fn bash_token_style(kind: &str) -> Option<Style> {
// Operators (&&, ||, |, $, -, >, <, etc.) - cyan
"operator" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)))),
- // Variables ($VAR, ${VAR}) - yellow
- "variable" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)))),
+ // Variables ($VAR, ${VAR}) - tree-sitter-bash 0.25 uses "property" not "variable"
+ "property" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)))),
// Numbers - yellow
- "digit" | "number" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)))),
+ "number" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)))),
// Constants/flags (--flag, -f) - cyan
"constant" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)))),
+ // Embedded content - default (no special styling)
+ "embedded" => None,
+
// Everything else (plain arguments, etc.)
_ => None,
}
diff --git a/templates/bash.sh b/templates/bash.sh
index 104b5dd78..4c0ad9ca7 100644
--- a/templates/bash.sh
+++ b/templates/bash.sh
@@ -37,9 +37,10 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];
_WORKTRUNK_CMD="./target/debug/{{ cmd_prefix }}"
fi
- # Force colors if wrapper's stdout is a TTY (respects NO_COLOR and explicit CLICOLOR_FORCE)
+ # Force colors if stderr is a TTY (directive mode outputs to stderr)
+ # Respects NO_COLOR and explicit CLICOLOR_FORCE
if [[ -z "${NO_COLOR:-}" && -z "${CLICOLOR_FORCE:-}" ]]; then
- if [[ -t 1 ]]; then export CLICOLOR_FORCE=1; fi
+ if [[ -t 2 ]]; then export CLICOLOR_FORCE=1; fi
fi
# Always use --internal mode for directive support
diff --git a/templates/elvish.elv b/templates/elvish.elv
index a1dd7dca8..5e9ce2cb9 100644
--- a/templates/elvish.elv
+++ b/templates/elvish.elv
@@ -104,9 +104,10 @@ if (or (has-external {{ cmd_prefix }}) (has-env WORKTRUNK_BIN)) {
set _WORKTRUNK_CMD = ./target/debug/{{ cmd_prefix }}
}
- # Force colors if wrapper's stdout is a TTY (respects NO_COLOR and explicit CLICOLOR_FORCE)
+ # Force colors if stderr is a TTY (directive mode outputs to stderr)
+ # Respects NO_COLOR and explicit CLICOLOR_FORCE
if (and (not (has-env NO_COLOR)) (not (has-env CLICOLOR_FORCE))) {
- if (isatty stdout) {
+ if (isatty stderr) {
set E:CLICOLOR_FORCE = 1
}
}
diff --git a/templates/fish.fish b/templates/fish.fish
index d03fb9fee..13e99e4fd 100644
--- a/templates/fish.fish
+++ b/templates/fish.fish
@@ -110,9 +110,10 @@ if type -q {{ cmd_prefix }}; or set -q WORKTRUNK_BIN
set _WORKTRUNK_CMD ./target/debug/{{ cmd_prefix }}
end
- # Force colors if wrapper's stdout is a TTY (respects NO_COLOR and explicit CLICOLOR_FORCE)
+ # Force colors if stderr is a TTY (directive mode outputs to stderr)
+ # Respects NO_COLOR and explicit CLICOLOR_FORCE
if not set -q NO_COLOR; and not set -q CLICOLOR_FORCE
- if isatty stdout
+ if isatty stderr
set -x CLICOLOR_FORCE 1
end
end
diff --git a/templates/nushell.nu b/templates/nushell.nu
index b3bf531a8..e248a4552 100644
--- a/templates/nushell.nu
+++ b/templates/nushell.nu
@@ -78,7 +78,11 @@ if (which {{ cmd_prefix }} | is-not-empty) or ($env.WORKTRUNK_BIN? | is-not-empt
$_WORKTRUNK_CMD
}
- # Force colors if wrapper's stdout is a TTY (respects NO_COLOR and explicit CLICOLOR_FORCE)
+ # Force colors if terminal is available (directive mode outputs to stderr)
+ # Respects NO_COLOR and explicit CLICOLOR_FORCE
+ # Note: Nushell's term size doesn't distinguish stdout vs stderr, but in directive
+ # mode output goes to stderr, so this check is conservative (may enable colors when
+ # stdout is TTY but stderr is redirected - users can set NO_COLOR to disable)
if ($env.NO_COLOR? | is-empty) and ($env.CLICOLOR_FORCE? | is-empty) {
if (do -i { term size } | is-not-empty) {
load-env { CLICOLOR_FORCE: "1" }
diff --git a/templates/powershell.ps1 b/templates/powershell.ps1
index 58e77bc19..98b1a5e56 100644
--- a/templates/powershell.ps1
+++ b/templates/powershell.ps1
@@ -127,9 +127,10 @@ if ((Get-Command {{ cmd_prefix }} -ErrorAction SilentlyContinue) -or $env:WORKTR
$cmd = $script:_WORKTRUNK_CMD
}
- # Force colors if wrapper's stdout is a TTY (respects NO_COLOR and explicit CLICOLOR_FORCE)
+ # Force colors if stderr is a TTY (directive mode outputs to stderr)
+ # Respects NO_COLOR and explicit CLICOLOR_FORCE
if (-not $env:NO_COLOR -and -not $env:CLICOLOR_FORCE) {
- if ([Console]::IsOutputRedirected -eq $false) {
+ if ([Console]::IsErrorRedirected -eq $false) {
$env:CLICOLOR_FORCE = "1"
}
}
diff --git a/templates/xonsh.xsh b/templates/xonsh.xsh
index f8f61d3c3..682693e0d 100644
--- a/templates/xonsh.xsh
+++ b/templates/xonsh.xsh
@@ -102,9 +102,10 @@ if shutil.which("{{ cmd_prefix }}") is not None or os.environ.get('WORKTRUNK_BIN
else:
cmd = _WORKTRUNK_CMD
- # Force colors if wrapper's stdout is a TTY (respects NO_COLOR and explicit CLICOLOR_FORCE)
+ # Force colors if stderr is a TTY (directive mode outputs to stderr)
+ # Respects NO_COLOR and explicit CLICOLOR_FORCE
if 'NO_COLOR' not in os.environ and 'CLICOLOR_FORCE' not in os.environ:
- if sys.stdout.isatty():
+ if sys.stderr.isatty():
os.environ['CLICOLOR_FORCE'] = '1'
# Always use --internal mode for directive support
diff --git a/templates/zsh.zsh b/templates/zsh.zsh
index 46855bae5..83da2abf7 100644
--- a/templates/zsh.zsh
+++ b/templates/zsh.zsh
@@ -37,9 +37,10 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];
_WORKTRUNK_CMD="./target/debug/{{ cmd_prefix }}"
fi
- # Force colors if wrapper's stdout is a TTY (respects NO_COLOR and explicit CLICOLOR_FORCE)
+ # Force colors if stderr is a TTY (directive mode outputs to stderr)
+ # Respects NO_COLOR and explicit CLICOLOR_FORCE
if [[ -z "${NO_COLOR:-}" && -z "${CLICOLOR_FORCE:-}" ]]; then
- if [[ -t 1 ]]; then export CLICOLOR_FORCE=1; fi
+ if [[ -t 2 ]]; then export CLICOLOR_FORCE=1; fi
fi
# Always use --internal mode for directive support
diff --git a/tests/common/list_snapshots.rs b/tests/common/list_snapshots.rs
index a4630573c..23bbf38e6 100644
--- a/tests/common/list_snapshots.rs
+++ b/tests/common/list_snapshots.rs
@@ -54,6 +54,54 @@ pub fn command_with_width(repo: &TestRepo, width: usize) -> Command {
cmd
}
+pub fn command_progressive(repo: &TestRepo) -> Command {
+ let mut cmd = command(repo, repo.root_path());
+ cmd.arg("--progressive");
+ cmd
+}
+
+pub fn command_no_progressive(repo: &TestRepo) -> Command {
+ let mut cmd = command(repo, repo.root_path());
+ cmd.arg("--no-progressive");
+ cmd
+}
+
+pub fn command_progressive_json(repo: &TestRepo) -> Command {
+ let mut cmd = command(repo, repo.root_path());
+ cmd.args(["--progressive", "--format=json"]);
+ cmd
+}
+
+pub fn command_no_progressive_json(repo: &TestRepo) -> Command {
+ let mut cmd = command(repo, repo.root_path());
+ cmd.args(["--no-progressive", "--format=json"]);
+ cmd
+}
+
+pub fn command_progressive_branches(repo: &TestRepo) -> Command {
+ let mut cmd = command(repo, repo.root_path());
+ cmd.args(["--progressive", "--branches"]);
+ cmd
+}
+
+pub fn command_task_dag(repo: &TestRepo) -> Command {
+ // Task DAG is now the default for progressive mode
+ command_progressive(repo)
+}
+
+pub fn command_task_dag_full(repo: &TestRepo) -> Command {
+ let mut cmd = command_task_dag(repo);
+ cmd.arg("--full");
+ cmd
+}
+
+pub fn command_task_dag_from_dir(repo: &TestRepo, cwd: &Path) -> Command {
+ let mut cmd = wt_command();
+ repo.clean_cli_env(&mut cmd);
+ cmd.args(["list", "--progressive"]).current_dir(cwd);
+ cmd
+}
+
fn normalize_worktree_paths(settings: &mut Settings, repo: &TestRepo) {
settings.add_filter(repo.root_path().to_str().unwrap(), "[REPO]");
for (name, path) in &repo.worktrees {
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 2cb77279b..c207d0726 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -591,12 +591,19 @@ exit 1
///
/// Must call `setup_mock_gh()` first. Prepends the mock bin directory to PATH
/// so gh/glab commands are intercepted.
+ ///
+ /// Note: This sets PATH explicitly (which will be captured in snapshots). We use
+ /// a clean, minimal PATH with only system paths to avoid leaking user-specific
+ /// paths like ~/.cargo/bin into version control. This hardcoded PATH works on
+ /// macOS and Linux but may need adjustment for other environments.
pub fn configure_mock_commands(&self, cmd: &mut Command) {
if let Some(mock_bin) = &self.mock_bin_path {
- // Prepend mock bin to PATH
- let current_path = std::env::var("PATH").unwrap_or_default();
- let new_path = format!("{}:{}", mock_bin.display(), current_path);
- cmd.env("PATH", new_path);
+ // Use clean, minimal PATH to avoid capturing user-specific paths in snapshots
+ let clean_path = format!(
+ "{}:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
+ mock_bin.display()
+ );
+ cmd.env("PATH", clean_path);
}
}
}
diff --git a/tests/helpers/dev-detach/src/setup-select-test.rs b/tests/helpers/dev-detach/src/setup-select-test.rs
new file mode 100644
index 000000000..4a0298e56
--- /dev/null
+++ b/tests/helpers/dev-detach/src/setup-select-test.rs
@@ -0,0 +1,188 @@
+//! Helper binary to setup a test environment for debugging `wt beta select`
+//!
+//! This creates a temporary git repository with a known state:
+//! - main branch with 3 commits
+//! - feature branch with 15 commits ahead of main (100 lines per file)
+//! - Multiple worktrees with varying amounts of work
+//! - Some uncommitted changes in the feature worktree
+//!
+//! Run with: cargo run --bin setup-select-test
+//! Then cd into the printed path and run: wt beta select
+
+use std::fs;
+use std::io::{self, Write};
+use std::path::PathBuf;
+use std::process::Command;
+
+fn main() {
+ println!("Setting up test environment for `wt beta select`...\n");
+
+ // Create temp directory in /tmp
+ let temp_base = std::env::temp_dir().join("wt-select-test");
+ if temp_base.exists() {
+ fs::remove_dir_all(&temp_base).expect("Failed to clean old test directory");
+ }
+ fs::create_dir(&temp_base).expect("Failed to create temp directory");
+
+ let root = temp_base.join("test-repo");
+ fs::create_dir(&root).expect("Failed to create repo directory");
+ let root = root.canonicalize().expect("Failed to canonicalize path");
+
+ // Initialize git repo
+ git(&root, &["init", "-b", "main"]);
+ git(&root, &["config", "user.name", "Test User"]);
+ git(&root, &["config", "user.email", "[email protected]"]);
+
+ // Create commits on main
+ for i in 1..=3 {
+ fs::write(
+ root.join(format!("file{}.txt", i)),
+ format!("content {}", i),
+ )
+ .expect("Failed to write file");
+ git(&root, &["add", "."]);
+ git(&root, &["commit", "-m", &format!("Main commit {}", i)]);
+ }
+
+ // Create feature branch with commits ahead - MORE COMMITS AND BIGGER FILES
+ git(&root, &["switch", "-c", "feature"]);
+ for i in 1..=15 {
+ // Create larger files with more content
+ let mut content = String::new();
+ for line in 1..=100 {
+ content.push_str(&format!("Line {} of feature file {}\n", line, i));
+ }
+ fs::write(root.join(format!("feature{}.txt", i)), content).expect("Failed to write file");
+ git(&root, &["add", "."]);
+ git(
+ &root,
+ &[
+ "commit",
+ "-m",
+ &format!("Feature commit {}: Add feature{}.txt with 100 lines", i, i),
+ ],
+ );
+ }
+
+ // Switch back to main in primary worktree BEFORE creating worktrees
+ git(&root, &["switch", "main"]);
+
+ // Create multiple worktrees to simulate realistic scenario
+
+ // Feature worktree (15 commits ahead)
+ let feature_wt = temp_base.join("feature-wt");
+ git(
+ &root,
+ &["worktree", "add", feature_wt.to_str().unwrap(), "feature"],
+ );
+
+ // Create more branches with different amounts of work
+ for (i, num_commits) in [(2, 5), (3, 3), (4, 8), (5, 2)].iter() {
+ let branch_name = format!("branch{}", i);
+ git(&root, &["branch", &branch_name, "main"]);
+
+ let wt_path = temp_base.join(format!("branch{}-wt", i));
+ git(
+ &root,
+ &["worktree", "add", wt_path.to_str().unwrap(), &branch_name],
+ );
+
+ // Add commits to this branch via its worktree
+ for j in 1..=*num_commits {
+ let file_content = format!("Content for {} commit {}\n", branch_name, j);
+ fs::write(wt_path.join(format!("file{}.txt", j)), file_content)
+ .expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ git_env(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&wt_path)
+ .output()
+ .expect("Failed to git add");
+
+ let mut cmd = Command::new("git");
+ git_env(&mut cmd);
+ cmd.args(["commit", "-m", &format!("{} commit {}", branch_name, j)])
+ .current_dir(&wt_path)
+ .output()
+ .expect("Failed to git commit");
+ }
+ }
+
+ // Add uncommitted changes to feature worktree
+ let feature_wt = feature_wt.canonicalize().expect("Failed to canonicalize");
+ fs::write(feature_wt.join("uncommitted.txt"), "uncommitted changes")
+ .expect("Failed to write uncommitted file");
+
+ // Create some branches without worktrees
+ git(&root, &["branch", "no-worktree-1", "main"]);
+ git(&root, &["branch", "no-worktree-2", "main"]);
+
+ println!("✅ Test environment ready!\n");
+ println!("Repository path: {}", root.display());
+ println!();
+ println!("Worktrees created:");
+ println!(" - main (primary): {}", root.display());
+ println!(" - feature: 15 commits ahead, 1 uncommitted file");
+ println!(" - branch2: 5 commits ahead");
+ println!(" - branch3: 3 commits ahead");
+ println!(" - branch4: 8 commits ahead");
+ println!(" - branch5: 2 commits ahead");
+ println!();
+ println!("Branches without worktrees:");
+ println!(" - no-worktree-1, no-worktree-2");
+ println!();
+ println!("Total: 6 worktrees + 2 branches = 8 items in list");
+ println!();
+ println!("To test:");
+ println!();
+ println!("Method 1 - Using cd:");
+ println!(" cd {}", root.display());
+ println!(" cargo run --quiet -- beta select");
+ println!();
+ println!("Method 2 - Using -C flag:");
+ println!(" cargo run --quiet -- -C {} beta select", root.display());
+ println!();
+ println!("Expected behavior:");
+ println!(" - Navigate with arrow keys through 8 items");
+ println!(" - Press 3 on 'feature': Shows LARGE diff (15 files, 1500 lines)");
+ println!(" - Press 3 on other branches: Shows smaller diffs");
+ println!();
+ println!("Press Enter to clean up and exit (or Ctrl+C to leave the test repo)...");
+
+ io::stdout().flush().unwrap();
+ let mut input = String::new();
+ io::stdin().read_line(&mut input).unwrap();
+
+ println!("Cleaning up...");
+ if let Err(e) = fs::remove_dir_all(&temp_base) {
+ eprintln!("Warning: Failed to clean up test directory: {}", e);
+ eprintln!("You may need to manually remove: {}", temp_base.display());
+ } else {
+ println!("Test environment cleaned up.");
+ }
+}
+
+fn git_env(cmd: &mut Command) {
+ // Set git config for test environment
+ cmd.env("GIT_CONFIG_GLOBAL", "/dev/null");
+ cmd.env("GIT_CONFIG_SYSTEM", "/dev/null");
+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T00:00:00Z");
+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T00:00:00Z");
+}
+
+fn git(repo: &PathBuf, args: &[&str]) {
+ let mut cmd = Command::new("git");
+ git_env(&mut cmd);
+ let output = cmd
+ .args(args)
+ .current_dir(repo)
+ .output()
+ .expect("Failed to execute git command");
+
+ if !output.status.success() {
+ eprintln!("Git command failed: git {}", args.join(" "));
+ eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
+ eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
+ std::process::exit(1);
+ }
+}
diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rs
index 839304e39..9ef1eda19 100644
--- a/tests/integration_tests/bare_repository.rs
+++ b/tests/integration_tests/bare_repository.rs
@@ -189,12 +189,12 @@ fn test_bare_repo_list_shows_no_bare_entry() {
cmd.arg("list").current_dir(&main_worktree);
let output = cmd.output().expect("Failed to run wt list");
- let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
- // Should only show the main worktree, not the bare repo
- assert!(stdout.contains("main"));
- assert!(!stdout.contains(".git"));
- assert!(!stdout.contains("bare"));
+ // Should only show the main worktree, not the bare repo (table output is on stderr)
+ assert!(stderr.contains("main"));
+ assert!(!stderr.contains(".git"));
+ assert!(!stderr.contains("bare"));
}
#[test]
@@ -362,11 +362,11 @@ fn test_bare_repo_identifies_primary_correctly() {
cmd.arg("list").current_dir(&main_worktree);
let output = cmd.output().expect("Failed to run wt list");
- let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
- // First non-bare worktree (main) should be primary
+ // First non-bare worktree (main) should be primary (table output is on stderr)
// The exact formatting may vary, but main should be listed
- assert!(stdout.contains("main"));
+ assert!(stderr.contains("main"));
}
#[test]
@@ -443,13 +443,13 @@ worktree-path = "{{ branch }}"
.output()
.expect("Failed to list normal worktrees");
- // Both should show 1 worktree (main/main)
- let bare_stdout = String::from_utf8_lossy(&bare_output.stdout);
- let normal_stdout = String::from_utf8_lossy(&normal_output.stdout);
+ // Both should show 1 worktree (main/main) - table output is on stderr
+ let bare_stderr = String::from_utf8_lossy(&bare_output.stderr);
+ let normal_stderr = String::from_utf8_lossy(&normal_output.stderr);
- assert!(bare_stdout.contains("main"));
- assert!(normal_stdout.contains("main"));
- assert_eq!(bare_stdout.lines().count(), normal_stdout.lines().count());
+ assert!(bare_stderr.contains("main"));
+ assert!(normal_stderr.contains("main"));
+ assert_eq!(bare_stderr.lines().count(), normal_stderr.lines().count());
}
#[test]
@@ -475,11 +475,11 @@ fn test_bare_repo_commands_from_bare_directory() {
);
}
- let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
- // Should list the worktree even when run from bare repo
- assert!(stdout.contains("main"), "Should show main worktree");
- assert!(!stdout.contains("bare"), "Should not show bare repo itself");
+ // Should list the worktree even when run from bare repo (table output is on stderr)
+ assert!(stderr.contains("main"), "Should show main worktree");
+ assert!(!stderr.contains("bare"), "Should not show bare repo itself");
}
#[test]
diff --git a/tests/integration_tests/column_alignment_verification.rs b/tests/integration_tests/column_alignment_verification.rs
index cc3bf800b..2c14ddfea 100644
--- a/tests/integration_tests/column_alignment_verification.rs
+++ b/tests/integration_tests/column_alignment_verification.rs
@@ -337,7 +337,7 @@ fn test_alignment_verification_with_varying_content() {
cmd.arg("list").current_dir(repo.root_path());
let output = cmd.output().expect("Failed to run wt list");
- let stdout = String::from_utf8_lossy(&output.stdout);
+ let stdout = String::from_utf8_lossy(&output.stderr);
println!("=== RAW OUTPUT ===");
println!("{}", stdout);
@@ -366,7 +366,7 @@ fn test_alignment_with_unicode_content() {
cmd.arg("list").current_dir(repo.root_path());
let output = cmd.output().expect("Failed to run wt list");
- let stdout = String::from_utf8_lossy(&output.stdout);
+ let stdout = String::from_utf8_lossy(&output.stderr);
println!("=== RAW OUTPUT WITH UNICODE ===");
println!("{}", stdout);
@@ -405,7 +405,7 @@ fn test_alignment_with_sparse_columns() {
cmd.arg("list").current_dir(repo.root_path());
let output = cmd.output().expect("Failed to run wt list");
- let stdout = String::from_utf8_lossy(&output.stdout);
+ let stdout = String::from_utf8_lossy(&output.stderr);
println!("=== RAW OUTPUT WITH SPARSE COLUMNS ===");
println!("{}", stdout);
@@ -456,7 +456,7 @@ fn test_alignment_real_world_scenario() {
cmd.arg("list").current_dir(repo.root_path());
let output = cmd.output().expect("Failed to run wt list");
- let stdout = String::from_utf8_lossy(&output.stdout);
+ let stdout = String::from_utf8_lossy(&output.stderr);
println!("=== RAW OUTPUT: Real World Scenario ===");
println!("{}", stdout);
@@ -491,7 +491,7 @@ fn test_alignment_at_different_terminal_widths() {
.env("COLUMNS", width.to_string());
let output = cmd.output().expect("Failed to run wt list");
- let stdout = String::from_utf8_lossy(&output.stdout);
+ let stdout = String::from_utf8_lossy(&output.stderr);
println!("{}", stdout);
diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rs
index 046de03a8..bb8892a56 100644
--- a/tests/integration_tests/directives.rs
+++ b/tests/integration_tests/directives.rs
@@ -84,14 +84,12 @@ fn test_remove_internal_directive() {
.current_dir(repo.root_path());
assert_cmd_snapshot!(cmd, @r"
- success: false
- exit_code: 1
+ success: true
+ exit_code: 0
----- stdout -----
-
+ __WORKTRUNK_CD__[PATH]
----- stderr -----
- ❌ Cannot remove main worktree
-
- 💡 Use 'wt remove' from a secondary worktree, or 'wt switch' to change branches
+ 🔄 Removing main & branch in background
");
});
}
@@ -111,12 +109,10 @@ fn test_remove_without_internal() {
cmd.arg("remove").current_dir(repo.root_path());
assert_cmd_snapshot!(cmd, @r"
- success: false
- exit_code: 1
+ success: true
+ exit_code: 0
----- stdout -----
- ❌ Cannot remove main worktree
-
- 💡 Use 'wt remove' from a secondary worktree, or 'wt switch' to change branches
+ 🔄 Removing main & branch in background
----- stderr -----
");
diff --git a/tests/integration_tests/internal_flag.rs b/tests/integration_tests/internal_flag.rs
index 5f56c15d6..58a4375e5 100644
--- a/tests/integration_tests/internal_flag.rs
+++ b/tests/integration_tests/internal_flag.rs
@@ -13,8 +13,13 @@ use tempfile::TempDir;
/// Test that `list` command works with --internal flag
///
-/// The list command doesn't emit directives, so output remains newline-terminated.
-/// The --internal flag can be safely passed without changing behavior.
+/// The list command outputs tables through stderr in directive mode for progressive
+/// streaming. This bypasses the shell wrapper's NUL-delimited parsing on stdout,
+/// allowing real-time display without buffering.
+///
+/// Expected behavior:
+/// - stdout: empty (no directives emitted by list command)
+/// - stderr: complete table output with ANSI formatting
#[test]
fn test_list_with_internal_flag() {
let repo = TestRepo::new();
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 1371e97a8..b4874b45b 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -36,6 +36,46 @@ fn snapshot_list_with_branches(test_name: &str, repo: &TestRepo) {
);
}
+fn snapshot_list_progressive(test_name: &str, repo: &TestRepo) {
+ run_snapshot(
+ list_snapshots::standard_settings(repo),
+ test_name,
+ list_snapshots::command_progressive(repo),
+ );
+}
+
+fn snapshot_list_no_progressive(test_name: &str, repo: &TestRepo) {
+ run_snapshot(
+ list_snapshots::standard_settings(repo),
+ test_name,
+ list_snapshots::command_no_progressive(repo),
+ );
+}
+
+fn snapshot_list_progressive_branches(test_name: &str, repo: &TestRepo) {
+ run_snapshot(
+ list_snapshots::standard_settings(repo),
+ test_name,
+ list_snapshots::command_progressive_branches(repo),
+ );
+}
+
+fn snapshot_list_task_dag(test_name: &str, repo: &TestRepo) {
+ run_snapshot(
+ list_snapshots::standard_settings(repo),
+ test_name,
+ list_snapshots::command_task_dag(repo),
+ );
+}
+
+fn snapshot_list_task_dag_full(test_name: &str, repo: &TestRepo) {
+ run_snapshot(
+ list_snapshots::standard_settings(repo),
+ test_name,
+ list_snapshots::command_task_dag_full(repo),
+ );
+}
+
fn run_snapshot(settings: Settings, test_name: &str, mut cmd: Command) {
settings.bind(|| {
assert_cmd_snapshot!(test_name, cmd);
@@ -730,21 +770,1020 @@ fn test_readme_example_simple_list() {
}
#[test]
-fn test_list_with_c_flag() {
+fn test_list_progressive_flag() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.add_worktree("feature-a", "feature-a");
+ repo.add_worktree("feature-b", "feature-b");
+
+ // Force progressive mode even in non-TTY test environment
+ // Output should be identical to buffered mode (only process differs)
+ snapshot_list_progressive("progressive_flag", &repo);
+}
+
+#[test]
+fn test_list_no_progressive_flag() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.add_worktree("feature", "feature");
+
+ // Explicitly force buffered mode
+ snapshot_list_no_progressive("no_progressive_flag", &repo);
+}
+
+#[test]
+fn test_list_progressive_with_branches() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create worktrees
+ repo.add_worktree("feature-a", "feature-a");
+
+ // Create branches without worktrees
+ create_branch(&repo, "orphan-1");
+ create_branch(&repo, "orphan-2");
+
+ // Critical: test that --branches works with --progressive
+ // This ensures progressive mode supports the --branches flag
+ snapshot_list_progressive_branches("progressive_with_branches", &repo);
+}
+
+// ============================================================================
+// Task DAG Mode Tests
+// ============================================================================
+
+#[test]
+fn test_list_task_dag_single_worktree() {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ snapshot_list_task_dag("task_dag_single_worktree", &repo);
+}
+
+#[test]
+fn test_list_task_dag_multiple_worktrees() {
let mut repo = TestRepo::new();
repo.commit("Initial commit");
- // Create some worktrees
repo.add_worktree("feature-a", "feature-a");
repo.add_worktree("feature-b", "feature-b");
+ repo.add_worktree("feature-c", "feature-c");
- // Run wt -C <repo_path> list from a completely different directory
- let settings = list_snapshots::standard_settings(&repo);
- settings.bind(|| {
- let mut cmd = wt_command();
- cmd.args(["-C", repo.root_path().to_str().unwrap(), "list"]);
- // Run from /tmp to ensure -C is actually being used
- cmd.current_dir("/tmp");
- assert_cmd_snapshot!("list_with_c_flag", cmd);
+ snapshot_list_task_dag("task_dag_multiple_worktrees", &repo);
+}
+
+#[test]
+fn test_list_task_dag_full_with_diffs() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create worktree with changes
+ let feature_a = repo.add_worktree("feature-a", "feature-a");
+ std::fs::write(feature_a.join("new.txt"), "content").expect("Failed to write file");
+
+ // Create another worktree with commits
+ let feature_b = repo.add_worktree("feature-b", "feature-b");
+ std::fs::write(feature_b.join("file.txt"), "test").expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&feature_b)
+ .output()
+ .expect("Failed to add");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Test commit"])
+ .current_dir(&feature_b)
+ .output()
+ .expect("Failed to commit");
+
+ snapshot_list_task_dag_full("task_dag_full_with_diffs", &repo);
+}
+
+#[test]
+fn test_list_task_dag_with_upstream() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit on main");
+ repo.setup_remote("main");
+
+ // Branch in sync
+ let in_sync = repo.add_worktree("in-sync", "in-sync");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["push", "-u", "origin", "in-sync"])
+ .current_dir(&in_sync)
+ .output()
+ .expect("Failed to push");
+
+ // Branch ahead
+ let ahead = repo.add_worktree("ahead", "ahead");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["push", "-u", "origin", "ahead"])
+ .current_dir(&ahead)
+ .output()
+ .expect("Failed to push");
+ std::fs::write(ahead.join("ahead.txt"), "ahead").expect("Failed to write");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&ahead)
+ .output()
+ .expect("Failed to add");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Ahead commit"])
+ .current_dir(&ahead)
+ .output()
+ .expect("Failed to commit");
+
+ snapshot_list_task_dag_full("task_dag_with_upstream", &repo);
+}
+
+#[test]
+fn test_list_task_dag_many_worktrees() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create 10 worktrees to test parallel processing
+ for i in 1..=10 {
+ repo.add_worktree(&format!("feature-{}", i), &format!("feature-{}", i));
+ }
+
+ snapshot_list_task_dag("task_dag_many_worktrees", &repo);
+}
+
+#[test]
+fn test_list_task_dag_with_locked_worktree() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ repo.add_worktree("normal", "normal");
+ repo.add_worktree("locked", "locked");
+ repo.lock_worktree("locked", Some("Testing task DAG with locked worktree"));
+
+ snapshot_list_task_dag("task_dag_with_locked", &repo);
+}
+
+#[test]
+fn test_list_task_dag_detached_head() {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.detach_head();
+
+ snapshot_list_task_dag("task_dag_detached_head", &repo);
+}
+
+#[test]
+fn test_list_task_dag_ordering_stability() {
+ // Test that task_dag mode produces same ordering as buffered mode
+ // Regression test for progressive rendering order instability
+ let mut repo = TestRepo::new();
+
+ // Create main with earliest timestamp (00:00)
+ repo.commit("Initial commit on main");
+
+ // Create worktrees with specific timestamps (non-chronological creation order)
+
+ // 1. Create feature-current (01:00) - we'll run test from here
+ let current_path = repo.add_worktree("feature-current", "feature-current");
+ {
+ let file_path = current_path.join("current.txt");
+ std::fs::write(&file_path, "current content").expect("Failed to write file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T01:00:00Z");
+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T01:00:00Z");
+ cmd.args(["add", "."])
+ .current_dir(&current_path)
+ .output()
+ .expect("Failed to git add");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T01:00:00Z");
+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T01:00:00Z");
+ cmd.args(["commit", "-m", "Commit at 01:00"])
+ .current_dir(&current_path)
+ .output()
+ .expect("Failed to git commit");
+ }
+
+ // 2. Create feature-newest (03:00) - most recent, should be 3rd
+ let newest_path = repo.add_worktree("feature-newest", "feature-newest");
+ {
+ let file_path = newest_path.join("newest.txt");
+ std::fs::write(&file_path, "newest content").expect("Failed to write file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T03:00:00Z");
+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T03:00:00Z");
+ cmd.args(["add", "."])
+ .current_dir(&newest_path)
+ .output()
+ .expect("Failed to git add");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T03:00:00Z");
+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T03:00:00Z");
+ cmd.args(["commit", "-m", "Commit at 03:00"])
+ .current_dir(&newest_path)
+ .output()
+ .expect("Failed to git commit");
+ }
+
+ // 3. Create feature-middle (02:00) - should be 4th
+ let middle_path = repo.add_worktree("feature-middle", "feature-middle");
+ {
+ let file_path = middle_path.join("middle.txt");
+ std::fs::write(&file_path, "middle content").expect("Failed to write file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T02:00:00Z");
+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T02:00:00Z");
+ cmd.args(["add", "."])
+ .current_dir(&middle_path)
+ .output()
+ .expect("Failed to git add");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T02:00:00Z");
+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T02:00:00Z");
+ cmd.args(["commit", "-m", "Commit at 02:00"])
+ .current_dir(&middle_path)
+ .output()
+ .expect("Failed to git commit");
+ }
+
+ // 4. Create feature-oldest (00:30) - should be 5th
+ let oldest_path = repo.add_worktree("feature-oldest", "feature-oldest");
+ {
+ let file_path = oldest_path.join("oldest.txt");
+ std::fs::write(&file_path, "oldest content").expect("Failed to write file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T00:30:00Z");
+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T00:30:00Z");
+ cmd.args(["add", "."])
+ .current_dir(&oldest_path)
+ .output()
+ .expect("Failed to git add");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T00:30:00Z");
+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T00:30:00Z");
+ cmd.args(["commit", "-m", "Commit at 00:30"])
+ .current_dir(&oldest_path)
+ .output()
+ .expect("Failed to git commit");
+ }
+
+ // Run from feature-current worktree
+ // Expected order: main, feature-current, feature-newest, feature-middle, feature-oldest
+ run_snapshot(
+ list_snapshots::standard_settings(&repo),
+ "task_dag_ordering_stability",
+ list_snapshots::command_task_dag_from_dir(&repo, &current_path),
+ );
+}
+
+#[test]
+fn test_list_progressive_vs_buffered_identical_data() {
+ // Critical test: Verify that progressive and buffered modes collect identical data
+ // despite using different rendering strategies (real-time UI vs collect-then-print).
+ // This ensures consolidation on task DAG data collection works correctly.
+ //
+ // Note: We compare JSON output, not table output, because:
+ // - Progressive mode renders headers before knowing final column widths (uses estimates)
+ // - Buffered mode renders headers after data collection (uses actual widths)
+ // - The DATA must be identical, but table formatting may differ slightly
+
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create varied worktrees to test multiple data points
+ repo.add_worktree("feature-a", "feature-a");
+ repo.add_worktree("feature-b", "feature-b");
+
+ // Modify a worktree to have uncommitted changes
+ let feature_a_path = repo.worktree_path("feature-a");
+ std::fs::write(feature_a_path.join("changes.txt"), "test").unwrap();
+
+ // Run both modes with JSON output to compare data (not formatting)
+ let progressive_output = list_snapshots::command_progressive_json(&repo)
+ .output()
+ .expect("Progressive JSON command failed");
+
+ let buffered_output = list_snapshots::command_no_progressive_json(&repo)
+ .output()
+ .expect("Buffered JSON command failed");
+
+ // Both should succeed
+ assert!(
+ progressive_output.status.success(),
+ "Progressive mode failed: {}",
+ String::from_utf8_lossy(&progressive_output.stderr)
+ );
+ assert!(
+ buffered_output.status.success(),
+ "Buffered mode failed: {}",
+ String::from_utf8_lossy(&buffered_output.stderr)
+ );
+
+ // Parse JSON outputs
+ let progressive_json: serde_json::Value = serde_json::from_slice(&progressive_output.stdout)
+ .expect("Invalid JSON from progressive mode");
+ let buffered_json: serde_json::Value =
+ serde_json::from_slice(&buffered_output.stdout).expect("Invalid JSON from buffered mode");
+
+ // The JSON data should be identical (ignoring display fields which may have formatting differences)
+ // Compare the structured data to ensure both modes collect the same information
+ assert_eq!(
+ progressive_json,
+ buffered_json,
+ "Progressive and buffered modes produced different data!\n\nProgressive:\n{}\n\nBuffered:\n{}",
+ serde_json::to_string_pretty(&progressive_json).unwrap(),
+ serde_json::to_string_pretty(&buffered_json).unwrap()
+ );
+}
+
+/// Test that errors from worktree collection include helpful context
+/// This verifies that when a worktree fails to collect data, the error message
+/// includes the worktree branch name and path for easier debugging.
+///
+/// TODO: This test is currently ignored because the parallel collection implementation
+/// silently handles errors instead of propagating them. We need to add proper error
+/// propagation through the CellUpdate channel. See collect_progressive_impl.rs TODOs.
+#[test]
+#[ignore = "Error handling needs improvement in parallel collection"]
+fn test_list_error_shows_worktree_context() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create a worktree
+ let feature_wt = repo.add_worktree("feature", "feature");
+
+ // Delete the worktree directory manually to trigger an error
+ // (but keep the git metadata, so git worktree list still shows it)
+ std::fs::remove_dir_all(&feature_wt).expect("Failed to remove worktree directory");
+
+ // Run list command and expect an error
+ let mut cmd = wt_command();
+ repo.clean_cli_env(&mut cmd);
+ repo.configure_mock_commands(&mut cmd);
+ cmd.arg("list").current_dir(repo.root_path());
+
+ let output = cmd.output().expect("Failed to run command");
+
+ // Should fail with non-zero exit code
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ assert!(
+ !output.status.success(),
+ "Expected command to fail. stdout:\n{}\nstderr:\n{}",
+ stdout,
+ stderr
+ );
+
+ // Error message should include worktree context (could be in stdout or stderr)
+ let combined = format!("{}{}", stdout, stderr);
+
+ assert!(
+ combined.contains("feature") && combined.contains("Failed to collect data for worktree"),
+ "Error message should include worktree branch 'feature' and context, but got:\nstdout:\n{}\nstderr:\n{}",
+ stdout,
+ stderr
+ );
+}
+
+#[test]
+fn test_list_with_c_flag() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create some worktrees
+ repo.add_worktree("feature-a", "feature-a");
+ repo.add_worktree("feature-b", "feature-b");
+
+ // Run wt -C <repo_path> list from a completely different directory
+ let settings = list_snapshots::standard_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ cmd.args(["-C", repo.root_path().to_str().unwrap(), "list"]);
+ // Run from /tmp to ensure -C is actually being used
+ cmd.current_dir("/tmp");
+ assert_cmd_snapshot!("list_with_c_flag", cmd);
+ });
+}
+
+#[test]
+fn test_list_large_diffs_alignment() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Worktree with large uncommitted changes and ahead commits
+ // Use a longer branch name similar to user's "wli-sequence" to trigger column width
+ let large_wt = repo.add_worktree("feature-changes", "feature-changes");
+
+ // Create a file with many lines for large diff
+ let large_content = (1..=100)
+ .map(|i| format!("line {}", i))
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(large_wt.join("large.txt"), &large_content).expect("Failed to write file");
+
+ // Commit it
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&large_wt)
+ .output()
+ .expect("Failed to add");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Add 100 lines"])
+ .current_dir(&large_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Add large uncommitted changes (both added and deleted lines)
+ // Add a new file with many lines
+ std::fs::write(large_wt.join("uncommitted.txt"), &large_content).expect("Failed to write file");
+
+ // Modify the existing file to create deletions
+ let modified_content = (1..=50)
+ .map(|i| format!("modified line {}", i))
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(large_wt.join("large.txt"), &modified_content).expect("Failed to write file");
+
+ // Add another new file with many lines
+ let another_large = (1..=80)
+ .map(|i| format!("another line {}", i))
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(large_wt.join("another.txt"), &another_large).expect("Failed to write file");
+
+ // Set user status
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["config", "worktrunk.status.feature-changes", "🤖"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to set user status");
+
+ // Worktree with short name to show gap before Status column
+ let short_wt = repo.add_worktree("fix", "fix");
+ std::fs::write(short_wt.join("quick.txt"), "quick fix").expect("Failed to write file");
+
+ // Set user status for short branch
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["config", "worktrunk.status.fix", "💬"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to set user status");
+
+ // Worktree with diverged status and working tree changes
+ let diverged_wt = repo.add_worktree("diverged", "diverged");
+
+ // Commit some changes
+ let diverged_content = (1..=60)
+ .map(|i| format!("diverged line {}", i))
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(diverged_wt.join("test.txt"), &diverged_content).expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&diverged_wt)
+ .output()
+ .expect("Failed to add");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Diverged commit"])
+ .current_dir(&diverged_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Add uncommitted changes
+ let modified_diverged = (1..=40)
+ .map(|i| format!("modified diverged line {}", i))
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(diverged_wt.join("test.txt"), &modified_diverged).expect("Failed to write file");
+
+ // Set user status
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["config", "worktrunk.status.diverged", "💬"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to set user status");
+
+ snapshot_list("large_diffs_alignment", &repo);
+}
+
+#[test]
+fn test_list_status_column_padding_with_emoji() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create worktree matching user's exact scenario: "wli-sequence"
+ let wli_seq = repo.add_worktree("wli-sequence", "wli-sequence");
+
+ // Create large working tree changes: +164, -111
+ // Need ~164 added lines and ~111 deleted lines
+ let initial_content = (1..=200)
+ .map(|i| format!("original line {}", i))
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(wli_seq.join("main.txt"), &initial_content).expect("write failed");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&wli_seq)
+ .output()
+ .expect("add failed");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Initial content"])
+ .current_dir(&wli_seq)
+ .output()
+ .expect("commit failed");
+
+ // Modify to create desired diff: remove ~111 lines, add different content
+ let modified_content = (1..=89)
+ .map(|i| format!("original line {}", i))
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(wli_seq.join("main.txt"), &modified_content).expect("write failed");
+
+ // Add new file with ~164 lines to get +164
+ let new_content = (1..=164)
+ .map(|i| format!("new line {}", i))
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(wli_seq.join("new.txt"), &new_content).expect("write failed");
+
+ // Set user status emoji 🤖
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["config", "worktrunk.status.wli-sequence", "🤖"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("config failed");
+
+ // Create "pr-link" worktree with different status (fewer symbols, same emoji type)
+ let pr_link = repo.add_worktree("pr-link", "pr-link");
+
+ // Commit to make it ahead
+ std::fs::write(pr_link.join("pr.txt"), "pr content").expect("write failed");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&pr_link)
+ .output()
+ .expect("add failed");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "PR commit"])
+ .current_dir(&pr_link)
+ .output()
+ .expect("commit failed");
+
+ // Set same emoji type
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["config", "worktrunk.status.pr-link", "🤖"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("config failed");
+
+ // Create "main-symbol" with different emoji
+ let main_sym = repo.add_worktree("main-symbol", "main-symbol");
+ std::fs::write(main_sym.join("sym.txt"), "symbol").expect("write failed");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&main_sym)
+ .output()
+ .expect("add failed");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Symbol commit"])
+ .current_dir(&main_sym)
+ .output()
+ .expect("commit failed");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["config", "worktrunk.status.main-symbol", "💬"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("config failed");
+
+ snapshot_list("status_column_padding_emoji", &repo);
+}
+
+#[test]
+fn test_list_maximum_working_tree_symbols() {
+ // Test that all 5 working tree symbols can appear simultaneously:
+ // ? (untracked), ! (modified), + (staged), » (renamed), ✘ (deleted)
+ // This verifies the maximum width of the working_tree position (5 chars)
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ let feature = repo.add_worktree("feature", "feature");
+
+ // Create initial files to manipulate
+ std::fs::write(feature.join("file-a.txt"), "original a").unwrap();
+ std::fs::write(feature.join("file-b.txt"), "original b").unwrap();
+ std::fs::write(feature.join("file-c.txt"), "original c").unwrap();
+ std::fs::write(feature.join("file-d.txt"), "original d").unwrap();
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Add files"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // 1. Create untracked file (?)
+ std::fs::write(feature.join("untracked.txt"), "new file").unwrap();
+
+ // 2. Modify tracked file without staging (!)
+ std::fs::write(feature.join("file-a.txt"), "modified content").unwrap();
+
+ // 3. Stage some changes (+)
+ std::fs::write(feature.join("file-b.txt"), "staged changes").unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "file-b.txt"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // 4. Rename a file and stage it (»)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["mv", "file-c.txt", "renamed-c.txt"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // 5. Delete a file in index (✘)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["rm", "file-d.txt"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // Result should show: ?!+»✘
+ snapshot_list("maximum_working_tree_symbols", &repo);
+}
+
+#[test]
+fn test_list_maximum_status_with_git_operation() {
+ // Test maximum status symbols including git operation (rebase/merge):
+ // ?!+ (working_tree) + = (conflicts) + ↻ (rebase) + ↕ (diverged) + ⊠ (locked) + 🤖 (user status)
+ // This pushes the Status column to ~10-11 chars of actual content
+ let mut repo = TestRepo::new();
+
+ // Create initial commit with a file that will conflict
+ std::fs::write(
+ repo.root_path().join("conflict.txt"),
+ "original line 1\noriginal line 2\n",
+ )
+ .unwrap();
+ std::fs::write(repo.root_path().join("shared.txt"), "shared content").unwrap();
+ repo.commit("Initial commit");
+
+ // Create feature worktree
+ let feature = repo.add_worktree("feature", "feature");
+
+ // Feature makes changes
+ std::fs::write(
+ feature.join("conflict.txt"),
+ "feature line 1\nfeature line 2\n",
+ )
+ .unwrap();
+ std::fs::write(feature.join("feature.txt"), "feature-specific content").unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Feature changes"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // Main makes conflicting changes
+ std::fs::write(
+ repo.root_path().join("conflict.txt"),
+ "main line 1\nmain line 2\n",
+ )
+ .unwrap();
+ std::fs::write(repo.root_path().join("main-only.txt"), "main content").unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Main conflicting changes"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Start rebase which will create conflicts and git operation state
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ let rebase_output = cmd
+ .args(["rebase", "main"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // Rebase should fail with conflicts - verify we're in rebase state
+ assert!(
+ !rebase_output.status.success(),
+ "Rebase should fail with conflicts"
+ );
+
+ // Now add working tree symbols while in rebase state
+ // 1. Untracked file (?)
+ std::fs::write(feature.join("untracked.txt"), "untracked during rebase").unwrap();
+
+ // 2. Modified file (!) - modify a non-conflicting file
+ std::fs::write(feature.join("feature.txt"), "modified during rebase").unwrap();
+
+ // 3. Staged file (+) - stage the conflict resolution
+ std::fs::write(feature.join("new-staged.txt"), "staged during rebase").unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "new-staged.txt"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // Lock the worktree (⊠)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["worktree", "lock", feature.to_str().unwrap()])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Set user status emoji (🤖)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["config", "worktrunk.status.feature", "🤖"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Result should show: ?!+ (working_tree) + = (conflicts) + ↻ (rebase) + ↕ (diverged) + ⊠ (locked) + 🤖 (user status)
+ // Use --full to enable conflict detection
+ let settings = list_snapshots::standard_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = list_snapshots::command(&repo, repo.root_path());
+ cmd.arg("--full");
+ assert_cmd_snapshot!("maximum_status_with_git_operation", cmd);
+ });
+}
+
+#[test]
+fn test_list_maximum_status_symbols() {
+ // Test the maximum status symbols possible:
+ // ?!+»✘ (5) + = (1) + ⊠ (1) + ↕ (1) + ⇅ (1) + 🤖 (2) = 11 chars
+ // Missing: ↻ (git operation - can't have with divergence), ◇ (bare), ⚠ (prunable)
+ let mut repo = TestRepo::new();
+
+ // Create initial commit on main with shared files
+ std::fs::write(repo.root_path().join("shared.txt"), "original").unwrap();
+ std::fs::write(repo.root_path().join("file-a.txt"), "a").unwrap();
+ std::fs::write(repo.root_path().join("file-b.txt"), "b").unwrap();
+ std::fs::write(repo.root_path().join("file-c.txt"), "c").unwrap();
+ std::fs::write(repo.root_path().join("file-d.txt"), "d").unwrap();
+ repo.commit("Initial commit");
+
+ // Create feature worktree
+ let feature = repo.add_worktree("feature", "feature");
+
+ // Make feature diverge from main (ahead) with conflicting change
+ std::fs::write(feature.join("shared.txt"), "feature version").unwrap();
+ std::fs::write(feature.join("feature.txt"), "feature content").unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Feature work"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // Set up a real local bare repository as the remote for reliable upstream tracking
+ let remote_dir = repo.root_path().parent().unwrap().join("remote.git");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args([
+ "clone",
+ "--bare",
+ repo.root_path().to_str().unwrap(),
+ remote_dir.to_str().unwrap(),
+ ])
+ .output()
+ .unwrap();
+
+ // Add the local bare repo as origin
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["remote", "add", "origin", remote_dir.to_str().unwrap()])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // Push to establish the remote branch
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["push", "-u", "origin", "feature"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // Create divergence: local has commits remote doesn't have, AND vice versa
+ // Step 1: Make a local commit (we'll be ahead)
+ std::fs::write(feature.join("local-only.txt"), "local content").unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "local-only.txt"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Local only commit"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // Step 2: Simulate remote having a divergent commit by creating a parallel history
+
+ // Clone to a temp location starting from our current feature commit
+ let temp_wt = repo.root_path().parent().unwrap().join("temp-for-remote");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args([
+ "clone",
+ "--branch",
+ "feature",
+ remote_dir.to_str().unwrap(),
+ temp_wt.to_str().unwrap(),
+ ])
+ .output()
+ .unwrap();
+
+ // Reset to the commit BEFORE our local commit (so we diverge from a common ancestor)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["reset", "--hard", "HEAD~1"])
+ .current_dir(&temp_wt)
+ .output()
+ .unwrap();
+
+ // Make a different commit on the same base (creating true divergence)
+ std::fs::write(
+ temp_wt.join("remote-diverged.txt"),
+ "remote diverged content",
+ )
+ .unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "remote-diverged.txt"])
+ .current_dir(&temp_wt)
+ .output()
+ .unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Remote diverged commit"])
+ .current_dir(&temp_wt)
+ .output()
+ .unwrap();
+
+ // Force push to update the remote (simulating someone else force-pushed)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["push", "--force", "origin", "feature"])
+ .current_dir(&temp_wt)
+ .output()
+ .unwrap();
+
+ // Fetch so our feature worktree knows about the remote commit
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["fetch", "origin"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // Make main advance with conflicting change (so feature is behind with conflicts)
+ std::fs::write(repo.root_path().join("shared.txt"), "main version").unwrap();
+ std::fs::write(repo.root_path().join("main2.txt"), "more main").unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "."])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Main advances"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Add all 5 working tree symbol types (without rebase, so we keep divergence)
+ // 1. Untracked (?)
+ std::fs::write(feature.join("untracked.txt"), "untracked").unwrap();
+
+ // 2. Modified (!)
+ std::fs::write(feature.join("feature.txt"), "modified").unwrap();
+
+ // 3. Staged (+)
+ std::fs::write(feature.join("new-staged.txt"), "staged content").unwrap();
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "new-staged.txt"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // 4. Renamed (»)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["mv", "file-c.txt", "renamed-c.txt"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // 5. Deleted (✘)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["rm", "file-d.txt"])
+ .current_dir(&feature)
+ .output()
+ .unwrap();
+
+ // Lock the worktree (⊠)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["worktree", "lock", feature.to_str().unwrap()])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Set user status emoji (🤖)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["config", "worktrunk.status.feature", "🤖"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Result should show 11 chars: ?!+»✘=⊠↕⇅🤖
+ let settings = list_snapshots::standard_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = list_snapshots::command(&repo, repo.root_path());
+ cmd.arg("--full");
+ assert_cmd_snapshot!("maximum_status_symbols", cmd);
});
}
diff --git a/tests/integration_tests/list_column_alignment.rs b/tests/integration_tests/list_column_alignment.rs
new file mode 100644
index 000000000..11c3566a5
--- /dev/null
+++ b/tests/integration_tests/list_column_alignment.rs
@@ -0,0 +1,94 @@
+//! Tests for verifying column alignment in list output
+//!
+//! These tests ensure that column headers align with their data,
+//! and that progressive rendering maintains consistent alignment.
+
+use crate::common::{TestRepo, make_snapshot_cmd, setup_snapshot_settings};
+use insta_cmd::assert_cmd_snapshot;
+
+/// Test that Status column data aligns with Status header
+#[test]
+fn test_status_column_alignment_with_header() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create worktree with status symbols
+ let wt = repo.add_worktree("test", "test");
+ std::fs::write(wt.join("file.txt"), "content").unwrap();
+
+ let mut cmd = std::process::Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "file.txt"])
+ .current_dir(&wt)
+ .output()
+ .unwrap();
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Test"])
+ .current_dir(&wt)
+ .output()
+ .unwrap();
+
+ // Add working tree changes for Status symbols
+ std::fs::write(wt.join("untracked.txt"), "new").unwrap();
+ std::fs::write(wt.join("file.txt"), "modified").unwrap();
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(&repo, "beta", &[], None);
+ cmd.arg("list");
+ assert_cmd_snapshot!("status_column_alignment_check", cmd);
+ });
+}
+
+/// Test that Status column width is consistent across all rows
+#[test]
+fn test_status_column_width_consistency() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create multiple worktrees with different status symbol combinations
+ let wt1 = repo.add_worktree("simple", "simple");
+ std::fs::write(wt1.join("file.txt"), "content").unwrap();
+
+ let mut cmd = std::process::Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "file.txt"])
+ .current_dir(&wt1)
+ .output()
+ .unwrap();
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Simple"])
+ .current_dir(&wt1)
+ .output()
+ .unwrap();
+
+ let wt2 = repo.add_worktree("complex", "complex");
+ std::fs::write(wt2.join("file.txt"), "content").unwrap();
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "file.txt"])
+ .current_dir(&wt2)
+ .output()
+ .unwrap();
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Complex"])
+ .current_dir(&wt2)
+ .output()
+ .unwrap();
+
+ // Add different working tree changes
+ std::fs::write(wt1.join("new.txt"), "new").unwrap(); // Just untracked (?)
+ std::fs::write(wt2.join("new1.txt"), "new").unwrap(); // Multiple: ?, !, +
+ std::fs::write(wt2.join("file.txt"), "modified").unwrap();
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "file.txt"])
+ .current_dir(&wt2)
+ .output()
+ .unwrap();
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(&repo, "beta", &[], None);
+ cmd.arg("list");
+ assert_cmd_snapshot!("status_column_width_consistency", cmd);
+ });
+}
diff --git a/tests/integration_tests/list_pty.rs b/tests/integration_tests/list_pty.rs
new file mode 100644
index 000000000..4eaa508b5
--- /dev/null
+++ b/tests/integration_tests/list_pty.rs
@@ -0,0 +1,228 @@
+//! PTY-based tests for `wt list` command
+//!
+//! These tests verify the list command output in a real PTY environment where stdout is a TTY.
+//! This allows testing the progressive rendering mode that uses indicatif progress bars.
+
+use crate::common::TestRepo;
+use insta::assert_snapshot;
+use insta_cmd::get_cargo_bin;
+use portable_pty::{CommandBuilder, PtySize, native_pty_system};
+use std::io::Read;
+use std::path::Path;
+use std::time::Duration;
+
+/// Execute wt list in a PTY
+///
+/// Returns (combined_output, exit_code)
+fn exec_wt_list_in_pty(
+ working_dir: &Path,
+ env_vars: &[(String, String)],
+ args: &[&str],
+) -> (String, i32) {
+ let pty_system = native_pty_system();
+ let pair = pty_system
+ .openpty(PtySize {
+ rows: 48,
+ cols: 150, // Match COLUMNS in standard tests
+ pixel_width: 0,
+ pixel_height: 0,
+ })
+ .expect("Failed to open PTY");
+
+ // Spawn wt list inside the PTY
+ let mut cmd = CommandBuilder::new(get_cargo_bin("wt"));
+ cmd.arg("list");
+ for arg in args {
+ cmd.arg(arg);
+ }
+ cmd.cwd(working_dir);
+
+ // Set minimal environment
+ cmd.env_clear();
+ cmd.env(
+ "HOME",
+ std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string()),
+ );
+ cmd.env(
+ "PATH",
+ std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".to_string()),
+ );
+
+ // Deterministic test environment
+ cmd.env("CLICOLOR_FORCE", "1");
+ cmd.env("LANG", "C");
+ cmd.env("LC_ALL", "C");
+ cmd.env("GIT_CONFIG_GLOBAL", "/dev/null");
+ cmd.env("GIT_CONFIG_SYSTEM", "/dev/null");
+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T00:00:00Z");
+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T00:00:00Z");
+ cmd.env("SOURCE_DATE_EPOCH", "1761609600");
+
+ // Add test-specific environment variables
+ for (key, value) in env_vars {
+ cmd.env(key, value);
+ }
+
+ let mut child = pair
+ .slave
+ .spawn_command(cmd)
+ .expect("Failed to spawn command in PTY");
+ drop(pair.slave); // Close slave in parent
+
+ // Get reader for the PTY master
+ let mut reader = pair
+ .master
+ .try_clone_reader()
+ .expect("Failed to clone PTY reader");
+
+ // Read output with timeout to handle progressive rendering
+ let mut buf = Vec::new();
+ let start = std::time::Instant::now();
+ let timeout = Duration::from_secs(10);
+
+ loop {
+ let mut temp_buf = [0u8; 4096];
+ match reader.read(&mut temp_buf) {
+ Ok(0) => break, // EOF
+ Ok(n) => {
+ buf.extend_from_slice(&temp_buf[..n]);
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
+ // Check if child has exited
+ if let Ok(Some(_)) = child.try_wait() {
+ // Child exited, read remaining data
+ std::thread::sleep(Duration::from_millis(100));
+ continue;
+ }
+ if start.elapsed() > timeout {
+ panic!("Timeout waiting for command output");
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ Err(e) => panic!("Failed to read PTY output: {}", e),
+ }
+ }
+
+ // Wait for child to exit
+ let exit_status = child.wait().expect("Failed to wait for child");
+ let exit_code = exit_status.exit_code() as i32;
+
+ let output = String::from_utf8_lossy(&buf).to_string();
+ (output, exit_code)
+}
+
+/// Normalize PTY output for snapshot testing
+fn normalize_pty_output(output: &str) -> String {
+ // Strip ANSI codes for easier snapshot reading
+ let output = strip_ansi_escapes::strip_str(output);
+
+ // Normalize line endings
+ output.replace("\r\n", "\n").replace('\r', "\n")
+}
+
+// Flaky: PTY progressive rendering has timing-dependent output that changes between runs.
+// The non-PTY tests already verify status column rendering with emoji user status.
+#[test]
+#[ignore]
+fn test_list_pty_status_column_padding_with_emoji() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create wli-sequence worktree with large diff
+ let wli_seq = repo.add_worktree("wli-sequence", "wli-sequence");
+
+ // Create initial content: 200 lines
+ let initial_content = (1..=200)
+ .map(|i| format!("original line {}", i))
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(wli_seq.join("main.txt"), &initial_content).expect("write failed");
+
+ let mut cmd = std::process::Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "main.txt"])
+ .current_dir(&wli_seq)
+ .output()
+ .expect("git add failed");
+
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Initial content"])
+ .current_dir(&wli_seq)
+ .output()
+ .expect("git commit failed");
+
+ // Modify to create large diff: +164, -111 (roughly)
+ let modified_content = (1..=253)
+ .map(|i| {
+ if i % 2 == 0 {
+ format!("modified line {}", i)
+ } else {
+ format!("original line {}", i)
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(wli_seq.join("main.txt"), &modified_content).expect("write failed");
+
+ // Add untracked and modified files for Status symbols
+ std::fs::write(wli_seq.join("untracked.txt"), "new file").expect("write untracked failed");
+
+ // Set user status emoji for wli-sequence
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["config", "worktrunk.status.wli-sequence", "🤖"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("config set failed");
+
+ // Create pr-link worktree with emoji
+ let pr_link = repo.add_worktree("pr-link", "pr-link");
+ std::fs::write(pr_link.join("pr.txt"), "PR commit").expect("write failed");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "pr.txt"])
+ .current_dir(&pr_link)
+ .output()
+ .expect("git add failed");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "PR commit"])
+ .current_dir(&pr_link)
+ .output()
+ .expect("git commit failed");
+
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["config", "worktrunk.status.pr-link", "🤖"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("config set failed");
+
+ // Create main-symbol worktree with emoji
+ let main_symbol = repo.add_worktree("main-symbol", "main-symbol");
+ std::fs::write(main_symbol.join("symbol.txt"), "Symbol commit").expect("write failed");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "symbol.txt"])
+ .current_dir(&main_symbol)
+ .output()
+ .expect("git add failed");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Symbol commit"])
+ .current_dir(&main_symbol)
+ .output()
+ .expect("git commit failed");
+
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["config", "worktrunk.status.main-symbol", "💬"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("config set failed");
+
+ // Run wt list in PTY
+ let env_vars = vec![(
+ "WORKTRUNK_CONFIG_PATH".to_string(),
+ repo.test_config_path().to_string_lossy().to_string(),
+ )];
+ let (output, exit_code) = exec_wt_list_in_pty(repo.root_path(), &env_vars, &[]);
+
+ assert_eq!(exit_code, 0, "wt list should succeed");
+
+ let normalized = normalize_pty_output(&output);
+ assert_snapshot!("list_pty_status_column_padding_emoji", normalized);
+}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index 99e4e6d8f..ccc55dca0 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -22,6 +22,8 @@ pub mod e2e_shell_post_start;
pub mod init;
pub mod internal_flag;
pub mod list;
+pub mod list_column_alignment;
+pub mod list_pty;
pub mod merge;
pub mod post_start_commands;
pub mod push;
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap b/tests/integration_tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap
index 2f5970274..e82a42284 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap
@@ -14,15 +14,15 @@ info:
LC_ALL: C
NO_COLOR: ""
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpGKqIBp/test-config.toml
+ WORKTRUNK_CONFIG: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmplGvHJf/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-feature ./test-repo.feature 72413a3b 10 months ago Work on feature
-main ↓∅ ↓1 ./test-repo.main 6c3da842 10 months ago Initial commit on main
-
-⚪ Showing 2 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+feature ./test-repo.feature 72413a3b 10 months ago Work on feature
+main ∅ ↓ ↓1 ./test-repo.main 6c3da842 10 months ago Initial commit on main
+
+⚪ Showing 2 worktrees
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_interactive_approval_demo.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_interactive_approval_demo.snap
deleted file mode 100644
index 3ce1c7eba..000000000
--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_interactive_approval_demo.snap
+++ /dev/null
@@ -1,23 +0,0 @@
----
-source: tests/integration_tests/shell_wrapper.rs
-expression: output.normalized()
----
-y
-
-^D🟡 origin wants to execute 1 command:
-
-🔄 pre-merge test:
-  echo '✓ Tests passed'
-
-💡 Allow and remember? [y/N]
-⚪ Commands declined, continuing merge
-🔄 Running pre-merge test:
-  echo '✓ Tests passed'
-✓ Tests passed
-🔄 Merging 1 commit to main @ [HASH] (no commit/squash/rebase needed)
-  * [HASH] (HEAD -> feature) Add feature
-  feature.txt | 1 +
-  1 file changed, 1 insertion(+)
-✅ Merged to main (1 commit, 1 file, +1)
-🔄 Removing worktree & branch...
-✅ Removed worktree & branch for feature, changed directory to [TMPDIR]/test-repo
diff --git a/tests/output_system_guard.rs b/tests/output_system_guard.rs
index 53869d97f..9118d2003 100644
--- a/tests/output_system_guard.rs
+++ b/tests/output_system_guard.rs
@@ -4,7 +4,12 @@ use std::path::Path;
#[test]
fn check_output_system_usage() {
let project_root = env!("CARGO_MANIFEST_DIR");
- let restricted_files = ["src/commands/worktree.rs", "src/commands/merge.rs"];
+ let restricted_files = [
+ "src/commands/worktree.rs",
+ "src/commands/merge.rs",
+ "src/commands/list/mod.rs",
+ "src/commands/list/collect.rs",
+ ];
let forbidden_tokens = ["print!", "println!", "eprint!", "eprintln!"];
let allowed_substrings = ["spacing_test.rs", "command_approval.rs"];
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index 9ae5f20b1..90faf44a7 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp9vlu3M/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpjbIi2I/test-config.toml
---
success: true
exit_code: 0
@@ -118,9 +118,10 @@ wt_exec() {
_WORKTRUNK_CMD="./target/debug/wt"
fi
- # Force colors if wrapper's stdout is a TTY (respects NO_COLOR and explicit CLICOLOR_FORCE)
+ # Force colors if stderr is a TTY (directive mode outputs to stderr)
+ # Respects NO_COLOR and explicit CLICOLOR_FORCE
if [[ -z "${NO_COLOR:-}" && -z "${CLICOLOR_FORCE:-}" ]]; then
- if [[ -t 1 ]]; then export CLICOLOR_FORCE=1; fi
+ if [[ -t 2 ]]; then export CLICOLOR_FORCE=1; fi
fi
# Always use --internal mode for directive support
@@ -588,7 +589,7 @@ _wt() {
return 0
;;
wt__list)
- opts="-C -v -h --format --branches --full --verbose --help"
+ opts="-C -v -h --format --branches --full --progressive --no-progressive --verbose --help"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 62521c405..73299ac7d 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpzQbSvH/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmppDJXpo/test-config.toml
---
success: true
exit_code: 0
@@ -133,9 +133,10 @@ if type -q wt; or set -q WORKTRUNK_BIN
set _WORKTRUNK_CMD ./target/debug/wt
end
- # Force colors if wrapper's stdout is a TTY (respects NO_COLOR and explicit CLICOLOR_FORCE)
+ # Force colors if stderr is a TTY (directive mode outputs to stderr)
+ # Respects NO_COLOR and explicit CLICOLOR_FORCE
if not set -q NO_COLOR; and not set -q CLICOLOR_FORCE
- if isatty stdout
+ if isatty stderr
set -x CLICOLOR_FORCE 1
end
end
@@ -277,6 +278,8 @@ json\t'JSON output'"
complete -c wt -n "__fish_wt_using_subcommand list" -s C -d 'Change working directory' -r -F
complete -c wt -n "__fish_wt_using_subcommand list" -l branches -d 'Include branches without worktrees'
complete -c wt -n "__fish_wt_using_subcommand list" -l full -d 'Show CI, conflicts, and full diffs'
+complete -c wt -n "__fish_wt_using_subcommand list" -l progressive -d 'Show rows progressively (auto-detects TTY)'
+complete -c wt -n "__fish_wt_using_subcommand list" -l no-progressive -d 'Disable progressive rendering'
complete -c wt -n "__fish_wt_using_subcommand list" -s v -l verbose -d 'Show git commands and debug info'
complete -c wt -n "__fish_wt_using_subcommand list" -s h -l help -d 'Print help (see more with \'--help\')'
complete -c wt -n "__fish_wt_using_subcommand switch" -s b -l base -f -d 'Base branch (defaults to default branch)' -r
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index 962c2bf63..0860905b7 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpnjIQTI/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpwBTqs5/test-config.toml
---
success: true
exit_code: 0
@@ -118,9 +118,10 @@ wt_exec() {
_WORKTRUNK_CMD="./target/debug/wt"
fi
- # Force colors if wrapper's stdout is a TTY (respects NO_COLOR and explicit CLICOLOR_FORCE)
+ # Force colors if stderr is a TTY (directive mode outputs to stderr)
+ # Respects NO_COLOR and explicit CLICOLOR_FORCE
if [[ -z "${NO_COLOR:-}" && -z "${CLICOLOR_FORCE:-}" ]]; then
- if [[ -t 1 ]]; then export CLICOLOR_FORCE=1; fi
+ if [[ -t 2 ]]; then export CLICOLOR_FORCE=1; fi
fi
# Always use --internal mode for directive support
@@ -406,6 +407,8 @@ json\:"JSON output"))' \
'-C+[Change working directory]:path:_files' \
'--branches[Include branches without worktrees]' \
'--full[Show CI, conflicts, and full diffs]' \
+'(--no-progressive)--progressive[Show rows progressively (auto-detects TTY)]' \
+'--no-progressive[Disable progressive rendering]' \
'-v[Show git commands and debug info]' \
'--verbose[Show git commands and debug info]' \
'-h[Print help (see more with '\''--help'\'')]' \
diff --git a/tests/snapshots/integration__integration_tests__internal_flag__list_with_internal_flag.snap b/tests/snapshots/integration__integration_tests__internal_flag__list_with_internal_flag.snap
index e1397ec81..65dc12467 100644
--- a/tests/snapshots/integration__integration_tests__internal_flag__list_with_internal_flag.snap
+++ b/tests/snapshots/integration__integration_tests__internal_flag__list_with_internal_flag.snap
@@ -16,14 +16,14 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpK9xwH7/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpxrS10W/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main . b834638e 10 months ago Initial commit
-
-⚪ Showing 1 worktree
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main . b834638e 10 months ago Initial commit
+
+⚪ Showing 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__list__branch_only_ignores_main_worktree_status.snap b/tests/snapshots/integration__integration_tests__list__branch_only_ignores_main_worktree_status.snap
deleted file mode 100644
index e457652e8..000000000
--- a/tests/snapshots/integration__integration_tests__list__branch_only_ignores_main_worktree_status.snap
+++ /dev/null
@@ -1,30 +0,0 @@
----
-source: tests/integration_tests/list.rs
-info:
- program: wt
- args:
- - list
- - "--branches"
- env:
- CLICOLOR_FORCE: "1"
- COLUMNS: "150"
- GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
- GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: /dev/null
- GIT_CONFIG_SYSTEM: /dev/null
- GIT_EDITOR: ""
- LANG: C
- LC_ALL: C
- SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpYCSwh8/test-config.toml
----
-success: true
-exit_code: 0
------ stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main . b834638e 10 months ago Initial commit
-branch-only b834638e 10 months ago Initial commit
-
-⚪ Showing 1 worktrees, 1 branches
-
------ stderr -----
diff --git a/tests/snapshots/integration__integration_tests__list__branch_only_with_status.snap b/tests/snapshots/integration__integration_tests__list__branch_only_with_status.snap
index 4e275c3ca..4b24fc224 100644
--- a/tests/snapshots/integration__integration_tests__list__branch_only_with_status.snap
+++ b/tests/snapshots/integration__integration_tests__list__branch_only_with_status.snap
@@ -16,15 +16,15 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpKrAsZ9/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpOqe8Xp/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main . b834638e 10 months ago Initial commit
-branch-only b834638e 10 months ago Initial commit
-
-⚪ Showing 1 worktrees, 1 branches
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main . b834638e 10 months ago Initial commit
+branch-only b834638e 10 months ago Initial commit
+
+⚪ Showing 1 worktrees, 1 branches
diff --git a/tests/snapshots/integration__integration_tests__list__detached_head.snap b/tests/snapshots/integration__integration_tests__list__detached_head.snap
index 029efbfc1..205e67d69 100644
--- a/tests/snapshots/integration__integration_tests__list__detached_head.snap
+++ b/tests/snapshots/integration__integration_tests__list__detached_head.snap
@@ -15,14 +15,14 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpUfT1zI/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpDawLcz/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-(detached) . b834638e 10 months ago Initial commit
-
-⚪ Showing 1 worktree
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+(detached) . b834638e 10 months ago Initial commit
+
+⚪ Showing 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap b/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap
index 96ca6b18b..b79842ea1 100644
--- a/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap
+++ b/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap
@@ -12,48 +12,25 @@ info:
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
- GIT_EDITOR: ""
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpvFchbF/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpYxhIJh/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
[
{
- "type": "worktree",
- "path": "[REPO]",
"head_sha": "a27cd57d20a6211799da676e70edefa5152f99fe",
"branch": "main",
- "bare": false,
- "detached": false,
- "locked": null,
- "prunable": null,
"timestamp": 0,
"commit_message": "Main commit 2",
- "ahead": 0,
- "behind": 0,
- "branch_diff": {
- "added": 0,
- "deleted": 0
- },
- "working_tree_diff": {
- "added": 0,
- "deleted": 0
- },
- "working_tree_diff_with_main": {
- "added": 0,
- "deleted": 0
- },
- "worktree_state": null,
- "has_conflicts": false,
- "is_primary": true,
"upstream_remote": null,
"upstream_ahead": 0,
"upstream_behind": 0,
"pr_status": null,
+ "has_conflicts": false,
"status_symbols": {
"has_conflicts": false,
"has_potential_conflicts": false,
@@ -64,17 +41,27 @@ exit_code: 0
"upstream_divergence": "",
"working_tree": "",
"user_status": null
- }
- },
- {
+ },
"type": "worktree",
- "path": "[WORKTREE_FEATURE_AHEAD]",
- "head_sha": "f16cd37915d5ee93903252f5cf877c76c54f3d50",
- "branch": "feature-ahead",
+ "path": "[REPO]",
"bare": false,
"detached": false,
"locked": null,
"prunable": null,
+ "working_tree_diff": {
+ "added": 0,
+ "deleted": 0
+ },
+ "working_tree_diff_with_main": {
+ "added": 0,
+ "deleted": 0
+ },
+ "worktree_state": null,
+ "is_primary": true
+ },
+ {
+ "head_sha": "f16cd37915d5ee93903252f5cf877c76c54f3d50",
+ "branch": "feature-ahead",
"timestamp": 0,
"commit_message": "Feature commit 2",
"ahead": 2,
@@ -83,17 +70,11 @@ exit_code: 0
"added": 1,
"deleted": 0
},
- "working_tree_diff": {
- "added": 1,
- "deleted": 1
- },
- "worktree_state": null,
- "has_conflicts": false,
- "is_primary": false,
"upstream_remote": null,
"upstream_ahead": 0,
"upstream_behind": 0,
"pr_status": null,
+ "has_conflicts": false,
"status_symbols": {
"has_conflicts": false,
"has_potential_conflicts": false,
@@ -107,18 +88,24 @@ exit_code: 0
},
"commits_display": "/u001b[32m↑2/u001b[0m /u001b[2m/u001b[31m↓2/u001b[0m",
"branch_diff_display": "/u001b[32m+1/u001b[0m",
- "status_display": "/u001b[36m?!/u001b[0m ↕ ",
- "working_diff_display": "/u001b[32m+1/u001b[0m /u001b[31m-1/u001b[0m"
- },
- {
"type": "worktree",
- "path": "[WORKTREE_FEATURE_BEHIND]",
- "head_sha": "6c3da84215d400bf6e05a7f9cd1efcfbd825b9e9",
- "branch": "feature-behind",
+ "path": "[WORKTREE_FEATURE_AHEAD]",
"bare": false,
"detached": false,
"locked": null,
"prunable": null,
+ "working_tree_diff": {
+ "added": 1,
+ "deleted": 1
+ },
+ "working_tree_diff_with_main": null,
+ "worktree_state": null,
+ "is_primary": false,
+ "working_diff_display": "/u001b[32m+1/u001b[0m /u001b[31m-1/u001b[0m"
+ },
+ {
+ "head_sha": "6c3da84215d400bf6e05a7f9cd1efcfbd825b9e9",
+ "branch": "feature-behind",
"timestamp": 0,
"commit_message": "Initial commit on main",
"ahead": 0,
@@ -127,17 +114,11 @@ exit_code: 0
"added": 0,
"deleted": 0
},
- "working_tree_diff": {
- "added": 0,
- "deleted": 0
- },
- "worktree_state": null,
- "has_conflicts": false,
- "is_primary": false,
"upstream_remote": null,
"upstream_ahead": 0,
"upstream_behind": 0,
"pr_status": null,
+ "has_conflicts": false,
"status_symbols": {
"has_conflicts": false,
"has_potential_conflicts": false,
@@ -150,7 +131,19 @@ exit_code: 0
"user_status": null
},
"commits_display": "/u001b[2m/u001b[31m↓2/u001b[0m",
- "status_display": " ↓ /u001b[2m∅/u001b[0m "
+ "type": "worktree",
+ "path": "[WORKTREE_FEATURE_BEHIND]",
+ "bare": false,
+ "detached": false,
+ "locked": null,
+ "prunable": null,
+ "working_tree_diff": {
+ "added": 0,
+ "deleted": 0
+ },
+ "working_tree_diff_with_main": null,
+ "worktree_state": null,
+ "is_primary": false
}
]
diff --git a/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap b/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap
index 5d14ddcf0..b20d74df9 100644
--- a/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap
+++ b/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap
@@ -12,48 +12,25 @@ info:
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
- GIT_EDITOR: ""
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp9iVH2N/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpxMKsWA/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
[
{
- "type": "worktree",
- "path": "[REPO]",
"head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
"branch": "main",
- "bare": false,
- "detached": false,
- "locked": null,
- "prunable": null,
"timestamp": 0,
"commit_message": "Initial commit",
- "ahead": 0,
- "behind": 0,
- "branch_diff": {
- "added": 0,
- "deleted": 0
- },
- "working_tree_diff": {
- "added": 0,
- "deleted": 0
- },
- "working_tree_diff_with_main": {
- "added": 0,
- "deleted": 0
- },
- "worktree_state": null,
- "has_conflicts": false,
- "is_primary": true,
"upstream_remote": null,
"upstream_ahead": 0,
"upstream_behind": 0,
"pr_status": null,
+ "has_conflicts": false,
"status_symbols": {
"has_conflicts": false,
"has_potential_conflicts": false,
@@ -64,25 +41,13 @@ exit_code: 0
"upstream_divergence": "",
"working_tree": "",
"user_status": null
- }
- },
- {
+ },
"type": "worktree",
- "path": "[WORKTREE_FEATURE_DETACHED]",
- "head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
- "branch": "feature-detached",
+ "path": "[REPO]",
"bare": false,
"detached": false,
"locked": null,
"prunable": null,
- "timestamp": 0,
- "commit_message": "Initial commit",
- "ahead": 0,
- "behind": 0,
- "branch_diff": {
- "added": 0,
- "deleted": 0
- },
"working_tree_diff": {
"added": 0,
"deleted": 0
@@ -92,12 +57,24 @@ exit_code: 0
"deleted": 0
},
"worktree_state": null,
- "has_conflicts": false,
- "is_primary": false,
+ "is_primary": true
+ },
+ {
+ "head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
+ "branch": "feature-detached",
+ "timestamp": 0,
+ "commit_message": "Initial commit",
+ "ahead": 0,
+ "behind": 0,
+ "branch_diff": {
+ "added": 0,
+ "deleted": 0
+ },
"upstream_remote": null,
"upstream_ahead": 0,
"upstream_behind": 0,
"pr_status": null,
+ "has_conflicts": false,
"status_symbols": {
"has_conflicts": false,
"has_potential_conflicts": false,
@@ -109,25 +86,12 @@ exit_code: 0
"working_tree": "",
"user_status": null
},
- "status_display": " /u001b[2m≡/u001b[0m "
- },
- {
"type": "worktree",
- "path": "[WORKTREE_LOCKED_FEATURE]",
- "head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
- "branch": "locked-feature",
+ "path": "[WORKTREE_FEATURE_DETACHED]",
"bare": false,
"detached": false,
- "locked": "Testing",
+ "locked": null,
"prunable": null,
- "timestamp": 0,
- "commit_message": "Initial commit",
- "ahead": 0,
- "behind": 0,
- "branch_diff": {
- "added": 0,
- "deleted": 0
- },
"working_tree_diff": {
"added": 0,
"deleted": 0
@@ -137,12 +101,24 @@ exit_code: 0
"deleted": 0
},
"worktree_state": null,
- "has_conflicts": false,
- "is_primary": false,
+ "is_primary": false
+ },
+ {
+ "head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
+ "branch": "locked-feature",
+ "timestamp": 0,
+ "commit_message": "Initial commit",
+ "ahead": 0,
+ "behind": 0,
+ "branch_diff": {
+ "added": 0,
+ "deleted": 0
+ },
"upstream_remote": null,
"upstream_ahead": 0,
"upstream_behind": 0,
"pr_status": null,
+ "has_conflicts": false,
"status_symbols": {
"has_conflicts": false,
"has_potential_conflicts": false,
@@ -154,7 +130,22 @@ exit_code: 0
"working_tree": "",
"user_status": null
},
- "status_display": " /u001b[2m≡/u001b[0m/u001b[33m⊠/u001b[0m "
+ "type": "worktree",
+ "path": "[WORKTREE_LOCKED_FEATURE]",
+ "bare": false,
+ "detached": false,
+ "locked": "Testing",
+ "prunable": null,
+ "working_tree_diff": {
+ "added": 0,
+ "deleted": 0
+ },
+ "working_tree_diff_with_main": {
+ "added": 0,
+ "deleted": 0
+ },
+ "worktree_state": null,
+ "is_primary": false
}
]
diff --git a/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap b/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap
index ba3584b84..2fe16f71b 100644
--- a/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap
+++ b/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap
@@ -12,48 +12,25 @@ info:
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
- GIT_EDITOR: ""
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp7D6YbP/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpPlVPx6/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
[
{
- "type": "worktree",
- "path": "[REPO]",
"head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
"branch": "main",
- "bare": false,
- "detached": false,
- "locked": null,
- "prunable": null,
"timestamp": 0,
"commit_message": "Initial commit",
- "ahead": 0,
- "behind": 0,
- "branch_diff": {
- "added": 0,
- "deleted": 0
- },
- "working_tree_diff": {
- "added": 0,
- "deleted": 0
- },
- "working_tree_diff_with_main": {
- "added": 0,
- "deleted": 0
- },
- "worktree_state": null,
- "has_conflicts": false,
- "is_primary": true,
"upstream_remote": null,
"upstream_ahead": 0,
"upstream_behind": 0,
"pr_status": null,
+ "has_conflicts": false,
"status_symbols": {
"has_conflicts": false,
"has_potential_conflicts": false,
@@ -64,25 +41,13 @@ exit_code: 0
"upstream_divergence": "",
"working_tree": "",
"user_status": null
- }
- },
- {
+ },
"type": "worktree",
- "path": "[WORKTREE_WITH_STATUS]",
- "head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
- "branch": "with-status",
+ "path": "[REPO]",
"bare": false,
"detached": false,
"locked": null,
"prunable": null,
- "timestamp": 0,
- "commit_message": "Initial commit",
- "ahead": 0,
- "behind": 0,
- "branch_diff": {
- "added": 0,
- "deleted": 0
- },
"working_tree_diff": {
"added": 0,
"deleted": 0
@@ -92,12 +57,25 @@ exit_code: 0
"deleted": 0
},
"worktree_state": null,
- "has_conflicts": false,
- "is_primary": false,
+ "is_primary": true
+ },
+ {
+ "head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
+ "branch": "with-status",
+ "timestamp": 0,
+ "commit_message": "Initial commit",
+ "ahead": 0,
+ "behind": 0,
+ "branch_diff": {
+ "added": 0,
+ "deleted": 0
+ },
"upstream_remote": null,
"upstream_ahead": 0,
"upstream_behind": 0,
"pr_status": null,
+ "has_conflicts": false,
+ "user_status": "🔧",
"status_symbols": {
"has_conflicts": false,
"has_potential_conflicts": false,
@@ -109,25 +87,12 @@ exit_code: 0
"working_tree": "",
"user_status": "🔧"
},
- "status_display": " /u001b[2m≡/u001b[0m 🔧"
- },
- {
"type": "worktree",
- "path": "[WORKTREE_WITHOUT_STATUS]",
- "head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
- "branch": "without-status",
+ "path": "[WORKTREE_WITH_STATUS]",
"bare": false,
"detached": false,
"locked": null,
"prunable": null,
- "timestamp": 0,
- "commit_message": "Initial commit",
- "ahead": 0,
- "behind": 0,
- "branch_diff": {
- "added": 0,
- "deleted": 0
- },
"working_tree_diff": {
"added": 0,
"deleted": 0
@@ -137,12 +102,24 @@ exit_code: 0
"deleted": 0
},
"worktree_state": null,
- "has_conflicts": false,
- "is_primary": false,
+ "is_primary": false
+ },
+ {
+ "head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
+ "branch": "without-status",
+ "timestamp": 0,
+ "commit_message": "Initial commit",
+ "ahead": 0,
+ "behind": 0,
+ "branch_diff": {
+ "added": 0,
+ "deleted": 0
+ },
"upstream_remote": null,
"upstream_ahead": 0,
"upstream_behind": 0,
"pr_status": null,
+ "has_conflicts": false,
"status_symbols": {
"has_conflicts": false,
"has_potential_conflicts": false,
@@ -154,7 +131,22 @@ exit_code: 0
"working_tree": "",
"user_status": null
},
- "status_display": " /u001b[2m≡/u001b[0m "
+ "type": "worktree",
+ "path": "[WORKTREE_WITHOUT_STATUS]",
+ "bare": false,
+ "detached": false,
+ "locked": null,
+ "prunable": null,
+ "working_tree_diff": {
+ "added": 0,
+ "deleted": 0
+ },
+ "working_tree_diff_with_main": {
+ "added": 0,
+ "deleted": 0
+ },
+ "worktree_state": null,
+ "is_primary": false
}
]
diff --git a/tests/snapshots/integration__integration_tests__list__large_diffs_alignment.snap b/tests/snapshots/integration__integration_tests__list__large_diffs_alignment.snap
new file mode 100644
index 000000000..2760b8cfa
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__large_diffs_alignment.snap
@@ -0,0 +1,31 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpNI9BWQ/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+diverged ! ↑ 💬 +40 -60 ↑1 ./diverged 8ba5aa92 10 months ago Diverged commit
+feature-changes ?! ↑ 🤖 +50 -1C ↑1 ./feature-changes b854b166 10 months ago Add 100 lines
+fix ? ≡ 💬 ./fix b834638e 10 months ago Initial commit
+
+⚪ Showing 4 worktrees, 2 with changes, 2 ahead
diff --git a/tests/snapshots/integration__integration_tests__list__list_ordering_rules.snap b/tests/snapshots/integration__integration_tests__list__list_ordering_rules.snap
index f68508c1e..023967010 100644
--- a/tests/snapshots/integration__integration_tests__list__list_ordering_rules.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_ordering_rules.snap
@@ -15,18 +15,18 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpHhY88S/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp1wfTdq/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo 6c3da842 10 months ago Initial commit on main
-feature-current ↑ ↑1 ./feature-current fc28a4d1 9 months ago Commit at 01:00
-feature-newest ↑ ↑1 ./feature-newest 136358eb 9 months ago Commit at 03:00
-feature-middle ↑ ↑1 ./feature-middle a0a4851a 9 months ago Commit at 02:00
-feature-oldest ↑ ↑1 ./feature-oldest 1b1a2d78 9 months ago Commit at 00:30
-
-⚪ Showing 5 worktrees, 4 ahead
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo 6c3da842 10 months ago Initial commit on main
+feature-current ↑ ↑1 ./feature-current fc28a4d1 9 months ago Commit at 01:00
+feature-newest ↑ ↑1 ./feature-newest 136358eb 9 months ago Commit at 03:00
+feature-middle ↑ ↑1 ./feature-middle a0a4851a 9 months ago Commit at 02:00
+feature-oldest ↑ ↑1 ./feature-oldest 1b1a2d78 9 months ago Commit at 00:30
+
+⚪ Showing 5 worktrees, 4 ahead
diff --git a/tests/snapshots/integration__integration_tests__list__list_primary_on_different_branch.snap b/tests/snapshots/integration__integration_tests__list__list_primary_on_different_branch.snap
index 96e4244c9..ddc25a188 100644
--- a/tests/snapshots/integration__integration_tests__list__list_primary_on_different_branch.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_primary_on_different_branch.snap
@@ -15,16 +15,16 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpn2Ky9f/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpIQWTTN/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-develop ./test-repo b834638e 10 months ago Initial commit
-feature-a ≡ ./feature-a b834638e 10 months ago Initial commit
-feature-b ≡ ./feature-b b834638e 10 months ago Initial commit
-
-⚪ Showing 3 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+develop ./test-repo b834638e 10 months ago Initial commit
+feature-a ≡ ./feature-a b834638e 10 months ago Initial commit
+feature-b ≡ ./feature-b b834638e 10 months ago Initial commit
+
+⚪ Showing 3 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__list_with_c_flag.snap b/tests/snapshots/integration__integration_tests__list__list_with_c_flag.snap
index cd64f5d8f..d5b9873c6 100644
--- a/tests/snapshots/integration__integration_tests__list__list_with_c_flag.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_with_c_flag.snap
@@ -4,7 +4,7 @@ info:
program: wt
args:
- "-C"
- - /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpxvzlCG/test-repo
+ - /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpR1ixOC/test-repo
- list
env:
CLICOLOR_FORCE: "1"
@@ -14,11 +14,11 @@ info:
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-feature-a ≡ ./feature-a b834638e 10 months ago Initial commit
-feature-b ≡ ./feature-b b834638e 10 months ago Initial commit
-
-⚪ Showing 3 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature-a ≡ ./feature-a b834638e 10 months ago Initial commit
+feature-b ≡ ./feature-b b834638e 10 months ago Initial commit
+
+⚪ Showing 3 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__locked_no_reason.snap b/tests/snapshots/integration__integration_tests__list__locked_no_reason.snap
index 85884ad1f..a84463db8 100644
--- a/tests/snapshots/integration__integration_tests__list__locked_no_reason.snap
+++ b/tests/snapshots/integration__integration_tests__list__locked_no_reason.snap
@@ -15,15 +15,15 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp2t0qWp/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpMK1AKe/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-locked-no-reason ≡⊠ ./locked-no-reason b834638e 10 months ago Initial commit
-
-⚪ Showing 2 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+locked-no-reason ≡ ⊠ ./locked-no-reason b834638e 10 months ago Initial commit
+
+⚪ Showing 2 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__locked_worktree.snap b/tests/snapshots/integration__integration_tests__list__locked_worktree.snap
index 3026d4345..7246aa28f 100644
--- a/tests/snapshots/integration__integration_tests__list__locked_worktree.snap
+++ b/tests/snapshots/integration__integration_tests__list__locked_worktree.snap
@@ -15,15 +15,15 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmptcut9H/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpA6DYgB/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-locked-feature ≡⊠ ./locked-feature b834638e 10 months ago Initial commit
-
-⚪ Showing 2 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+locked-feature ≡ ⊠ ./locked-feature b834638e 10 months ago Initial commit
+
+⚪ Showing 2 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__long_commit_message.snap b/tests/snapshots/integration__integration_tests__list__long_commit_message.snap
index eeb8f7b97..f2e892337 100644
--- a/tests/snapshots/integration__integration_tests__list__long_commit_message.snap
+++ b/tests/snapshots/integration__integration_tests__list__long_commit_message.snap
@@ -15,15 +15,15 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp0Jg3w4/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp6tKV5l/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo 1310bfb9 10 months ago Short message
-feature-a ↓∅ ↓1 ./feature-a f078644e 10 months ago This is a very long commit message that should test how the...
-
-⚪ Showing 2 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo 1310bfb9 10 months ago Short message
+feature-a ∅ ↓ ↓1 ./feature-a f078644e 10 months ago This is a very long commit message that should test how...
+
+⚪ Showing 2 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__many_worktrees_varied.snap b/tests/snapshots/integration__integration_tests__list__many_worktrees_varied.snap
index bb6df7964..d878c8812 100644
--- a/tests/snapshots/integration__integration_tests__list__many_worktrees_varied.snap
+++ b/tests/snapshots/integration__integration_tests__list__many_worktrees_varied.snap
@@ -15,18 +15,18 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpsGoyzk/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpdjY4HN/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-medium-name ≡ ./medium-name b834638e 10 months ago Initial commit
-short ≡ ./short b834638e 10 months ago Initial commit
-very-long-branch-name-here ≡ ./very-long-branch-name-here b834638e 10 months ago Initial commit
-with-changes ≡ ./with-changes b834638e 10 months ago Initial commit
-
-⚪ Showing 5 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+medium-name ≡ ./medium-name b834638e 10 months ago Initial commit
+short ≡ ./short b834638e 10 months ago Initial commit
+very-long-branch-name-here ≡ ./very-long-branch-name-here b834638e 10 months ago Initial commit
+with-changes ≡ ./with-changes b834638e 10 months ago Initial commit
+
+⚪ Showing 5 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__maximum_status_symbols.snap b/tests/snapshots/integration__integration_tests__list__maximum_status_symbols.snap
new file mode 100644
index 000000000..91a7e5319
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__maximum_status_symbols.snap
@@ -0,0 +1,30 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--full"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp1pu5eo/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ main…± Path Remote⇅ CI Commit Age Message
+main ./test-repo 85ed6d3d 10 months ago Main advances
+feature ?!+»✘= ⊠ ↕⇅🤖 +2 -2 ↑2 ↓1 +3 -1 ./feature ↑2 ↓1 21dc61ca 10 months ago Local only commit
+
+⚪ Showing 2 worktrees, 1 with changes, 1 ahead
diff --git a/tests/snapshots/integration__integration_tests__list__maximum_status_with_git_operation.snap b/tests/snapshots/integration__integration_tests__list__maximum_status_with_git_operation.snap
new file mode 100644
index 000000000..b53adbc30
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__maximum_status_with_git_operation.snap
@@ -0,0 +1,30 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--full"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp5jAqCV/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ main…± Path Remote⇅ CI Commit Age Message
+main ./test-repo b7c14ce1 10 months ago Main conflicting changes
+feature ?!+ ↻⊠ 🤖 +7 ./feature b7c14ce1 10 months ago Main conflicting changes
+
+⚪ Showing 2 worktrees, 1 with changes
diff --git a/tests/snapshots/integration__integration_tests__list__maximum_working_tree_symbols.snap b/tests/snapshots/integration__integration_tests__list__maximum_working_tree_symbols.snap
new file mode 100644
index 000000000..ee1a341f1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__maximum_working_tree_symbols.snap
@@ -0,0 +1,29 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp53X7Q6/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature ?!+»✘ ↑ +2 -3 ↑1 ./feature 689c2504 10 months ago Add files
+
+⚪ Showing 2 worktrees, 1 with changes, 1 ahead
diff --git a/tests/snapshots/integration__integration_tests__list__multiple_worktrees.snap b/tests/snapshots/integration__integration_tests__list__multiple_worktrees.snap
index 9d7de9f3a..ef1325ea8 100644
--- a/tests/snapshots/integration__integration_tests__list__multiple_worktrees.snap
+++ b/tests/snapshots/integration__integration_tests__list__multiple_worktrees.snap
@@ -15,16 +15,16 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpQreEDm/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpRuQwij/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-feature-a ≡ ./feature-a b834638e 10 months ago Initial commit
-feature-b ≡ ./feature-b b834638e 10 months ago Initial commit
-
-⚪ Showing 3 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature-a ≡ ./feature-a b834638e 10 months ago Initial commit
+feature-b ≡ ./feature-b b834638e 10 months ago Initial commit
+
+⚪ Showing 3 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__no_progressive_flag.snap b/tests/snapshots/integration__integration_tests__list__no_progressive_flag.snap
new file mode 100644
index 000000000..df79ec6e2
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__no_progressive_flag.snap
@@ -0,0 +1,30 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--no-progressive"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpkoxAU8/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature ≡ ./feature b834638e 10 months ago Initial commit
+
+⚪ Showing 2 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__progressive_flag.snap b/tests/snapshots/integration__integration_tests__list__progressive_flag.snap
new file mode 100644
index 000000000..3ca809a7a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__progressive_flag.snap
@@ -0,0 +1,31 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--progressive"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpppdMPk/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature-a ≡ ./feature-a b834638e 10 months ago Initial commit
+feature-b ≡ ./feature-b b834638e 10 months ago Initial commit
+
+⚪ Showing 3 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__progressive_with_branches.snap b/tests/snapshots/integration__integration_tests__list__progressive_with_branches.snap
new file mode 100644
index 000000000..cfea607e4
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__progressive_with_branches.snap
@@ -0,0 +1,33 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--progressive"
+ - "--branches"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpUBQhWn/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature-a ≡ ./feature-a b834638e 10 months ago Initial commit
+orphan-1 b834638e 10 months ago Initial commit
+orphan-2 b834638e 10 months ago Initial commit
+
+⚪ Showing 2 worktrees, 2 branches
diff --git a/tests/snapshots/integration__integration_tests__list__readme_example_simple_list.snap b/tests/snapshots/integration__integration_tests__list__readme_example_simple_list.snap
index aa6644650..759edfd19 100644
--- a/tests/snapshots/integration__integration_tests__list__readme_example_simple_list.snap
+++ b/tests/snapshots/integration__integration_tests__list__readme_example_simple_list.snap
@@ -15,16 +15,16 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpwFDA4j/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpdSy0BG/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo ↑0 ↓0 b834638e 10 months ago Initial commit
-bugfix-y ↑ ↑1 ./bugfix-y 412a27c8 10 months ago Fix bug
-feature-x +↑ +5 ↑3 ./feature-x 7fd821aa 10 months ago Add file 3
-
-⚪ Showing 3 worktrees, 1 with changes, 2 ahead
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo ↑0 ↓0 b834638e 10 months ago Initial commit
+bugfix-y ↑ ↑1 ./bugfix-y 412a27c8 10 months ago Fix bug
+feature-x + ↑ +5 ↑3 ./feature-x 7fd821aa 10 months ago Add file 3
+
+⚪ Showing 3 worktrees, 1 with changes, 2 ahead
diff --git a/tests/snapshots/integration__integration_tests__list__single_worktree.snap b/tests/snapshots/integration__integration_tests__list__single_worktree.snap
index 8eeb4aec3..eac1e422c 100644
--- a/tests/snapshots/integration__integration_tests__list__single_worktree.snap
+++ b/tests/snapshots/integration__integration_tests__list__single_worktree.snap
@@ -15,14 +15,14 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpzPiroO/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpNWJi8U/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main . b834638e 10 months ago Initial commit
-
-⚪ Showing 1 worktree
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main . b834638e 10 months ago Initial commit
+
+⚪ Showing 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__list__status_column_padding_emoji.snap b/tests/snapshots/integration__integration_tests__list__status_column_padding_emoji.snap
new file mode 100644
index 000000000..498f565ff
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__status_column_padding_emoji.snap
@@ -0,0 +1,31 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpUZxZvW/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+main-symbol ↑ 💬 ↑1 ./main-symbol 579fcd0b 10 months ago Symbol commit
+pr-link ↑ 🤖 ↑1 ./pr-link e17e7d2d 10 months ago PR commit
+wli-sequence ?! ↑ 🤖 +1 -1C ↑1 ./wli-sequence a2483ffd 10 months ago Initial content
+
+⚪ Showing 4 worktrees, 1 with changes, 3 ahead
diff --git a/tests/snapshots/integration__integration_tests__list__task_dag_detached_head.snap b/tests/snapshots/integration__integration_tests__list__task_dag_detached_head.snap
new file mode 100644
index 000000000..5033d9eac
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__task_dag_detached_head.snap
@@ -0,0 +1,29 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--progressive"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpZsevTF/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+(detached) . b834638e 10 months ago Initial commit
+
+⚪ Showing 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__list__task_dag_full_with_diffs.snap b/tests/snapshots/integration__integration_tests__list__task_dag_full_with_diffs.snap
new file mode 100644
index 000000000..97e917154
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__task_dag_full_with_diffs.snap
@@ -0,0 +1,32 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--progressive"
+ - "--full"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpzOZNrE/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ main…± Path Remote⇅ CI Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature-a ? ≡ ./feature-a b834638e 10 months ago Initial commit
+feature-b ↑ ↑1 +1 -1 ./feature-b 2d37ca75 10 months ago Test commit
+
+⚪ Showing 3 worktrees, 1 ahead
diff --git a/tests/snapshots/integration__integration_tests__list__task_dag_many_worktrees.snap b/tests/snapshots/integration__integration_tests__list__task_dag_many_worktrees.snap
new file mode 100644
index 000000000..7f33fa5a8
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__task_dag_many_worktrees.snap
@@ -0,0 +1,39 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--progressive"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpRpBog2/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature-1 ≡ ./feature-1 b834638e 10 months ago Initial commit
+feature-10 ≡ ./feature-10 b834638e 10 months ago Initial commit
+feature-2 ≡ ./feature-2 b834638e 10 months ago Initial commit
+feature-3 ≡ ./feature-3 b834638e 10 months ago Initial commit
+feature-4 ≡ ./feature-4 b834638e 10 months ago Initial commit
+feature-5 ≡ ./feature-5 b834638e 10 months ago Initial commit
+feature-6 ≡ ./feature-6 b834638e 10 months ago Initial commit
+feature-7 ≡ ./feature-7 b834638e 10 months ago Initial commit
+feature-8 ≡ ./feature-8 b834638e 10 months ago Initial commit
+feature-9 ≡ ./feature-9 b834638e 10 months ago Initial commit
+
+⚪ Showing 11 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__task_dag_multiple_worktrees.snap b/tests/snapshots/integration__integration_tests__list__task_dag_multiple_worktrees.snap
new file mode 100644
index 000000000..aae0a3f6a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__task_dag_multiple_worktrees.snap
@@ -0,0 +1,32 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--progressive"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpO098of/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature-a ≡ ./feature-a b834638e 10 months ago Initial commit
+feature-b ≡ ./feature-b b834638e 10 months ago Initial commit
+feature-c ≡ ./feature-c b834638e 10 months ago Initial commit
+
+⚪ Showing 4 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__task_dag_ordering_stability.snap b/tests/snapshots/integration__integration_tests__list__task_dag_ordering_stability.snap
new file mode 100644
index 000000000..c3495ad79
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__task_dag_ordering_stability.snap
@@ -0,0 +1,33 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--progressive"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp9UJhm0/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo 6c3da842 10 months ago Initial commit on main
+feature-current ↑ ↑1 ./feature-current fc28a4d1 9 months ago Commit at 01:00
+feature-newest ↑ ↑1 ./feature-newest 136358eb 9 months ago Commit at 03:00
+feature-middle ↑ ↑1 ./feature-middle a0a4851a 9 months ago Commit at 02:00
+feature-oldest ↑ ↑1 ./feature-oldest 1b1a2d78 9 months ago Commit at 00:30
+
+⚪ Showing 5 worktrees, 4 ahead
diff --git a/tests/snapshots/integration__integration_tests__list__task_dag_single_worktree.snap b/tests/snapshots/integration__integration_tests__list__task_dag_single_worktree.snap
new file mode 100644
index 000000000..7e8f285b1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__task_dag_single_worktree.snap
@@ -0,0 +1,29 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--progressive"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpvvVWdN/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main . b834638e 10 months ago Initial commit
+
+⚪ Showing 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__list__task_dag_with_locked.snap b/tests/snapshots/integration__integration_tests__list__task_dag_with_locked.snap
new file mode 100644
index 000000000..cfbf2c906
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__task_dag_with_locked.snap
@@ -0,0 +1,31 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--progressive"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpTOeXJS/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+locked ≡ ⊠ ./locked b834638e 10 months ago Initial commit
+normal ≡ ./normal b834638e 10 months ago Initial commit
+
+⚪ Showing 3 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__task_dag_with_upstream.snap b/tests/snapshots/integration__integration_tests__list__task_dag_with_upstream.snap
new file mode 100644
index 000000000..e8da87fc2
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__task_dag_with_upstream.snap
@@ -0,0 +1,32 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--progressive"
+ - "--full"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp32fLDs/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+Branch Status HEAD± main↕ main…± Path Remote⇅ CI Commit Age Message
+main ./test-repo ↑0 ↓0 6c3da842 10 months ago Initial commit on main
+ahead ↑⇡ ↑1 +1 ./ahead ↑1 ↓0 2fff52c2 10 months ago Ahead commit
+in-sync ≡ ./in-sync ↑0 ↓0 6c3da842 10 months ago Initial commit on main
+
+⚪ Showing 3 worktrees, 1 ahead
diff --git a/tests/snapshots/integration__integration_tests__list__unicode_commit_message.snap b/tests/snapshots/integration__integration_tests__list__unicode_commit_message.snap
index 9c532076f..8411c2ad8 100644
--- a/tests/snapshots/integration__integration_tests__list__unicode_commit_message.snap
+++ b/tests/snapshots/integration__integration_tests__list__unicode_commit_message.snap
@@ -15,15 +15,15 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpJxwHmB/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpo4U5B1/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo e4614cb7 10 months ago Fix bug with café ☕ handling
-feature-test ↓∅ ↓1 ./feature-test 0c53695b 10 months ago Add support for 日本語 and émoji 🎉
-
-⚪ Showing 2 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo e4614cb7 10 months ago Fix bug with café ☕ handling
+feature-test ∅ ↓ ↓1 ./feature-test 0c53695b 10 months ago Add support for 日本語 and émoji 🎉
+
+⚪ Showing 2 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__user_status_special_chars.snap b/tests/snapshots/integration__integration_tests__list__user_status_special_chars.snap
index ff87932ad..7744f66f3 100644
--- a/tests/snapshots/integration__integration_tests__list__user_status_special_chars.snap
+++ b/tests/snapshots/integration__integration_tests__list__user_status_special_chars.snap
@@ -15,16 +15,16 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpXzaYQA/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpiEICGD/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-emoji ≡🔄 ./emoji b834638e 10 months ago Initial commit
-multi ≡👨‍💻 ./multi b834638e 10 months ago Initial commit
-
-⚪ Showing 3 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+emoji ≡ 🔄 ./emoji b834638e 10 months ago Initial commit
+multi ≡ 👨‍💻 ./multi b834638e 10 months ago Initial commit
+
+⚪ Showing 3 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__with_branches_flag.snap b/tests/snapshots/integration__integration_tests__list__with_branches_flag.snap
index fa68db35d..e7ee12bed 100644
--- a/tests/snapshots/integration__integration_tests__list__with_branches_flag.snap
+++ b/tests/snapshots/integration__integration_tests__list__with_branches_flag.snap
@@ -16,18 +16,18 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpA2nHxV/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp3UagGO/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-feature-with-worktree ≡ ./feature-with-worktree b834638e 10 months ago Initial commit
-another-branch b834638e 10 months ago Initial commit
-feature-without-worktree b834638e 10 months ago Initial commit
-fix-bug b834638e 10 months ago Initial commit
-
-⚪ Showing 2 worktrees, 3 branches
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature-with-worktree ≡ ./feature-with-worktree b834638e 10 months ago Initial commit
+another-branch b834638e 10 months ago Initial commit
+feature-without-worktree b834638e 10 months ago Initial commit
+fix-bug b834638e 10 months ago Initial commit
+
+⚪ Showing 2 worktrees, 3 branches
diff --git a/tests/snapshots/integration__integration_tests__list__with_branches_flag_none_available.snap b/tests/snapshots/integration__integration_tests__list__with_branches_flag_none_available.snap
index c127c54dc..f6709eac2 100644
--- a/tests/snapshots/integration__integration_tests__list__with_branches_flag_none_available.snap
+++ b/tests/snapshots/integration__integration_tests__list__with_branches_flag_none_available.snap
@@ -16,16 +16,16 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpHDByIR/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpDA5dTV/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-feature-a ≡ ./feature-a b834638e 10 months ago Initial commit
-feature-b ≡ ./feature-b b834638e 10 months ago Initial commit
-
-⚪ Showing 3 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature-a ≡ ./feature-a b834638e 10 months ago Initial commit
+feature-b ≡ ./feature-b b834638e 10 months ago Initial commit
+
+⚪ Showing 3 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__with_branches_flag_only_branches.snap b/tests/snapshots/integration__integration_tests__list__with_branches_flag_only_branches.snap
index c6b46b9f2..e8a24937f 100644
--- a/tests/snapshots/integration__integration_tests__list__with_branches_flag_only_branches.snap
+++ b/tests/snapshots/integration__integration_tests__list__with_branches_flag_only_branches.snap
@@ -16,17 +16,17 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpzSxhN9/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpzMqAND/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main . b834638e 10 months ago Initial commit
-branch-alpha b834638e 10 months ago Initial commit
-branch-beta b834638e 10 months ago Initial commit
-branch-gamma b834638e 10 months ago Initial commit
-
-⚪ Showing 1 worktrees, 3 branches
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main . b834638e 10 months ago Initial commit
+branch-alpha b834638e 10 months ago Initial commit
+branch-beta b834638e 10 months ago Initial commit
+branch-gamma b834638e 10 months ago Initial commit
+
+⚪ Showing 1 worktrees, 3 branches
diff --git a/tests/snapshots/integration__integration_tests__list__with_upstream_tracking.snap b/tests/snapshots/integration__integration_tests__list__with_upstream_tracking.snap
index 50225d912..b88a06014 100644
--- a/tests/snapshots/integration__integration_tests__list__with_upstream_tracking.snap
+++ b/tests/snapshots/integration__integration_tests__list__with_upstream_tracking.snap
@@ -16,21 +16,21 @@ info:
GIT_EDITOR: ""
LANG: C
LC_ALL: C
- PATH: "/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpUb65WQ/mock-bin:/Users/maximilian/.cargo/bin:/Users/maximilian/.local/bin:/Users/maximilian/.bun/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
+ PATH: "/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpxKTdFT/mock-bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpUb65WQ/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpxKTdFT/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ main…± Path Remote⇅ CI Commit Age Message
-main ./test-repo ↑0 ↓0 6c3da842 10 months ago Initial commit on main
-ahead ↑⇡ ↑2 +2 ./ahead ↑2 ↓0 8d8f4673 10 months ago Ahead commit 2
-behind ⇣≡ ./behind ↑0 ↓1 6c3da842 10 months ago Initial commit on main
-diverged ↑⇅ ↑1 +1 ./diverged ↑1 ↓1 ca7cb696 10 months ago Diverged local commit
-in-sync ≡ ./in-sync ↑0 ↓0 6c3da842 10 months ago Initial commit on main
-no-upstream ≡ ./no-upstream 6c3da842 10 months ago Initial commit on main
-
-⚪ Showing 6 worktrees, 2 ahead
----- stderr -----
+Branch Status HEAD± main↕ main…± Path Remote⇅ CI Commit Age Message
+main ./test-repo ↑0 ↓0 6c3da842 10 months ago Initial commit on main
+ahead ↑⇡ ↑2 +2 ./ahead ↑2 ↓0 8d8f4673 10 months ago Ahead commit 2
+behind ≡ ⇣ ./behind ↑0 ↓1 6c3da842 10 months ago Initial commit on main
+diverged ↑⇅ ↑1 +1 ./diverged ↑1 ↓1 ca7cb696 10 months ago Diverged local commit
+in-sync ≡ ./in-sync ↑0 ↓0 6c3da842 10 months ago Initial commit on main
+no-upstream ≡ ./no-upstream 6c3da842 10 months ago Initial commit on main
+
+⚪ Showing 6 worktrees, 2 ahead
diff --git a/tests/snapshots/integration__integration_tests__list__with_user_status.snap b/tests/snapshots/integration__integration_tests__list__with_user_status.snap
index 2bc91a4f7..0a916dc38 100644
--- a/tests/snapshots/integration__integration_tests__list__with_user_status.snap
+++ b/tests/snapshots/integration__integration_tests__list__with_user_status.snap
@@ -15,18 +15,18 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpWE5JFJ/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpEr7pC5/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-clean-no-status ≡ ./clean-no-status b834638e 10 months ago Initial commit
-clean-with-status ≡💬 ./clean-with-status b834638e 10 months ago Initial commit
-dirty-no-status ! +1 -1 ./dirty-no-status b834638e 10 months ago Initial commit
-dirty-with-status ?≡🤖 ./dirty-with-status b834638e 10 months ago Initial commit
-
-⚪ Showing 5 worktrees, 1 with changes
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+clean-no-status ≡ ./clean-no-status b834638e 10 months ago Initial commit
+clean-with-status ≡ 💬 ./clean-with-status b834638e 10 months ago Initial commit
+dirty-no-status ! +1 -1 ./dirty-no-status b834638e 10 months ago Initial commit
+dirty-with-status ? ≡ 🤖 ./dirty-with-status b834638e 10 months ago Initial commit
+
+⚪ Showing 5 worktrees, 1 with changes
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_background.snap b/tests/snapshots/integration__integration_tests__list_column_alignment__status_column_alignment_check.snap
similarity index 55%
rename from tests/snapshots/integration__integration_tests__remove__remove_background.snap
rename to tests/snapshots/integration__integration_tests__list_column_alignment__status_column_alignment_check.snap
index eb844677b..27c5214a2 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_background.snap
+++ b/tests/snapshots/integration__integration_tests__list_column_alignment__status_column_alignment_check.snap
@@ -1,11 +1,10 @@
---
-source: tests/integration_tests/remove.rs
+source: tests/integration_tests/list_column_alignment.rs
info:
program: wt
args:
- - remove
- - "--background"
- - feature-bg
+ - beta
+ - list
env:
CLICOLOR_FORCE: "1"
COLUMNS: "150"
@@ -17,11 +16,15 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpWK1Gf3/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmputwz5p/test-config.toml
---
-success: true
-exit_code: 0
+success: false
+exit_code: 2
----- stdout -----
-🔄 Removing feature-bg in background
----- stderr -----
+error: unrecognized subcommand 'list'
+
+Usage: wt beta [OPTIONS] <COMMAND>
+
+For more information, try '--help'.
diff --git a/tests/snapshots/integration__integration_tests__list_column_alignment__status_column_width_consistency.snap b/tests/snapshots/integration__integration_tests__list_column_alignment__status_column_width_consistency.snap
new file mode 100644
index 000000000..1e870cf54
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list_column_alignment__status_column_width_consistency.snap
@@ -0,0 +1,30 @@
+---
+source: tests/integration_tests/list_column_alignment.rs
+info:
+ program: wt
+ args:
+ - beta
+ - list
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp9FT0wK/test-config.toml
+---
+success: false
+exit_code: 2
+----- stdout -----
+
+----- stderr -----
+error: unrecognized subcommand 'list'
+
+Usage: wt beta [OPTIONS] <COMMAND>
+
+For more information, try '--help'.
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_already_on_default.snap b/tests/snapshots/integration__integration_tests__remove__remove_already_on_default.snap
index 8b7ea87b1..6bd0a1908 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_already_on_default.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_already_on_default.snap
@@ -15,13 +15,11 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpANO5Mz/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpgHDWzN/test-config.toml
---
-success: false
-exit_code: 1
+success: true
+exit_code: 0
----- stdout -----
-❌ Cannot remove main worktree
-
-💡 Use 'wt remove' from a secondary worktree, or 'wt switch' to change branches
+🔄 Removing main & branch in background
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_switch_to_default.snap b/tests/snapshots/integration__integration_tests__remove__remove_switch_to_default.snap
index 48ba8285f..82af0ac9c 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_switch_to_default.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_switch_to_default.snap
@@ -15,13 +15,11 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpaRDNUu/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpVkRmfM/test-config.toml
---
-success: false
-exit_code: 1
+success: true
+exit_code: 0
----- stdout -----
-❌ Cannot remove main worktree
-
-💡 Use 'wt remove' from a secondary worktree, or 'wt switch' to change branches
+🔄 Removing feature & branch in background
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__security__commit_message_with_directive_not_executed.snap b/tests/snapshots/integration__integration_tests__security__commit_message_with_directive_not_executed.snap
index 14d1fe1c8..41e7e110d 100644
--- a/tests/snapshots/integration__integration_tests__security__commit_message_with_directive_not_executed.snap
+++ b/tests/snapshots/integration__integration_tests__security__commit_message_with_directive_not_executed.snap
@@ -15,15 +15,15 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpxpTfkt/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmppuhJG1/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo [SHA] 10 months ago Fix bug __WORKTRUNK_EXEC__echo PWNED > /tmp/hacked4
-feature ≡ ./feature [SHA] 10 months ago Fix bug __WORKTRUNK_EXEC__echo PWNED > /tmp/hacked4
-
-⚪ Showing 2 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo [SHA] 10 months ago Fix bug __WORKTRUNK_EXEC__echo PWNED > /tmp/hacked4
+feature ≡ ./feature [SHA] 10 months ago Fix bug __WORKTRUNK_EXEC__echo PWNED > /tmp/hacked4
+
+⚪ Showing 2 worktrees
diff --git a/tests/snapshots/integration__integration_tests__security__path_with_directive_not_executed.snap b/tests/snapshots/integration__integration_tests__security__path_with_directive_not_executed.snap
index 7e6f311a3..8040aa9a2 100644
--- a/tests/snapshots/integration__integration_tests__security__path_with_directive_not_executed.snap
+++ b/tests/snapshots/integration__integration_tests__security__path_with_directive_not_executed.snap
@@ -15,14 +15,14 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpxjrHGj/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpNeyRrV/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main . b834638e 10 months ago Initial commit
-
-⚪ Showing 1 worktree
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main . b834638e 10 months ago Initial commit
+
+⚪ Showing 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_empty_diffs.snap b/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_empty_diffs.snap
index 06dad69f1..eedc18714 100644
--- a/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_empty_diffs.snap
+++ b/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_empty_diffs.snap
@@ -15,17 +15,17 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp1uRldo/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp4lD4Wr/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-also-no-changes ≡ ./also-no-changes b834638e 10 months ago Initial commit
-no-changes ≡ ./no-changes b834638e 10 months ago Initial commit
-with-changes ! +1 -1 ./with-changes b834638e 10 months ago Initial commit
-
-⚪ Showing 4 worktrees, 1 with changes
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+also-no-changes ≡ ./also-no-changes b834638e 10 months ago Initial commit
+no-changes ≡ ./no-changes b834638e 10 months ago Initial commit
+with-changes ! +1 -1 ./with-changes b834638e 10 months ago Initial commit
+
+⚪ Showing 4 worktrees, 1 with changes
diff --git a/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_extreme_diffs.snap b/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_extreme_diffs.snap
index 0675b71bd..d972eb3a4 100644
--- a/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_extreme_diffs.snap
+++ b/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_extreme_diffs.snap
@@ -15,16 +15,16 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpS1kIx7/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpJaIb7d/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-huge ?≡ ./huge b834638e 10 months ago Initial commit
-tiny ! +1 -1 ./tiny b834638e 10 months ago Initial commit
-
-⚪ Showing 3 worktrees, 1 with changes
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+huge ? ≡ ./huge b834638e 10 months ago Initial commit
+tiny ! +1 -1 ./tiny b834638e 10 months ago Initial commit
+
+⚪ Showing 3 worktrees, 1 with changes
diff --git a/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_varying_diffs.snap b/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_varying_diffs.snap
index 93f18960d..be4df64cc 100644
--- a/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_varying_diffs.snap
+++ b/tests/snapshots/integration__integration_tests__spacing_edge_cases__alignment_varying_diffs.snap
@@ -15,17 +15,17 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp6Vlapm/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp5X5cWc/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-feature-large ?≡ ./feature-large b834638e 10 months ago Initial commit
-feature-medium ?≡ ./feature-medium b834638e 10 months ago Initial commit
-feature-small ?≡ ./feature-small b834638e 10 months ago Initial commit
-
-⚪ Showing 4 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+feature-large ? ≡ ./feature-large b834638e 10 months ago Initial commit
+feature-medium ? ≡ ./feature-medium b834638e 10 months ago Initial commit
+feature-small ? ≡ ./feature-small b834638e 10 months ago Initial commit
+
+⚪ Showing 4 worktrees
diff --git a/tests/snapshots/integration__integration_tests__spacing_edge_cases__long_branch_names.snap b/tests/snapshots/integration__integration_tests__spacing_edge_cases__long_branch_names.snap
index 52dee9bf2..3a49bd593 100644
--- a/tests/snapshots/integration__integration_tests__spacing_edge_cases__long_branch_names.snap
+++ b/tests/snapshots/integration__integration_tests__spacing_edge_cases__long_branch_names.snap
@@ -15,17 +15,17 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpCpEYl4/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpWxqH5k/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-another-extremely-long-name-here ≡ ./another-extremely-long-name-here b834638e 10 months ago Initial commit
-short ≡ ./short b834638e 10 months ago Initial commit
-very-long-feature-branch-name ≡ ./very-long-feature-branch-name b834638e 10 months ago Initial commit
-
-⚪ Showing 4 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+another-extremely-long-name-here ≡ ./another-extremely-long-name-here b834638e 10 months ago Initial commit
+short ≡ ./short b834638e 10 months ago Initial commit
+very-long-feature-branch-name ≡ ./very-long-feature-branch-name b834638e 10 months ago Initial commit
+
+⚪ Showing 4 worktrees
diff --git a/tests/snapshots/integration__integration_tests__spacing_edge_cases__mixed_length_branch_names.snap b/tests/snapshots/integration__integration_tests__spacing_edge_cases__mixed_length_branch_names.snap
index fbada3f01..f443094dd 100644
--- a/tests/snapshots/integration__integration_tests__spacing_edge_cases__mixed_length_branch_names.snap
+++ b/tests/snapshots/integration__integration_tests__spacing_edge_cases__mixed_length_branch_names.snap
@@ -15,17 +15,17 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpOOtT28/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpbmenD6/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-long ≡ ./extremely-long-branch-name-that-might-cause-layout-issues b834638e 10 months ago Initial commit
-medium ≡ ./medium-length-name b834638e 10 months ago Initial commit
-x ≡ ./x b834638e 10 months ago Initial commit
-
-⚪ Showing 4 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+long ≡ ./extremely-long-branch-name-that-might-cause-layout-issues b834638e 10 months ago Initial commit
+medium ≡ ./medium-length-name b834638e 10 months ago Initial commit
+x ≡ ./x b834638e 10 months ago Initial commit
+
+⚪ Showing 4 worktrees
diff --git a/tests/snapshots/integration__integration_tests__spacing_edge_cases__short_branch_names.snap b/tests/snapshots/integration__integration_tests__spacing_edge_cases__short_branch_names.snap
index 1da2fe775..1acf1413e 100644
--- a/tests/snapshots/integration__integration_tests__spacing_edge_cases__short_branch_names.snap
+++ b/tests/snapshots/integration__integration_tests__spacing_edge_cases__short_branch_names.snap
@@ -15,17 +15,17 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp6DiobG/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpekKic5/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-a ≡ ./a b834638e 10 months ago Initial commit
-bb ≡ ./bb b834638e 10 months ago Initial commit
-ccc ≡ ./ccc b834638e 10 months ago Initial commit
-
-⚪ Showing 4 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+a ≡ ./a b834638e 10 months ago Initial commit
+bb ≡ ./bb b834638e 10 months ago Initial commit
+ccc ≡ ./ccc b834638e 10 months ago Initial commit
+
+⚪ Showing 4 worktrees
diff --git a/tests/snapshots/integration__integration_tests__spacing_edge_cases__unicode_branch_names.snap b/tests/snapshots/integration__integration_tests__spacing_edge_cases__unicode_branch_names.snap
index a9dbc80e7..8bf1d6f0f 100644
--- a/tests/snapshots/integration__integration_tests__spacing_edge_cases__unicode_branch_names.snap
+++ b/tests/snapshots/integration__integration_tests__spacing_edge_cases__unicode_branch_names.snap
@@ -15,17 +15,17 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpMIPLBV/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpycdgnL/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-main ./test-repo b834638e 10 months ago Initial commit
-cafe ≡ ./café b834638e 10 months ago Initial commit
-naive ≡ ./naïve b834638e 10 months ago Initial commit
-resume ≡ ./résumé b834638e 10 months ago Initial commit
-
-⚪ Showing 4 worktrees
----- stderr -----
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+main ./test-repo b834638e 10 months ago Initial commit
+cafe ≡ ./café b834638e 10 months ago Initial commit
+naive ≡ ./naïve b834638e 10 months ago Initial commit
+resume ≡ ./résumé b834638e 10 months ago Initial commit
+
+⚪ Showing 4 worktrees