Skip to content

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

Refactor: Extract command execution logic to new module

Maximilian Roos1d94b4e438b2
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 5b97aceaa..df316ccfc 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -1,28 +1,19 @@
//! Command approval and execution utilities
//!
-//! This module provides shared functionality for approving and executing commands
-//! across different worktrunk operations (post-create, post-start, pre-merge).
+//! Shared helpers for approving commands declared in project configuration.
-use worktrunk::config::{ApprovedCommand, CommandConfig, WorktrunkConfig};
+use worktrunk::config::{CommandConfig, WorktrunkConfig};
use worktrunk::git::GitError;
use worktrunk::styling::{
AnstyleStyle, HINT_EMOJI, WARNING, WARNING_EMOJI, eprintln, format_with_gutter,
};
-/// Convert CommandConfig to a vector of (name, command) pairs
+/// Convert CommandConfig to a vector of `(name, command)` pairs.
///
-/// # Arguments
-/// * `config` - The command configuration to convert
-/// * `default_prefix` - Prefix for unnamed commands (typically "cmd")
-///
-/// # Naming Behavior
-/// - **Single string**: Uses the exact prefix without numbering
-/// - `pre-merge-check = "exit 0"` → `("cmd", "exit 0")`
-/// - **Array (even single-element)**: Appends 1-based index to prefix
-/// - `pre-merge-check = ["exit 0"]` → `("cmd-1", "exit 0")`
-/// - `pre-merge-check = ["a", "b"]` → `("cmd-1", "a"), ("cmd-2", "b")`
-/// - **Named table**: Uses the key names directly (sorted alphabetically)
-/// - `[pre-merge-check]` `foo="a"` `bar="b"` → `("bar", "b"), ("foo", "a")`
+/// Naming rules:
+/// - Single string → uses the prefix directly (`"cmd"`)
+/// - Array → appends 1-based index (`"cmd-1"`, `"cmd-2"`, …)
+/// - Table → uses the map keys (sorted for determinism)
pub fn command_config_to_vec(
config: &CommandConfig,
default_prefix: &str,
@@ -36,18 +27,15 @@ pub fn command_config_to_vec(
.collect(),
CommandConfig::Named(map) => {
let mut pairs: Vec<_> = map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
- // Sort by name for deterministic iteration order
pairs.sort_by(|a, b| a.0.cmp(&b.0));
pairs
}
}
}
-/// Check if commands need approval and handle the approval flow
-///
-/// Returns `Ok(true)` if all commands are approved (or force-approved),
-/// `Ok(false)` if user declined approval.
-/// Automatically saves approvals when granted.
+/// Batch approval helper used when multiple commands are queued for execution.
+/// Returns `Ok(true)` when execution may continue, `Ok(false)` when the user
+/// declined, and `Err` if config reload/save fails.
pub fn approve_command_batch(
commands: &[(String, String)],
project_id: &str,
@@ -55,73 +43,96 @@ pub fn approve_command_batch(
force: bool,
context: &str,
) -> Result<bool, GitError> {
- // Find commands that need approval
- let needs_approval: Vec<(&str, &str)> = commands
+ let needs_approval: Vec<(&String, &String)> = commands
.iter()
- .filter(|(_, cmd)| !config.is_command_approved(project_id, cmd))
- .map(|(name, cmd)| (name.as_str(), cmd.as_str()))
+ .filter(|(_, command)| !config.is_command_approved(project_id, command))
+ .map(|(name, command)| (name, command))
.collect();
if needs_approval.is_empty() {
return Ok(true);
}
- // Prompt or force-approve
- let should_approve = if force {
+ let approved = if force {
true
} else {
prompt_for_batch_approval(&needs_approval, project_id)
- .map_err(|e| GitError::CommandFailed(format!("Failed to read user input: {}", e)))?
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?
};
- if !should_approve {
+ if !approved {
let dim = AnstyleStyle::new().dimmed();
eprintln!("{dim}{context} declined{dim:#}");
return Ok(false);
}
- // Save all approvals to config
let mut fresh_config = WorktrunkConfig::load()
.map_err(|e| GitError::CommandFailed(format!("Failed to reload config: {}", e)))?;
- // Add each command to approved list
- for (_, command) in &needs_approval {
- if !fresh_config.is_command_approved(project_id, command) {
- fresh_config.approved_commands.push(ApprovedCommand {
- project: project_id.to_string(),
- command: command.to_string(),
- });
+ for (_, command) in needs_approval {
+ if let Err(e) = fresh_config.approve_command(project_id.to_string(), command.to_string()) {
+ log_approval_warning("Failed to save command approval", e);
+ eprintln!("You will be prompted again next time.");
}
}
- // Save all approvals at once
- if let Err(e) = fresh_config.save() {
- eprintln!("{WARNING_EMOJI} {WARNING}Failed to save command approvals: {e}{WARNING:#}");
- eprintln!("You will be prompted again next time.");
- }
-
Ok(true)
}
-/// Prompt the user to approve multiple commands for execution
+/// Check whether a command is approved, prompting and persisting approval if needed.
+///
+/// Returns `Ok(true)` when the command may execute, `Ok(false)` when the user declined,
+/// and `Err` when an unexpected I/O failure occurs.
///
-/// Displays a formatted prompt asking the user to approve a batch of commands,
-/// showing both the project and all commands being requested.
-pub fn prompt_for_batch_approval(
- commands: &[(&str, &str)],
+/// `from_project_config` should be `true` for commands sourced from `.config/wt.toml`,
+/// which we treat as trusted because they are checked into the repository.
+#[allow(dead_code)]
+pub fn check_and_approve_command(
project_id: &str,
-) -> std::io::Result<bool> {
- use std::io::{self, Write};
- use worktrunk::styling::eprintln;
+ command: &str,
+ config: &WorktrunkConfig,
+ force: bool,
+ from_project_config: bool,
+) -> Result<bool, GitError> {
+ if from_project_config || force || config.is_command_approved(project_id, command) {
+ return Ok(true);
+ }
- debug_assert!(
- !commands.is_empty(),
- "prompt_for_batch_approval called with empty commands list"
- );
+ match prompt_for_approval(command, project_id) {
+ Ok(true) => {
+ match WorktrunkConfig::load() {
+ Ok(mut fresh_config) => {
+ if let Err(e) =
+ fresh_config.approve_command(project_id.to_string(), command.to_string())
+ {
+ log_approval_warning("Failed to save command approval", e);
+ eprintln!("You will be prompted again next time.");
+ }
+ }
+ Err(e) => {
+ log_approval_warning("Failed to reload config for saving approval", e);
+ eprintln!("You will be prompted again next time.");
+ }
+ }
+ Ok(true)
+ }
+ Ok(false) => Ok(false),
+ Err(e) => {
+ log_approval_warning("Failed to read user input", e);
+ Ok(false)
+ }
+ }
+}
- // Extract just the project name for cleaner display
- let project_name = project_id.split('/').next_back().unwrap_or(project_id);
+fn log_approval_warning(message: &str, error: impl std::fmt::Display) {
+ eprintln!("{WARNING_EMOJI} {WARNING}{message}: {error}{WARNING:#}");
+}
+
+#[allow(dead_code)]
+fn prompt_for_approval(command: &str, project_id: &str) -> std::io::Result<bool> {
+ use std::io::{self, Write};
+ let project_name = project_id.split('/').next_back().unwrap_or(project_id);
let bold = AnstyleStyle::new().bold();
let dim = AnstyleStyle::new().dimmed();
@@ -129,21 +140,51 @@ pub fn prompt_for_batch_approval(
eprintln!("{WARNING_EMOJI} {WARNING}Permission required to execute in worktree{WARNING:#}");
eprintln!();
eprintln!("{bold}{project_name}{bold:#} ({dim}{project_id}{dim:#}) wants to execute:");
+ eprint!("{}", format_with_gutter(command, "")); // Gutter at column 0
+ eprintln!();
+ eprint!("{HINT_EMOJI} Allow and remember? {bold}[y/N]{bold:#} ");
+ io::stderr().flush()?;
+
+ let mut response = String::new();
+ io::stdin().read_line(&mut response)?;
+ Ok(response.trim().eq_ignore_ascii_case("y"))
+}
+
+fn prompt_for_batch_approval(
+ commands: &[(&String, &String)],
+ project_id: &str,
+) -> std::io::Result<bool> {
+ use std::io::{self, Write};
+
+ let project_name = project_id.split('/').next_back().unwrap_or(project_id);
+ let bold = AnstyleStyle::new().bold();
+ let dim = AnstyleStyle::new().dimmed();
+ let count = commands.len();
+ let plural = if count == 1 { "" } else { "s" };
+
+ eprintln!();
+ eprintln!(
+ "{WARNING_EMOJI} {WARNING}Permission required to execute {bold}{count}{bold:#} command{plural}{WARNING:#}",
+ );
+ eprintln!();
+ eprintln!("{bold}{project_name}{bold:#} ({dim}{project_id}{dim:#}) wants to execute:");
eprintln!();
- // Show each command with its name
for (name, command) in commands {
- eprintln!("{bold}{name}:{bold:#}");
- eprint!("{}", format_with_gutter(command));
- eprintln!();
+ let label = if count == 1 {
+ (*command).clone()
+ } else {
+ format!("{name}: {command}")
+ };
+ eprint!("{}", format_with_gutter(&label, ""));
}
+ eprintln!();
eprint!("{HINT_EMOJI} Allow and remember? {bold}[y/N]{bold:#} ");
io::stderr().flush()?;
let mut response = String::new();
io::stdin().read_line(&mut response)?;
-
Ok(response.trim().eq_ignore_ascii_case("y"))
}
@@ -179,7 +220,6 @@ mod tests {
map.insert("alpha".to_string(), "a".to_string());
let config = CommandConfig::Named(map);
let result = command_config_to_vec(&config, "cmd");
- // Should be sorted alphabetically
assert_eq!(
result,
vec![
@@ -188,13 +228,4 @@ mod tests {
]
);
}
-
- #[test]
- fn test_command_config_to_vec_different_prefix() {
- let config = CommandConfig::Single("test".to_string());
- let result1 = command_config_to_vec(&config, "cmd");
- let result2 = command_config_to_vec(&config, "check");
- assert_eq!(result1[0].0, "cmd");
- assert_eq!(result2[0].0, "check");
- }
}
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
new file mode 100644
index 000000000..eabc90099
--- /dev/null
+++ b/src/commands/command_executor.rs
@@ -0,0 +1,107 @@
+use std::collections::HashMap;
+use std::path::Path;
+use worktrunk::config::{CommandConfig, WorktrunkConfig, expand_template};
+use worktrunk::git::{GitError, Repository};
+
+use super::command_approval::{approve_command_batch, command_config_to_vec};
+
+#[derive(Debug)]
+pub struct PreparedCommand {
+ pub name: String,
+ pub expanded: String,
+}
+
+pub struct CommandContext<'a> {
+ pub repo: &'a Repository,
+ pub config: &'a WorktrunkConfig,
+ pub branch: &'a str,
+ pub worktree_path: &'a Path,
+ pub force: bool,
+}
+
+impl<'a> CommandContext<'a> {
+ pub fn new(
+ repo: &'a Repository,
+ config: &'a WorktrunkConfig,
+ branch: &'a str,
+ worktree_path: &'a Path,
+ force: bool,
+ ) -> Self {
+ Self {
+ repo,
+ config,
+ branch,
+ worktree_path,
+ force,
+ }
+ }
+}
+
+pub fn prepare_project_commands<F>(
+ command_config: &CommandConfig,
+ default_prefix: &str,
+ ctx: &CommandContext<'_>,
+ auto_trust: bool,
+ extra_vars: &[(&str, &str)],
+ approval_context: &str,
+ mut on_skip: F,
+) -> Result<Vec<PreparedCommand>, GitError>
+where
+ F: FnMut(&str, &str),
+{
+ let commands = command_config_to_vec(command_config, default_prefix);
+ if commands.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let project_id = ctx.repo.project_identifier()?;
+ let repo_root = ctx.repo.main_worktree_root()?;
+ let repo_name = repo_root
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("unknown");
+
+ let mut base_extras = HashMap::new();
+ base_extras.insert(
+ "worktree".to_string(),
+ ctx.worktree_path.to_string_lossy().to_string(),
+ );
+ base_extras.insert(
+ "repo_root".to_string(),
+ repo_root.to_str().unwrap_or("").to_string(),
+ );
+ for &(key, value) in extra_vars {
+ base_extras.insert(key.to_string(), value.to_string());
+ }
+
+ let mut prepared = Vec::new();
+
+ if !auto_trust {
+ if !approve_command_batch(
+ &commands,
+ &project_id,
+ ctx.config,
+ ctx.force,
+ approval_context,
+ )? {
+ for (name, command) in &commands {
+ on_skip(name, command);
+ }
+ return Err(GitError::CommandFailed(String::new()));
+ }
+ }
+
+ for (name, command) in commands {
+ let extras_owned = base_extras.clone();
+ let extras_ref: HashMap<&str, &str> = extras_owned
+ .iter()
+ .map(|(k, v)| (k.as_str(), v.as_str()))
+ .collect();
+
+ let expanded = expand_template(&command, repo_name, ctx.branch, &extras_ref);
+
+ prepared.push(PreparedCommand { name, expanded });
+ }
+
+ Ok(prepared)
+}
diff --git a/src/commands/config.rs b/src/commands/config.rs
index 0f424f0b4..b7ecd98b7 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -89,8 +89,8 @@ fn display_global_config() -> Result<(), GitError> {
return Ok(());
}
- // Display TOML with syntax highlighting
- print!("{}", format_toml(&contents));
+ // Display TOML with syntax highlighting (gutter at column 0)
+ print!("{}", format_toml(&contents, ""));
Ok(())
}
@@ -127,8 +127,8 @@ fn display_project_config() -> Result<(), GitError> {
return Ok(());
}
- // Display TOML with syntax highlighting
- print!("{}", format_toml(&contents));
+ // Display TOML with syntax highlighting (gutter at column 0)
+ print!("{}", format_toml(&contents, ""));
Ok(())
}
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index 80aeecb78..281a5a72c 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -2,7 +2,7 @@ use crate::display::{find_common_prefix, get_terminal_width};
use std::path::{Path, PathBuf};
use unicode_width::UnicodeWidthStr;
-use super::ListItem;
+use super::model::ListItem;
/// Helper: Try to allocate space for a column. Returns the allocated width if successful.
/// Updates `remaining` by subtracting the allocated width + spacing.
@@ -310,7 +310,7 @@ mod tests {
#[test]
fn test_column_width_calculation_with_unicode() {
- use crate::commands::list::{
+ use crate::commands::list::model::{
AheadBehind, BranchDiffTotals, CommitDetails, UpstreamStatus, WorktreeInfo,
};
@@ -335,11 +335,7 @@ mod tests {
working_tree_diff: (100, 50),
branch_diff: BranchDiffTotals { diff: (200, 30) },
is_primary: false,
- upstream: UpstreamStatus {
- remote: Some("origin".to_string()),
- ahead: 4,
- behind: 0,
- },
+ upstream: UpstreamStatus::from_parts(Some("origin".to_string()), 4, 0),
worktree_state: None,
};
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index bc62078c2..4e9ed476d 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -1,356 +1,38 @@
mod layout;
+mod model;
mod render;
#[cfg(test)]
mod spacing_test;
-use rayon::prelude::*;
-use worktrunk::git::{GitError, Repository};
-use worktrunk::styling::{HINT, HINT_EMOJI, WARNING, WARNING_EMOJI, eprintln};
-
use layout::calculate_responsive_layout;
+use model::{ListData, ListItem, gather_list_data};
use render::{format_header_line, format_list_item_line};
-
-#[derive(serde::Serialize)]
-pub struct WorktreeInfo {
- pub worktree: worktrunk::git::Worktree,
- #[serde(flatten)]
- pub commit: CommitDetails,
- #[serde(flatten)]
- pub counts: AheadBehind,
- pub working_tree_diff: (usize, usize),
- #[serde(flatten)]
- pub branch_diff: BranchDiffTotals,
- pub is_primary: bool,
- #[serde(flatten)]
- pub upstream: UpstreamStatus,
- pub worktree_state: Option<String>,
-}
-
-#[derive(serde::Serialize)]
-pub struct BranchInfo {
- pub name: String,
- pub head: String,
- #[serde(flatten)]
- pub commit: CommitDetails,
- #[serde(flatten)]
- pub counts: AheadBehind,
- #[serde(flatten)]
- pub branch_diff: BranchDiffTotals,
- #[serde(flatten)]
- pub upstream: UpstreamStatus,
-}
-
-#[derive(serde::Serialize, Clone)]
-pub(crate) 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)]
-pub(crate) 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)]
-pub(crate) struct BranchDiffTotals {
- #[serde(rename = "branch_diff")]
- pub diff: (usize, usize),
-}
-
-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)]
-pub(crate) struct UpstreamStatus {
- #[serde(rename = "upstream_remote")]
- remote: Option<String>,
- #[serde(rename = "upstream_ahead")]
- ahead: usize,
- #[serde(rename = "upstream_behind")]
- 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()),
- }
- }
-
- fn active(&self) -> Option<(&str, usize, usize)> {
- if self.ahead == 0 && self.behind == 0 {
- None
- } else {
- Some((
- self.remote.as_deref().unwrap_or("origin"),
- self.ahead,
- self.behind,
- ))
- }
- }
-}
-
-/// Unified type for displaying worktrees and branches in the same table
-#[derive(serde::Serialize)]
-#[serde(tag = "type", rename_all = "lowercase")]
-pub enum ListItem {
- Worktree(WorktreeInfo),
- Branch(BranchInfo),
-}
-
-impl ListItem {
- pub fn branch_name(&self) -> &str {
- match self {
- ListItem::Worktree(wt) => wt.worktree.branch.as_deref().unwrap_or("(detached)"),
- ListItem::Branch(br) => &br.name,
- }
- }
-
- pub fn is_primary(&self) -> bool {
- match self {
- ListItem::Worktree(wt) => wt.is_primary,
- ListItem::Branch(_) => false,
- }
- }
-
- pub fn commit_timestamp(&self) -> i64 {
- match self {
- ListItem::Worktree(info) => info.commit.timestamp,
- ListItem::Branch(info) => info.commit.timestamp,
- }
- }
-
- pub fn head(&self) -> &str {
- match self {
- ListItem::Worktree(info) => &info.worktree.head,
- ListItem::Branch(info) => &info.head,
- }
- }
-
- pub fn commit_details(&self) -> &CommitDetails {
- match self {
- ListItem::Worktree(info) => &info.commit,
- ListItem::Branch(info) => &info.commit,
- }
- }
-
- pub fn counts(&self) -> &AheadBehind {
- match self {
- ListItem::Worktree(info) => &info.counts,
- ListItem::Branch(info) => &info.counts,
- }
- }
-
- pub fn branch_diff(&self) -> &BranchDiffTotals {
- match self {
- ListItem::Worktree(info) => &info.branch_diff,
- ListItem::Branch(info) => &info.branch_diff,
- }
- }
-
- pub fn upstream(&self) -> &UpstreamStatus {
- match self {
- ListItem::Worktree(info) => &info.upstream,
- ListItem::Branch(info) => &info.upstream,
- }
- }
-
- pub fn worktree_info(&self) -> Option<&WorktreeInfo> {
- match self {
- ListItem::Worktree(info) => Some(info),
- ListItem::Branch(_) => None,
- }
- }
-
- pub fn worktree_path(&self) -> Option<&std::path::PathBuf> {
- self.worktree_info().map(|info| &info.worktree.path)
- }
-}
-
-impl BranchInfo {
- /// Create BranchInfo from a branch name, enriching it with git metadata
- fn from_branch(
- branch: &str,
- repo: &Repository,
- primary_branch: Option<&str>,
- ) -> 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)?;
-
- Ok(BranchInfo {
- name: branch.to_string(),
- head,
- commit,
- counts,
- branch_diff,
- upstream,
- })
- }
-}
-
-impl WorktreeInfo {
- /// Create WorktreeInfo from a Worktree, enriching it with git metadata
- fn from_worktree(
- wt: &worktrunk::git::Worktree,
- primary: &worktrunk::git::Worktree,
- ) -> 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 working_tree_diff = wt_repo.working_tree_diff_stats()?;
- let branch_diff = BranchDiffTotals::compute(&wt_repo, base_branch, &wt.head)?;
- let upstream = UpstreamStatus::calculate(&wt_repo, wt.branch.as_deref(), &wt.head)?;
-
- // Get worktree state (merge/rebase/etc)
- let worktree_state = wt_repo.worktree_state()?;
-
- Ok(WorktreeInfo {
- worktree: wt.clone(),
- commit,
- counts,
- working_tree_diff,
- branch_diff,
- is_primary,
- upstream,
- worktree_state,
- })
- }
-}
+use worktrunk::git::{GitError, Repository};
pub fn handle_list(format: crate::OutputFormat, show_branches: bool) -> Result<(), GitError> {
let repo = Repository::current();
- let worktrees = repo.list_worktrees()?;
-
- if worktrees.is_empty() {
+ let Some(ListData {
+ items,
+ current_worktree_path,
+ }) = gather_list_data(&repo, show_branches)?
+ else {
return Ok(());
- }
-
- // First worktree is the primary - clone it for use in closure
- let primary = worktrees[0].clone();
-
- // Get current worktree to identify active one
- let current_worktree_path = repo.worktree_root().ok();
-
- // Gather enhanced information for all worktrees in parallel
- //
- // Parallelization strategy: Use Rayon to process worktrees concurrently.
- // Each worktree requires ~5 git operations (timestamp, ahead/behind, diffs).
- //
- // Benchmark results: See benches/list.rs for sequential vs parallel comparison.
- //
- // Decision: Always use parallel for simplicity and 2+ worktree performance.
- // Rayon overhead (~1-2ms) is acceptable for single-worktree case.
- //
- // TODO: Could parallelize the 5 git commands within each worktree if needed,
- // but worktree-level parallelism provides the best cost/benefit tradeoff
- let worktree_infos: Vec<WorktreeInfo> = worktrees
- .par_iter()
- .map(|wt| WorktreeInfo::from_worktree(wt, &primary))
- .collect::<Result<Vec<_>, _>>()?;
-
- // Build list of items to display (worktrees + optional branches)
- let mut items: Vec<ListItem> = worktree_infos.into_iter().map(ListItem::Worktree).collect();
-
- // Add branches if requested
- if show_branches {
- let available_branches = repo.available_branches()?;
- let primary_branch = primary.branch.as_deref();
- for branch in available_branches {
- match BranchInfo::from_branch(&branch, &repo, primary_branch) {
- Ok(branch_info) => items.push(ListItem::Branch(branch_info)),
- Err(e) => {
- let warning_bold = WARNING.bold();
- eprintln!(
- "{WARNING_EMOJI} {WARNING}Failed to enrich branch {warning_bold}{branch}{warning_bold:#}: {e}{WARNING:#}"
- );
- eprintln!(
- "{HINT_EMOJI} {HINT}This branch will be shown with limited information{HINT:#}"
- );
- }
- }
- }
- }
-
- // Sort by most recent commit (descending)
- items.sort_by_key(|item| std::cmp::Reverse(item.commit_timestamp()));
+ };
match format {
crate::OutputFormat::Json => {
- // Output JSON format
let json = serde_json::to_string_pretty(&items).map_err(|e| {
GitError::CommandFailed(format!("Failed to serialize to JSON: {}", e))
})?;
println!("{}", json);
}
crate::OutputFormat::Table => {
- // Calculate responsive layout based on terminal width
let layout = calculate_responsive_layout(&items);
-
- // Display header
format_header_line(&layout);
-
- // Display formatted output
for item in &items {
format_list_item_line(item, &layout, current_worktree_path.as_ref());
}
-
- // Display summary line
display_summary(&items, show_branches);
}
}
diff --git a/src/commands/list/model.rs b/src/commands/list/model.rs
new file mode 100644
index 000000000..eb495765e
--- /dev/null
+++ b/src/commands/list/model.rs
@@ -0,0 +1,331 @@
+use rayon::prelude::*;
+use std::path::PathBuf;
+use worktrunk::git::{GitError, Repository};
+use worktrunk::styling::{HINT, HINT_EMOJI, WARNING, WARNING_EMOJI, eprintln};
+
+#[derive(serde::Serialize)]
+pub struct WorktreeInfo {
+ pub worktree: worktrunk::git::Worktree,
+ #[serde(flatten)]
+ pub commit: CommitDetails,
+ #[serde(flatten)]
+ pub counts: AheadBehind,
+ pub working_tree_diff: (usize, usize),
+ #[serde(flatten)]
+ pub branch_diff: BranchDiffTotals,
+ pub is_primary: bool,
+ #[serde(flatten)]
+ pub upstream: UpstreamStatus,
+ pub worktree_state: Option<String>,
+}
+
+#[derive(serde::Serialize)]
+pub struct BranchInfo {
+ pub name: String,
+ pub head: String,
+ #[serde(flatten)]
+ pub commit: CommitDetails,
+ #[serde(flatten)]
+ pub counts: AheadBehind,
+ #[serde(flatten)]
+ pub branch_diff: BranchDiffTotals,
+ #[serde(flatten)]
+ pub upstream: UpstreamStatus,
+}
+
+#[derive(serde::Serialize, Clone)]
+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)]
+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)]
+pub struct BranchDiffTotals {
+ #[serde(rename = "branch_diff")]
+ pub diff: (usize, usize),
+}
+
+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)]
+pub struct UpstreamStatus {
+ #[serde(rename = "upstream_remote")]
+ remote: Option<String>,
+ #[serde(rename = "upstream_ahead")]
+ ahead: usize,
+ #[serde(rename = "upstream_behind")]
+ 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)> {
+ if self.ahead == 0 && self.behind == 0 {
+ None
+ } else {
+ Some((
+ self.remote.as_deref().unwrap_or("origin"),
+ self.ahead,
+ self.behind,
+ ))
+ }
+ }
+
+ #[cfg(test)]
+ pub fn from_parts(remote: Option<String>, ahead: usize, behind: usize) -> Self {
+ Self {
+ remote,
+ ahead,
+ behind,
+ }
+ }
+}
+
+/// Unified type for displaying worktrees and branches in the same table
+#[derive(serde::Serialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum ListItem {
+ Worktree(WorktreeInfo),
+ Branch(BranchInfo),
+}
+
+pub struct ListData {
+ pub items: Vec<ListItem>,
+ pub current_worktree_path: Option<PathBuf>,
+}
+
+impl ListItem {
+ pub fn branch_name(&self) -> &str {
+ match self {
+ ListItem::Worktree(wt) => wt.worktree.branch.as_deref().unwrap_or("(detached)"),
+ ListItem::Branch(br) => &br.name,
+ }
+ }
+
+ 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,
+ }
+ }
+
+ pub fn head(&self) -> &str {
+ match self {
+ ListItem::Worktree(info) => &info.worktree.head,
+ ListItem::Branch(info) => &info.head,
+ }
+ }
+
+ pub fn commit_details(&self) -> &CommitDetails {
+ match self {
+ ListItem::Worktree(info) => &info.commit,
+ ListItem::Branch(info) => &info.commit,
+ }
+ }
+
+ pub fn counts(&self) -> &AheadBehind {
+ match self {
+ ListItem::Worktree(info) => &info.counts,
+ ListItem::Branch(info) => &info.counts,
+ }
+ }
+
+ pub fn branch_diff(&self) -> &BranchDiffTotals {
+ match self {
+ ListItem::Worktree(info) => &info.branch_diff,
+ ListItem::Branch(info) => &info.branch_diff,
+ }
+ }
+
+ pub fn upstream(&self) -> &UpstreamStatus {
+ match self {
+ ListItem::Worktree(info) => &info.upstream,
+ ListItem::Branch(info) => &info.upstream,
+ }
+ }
+
+ pub fn worktree_info(&self) -> Option<&WorktreeInfo> {
+ match self {
+ ListItem::Worktree(info) => Some(info),
+ ListItem::Branch(_) => None,
+ }
+ }
+
+ pub fn worktree_path(&self) -> Option<&PathBuf> {
+ self.worktree_info().map(|info| &info.worktree.path)
+ }
+}
+
+impl BranchInfo {
+ /// Create BranchInfo from a branch name, enriching it with git metadata
+ fn from_branch(
+ branch: &str,
+ repo: &Repository,
+ primary_branch: Option<&str>,
+ ) -> 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)?;
+
+ Ok(BranchInfo {
+ name: branch.to_string(),
+ head,
+ commit,
+ counts,
+ branch_diff,
+ upstream,
+ })
+ }
+}
+
+impl WorktreeInfo {
+ /// Create WorktreeInfo from a Worktree, enriching it with git metadata
+ fn from_worktree(
+ wt: &worktrunk::git::Worktree,
+ primary: &worktrunk::git::Worktree,
+ ) -> 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 working_tree_diff = wt_repo.working_tree_diff_stats()?;
+ let branch_diff = BranchDiffTotals::compute(&wt_repo, base_branch, &wt.head)?;
+ let upstream = UpstreamStatus::calculate(&wt_repo, wt.branch.as_deref(), &wt.head)?;
+
+ // Get worktree state (merge/rebase/etc)
+ let worktree_state = wt_repo.worktree_state()?;
+
+ Ok(WorktreeInfo {
+ worktree: wt.clone(),
+ commit,
+ counts,
+ working_tree_diff,
+ branch_diff,
+ is_primary,
+ upstream,
+ worktree_state,
+ })
+ }
+}
+
+/// Gather list data (worktrees + optional branches).
+pub fn gather_list_data(
+ repo: &Repository,
+ show_branches: bool,
+) -> Result<Option<ListData>, GitError> {
+ let worktrees = repo.list_worktrees()?;
+
+ if worktrees.is_empty() {
+ return Ok(None);
+ }
+
+ // First worktree is the primary - clone it for use in closure
+ let primary = worktrees[0].clone();
+
+ // Get current worktree to identify active one
+ let current_worktree_path = repo.worktree_root().ok();
+
+ // Gather enhanced information for all worktrees in parallel
+ let worktree_infos: Vec<WorktreeInfo> = worktrees
+ .par_iter()
+ .map(|wt| WorktreeInfo::from_worktree(wt, &primary))
+ .collect::<Result<Vec<_>, _>>()?;
+
+ // Build list of items to display (worktrees + optional branches)
+ let mut items: Vec<ListItem> = worktree_infos.into_iter().map(ListItem::Worktree).collect();
+
+ if show_branches {
+ let available_branches = repo.available_branches()?;
+ let primary_branch = primary.branch.as_deref();
+ for branch in available_branches {
+ match BranchInfo::from_branch(&branch, repo, primary_branch) {
+ Ok(branch_info) => items.push(ListItem::Branch(branch_info)),
+ Err(e) => {
+ let warning_bold = WARNING.bold();
+ eprintln!(
+ "{WARNING_EMOJI} {WARNING}Failed to enrich branch {warning_bold}{branch}{warning_bold:#}: {e}{WARNING:#}"
+ );
+ eprintln!(
+ "{HINT_EMOJI} {HINT}This branch will be shown with limited information{HINT:#}"
+ );
+ }
+ }
+ }
+ }
+
+ // Sort by most recent commit (descending)
+ items.sort_by_key(|item| std::cmp::Reverse(item.commit_timestamp()));
+
+ Ok(Some(ListData {
+ items,
+ current_worktree_path,
+ }))
+}
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index fb6fd78e9..887d5d773 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -3,7 +3,7 @@ use anstyle::{AnsiColor, Color, Style};
use worktrunk::styling::{ADDITION, CURRENT, DELETION, StyledLine};
use super::layout::{DiffWidths, LayoutConfig};
-use super::{ListItem, WorktreeInfo};
+use super::model::{ListItem, WorktreeInfo};
/// Format diff values as styled segments (right-aligned with attached signs)
fn format_diff_column(
@@ -293,11 +293,11 @@ pub fn format_list_item_line(
#[cfg(test)]
mod tests {
- use super::super::{
- AheadBehind, BranchDiffTotals, CommitDetails, UpstreamStatus, WorktreeInfo,
- };
use super::*;
use crate::commands::list::layout::{ColumnWidths, LayoutConfig};
+ use crate::commands::list::model::{
+ AheadBehind, BranchDiffTotals, CommitDetails, UpstreamStatus, WorktreeInfo,
+ };
use crate::display::shorten_path;
use std::path::PathBuf;
use worktrunk::styling::StyledLine;
@@ -326,11 +326,7 @@ mod tests {
working_tree_diff: (100, 50),
branch_diff: BranchDiffTotals { diff: (200, 30) },
is_primary: false,
- upstream: UpstreamStatus {
- remote: Some("origin".to_string()),
- ahead: 4,
- behind: 0,
- },
+ upstream: UpstreamStatus::from_parts(Some("origin".to_string()), 4, 0),
worktree_state: None,
};
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 7e6e8b3f7..cc49f6627 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -1,11 +1,12 @@
-use worktrunk::config::{ProjectConfig, WorktrunkConfig, expand_command_template};
+use anstyle::{AnsiColor, Color};
+use worktrunk::config::{ProjectConfig, WorktrunkConfig};
use worktrunk::git::{GitError, Repository};
use worktrunk::styling::{
AnstyleStyle, CYAN, CYAN_BOLD, ERROR, ERROR_EMOJI, GREEN, GREEN_BOLD, HINT, HINT_EMOJI,
eprintln, println,
};
-use super::command_approval::{approve_command_batch, command_config_to_vec};
+use super::command_executor::{CommandContext, prepare_project_commands};
use super::worktree::handle_push;
use super::worktree::handle_remove;
use crate::output::{execute_command_in_worktree, handle_remove_output};
@@ -306,45 +307,36 @@ fn run_pre_merge_checks(
return Ok(());
};
- let commands = command_config_to_vec(pre_merge_config, "cmd");
- if commands.is_empty() {
- return Ok(());
- }
-
- let project_id = repo.project_identifier()?;
- let repo_root = repo.main_worktree_root()?;
- let repo_name = repo_root
- .file_name()
- .and_then(|n| n.to_str())
- .unwrap_or("unknown");
-
- // Approve commands (prompt if needed, save approvals)
- if !approve_command_batch(&commands, &project_id, config, force, "Pre-merge checks")? {
- return Err(GitError::CommandFailed(String::new()));
- }
-
- // Execute each command sequentially, fail-fast on errors
- for (name, command) in commands {
- let expanded_command = expand_command_template(
- &command,
- repo_name,
- current_branch,
- worktree_path,
- &repo_root,
- Some(target_branch),
- );
-
+ let ctx = CommandContext::new(repo, config, current_branch, worktree_path, force);
+ let commands = prepare_project_commands(
+ pre_merge_config,
+ "cmd",
+ &ctx,
+ false,
+ &[("target", target_branch)],
+ "Pre-merge checks",
+ |_, command| {
+ let dim = AnstyleStyle::new().dimmed();
+ eprintln!("{dim}Skipping pre-merge check: {command}{dim:#}");
+ },
+ )?;
+ for prepared in commands {
if !internal {
use std::io::Write;
- println!("🔄 {CYAN}Running pre-merge check '{name}'...{CYAN:#}");
+ let cyan = AnstyleStyle::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)));
+ println!(
+ "🔄 {cyan}Running pre-merge check '{name}'...{cyan:#}",
+ name = prepared.name
+ );
let _ = std::io::stdout().flush();
}
- if let Err(e) = execute_command_in_worktree(worktree_path, &expanded_command) {
+ if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
eprintln!();
let error_bold = ERROR.bold();
eprintln!(
- "{ERROR_EMOJI} {ERROR}Pre-merge check failed: {error_bold}{name}{error_bold:#}{ERROR:#}"
+ "{ERROR_EMOJI} {ERROR}Pre-merge check failed: {error_bold}{name}{error_bold:#}{ERROR:#}",
+ name = prepared.name,
);
eprintln!();
eprintln!(" {e}");
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index d217ae47a..9e6cd4cfb 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -1,4 +1,5 @@
pub mod command_approval;
+mod command_executor;
pub mod completion;
pub mod config;
pub mod configure_shell;
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index f69df1166..68db4a499 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -101,14 +101,14 @@
//! See also: DEMO.md for detailed architecture explanation.
use std::path::PathBuf;
-use worktrunk::config::{ProjectConfig, WorktrunkConfig, expand_command_template};
+use worktrunk::config::{ProjectConfig, WorktrunkConfig};
use worktrunk::git::{GitError, Repository};
use worktrunk::styling::{
ADDITION, AnstyleStyle, CYAN, CYAN_BOLD, DELETION, ERROR, ERROR_EMOJI, GREEN, GREEN_BOLD, HINT,
HINT_EMOJI, WARNING, WARNING_EMOJI, eprint, eprintln, format_with_gutter, println,
};
-use crate::commands::command_approval::{approve_command_batch, command_config_to_vec};
+use super::command_executor::{CommandContext, prepare_project_commands};
use crate::commands::process::spawn_detached;
use crate::output::execute_command_in_worktree;
@@ -173,7 +173,9 @@ pub fn handle_switch(
// Check if worktree already exists for this branch
match repo.worktree_for_branch(branch)? {
Some(existing_path) if existing_path.exists() => {
- return Ok(SwitchResult::ExistingWorktree(existing_path));
+ // Canonicalize the path for cleaner display
+ let canonical_existing_path = existing_path.canonicalize().unwrap_or(existing_path);
+ return Ok(SwitchResult::ExistingWorktree(canonical_existing_path));
}
Some(_) => {
let error_bold = ERROR.bold();
@@ -216,12 +218,12 @@ pub fn handle_switch(
// Execute post-create commands (sequential, blocking)
if !no_config_commands {
- execute_post_create_commands(&worktree_path, &repo, config, branch, repo_name, force)?;
+ execute_post_create_commands(&worktree_path, &repo, config, branch, force)?;
}
// Spawn post-start commands (parallel, background)
if !no_config_commands {
- spawn_post_start_commands(&worktree_path, &repo, config, branch, repo_name, force)?;
+ spawn_post_start_commands(&worktree_path, &repo, config, branch, force)?;
}
Ok(SwitchResult::CreatedWorktree {
@@ -400,19 +402,22 @@ fn check_worktree_conflicts(
Ok(())
}
+/// Helper to load project config with error handling
+fn load_project_config(repo: &Repository) -> Result<Option<ProjectConfig>, GitError> {
+ let repo_root = repo.worktree_root()?;
+ ProjectConfig::load(&repo_root)
+ .map_err(|e| GitError::CommandFailed(format!("Failed to load project config: {}", e)))
+}
+
/// Execute post-create commands sequentially (blocking)
fn execute_post_create_commands(
worktree_path: &std::path::Path,
repo: &Repository,
config: &WorktrunkConfig,
branch: &str,
- repo_name: &str,
force: bool,
) -> Result<(), GitError> {
- let repo_root = repo.worktree_root()?;
- let project_config = match ProjectConfig::load(&repo_root)
- .map_err(|e| GitError::CommandFailed(format!("Failed to load project config: {}", e)))?
- {
+ let project_config = match load_project_config(repo)? {
Some(cfg) => cfg,
None => return Ok(()),
};
@@ -421,39 +426,36 @@ fn execute_post_create_commands(
return Ok(());
};
- let commands = command_config_to_vec(post_create_config, "cmd");
- if commands.is_empty() {
- return Ok(());
- }
-
- let project_id = repo.project_identifier()?;
- let repo_root = repo.main_worktree_root()?;
-
- // Approve commands (prompt if needed, save approvals)
- if !approve_command_batch(
- &commands,
- &project_id,
- config,
- force,
+ let ctx = CommandContext::new(repo, config, branch, worktree_path, force);
+ let commands = prepare_project_commands(
+ post_create_config,
+ "cmd",
+ &ctx,
+ false,
+ &[],
"Post-create commands",
- )? {
+ |_, command| {
+ let dim = AnstyleStyle::new().dimmed();
+ eprintln!("{dim}Skipping command: {command}{dim:#}");
+ },
+ )?;
+
+ if commands.is_empty() {
return Ok(());
}
// Execute each command sequentially
- for (name, command) in commands {
- let expanded_command =
- expand_command_template(&command, repo_name, branch, worktree_path, &repo_root, None);
-
+ for prepared in commands {
use std::io::Write;
eprintln!("🔄 {CYAN}Executing (post-create):{CYAN:#}");
- eprint!("{}", format_with_gutter(&expanded_command));
+ eprint!("{}", format_with_gutter(&prepared.expanded, "")); // Gutter at column 0
let _ = std::io::stderr().flush();
- if let Err(e) = execute_command_in_worktree(worktree_path, &expanded_command) {
+ if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
let warning_bold = WARNING.bold();
eprintln!(
- "{WARNING_EMOJI} {WARNING}Command {warning_bold}{name}{warning_bold:#} failed: {e}{WARNING:#}"
+ "{WARNING_EMOJI} {WARNING}Command {warning_bold}{name}{warning_bold:#} failed: {e}{WARNING:#}",
+ name = prepared.name,
);
// Continue with other commands even if one fails
}
@@ -472,13 +474,9 @@ fn spawn_post_start_commands(
repo: &Repository,
config: &WorktrunkConfig,
branch: &str,
- repo_name: &str,
force: bool,
) -> Result<(), GitError> {
- let repo_root = repo.worktree_root()?;
- let project_config = match ProjectConfig::load(&repo_root)
- .map_err(|e| GitError::CommandFailed(format!("Failed to load project config: {}", e)))?
- {
+ let project_config = match load_project_config(repo)? {
Some(cfg) => cfg,
None => return Ok(()),
};
@@ -487,30 +485,32 @@ fn spawn_post_start_commands(
return Ok(());
};
- let commands = command_config_to_vec(post_start_config, "cmd");
- if commands.is_empty() {
- return Ok(());
- }
-
- let project_id = repo.project_identifier()?;
- let repo_root = repo.main_worktree_root()?;
+ let ctx = CommandContext::new(repo, config, branch, worktree_path, force);
+ let commands = prepare_project_commands(
+ post_start_config,
+ "cmd",
+ &ctx,
+ false,
+ &[],
+ "Post-start commands",
+ |_, command| {
+ let dim = AnstyleStyle::new().dimmed();
+ eprintln!("{dim}Skipping command: {command}{dim:#}");
+ },
+ )?;
- // Approve commands (prompt if needed, save approvals)
- if !approve_command_batch(&commands, &project_id, config, force, "Post-start commands")? {
+ if commands.is_empty() {
return Ok(());
}
// Spawn each command as a detached background process
- for (name, command) in commands {
- let expanded_command =
- expand_command_template(&command, repo_name, branch, worktree_path, &repo_root, None);
-
+ for prepared in commands {
use std::io::Write;
eprintln!("🔄 {CYAN}Starting (background):{CYAN:#}");
- eprint!("{}", format_with_gutter(&expanded_command));
+ eprint!("{}", format_with_gutter(&prepared.expanded, ""));
let _ = std::io::stderr().flush();
- match spawn_detached(worktree_path, &expanded_command, &name) {
+ match spawn_detached(worktree_path, &prepared.expanded, &prepared.name) {
Ok(log_path) => {
let dim = AnstyleStyle::new().dimmed();
// Show relative path from worktree/.git/wt-logs/
@@ -522,7 +522,10 @@ fn spawn_post_start_commands(
eprintln!("{dim}Logs: {}{dim:#}", display_path);
}
Err(e) => {
- eprintln!("{WARNING_EMOJI} {WARNING}Failed to spawn '{name}': {e}{WARNING:#}");
+ eprintln!(
+ "{WARNING_EMOJI} {WARNING}Failed to spawn '{name}': {e}{WARNING:#}",
+ name = prepared.name,
+ );
}
}
}
@@ -652,18 +655,18 @@ pub fn handle_push(
if commit_count == 1 { "" } else { "s" }
)];
- if stats.files > 0 {
+ if let Some(files) = stats.files {
summary_parts.push(format!(
"{} file{}",
- stats.files,
- if stats.files == 1 { "" } else { "s" }
+ files,
+ if files == 1 { "" } else { "s" }
));
}
- if stats.insertions > 0 {
- summary_parts.push(format!("{ADDITION}+{}{ADDITION:#}", stats.insertions));
+ if let Some(insertions) = stats.insertions {
+ summary_parts.push(format!("{ADDITION}+{insertions}{ADDITION:#}"));
}
- if stats.deletions > 0 {
- summary_parts.push(format!("{DELETION}-{}{DELETION:#}", stats.deletions));
+ if let Some(deletions) = stats.deletions {
+ summary_parts.push(format!("{DELETION}-{deletions}{DELETION:#}"));
}
println!(
@@ -680,33 +683,36 @@ pub fn handle_push(
/// Parse git diff --shortstat output
struct DiffStats {
- files: usize,
- insertions: usize,
- deletions: usize,
+ files: Option<usize>,
+ insertions: Option<usize>,
+ deletions: Option<usize>,
}
fn parse_diff_shortstat(output: &str) -> DiffStats {
let mut stats = DiffStats {
- files: 0,
- insertions: 0,
- deletions: 0,
+ files: None,
+ insertions: None,
+ deletions: None,
};
// Example: " 3 files changed, 45 insertions(+), 12 deletions(-)"
- for part in output.split(',') {
- let tokens: Vec<&str> = part.trim().split_whitespace().collect();
- if tokens.len() < 2 {
- continue;
- }
+ let parts: Vec<&str> = output.split(',').collect();
+
+ for part in parts {
+ let part = part.trim();
- if let Ok(n) = tokens[0].parse::<usize>() {
- if tokens[1].starts_with("file") {
- stats.files = n;
- } else if tokens[1].starts_with("insertion") {
- stats.insertions = n;
- } else if tokens[1].starts_with("deletion") {
- stats.deletions = n;
+ if part.contains("file") {
+ if let Some(num_str) = part.split_whitespace().next() {
+ stats.files = num_str.parse().ok();
+ }
+ } else if part.contains("insertion") {
+ if let Some(num_str) = part.split_whitespace().next() {
+ stats.insertions = num_str.parse().ok();
}
+ } else if part.contains("deletion")
+ && let Some(num_str) = part.split_whitespace().next()
+ {
+ stats.deletions = num_str.parse().ok();
}
}
diff --git a/src/styling.rs b/src/styling.rs
index 8fce7cb7d..9082af0a4 100644
--- a/src/styling.rs
+++ b/src/styling.rs
@@ -39,6 +39,22 @@ pub use anstyle::Style as AnstyleStyle;
/// Error style (red) - use as `{ERROR}text{ERROR:#}`
pub const ERROR: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red)));
+// ============================================================================
+// Message Emojis
+// ============================================================================
+
+/// Progress emoji - use with cyan style: `println!("{PROGRESS_EMOJI} {cyan}message{cyan:#}");`
+pub const PROGRESS_EMOJI: &str = "🔄";
+
+/// Error emoji - use with ERROR style: `eprintln!("{ERROR_EMOJI} {ERROR}message{ERROR:#}");`
+pub const ERROR_EMOJI: &str = "❌";
+
+/// Warning emoji - use with WARNING style: `eprintln!("{WARNING_EMOJI} {WARNING}message{WARNING:#}");`
+pub const WARNING_EMOJI: &str = "🟡";
+
+/// Hint emoji - use with HINT style: `println!("{HINT_EMOJI} {HINT}message{HINT:#}");`
+pub const HINT_EMOJI: &str = "💡";
+
/// Warning style (yellow) - use as `{WARNING}text{WARNING:#}`
pub const WARNING: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)));
@@ -72,22 +88,6 @@ pub const GREEN_BOLD: Style = Style::new()
.fg_color(Some(Color::Ansi(AnsiColor::Green)))
.bold();
-// ============================================================================
-// Message Emojis
-// ============================================================================
-
-/// Progress emoji - use with cyan style: `println!("{PROGRESS_EMOJI} {cyan}message{cyan:#}");`
-pub const PROGRESS_EMOJI: &str = "🔄";
-
-/// Error emoji - use with ERROR style: `eprintln!("{ERROR_EMOJI} {ERROR}message{ERROR:#}");`
-pub const ERROR_EMOJI: &str = "❌";
-
-/// Warning emoji - use with WARNING style: `eprintln!("{WARNING_EMOJI} {WARNING}message{WARNING:#}");`
-pub const WARNING_EMOJI: &str = "🟡";
-
-/// Hint emoji - use with HINT style: `println!("{HINT_EMOJI} {HINT}message{HINT:#}");`
-pub const HINT_EMOJI: &str = "💡";
-
// ============================================================================
// Styled Output Types
// ============================================================================
@@ -185,20 +185,22 @@ impl StyledLine {
///
/// # Arguments
/// * `content` - The text to format (preserves internal structure for multi-line)
+/// * `left_margin` - Should always be "" (gutter provides all visual separation)
///
/// The gutter appears at column 0, followed by 1 space, then the content at column 1.
///
/// # Example
/// ```ignore
-/// print!("{}", format_with_gutter(&config));
-/// print!("{}", format_with_gutter(&command));
+/// // All contexts use empty left margin
+/// print!("{}", format_with_gutter(&config, ""));
+/// print!("{}", format_with_gutter(&command, ""));
/// ```
-pub fn format_with_gutter(content: &str) -> String {
+pub fn format_with_gutter(content: &str, left_margin: &str) -> String {
let gutter = Style::new().bg_color(Some(Color::Ansi(AnsiColor::Black)));
let mut output = String::new();
for line in content.lines() {
- output.push_str(&format!("{gutter} {gutter:#} {line}\n"));
+ output.push_str(&format!("{left_margin}{gutter} {gutter:#} {line}\n"));
}
output
@@ -209,7 +211,7 @@ pub fn format_with_gutter(content: &str) -> String {
// ============================================================================
/// Formats TOML content with syntax highlighting using synoptic
-pub fn format_toml(content: &str) -> String {
+pub fn format_toml(content: &str, left_margin: &str) -> String {
// Gutter style: subtle background for visual separation
let gutter = Style::new().bg_color(Some(Color::Ansi(AnsiColor::Black)));
@@ -221,7 +223,9 @@ pub fn format_toml(content: &str) -> String {
let dim = Style::new().dimmed();
let mut output = String::new();
for line in content.lines() {
- output.push_str(&format!("{gutter} {gutter:#} {dim}{line}{dim:#}\n"));
+ output.push_str(&format!(
+ "{left_margin}{gutter} {gutter:#} {dim}{line}{dim:#}\n"
+ ));
}
return output;
}
@@ -235,8 +239,8 @@ pub fn format_toml(content: &str) -> String {
// Render each line with appropriate styling
for (y, line) in lines.iter().enumerate() {
- // Add gutter and spacing
- output.push_str(&format!("{gutter} {gutter:#} "));
+ // Add left margin, gutter, and spacing
+ output.push_str(&format!("{left_margin}{gutter} {gutter:#} "));
// Render each token with appropriate styling
for token in highlighter.line(y, line) {
@@ -313,7 +317,7 @@ project = "github.com/user/repo"
command = "npm install"
"#;
- let output = format_toml(toml_content);
+ let output = format_toml(toml_content, "");
// Check that output contains ANSI escape codes
assert!(