Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor: Move diff-related parsing and rendering to methods
Maximilian Roos71473c3b47f5
diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex 03e05cc82..d1454ea9b 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -1,10 +1,9 @@-use worktrunk::HookType;-use worktrunk::config::{CommandPhase, CommitGenerationConfig, ProjectConfig};+use worktrunk::config::CommitGenerationConfig;use worktrunk::git::{GitError, GitResultExt, Repository};use worktrunk::styling::{AnstyleStyle, CYAN, GREEN, HINT, format_with_gutter};use super::command_executor::CommandContext;-use super::hooks::{HookFailureStrategy, HookPipeline};+use super::hooks::HookPipeline;use super::repository_ext::RepositoryCliExt;/// Options for committing current changes.@@ -33,155 +32,121 @@ impl<'a> CommitOptions<'a> {}}-/// Format a commit message with the first line in bold, ready for gutter display.-pub fn format_commit_message_for_display(message: &str) -> String {- let bold = AnstyleStyle::new().bold();- let lines: Vec<&str> = message.lines().collect();+pub(crate) struct CommitGenerator<'a> {+ config: &'a CommitGenerationConfig,+}- if lines.is_empty() {- return String::new();+impl<'a> CommitGenerator<'a> {+ pub fn new(config: &'a CommitGenerationConfig) -> Self {+ Self { config }}- let mut result = format!("{bold}{}{bold:#}", lines[0]);+ pub fn format_message_for_display(&self, message: &str) -> String {+ let bold = AnstyleStyle::new().bold();+ let lines: Vec<&str> = message.lines().collect();- if lines.len() > 1 {- for line in &lines[1..] {- result.push('\n');- result.push_str(line);+ if lines.is_empty() {+ return String::new();}- }- result-}+ let mut result = format!("{bold}{}{bold:#}", lines[0]);-/// Show hint if no LLM command is configured.-pub fn show_llm_config_hint_if_needed(- commit_generation_config: &CommitGenerationConfig,-) -> Result<(), GitError> {- if !commit_generation_config.is_configured() {- crate::output::hint(format!(- "{HINT}Using fallback commit message. Run 'wt config help' to configure LLM-generated messages{HINT:#}"- ))?;+ if lines.len() > 1 {+ for line in &lines[1..] {+ result.push('\n');+ result.push_str(line);+ }+ }++ result}- Ok(())-}-/// Commit already-staged changes with LLM-generated or fallback message.-pub fn commit_staged_changes(- commit_generation_config: &CommitGenerationConfig,- show_no_squash_note: bool,-) -> Result<(), GitError> {- let repo = Repository::current();+ pub fn emit_hint_if_needed(&self) -> Result<(), GitError> {+ if !self.config.is_configured() {+ crate::output::hint(format!(+ "{HINT}Using fallback commit message. Run 'wt config help' to configure LLM-generated messages{HINT:#}"+ ))?;+ }+ Ok(())+ }- let stats_parts = repo.diff_stats_summary(&["diff", "--staged", "--shortstat"]);+ pub fn commit_staged_changes(&self, show_no_squash_note: bool) -> Result<(), GitError> {+ let repo = Repository::current();- let action = if commit_generation_config.is_configured() {- "Generating commit message and committing..."- } else {- "Committing with default message..."- };+ let stats_parts = repo.diff_stats_summary(&["diff", "--staged", "--shortstat"]);- let mut parts = vec![];- if !stats_parts.is_empty() {- parts.extend(stats_parts);- }- if show_no_squash_note {- parts.push("no squashing needed".to_string());- }+ let action = if self.config.is_configured() {+ "Generating commit message and committing..."+ } else {+ "Committing with default message..."+ };- let full_progress_msg = if parts.is_empty() {- format!("{CYAN}{action}{CYAN:#}")- } else {- format!("{CYAN}{action}{CYAN:#} ({})", parts.join(", "))- };+ let mut parts = vec![];+ if !stats_parts.is_empty() {+ parts.extend(stats_parts);+ }+ if show_no_squash_note {+ parts.push("no squashing needed".to_string());+ }- crate::output::progress(full_progress_msg)?;+ let full_progress_msg = if parts.is_empty() {+ format!("{CYAN}{action}{CYAN:#}")+ } else {+ format!("{CYAN}{action}{CYAN:#} ({})", parts.join(", "))+ };- show_llm_config_hint_if_needed(commit_generation_config)?;- let commit_message = crate::llm::generate_commit_message(commit_generation_config)?;+ crate::output::progress(full_progress_msg)?;- let formatted_message = format_commit_message_for_display(&commit_message);- crate::output::gutter(format_with_gutter(&formatted_message, "", None))?;+ self.emit_hint_if_needed()?;+ let commit_message = crate::llm::generate_commit_message(self.config)?;- repo.run_command(&["commit", "-m", &commit_message])- .git_context("Failed to commit")?;+ let formatted_message = self.format_message_for_display(&commit_message);+ crate::output::gutter(format_with_gutter(&formatted_message, "", None))?;- let commit_hash = repo- .run_command(&["rev-parse", "--short", "HEAD"])?- .trim()- .to_string();+ repo.run_command(&["commit", "-m", &commit_message])+ .git_context("Failed to commit")?;- let green_dim = GREEN.dimmed();- crate::output::success(format!(- "{GREEN}Committed changes @ {green_dim}{commit_hash}{green_dim:#}{GREEN:#}"- ))?;+ let commit_hash = repo+ .run_command(&["rev-parse", "--short", "HEAD"])?+ .trim()+ .to_string();- Ok(())-}+ let green_dim = GREEN.dimmed();+ crate::output::success(format!(+ "{GREEN}Committed changes @ {green_dim}{commit_hash}{green_dim:#}{GREEN:#}"+ ))?;-/// Commit uncommitted changes with the shared commit pipeline.-pub fn commit_changes(options: CommitOptions<'_>) -> Result<(), GitError> {- if !options.no_verify- && let Some(project_config) = options.ctx.repo.load_project_config()?- {- run_pre_commit_commands(- &project_config,- options.ctx,- options.target_branch,- options.auto_trust,- )?;+ Ok(())}+}- if options.warn_about_untracked && !options.tracked_only {- options.ctx.repo.warn_if_auto_staging_untracked()?;- }+/// Commit uncommitted changes with the shared commit pipeline.+impl CommitOptions<'_> {+ pub fn commit(self) -> Result<(), GitError> {+ if !self.no_verify+ && let Some(project_config) = self.ctx.repo.load_project_config()?+ {+ let pipeline = HookPipeline::new(*self.ctx);+ pipeline.run_pre_commit(&project_config, self.target_branch, self.auto_trust)?;+ }- if options.tracked_only {- options- .ctx- .repo- .run_command(&["add", "-u"])- .git_context("Failed to stage tracked changes")?;- } else {- options- .ctx- .repo- .run_command(&["add", "-A"])- .git_context("Failed to stage changes")?;- }+ if self.warn_about_untracked && !self.tracked_only {+ self.ctx.repo.warn_if_auto_staging_untracked()?;+ }- commit_staged_changes(- &options.ctx.config.commit_generation,- options.show_no_squash_note,- )-}+ if self.tracked_only {+ self.ctx+ .repo+ .run_command(&["add", "-u"])+ .git_context("Failed to stage tracked changes")?;+ } else {+ self.ctx+ .repo+ .run_command(&["add", "-A"])+ .git_context("Failed to stage changes")?;+ }-/// Run pre-commit commands sequentially (blocking, fail-fast).-pub fn run_pre_commit_commands(- project_config: &ProjectConfig,- ctx: &CommandContext,- target_branch: Option<&str>,- auto_trust: bool,-) -> Result<(), GitError> {- let Some(pre_commit_config) = &project_config.pre_commit_command else {- return Ok(());- };-- let pipeline = HookPipeline::new(*ctx);-- let extra_vars: Vec<(&str, &str)> = target_branch- .into_iter()- .map(|target| ("target", target))- .collect();-- pipeline.run_sequential(- pre_commit_config,- CommandPhase::PreCommit,- auto_trust,- &extra_vars,- "pre-commit",- HookFailureStrategy::FailFast {- hook_type: HookType::PreCommit,- },- )+ CommitGenerator::new(&self.ctx.config.commit_generation)+ .commit_staged_changes(self.show_no_squash_note)+ }}diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 648bb52a5..94d641680 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -1,5 +1,5 @@use worktrunk::HookType;-use worktrunk::config::{CommandConfig, CommandPhase};+use worktrunk::config::{CommandConfig, CommandPhase, ProjectConfig};use worktrunk::git::GitError;use worktrunk::styling::{CYAN, WARNING, WARNING_BOLD, format_bash_with_gutter};@@ -126,4 +126,31 @@ impl<'a> HookPipeline<'a> {crate::output::flush()?;Ok(())}++ pub fn run_pre_commit(+ &self,+ project_config: &ProjectConfig,+ target_branch: Option<&str>,+ auto_trust: bool,+ ) -> Result<(), GitError> {+ let Some(pre_commit_config) = &project_config.pre_commit_command else {+ return Ok(());+ };++ let extra_vars: Vec<(&str, &str)> = target_branch+ .into_iter()+ .map(|target| ("target", target))+ .collect();++ self.run_sequential(+ pre_commit_config,+ CommandPhase::PreCommit,+ auto_trust,+ &extra_vars,+ "pre-commit",+ HookFailureStrategy::FailFast {+ hook_type: HookType::PreCommit,+ },+ )+ }}diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rsindex c7a6eae8a..7a5c11c95 100644--- a/src/commands/list/layout.rs+++ b/src/commands/list/layout.rs@@ -547,18 +547,19 @@ pub fn calculate_column_widths(items: &[ListItem], fetch_ci: bool) -> LayoutMeta// Working tree diff (worktrees only) - track digits separatelyif let Some(info) = worktree_info- && (info.working_tree_diff.0 > 0 || info.working_tree_diff.1 > 0)+ && !info.working_tree_diff.is_empty(){max_wt_added_digits =- max_wt_added_digits.max(info.working_tree_diff.0.to_string().len());+ max_wt_added_digits.max(info.working_tree_diff.added.to_string().len());max_wt_deleted_digits =- max_wt_deleted_digits.max(info.working_tree_diff.1.to_string().len());+ max_wt_deleted_digits.max(info.working_tree_diff.deleted.to_string().len());}// Branch diff (only for non-primary items) - track digits separately- if !item.is_primary() && (branch_diff.0 > 0 || branch_diff.1 > 0) {- max_br_added_digits = max_br_added_digits.max(branch_diff.0.to_string().len());- max_br_deleted_digits = max_br_deleted_digits.max(branch_diff.1.to_string().len());+ if !item.is_primary() && !branch_diff.is_empty() {+ max_br_added_digits = max_br_added_digits.max(branch_diff.added.to_string().len());+ max_br_deleted_digits =+ max_br_deleted_digits.max(branch_diff.deleted.to_string().len());}// Upstream tracking - track digits only (not remote name yet)@@ -833,6 +834,7 @@ mod tests {use super::*;use crate::commands::list::columns::ColumnKind;use std::path::PathBuf;+ use worktrunk::git::LineDiff;#[test]fn test_column_width_calculation_with_unicode() {@@ -859,9 +861,11 @@ mod tests {ahead: 3,behind: 2,},- working_tree_diff: (100, 50),- working_tree_diff_with_main: Some((0, 0)),- branch_diff: BranchDiffTotals { diff: (200, 30) },+ working_tree_diff: LineDiff::from((100, 50)),+ working_tree_diff_with_main: Some(LineDiff::default()),+ branch_diff: BranchDiffTotals {+ diff: LineDiff::from((200, 30)),+ },is_primary: false,upstream: UpstreamStatus::from_parts(Some("origin".to_string()), 4, 0),worktree_state: None,@@ -935,9 +939,11 @@ mod tests {ahead: 5,behind: 10,},- working_tree_diff: (100, 50),- working_tree_diff_with_main: Some((0, 0)),- branch_diff: BranchDiffTotals { diff: (200, 30) },+ working_tree_diff: LineDiff::from((100, 50)),+ working_tree_diff_with_main: Some(LineDiff::default()),+ branch_diff: BranchDiffTotals {+ diff: LineDiff::from((200, 30)),+ },is_primary: false,upstream: UpstreamStatus::from_parts(Some("origin".to_string()), 4, 2),worktree_state: None,@@ -1010,9 +1016,11 @@ mod tests {ahead: 0,behind: 0,},- working_tree_diff: (0, 0),- working_tree_diff_with_main: Some((0, 0)),- branch_diff: BranchDiffTotals { diff: (0, 0) },+ working_tree_diff: LineDiff::default(),+ working_tree_diff_with_main: Some(LineDiff::default()),+ branch_diff: BranchDiffTotals {+ diff: LineDiff::default(),+ },is_primary: true, // Primary worktree: no ahead/behind shownupstream: UpstreamStatus::default(),worktree_state: None,@@ -1076,12 +1084,14 @@ mod tests {ahead: 0,behind: 0,},- working_tree_diff: (0, 0), // Empty: no dirty changes- working_tree_diff_with_main: Some((0, 0)),- branch_diff: BranchDiffTotals { diff: (0, 0) }, // Empty: no diff- is_primary: true, // Empty: no ahead/behind for primary- upstream: UpstreamStatus::default(), // Empty: no upstream- worktree_state: None, // Empty: no state+ working_tree_diff: LineDiff::default(), // Empty: no dirty changes+ working_tree_diff_with_main: Some(LineDiff::default()),+ branch_diff: BranchDiffTotals {+ diff: LineDiff::default(),+ }, // Empty: no diff+ is_primary: true, // Empty: no ahead/behind for primary+ upstream: UpstreamStatus::default(), // Empty: no upstream+ worktree_state: None, // Empty: no statepr_status: None,has_conflicts: false,status_symbols: StatusSymbols::default(),diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex e36f0f173..d07d76fb9 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -11,40 +11,11 @@ mod status_column_tests;use super::repository_ext::RepositoryCliExt;use columns::ColumnKind;-use layout::calculate_responsive_layout;-use model::{ListData, ListItem};+use layout::{LayoutConfig, calculate_responsive_layout};+use model::{DisplayFields, ListData, ListItem};use worktrunk::git::{GitError, Repository};use worktrunk::styling::{INFO_EMOJI, println};-/// Helper to enrich common display fields shared between worktrees and branches-fn enrich_common_fields(- counts: &model::AheadBehind,- branch_diff: &model::BranchDiffTotals,- upstream: &model::UpstreamStatus,- pr_status: &Option<ci_status::PrStatus>,-) -> model::DisplayFields {- let commits_display = ColumnKind::AheadBehind.format_diff_plain(counts.ahead, counts.behind);-- let (added, deleted) = branch_diff.diff;- let branch_diff_display = ColumnKind::BranchDiff.format_diff_plain(added, deleted);-- let upstream_display = upstream- .active()- .and_then(|(_, upstream_ahead, upstream_behind)| {- ColumnKind::Upstream.format_diff_plain(upstream_ahead, upstream_behind)- });-- let ci_status_display = pr_status.as_ref().map(ci_status::PrStatus::format_plain);-- model::DisplayFields {- commits_display,- branch_diff_display,- upstream_display,- ci_status_display,- status_display: None, // Status display is populated in WorktreeInfo/BranchInfo constructors- }-}-pub fn handle_list(format: crate::OutputFormat,show_branches: bool,@@ -77,69 +48,13 @@ pub fn handle_list(for item in &items {layout.format_list_item_line(item, current_worktree_path.as_ref());}- display_summary(&items, show_branches, &layout);+ layout.render_summary(&items, show_branches);}}Ok(())}-fn display_summary(items: &[ListItem], include_branches: bool, layout: &layout::LayoutConfig) {- use anstyle::Style;-- if items.is_empty() {- println!();- use worktrunk::styling::{HINT, HINT_EMOJI};- println!("{HINT_EMOJI} {HINT}No worktrees found{HINT:#}");- println!("{HINT_EMOJI} {HINT}Create one with: wt switch --create <branch>{HINT:#}");- return;- }-- let mut metrics = SummaryMetrics::default();- for item in items {- metrics.update(item);- }-- println!();- let dim = Style::new().dimmed();-- // Build summary parts- let mut parts = Vec::new();-- if include_branches {- parts.push(format!("{} worktrees", metrics.worktrees));- if metrics.branches > 0 {- parts.push(format!("{} branches", metrics.branches));- }- } else {- let plural = if metrics.worktrees == 1 { "" } else { "s" };- parts.push(format!("{} worktree{}", metrics.worktrees, plural));- }-- if metrics.dirty_worktrees > 0 {- parts.push(format!("{} with changes", metrics.dirty_worktrees));- }-- if metrics.ahead_items > 0 {- parts.push(format!("{} ahead", metrics.ahead_items));- }-- if layout.hidden_nonempty_count > 0 {- let plural = if layout.hidden_nonempty_count == 1 {- "column"- } else {- "columns"- };- parts.push(format!(- "{} {} hidden",- layout.hidden_nonempty_count, plural- ));- }-- let summary = parts.join(", ");- println!("{INFO_EMOJI} {dim}Showing {summary}{dim:#}");-}-#[derive(Default)]struct SummaryMetrics {worktrees: usize,@@ -152,8 +67,7 @@ impl SummaryMetrics {fn update(&mut self, item: &ListItem) {if let Some(info) = item.worktree_info() {self.worktrees += 1;- let (added, deleted) = info.working_tree_diff;- if added > 0 || deleted > 0 {+ if !info.working_tree_diff.is_empty() {self.dirty_worktrees += 1;}} else {@@ -167,12 +81,66 @@ impl SummaryMetrics {}}+impl LayoutConfig {+ fn render_summary(&self, items: &[ListItem], include_branches: bool) {+ use anstyle::Style;++ if items.is_empty() {+ println!();+ use worktrunk::styling::{HINT, HINT_EMOJI};+ println!("{HINT_EMOJI} {HINT}No worktrees found{HINT:#}");+ println!("{HINT_EMOJI} {HINT}Create one with: wt switch --create <branch>{HINT:#}");+ return;+ }++ let mut metrics = SummaryMetrics::default();+ for item in items {+ metrics.update(item);+ }++ println!();+ let dim = Style::new().dimmed();++ let mut parts = Vec::new();++ if include_branches {+ parts.push(format!("{} worktrees", metrics.worktrees));+ if metrics.branches > 0 {+ parts.push(format!("{} branches", metrics.branches));+ }+ } else {+ let plural = if metrics.worktrees == 1 { "" } else { "s" };+ parts.push(format!("{} worktree{}", metrics.worktrees, plural));+ }++ if metrics.dirty_worktrees > 0 {+ parts.push(format!("{} with changes", metrics.dirty_worktrees));+ }++ if metrics.ahead_items > 0 {+ parts.push(format!("{} ahead", metrics.ahead_items));+ }++ if self.hidden_nonempty_count > 0 {+ let plural = if self.hidden_nonempty_count == 1 {+ "column"+ } else {+ "columns"+ };+ parts.push(format!("{} {} hidden", self.hidden_nonempty_count, plural));+ }++ let summary = parts.join(", ");+ println!("{INFO_EMOJI} {dim}Showing {summary}{dim:#}");+ }+}+impl ListItem {/// Enrich a ListItem with display fields for json-pretty format.fn with_display_fields(mut self) -> Self {match &mut self {ListItem::Worktree(info) => {- let mut display = enrich_common_fields(+ let mut display = DisplayFields::from_common_fields(&info.counts,&info.branch_diff,&info.upstream,@@ -183,12 +151,13 @@ impl ListItem {info.display = display;// Working tree specific field- let (added, deleted) = info.working_tree_diff;- info.working_diff_display =- ColumnKind::WorkingDiff.format_diff_plain(added, deleted);+ info.working_diff_display = ColumnKind::WorkingDiff.format_diff_plain(+ info.working_tree_diff.added,+ info.working_tree_diff.deleted,+ );}ListItem::Branch(info) => {- let mut display = enrich_common_fields(+ let mut display = DisplayFields::from_common_fields(&info.counts,&info.branch_diff,&info.upstream,diff --git a/src/commands/list/model.rs b/src/commands/list/model.rsindex 129e3ac0f..18bef6817 100644--- a/src/commands/list/model.rs+++ b/src/commands/list/model.rs@@ -1,7 +1,8 @@use std::path::PathBuf;-use worktrunk::git::{GitError, Repository};+use worktrunk::git::{GitError, LineDiff, Repository};use super::ci_status::PrStatus;+use super::columns::ColumnKind;/// Display fields shared between WorktreeInfo and BranchInfo/// These contain formatted strings with ANSI colors for json-pretty output@@ -19,6 +20,38 @@ pub struct DisplayFields {pub status_display: Option<String>,}+impl DisplayFields {+ pub(crate) fn from_common_fields(+ counts: &AheadBehind,+ branch_diff: &BranchDiffTotals,+ upstream: &UpstreamStatus,+ pr_status: &Option<PrStatus>,+ ) -> Self {+ let commits_display =+ ColumnKind::AheadBehind.format_diff_plain(counts.ahead, counts.behind);++ let branch_diff_display = ColumnKind::BranchDiff+ .format_diff_plain(branch_diff.diff.added, branch_diff.diff.deleted);++ let upstream_display =+ upstream+ .active()+ .and_then(|(_, upstream_ahead, upstream_behind)| {+ ColumnKind::Upstream.format_diff_plain(upstream_ahead, upstream_behind)+ });++ let ci_status_display = pr_status.as_ref().map(PrStatus::format_plain);++ Self {+ commits_display,+ branch_diff_display,+ upstream_display,+ ci_status_display,+ status_display: None,+ }+ }+}+#[derive(serde::Serialize)]pub struct WorktreeInfo {pub worktree: worktrunk::git::Worktree,@@ -26,13 +59,13 @@ pub struct WorktreeInfo {pub commit: CommitDetails,#[serde(flatten)]pub counts: AheadBehind,- pub working_tree_diff: (usize, usize),+ pub working_tree_diff: LineDiff,/// Diff between working tree and main branch./// `None` means "not computed" (optimization: skipped when trees differ)./// `Some((0, 0))` means working tree matches main exactly./// `Some((a, d))` means a lines added, d deleted vs main.#[serde(skip_serializing_if = "Option::is_none")]- pub working_tree_diff_with_main: Option<(usize, usize)>,+ pub working_tree_diff_with_main: Option<LineDiff>,#[serde(flatten)]pub branch_diff: BranchDiffTotals,pub is_primary: bool,@@ -112,7 +145,7 @@ impl AheadBehind {#[derive(serde::Serialize, Default, Clone)]pub struct BranchDiffTotals {#[serde(rename = "branch_diff")]- pub diff: (usize, usize),+ pub diff: LineDiff,}impl BranchDiffTotals {@@ -271,8 +304,10 @@ impl ListItem {let counts = self.counts();if let Some(info) = self.worktree_info() {- let no_commits_and_clean = counts.ahead == 0 && info.working_tree_diff == (0, 0);- let matches_main = info.working_tree_diff_with_main == Some((0, 0));+ let no_commits_and_clean = counts.ahead == 0 && info.working_tree_diff.is_empty();+ let matches_main = info+ .working_tree_diff_with_main+ .is_some_and(|diff| diff.is_empty());no_commits_and_clean || matches_main} else {counts.ahead == 0@@ -837,7 +872,7 @@ impl WorktreeInfo {let working_tree_diff = if status_info.is_dirty {wt_repo.working_tree_diff_stats()?} else {- (0, 0) // Clean working tree+ LineDiff::default() // Clean working tree};// Use tree equality check instead of expensive diff for "matches main"@@ -860,7 +895,7 @@ impl WorktreeInfo {Some(wt_repo.working_tree_diff_vs_ref(base)?)} else {// Trees match and working tree is clean → matches main exactly- Some((0, 0))+ Some(LineDiff::default())}} else {// Trees differ - skip the expensive scan@@ -868,7 +903,7 @@ impl WorktreeInfo {None}} else {- Some((0, 0)) // Primary worktree always matches itself+ Some(LineDiff::default()) // Primary worktree always matches itself};let branch_diff = BranchDiffTotals::compute(&wt_repo, base_branch, &wt.head)?;@@ -906,9 +941,9 @@ impl WorktreeInfo {// Branch state: ≡ matches main, ∅ no commits (mutually exclusive)if !is_primary {- if working_tree_diff_with_main == Some((0, 0)) {+ if working_tree_diff_with_main.is_some_and(|diff| diff.is_empty()) {symbols.branch_state = BranchState::MatchesMain;- } else if counts.ahead == 0 && working_tree_diff == (0, 0) {+ } else if counts.ahead == 0 && working_tree_diff.is_empty() {symbols.branch_state = BranchState::NoCommits;}}diff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex 006b1c198..41a952d25 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -11,47 +11,46 @@ use super::layout::{use super::model::{AheadBehind, CommitDetails, ListItem, PositionMask, UpstreamStatus, WorktreeInfo,};+use worktrunk::git::LineDiff;-fn format_plain_diff_from_config(- positive: usize,- negative: usize,- config: DiffDisplayConfig,-) -> Option<String> {- if !config.always_show_zeros && positive == 0 && negative == 0 {- return None;- }+impl DiffDisplayConfig {+ fn format_plain(&self, positive: usize, negative: usize) -> Option<String> {+ if !self.always_show_zeros && positive == 0 && negative == 0 {+ return None;+ }- let (positive_symbol, negative_symbol) = match config.variant {- DiffVariant::Signs => ("+", "-"),- DiffVariant::Arrows => ("↑", "↓"),- };-- let mut parts = Vec::with_capacity(2);-- if positive > 0 || config.always_show_zeros {- parts.push(format!(- "{}{}{}{}",- config.positive_style,- positive_symbol,- positive,- config.positive_style.render_reset()- ));- }+ let (positive_symbol, negative_symbol) = match self.variant {+ DiffVariant::Signs => ("+", "-"),+ DiffVariant::Arrows => ("↑", "↓"),+ };- if negative > 0 || config.always_show_zeros {- parts.push(format!(- "{}{}{}{}",- config.negative_style,- negative_symbol,- negative,- config.negative_style.render_reset()- ));- }+ let mut parts = Vec::with_capacity(2);- if parts.is_empty() {- None- } else {- Some(parts.join(" "))+ if positive > 0 || self.always_show_zeros {+ parts.push(format!(+ "{}{}{}{}",+ self.positive_style,+ positive_symbol,+ positive,+ self.positive_style.render_reset()+ ));+ }++ if negative > 0 || self.always_show_zeros {+ parts.push(format!(+ "{}{}{}{}",+ self.negative_style,+ negative_symbol,+ negative,+ self.negative_style.render_reset()+ ));+ }++ if parts.is_empty() {+ None+ } else {+ Some(parts.join(" "))+ }}}@@ -60,7 +59,7 @@ impl ColumnKind {pub(crate) fn format_diff_plain(self, positive: usize, negative: usize) -> Option<String> {let config = self.diff_display_config()?;- format_plain_diff_from_config(positive, negative, config)+ config.format_plain(positive, negative)}}@@ -117,76 +116,76 @@ struct DiffRenderConfig {align: ValueAlign,}-fn diff_render_config(variant: DiffVariant) -> DiffRenderConfig {- match variant {- DiffVariant::Signs => DiffRenderConfig {- positive_symbol: "+",- negative_symbol: "-",- align: ValueAlign::Right,- },- DiffVariant::Arrows => DiffRenderConfig {- positive_symbol: "↑",- negative_symbol: "↓",- align: ValueAlign::Left,- },+impl DiffVariant {+ fn render_config(self) -> DiffRenderConfig {+ match self {+ DiffVariant::Signs => DiffRenderConfig {+ positive_symbol: "+",+ negative_symbol: "-",+ align: ValueAlign::Right,+ },+ DiffVariant::Arrows => DiffRenderConfig {+ positive_symbol: "↑",+ negative_symbol: "↓",+ align: ValueAlign::Left,+ },+ }}}-fn format_diff_like_column(- positive: usize,- negative: usize,- config: DiffColumnConfig,-) -> StyledLine {- let render_config = diff_render_config(config.display.variant);- let mut segment = StyledLine::new();-- if positive == 0 && negative == 0 && !config.display.always_show_zeros {- segment.push_raw(" ".repeat(config.total_width));- return segment;- }+impl DiffColumnConfig {+ fn render_segment(&self, positive: usize, negative: usize) -> StyledLine {+ let render_config = self.display.variant.render_config();+ let mut segment = StyledLine::new();- let positive_width = 1 + config.digits.added;- let negative_width = 1 + config.digits.deleted;- let content_width = positive_width + 1 + negative_width;- let extra_padding = config.total_width.saturating_sub(content_width);+ if positive == 0 && negative == 0 && !self.display.always_show_zeros {+ segment.push_raw(" ".repeat(self.total_width));+ return segment;+ }- if matches!(render_config.align, ValueAlign::Right) && extra_padding > 0 {- segment.push_raw(" ".repeat(extra_padding));- }+ let positive_width = 1 + self.digits.added;+ let negative_width = 1 + self.digits.deleted;+ let content_width = positive_width + 1 + negative_width;+ let extra_padding = self.total_width.saturating_sub(content_width);- if positive > 0 || (positive == 0 && config.display.always_show_zeros) {- let value = format!("{}{}", render_config.positive_symbol, positive);- let formatted = match render_config.align {- ValueAlign::Right => format!("{:>width$}", value, width = positive_width),- ValueAlign::Left => format!("{:<width$}", value, width = positive_width),- };- segment.push_styled(formatted, config.display.positive_style);- } else {- segment.push_raw(" ".repeat(positive_width));- }+ if matches!(render_config.align, ValueAlign::Right) && extra_padding > 0 {+ segment.push_raw(" ".repeat(extra_padding));+ }- segment.push_raw(" ");+ if positive > 0 || (positive == 0 && self.display.always_show_zeros) {+ let value = format!("{}{}", render_config.positive_symbol, positive);+ let formatted = match render_config.align {+ ValueAlign::Right => format!("{:>width$}", value, width = positive_width),+ ValueAlign::Left => format!("{:<width$}", value, width = positive_width),+ };+ segment.push_styled(formatted, self.display.positive_style);+ } else {+ segment.push_raw(" ".repeat(positive_width));+ }- if negative > 0 || (negative == 0 && config.display.always_show_zeros) {- let value = format!("{}{}", render_config.negative_symbol, negative);- let formatted = match render_config.align {- ValueAlign::Right => format!("{:>width$}", value, width = negative_width),- ValueAlign::Left => format!("{:<width$}", value, width = negative_width),- };- segment.push_styled(formatted, config.display.negative_style);- } else {- segment.push_raw(" ".repeat(negative_width));- }+ segment.push_raw(" ");- if matches!(render_config.align, ValueAlign::Left) && extra_padding > 0 {- segment.pad_to(segment.width() + extra_padding);- }+ if negative > 0 || (negative == 0 && self.display.always_show_zeros) {+ let value = format!("{}{}", render_config.negative_symbol, negative);+ let formatted = match render_config.align {+ ValueAlign::Right => format!("{:>width$}", value, width = negative_width),+ ValueAlign::Left => format!("{:<width$}", value, width = negative_width),+ };+ segment.push_styled(formatted, self.display.negative_style);+ } else {+ segment.push_raw(" ".repeat(negative_width));+ }- if segment.width() < config.total_width {- segment.pad_to(config.total_width);- }+ if matches!(render_config.align, ValueAlign::Left) && extra_padding > 0 {+ segment.pad_to(segment.width() + extra_padding);+ }- segment+ if segment.width() < self.total_width {+ segment.pad_to(self.total_width);+ }++ segment+ }}impl LayoutConfig {@@ -250,7 +249,7 @@ struct ListRowContext<'a> {item: &'a ListItem,worktree_info: Option<&'a WorktreeInfo>,counts: &'a AheadBehind,- branch_diff: (usize, usize),+ branch_diff: LineDiff,upstream: &'a UpstreamStatus,commit: &'a CommitDetails,head: &'a str,@@ -316,7 +315,7 @@ impl ColumnLayout {debug_assert_eq!(config.total_width, self.width);- format_diff_like_column(positive, negative, config)+ config.render_segment(positive, negative)}fn render_cell(@@ -360,11 +359,10 @@ impl ColumnLayout {cell}ColumnKind::WorkingDiff => {- let Some((added, deleted)) = ctx.worktree_info.map(|info| info.working_tree_diff)- else {+ let Some(diff) = ctx.worktree_info.map(|info| info.working_tree_diff) else {return StyledLine::new();};- self.render_diff_cell(added, deleted)+ self.render_diff_cell(diff.added, diff.deleted)}ColumnKind::AheadBehind => {if ctx.item.is_primary() {@@ -381,7 +379,7 @@ impl ColumnLayout {if ctx.item.is_primary() {return StyledLine::new();}- self.render_diff_cell(ctx.branch_diff.0, ctx.branch_diff.1)+ self.render_diff_cell(ctx.branch_diff.added, ctx.branch_diff.deleted)}ColumnKind::Path => {let Some(info) = ctx.worktree_info else {@@ -435,6 +433,14 @@ mod tests {use crate::commands::list::layout::{DiffDigits, DiffDisplayConfig};use worktrunk::styling::{ADDITION, DELETION, StyledLine};+ fn format_diff_like_column(+ positive: usize,+ negative: usize,+ config: DiffColumnConfig,+ ) -> StyledLine {+ config.render_segment(positive, negative)+ }+#[test]fn test_format_diff_column_pads_to_total_width() {use super::super::columns::DiffVariant;diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 428e738d0..d57a8c317 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -5,7 +5,7 @@ use worktrunk::styling::{CYAN, CYAN_BOLD, ERROR, ERROR_EMOJI, GREEN_BOLD, HINT,use super::command_approval::approve_command_batch;use super::command_executor::CommandContext;-use super::commit::{CommitOptions, commit_changes};+use super::commit::CommitOptions;use super::context::CommandEnv;use super::hooks::{HookFailureStrategy, HookPipeline};use super::project_config::collect_commands_for_hooks;@@ -119,7 +119,7 @@ pub fn handle_merge(options.warn_about_untracked = !tracked_only;options.show_no_squash_note = true;- commit_changes(options)?;+ options.commit()?;true // Committed directly}} else {diff --git a/src/commands/standalone.rs b/src/commands/standalone.rsindex 9083119ce..491670dc6 100644--- a/src/commands/standalone.rs+++ b/src/commands/standalone.rs@@ -4,11 +4,9 @@ use worktrunk::styling::{AnstyleStyle, CYAN, CYAN_BOLD, GREEN_BOLD, HINT, HINT_EMOJI, eprintln, format_with_gutter,};-use super::commit::{- CommitOptions, commit_changes, commit_staged_changes, format_commit_message_for_display,- run_pre_commit_commands, show_llm_config_hint_if_needed,-};+use super::commit::{CommitGenerator, CommitOptions};use super::context::CommandEnv;+use super::hooks::HookPipeline;use super::merge::{execute_post_merge_commands, run_pre_merge_commands};use super::project_config::collect_commands_for_hooks;use super::repository_ext::RepositoryCliExt;@@ -40,12 +38,7 @@ pub fn handle_standalone_run_hook(hook_type: HookType, force: bool) -> Result<()check_hook_configured(&project_config.pre_commit_command, hook_type)?;// Pre-commit hook can optionally use target branch contextlet target_branch = repo.default_branch().ok();- run_pre_commit_commands(- &project_config,- &ctx,- target_branch.as_deref(),- false, // auto_trust: standalone command, needs approval- )+ HookPipeline::new(ctx).run_pre_commit(&project_config, target_branch.as_deref(), false)}HookType::PreMerge => {check_hook_configured(&project_config.pre_merge_command, hook_type)?;@@ -81,7 +74,7 @@ pub fn handle_standalone_commit(force: bool, no_verify: bool) -> Result<(), GitEoptions.auto_trust = false;options.show_no_squash_note = false;- commit_changes(options)+ options.commit()}/// Handle shared squash workflow (used by `wt beta squash` and `wt merge`)@@ -104,6 +97,7 @@ pub fn handle_squash(let repo = &env.repo;let current_branch = env.branch.clone();let ctx = env.context(force);+ let generator = CommitGenerator::new(&env.config.commit_generation);// Get target branch (default to default branch if not provided)let target_branch = repo.resolve_target_branch(target)?;@@ -123,7 +117,7 @@ pub fn handle_squash(// Run pre-commit hook unless explicitly skippedif !skip_pre_commit && let Some(project_config) = repo.load_project_config()? {- run_pre_commit_commands(&project_config, &ctx, Some(&target_branch), auto_trust)?;+ HookPipeline::new(ctx).run_pre_commit(&project_config, Some(&target_branch), auto_trust)?;}// Get merge base with target branch@@ -143,7 +137,7 @@ pub fn handle_squash(if commit_count == 0 && has_staged {// Just staged changes, no commits - commit them directly (no squashing needed)- commit_staged_changes(&env.config.commit_generation, true)?;+ generator.commit_staged_changes(true)?;return Ok(true);}@@ -184,7 +178,7 @@ pub fn handle_squash(// Generate squash commit messagecrate::output::progress(format!("{CYAN}Generating squash commit message...{CYAN:#}"))?;- show_llm_config_hint_if_needed(&env.config.commit_generation)?;+ generator.emit_hint_if_needed()?;// Get current branch and repo name for template variableslet repo_root = repo.worktree_root()?;@@ -203,7 +197,7 @@ pub fn handle_squash(.git_context("Failed to generate commit message")?;// Display the generated commit message- let formatted_message = format_commit_message_for_display(&commit_message);+ let formatted_message = generator.format_message_for_display(&commit_message);crate::output::gutter(format_with_gutter(&formatted_message, "", None))?;// Reset to merge base (soft reset stages all changes, including any already-staged uncommitted changes)diff --git a/src/git/diff.rs b/src/git/diff.rsindex 8d1913ea6..2362a3f14 100644--- a/src/git/diff.rs+++ b/src/git/diff.rs@@ -1,7 +1,76 @@//! Git diff utilities for parsing and formatting diff statistics.+use super::GitError;use crate::styling::{ADDITION, DELETION};+/// Line-level diff totals (added/deleted counts) used across git operations.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize)]+pub struct LineDiff {+ pub added: usize,+ pub deleted: usize,+}++impl LineDiff {+ /// Parse `git diff --numstat` output into aggregated line totals.+ pub fn from_numstat(output: &str) -> Result<Self, GitError> {+ let mut totals = LineDiff::default();++ for line in output.lines() {+ if line.trim().is_empty() {+ continue;+ }++ let mut parts = line.split('\t');+ let Some(added_str) = parts.next() else {+ continue;+ };+ let Some(deleted_str) = parts.next() else {+ continue;+ };++ // Binary files show "-" for added/deleted+ if added_str == "-" || deleted_str == "-" {+ continue;+ }++ let Ok(added) = added_str.parse::<usize>() else {+ continue;+ };+ let Ok(deleted) = deleted_str.parse::<usize>() else {+ continue;+ };++ totals.added += added;+ totals.deleted += deleted;+ }++ Ok(totals)+ }++ pub fn is_empty(&self) -> bool {+ self.added == 0 && self.deleted == 0+ }++ pub fn into_tuple(self) -> (usize, usize) {+ (self.added, self.deleted)+ }+}++impl From<LineDiff> for (usize, usize) {+ fn from(diff: LineDiff) -> Self {+ diff.into_tuple()+ }+}++impl From<(usize, usize)> for LineDiff {+ fn from(value: (usize, usize)) -> Self {+ Self {+ added: value.0,+ deleted: value.1,+ }+ }+}+/// Parse git diff --shortstat output#[derive(Debug)]pub struct DiffStats {@@ -11,6 +80,38 @@ pub struct DiffStats {}impl DiffStats {+ /// Construct stats from `git diff --shortstat` output.+ pub fn from_shortstat(output: &str) -> Self {+ let mut stats = DiffStats {+ files: None,+ insertions: None,+ deletions: None,+ };++ // Example: " 3 files changed, 45 insertions(+), 12 deletions(-)"+ let parts: Vec<&str> = output.split(',').collect();++ for part in parts {+ let part = part.trim();++ 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();+ }+ }++ stats+ }+/// Format stats as a summary string (e.g., "3 files, +45, -12")pub fn format_summary(&self) -> Vec<String> {let mut parts = Vec::new();@@ -32,34 +133,3 @@ impl DiffStats {parts}}--pub fn parse_diff_shortstat(output: &str) -> DiffStats {- let mut stats = DiffStats {- files: None,- insertions: None,- deletions: None,- };-- // Example: " 3 files changed, 45 insertions(+), 12 deletions(-)"- let parts: Vec<&str> = output.split(',').collect();-- for part in parts {- let part = part.trim();-- 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();- }- }-- stats-}diff --git a/src/git/mod.rs b/src/git/mod.rsindex afe78aa55..dc3352525 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -12,14 +12,12 @@ mod repository;mod test;// Re-exports from submodules-pub use diff::{DiffStats, parse_diff_shortstat};+pub use diff::{DiffStats, LineDiff};pub use error::GitError;pub use repository::{GitResultExt, Repository};-// Re-export parsing functions for internal use-pub(crate) use parse::{- parse_local_default_branch, parse_numstat, parse_remote_default_branch, parse_worktree_list,-};+// Re-export parsing helpers for internal use+pub(crate) use parse::DefaultBranchName;// Note: HookType, Worktree, and WorktreeList are defined in this module and are already public.// They're accessible as git::HookType, git::Worktree, and git::WorktreeList without needing re-export.diff --git a/src/git/parse.rs b/src/git/parse.rsindex 96ea6c93d..bee14dfe3 100644--- a/src/git/parse.rs+++ b/src/git/parse.rs@@ -4,147 +4,124 @@ use std::path::PathBuf;use super::{GitError, Worktree, finalize_worktree};-pub(crate) fn parse_worktree_list(output: &str) -> Result<Vec<Worktree>, GitError> {- let mut worktrees = Vec::new();- let mut current: Option<Worktree> = None;-- for line in output.lines() {- if line.is_empty() {- if let Some(wt) = current.take() {- worktrees.push(finalize_worktree(wt));+impl Worktree {+ pub(crate) fn parse_porcelain_list(output: &str) -> Result<Vec<Self>, GitError> {+ let mut worktrees = Vec::new();+ let mut current: Option<Worktree> = None;++ for line in output.lines() {+ if line.is_empty() {+ if let Some(wt) = current.take() {+ worktrees.push(finalize_worktree(wt));+ }+ continue;}- continue;- }- let (key, value) = match line.split_once(' ') {- Some((k, v)) => (k, Some(v)),- None => (line, None),- };+ let (key, value) = match line.split_once(' ') {+ Some((k, v)) => (k, Some(v)),+ None => (line, None),+ };- match key {- "worktree" => {- let path = value.ok_or_else(|| {- GitError::ParseError("worktree line missing path".to_string())- })?;- current = Some(Worktree {- path: PathBuf::from(path),- head: String::new(),- branch: None,- bare: false,- detached: false,- locked: None,- prunable: None,- });- }- key => match (key, current.as_mut()) {- ("HEAD", Some(wt)) => {- wt.head = value- .ok_or_else(|| GitError::ParseError("HEAD line missing SHA".to_string()))?- .to_string();- }- ("branch", Some(wt)) => {- // Strip refs/heads/ prefix if present- let branch_ref = value.ok_or_else(|| {- GitError::ParseError("branch line missing ref".to_string())+ match key {+ "worktree" => {+ let path = value.ok_or_else(|| {+ GitError::ParseError("worktree line missing path".to_string())})?;- let branch = branch_ref- .strip_prefix("refs/heads/")- .unwrap_or(branch_ref)- .to_string();- wt.branch = Some(branch);- }- ("bare", Some(wt)) => {- wt.bare = true;+ current = Some(Worktree {+ path: PathBuf::from(path),+ head: String::new(),+ branch: None,+ bare: false,+ detached: false,+ locked: None,+ prunable: None,+ });}- ("detached", Some(wt)) => {- wt.detached = true;- }- ("locked", Some(wt)) => {- wt.locked = Some(value.unwrap_or_default().to_string());- }- ("prunable", Some(wt)) => {- wt.prunable = Some(value.unwrap_or_default().to_string());- }- _ => {- // Ignore unknown attributes or attributes before first worktree- }- },+ key => match (key, current.as_mut()) {+ ("HEAD", Some(wt)) => {+ wt.head = value+ .ok_or_else(|| {+ GitError::ParseError("HEAD line missing SHA".to_string())+ })?+ .to_string();+ }+ ("branch", Some(wt)) => {+ // Strip refs/heads/ prefix if present+ let branch_ref = value.ok_or_else(|| {+ GitError::ParseError("branch line missing ref".to_string())+ })?;+ let branch = branch_ref+ .strip_prefix("refs/heads/")+ .unwrap_or(branch_ref)+ .to_string();+ wt.branch = Some(branch);+ }+ ("bare", Some(wt)) => {+ wt.bare = true;+ }+ ("detached", Some(wt)) => {+ wt.detached = true;+ }+ ("locked", Some(wt)) => {+ wt.locked = Some(value.unwrap_or_default().to_string());+ }+ ("prunable", Some(wt)) => {+ wt.prunable = Some(value.unwrap_or_default().to_string());+ }+ _ => {+ // Ignore unknown attributes or attributes before first worktree+ }+ },+ }}- }- // Push the last worktree if the output doesn't end with a blank line- if let Some(wt) = current {- worktrees.push(finalize_worktree(wt));- }-- Ok(worktrees)-}--pub(crate) fn parse_local_default_branch(output: &str, remote: &str) -> Result<String, GitError> {- let trimmed = output.trim();-- // Strip "remote/" prefix if present- let prefix = format!("{}/", remote);- let branch = trimmed.strip_prefix(&prefix).unwrap_or(trimmed);+ // Push the last worktree if the output doesn't end with a blank line+ if let Some(wt) = current {+ worktrees.push(finalize_worktree(wt));+ }- if branch.is_empty() {- return Err(GitError::ParseError(format!(- "Empty branch name from {}/HEAD",- remote- )));+ Ok(worktrees)}-- Ok(branch.to_string())-}--pub(crate) fn parse_remote_default_branch(output: &str) -> Result<String, GitError> {- output- .lines()- .find_map(|line| {- line.strip_prefix("ref: ")- .and_then(|symref| symref.split_once('\t'))- .map(|(ref_path, _)| ref_path)- .and_then(|ref_path| ref_path.strip_prefix("refs/heads/"))- .map(|branch| branch.to_string())- })- .ok_or_else(|| {- GitError::ParseError("Could not find symbolic ref in ls-remote output".to_string())- })}-pub(crate) fn parse_numstat(output: &str) -> Result<(usize, usize), GitError> {- let mut total_added = 0;- let mut total_deleted = 0;+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct DefaultBranchName(String);- for line in output.lines() {- if line.trim().is_empty() {- continue;- }+impl DefaultBranchName {+ pub(crate) fn from_local(remote: &str, output: &str) -> Result<Self, GitError> {+ let trimmed = output.trim();- let mut parts = line.split('\t');- let Some(added_str) = parts.next() else {- continue;- };- let Some(deleted_str) = parts.next() else {- continue;- };+ // Strip "remote/" prefix if present+ let prefix = format!("{}/", remote);+ let branch = trimmed.strip_prefix(&prefix).unwrap_or(trimmed);- // Binary files show "-" for added/deleted- if added_str == "-" || deleted_str == "-" {- continue;+ if branch.is_empty() {+ return Err(GitError::ParseError(format!(+ "Empty branch name from {}/HEAD",+ remote+ )));}- // Skip malformed lines (e.g., missing tabs) by treating parse errors as non-fatal- let Ok(added) = added_str.parse::<usize>() else {- continue;- };- let Ok(deleted) = deleted_str.parse::<usize>() else {- continue;- };+ Ok(Self(branch.to_string()))+ }- total_added += added;- total_deleted += deleted;+ pub(crate) fn from_remote(output: &str) -> Result<Self, GitError> {+ output+ .lines()+ .find_map(|line| {+ line.strip_prefix("ref: ")+ .and_then(|symref| symref.split_once('\t'))+ .map(|(ref_path, _)| ref_path)+ .and_then(|ref_path| ref_path.strip_prefix("refs/heads/"))+ .map(|branch| branch.to_string())+ })+ .map(Self)+ .ok_or_else(|| {+ GitError::ParseError("Could not find symbolic ref in ls-remote output".to_string())+ })}- Ok((total_added, total_deleted))+ pub(crate) fn into_string(self) -> String {+ self.0+ }}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex baf07a893..9029b4d66 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -4,10 +4,7 @@ use std::process::{Command, Stdio};use std::sync::OnceLock;// Import types and functions from parent module (mod.rs)-use super::{- GitError, WorktreeList, parse_local_default_branch, parse_numstat, parse_remote_default_branch,- parse_worktree_list,-};+use super::{DefaultBranchName, DiffStats, GitError, LineDiff, Worktree, WorktreeList};/// Extension trait for Result types to simplify GitError conversions///@@ -534,11 +531,9 @@ impl Repository {}/// Get line diff statistics for working tree changes (unstaged + staged).- ///- /// Returns (added_lines, deleted_lines).- pub fn working_tree_diff_stats(&self) -> Result<(usize, usize), GitError> {+ pub fn working_tree_diff_stats(&self) -> Result<LineDiff, GitError> {let stdout = self.run_command(&["diff", "--numstat", "HEAD"])?;- parse_numstat(&stdout)+ LineDiff::from_numstat(&stdout)}/// Get line diff statistics between working tree and a specific ref.@@ -546,19 +541,17 @@ impl Repository {/// This compares the current working tree contents (including uncommitted changes)/// against the specified ref, regardless of what HEAD points to.///- /// Returns (added_lines, deleted_lines).- pub fn working_tree_diff_vs_ref(&self, ref_name: &str) -> Result<(usize, usize), GitError> {+ pub fn working_tree_diff_vs_ref(&self, ref_name: &str) -> Result<LineDiff, GitError> {let stdout = self.run_command(&["diff", "--numstat", ref_name])?;- parse_numstat(&stdout)+ LineDiff::from_numstat(&stdout)}/// Get line diff statistics between two refs (using three-dot diff for merge base).///- /// Returns (added_lines, deleted_lines).- pub fn branch_diff_stats(&self, base: &str, head: &str) -> Result<(usize, usize), GitError> {+ pub fn branch_diff_stats(&self, base: &str, head: &str) -> Result<LineDiff, GitError> {let range = format!("{}...{}", base, head);let stdout = self.run_command(&["diff", "--numstat", &range])?;- parse_numstat(&stdout)+ LineDiff::from_numstat(&stdout)}/// Get formatted diff stats summary for display.@@ -570,10 +563,7 @@ impl Repository {pub fn diff_stats_summary(&self, args: &[&str]) -> Vec<String> {self.run_command(args).ok()- .map(|output| {- use crate::git::parse_diff_shortstat;- parse_diff_shortstat(&output).format_summary()- })+ .map(|output| DiffStats::from_shortstat(&output).format_summary()).unwrap_or_default()}@@ -635,7 +625,7 @@ impl Repository {/// and provides access to the primary worktree.pub fn list_worktrees(&self) -> Result<WorktreeList, GitError> {let stdout = self.run_command(&["worktree", "list", "--porcelain"])?;- let raw_worktrees = parse_worktree_list(&stdout)?;+ let raw_worktrees = Worktree::parse_porcelain_list(&stdout)?;WorktreeList::from_raw(raw_worktrees)}@@ -712,12 +702,12 @@ impl Repository {fn get_local_default_branch(&self, remote: &str) -> Result<String, GitError> {let stdout =self.run_command(&["rev-parse", "--abbrev-ref", &format!("{}/HEAD", remote)])?;- parse_local_default_branch(&stdout, remote)+ DefaultBranchName::from_local(remote, &stdout).map(DefaultBranchName::into_string)}fn query_remote_default_branch(&self, remote: &str) -> Result<String, GitError> {let stdout = self.run_command(&["ls-remote", "--symref", remote, "HEAD"])?;- parse_remote_default_branch(&stdout)+ DefaultBranchName::from_remote(&stdout).map(DefaultBranchName::into_string)}fn cache_default_branch(&self, remote: &str, branch: &str) -> Result<(), GitError> {diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex b0e47f8ae..31f04421a 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -1,9 +1,6 @@use std::path::PathBuf;-use super::super::{- Worktree, finalize_worktree, parse_local_default_branch, parse_remote_default_branch,- parse_worktree_list,-};+use super::super::{DefaultBranchName, Worktree, finalize_worktree};use super::*;#[test]@@ -18,7 +15,7 @@ branch refs/heads/feature";- let worktrees = parse_worktree_list(output).unwrap();+ let worktrees = Worktree::parse_porcelain_list(output).unwrap();assert_eq!(worktrees.len(), 2);assert_eq!(worktrees[0].path, PathBuf::from("/path/to/main"));@@ -40,7 +37,7 @@ detached";- let worktrees = parse_worktree_list(output).unwrap();+ let worktrees = Worktree::parse_porcelain_list(output).unwrap();assert_eq!(worktrees.len(), 1);assert!(worktrees[0].detached);assert_eq!(worktrees[0].branch, None);@@ -111,7 +108,7 @@ locked reason for lock";- let worktrees = parse_worktree_list(output).unwrap();+ let worktrees = Worktree::parse_porcelain_list(output).unwrap();assert_eq!(worktrees.len(), 1);assert_eq!(worktrees[0].locked, Some("reason for lock".to_string()));}@@ -124,7 +121,7 @@ bare";- let worktrees = parse_worktree_list(output).unwrap();+ let worktrees = Worktree::parse_porcelain_list(output).unwrap();assert_eq!(worktrees.len(), 1);assert!(worktrees[0].bare);}@@ -132,42 +129,53 @@ bare#[test]fn test_parse_local_default_branch_with_prefix() {let output = "origin/main\n";- let branch = parse_local_default_branch(output, "origin").unwrap();+ let branch = DefaultBranchName::from_local("origin", output)+ .map(DefaultBranchName::into_string)+ .unwrap();assert_eq!(branch, "main");}#[test]fn test_parse_local_default_branch_without_prefix() {let output = "main\n";- let branch = parse_local_default_branch(output, "origin").unwrap();+ let branch = DefaultBranchName::from_local("origin", output)+ .map(DefaultBranchName::into_string)+ .unwrap();assert_eq!(branch, "main");}#[test]fn test_parse_local_default_branch_master() {let output = "origin/master\n";- let branch = parse_local_default_branch(output, "origin").unwrap();+ let branch = DefaultBranchName::from_local("origin", output)+ .map(DefaultBranchName::into_string)+ .unwrap();assert_eq!(branch, "master");}#[test]fn test_parse_local_default_branch_custom_name() {let output = "origin/develop\n";- let branch = parse_local_default_branch(output, "origin").unwrap();+ let branch = DefaultBranchName::from_local("origin", output)+ .map(DefaultBranchName::into_string)+ .unwrap();assert_eq!(branch, "develop");}#[test]fn test_parse_local_default_branch_custom_remote() {let output = "upstream/main\n";- let branch = parse_local_default_branch(output, "upstream").unwrap();+ let branch = DefaultBranchName::from_local("upstream", output)+ .map(DefaultBranchName::into_string)+ .unwrap();assert_eq!(branch, "main");}#[test]fn test_parse_local_default_branch_empty() {let output = "";- let result = parse_local_default_branch(output, "origin");+ let result =+ DefaultBranchName::from_local("origin", output).map(DefaultBranchName::into_string);assert!(result.is_err());assert!(matches!(result.unwrap_err(), GitError::ParseError(_)));}@@ -175,7 +183,8 @@ fn test_parse_local_default_branch_empty() {#[test]fn test_parse_local_default_branch_whitespace_only() {let output = " \n ";- let result = parse_local_default_branch(output, "origin");+ let result =+ DefaultBranchName::from_local("origin", output).map(DefaultBranchName::into_string);assert!(result.is_err());}@@ -184,7 +193,9 @@ fn test_parse_remote_default_branch_main() {let output = "ref: refs/heads/main\tHEAD85a1ce7c7182540f9c02453441cb3e8bf0ced214\tHEAD";- let branch = parse_remote_default_branch(output).unwrap();+ let branch = DefaultBranchName::from_remote(output)+ .map(DefaultBranchName::into_string)+ .unwrap();assert_eq!(branch, "main");}@@ -193,7 +204,9 @@ fn test_parse_remote_default_branch_master() {let output = "ref: refs/heads/master\tHEADabcd1234567890abcd1234567890abcd12345678\tHEAD";- let branch = parse_remote_default_branch(output).unwrap();+ let branch = DefaultBranchName::from_remote(output)+ .map(DefaultBranchName::into_string)+ .unwrap();assert_eq!(branch, "master");}@@ -202,21 +215,25 @@ fn test_parse_remote_default_branch_custom() {let output = "ref: refs/heads/develop\tHEAD1234567890abcdef1234567890abcdef12345678\tHEAD";- let branch = parse_remote_default_branch(output).unwrap();+ let branch = DefaultBranchName::from_remote(output)+ .map(DefaultBranchName::into_string)+ .unwrap();assert_eq!(branch, "develop");}#[test]fn test_parse_remote_default_branch_only_symref_line() {let output = "ref: refs/heads/main\tHEAD\n";- let branch = parse_remote_default_branch(output).unwrap();+ let branch = DefaultBranchName::from_remote(output)+ .map(DefaultBranchName::into_string)+ .unwrap();assert_eq!(branch, "main");}#[test]fn test_parse_remote_default_branch_missing_symref() {let output = "85a1ce7c7182540f9c02453441cb3e8bf0ced214\tHEAD\n";- let result = parse_remote_default_branch(output);+ let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);assert!(result.is_err());assert!(matches!(result.unwrap_err(), GitError::ParseError(_)));}@@ -224,7 +241,7 @@ fn test_parse_remote_default_branch_missing_symref() {#[test]fn test_parse_remote_default_branch_empty() {let output = "";- let result = parse_remote_default_branch(output);+ let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);assert!(result.is_err());}@@ -232,7 +249,7 @@ fn test_parse_remote_default_branch_empty() {fn test_parse_remote_default_branch_malformed_ref() {// Missing refs/heads/ prefixlet output = "ref: main\tHEAD\n";- let result = parse_remote_default_branch(output);+ let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);assert!(result.is_err());}@@ -240,7 +257,7 @@ fn test_parse_remote_default_branch_malformed_ref() {fn test_parse_remote_default_branch_with_spaces() {// Space instead of tab - should be rejected as malformed inputlet output = "ref: refs/heads/main HEAD\n";- let result = parse_remote_default_branch(output);+ let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);// Using split_once correctly rejects malformed input with spaces instead of tabsassert!(result.is_err());}@@ -248,6 +265,8 @@ fn test_parse_remote_default_branch_with_spaces() {#[test]fn test_parse_remote_default_branch_branch_with_slash() {let output = "ref: refs/heads/feature/new-ui\tHEAD\n";- let branch = parse_remote_default_branch(output).unwrap();+ let branch = DefaultBranchName::from_remote(output)+ .map(DefaultBranchName::into_string)+ .unwrap();assert_eq!(branch, "feature/new-ui");}diff --git a/src/git/test.rs b/src/git/test.rsindex f564e7217..98a8446b6 100644--- a/src/git/test.rs+++ b/src/git/test.rs@@ -3,15 +3,12 @@//! These tests target edge cases and error conditions in git output parsing//! that are likely to reveal bugs in real-world usage.-use super::{- GitError, parse_local_default_branch, parse_numstat, parse_remote_default_branch,- parse_worktree_list,-};+use super::{DefaultBranchName, GitError, LineDiff, Worktree};#[test]fn test_parse_worktree_list_empty_output() {// Bug hypothesis: Empty output might not be handled correctly- let result = parse_worktree_list("");+ let result = Worktree::parse_porcelain_list("");assert!(result.is_ok(), "Empty output should parse successfully");assert_eq!(result.unwrap().len(), 0, "Should return empty vector");}@@ -21,7 +18,7 @@ fn test_parse_worktree_list_missing_head() {// Bug hypothesis: Worktree without HEAD field might have empty string for head// This could cause issues when the head field is used laterlet output = "worktree /path/to/repo\nbranch refs/heads/main\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok(), "Should parse even without HEAD field");let worktrees = result.unwrap();@@ -41,7 +38,7 @@ fn test_parse_worktree_list_locked_with_empty_reason() {// Current code: `locked = Some(value.unwrap_or_default().to_string())`// This means locked with no value becomes Some("")let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok());let worktrees = result.unwrap();@@ -67,7 +64,7 @@ fn test_parse_worktree_list_locked_with_reason() {// Verify normal locked behavior workslet output ="worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked working on it\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok());let worktrees = result.unwrap();@@ -79,7 +76,7 @@ fn test_parse_worktree_list_locked_with_reason() {fn test_parse_worktree_list_prunable_empty() {// Same issue as locked - prunable with no valuelet output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nprunable\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok());let worktrees = result.unwrap();@@ -95,7 +92,7 @@ fn test_parse_worktree_list_fields_before_worktree() {// Bug hypothesis: If we get HEAD/branch lines before a worktree line,// they'll be silently ignored because current is Nonelet output = "HEAD abc123\nbranch refs/heads/main\nworktree /path/to/repo\nHEAD def456\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok());let worktrees = result.unwrap();@@ -111,7 +108,7 @@ fn test_parse_worktree_list_no_trailing_blank_line() {// the last worktree might not be added// Looking at the code (lines 1128-1130), this should be handled correctlylet output = "worktree /path/to/repo1\nHEAD abc123\nbranch refs/heads/main\n\nworktree /path/to/repo2\nHEAD def456\nbranch refs/heads/dev";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok());let worktrees = result.unwrap();@@ -127,7 +124,7 @@ fn test_parse_worktree_list_no_trailing_blank_line() {#[test]fn test_parse_worktree_list_bare_repository() {let output = "worktree /path/to/repo\nbare\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok());let worktrees = result.unwrap();@@ -138,7 +135,7 @@ fn test_parse_worktree_list_bare_repository() {#[test]fn test_parse_worktree_list_detached_head() {let output = "worktree /path/to/repo\nHEAD abc123\ndetached\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok());let worktrees = result.unwrap();@@ -149,7 +146,7 @@ fn test_parse_worktree_list_detached_head() {#[test]fn test_parse_worktree_list_branch_with_refs_prefix() {let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/feature/nested/branch\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok());let worktrees = result.unwrap();@@ -167,7 +164,7 @@ fn test_parse_worktree_list_branch_with_refs_prefix() {fn test_parse_worktree_list_branch_without_refs_prefix() {// Bug hypothesis: What if git returns branch without refs/heads/ prefix?let output = "worktree /path/to/repo\nHEAD abc123\nbranch main\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok());let worktrees = result.unwrap();@@ -179,7 +176,7 @@ fn test_parse_worktree_list_branch_without_refs_prefix() {fn test_parse_worktree_list_unknown_attributes() {// Forward compatibility - unknown attributes should be ignoredlet output = "worktree /path/to/repo\nHEAD abc123\nfutureattr somevalue\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok(),@@ -192,7 +189,7 @@ fn test_parse_worktree_list_unknown_attributes() {#[test]fn test_parse_worktree_list_multiple_worktrees() {let output = "worktree /path/to/main\nHEAD abc123\nbranch refs/heads/main\n\nworktree /path/to/feature\nHEAD def456\nbranch refs/heads/feature\ndetached\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);assert!(result.is_ok());let worktrees = result.unwrap();@@ -209,7 +206,7 @@ fn test_parse_worktree_list_multiple_worktrees() {fn test_parse_worktree_list_worktree_missing_path() {// Bug hypothesis: "worktree" line with no path should errorlet output = "worktree\nHEAD abc123\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);// Current code: value.ok_or_else(|| GitError::ParseError("worktree line missing path"))assert!(result.is_err(), "Worktree without path should error");@@ -228,7 +225,7 @@ fn test_parse_worktree_list_worktree_missing_path() {fn test_parse_worktree_list_head_missing_sha() {// Bug hypothesis: "HEAD" line with no SHA should errorlet output = "worktree /path/to/repo\nHEAD\nbranch refs/heads/main\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);// Current code: value.ok_or_else(|| GitError::ParseError("HEAD line missing SHA"))assert!(result.is_err(), "HEAD without SHA should error");@@ -247,7 +244,7 @@ fn test_parse_worktree_list_head_missing_sha() {fn test_parse_worktree_list_branch_missing_ref() {// Bug hypothesis: "branch" line with no ref should errorlet output = "worktree /path/to/repo\nHEAD abc123\nbranch\n\n";- let result = parse_worktree_list(output);+ let result = Worktree::parse_porcelain_list(output);// Current code: value.ok_or_else(|| GitError::ParseError("branch line missing ref"))assert!(result.is_err(), "Branch without ref should error");@@ -268,7 +265,7 @@ fn test_parse_worktree_list_branch_missing_ref() {fn test_parse_remote_default_branch_normal() {// Normal git ls-remote output for HEADlet output = "ref: refs/heads/main\tHEAD\n";- let result = parse_remote_default_branch(output);+ let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);assert!(result.is_ok());assert_eq!(result.unwrap(), "main");@@ -278,7 +275,7 @@ fn test_parse_remote_default_branch_normal() {fn test_parse_remote_default_branch_with_feature_branch() {// Remote default is a feature branch with slasheslet output = "ref: refs/heads/feature/nested/branch\tHEAD\n";- let result = parse_remote_default_branch(output);+ let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);assert!(result.is_ok());assert_eq!(result.unwrap(), "feature/nested/branch");@@ -288,7 +285,7 @@ fn test_parse_remote_default_branch_with_feature_branch() {fn test_parse_remote_default_branch_empty_output() {// Bug hypothesis: Empty output should error, not paniclet output = "";- let result = parse_remote_default_branch(output);+ let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);assert!(result.is_err(), "Empty output should return an error");match result {@@ -306,7 +303,7 @@ fn test_parse_remote_default_branch_empty_output() {fn test_parse_remote_default_branch_no_ref_prefix() {// Bug hypothesis: Line without "ref: " prefix should be ignoredlet output = "refs/heads/main\tHEAD\n";- let result = parse_remote_default_branch(output);+ let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);// Should error because no line matches the patternassert!(result.is_err());@@ -317,7 +314,7 @@ fn test_parse_remote_default_branch_missing_tab() {// Bug hypothesis: What if there's no tab separator?// Looking at the code: line.split_once('\t') returns None, so line is ignoredlet output = "ref: refs/heads/main";- let result = parse_remote_default_branch(output);+ let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);// Should error because split_once returns Noneassert!(result.is_err(), "Missing tab should cause error");@@ -327,7 +324,7 @@ fn test_parse_remote_default_branch_missing_tab() {fn test_parse_remote_default_branch_multiple_lines() {// Bug hypothesis: Multiple matching lines - should use first matchlet output = "ref: refs/heads/main\tHEAD\nref: refs/heads/develop\tHEAD\n";- let result = parse_remote_default_branch(output);+ let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);assert!(result.is_ok());// find_map returns first match@@ -339,7 +336,7 @@ fn test_parse_remote_default_branch_missing_refs_heads_prefix() {// Bug hypothesis: What if the ref doesn't have refs/heads/ prefix?// Looking at the code: strip_prefix returns None, so line is ignoredlet output = "ref: main\tHEAD\n";- let result = parse_remote_default_branch(output);+ let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);// Should error because strip_prefix failsassert!(result.is_err());@@ -349,7 +346,8 @@ fn test_parse_remote_default_branch_missing_refs_heads_prefix() {#[test]fn test_parse_local_default_branch_normal() {- let result = parse_local_default_branch("origin/main", "origin");+ let result =+ DefaultBranchName::from_local("origin", "origin/main").map(DefaultBranchName::into_string);assert!(result.is_ok());assert_eq!(result.unwrap(), "main");@@ -358,7 +356,8 @@ fn test_parse_local_default_branch_normal() {#[test]fn test_parse_local_default_branch_without_remote_prefix() {// Bug hypothesis: If output doesn't have remote prefix, just return it as-is- let result = parse_local_default_branch("main", "origin");+ let result =+ DefaultBranchName::from_local("origin", "main").map(DefaultBranchName::into_string);assert!(result.is_ok());// strip_prefix fails, so unwrap_or returns original@@ -369,7 +368,8 @@ fn test_parse_local_default_branch_without_remote_prefix() {fn test_parse_local_default_branch_with_nested_slashes() {// Bug hypothesis: Branch name like "feature/sub/branch" might break if we have// multiple slashes. Let's verify it works correctly.- let result = parse_local_default_branch("origin/feature/sub/branch", "origin");+ let result = DefaultBranchName::from_local("origin", "origin/feature/sub/branch")+ .map(DefaultBranchName::into_string);assert!(result.is_ok());// Should strip only "origin/" prefix, leaving "feature/sub/branch"@@ -379,7 +379,7 @@ fn test_parse_local_default_branch_with_nested_slashes() {#[test]fn test_parse_local_default_branch_empty_output() {// Bug hypothesis: Empty string after trimming should error- let result = parse_local_default_branch("", "origin");+ let result = DefaultBranchName::from_local("origin", "").map(DefaultBranchName::into_string);assert!(result.is_err(), "Empty output should error");match result {@@ -396,7 +396,8 @@ fn test_parse_local_default_branch_empty_output() {#[test]fn test_parse_local_default_branch_whitespace_only() {// Bug hypothesis: Whitespace-only input should error after trim- let result = parse_local_default_branch(" \n ", "origin");+ let result =+ DefaultBranchName::from_local("origin", " \n ").map(DefaultBranchName::into_string);assert!(result.is_err(), "Whitespace-only should error");}@@ -405,79 +406,80 @@ fn test_parse_local_default_branch_whitespace_only() {fn test_parse_local_default_branch_empty_remote() {// Bug hypothesis: What if remote name is empty?// This creates prefix = "/" which might match branch names starting with /- let result = parse_local_default_branch("/weird/branch", "");+ let result =+ DefaultBranchName::from_local("", "/weird/branch").map(DefaultBranchName::into_string);assert!(result.is_ok());// Strips "/" prefix, leaving "weird/branch"assert_eq!(result.unwrap(), "weird/branch");}-// Tests for parse_numstat+// Tests for LineDiff::from_numstat#[test]-fn test_parse_numstat_normal() {+fn test_line_diff_from_numstat_normal() {let output = "10\t5\tfile1.rs\n3\t2\tfile2.rs\n";- let result = parse_numstat(output);+ let result = LineDiff::from_numstat(output);assert!(result.is_ok());- let (added, deleted) = result.unwrap();+ let (added, deleted) = result.unwrap().into_tuple();assert_eq!(added, 13, "Should sum added lines");assert_eq!(deleted, 7, "Should sum deleted lines");}#[test]-fn test_parse_numstat_empty_output() {+fn test_line_diff_from_numstat_empty_output() {// Bug hypothesis: Empty output should return (0, 0), not error- let result = parse_numstat("");+ let result = LineDiff::from_numstat("");assert!(result.is_ok());- let (added, deleted) = result.unwrap();+ let (added, deleted) = result.unwrap().into_tuple();assert_eq!(added, 0);assert_eq!(deleted, 0);}#[test]-fn test_parse_numstat_binary_files() {+fn test_line_diff_from_numstat_binary_files() {// Binary files show "-" for added/deletedlet output = "10\t5\tfile1.rs\n-\t-\timage.png\n3\t2\tfile2.rs\n";- let result = parse_numstat(output);+ let result = LineDiff::from_numstat(output);assert!(result.is_ok());- let (added, deleted) = result.unwrap();+ let (added, deleted) = result.unwrap().into_tuple();// Should skip the binary file lineassert_eq!(added, 13);assert_eq!(deleted, 7);}#[test]-fn test_parse_numstat_mixed_binary() {+fn test_line_diff_from_numstat_mixed_binary() {// Bug hypothesis: What if only one side is "-"?// Current code checks "if added_str == '-' || deleted_str == '-'"// So it skips the line if EITHER is "-"let output = "10\t-\tfile1.rs\n-\t5\tfile2.rs\n";- let result = parse_numstat(output);+ let result = LineDiff::from_numstat(output);assert!(result.is_ok());- let (added, deleted) = result.unwrap();+ let (added, deleted) = result.unwrap().into_tuple();// Both lines should be skippedassert_eq!(added, 0);assert_eq!(deleted, 0);}#[test]-fn test_parse_numstat_empty_lines() {+fn test_line_diff_from_numstat_empty_lines() {let output = "10\t5\tfile1.rs\n\n3\t2\tfile2.rs\n\n";- let result = parse_numstat(output);+ let result = LineDiff::from_numstat(output);assert!(result.is_ok());- let (added, deleted) = result.unwrap();+ let (added, deleted) = result.unwrap().into_tuple();// Empty lines should be skippedassert_eq!(added, 13);assert_eq!(deleted, 7);}#[test]-fn test_parse_numstat_malformed_missing_second_value() {+fn test_line_diff_from_numstat_malformed_missing_second_value() {// BUG FIXED: Line with only one tab used to try to parse filename as number// Input: "10\tfile.rs\n"// parts.next() -> Some("10") ✓@@ -487,60 +489,60 @@ fn test_parse_numstat_malformed_missing_second_value() {//// The real git numstat format is: <added>\t<deleted>\t<filename>let output = "10\tfile.rs\n";- let result = parse_numstat(output);+ let result = LineDiff::from_numstat(output);// Fixed: Malformed lines are now skipped instead of causing errorsassert!(result.is_ok(), "Malformed lines should be skipped");- let (added, deleted) = result.unwrap();+ let (added, deleted) = result.unwrap().into_tuple();assert_eq!(added, 0, "Malformed line should be skipped");assert_eq!(deleted, 0, "Malformed line should be skipped");}#[test]-fn test_parse_numstat_malformed_missing_first_value() {+fn test_line_diff_from_numstat_malformed_missing_first_value() {// Bug hypothesis: Line with no tabs// parts.next() returns the whole line, parts.next() again returns Nonelet output = "file.rs\n";- let result = parse_numstat(output);+ let result = LineDiff::from_numstat(output);assert!(result.is_ok());// Line should be skipped- let (added, deleted) = result.unwrap();+ let (added, deleted) = result.unwrap().into_tuple();assert_eq!(added, 0);assert_eq!(deleted, 0);}#[test]-fn test_parse_numstat_non_numeric_values() {+fn test_line_diff_from_numstat_non_numeric_values() {// Non-numeric values should be skipped (after the fix)let output = "abc\t5\tfile.rs\n";- let result = parse_numstat(output);+ let result = LineDiff::from_numstat(output);assert!(result.is_ok(), "Malformed lines should be skipped");- let (added, deleted) = result.unwrap();+ let (added, deleted) = result.unwrap().into_tuple();assert_eq!(added, 0, "Non-numeric line should be skipped");assert_eq!(deleted, 0, "Non-numeric line should be skipped");}#[test]-fn test_parse_numstat_non_numeric_deleted() {+fn test_line_diff_from_numstat_non_numeric_deleted() {// Non-numeric deleted value should be skippedlet output = "5\txyz\tfile.rs\n";- let result = parse_numstat(output);+ let result = LineDiff::from_numstat(output);assert!(result.is_ok(), "Malformed lines should be skipped");- let (added, deleted) = result.unwrap();+ let (added, deleted) = result.unwrap().into_tuple();assert_eq!(added, 0, "Non-numeric line should be skipped");assert_eq!(deleted, 0, "Non-numeric line should be skipped");}#[test]-fn test_parse_numstat_zero_values() {+fn test_line_diff_from_numstat_zero_values() {let output = "0\t0\tfile.rs\n";- let result = parse_numstat(output);+ let result = LineDiff::from_numstat(output);assert!(result.is_ok());- let (added, deleted) = result.unwrap();+ let (added, deleted) = result.unwrap().into_tuple();assert_eq!(added, 0);assert_eq!(deleted, 0);}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.snapindex 4375fb7fd..483b4eff5 100644--- a/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap+++ b/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap@@ -12,11 +12,10 @@ info:GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/null- GIT_EDITOR: ""LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp6RaMfE/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp2IgNi2/test-config.toml---success: trueexit_code: 0@@ -37,18 +36,18 @@ exit_code: 0"commit_message": "Main commit 2","ahead": 0,"behind": 0,- "working_tree_diff": [- 0,- 0- ],- "working_tree_diff_with_main": [- 0,- 0- ],- "branch_diff": [- 0,- 0- ],+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "working_tree_diff_with_main": {+ "added": 0,+ "deleted": 0+ },+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },"is_primary": true,"upstream_remote": null,"upstream_ahead": 0,@@ -81,14 +80,14 @@ exit_code: 0"commit_message": "Feature commit 2","ahead": 2,"behind": 2,- "working_tree_diff": [- 1,- 1- ],- "branch_diff": [- 1,- 0- ],+ "working_tree_diff": {+ "added": 1,+ "deleted": 1+ },+ "branch_diff": {+ "added": 1,+ "deleted": 0+ },"is_primary": false,"upstream_remote": null,"upstream_ahead": 0,@@ -125,14 +124,14 @@ exit_code: 0"commit_message": "Initial commit on main","ahead": 0,"behind": 2,- "working_tree_diff": [- 0,- 0- ],- "branch_diff": [- 0,- 0- ],+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },"is_primary": false,"upstream_remote": null,"upstream_ahead": 0,diff --git a/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap b/tests/snapshots/integration__integration_tests__list__json_with_metadata.snapindex 6907b1bfe..4f85b9f5b 100644--- a/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap+++ b/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap@@ -12,11 +12,10 @@ info:GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/null- GIT_EDITOR: ""LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp7e0bkQ/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpS5lSrA/test-config.toml---success: trueexit_code: 0@@ -37,18 +36,18 @@ exit_code: 0"commit_message": "Initial commit","ahead": 0,"behind": 0,- "working_tree_diff": [- 0,- 0- ],- "working_tree_diff_with_main": [- 0,- 0- ],- "branch_diff": [- 0,- 0- ],+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "working_tree_diff_with_main": {+ "added": 0,+ "deleted": 0+ },+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },"is_primary": true,"upstream_remote": null,"upstream_ahead": 0,@@ -81,18 +80,18 @@ exit_code: 0"commit_message": "Initial commit","ahead": 0,"behind": 0,- "working_tree_diff": [- 0,- 0- ],- "working_tree_diff_with_main": [- 0,- 0- ],- "branch_diff": [- 0,- 0- ],+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "working_tree_diff_with_main": {+ "added": 0,+ "deleted": 0+ },+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },"is_primary": false,"upstream_remote": null,"upstream_ahead": 0,@@ -126,18 +125,18 @@ exit_code: 0"commit_message": "Initial commit","ahead": 0,"behind": 0,- "working_tree_diff": [- 0,- 0- ],- "working_tree_diff_with_main": [- 0,- 0- ],- "branch_diff": [- 0,- 0- ],+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "working_tree_diff_with_main": {+ "added": 0,+ "deleted": 0+ },+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },"is_primary": false,"upstream_remote": null,"upstream_ahead": 0,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.snapindex 3950f5cbc..93a708abc 100644--- a/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap+++ b/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap@@ -12,11 +12,10 @@ info:GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/null- GIT_EDITOR: ""LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpLHcw4p/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpuw0Gca/test-config.toml---success: trueexit_code: 0@@ -37,18 +36,18 @@ exit_code: 0"commit_message": "Initial commit","ahead": 0,"behind": 0,- "working_tree_diff": [- 0,- 0- ],- "working_tree_diff_with_main": [- 0,- 0- ],- "branch_diff": [- 0,- 0- ],+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "working_tree_diff_with_main": {+ "added": 0,+ "deleted": 0+ },+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },"is_primary": true,"upstream_remote": null,"upstream_ahead": 0,@@ -81,18 +80,18 @@ exit_code: 0"commit_message": "Initial commit","ahead": 0,"behind": 0,- "working_tree_diff": [- 0,- 0- ],- "working_tree_diff_with_main": [- 0,- 0- ],- "branch_diff": [- 0,- 0- ],+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "working_tree_diff_with_main": {+ "added": 0,+ "deleted": 0+ },+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },"is_primary": false,"upstream_remote": null,"upstream_ahead": 0,@@ -127,18 +126,18 @@ exit_code: 0"commit_message": "Initial commit","ahead": 0,"behind": 0,- "working_tree_diff": [- 0,- 0- ],- "working_tree_diff_with_main": [- 0,- 0- ],- "branch_diff": [- 0,- 0- ],+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "working_tree_diff_with_main": {+ "added": 0,+ "deleted": 0+ },+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },"is_primary": false,"upstream_remote": null,"upstream_ahead": 0,