Skip to content

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

Refactor: consolidate parsing and utility functions into shared modules

Maximilian Roosb534f8f447be
diff --git a/src/commands/config.rs b/src/commands/config.rs
index f668062d5..2c7a2e8a8 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -691,8 +691,7 @@ fn require_user_config_path() -> anyhow::Result<PathBuf> {
/// Clear all log files from the wt-logs directory
fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {
- let git_common_dir = repo.git_common_dir()?;
- let log_dir = git_common_dir.join("wt-logs");
+ let log_dir = repo.wt_logs_dir()?;
if !log_dir.exists() {
return Ok(0);
@@ -718,8 +717,7 @@ fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {
/// Render the LOG FILES section (heading + table or "(none)") into the output buffer
fn render_log_files(out: &mut String, repo: &Repository) -> anyhow::Result<()> {
- let git_common_dir = repo.git_common_dir()?;
- let log_dir = git_common_dir.join("wt-logs");
+ let log_dir = repo.wt_logs_dir()?;
let log_dir_display = format_path_for_display(&log_dir);
writeln!(
@@ -1133,8 +1131,7 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
.collect();
// Get log files
- let git_common_dir = repo.git_common_dir()?;
- let log_dir = git_common_dir.join("wt-logs");
+ let log_dir = repo.wt_logs_dir()?;
let logs: Vec<serde_json::Value> = if log_dir.exists() {
let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?
.filter_map(|e| e.ok())
diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rs
index ee3ef1374..7d7ab878b 100644
--- a/src/commands/list/ci_status.rs
+++ b/src/commands/list/ci_status.rs
@@ -1,8 +1,9 @@
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::fs;
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
use std::process::Command;
use worktrunk::git::{GitRemoteUrl, Repository};
+use worktrunk::path::sanitize_for_filename;
use worktrunk::shell_exec::run;
use worktrunk::utils::get_now;
@@ -35,16 +36,11 @@ pub fn get_platform_for_repo(repo_root: &str) -> Option<CiPlatform> {
/// Get the origin remote URL for a repository.
fn get_remote_url_for_repo(repo_root: &str) -> Option<String> {
- let mut cmd = Command::new("git");
- cmd.args(["remote", "get-url", "origin"])
- .current_dir(repo_root);
- let output = run(&mut cmd, None).ok()?;
-
- if output.status.success() {
- String::from_utf8(output.stdout).ok()
- } else {
- None
- }
+ let repo = Repository::at(repo_root);
+ repo.run_command(&["remote", "get-url", "origin"])
+ .ok()
+ .map(|output| output.trim().to_string())
+ .filter(|output| !output.is_empty())
}
/// Get the GitLab hostname for a repository by parsing its origin remote URL.
@@ -1093,68 +1089,15 @@ impl CachedCiStatus {
/// Get the cache directory path: `.git/wt-cache/ci-status/`
fn cache_dir(repo_root: &str) -> Option<PathBuf> {
- let mut cmd = Command::new("git");
- cmd.args(["rev-parse", "--git-common-dir"])
- .current_dir(repo_root);
- let output = run(&mut cmd, None).ok()?;
-
- if !output.status.success() {
- return None;
- }
-
- let git_dir = String::from_utf8(output.stdout).ok()?;
- let git_dir = git_dir.trim();
-
- // Handle relative paths from git rev-parse
- let git_path = if Path::new(git_dir).is_absolute() {
- PathBuf::from(git_dir)
- } else {
- PathBuf::from(repo_root).join(git_dir)
- };
-
- Some(git_path.join("wt-cache").join("ci-status"))
- }
-
- /// Sanitize branch name for use as a filename.
- /// Handles Windows reserved names, control characters, and invalid filename characters.
- fn sanitize_branch_for_filename(branch: &str) -> String {
- let mut result: String = branch
- .chars()
- .map(|c| match c {
- // Windows/Unix invalid filename characters
- '/' | '\\' | '<' | '>' | ':' | '"' | '|' | '?' | '*' => '-',
- // Control characters (0x00-0x1F)
- c if c.is_control() => '-',
- _ => c,
- })
- .collect();
-
- // Trim trailing dots and spaces (Windows silently strips these)
- while result.ends_with('.') || result.ends_with(' ') {
- result.pop();
- }
-
- // Handle Windows reserved names (case-insensitive)
- // CON, PRN, AUX, NUL, COM1-9, LPT1-9
- let upper = result.to_uppercase();
- let is_reserved = matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
- || (upper.len() == 4
- && (upper.starts_with("COM") || upper.starts_with("LPT"))
- && upper.chars().last().is_some_and(|c| c.is_ascii_digit()));
-
- if is_reserved {
- format!("_{result}")
- } else if result.is_empty() {
- "_empty".to_string()
- } else {
- result
- }
+ let repo = Repository::at(repo_root);
+ let git_common_dir = repo.git_common_dir().ok()?;
+ Some(git_common_dir.join("wt-cache").join("ci-status"))
}
/// Get the cache file path for a branch.
fn cache_file(branch: &str, repo_root: &str) -> Option<PathBuf> {
let dir = Self::cache_dir(repo_root)?;
- let safe_branch = Self::sanitize_branch_for_filename(branch);
+ let safe_branch = sanitize_for_filename(branch);
Some(dir.join(format!("{safe_branch}.json")))
}
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index 9eb9d3bc4..d7addb6b0 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -283,6 +283,93 @@ pub struct DiffDisplayConfig {
pub always_show_zeros: bool,
}
+impl DiffDisplayConfig {
+ /// Format diff values with fixed-width alignment for tabular display.
+ ///
+ /// Numbers are right-aligned within a 3-digit column width.
+ /// Returns empty spaces if both values are zero (unless `always_show_zeros` is set).
+ #[cfg(unix)] // Only used by select command which is unix-only
+ pub fn format_aligned(&self, positive: usize, negative: usize) -> String {
+ const DIGITS: usize = 3;
+ let positive_width = 1 + DIGITS; // symbol + digits
+ let negative_width = 1 + DIGITS;
+ let total_width = positive_width + 1 + negative_width; // with separator
+
+ let config = DiffColumnConfig {
+ positive_digits: DIGITS,
+ negative_digits: DIGITS,
+ total_width,
+ display: *self,
+ };
+
+ config.render_segment(positive, negative).render()
+ }
+
+ /// Format diff values as plain text with ANSI colors (no fixed-width alignment).
+ ///
+ /// Returns `None` if both values are zero (unless `always_show_zeros` is set).
+ /// Format: `+N -M` with appropriate colors for each component.
+ pub fn format_plain(&self, positive: usize, negative: usize) -> Option<String> {
+ if !self.always_show_zeros && positive == 0 && negative == 0 {
+ return None;
+ }
+
+ let symbols = self.variant.symbols();
+ let mut parts = Vec::with_capacity(2);
+
+ if positive > 0 || self.always_show_zeros {
+ parts.push(format!(
+ "{}{}{}{}",
+ self.positive_style,
+ symbols.positive,
+ positive,
+ self.positive_style.render_reset()
+ ));
+ }
+
+ if negative > 0 || self.always_show_zeros {
+ parts.push(format!(
+ "{}{}{}{}",
+ self.negative_style,
+ symbols.negative,
+ negative,
+ self.negative_style.render_reset()
+ ));
+ }
+
+ if parts.is_empty() {
+ None
+ } else {
+ Some(parts.join(" "))
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+pub(super) struct DiffSymbols {
+ pub(super) positive: &'static str,
+ pub(super) negative: &'static str,
+}
+
+impl DiffVariant {
+ pub(super) fn symbols(self) -> DiffSymbols {
+ match self {
+ DiffVariant::Signs => DiffSymbols {
+ positive: "+",
+ negative: "-",
+ },
+ DiffVariant::Arrows => DiffSymbols {
+ positive: "↑",
+ negative: "↓",
+ },
+ DiffVariant::UpstreamArrows => DiffSymbols {
+ positive: "⇡",
+ negative: "⇣",
+ },
+ }
+ }
+}
+
impl ColumnKind {
pub fn diff_display_config(self) -> Option<DiffDisplayConfig> {
match self {
@@ -308,6 +395,12 @@ impl ColumnKind {
}
}
+ /// Format diff-style values as plain text with ANSI colors (for json-pretty).
+ pub(crate) fn format_diff_plain(self, positive: usize, negative: usize) -> Option<String> {
+ let config = self.diff_display_config()?;
+ config.format_plain(positive, negative)
+ }
+
pub fn has_data(self, flags: &ColumnDataFlags) -> bool {
match self {
ColumnKind::Gutter => true, // Always present (shows @ ^ + or space)
diff --git a/src/commands/list/model.rs b/src/commands/list/model.rs
index 6162af6b2..63a52ce3c 100644
--- a/src/commands/list/model.rs
+++ b/src/commands/list/model.rs
@@ -81,7 +81,7 @@ pub struct WorktreeData {
#[serde(skip_serializing_if = "Option::is_none")]
pub working_tree_diff_with_main: Option<Option<LineDiff>>,
/// Git operation in progress (rebase/merge)
- #[serde(skip_serializing_if = "git_operation_is_none")]
+ #[serde(skip_serializing_if = "GitOperationState::is_none")]
pub git_operation: GitOperationState,
pub is_main: bool,
/// Whether this is the current worktree (matches $PWD)
@@ -259,8 +259,6 @@ pub struct ListItem {
pub struct ListData {
pub items: Vec<ListItem>,
/// Path to the main worktree, used for computing relative paths in display.
- /// Currently only read by `select` command (unix-only).
- #[cfg_attr(windows, allow(dead_code))]
pub main_worktree_path: std::path::PathBuf,
}
@@ -977,6 +975,12 @@ pub enum GitOperationState {
Merge,
}
+impl GitOperationState {
+ fn is_none(&self) -> bool {
+ matches!(self, Self::None)
+ }
+}
+
/// Tracks which status symbol positions are actually used across all items
/// and the maximum width needed for each position.
///
@@ -1287,11 +1291,6 @@ impl WorkingTreeStatus {
}
}
-/// Helper for serde skip_serializing_if
-fn git_operation_is_none(state: &GitOperationState) -> bool {
- *state == GitOperationState::None
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -1949,10 +1948,10 @@ mod tests {
}
#[test]
- fn test_git_operation_is_none() {
- assert!(git_operation_is_none(&GitOperationState::None));
- assert!(!git_operation_is_none(&GitOperationState::Rebase));
- assert!(!git_operation_is_none(&GitOperationState::Merge));
+ fn test_git_operation_state_is_none() {
+ assert!(GitOperationState::None.is_none());
+ assert!(!GitOperationState::Rebase.is_none());
+ assert!(!GitOperationState::Merge.is_none());
}
// ============================================================================
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index 784f73352..9fd84b875 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -6,88 +6,12 @@ use worktrunk::styling::StyledLine;
use super::ci_status::PrStatus;
use super::columns::{ColumnKind, DiffVariant};
-use super::layout::{
- ColumnFormat, ColumnLayout, DiffColumnConfig, DiffDisplayConfig, LayoutConfig,
-};
+use super::layout::{ColumnFormat, ColumnLayout, DiffColumnConfig, LayoutConfig};
use super::model::{
AheadBehind, CommitDetails, ListItem, PositionMask, UpstreamStatus, WorktreeData,
};
use worktrunk::git::LineDiff;
-impl DiffDisplayConfig {
- /// Format diff values with fixed-width alignment for tabular display.
- ///
- /// Numbers are right-aligned within a 3-digit column width.
- /// Returns empty spaces if both values are zero (unless `always_show_zeros` is set).
- #[cfg(unix)] // Only used by select command which is unix-only
- pub fn format_aligned(&self, positive: usize, negative: usize) -> String {
- use super::layout::DiffColumnConfig;
-
- const DIGITS: usize = 3;
- let positive_width = 1 + DIGITS; // symbol + digits
- let negative_width = 1 + DIGITS;
- let total_width = positive_width + 1 + negative_width; // with separator
-
- let config = DiffColumnConfig {
- positive_digits: DIGITS,
- negative_digits: DIGITS,
- total_width,
- display: *self,
- };
-
- config.render_segment(positive, negative).render()
- }
-
- /// Format diff values as plain text with ANSI colors (no fixed-width alignment).
- ///
- /// Returns `None` if both values are zero (unless `always_show_zeros` is set).
- /// Format: `+N -M` with appropriate colors for each component.
- pub fn format_plain(&self, positive: usize, negative: usize) -> Option<String> {
- if !self.always_show_zeros && positive == 0 && negative == 0 {
- return None;
- }
-
- let symbols = self.variant.symbols();
-
- let mut parts = Vec::with_capacity(2);
-
- if positive > 0 || self.always_show_zeros {
- parts.push(format!(
- "{}{}{}{}",
- self.positive_style,
- symbols.positive,
- positive,
- self.positive_style.render_reset()
- ));
- }
-
- if negative > 0 || self.always_show_zeros {
- parts.push(format!(
- "{}{}{}{}",
- self.negative_style,
- symbols.negative,
- negative,
- self.negative_style.render_reset()
- ));
- }
-
- if parts.is_empty() {
- None
- } else {
- Some(parts.join(" "))
- }
- }
-}
-
-impl ColumnKind {
- /// Format diff-style values as plain text with ANSI colors (for json-pretty).
- pub(crate) fn format_diff_plain(self, positive: usize, negative: usize) -> Option<String> {
- let config = self.diff_display_config()?;
-
- config.format_plain(positive, negative)
- }
-}
-
impl PrStatus {
/// Render indicator as a StyledLine for table column rendering.
fn render_indicator(&self) -> StyledLine {
@@ -97,31 +21,6 @@ impl PrStatus {
}
}
-#[derive(Clone, Copy)]
-struct DiffSymbols {
- positive: &'static str,
- negative: &'static str,
-}
-
-impl DiffVariant {
- fn symbols(self) -> DiffSymbols {
- match self {
- DiffVariant::Signs => DiffSymbols {
- positive: "+",
- negative: "-",
- },
- DiffVariant::Arrows => DiffSymbols {
- positive: "↑",
- negative: "↓",
- },
- DiffVariant::UpstreamArrows => DiffSymbols {
- positive: "⇡",
- negative: "⇣",
- },
- }
- }
-}
-
impl DiffColumnConfig {
/// Check if a value exceeds the allocated digit width
fn exceeds_width(value: usize, digits: usize) -> bool {
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 5af25ccf3..4f06a14c6 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -5,35 +5,7 @@ use std::path::Path;
use std::process::Command;
use std::process::Stdio;
use worktrunk::git::Repository;
-use worktrunk::path::format_path_for_display;
-
-/// Sanitize a string for use as a filename on all platforms.
-/// Replaces characters that are illegal in Windows filenames or are path separators.
-/// Also handles Windows reserved device names (CON, PRN, AUX, NUL, COM1-9, LPT1-9).
-fn sanitize_for_filename(s: &str) -> String {
- // Replace illegal characters
- let sanitized: String = s
- .chars()
- .map(|c| match c {
- '/' | '\\' | '<' | '>' | ':' | '"' | '|' | '?' | '*' => '-',
- _ => c,
- })
- .collect();
-
- // Check for Windows reserved device names (case-insensitive)
- // These cannot be used as filenames on Windows, even with extensions
- let upper = sanitized.to_uppercase();
- let is_reserved = matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
- || (upper.len() == 4
- && (upper.starts_with("COM") || upper.starts_with("LPT"))
- && upper.chars().nth(3).is_some_and(|c| matches!(c, '1'..='9')));
-
- if is_reserved {
- format!("_{}", sanitized)
- } else {
- sanitized
- }
-}
+use worktrunk::path::{format_path_for_display, sanitize_for_filename};
/// Get the separator needed before closing brace in POSIX shell command grouping.
/// Returns empty string if command already ends with newline or semicolon.
@@ -71,11 +43,8 @@ pub fn spawn_detached(
name: &str,
context_json: Option<&str>,
) -> anyhow::Result<std::path::PathBuf> {
- // Get the git common directory (shared across all worktrees)
- let git_common_dir = repo.git_common_dir()?;
-
// Create log directory in the common git directory
- let log_dir = git_common_dir.join("wt-logs");
+ let log_dir = repo.wt_logs_dir()?;
fs::create_dir_all(&log_dir).with_context(|| {
format!(
"Failed to create log directory {}",
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 2e313808c..c04e23271 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -6,7 +6,9 @@ use super::worktree::{BranchDeletionMode, RemoveResult};
use anyhow::Context;
use color_print::cformat;
use worktrunk::config::ProjectConfig;
-use worktrunk::git::{GitError, IntegrationReason, Repository};
+use worktrunk::git::{
+ GitError, IntegrationReason, Repository, parse_porcelain_z, parse_untracked_files,
+};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{format_with_gutter, progress_message, warning_message};
@@ -313,70 +315,6 @@ fn compute_integration_reason(
worktrunk::git::check_integration(&mut provider)
}
-/// Parse `git status --porcelain -z` output into a list of affected filenames.
-///
-/// The -z format uses NUL separators and handles renames specially:
-/// - Normal entries: `XY path\0`
-/// - Renames/copies: `XY new_path\0old_path\0`
-///
-/// This correctly handles filenames with spaces and ensures both old and new
-/// paths are included for renames/copies (important for overlap detection).
-fn parse_porcelain_z(output: &str) -> Vec<String> {
- let mut files = Vec::new();
- let mut entries = output.split('\0').filter(|s| !s.is_empty());
-
- while let Some(entry) = entries.next() {
- // Each entry is "XY path" where XY is exactly 2 status chars
- if entry.len() < 3 {
- continue;
- }
-
- let status = &entry[0..2];
- let path = &entry[3..];
- files.push(path.to_string());
-
- // For renames (R) and copies (C), the next NUL-separated field is the old path
- if (status.starts_with('R') || status.starts_with('C'))
- && let Some(old_path) = entries.next()
- {
- files.push(old_path.to_string());
- }
- }
-
- files
-}
-
-/// Parse untracked files from `git status --porcelain -z` output.
-///
-/// Format: "XY path\0" where XY is the status code and path follows a space.
-/// Untracked files have status "??".
-fn parse_untracked_files(status_output: &str) -> Vec<String> {
- let mut files = Vec::new();
- let mut entries = status_output.split('\0').filter(|s| !s.is_empty());
-
- while let Some(entry) = entries.next() {
- // Format: "XY PATH" where XY is 2 status chars, space, then path
- if entry.len() < 3 {
- continue;
- }
-
- let status = &entry[0..2];
- let path = &entry[3..];
-
- // Only collect untracked files
- if status == "??" {
- files.push(path.to_string());
- }
-
- // Skip old path for renames/copies (we don't care about them here)
- if status.starts_with('R') || status.starts_with('C') {
- entries.next();
- }
- }
-
- files
-}
-
/// Warn about untracked files that will be auto-staged.
fn warn_about_untracked_files(status_output: &str) -> anyhow::Result<()> {
let files = parse_untracked_files(status_output);
diff --git a/src/commands/select.rs b/src/commands/select.rs
index 11e8321cb..5645ebf61 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -8,14 +8,14 @@ use std::process::{Command, Stdio};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use worktrunk::config::WorktrunkConfig;
-use worktrunk::git::Repository;
-use worktrunk::shell_exec::run;
+use worktrunk::git::{Repository, parse_numstat_line};
use super::list::collect;
use super::list::layout::{DiffDisplayConfig, DiffVariant};
use super::list::model::ListItem;
use super::worktree::handle_switch;
use crate::output::handle_switch_output;
+use crate::pager::{git_config_pager, parse_pager_value};
/// Cached pager command, detected once at startup.
///
@@ -27,29 +27,13 @@ static CACHED_PAGER: OnceLock<Option<String>> = OnceLock::new();
fn get_diff_pager() -> Option<&'static String> {
CACHED_PAGER
.get_or_init(|| {
- // Returns Some(pager) if valid, None if empty/cat (no pager desired)
- let parse_pager = |s: &str| -> Option<String> {
- let trimmed = s.trim();
- (!trimmed.is_empty() && trimmed != "cat").then(|| trimmed.to_string())
- };
-
// GIT_PAGER takes precedence - if set (even to "cat" or empty), don't fall back
if let Ok(pager) = std::env::var("GIT_PAGER") {
- return parse_pager(&pager);
+ return parse_pager_value(&pager);
}
// Fall back to core.pager config
- let mut cmd = Command::new("git");
- cmd.args(["config", "--get", "core.pager"]);
- run(&mut cmd, None).ok().and_then(|output| {
- if output.status.success() {
- String::from_utf8(output.stdout)
- .ok()
- .and_then(|s| parse_pager(&s))
- } else {
- None
- }
- })
+ git_config_pager()
})
.as_ref()
}
@@ -660,42 +644,6 @@ impl WorktreeSkimItem {
}
}
-/// Parse a git numstat line and extract insertions/deletions
-///
-/// Numstat format: `added<TAB>deleted<TAB>filename`
-/// With --graph --color=always, lines have ANSI-colored graph prefix like `ESC[31m|ESC[m `.
-/// Binary files show "-" instead of numbers.
-///
-/// Returns Some((insertions, deletions)) for valid numstat lines.
-fn parse_numstat_line(line: &str) -> Option<(usize, usize)> {
- use ansi_str::AnsiStr;
-
- // First strip ANSI escape sequences (graph coloring contains digits that confuse parsing)
- let stripped = line.ansi_strip();
-
- // Strip graph prefix (e.g., "| ") and find tab-separated values
- let trimmed = stripped.trim_start_matches(|c: char| !c.is_ascii_digit() && c != '-');
-
- // Must have at least two tab-separated fields
- let mut parts = trimmed.split('\t');
- let added_str = parts.next()?;
- let deleted_str = parts.next()?;
-
- // "-" means binary file, treat as 0
- let added = if added_str == "-" {
- 0
- } else {
- added_str.parse().ok()?
- };
- let deleted = if deleted_str == "-" {
- 0
- } else {
- deleted_str.parse().ok()?
- };
-
- Some((added, deleted))
-}
-
/// Field delimiter for git log format with timestamps
const FIELD_DELIM: char = '\x1f';
@@ -1149,7 +1097,7 @@ mod tests {
fn test_parse_numstat_line_binary_file() {
// Binary files show "-" instead of numbers
let result = parse_numstat_line("-\t-\timage.png");
- assert_eq!(result, Some((0, 0)));
+ assert_eq!(result, None);
}
#[test]
diff --git a/src/git/diff.rs b/src/git/diff.rs
index 35a1e73d3..b1c740291 100644
--- a/src/git/diff.rs
+++ b/src/git/diff.rs
@@ -1,5 +1,6 @@
//! Git diff utilities for parsing and formatting diff statistics.
+use ansi_str::AnsiStr;
use color_print::cformat;
/// Line-level diff totals (added/deleted counts) used across git operations.
@@ -9,38 +10,43 @@ pub struct LineDiff {
pub deleted: usize,
}
+/// Parse a git numstat line and extract insertions/deletions.
+///
+/// Supports standard `git diff --numstat` output as well as log output with
+/// `--graph --color=always` prefixes.
+/// Returns `None` for binary entries (`-` counts).
+pub fn parse_numstat_line(line: &str) -> Option<(usize, usize)> {
+ // Strip ANSI escape sequences (graph coloring contains digits that confuse parsing).
+ let stripped = line.ansi_strip();
+
+ // Strip graph prefix (e.g., "| ") and find tab-separated values.
+ let trimmed = stripped.trim_start_matches(|c: char| !c.is_ascii_digit() && c != '-');
+
+ let mut parts = trimmed.split('\t');
+ let added_str = parts.next()?;
+ let deleted_str = parts.next()?;
+
+ // "-" means binary file; line counts are unavailable, so skip.
+ if added_str == "-" || deleted_str == "-" {
+ return None;
+ }
+
+ let added = added_str.parse().ok()?;
+ let deleted = deleted_str.parse().ok()?;
+
+ Some((added, deleted))
+}
+
impl LineDiff {
/// Parse `git diff --numstat` output into aggregated line totals.
pub fn from_numstat(output: &str) -> anyhow::Result<Self> {
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;
+ if let Some((added, deleted)) = parse_numstat_line(line) {
+ totals.added += added;
+ totals.deleted += deleted;
}
-
- 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)
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 339c3628f..36d769a37 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -29,7 +29,7 @@ use std::sync::LazyLock;
static HEAVY_OPS_SEMAPHORE: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(4));
// Re-exports from submodules
-pub use diff::{DiffStats, LineDiff};
+pub use diff::{DiffStats, LineDiff, parse_numstat_line};
pub use error::{
// Typed error enum (Display produces styled output)
GitError,
@@ -40,6 +40,7 @@ pub use error::{
add_hook_skip_hint,
exit_code,
};
+pub use parse::{parse_porcelain_z, parse_untracked_files};
pub use repository::{Repository, ResolvedWorktree, set_base_path};
pub use url::GitRemoteUrl;
/// Why branch content is considered integrated into the target branch.
diff --git a/src/git/parse.rs b/src/git/parse.rs
index f625a89d1..50dcfa262 100644
--- a/src/git/parse.rs
+++ b/src/git/parse.rs
@@ -137,6 +137,70 @@ impl DefaultBranchName {
}
}
+/// Parse `git status --porcelain -z` output into a list of affected filenames.
+///
+/// The -z format uses NUL separators and handles renames specially:
+/// - Normal entries: `XY path\0`
+/// - Renames/copies: `XY new_path\0old_path\0`
+///
+/// This correctly handles filenames with spaces and ensures both old and new
+/// paths are included for renames/copies (important for overlap detection).
+pub fn parse_porcelain_z(output: &str) -> Vec<String> {
+ let mut files = Vec::new();
+ let mut entries = output.split('\0').filter(|s| !s.is_empty());
+
+ while let Some(entry) = entries.next() {
+ // Each entry is "XY path" where XY is exactly 2 status chars
+ if entry.len() < 3 {
+ continue;
+ }
+
+ let status = &entry[0..2];
+ let path = &entry[3..];
+ files.push(path.to_string());
+
+ // For renames (R) and copies (C), the next NUL-separated field is the old path
+ if (status.starts_with('R') || status.starts_with('C'))
+ && let Some(old_path) = entries.next()
+ {
+ files.push(old_path.to_string());
+ }
+ }
+
+ files
+}
+
+/// Parse untracked files from `git status --porcelain -z` output.
+///
+/// Format: "XY path\0" where XY is the status code and path follows a space.
+/// Untracked files have status "??".
+pub fn parse_untracked_files(status_output: &str) -> Vec<String> {
+ let mut files = Vec::new();
+ let mut entries = status_output.split('\0').filter(|s| !s.is_empty());
+
+ while let Some(entry) = entries.next() {
+ // Format: "XY PATH" where XY is 2 status chars, space, then path
+ if entry.len() < 3 {
+ continue;
+ }
+
+ let status = &entry[0..2];
+ let path = &entry[3..];
+
+ // Only collect untracked files
+ if status == "??" {
+ files.push(path.to_string());
+ }
+
+ // Skip old path for renames/copies (we don't care about them here)
+ if status.starts_with('R') || status.starts_with('C') {
+ entries.next();
+ }
+ }
+
+ files
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 632435713..3c40d8396 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -518,6 +518,14 @@ impl Repository {
.map(PathBuf::as_path)
}
+ /// Get the directory where worktrunk background logs are stored.
+ ///
+ /// Logs are centralized under the main worktree's git directory:
+ /// `.git/wt-logs/`.
+ pub fn wt_logs_dir(&self) -> anyhow::Result<PathBuf> {
+ Ok(self.git_common_dir()?.join("wt-logs"))
+ }
+
/// Get the git directory (may be different from common-dir in worktrees).
///
/// Always returns an absolute path, resolving any relative paths returned by git.
diff --git a/src/help_pager.rs b/src/help_pager.rs
index 03b65377d..97c060f60 100644
--- a/src/help_pager.rs
+++ b/src/help_pager.rs
@@ -21,13 +21,10 @@
//! commands like `less`. If Git Bash is not available, falls back to direct output.
use std::io::{IsTerminal, Write};
-use std::process::{Command, Stdio};
-use worktrunk::shell_exec::{ShellConfig, run};
+use std::process::Stdio;
+use worktrunk::shell_exec::ShellConfig;
-fn validate_pager(s: &str) -> Option<String> {
- let trimmed = s.trim();
- (!trimmed.is_empty() && trimmed != "cat").then(|| trimmed.to_string())
-}
+use crate::pager::{git_config_pager, parse_pager_value};
/// Detect pager for help output, following git's pager precedence.
///
@@ -41,22 +38,13 @@ fn detect_help_pager() -> Option<String> {
// Check environment variables in git's precedence order
let pager = std::env::var("GIT_PAGER")
.ok()
- .and_then(|s| validate_pager(&s))
+ .and_then(|s| parse_pager_value(&s))
+ .or_else(git_config_pager)
.or_else(|| {
- // Try git config core.pager
- let mut cmd = Command::new("git");
- cmd.args(["config", "--get", "core.pager"]);
- run(&mut cmd, None).ok().and_then(|output| {
- if !output.status.success() {
- return None;
- }
- String::from_utf8(output.stdout)
- .inspect_err(|e| log::debug!("git config output not UTF-8: {}", e))
- .ok()
- .and_then(|s| validate_pager(&s))
- })
- })
- .or_else(|| std::env::var("PAGER").ok().and_then(|s| validate_pager(&s)));
+ std::env::var("PAGER")
+ .ok()
+ .and_then(|s| parse_pager_value(&s))
+ });
// If user explicitly configured a pager, use it
if pager.is_some() {
@@ -142,22 +130,21 @@ pub fn show_help_in_pager(help_text: &str) -> std::io::Result<()> {
#[cfg(test)]
mod tests {
+ use crate::pager::parse_pager_value;
+
#[test]
fn test_validate_excludes_cat() {
- assert_eq!(super::validate_pager("cat"), None);
- assert_eq!(super::validate_pager(" cat "), None);
- assert_eq!(super::validate_pager(""), None);
- assert_eq!(super::validate_pager(" "), None);
+ assert_eq!(parse_pager_value("cat"), None);
+ assert_eq!(parse_pager_value(" cat "), None);
+ assert_eq!(parse_pager_value(""), None);
+ assert_eq!(parse_pager_value(" "), None);
}
#[test]
fn test_validate_accepts_valid_pagers() {
- assert_eq!(super::validate_pager("less"), Some("less".to_string()));
- assert_eq!(super::validate_pager(" less "), Some("less".to_string()));
- assert_eq!(super::validate_pager("delta"), Some("delta".to_string()));
- assert_eq!(
- super::validate_pager("less -R"),
- Some("less -R".to_string())
- );
+ assert_eq!(parse_pager_value("less"), Some("less".to_string()));
+ assert_eq!(parse_pager_value(" less "), Some("less".to_string()));
+ assert_eq!(parse_pager_value("delta"), Some("delta".to_string()));
+ assert_eq!(parse_pager_value("less -R"), Some("less -R".to_string()));
}
}
diff --git a/src/main.rs b/src/main.rs
index b8c8f71cb..3afbaf4c8 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -19,6 +19,7 @@ pub(crate) mod help_pager;
mod llm;
mod md_help;
mod output;
+mod pager;
pub use crate::cli::OutputFormat;
diff --git a/src/pager.rs b/src/pager.rs
new file mode 100644
index 000000000..00555f3b3
--- /dev/null
+++ b/src/pager.rs
@@ -0,0 +1,15 @@
+use worktrunk::git::Repository;
+
+/// Parse a pager value, treating empty strings and "cat" as "no pager".
+pub(crate) fn parse_pager_value(value: &str) -> Option<String> {
+ let trimmed = value.trim();
+ (!trimmed.is_empty() && trimmed != "cat").then(|| trimmed.to_string())
+}
+
+/// Read `core.pager` from git config, returning None if unset or invalid.
+pub(crate) fn git_config_pager() -> Option<String> {
+ let repo = Repository::current();
+ repo.run_command(&["config", "--get", "core.pager"])
+ .ok()
+ .and_then(|output| parse_pager_value(&output))
+}
diff --git a/src/path.rs b/src/path.rs
index 951a9297b..2b3210eb9 100644
--- a/src/path.rs
+++ b/src/path.rs
@@ -106,11 +106,49 @@ pub fn format_path_for_display(path: &Path) -> String {
path.display().to_string()
}
+/// Sanitize a string for use as a filename on all platforms.
+///
+/// Replaces invalid characters and control characters with `-`, trims trailing
+/// dots/spaces (Windows), and prefixes reserved device names with `_`.
+pub fn sanitize_for_filename(value: &str) -> String {
+ let mut result: String = value
+ .chars()
+ .map(|c| match c {
+ // Windows/Unix invalid filename characters
+ '/' | '\\' | '<' | '>' | ':' | '"' | '|' | '?' | '*' => '-',
+ // Control characters (0x00-0x1F)
+ c if c.is_control() => '-',
+ _ => c,
+ })
+ .collect();
+
+ // Trim trailing dots and spaces (Windows silently strips these)
+ while result.ends_with('.') || result.ends_with(' ') {
+ result.pop();
+ }
+
+ // Handle Windows reserved names (case-insensitive)
+ // CON, PRN, AUX, NUL, COM1-9, LPT1-9
+ let upper = result.to_uppercase();
+ let is_reserved = matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
+ || (upper.len() == 4
+ && (upper.starts_with("COM") || upper.starts_with("LPT"))
+ && upper.chars().nth(3).is_some_and(|c| matches!(c, '1'..='9')));
+
+ if is_reserved {
+ format!("_{result}")
+ } else if result.is_empty() {
+ "_empty".to_string()
+ } else {
+ result
+ }
+}
+
#[cfg(test)]
mod tests {
use std::path::PathBuf;
- use super::{format_path_for_display, home_dir, to_posix_path};
+ use super::{format_path_for_display, home_dir, sanitize_for_filename, to_posix_path};
#[test]
fn shortens_path_under_home() {
@@ -216,4 +254,27 @@ mod tests {
assert_eq!(to_posix_path("relative"), "relative");
assert_eq!(to_posix_path(""), "");
}
+
+ #[test]
+ fn test_sanitize_for_filename_replaces_invalid_chars() {
+ assert_eq!(sanitize_for_filename("foo/bar"), "foo-bar");
+ assert_eq!(sanitize_for_filename("name:with?chars"), "name-with-chars");
+ }
+
+ #[test]
+ fn test_sanitize_for_filename_trims_trailing_dots_and_spaces() {
+ assert_eq!(sanitize_for_filename("file. "), "file");
+ assert_eq!(sanitize_for_filename("file..."), "file");
+ }
+
+ #[test]
+ fn test_sanitize_for_filename_prefixes_reserved_names() {
+ assert_eq!(sanitize_for_filename("CON"), "_CON");
+ assert_eq!(sanitize_for_filename("com1"), "_com1");
+ }
+
+ #[test]
+ fn test_sanitize_for_filename_handles_empty() {
+ assert_eq!(sanitize_for_filename(""), "_empty");
+ }
}