Skip to content

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

feat: Enhance `wt beta statusline` with new flags and improved formatting

Maximilian Roosddae3b9e1a89
diff --git a/.typos.toml b/.typos.toml
index 4c3dac8be..f3ebf1951 100644
--- a/.typos.toml
+++ b/.typos.toml
@@ -1,3 +1,5 @@
[default.extend-words]
# Git commit hashes that typos flags as potential typos
ba = "ba" # Part of commit hashes like e28e0ba
+# ANSI escape codes in snapshots make is_main/is_current/is_previous look like "mis"
+mis = "mis"
diff --git a/README.md b/README.md
index 901ef3093..d1019fcce 100644
--- a/README.md
+++ b/README.md
@@ -758,6 +758,12 @@ with the same fields in the same order as Status Symbols above:
Note: `locked` and `prunable` are top-level fields on worktree objects, not in status.
+**Worktree position fields** (for identifying special worktrees):
+
+- `is_main`: boolean - is the main/default worktree
+- `is_current`: boolean - is the current working directory (present when true)
+- `is_previous`: boolean - is the previous worktree from `wt switch` (present when true)
+
**Query examples:**
```console
@@ -775,6 +781,9 @@ jq '.[] | select(.status.main_divergence == "Ahead")'
# Find locked worktrees
jq '.[] | select(.locked != null)'
+
+# Get current worktree info (useful for statusline tools)
+jq '.[] | select(.is_current == true)'
```
<!-- README:end -->
diff --git a/src/cli.rs b/src/cli.rs
index 5e60f330b..2ef224a3d 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -507,6 +507,21 @@ pub enum BetaCommand {
/// Note: When viewing main itself, all commits shown without dimming
#[cfg(unix)]
Select,
+
+ /// Single-line status for shell prompts
+ ///
+ /// Format: `branch status ±working commits upstream ci`
+ ///
+ /// Designed for shell prompts, starship, or editor integrations.
+ /// Uses same collection infrastructure as `wt list`.
+ Statusline {
+ /// Claude Code mode: read context from stdin, add directory and model
+ ///
+ /// Reads JSON from stdin with `.workspace.current_dir` and `.model.display_name`.
+ /// Output: `dir branch status ±working commits upstream ci | model`
+ #[arg(long)]
+ claude_code: bool,
+ },
}
#[derive(Subcommand)]
@@ -665,6 +680,12 @@ with the same fields in the same order as Status Symbols above:
Note: `locked` and `prunable` are top-level fields on worktree objects, not in status.
+**Worktree position fields** (for identifying special worktrees):
+
+- `is_main`: boolean - is the main/default worktree
+- `is_current`: boolean - is the current working directory (present when true)
+- `is_previous`: boolean - is the previous worktree from `wt switch` (present when true)
+
**Query examples:**
```console
@@ -682,6 +703,9 @@ jq '.[] | select(.status.main_divergence == \"Ahead\")'
# Find locked worktrees
jq '.[] | select(.locked != null)'
+
+# Get current worktree info (useful for statusline tools)
+jq '.[] | select(.is_current == true)'
```")]
List {
/// Output format (table, json)
diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rs
index afab7b0db..0b242610e 100644
--- a/src/commands/list/ci_status.rs
+++ b/src/commands/list/ci_status.rs
@@ -167,7 +167,53 @@ pub struct PrStatus {
pub url: Option<String>,
}
+impl CiStatus {
+ /// Get the ANSI color for this CI status.
+ ///
+ /// - Passed: Green
+ /// - Running: Blue
+ /// - Failed: Red
+ /// - Conflicts: Yellow
+ /// - NoCI: BrightBlack (dimmed)
+ pub fn color(&self) -> anstyle::AnsiColor {
+ use anstyle::AnsiColor;
+ match self {
+ Self::Passed => AnsiColor::Green,
+ Self::Running => AnsiColor::Blue,
+ Self::Failed => AnsiColor::Red,
+ Self::Conflicts => AnsiColor::Yellow,
+ Self::NoCI => AnsiColor::BrightBlack,
+ }
+ }
+}
+
+impl CiSource {
+ /// Get the indicator symbol for this CI source
+ pub fn indicator(&self) -> &'static str {
+ match self {
+ Self::PullRequest => "●",
+ Self::Branch => "○",
+ }
+ }
+}
+
impl PrStatus {
+ /// Get the style for this PR status (color + optional dimming for stale)
+ pub fn style(&self) -> anstyle::Style {
+ use anstyle::{Color, Style};
+ let style = Style::new().fg_color(Some(Color::Ansi(self.ci_status.color())));
+ if self.is_stale { style.dimmed() } else { style }
+ }
+
+ /// Format CI status as a colored indicator for statusline output.
+ ///
+ /// Returns a string like "●" with appropriate ANSI color.
+ pub fn format_indicator(&self) -> String {
+ let style = self.style();
+ let indicator = self.source.indicator();
+ format!("{style}{indicator}{style:#}")
+ }
+
/// Detect CI status for a branch using gh/glab CLI
/// First tries to find PR/MR status, then falls back to workflow/pipeline runs
/// Returns None if no CI found or CLI tools unavailable
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index d0c520846..681cbf773 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -493,20 +493,31 @@ pub fn collect(
// Initialize worktree items with identity fields and None for computed fields
let mut all_items: Vec<ListItem> = sorted_worktrees
.iter()
- .map(|wt| ListItem {
- head: wt.head.clone(),
- branch: wt.branch.clone(),
- commit: None,
- counts: None,
- branch_diff: None,
- upstream: None,
- pr_status: None,
- status_symbols: None,
- display: DisplayFields::default(),
- kind: ItemKind::Worktree(Box::new(WorktreeData::from_worktree(
- wt,
- wt.path == main_worktree.path,
- ))),
+ .map(|wt| {
+ let is_main = wt.path == main_worktree.path;
+ let is_current = current_worktree_path
+ .as_ref()
+ .is_some_and(|cp| &wt.path == cp);
+ let is_previous = previous_branch
+ .as_deref()
+ .is_some_and(|prev| wt.branch.as_deref() == Some(prev));
+ ListItem {
+ head: wt.head.clone(),
+ branch: wt.branch.clone(),
+ commit: None,
+ counts: None,
+ branch_diff: None,
+ upstream: None,
+ pr_status: None,
+ status_symbols: None,
+ display: DisplayFields::default(),
+ kind: ItemKind::Worktree(Box::new(WorktreeData::from_worktree(
+ wt,
+ is_main,
+ is_current,
+ is_previous,
+ ))),
+ }
})
.collect();
@@ -571,21 +582,11 @@ pub fn collect(
.iter()
.map(|item| {
if item.worktree_data().is_some() {
- let is_current = item
- .worktree_path()
- .and_then(|p| current_worktree_path.as_ref().map(|cp| p == cp))
- .unwrap_or(false);
- let is_previous = previous_branch
- .as_deref()
- .map(|prev| item.branch.as_deref() == Some(prev))
- .unwrap_or(false);
- layout.format_skeleton_row(item, is_current, is_previous)
+ // Worktrees get skeleton rows (format_skeleton_row extracts is_current/is_previous internally)
+ layout.format_skeleton_row(item)
} else {
- layout.format_list_item_line(
- item,
- current_worktree_path.as_ref(),
- previous_branch.as_deref(),
- )
+ // Branches render immediately (no skeleton needed)
+ layout.format_list_item_line(item, previous_branch.as_deref())
}
})
.collect();
@@ -720,11 +721,7 @@ pub fn collect(
}
// Re-render the row with caching (now includes status if computed)
- let rendered = layout.format_list_item_line(
- item,
- current_worktree_path.as_ref(),
- previous_branch.as_deref(),
- );
+ let rendered = layout.format_list_item_line(item, previous_branch.as_deref());
// Compare using full line so changes beyond the clamp (e.g., CI) still refresh.
if rendered != last_rendered_lines[item_idx] {
@@ -748,11 +745,7 @@ pub fn collect(
if table.is_tty() {
// Interactive: do final render pass and update footer to summary
for (item_idx, item) in all_items.iter().enumerate() {
- let rendered = layout.format_list_item_line(
- item,
- current_worktree_path.as_ref(),
- previous_branch.as_deref(),
- );
+ let rendered = layout.format_list_item_line(item, previous_branch.as_deref());
if let Err(e) = table.update_row(item_idx, rendered) {
log::debug!("Final row update failed: {}", e);
}
@@ -763,11 +756,7 @@ pub fn collect(
let mut final_lines = Vec::new();
final_lines.push(layout.format_header_line());
for item in &all_items {
- final_lines.push(layout.format_list_item_line(
- item,
- current_worktree_path.as_ref(),
- previous_branch.as_deref(),
- ));
+ final_lines.push(layout.format_list_item_line(item, previous_branch.as_deref()));
}
final_lines.push(String::new()); // Spacer
final_lines.push(final_msg);
@@ -783,11 +772,9 @@ pub fn collect(
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(),
- previous_branch.as_deref(),
- ))?;
+ crate::output::raw_terminal(
+ layout.format_list_item_line(item, previous_branch.as_deref()),
+ )?;
}
crate::output::raw_terminal("")?;
crate::output::raw_terminal(final_msg)?;
@@ -795,8 +782,8 @@ pub fn collect(
// Status symbols are now computed during data collection (both modes), no fallback needed
- // Compute display fields for all items (used by JSON output)
- // Table rendering uses raw data directly; these fields provide pre-formatted strings for JSON
+ // Compute display fields for all items (used by JSON output and statusline)
+ // Table rendering uses raw data directly; these fields provide pre-formatted strings
for item in &mut all_items {
item.display = super::model::DisplayFields::from_common_fields(
&item.counts,
@@ -804,6 +791,7 @@ pub fn collect(
&item.upstream,
&item.pr_status,
);
+ item.display.status_line = Some(item.format_statusline());
if let super::model::ItemKind::Worktree(ref mut wt_data) = item.kind
&& let Some(ref working_tree_diff) = wt_data.working_tree_diff
@@ -867,3 +855,143 @@ fn sort_worktrees(
indexed.into_iter().map(|(_, wt)| wt).collect()
}
+
+// ============================================================================
+// Public API for single-worktree collection (used by statusline)
+// ============================================================================
+
+pub use super::collect_progressive_impl::CollectOptions;
+
+/// Build a ListItem for a single worktree with identity fields only.
+///
+/// Computed fields (counts, diffs, CI) are left as None. Use `populate_items()`
+/// to fill them in.
+pub fn build_worktree_item(
+ wt: &Worktree,
+ is_main: bool,
+ is_current: bool,
+ is_previous: bool,
+) -> ListItem {
+ ListItem {
+ head: wt.head.clone(),
+ branch: wt.branch.clone(),
+ commit: None,
+ counts: None,
+ branch_diff: None,
+ upstream: None,
+ pr_status: None,
+ status_symbols: None,
+ display: DisplayFields::default(),
+ kind: ItemKind::Worktree(Box::new(WorktreeData::from_worktree(
+ wt,
+ is_main,
+ is_current,
+ is_previous,
+ ))),
+ }
+}
+
+/// Populate computed fields for items in parallel (blocking).
+///
+/// Spawns parallel git operations and collects results. Modifies items in place
+/// with: commit details, ahead/behind, diffs, upstream, CI, etc.
+///
+/// This is the blocking version used by statusline. For progressive rendering
+/// with callbacks, see the `collect()` function.
+pub fn populate_items(
+ items: &mut [ListItem],
+ default_branch: &str,
+ options: CollectOptions,
+) -> anyhow::Result<()> {
+ use std::sync::Arc;
+ use std::sync::atomic::AtomicUsize;
+
+ if items.is_empty() {
+ return Ok(());
+ }
+
+ // Create channel for cell updates
+ let (tx, rx) = chan::unbounded();
+
+ // Counter for cells (not used for progress, but required by spawn functions)
+ let cell_count = Arc::new(AtomicUsize::new(0));
+
+ // Collect worktree info: (index, path, head, branch)
+ let worktree_info: Vec<_> = items
+ .iter()
+ .enumerate()
+ .filter_map(|(idx, item)| {
+ item.worktree_data().map(|data| {
+ (
+ idx,
+ data.path.clone(),
+ item.head.clone(),
+ item.branch.clone(),
+ )
+ })
+ })
+ .collect();
+
+ // Spawn collection in background thread
+ let default_branch_clone = default_branch.to_string();
+ std::thread::spawn(move || {
+ for (idx, path, head, branch) in worktree_info {
+ // Create a minimal Worktree struct for the collection function
+ let wt = Worktree {
+ path,
+ head,
+ branch,
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ };
+ super::collect_progressive_impl::collect_worktree_progressive(
+ &wt,
+ idx,
+ &default_branch_clone,
+ &options,
+ tx.clone(),
+ &cell_count,
+ );
+ }
+ });
+
+ // Drain cell updates (blocking until all complete)
+ drain_cell_updates(rx, items, |_item_idx, item, ctx| {
+ // Compute status symbols as data arrives (same logic as in collect())
+ let item_default_branch = if item.is_main() {
+ None
+ } else {
+ Some(default_branch)
+ };
+ compute_item_status_symbols(
+ item,
+ item_default_branch,
+ ctx.has_merge_tree_conflicts,
+ ctx.user_status.clone(),
+ ctx.working_tree_symbols.as_deref(),
+ ctx.has_conflicts,
+ );
+ });
+
+ // Compute display fields (including status_line for statusline command)
+ for item in items.iter_mut() {
+ item.display = DisplayFields::from_common_fields(
+ &item.counts,
+ &item.branch_diff,
+ &item.upstream,
+ &item.pr_status,
+ );
+ item.display.status_line = Some(item.format_statusline());
+
+ if let ItemKind::Worktree(ref mut wt_data) = item.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);
+ }
+ }
+
+ Ok(())
+}
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index fa60b3ad7..6aff8b07b 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -841,6 +841,8 @@ mod tests {
working_tree_diff_with_main: Some(Some(LineDiff::default())),
worktree_state: None,
is_main: false,
+ is_current: false,
+ is_previous: false,
working_diff_display: None,
})),
};
@@ -924,6 +926,8 @@ mod tests {
working_tree_diff_with_main: Some(Some(LineDiff::default())),
worktree_state: None,
is_main: true, // Primary worktree: no ahead/behind shown
+ is_current: false,
+ is_previous: false,
working_diff_display: None,
})),
};
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index ed4280452..ec4cde512 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -116,7 +116,7 @@
//! - Run `git gc` periodically to consolidate objects into pack files
//! - Minimize uncommitted changes across worktrees (each dirty worktree adds diff overhead)
-mod ci_status;
+pub mod ci_status;
pub(crate) mod collect;
mod collect_progressive_impl;
mod columns;
@@ -134,6 +134,9 @@ use model::{ListData, ListItem};
use progressive::RenderMode;
use worktrunk::git::Repository;
+// Re-export for statusline and other consumers
+pub use collect::{CollectOptions, build_worktree_item, populate_items};
+
pub fn handle_list(
format: crate::OutputFormat,
show_branches: bool,
diff --git a/src/commands/list/model.rs b/src/commands/list/model.rs
index 8ba336ddd..3834fd86e 100644
--- a/src/commands/list/model.rs
+++ b/src/commands/list/model.rs
@@ -18,6 +18,12 @@ pub struct DisplayFields {
pub ci_status_display: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub status_display: Option<String>,
+ /// Pre-formatted single-line representation for statusline tools.
+ /// Format: `branch status ±working commits upstream ci` (2-space separators)
+ ///
+ /// Use via JSON: `wt list --format=json | jq '.[] | select(.is_current) | .status_line'`
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub status_line: Option<String>,
}
impl DisplayFields {
@@ -51,6 +57,7 @@ impl DisplayFields {
upstream_display,
ci_status_display,
status_display: None,
+ status_line: None,
}
}
}
@@ -76,13 +83,24 @@ pub struct WorktreeData {
pub working_tree_diff_with_main: Option<Option<LineDiff>>,
pub worktree_state: Option<String>,
pub is_main: bool,
+ /// Whether this is the current worktree (matches $PWD)
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub is_current: bool,
+ /// Whether this was the previous worktree (from WT_PREVIOUS_BRANCH)
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub is_previous: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub working_diff_display: 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_main: bool) -> Self {
+ pub(crate) fn from_worktree(
+ wt: &worktrunk::git::Worktree,
+ is_main: bool,
+ is_current: bool,
+ is_previous: bool,
+ ) -> Self {
Self {
// Identity fields (known immediately from worktree list)
path: wt.path.clone(),
@@ -91,6 +109,8 @@ impl WorktreeData {
locked: wt.locked.clone(),
prunable: wt.prunable.clone(),
is_main,
+ is_current,
+ is_previous,
// Computed fields start as None (filled progressively)
..Default::default()
@@ -283,6 +303,57 @@ impl ListItem {
counts.ahead == 0
}
}
+
+ /// Format this item as a single-line statusline string.
+ ///
+ /// Format: `branch status ±working commits upstream ci`
+ /// Uses 2-space separators between non-empty parts.
+ pub fn format_statusline(&self) -> String {
+ let mut parts: Vec<String> = Vec::new();
+
+ // 1. Branch name
+ parts.push(self.branch_name().to_string());
+
+ // 2. Status symbols (compact, no grid alignment)
+ if let Some(ref symbols) = self.status_symbols {
+ let status = symbols.format_compact();
+ if !status.is_empty() {
+ parts.push(status);
+ }
+ }
+
+ // 3. Working diff (worktrees only)
+ if let Some(data) = self.worktree_data()
+ && let Some(ref diff) = data.working_tree_diff
+ && !diff.is_empty()
+ && let Some(formatted) =
+ ColumnKind::WorkingDiff.format_diff_plain(diff.added, diff.deleted)
+ {
+ parts.push(format!("±{formatted}"));
+ }
+
+ // 4. Commits ahead/behind main
+ if let Some(formatted) =
+ ColumnKind::AheadBehind.format_diff_plain(self.counts().ahead, self.counts().behind)
+ {
+ parts.push(formatted);
+ }
+
+ // 5. Upstream status
+ if let Some(ref upstream) = self.upstream
+ && let Some((_, ahead, behind)) = upstream.active()
+ && let Some(formatted) = ColumnKind::Upstream.format_diff_plain(ahead, behind)
+ {
+ parts.push(formatted);
+ }
+
+ // 6. CI status
+ if let Some(Some(ref pr_status)) = self.pr_status {
+ parts.push(pr_status.format_indicator());
+ }
+
+ parts.join(" ")
+ }
}
/// Main branch divergence state
@@ -435,6 +506,26 @@ impl std::fmt::Display for BranchOpState {
}
}
+impl BranchOpState {
+ /// Returns styled symbol with appropriate color, or None for None variant.
+ ///
+ /// Color semantics:
+ /// - ERROR (red): Conflicts - blocking problems
+ /// - WARNING (yellow): Rebase, Merge, MergeTreeConflicts - active/stuck states
+ /// - HINT (dimmed): MatchesMain, NoCommits - low urgency removability indicators
+ pub fn styled(&self) -> Option<String> {
+ use worktrunk::styling::{ERROR, HINT, WARNING};
+ match self {
+ Self::None => None,
+ Self::Conflicts => Some(format!("{ERROR}{self}{ERROR:#}")),
+ Self::Rebase | Self::Merge | Self::MergeTreeConflicts => {
+ Some(format!("{WARNING}{self}{WARNING:#}"))
+ }
+ Self::MatchesMain | Self::NoCommits => Some(format!("{HINT}{self}{HINT:#}")),
+ }
+ }
+}
+
impl serde::Serialize for BranchOpState {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
@@ -556,7 +647,7 @@ impl StatusSymbols {
///
/// See [`StatusSymbols`] struct doc for symbol categories.
pub fn render_with_mask(&self, mask: &PositionMask) -> String {
- use worktrunk::styling::{CYAN, ERROR, HINT, StyledLine, WARNING};
+ use worktrunk::styling::{CYAN, HINT, StyledLine, WARNING};
let mut result = String::with_capacity(64);
@@ -571,14 +662,9 @@ impl StatusSymbols {
// - Yellow (WARNING): Potential conflicts, git operations, locked/prunable (active/stuck states)
// - Cyan: Working tree changes (activity)
// - Dimmed (HINT): Branch state symbols that indicate removability + divergence arrows (low urgency)
- let (branch_op_state_str, has_branch_op_state) = match self.branch_op_state {
- BranchOpState::None => (String::new(), false),
- BranchOpState::Conflicts => (format!("{ERROR}✖{ERROR:#}"), true),
- BranchOpState::Rebase => (format!("{WARNING}↻{WARNING:#}"), true),
- BranchOpState::Merge => (format!("{WARNING}⋈{WARNING:#}"), true),
- BranchOpState::MergeTreeConflicts => (format!("{WARNING}⚠{WARNING:#}"), true),
- BranchOpState::MatchesMain => (format!("{HINT}≡{HINT:#}"), true),
- BranchOpState::NoCommits => (format!("{HINT}∅{HINT:#}"), true),
+ let (branch_op_state_str, has_branch_op_state) = match self.branch_op_state.styled() {
+ Some(s) => (s, true),
+ None => (String::new(), false),
};
let main_divergence_str = if self.main_divergence != MainDivergence::None {
format!("{HINT}{}{HINT:#}", self.main_divergence)
@@ -691,6 +777,36 @@ impl StatusSymbols {
&& self.working_tree.is_empty()
&& self.user_status.is_none()
}
+
+ /// Render status symbols in compact form for statusline (no grid alignment).
+ pub fn format_compact(&self) -> String {
+ use worktrunk::styling::{CYAN, WARNING};
+
+ let mut result = String::new();
+
+ // Working tree symbols (compact, no padding)
+ if !self.working_tree.is_empty() {
+ result.push_str(&format!("{CYAN}{}{CYAN:#}", self.working_tree));
+ }
+
+ // Branch/op state
+ if let Some(styled) = self.branch_op_state.styled() {
+ result.push_str(&styled);
+ }
+
+ // Worktree state (locked/prunable) - skip branch indicator (⎇)
+ // Note: ⎇ only appears for branch-only items, never for worktrees (statusline context)
+ if !self.worktree_state.is_empty() && self.worktree_state != "⎇" {
+ result.push_str(&format!("{WARNING}{}{WARNING:#}", self.worktree_state));
+ }
+
+ // User status
+ if let Some(ref user_status) = self.user_status {
+ result.push_str(user_status);
+ }
+
+ result
+ }
}
/// Working tree changes parsed into structured booleans
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index 80fdc3ae7..eababdfef 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -4,7 +4,7 @@ use std::path::Path;
use unicode_width::UnicodeWidthStr;
use worktrunk::styling::{CURRENT, StyledLine};
-use super::ci_status::{CiSource, CiStatus, PrStatus};
+use super::ci_status::PrStatus;
use super::columns::{ColumnKind, DiffVariant};
use super::layout::{
ColumnFormat, ColumnLayout, DiffColumnConfig, DiffDisplayConfig, LayoutConfig,
@@ -75,37 +75,14 @@ impl ColumnKind {
}
impl PrStatus {
- /// Determine the style for a CI status (color + optional dimming)
- fn style(&self) -> Style {
- let color = match self.ci_status {
- CiStatus::Passed => AnsiColor::Green,
- CiStatus::Running => AnsiColor::Blue,
- CiStatus::Failed => AnsiColor::Red,
- CiStatus::Conflicts => AnsiColor::Yellow,
- CiStatus::NoCI => AnsiColor::BrightBlack,
- };
-
- if self.is_stale {
- Style::new().fg_color(Some(Color::Ansi(color))).dimmed()
- } else {
- Style::new().fg_color(Some(Color::Ansi(color)))
- }
- }
-
- /// Get indicator symbol and style for rendering
+ /// Get indicator symbol and style for rendering (with URL underline)
fn indicator_and_style(&self) -> (&'static str, Style) {
- let indicator = match self.source {
- CiSource::PullRequest => "●",
- CiSource::Branch => "○",
- };
-
let style = if self.url.is_some() {
self.style().underline()
} else {
self.style()
};
-
- (indicator, style)
+ (self.source.indicator(), style)
}
fn render_indicator(&self) -> StyledLine {
@@ -364,24 +341,17 @@ impl LayoutConfig {
})
}
- pub fn format_list_item_line(
- &self,
- item: &ListItem,
- current_worktree_path: Option<&std::path::PathBuf>,
- previous_branch: Option<&str>,
- ) -> String {
- self.render_list_item_line(item, current_worktree_path, previous_branch)
- .render()
+ pub fn format_list_item_line(&self, item: &ListItem, previous_branch: Option<&str>) -> String {
+ self.render_list_item_line(item, previous_branch).render()
}
/// Render list item line as StyledLine (for extracting both plain and styled text)
pub fn render_list_item_line(
&self,
item: &ListItem,
- current_worktree_path: Option<&std::path::PathBuf>,
previous_branch: Option<&str>,
) -> StyledLine {
- let ctx = ListRowContext::new(item, current_worktree_path, previous_branch);
+ let ctx = ListRowContext::new(item, previous_branch);
self.render_line(|column| {
column.render_cell(
&ctx,
@@ -392,17 +362,17 @@ impl LayoutConfig {
})
}
- /// Render a skeleton row showing known data (branch, path) with placeholders for other columns
- pub fn format_skeleton_row(
- &self,
- item: &super::model::ListItem,
- is_current: bool,
- is_previous: bool,
- ) -> String {
+ /// Render a skeleton row showing known data (branch, path) with placeholders for other columns.
+ ///
+ /// Only called for worktrees (not branches), so we can extract is_current/is_previous from WorktreeData.
+ pub fn format_skeleton_row(&self, item: &super::model::ListItem) -> String {
use crate::display::shorten_path;
let branch = item.branch_name();
+ let wt_data = item.worktree_data();
let is_main = item.is_main();
+ let is_current = wt_data.map(|d| d.is_current).unwrap_or(false);
+ let is_previous = wt_data.map(|d| d.is_previous).unwrap_or(false);
let shortened_path = item
.worktree_path()
.map(|p| shorten_path(p, &self.common_prefix))
@@ -418,19 +388,14 @@ impl LayoutConfig {
ColumnKind::Gutter => {
// Show actual gutter symbol even in skeleton
// Priority: @ (current) > ^ (main) > - (previous) > + (regular)
- let has_worktree = item.worktree_path().is_some();
- let symbol = if has_worktree {
- if is_current {
- "@ "
- } else if is_main {
- "^ "
- } else if is_previous {
- "- "
- } else {
- "+ "
- }
+ let symbol = if is_current {
+ "@ "
+ } else if is_main {
+ "^ "
+ } else if is_previous {
+ "- "
} else {
- " "
+ "+ "
};
cell.push_raw(symbol.to_string());
}
@@ -478,11 +443,7 @@ struct ListRowContext<'a> {
}
impl<'a> ListRowContext<'a> {
- fn new(
- item: &'a ListItem,
- current_worktree_path: Option<&std::path::PathBuf>,
- previous_branch: Option<&str>,
- ) -> Self {
+ fn new(item: &'a ListItem, previous_branch: Option<&str>) -> Self {
let worktree_data = item.worktree_data();
let counts = item.counts();
let commit = item.commit_details();
@@ -490,13 +451,14 @@ impl<'a> ListRowContext<'a> {
let upstream = item.upstream();
let head = item.head();
- let is_current = worktree_data
- .and_then(|data| current_worktree_path.map(|p| p == &data.path))
- .unwrap_or(false);
-
- let is_previous = previous_branch
- .map(|prev| item.branch.as_deref() == Some(prev))
- .unwrap_or(false);
+ // Use stored values for worktrees, compute for branches
+ let is_current = worktree_data.map(|d| d.is_current).unwrap_or(false);
+ let is_previous = worktree_data.map(|d| d.is_previous).unwrap_or_else(|| {
+ // Branches don't have WorktreeData, compute from previous_branch
+ previous_branch
+ .map(|prev| item.branch.as_deref() == Some(prev))
+ .unwrap_or(false)
+ });
let mut ctx = Self {
item,
@@ -511,7 +473,7 @@ impl<'a> ListRowContext<'a> {
is_previous,
};
- ctx.text_style = ctx.compute_text_style(current_worktree_path);
+ ctx.text_style = ctx.compute_text_style();
ctx
}
@@ -519,20 +481,15 @@ impl<'a> ListRowContext<'a> {
&self.head[..8.min(self.head.len())]
}
- fn compute_text_style(
- &self,
- current_worktree_path: Option<&std::path::PathBuf>,
- ) -> Option<Style> {
- let base_style = self.worktree_data.and_then(|data| {
- let is_current = current_worktree_path
- .map(|p| p == &data.path)
- .unwrap_or(false);
- match (is_current, data.is_main) {
- (true, _) => Some(CURRENT),
- (_, true) => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)))),
- _ => None,
- }
- });
+ fn compute_text_style(&self) -> Option<Style> {
+ // Use stored is_current instead of recomputing from paths
+ let base_style =
+ self.worktree_data
+ .and_then(|data| match (self.is_current, data.is_main) {
+ (true, _) => Some(CURRENT),
+ (_, true) => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)))),
+ _ => None,
+ });
if self.item.is_potentially_removable() {
Some(base_style.unwrap_or_default().dimmed())
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 0908e758b..148c8ab88 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -14,6 +14,7 @@ pub mod repository_ext;
#[cfg(unix)]
pub mod select;
pub mod standalone;
+pub mod statusline;
pub mod worktree;
pub use config::{
diff --git a/src/commands/select.rs b/src/commands/select.rs
index fd7ca1f45..2ecddb6ec 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -286,7 +286,7 @@ pub fn handle_select(is_directive_mode: bool) -> anyhow::Result<()> {
};
// Get current worktree path for styling
- let current_worktree_path = repo.worktree_root().ok();
+ let _current_worktree_path = repo.worktree_root().ok();
// Use the same layout system as `wt list` for proper column alignment
let layout = super::list::layout::calculate_layout_from_basics(
@@ -307,8 +307,7 @@ pub fn handle_select(is_directive_mode: bool) -> anyhow::Result<()> {
let branch_name = item.branch_name().to_string();
// Use layout system to render the line - this handles all column alignment
- let rendered_line =
- layout.render_list_item_line(&item, current_worktree_path.as_ref(), None);
+ let rendered_line = layout.render_list_item_line(&item, None);
let display_text_with_ansi = rendered_line.render();
let display_text = rendered_line.plain_text();
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
new file mode 100644
index 000000000..d9ab69fa1
--- /dev/null
+++ b/src/commands/statusline.rs
@@ -0,0 +1,279 @@
+//! Statusline output for shell prompts and editors.
+//!
+//! Outputs a single-line status for the current worktree:
+//! `branch status ±working commits upstream [ci]`
+//!
+//! This command reuses the data collection infrastructure from `wt list`,
+//! avoiding duplication of git operations.
+
+use anyhow::{Context, Result};
+use std::env;
+use std::io::{self, Read};
+use std::path::Path;
+use std::time::Duration;
+use worktrunk::git::Repository;
+use worktrunk::styling::print;
+
+use super::list::{self, CollectOptions};
+
+/// Claude Code context parsed from stdin JSON
+struct ClaudeCodeContext {
+ /// Working directory from `.workspace.current_dir`
+ current_dir: String,
+ /// Model name from `.model.display_name`
+ model_name: Option<String>,
+}
+
+impl ClaudeCodeContext {
+ /// Try to read and parse Claude Code context from stdin.
+ /// Returns None if stdin is empty or not valid JSON.
+ fn from_stdin() -> Option<Self> {
+ // Non-blocking read with timeout
+ // Claude Code pipes JSON to stdin, but we shouldn't block if nothing is there
+ use std::sync::mpsc;
+ use std::thread;
+
+ let (tx, rx) = mpsc::channel();
+
+ thread::spawn(move || {
+ let mut input = String::new();
+ let _ = io::stdin().read_to_string(&mut input);
+ let _ = tx.send(input);
+ });
+
+ // Wait up to 10ms for stdin
+ let input = rx.recv_timeout(Duration::from_millis(10)).ok()?;
+
+ if input.is_empty() {
+ return None;
+ }
+
+ // Parse JSON
+ let json: serde_json::Value = serde_json::from_str(&input).ok()?;
+
+ let current_dir = json
+ .get("workspace")
+ .and_then(|w| w.get("current_dir"))
+ .and_then(|d| d.as_str())
+ .unwrap_or(".")
+ .to_string();
+
+ let model_name = json
+ .get("model")
+ .and_then(|m| m.get("display_name"))
+ .and_then(|n| n.as_str())
+ .map(|s| s.to_string());
+
+ Some(Self {
+ current_dir,
+ model_name,
+ })
+ }
+}
+
+/// Format a directory path in fish-style (abbreviated parent directories).
+///
+/// Examples:
+/// - `/home/user/workspace/project` -> `~/w/project`
+/// - `/home/user` -> `~`
+/// - `/tmp/test` -> `/t/test`
+fn format_directory_fish_style(path: &str) -> String {
+ let home = env::var("HOME").unwrap_or_default();
+
+ // Replace home with ~
+ let path = if !home.is_empty() && path.starts_with(&home) {
+ format!("~{}", &path[home.len()..])
+ } else {
+ path.to_string()
+ };
+
+ // Handle absolute paths - preserve leading /
+ let is_absolute = path.starts_with('/');
+ let parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect();
+
+ if parts.is_empty() {
+ return path;
+ }
+
+ if parts.len() == 1 {
+ // Single component - return as-is with leading / if absolute
+ return if is_absolute {
+ format!("/{}", parts[0])
+ } else {
+ parts[0].to_string()
+ };
+ }
+
+ let mut result = String::new();
+
+ // Add leading / for absolute paths
+ if is_absolute {
+ result.push('/');
+ }
+
+ for (i, part) in parts.iter().enumerate() {
+ let is_last = i == parts.len() - 1;
+ let is_first = i == 0;
+
+ if is_first && *part == "~" {
+ result.push('~');
+ } else if is_last {
+ // Keep full name for last component
+ if !is_first {
+ result.push('/');
+ }
+ result.push_str(part);
+ } else {
+ // Abbreviate to first character
+ if !is_first {
+ result.push('/');
+ }
+ if let Some(c) = part.chars().next() {
+ result.push(c);
+ }
+ }
+ }
+
+ result
+}
+
+/// Run the statusline command.
+pub fn run(claude_code: bool) -> Result<()> {
+ // Get context - either from stdin (claude-code mode) or current directory
+ let (cwd, model_name) = if claude_code {
+ let ctx = ClaudeCodeContext::from_stdin();
+ let current_dir = ctx
+ .as_ref()
+ .map(|c| c.current_dir.clone())
+ .unwrap_or_else(|| env::current_dir().unwrap_or_default().display().to_string());
+ let model = ctx.and_then(|c| c.model_name);
+ (Path::new(&current_dir).to_path_buf(), model)
+ } else {
+ (
+ env::current_dir().context("Failed to get current directory")?,
+ None,
+ )
+ };
+
+ // Build output parts
+ let mut parts: Vec<String> = Vec::new();
+
+ // Directory (claude-code mode only)
+ if claude_code {
+ let formatted_dir = format_directory_fish_style(&cwd.display().to_string());
+ parts.push(formatted_dir);
+ }
+
+ // Git status
+ let repo = Repository::at(&cwd);
+ if repo.git_dir().is_ok()
+ && let Some(status_line) = get_git_status(&repo, &cwd)?
+ {
+ parts.push(status_line);
+ }
+
+ // Model name (claude-code mode only)
+ if let Some(model) = model_name {
+ // Use " | " as separator before model name
+ if !parts.is_empty() {
+ let last = parts.pop().unwrap();
+ parts.push(format!("{last} | {model}"));
+ } else {
+ parts.push(format!("| {model}"));
+ }
+ }
+
+ // Output with ANSI reset prefix
+ if !parts.is_empty() {
+ let output = parts.join(" ");
+ if claude_code {
+ // Reset any prior formatting, add leading space for visual separation
+ let reset = anstyle::Reset;
+ print!("{reset} {output}");
+ } else {
+ print!("{output}");
+ }
+ }
+
+ Ok(())
+}
+
+/// Get git status line for the current worktree
+fn get_git_status(repo: &Repository, cwd: &Path) -> Result<Option<String>> {
+ // Get current worktree info
+ let worktrees = repo.list_worktrees()?;
+ let current_worktree = worktrees
+ .worktrees
+ .iter()
+ .find(|wt| cwd.starts_with(&wt.path));
+
+ let Some(wt) = current_worktree else {
+ // Not in a worktree - just show branch name
+ if let Ok(Some(branch)) = repo.current_branch() {
+ return Ok(Some(branch));
+ }
+ return Ok(None);
+ };
+
+ // Get default branch for comparisons
+ let default_branch = match repo.default_branch() {
+ Ok(b) => b,
+ Err(_) => {
+ // Can't determine default branch - just show current branch
+ return Ok(Some(wt.branch.as_deref().unwrap_or("HEAD").to_string()));
+ }
+ };
+
+ // Determine if this is the main worktree
+ let main_worktree = worktrees
+ .worktrees
+ .iter()
+ .find(|w| w.branch.as_deref() == Some(default_branch.as_str()))
+ .unwrap_or_else(|| worktrees.main());
+ let is_main = wt.path == main_worktree.path;
+
+ // Build item with identity fields
+ let mut items = vec![list::build_worktree_item(wt, is_main, true, false)];
+
+ // Populate computed fields (parallel git operations) and format status_line
+ list::populate_items(
+ &mut items,
+ &default_branch,
+ CollectOptions {
+ fetch_ci: true,
+ check_merge_tree_conflicts: false,
+ },
+ )?;
+
+ // Return the pre-formatted status line
+ if let Some(ref status_line) = items[0].display.status_line {
+ Ok(Some(status_line.clone()))
+ } else {
+ // Fallback: just show branch name
+ Ok(Some(wt.branch.as_deref().unwrap_or("HEAD").to_string()))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_format_directory_fish_style() {
+ // Test paths that don't depend on HOME
+ assert_eq!(format_directory_fish_style("/tmp/test"), "/t/test");
+ assert_eq!(format_directory_fish_style("/"), "/");
+ assert_eq!(format_directory_fish_style("/var/log/app"), "/v/l/app");
+
+ // Test with actual HOME (if set)
+ if let Ok(home) = env::var("HOME") {
+ let test_path = format!("{home}/workspace/project");
+ let result = format_directory_fish_style(&test_path);
+ assert!(result.starts_with("~/"), "Expected ~ prefix, got: {result}");
+ assert!(
+ result.ends_with("/project"),
+ "Expected /project suffix, got: {result}"
+ );
+ }
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 39d24febd..6bcc382c7 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -554,9 +554,10 @@ fn main() {
handle_standalone_run_hook(HookType::PostMerge, force)
}
},
- #[cfg(unix)]
Commands::Beta { action } => match action {
+ #[cfg(unix)]
BetaCommand::Select => handle_select(cli.internal),
+ BetaCommand::Statusline { claude_code } => commands::statusline::run(claude_code),
},
Commands::List {
format,
diff --git a/tests/snapshots/integration__integration_tests__help__help_beta.snap b/tests/snapshots/integration__integration_tests__help__help_beta.snap
index e3a7eda80..fe22b1214 100644
--- a/tests/snapshots/integration__integration_tests__help__help_beta.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_beta.snap
@@ -18,7 +18,8 @@ wt beta - Experimental commands
Usage: wt beta [OPTIONS] <COMMAND>
Commands:
- select Interactive worktree selector
+ select Interactive worktree selector
+ statusline Single-line status for shell prompts
Options:
-h, --help
diff --git a/tests/snapshots/integration__integration_tests__help__help_list.snap b/tests/snapshots/integration__integration_tests__help__help_list.snap
index f52ae88b0..723b7ecc7 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list.snap
@@ -116,6 +116,12 @@ with the same fields in the same order as Status Symbols above:
Note: locked and prunable are top-level fields on worktree objects, not in status.
+Worktree position fields (for identifying special worktrees):
+
+- is_main: boolean - is the main/default worktree
+- is_current: boolean - is the current working directory (present when true)
+- is_previous: boolean - is the previous worktree from wt switch (present when true)
+
Query examples:
# Find worktrees with conflicts
@@ -132,5 +138,8 @@ Note: locked and prunable are top-level fields on worktree objec

# Find locked worktrees
jq '.[] | select(.locked != null)'
+ 
+ # Get current worktree info (useful for statusline tools)
+ jq '.[] | select(.is_current == true)'
----- stderr -----
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 5569d956f..d22b36092 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
@@ -57,6 +57,7 @@ exit_code: 0
"upstream_divergence": "",
"worktree_state": ""
},
+ "status_line": "main",
"type": "worktree",
"path": "[REPO]",
"bare": false,
@@ -70,7 +71,8 @@ exit_code: 0
"deleted": 0
},
"worktree_state": null,
- "is_main": true
+ "is_main": true,
+ "is_current": true
},
{
"head_sha": "f16cd37915d5ee93903252f5cf877c76c54f3d50",
@@ -109,6 +111,7 @@ 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_line": "feature-ahead /u001b[36m!?/u001b[0m ±/u001b[32m+1/u001b[0m /u001b[31m-1/u001b[0m /u001b[32m↑2/u001b[0m /u001b[2m/u001b[31m↓2/u001b[0m",
"type": "worktree",
"path": "[WORKTREE_FEATURE_AHEAD]",
"bare": false,
@@ -158,6 +161,7 @@ exit_code: 0
"worktree_state": ""
},
"commits_display": "/u001b[2m/u001b[31m↓2/u001b[0m",
+ "status_line": "feature-behind /u001b[2m∅/u001b[0m /u001b[2m/u001b[31m↓2/u001b[0m",
"type": "worktree",
"path": "[WORKTREE_FEATURE_BEHIND]",
"bare": 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 b39c848e4..abbee6b35 100644
--- a/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap
+++ b/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap
@@ -57,6 +57,7 @@ exit_code: 0
"upstream_divergence": "",
"worktree_state": ""
},
+ "status_line": "main",
"type": "worktree",
"path": "[REPO]",
"bare": false,
@@ -70,7 +71,8 @@ exit_code: 0
"deleted": 0
},
"worktree_state": null,
- "is_main": true
+ "is_main": true,
+ "is_current": true
},
{
"head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
@@ -107,6 +109,7 @@ exit_code: 0
"upstream_divergence": "",
"worktree_state": ""
},
+ "status_line": "feature-detached /u001b[2m∅/u001b[0m",
"type": "worktree",
"path": "[WORKTREE_FEATURE_DETACHED]",
"bare": false,
@@ -157,6 +160,7 @@ exit_code: 0
"upstream_divergence": "",
"worktree_state": "⊠"
},
+ "status_line": "locked-feature /u001b[2m∅/u001b[0m/u001b[33m⊠/u001b[0m",
"type": "worktree",
"path": "[WORKTREE_LOCKED_FEATURE]",
"bare": 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 39053cf5b..26717d2a7 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
@@ -57,6 +57,7 @@ exit_code: 0
"upstream_divergence": "",
"worktree_state": ""
},
+ "status_line": "main",
"type": "worktree",
"path": "[REPO]",
"bare": false,
@@ -70,7 +71,8 @@ exit_code: 0
"deleted": 0
},
"worktree_state": null,
- "is_main": true
+ "is_main": true,
+ "is_current": true
},
{
"head_sha": "b834638e33dbc6b37002685ee0777f4b8f1af904",
@@ -109,6 +111,7 @@ exit_code: 0
"worktree_state": "",
"user_status": "🔧"
},
+ "status_line": "with-status /u001b[2m∅/u001b[0m🔧",
"type": "worktree",
"path": "[WORKTREE_WITH_STATUS]",
"bare": false,
@@ -159,6 +162,7 @@ exit_code: 0
"upstream_divergence": "",
"worktree_state": ""
},
+ "status_line": "without-status /u001b[2m∅/u001b[0m",
"type": "worktree",
"path": "[WORKTREE_WITHOUT_STATUS]",
"bare": false,