Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: Remove unused .bak files
Maximilian Roos0a5278e7fd42
diff --git a/src/git/repository.rs.bak b/src/git/repository.rs.bakdeleted file mode 100644index 7b46a12fd..000000000--- a/src/git/repository.rs.bak+++ /dev/null@@ -1,1072 +0,0 @@-use std::path::PathBuf;-use std::process::Command;-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,-};--/// Extension trait for Result types to simplify GitError conversions-///-/// This trait provides ergonomic methods to convert any Result into Result<T, GitError>.-///-/// # Examples-///-/// ```no_run-/// use worktrunk::git::{GitError, GitResultExt};-///-/// fn load_config() -> Result<String, std::io::Error> {-/// std::fs::read_to_string("config.toml")-/// }-///-/// // Without context:-/// let config = load_config().git_err()?;-///-/// // With context:-/// let config = load_config().git_context("Failed to load config")?;-/// # Ok::<(), GitError>(())-/// ```-pub trait GitResultExt<T> {- /// Convert the error to GitError with additional context- fn git_context(self, context: &str) -> Result<T, GitError>;-- /// Convert the error to GitError using its Display implementation- fn git_err(self) -> Result<T, GitError>;-}--impl<T, E: std::fmt::Display> GitResultExt<T> for Result<T, E> {- fn git_context(self, context: &str) -> Result<T, GitError> {- self.map_err(|e| GitError::CommandFailed(format!("{}: {}", context, e)))- }-- fn git_err(self) -> Result<T, GitError> {- self.map_err(|e| GitError::CommandFailed(e.to_string()))- }-}--/// Internal layout information for a repository.-///-/// Cached to avoid repeated git queries.-#[derive(Debug, Clone)]-struct RepositoryLayout {- /// Base path for worktrees (repo root for normal repos, bare repo path for bare repos)- worktree_base: PathBuf,-}--/// Repository context for git operations.-///-/// Provides a more ergonomic API than the `*_in(path, ...)` functions by-/// encapsulating the repository path.-///-/// # Examples-///-/// ```no_run-/// use worktrunk::git::Repository;-///-/// let repo = Repository::current();-/// let branch = repo.current_branch()?;-/// let is_dirty = repo.is_dirty()?;-/// # Ok::<(), worktrunk::git::GitError>(())-/// ```-#[derive(Debug)]-pub struct Repository {- path: PathBuf,- layout: OnceLock<RepositoryLayout>,-}--impl Repository {- /// Create a repository context at the specified path.- pub fn at(path: impl Into<PathBuf>) -> Self {- Self {- path: path.into(),- layout: OnceLock::new(),- }- }-- /// Create a repository context for the current directory.- ///- /// This is the most common usage pattern.- pub fn current() -> Self {- Self::at(".")- }-- /// Get the path this repository context operates on.- pub fn path(&self) -> &std::path::Path {- &self.path- }-- /// Get the repository layout, initializing it if needed.- fn layout(&self) -> Result<&RepositoryLayout, GitError> {- if let Some(layout) = self.layout.get() {- return Ok(layout);- }-- let git_common_dir = self- .git_common_dir()?- .canonicalize()- .map_err(|e| GitError::CommandFailed(format!("Failed to canonicalize path: {}", e)))?;-- let is_bare = self.is_bare_repo()?;-- let worktree_base = if is_bare {- git_common_dir.clone()- } else {- git_common_dir- .parent()- .ok_or_else(|| GitError::CommandFailed("Invalid git directory".to_string()))?- .to_path_buf()- };-- let layout = RepositoryLayout { worktree_base };-- // set() returns Err if already set, but we checked above, so ignore the result- let _ = self.layout.set(layout);-- // Now get() will succeed- Ok(self.layout.get().expect("just set"))- }-- /// Check if this is a bare repository (no working tree).- fn is_bare_repo(&self) -> Result<bool, GitError> {- let output = self.run_command(&["config", "--bool", "core.bare"])?;- Ok(output.trim() == "true")- }-- /// Get the primary remote name for this repository.- ///- /// Uses the following strategy:- /// 1. If the current branch has an upstream, use its remote- /// (Note: Detached HEAD falls through to step 2)- /// 2. Otherwise, get the first remote from `git remote`- /// 3. Fall back to "origin" if no remotes exist- pub fn primary_remote(&self) -> Result<String, GitError> {- // Try to get the remote from the current branch's upstream- if let Ok(Some(branch)) = self.current_branch()- && let Ok(Some(upstream)) = self.upstream_branch(&branch)- && let Some((remote, _)) = upstream.split_once('/')- {- return Ok(remote.to_string());- }-- // Fall back to first remote in the list- let output = self.run_command(&["remote"])?;- let first_remote = output.lines().next();-- Ok(first_remote.unwrap_or("origin").to_string())- }-- /// Check if a local git branch exists.- pub fn local_branch_exists(&self, branch: &str) -> Result<bool, GitError> {- Ok(self- .run_command(&["rev-parse", "--verify", &format!("refs/heads/{}", branch)])- .is_ok())- }-- /// Check if a git branch exists (local or remote).- pub fn branch_exists(&self, branch: &str) -> Result<bool, GitError> {- // Try local branch first- if self.local_branch_exists(branch)? {- return Ok(true);- }-- // Try remote branch- let remote = self.primary_remote()?;- Ok(self- .run_command(&[- "rev-parse",- "--verify",- &format!("refs/remotes/{}/{}", remote, branch),- ])- .is_ok())- }-- /// Get the current branch name, or None if in detached HEAD state.- pub fn current_branch(&self) -> Result<Option<String>, GitError> {- let stdout = self.run_command(&["branch", "--show-current"])?;- let branch = stdout.trim();-- if branch.is_empty() {- Ok(None) // Detached HEAD- } else {- Ok(Some(branch.to_string()))- }- }-- /// Resolve a worktree name, expanding "@" to the current branch.- ///- /// # Arguments- /// * `name` - The worktree name to resolve (or "@" for current HEAD)- ///- /// # Returns- /// - `Ok(name)` if not "@"- /// - `Ok(current_branch)` if "@" and on a branch- /// - `Err(DetachedHead)` if "@" and in detached HEAD state- pub fn resolve_worktree_name(&self, name: &str) -> Result<String, GitError> {- if name == "@" {- self.current_branch()?.ok_or(GitError::DetachedHead)- } else {- Ok(name.to_string())- }- }-- /// Get the default branch name for the repository.- ///- /// **Performance note:** This method may trigger a network call on first invocation- /// if the remote HEAD is not cached locally. The result is then cached in git's- /// config for subsequent calls. To minimize latency:- /// - Defer calling this until after fast, local checks (see e497f0f for example)- /// - Consider passing the result as a parameter if needed multiple times- /// - For optional operations, provide a fallback (e.g., `.unwrap_or("main")`)- ///- /// Uses a hybrid approach:- /// 1. Try local cache (`git rev-parse origin/HEAD`) first - fast, no network- /// 2. If not cached, query remote (`git ls-remote`) - may take 100ms-2s depending on network- /// 3. Cache the result (`git remote set-head`) for future invocations- /// 4. If no remote available, infer from local branches (no caching, shows hint)- pub fn default_branch(&self) -> Result<String, GitError> {- // Try to get default branch from remote- if let Ok(remote) = self.primary_remote() {- // Try local cache first (fast path)- if let Ok(branch) = self.get_local_default_branch(&remote) {- return Ok(branch);- }-- // Query remote and cache it- if let Ok(branch) = self.query_remote_default_branch(&remote) {- let _ = self.cache_default_branch(&remote, &branch);- return Ok(branch);- }- }-- // Fallback: No remote or remote query failed, try to infer locally- // TODO: Show message to user when using inference fallback:- // "No remote configured. Using inferred default branch: {branch}"- // "To cache the default branch, set up a remote and run: wt config refresh-cache"- // Problem: git.rs is in lib crate, output module is in binary.- // Options: (1) Return info about whether fallback was used, let callers show message- // (2) Add messages in specific commands (merge.rs, worktree.rs)- // (3) Move output abstraction to lib crate- self.infer_default_branch_locally()- }-- /// Resolve a target branch from an optional override- ///- /// If target is Some, returns it as a String. Otherwise, queries the default branch.- /// This is a common pattern used throughout commands that accept an optional --target flag.- pub fn resolve_target_branch(&self, target: Option<&str>) -> Result<String, GitError> {- target.map_or_else(|| self.default_branch(), |b| Ok(b.to_string()))- }-- /// Infer the default branch locally (without remote).- ///- /// Uses local heuristics when no remote is available:- /// 1. If only one local branch exists, use it- /// 2. Check what HEAD points to (current branch in main worktree)- /// 3. Check user's git config init.defaultBranch- /// 4. Look for common branch names (main, master, develop)- /// 5. Fail if none of the above work- fn infer_default_branch_locally(&self) -> Result<String, GitError> {- // 1. If there's only one local branch, use it- let branches = self.local_branches()?;- if branches.len() == 1 {- return Ok(branches[0].clone());- }-- // 2. Use the branch HEAD points to (from main worktree)- // This is what the main worktree is currently on- if let Ok(current) = self.run_command(&["symbolic-ref", "--short", "HEAD"]) {- let branch = current.trim().to_string();- if !branch.is_empty() {- return Ok(branch);- }- }-- // 3. Check git config init.defaultBranch- if let Ok(default) = self.run_command(&["config", "--get", "init.defaultBranch"]) {- let branch = default.trim().to_string();- if !branch.is_empty() && branches.contains(&branch) {- return Ok(branch);- }- }-- // 4. Look for common branch names- for name in ["main", "master", "develop", "trunk"] {- if branches.contains(&name.to_string()) {- return Ok(name.to_string());- }- }-- // 5. Give up - can't infer- Err(GitError::CommandFailed(- "Could not infer default branch. Please specify target branch explicitly or set up a remote.".to_string()- ))- }-- /// List all local branches.- fn local_branches(&self) -> Result<Vec<String>, GitError> {- let stdout = self.run_command(&["branch", "--format=%(refname:short)"])?;- Ok(stdout.lines().map(|s| s.trim().to_string()).collect())- }-- /// Get the git common directory (the actual .git directory for the repository).- pub fn git_common_dir(&self) -> Result<PathBuf, GitError> {- let stdout = self.run_command(&["rev-parse", "--git-common-dir"])?;- Ok(PathBuf::from(stdout.trim()))- }-- /// Get the git directory (may be different from common-dir in worktrees).- pub fn git_dir(&self) -> Result<PathBuf, GitError> {- let stdout = self.run_command(&["rev-parse", "--git-dir"])?;- Ok(PathBuf::from(stdout.trim()))- }-- /// Get the base directory where worktrees are created relative to.- ///- /// For normal repositories: the parent of .git (the repo root).- /// For bare repositories: the bare repository directory itself.- ///- /// This is the path that should be used when constructing worktree paths.- pub fn worktree_base(&self) -> Result<PathBuf, GitError> {- Ok(self.layout()?.worktree_base.clone())- }-- /// Check if the working tree has uncommitted changes.- pub fn is_dirty(&self) -> Result<bool, GitError> {- let stdout = self.run_command(&["status", "--porcelain"])?;- Ok(!stdout.trim().is_empty())- }-- /// Ensure the working tree is clean (no uncommitted changes).- ///- /// Returns an error if there are uncommitted changes.- pub fn ensure_clean_working_tree(&self) -> Result<(), GitError> {- if self.is_dirty()? {- return Err(GitError::UncommittedChanges);- }- Ok(())- }-- /// Get the worktree root directory (top-level of the working tree).- ///- /// Returns the canonicalized absolute path to the top-level directory of the- /// current working tree. This could be the main worktree or a linked worktree.- pub fn worktree_root(&self) -> Result<PathBuf, GitError> {- let stdout = self.run_command(&["rev-parse", "--show-toplevel"])?;- let path = PathBuf::from(stdout.trim());- path.canonicalize().map_err(|e| {- GitError::CommandFailed(format!("Failed to canonicalize worktree root: {}", e))- })- }-- /// Check if the path is in a worktree (vs the main repository).- pub fn is_in_worktree(&self) -> Result<bool, GitError> {- let git_dir = self.git_dir()?;- let common_dir = self.git_common_dir()?;- Ok(git_dir != common_dir)- }-- /// Check if base is an ancestor of head (i.e., would be a fast-forward).- pub fn is_ancestor(&self, base: &str, head: &str) -> Result<bool, GitError> {- self.run_command_check(&["merge-base", "--is-ancestor", base, head])- }-- /// Count commits between base and head.- pub fn count_commits(&self, base: &str, head: &str) -> Result<usize, GitError> {- let range = format!("{}..{}", base, head);- let stdout = self.run_command(&["rev-list", "--count", &range])?;- stdout- .trim()- .parse()- .map_err(|e| GitError::ParseError(format!("Failed to parse commit count: {}", e)))- }-- /// Check if there are merge commits in the range base..head.- pub fn has_merge_commits(&self, base: &str, head: &str) -> Result<bool, GitError> {- let range = format!("{}..{}", base, head);- let stdout = self.run_command(&["rev-list", "--merges", &range])?;- Ok(!stdout.trim().is_empty())- }-- /// Get files changed between base and head.- pub fn changed_files(&self, base: &str, head: &str) -> Result<Vec<String>, GitError> {- let range = format!("{}..{}", base, head);- let stdout = self.run_command(&["diff", "--name-only", &range])?;- Ok(stdout.lines().map(String::from).collect())- }-- /// Get commit timestamp in seconds since epoch.- pub fn commit_timestamp(&self, commit: &str) -> Result<i64, GitError> {- let stdout = self.run_command(&["show", "-s", "--format=%ct", commit])?;- stdout- .trim()- .parse()- .map_err(|e| GitError::ParseError(format!("Failed to parse timestamp: {}", e)))- }-- /// Get commit message (subject line) for a commit.- pub fn commit_message(&self, commit: &str) -> Result<String, GitError> {- let stdout = self.run_command(&["show", "-s", "--format=%s", commit])?;- Ok(stdout.trim().to_owned())- }-- /// Get the upstream tracking branch for the given branch.- pub fn upstream_branch(&self, branch: &str) -> Result<Option<String>, GitError> {- let result = self.run_command(&["rev-parse", "--abbrev-ref", &format!("{}@{{u}}", branch)]);-- match result {- Ok(upstream) => {- let trimmed = upstream.trim();- Ok((!trimmed.is_empty()).then(|| trimmed.to_string()))- }- Err(_) => Ok(None), // No upstream configured- }- }-- /// Get merge/rebase status for the worktree.- pub fn worktree_state(&self) -> Result<Option<String>, GitError> {- let git_dir = self.git_dir()?;-- // Check for merge- if git_dir.join("MERGE_HEAD").exists() {- return Ok(Some("MERGING".to_string()));- }-- // Check for rebase- if git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists() {- let rebase_dir = if git_dir.join("rebase-merge").exists() {- git_dir.join("rebase-merge")- } else {- git_dir.join("rebase-apply")- };-- if let (Ok(msgnum), Ok(end)) = (- std::fs::read_to_string(rebase_dir.join("msgnum")),- std::fs::read_to_string(rebase_dir.join("end")),- ) {- let current = msgnum.trim();- let total = end.trim();- return Ok(Some(format!("REBASING {}/{}", current, total)));- }-- return Ok(Some("REBASING".to_string()));- }-- // Check for cherry-pick- if git_dir.join("CHERRY_PICK_HEAD").exists() {- return Ok(Some("CHERRY-PICKING".to_string()));- }-- // Check for revert- if git_dir.join("REVERT_HEAD").exists() {- return Ok(Some("REVERTING".to_string()));- }-- // Check for bisect- if git_dir.join("BISECT_LOG").exists() {- return Ok(Some("BISECTING".to_string()));- }-- Ok(None)- }-- /// Calculate commits ahead and behind between two refs.- ///- /// Returns (ahead, behind) where ahead is commits in head not in base,- /// and behind is commits in base not in head.- pub fn ahead_behind(&self, base: &str, head: &str) -> Result<(usize, usize), GitError> {- let ahead = self.count_commits(base, head)?;- let behind = self.count_commits(head, base)?;- Ok((ahead, behind))- }-- /// 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> {- let stdout = self.run_command(&["diff", "--numstat", "HEAD"])?;- parse_numstat(&stdout)- }-- /// Get line diff statistics between working tree and a specific ref.- ///- /// 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> {- let stdout = self.run_command(&["diff", "--numstat", ref_name])?;- parse_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> {- let range = format!("{}...{}", base, head);- let stdout = self.run_command(&["diff", "--numstat", &range])?;- parse_numstat(&stdout)- }-- /// Get all branch names (local branches only).- pub fn all_branches(&self) -> Result<Vec<String>, GitError> {- let stdout = self.run_command(&["branch", "--format=%(refname:short)"])?;- Ok(stdout- .lines()- .map(|s| s.trim())- .filter(|s| !s.is_empty())- .map(str::to_owned)- .collect())- }-- /// Get the merge base between two commits.- pub fn merge_base(&self, commit1: &str, commit2: &str) -> Result<String, GitError> {- let output = self.run_command(&["merge-base", commit1, commit2])?;- Ok(output.trim().to_owned())- }-- /// Check if merging head into base would result in conflicts.- ///- /// Uses `git merge-tree` to simulate a merge without touching the working tree.- /// Returns true if conflicts would occur, false for a clean merge.- ///- /// # Examples- /// ```no_run- /// use worktrunk::git::Repository;- ///- /// let repo = Repository::current();- /// let has_conflicts = repo.has_merge_conflicts("main", "feature-branch")?;- /// # Ok::<(), worktrunk::git::GitError>(())- /// ```- pub fn has_merge_conflicts(&self, base: &str, head: &str) -> Result<bool, GitError> {- let merge_base = self.merge_base(base, head)?;-- // git merge-tree exits with 0 for clean merge, 1 for conflicts- // run_command_check returns true for exit 0, false otherwise- let clean_merge = self.run_command_check(&["merge-tree", &merge_base, base, head])?;- Ok(!clean_merge)- }-- /// Get commit subjects (first line of commit message) from a range.- pub fn commit_subjects(&self, range: &str) -> Result<Vec<String>, GitError> {- let output = self.run_command(&["log", "--format=%s", range])?;- Ok(output.lines().map(String::from).collect())- }-- /// Check if there are staged changes.- pub fn has_staged_changes(&self) -> Result<bool, GitError> {- // exit code 0 = no changes, 1 = has changes- let no_changes = self.run_command_check(&["diff", "--cached", "--quiet", "--exit-code"])?;- Ok(!no_changes)- }-- /// List all worktrees for this repository.- ///- /// Returns a WorktreeList that automatically filters out bare repositories- /// 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)?;- WorktreeList::from_raw(raw_worktrees)- }-- /// Find the worktree path for a given branch, if one exists.- pub fn worktree_for_branch(&self, branch: &str) -> Result<Option<PathBuf>, GitError> {- let worktrees = self.list_worktrees()?;-- Ok(worktrees- .iter()- .find(|wt| wt.branch.as_deref() == Some(branch))- .map(|wt| wt.path.clone()))- }-- /// Get branches that don't have worktrees (available for switch).- pub fn available_branches(&self) -> Result<Vec<String>, GitError> {- let all_branches = self.all_branches()?;- let worktrees = self.list_worktrees()?;-- // Collect branches that have worktrees- let branches_with_worktrees: std::collections::HashSet<String> = worktrees- .iter()- .filter_map(|wt| wt.branch.clone())- .collect();-- // Filter out branches with worktrees- Ok(all_branches- .into_iter()- .filter(|branch| !branches_with_worktrees.contains(branch))- .collect())- }-- /// Get a git config value. Returns None if the key doesn't exist.- pub fn get_config(&self, key: &str) -> Result<Option<String>, GitError> {- match self.run_command(&["config", key]) {- Ok(value) => Ok(Some(value.trim().to_string())),- Err(_) => Ok(None), // Config key doesn't exist- }- }-- /// Set a git config value.- pub fn set_config(&self, key: &str, value: &str) -> Result<(), GitError> {- self.run_command(&["config", key, value])?;- Ok(())- }-- /// Remove a worktree at the specified path.- pub fn remove_worktree(&self, path: &std::path::Path) -> Result<(), GitError> {- let path_str = path- .to_str()- .ok_or_else(|| GitError::CommandFailed("Invalid UTF-8 in worktree path".to_string()))?;- self.run_command(&["worktree", "remove", path_str])?;- Ok(())- }-- /// Refresh the default branch cache by querying the remote.- ///- /// This forces a network call to `git ls-remote` to fetch the current default- /// branch from the remote, then updates the local cache. Use this when you- /// suspect the cached default branch is stale (e.g., after a repository's- /// default branch has been changed on the remote).- ///- /// Returns the refreshed default branch name.- pub fn refresh_default_branch(&self) -> Result<String, GitError> {- let remote = self.primary_remote()?;- let branch = self.query_remote_default_branch(&remote)?;- self.cache_default_branch(&remote, &branch)?;- Ok(branch)- }-- // Private helper methods for default_branch()-- 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)- }-- 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)- }-- fn cache_default_branch(&self, remote: &str, branch: &str) -> Result<(), GitError> {- self.run_command(&["remote", "set-head", remote, branch])?;- Ok(())- }-- /// Get a project identifier for approval tracking.- ///- /// Uses the git remote URL if available (e.g., "github.com/user/repo"),- /// otherwise falls back to the repository directory name.- ///- /// This identifier is used to track which commands have been approved- /// for execution in this project.- pub fn project_identifier(&self) -> Result<String, GitError> {- // Try to get the remote URL first- let remote = self.primary_remote()?;-- if let Ok(url) = self.run_command(&["remote", "get-url", &remote]) {- let url = url.trim();-- // Parse common git URL formats:- // - https://github.com/user/repo.git- // - [email protected]:user/repo.git- // - ssh://[email protected]/user/repo.git-- // Remove .git suffix if present- let url = url.strip_suffix(".git").unwrap_or(url);-- // Handle SSH format (git@host:path)- if let Some(ssh_part) = url.strip_prefix("git@")- && let Some((host, path)) = ssh_part.split_once(':')- {- return Ok(format!("{}/{}", host, path));- }-- // Handle HTTPS/HTTP format- if let Some(https_part) = url- .strip_prefix("https://")- .or_else(|| url.strip_prefix("http://"))- {- return Ok(https_part.to_string());- }-- // Handle ssh:// format- if let Some(ssh_part) = url.strip_prefix("ssh://") {- // Remove git@ prefix if present- let ssh_part = ssh_part.strip_prefix("git@").unwrap_or(ssh_part);- // Replace first : with /- if let Some(colon_pos) = ssh_part.find(':') {- let (host, path) = ssh_part.split_at(colon_pos);- return Ok(format!("{}{}", host, path.replacen(':', "/", 1)));- }- return Ok(ssh_part.to_string());- }-- // If we can't parse it, use the URL as-is- return Ok(url.to_string());- }-- // Fall back to repository name (use worktree base for consistency across all worktrees)- let repo_root = self.worktree_base()?;- let repo_name = repo_root- .file_name()- .and_then(|name| name.to_str())- .ok_or_else(|| {- GitError::CommandFailed("Could not determine repository name".to_string())- })?;-- Ok(repo_name.to_string())- }-- /// Run a git command in this repository's context.- ///- /// Executes the git command with this repository's path as the working directory- /// and returns the stdout output.- ///- /// # Examples- /// ```no_run- /// use worktrunk::git::Repository;- ///- /// let repo = Repository::current();- /// let status = repo.run_command(&["status", "--porcelain"])?;- /// # Ok::<(), worktrunk::git::GitError>(())- /// ```- pub fn run_command(&self, args: &[&str]) -> Result<String, GitError> {- let mut cmd = Command::new("git");- cmd.args(args);- cmd.current_dir(&self.path);-- // Log: $ git <args> [worktree]- // TODO: Guard with log::log_enabled! if args.join() overhead becomes measurable- if self.path.to_str() == Some(".") {- log::debug!("$ git {}", args.join(" "));- } else {- let worktree = self- .path- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("?");- log::debug!("$ git {} [{}]", args.join(" "), worktree);- }-- let output = cmd- .output()- .map_err(|e| GitError::CommandFailed(e.to_string()))?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- // Normalize carriage returns to newlines for consistent output- // Git uses \r for progress updates; in non-TTY contexts this causes snapshot instability- let stderr = stderr.replace('\r', "\n");- // Log errors with ! prefix- for line in stderr.trim().lines() {- log::debug!(" ! {}", line);- }- return Err(GitError::CommandFailed(stderr));- }-- let stdout = String::from_utf8_lossy(&output.stdout).into_owned();- if !stdout.is_empty() {- // Log output indented- for line in stdout.trim().lines() {- log::debug!(" {}", line);- }- }- Ok(stdout)- }-- /// Run a git command and return whether it succeeded (exit code 0).- ///- /// This is useful for commands that use exit codes for boolean results,- /// like `git merge-base --is-ancestor` or `git diff --quiet`.- ///- /// # Examples- /// ```no_run- /// use worktrunk::git::Repository;- ///- /// let repo = Repository::current();- /// let is_clean = repo.run_command_check(&["diff", "--quiet", "--exit-code"])?;- /// # Ok::<(), worktrunk::git::GitError>(())- /// ```- pub fn run_command_check(&self, args: &[&str]) -> Result<bool, GitError> {- let mut cmd = Command::new("git");- cmd.args(args);- cmd.current_dir(&self.path);-- // Log: $ git <args> [worktree]- if self.path.to_str() == Some(".") {- log::debug!("$ git {}", args.join(" "));- } else {- let worktree = self- .path- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("?");- log::debug!("$ git {} [{}]", args.join(" "), worktree);- }-- let output = cmd- .output()- .map_err(|e| GitError::CommandFailed(e.to_string()))?;-- let success = output.status.success();- if !success {- log::debug!(" β exit code: non-zero");- }- Ok(success)- }-}--#[cfg(test)]-mod tests {- use super::super::{Worktree, finalize_worktree};- use super::*;-- #[test]- fn test_parse_worktree_list() {- let output = "worktree /path/to/main-HEAD abcd1234-branch refs/heads/main--worktree /path/to/feature-HEAD efgh5678-branch refs/heads/feature--";-- let worktrees = parse_worktree_list(output).unwrap();- assert_eq!(worktrees.len(), 2);-- assert_eq!(worktrees[0].path, PathBuf::from("/path/to/main"));- assert_eq!(worktrees[0].head, "abcd1234");- assert_eq!(worktrees[0].branch, Some("main".to_string()));- assert!(!worktrees[0].bare);- assert!(!worktrees[0].detached);-- assert_eq!(worktrees[1].path, PathBuf::from("/path/to/feature"));- assert_eq!(worktrees[1].head, "efgh5678");- assert_eq!(worktrees[1].branch, Some("feature".to_string()));- }-- #[test]- fn test_parse_detached_worktree() {- let output = "worktree /path/to/detached-HEAD abcd1234-detached--";-- let worktrees = parse_worktree_list(output).unwrap();- assert_eq!(worktrees.len(), 1);- assert!(worktrees[0].detached);- assert_eq!(worktrees[0].branch, None);- }-- #[test]- fn test_finalize_worktree_with_branch() {- // Worktree with a branch should not be modified- let wt = Worktree {- path: PathBuf::from("/path/to/worktree"),- head: "abcd1234".to_string(),- branch: Some("feature".to_string()),- bare: false,- detached: false,- locked: None,- prunable: None,- };-- let finalized = finalize_worktree(wt.clone());- assert_eq!(finalized.branch, Some("feature".to_string()));- }-- #[test]- fn test_finalize_worktree_detached_with_branch() {- // Detached worktree with a branch (unusual but possible) should keep the branch- let wt = Worktree {- path: PathBuf::from("/path/to/worktree"),- head: "abcd1234".to_string(),- branch: Some("feature".to_string()),- bare: false,- detached: true,- locked: None,- prunable: None,- };-- let finalized = finalize_worktree(wt.clone());- assert_eq!(finalized.branch, Some("feature".to_string()));- }-- #[test]- fn test_finalize_worktree_detached_no_branch() {- // Detached worktree with no branch should attempt rebase detection- // Note: This test validates the logic flow but doesn't test actual file reading- // since that would require setting up git rebase state files.- // Actual rebase detection has been manually verified.- let wt = Worktree {- path: PathBuf::from("/nonexistent/path"),- head: "abcd1234".to_string(),- branch: None,- bare: false,- detached: true,- locked: None,- prunable: None,- };-- let finalized = finalize_worktree(wt);- // With a nonexistent path, rebase detection should fail gracefully- // and branch should remain None- assert_eq!(finalized.branch, None);- }-- #[test]- fn test_parse_locked_worktree() {- let output = "worktree /path/to/locked-HEAD abcd1234-branch refs/heads/main-locked reason for lock--";-- let worktrees = parse_worktree_list(output).unwrap();- assert_eq!(worktrees.len(), 1);- assert_eq!(worktrees[0].locked, Some("reason for lock".to_string()));- }-- #[test]- fn test_parse_bare_worktree() {- let output = "worktree /path/to/bare-HEAD abcd1234-bare--";-- let worktrees = parse_worktree_list(output).unwrap();- assert_eq!(worktrees.len(), 1);- assert!(worktrees[0].bare);- }-- #[test]- fn test_parse_local_default_branch_with_prefix() {- let output = "origin/main\n";- let branch = parse_local_default_branch(output, "origin").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();- 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();- 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();- 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();- assert_eq!(branch, "main");- }-- #[test]- fn test_parse_local_default_branch_empty() {- let output = "";- let result = parse_local_default_branch(output, "origin");- assert!(result.is_err());- assert!(matches!(result.unwrap_err(), GitError::ParseError(_)));- }-- #[test]- fn test_parse_local_default_branch_whitespace_only() {- let output = " \n ";- let result = parse_local_default_branch(output, "origin");- assert!(result.is_err());- }-- #[test]- fn test_parse_remote_default_branch_main() {- let output = "ref: refs/heads/main\tHEAD-85a1ce7c7182540f9c02453441cb3e8bf0ced214\tHEAD-";- let branch = parse_remote_default_branch(output).unwrap();- assert_eq!(branch, "main");- }-- #[test]- fn test_parse_remote_default_branch_master() {- let output = "ref: refs/heads/master\tHEAD-abcd1234567890abcd1234567890abcd12345678\tHEAD-";- let branch = parse_remote_default_branch(output).unwrap();- assert_eq!(branch, "master");- }-- #[test]- fn test_parse_remote_default_branch_custom() {- let output = "ref: refs/heads/develop\tHEAD-1234567890abcdef1234567890abcdef12345678\tHEAD-";- let branch = parse_remote_default_branch(output).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();- 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);- assert!(result.is_err());- assert!(matches!(result.unwrap_err(), GitError::ParseError(_)));- }-- #[test]- fn test_parse_remote_default_branch_empty() {- let output = "";- let result = parse_remote_default_branch(output);- assert!(result.is_err());- }-- #[test]- fn test_parse_remote_default_branch_malformed_ref() {- // Missing refs/heads/ prefix- let output = "ref: main\tHEAD\n";- let result = parse_remote_default_branch(output);- assert!(result.is_err());- }-- #[test]- fn test_parse_remote_default_branch_with_spaces() {- // Space instead of tab - should be rejected as malformed input- let output = "ref: refs/heads/main HEAD\n";- let result = parse_remote_default_branch(output);- // Using split_once correctly rejects malformed input with spaces instead of tabs- assert!(result.is_err());- }-- #[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();- assert_eq!(branch, "feature/new-ui");- }-}diff --git a/src/styling.rs.bak b/src/styling.rs.bakdeleted file mode 100644index 79f5d51e2..000000000--- a/src/styling.rs.bak+++ /dev/null@@ -1,930 +0,0 @@-//! Consolidated styling module for terminal output.-//!-//! This module uses the anstyle ecosystem:-//! - anstream for auto-detecting color support-//! - anstyle for composable styling-//! - Semantic style constants for domain-specific use-//!-//! ## stdout vs stderr principle-//!-//! - **stdout**: ALL worktrunk output (messages, errors, warnings, directives, data)-//! - **stderr**: ALL child process output (git, npm, user commands)-//! - **Exception**: Interactive prompts use stderr so they appear even when stdout is redirected-//!-//! Use `println!` for all worktrunk messages. Use `eprintln!` only for interactive prompts.--use anstyle::{AnsiColor, Color, Style};-use synoptic::{TokOpt, from_extension}; // Still used for TOML highlighting-use unicode_width::UnicodeWidthStr;--// ============================================================================-// Re-exports from anstream (auto-detecting output)-// ============================================================================--/// Auto-detecting println that respects NO_COLOR, CLICOLOR_FORCE, and terminal capabilities-pub use anstream::println;--/// Auto-detecting eprintln that respects NO_COLOR, CLICOLOR_FORCE, and terminal capabilities-pub use anstream::eprintln;--/// Auto-detecting print that respects NO_COLOR, CLICOLOR_FORCE, and terminal capabilities-pub use anstream::print;--/// Auto-detecting eprint that respects NO_COLOR, CLICOLOR_FORCE, and terminal capabilities-pub use anstream::eprint;--/// Auto-detecting stderr stream that respects NO_COLOR, CLICOLOR_FORCE, and terminal capabilities-pub use anstream::stderr;--/// Auto-detecting stdout stream that respects NO_COLOR, CLICOLOR_FORCE, and terminal capabilities-pub use anstream::stdout;--// ============================================================================-// Re-exports from anstyle (for composition)-// ============================================================================--/// Re-export Style for users who want to compose custom styles-pub use anstyle::Style as AnstyleStyle;--// ============================================================================-// Semantic Style Constants-// ============================================================================--/// Error style (red) - use as `{ERROR}text{ERROR:#}`-pub const ERROR: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red)));--// ============================================================================-// Message Emojis-// ============================================================================--/// Progress emoji - use with cyan style: `println!("{PROGRESS_EMOJI} {cyan}message{cyan:#}");`-pub const PROGRESS_EMOJI: &str = "π";--/// Success emoji - use with GREEN style: `println!("{SUCCESS_EMOJI} {GREEN}message{GREEN:#}");`-pub const SUCCESS_EMOJI: &str = "β ";--/// Error emoji - use with ERROR style: `println!("{ERROR_EMOJI} {ERROR}message{ERROR:#}");`-pub const ERROR_EMOJI: &str = "β";--/// Warning emoji - use with WARNING style: `println!("{WARNING_EMOJI} {WARNING}message{WARNING:#}");`-pub const WARNING_EMOJI: &str = "π‘";--/// Hint emoji - use with HINT style: `println!("{HINT_EMOJI} {HINT}message{HINT:#}");`-pub const HINT_EMOJI: &str = "π‘";--/// Info emoji - use with dimmed style: `println!("{INFO_EMOJI} {dim}message{dim:#}");`-pub const INFO_EMOJI: &str = "βͺ";--/// Warning style (yellow) - use as `{WARNING}text{WARNING:#}`-pub const WARNING: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)));--/// Hint style (dimmed) - use as `{HINT}text{HINT:#}`-pub const HINT: Style = Style::new().dimmed();--/// Current worktree style (magenta + bold)-pub const CURRENT: Style = Style::new()- .bold()- .fg_color(Some(Color::Ansi(AnsiColor::Magenta)));--/// Addition style for diffs (green)-pub const ADDITION: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));--/// Deletion style for diffs (red)-pub const DELETION: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red)));--/// Cyan style - use as `{CYAN}text{CYAN:#}`-pub const CYAN: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)));--/// Cyan bold style - use as `{CYAN_BOLD}text{CYAN_BOLD:#}`-pub const CYAN_BOLD: Style = Style::new()- .fg_color(Some(Color::Ansi(AnsiColor::Cyan)))- .bold();--/// Green style - use as `{GREEN}text{GREEN:#}`-pub const GREEN: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));--/// Green bold style - use as `{GREEN_BOLD}text{GREEN_BOLD:#}`-pub const GREEN_BOLD: Style = Style::new()- .fg_color(Some(Color::Ansi(AnsiColor::Green)))- .bold();--// ============================================================================-// Styled Output Types-// ============================================================================--/// A piece of text with an optional style-#[derive(Clone, Debug)]-pub struct StyledString {- pub text: String,- pub style: Option<Style>,-}--impl StyledString {- pub fn new(text: impl Into<String>, style: Option<Style>) -> Self {- Self {- text: text.into(),- style,- }- }-- pub fn raw(text: impl Into<String>) -> Self {- Self::new(text, None)- }-- pub fn styled(text: impl Into<String>, style: Style) -> Self {- Self::new(text, Some(style))- }-- /// Returns the visual width (unicode-aware, no ANSI codes)- pub fn width(&self) -> usize {- self.text.width()- }-- /// Renders to a string with ANSI escape codes- pub fn render(&self) -> String {- if let Some(style) = &self.style {- format!("{}{}{}", style.render(), self.text, style.render_reset())- } else {- self.text.clone()- }- }-}--/// A line composed of multiple styled strings-#[derive(Clone, Debug, Default)]-pub struct StyledLine {- pub segments: Vec<StyledString>,-}--impl StyledLine {- pub fn new() -> Self {- Self::default()- }-- /// Add a raw (unstyled) segment- pub fn push_raw(&mut self, text: impl Into<String>) {- self.segments.push(StyledString::raw(text));- }-- /// Add a styled segment- pub fn push_styled(&mut self, text: impl Into<String>, style: Style) {- self.segments.push(StyledString::styled(text, style));- }-- /// Add a segment (StyledString)- pub fn push(&mut self, segment: StyledString) {- self.segments.push(segment);- }-- /// Pad with spaces to reach a specific width- pub fn pad_to(&mut self, target_width: usize) {- let current_width = self.width();- if current_width < target_width {- self.push_raw(" ".repeat(target_width - current_width));- }- }-- /// Returns the total visual width- pub fn width(&self) -> usize {- self.segments.iter().map(|s| s.width()).sum()- }-- /// Renders the entire line with ANSI escape codes- pub fn render(&self) -> String {- self.segments.iter().map(|s| s.render()).collect()- }-}--// ============================================================================-// Gutter Formatting-// ============================================================================--/// Default terminal width fallback if detection fails-const DEFAULT_TERMINAL_WIDTH: usize = 80;--/// Get terminal width, defaulting to 80 if detection fails-///-/// Checks COLUMNS environment variable first (for testing and scripts),-/// then falls back to actual terminal size detection.-fn get_terminal_width() -> usize {- // Check COLUMNS environment variable first (for testing and scripts)- if let Ok(cols) = std::env::var("COLUMNS")- && let Ok(width) = cols.parse::<usize>()- {- return width;- }-- // Fall back to actual terminal size- terminal_size::terminal_size()- .map(|(terminal_size::Width(w), _)| w as usize)- .unwrap_or(DEFAULT_TERMINAL_WIDTH)-}--/// Wraps text at word boundaries to fit within the specified width-///-/// # Arguments-/// * `text` - The text to wrap-/// * `max_width` - Maximum width for each line-///-/// # Returns-/// A vector of wrapped lines-fn wrap_text_at_width(text: &str, max_width: usize) -> Vec<String> {- if max_width == 0 {- return vec![text.to_string()];- }-- let text_width = text.width();-- // If the line fits, return it as-is- if text_width <= max_width {- return vec![text.to_string()];- }-- let mut lines = Vec::new();- let mut current_line = String::new();- let mut current_width = 0;-- for word in text.split_whitespace() {- let word_width = word.width();-- // If this is the first word in the line- if current_line.is_empty() {- // If a single word is longer than max_width, we have to include it anyway- current_line = word.to_string();- current_width = word_width;- } else {- // Calculate width with space before the word- let new_width = current_width + 1 + word_width;-- if new_width <= max_width {- // Word fits on current line- current_line.push(' ');- current_line.push_str(word);- current_width = new_width;- } else {- // Word doesn't fit, start a new line- lines.push(current_line);- current_line = word.to_string();- current_width = word_width;- }- }- }-- // Add the last line if there's content- if !current_line.is_empty() {- lines.push(current_line);- }-- // Handle empty input- if lines.is_empty() {- lines.push(String::new());- }-- lines-}--/// Formats text with a gutter (single-space with background color) on each line-///-/// This creates a subtle visual separator for quoted content like commands or configuration.-/// Text is automatically word-wrapped at terminal width to prevent overflow.-///-/// # Arguments-/// * `content` - The text to format (preserves internal structure for multi-line)-/// * `left_margin` - Should always be "" (gutter provides all visual separation)-/// * `max_width` - Optional maximum width (for testing). If None, auto-detects terminal width.-///-/// The gutter appears at column 0, followed by 2 spaces, then the content starts at column 3.-/// This aligns with emoji messages where the emoji (2 columns) + space (1 column) also starts content at column 3.-///-/// # Example-/// ```ignore-/// // All contexts use empty left margin and auto-detect width-/// print!("{}", format_with_gutter(&config, "", None));-/// ```-pub fn format_with_gutter(content: &str, left_margin: &str, max_width: Option<usize>) -> String {- let gutter = Style::new().bg_color(Some(Color::Ansi(AnsiColor::Black)));- let mut output = String::new();-- // Use provided width or detect terminal width (respects COLUMNS env var)- let term_width = max_width.unwrap_or_else(get_terminal_width);-- // Account for gutter (1) + spaces (2) + left_margin- let left_margin_width = left_margin.width();- let available_width = term_width.saturating_sub(3 + left_margin_width);-- for line in content.lines() {- // Wrap the line at word boundaries- let wrapped_lines = wrap_text_at_width(line, available_width);-- for wrapped_line in wrapped_lines {- output.push_str(&format!(- "{left_margin}{gutter} {gutter:#} {wrapped_line}\n"- ));- }- }-- output-}--/// Formats bash/shell commands with syntax highlighting and gutter-///-/// Similar to `format_with_gutter` but applies bash syntax highlighting using tree-sitter.-/// Long lines are wrapped at word boundaries to fit terminal width.-///-/// # Example-/// ```ignore-/// print!("{}", format_bash_with_gutter("npm install --frozen-lockfile"));-/// ```-#[cfg(feature = "syntax-highlighting")]-pub fn format_bash_with_gutter(content: &str, left_margin: &str) -> String {- use tree_sitter_highlight::{HighlightConfiguration, HighlightEvent, Highlighter};-- let gutter = Style::new().bg_color(Some(Color::Ansi(AnsiColor::Black)));- let mut output = String::new();-- // Calculate available width for wrapping- let term_width = get_terminal_width();- let left_margin_width = left_margin.width();- let available_width = term_width.saturating_sub(3 + left_margin_width);-- // Wrap lines at word boundaries- let mut wrapped_lines = Vec::new();- for line in content.lines() {- let wrapped = wrap_text_at_width(line, available_width);- wrapped_lines.extend(wrapped);- }-- // Set up tree-sitter bash highlighting- let highlight_names = vec![- "function", // Commands like npm, git, cargo- "keyword", // Keywords like for, if, while- "string", // Quoted strings- "operator", // Operators like &&, ||, |, $, -- "comment", // Comments- "number", // Numbers- "variable", // Variables- "constant", // Constants/flags- ];-- let bash_language = tree_sitter_bash::language();- let bash_highlights = tree_sitter_bash::HIGHLIGHT_QUERY;-- let mut config = HighlightConfiguration::new(- bash_language,- bash_highlights,- "", // injections query- "", // locals query- )- .unwrap_or_else(|_| {- // Fallback: if tree-sitter fails, use plain gutter formatting- HighlightConfiguration::new(- bash_language,- "", // empty query- "",- "",- )- .unwrap()- });-- config.configure(&highlight_names);-- let mut highlighter = Highlighter::new();-- // Process each wrapped line- for line in &wrapped_lines {- output.push_str(&format!("{left_margin}{gutter} {gutter:#} "));-- // Highlight this line- let Ok(highlights) = highlighter.highlight(&config, line.as_bytes(), None, |_| None) else {- // Fallback: just print plain text if highlighting fails- output.push_str(line);- output.push('\n');- continue;- };-- let line_bytes = line.as_bytes();-- for event in highlights {- match event.unwrap() {- HighlightEvent::Source { start, end } => {- // Output the text for this source region- if let Ok(text) = std::str::from_utf8(&line_bytes[start..end]) {- output.push_str(text);- }- }- HighlightEvent::HighlightStart(idx) => {- // Start of a highlighted region - apply style- if let Some(name) = highlight_names.get(idx.0)- && let Some(style) = bash_token_style(name)- {- output.push_str(&format!("{style}"));- }- }- HighlightEvent::HighlightEnd => {- // End of highlighted region - reset style- output.push_str(&format!("{}", anstyle::Reset));- }- }- }-- // Ensure all styles are reset at end of line to prevent leaking into child process output- output.push_str(&format!("{}", anstyle::Reset));- output.push('\n');- }-- output-}--/// Format bash commands with gutter (fallback without syntax highlighting)-///-/// This version is used when the `syntax-highlighting` feature is disabled.-/// It provides the same gutter formatting without tree-sitter dependencies.-#[cfg(not(feature = "syntax-highlighting"))]-pub fn format_bash_with_gutter(content: &str, left_margin: &str) -> String {- let gutter = Style::new().bg_color(Some(Color::Ansi(AnsiColor::Black)));- let mut output = String::new();-- // Calculate available width for wrapping- let term_width = get_terminal_width();- let left_margin_width = left_margin.width();- let available_width = term_width.saturating_sub(3 + left_margin_width);-- // Wrap lines at word boundaries- let mut wrapped_lines = Vec::new();- for line in content.lines() {- let wrapped = wrap_text_at_width(line, available_width);- wrapped_lines.extend(wrapped);- }-- // Process each wrapped line with plain gutter (no syntax highlighting)- for line in &wrapped_lines {- output.push_str(&format!("{left_margin}{gutter} {gutter:#} "));- output.push_str(line);- // Ensure all styles are reset at end of line to prevent leaking into child process output- output.push_str(&format!("{}", anstyle::Reset));- output.push('\n');- }-- output-}--// ============================================================================-// Bash Syntax Highlighting-// ============================================================================--/// Maps bash token kinds to anstyle styles-///-/// Token names come from tree-sitter-bash's highlight queries.-/// Common tokens include:-/// - "function": commands like npm, git, cargo, echo, cd-/// - "keyword": bash keywords (if, then, for, while, do, done, etc.)-/// - "string": quoted strings-/// - "comment": hash-prefixed comments-/// - "operator": operators like &&, ||, |, $, -, etc.-/// - "constant": flags (arguments starting with -)-#[cfg(feature = "syntax-highlighting")]-fn bash_token_style(kind: &str) -> Option<Style> {- match kind {- // Commands (npm, git, cargo, echo, cd, etc.) - bold blue- "function" => Some(- Style::new()- .fg_color(Some(Color::Ansi(AnsiColor::Blue)))- .bold(),- ),-- // Keywords (if, then, for, while, do, done, etc.) - bold magenta- "keyword" => Some(- Style::new()- .fg_color(Some(Color::Ansi(AnsiColor::Magenta)))- .bold(),- ),-- // Strings (quoted values) - green- "string" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green)))),-- // Comments (hash-prefixed) - dimmed- "comment" => Some(Style::new().dimmed()),-- // Operators (&&, ||, |, $, -, >, <, etc.) - cyan- "operator" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)))),-- // Variables ($VAR, ${VAR}) - yellow- "variable" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)))),-- // Numbers - yellow- "digit" | "number" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)))),-- // Constants/flags (--flag, -f) - cyan- "constant" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)))),-- // Everything else (plain arguments, etc.)- _ => None,- }-}--// ============================================================================-// TOML Syntax Highlighting-// ============================================================================--/// Formats TOML content with syntax highlighting using synoptic-pub fn format_toml(content: &str, left_margin: &str) -> String {- // Gutter style: subtle background for visual separation- let gutter = Style::new().bg_color(Some(Color::Ansi(AnsiColor::Black)));-- // Get TOML highlighter from synoptic's built-in rules (tab_width = 4)- let mut highlighter = match from_extension("toml", 4) {- Some(h) => h,- None => {- // Fallback: return dimmed content if TOML highlighter not available- let dim = Style::new().dimmed();- let mut output = String::new();- for line in content.lines() {- output.push_str(&format!(- "{left_margin}{gutter} {gutter:#} {dim}{line}{dim:#}\n"- ));- }- return output;- }- };-- let mut output = String::new();- let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();-- // Process all lines through the highlighter- highlighter.run(&lines);-- // Render each line with appropriate styling- for (y, line) in lines.iter().enumerate() {- // Add left margin, gutter, and spacing- output.push_str(&format!("{left_margin}{gutter} {gutter:#} "));-- // Render each token with appropriate styling- for token in highlighter.line(y, line) {- match token {- TokOpt::Some(text, kind) => {- let style = toml_token_style(&kind);- if let Some(s) = style {- output.push_str(&format!("{s}{text}{s:#}"));- } else {- output.push_str(&text);- }- }- TokOpt::None(text) => {- output.push_str(&text);- }- }- }-- output.push('\n');- }-- output-}--/// Maps TOML token kinds to anstyle styles-///-/// Token names come from synoptic's TOML highlighter:-/// - "string": quoted strings-/// - "comment": hash-prefixed comments-/// - "boolean": true/false values-/// - "table": table headers [...]-/// - "digit": numeric values-fn toml_token_style(kind: &str) -> Option<Style> {- match kind {- // Strings (quoted values)- "string" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green)))),-- // Comments (hash-prefixed)- "comment" => Some(Style::new().dimmed()),-- // Table headers [table] and [[array]]- "table" => Some(- Style::new()- .fg_color(Some(Color::Ansi(AnsiColor::Cyan)))- .bold(),- ),-- // Booleans and numbers- "boolean" | "digit" => Some(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)))),-- // Everything else (operators, punctuation, keys)- _ => None,- }-}--// ============================================================================-// Tests-// ============================================================================--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_toml_formatting() {- let toml_content = r#"worktree-path = "../{repo}.{branch}"--[llm]-args = []--# This is a comment-[[approved-commands]]-project = "github.com/user/repo"-command = "npm install"-"#;-- let output = format_toml(toml_content, "");-- // Check that output contains ANSI escape codes- assert!(- output.contains("\x1b["),- "Output should contain ANSI escape codes"- );-- // Check that strings are highlighted (green = 32)- assert!(- output.contains("\x1b[32m"),- "Should contain green color for strings"- );-- // Check that comments are dimmed (dim = 2)- assert!(- output.contains("\x1b[2m"),- "Should contain dim style for comments"- );-- // Check that table headers are highlighted (cyan = 36, bold = 1)- assert!(- output.contains("\x1b[36m") || output.contains("\x1b[1m"),- "Should contain cyan or bold for tables"- );-- // Check that gutter background is present (Black background = 40)- assert!(- output.contains("\x1b[40m"),- "Should contain gutter background color (Black = 40)"- );-- // Check that lines have content (not just gutter)- assert!(- output.lines().any(|line| line.len() > 20),- "Should have lines with actual content beyond gutter and indent"- );- }-- // StyledString tests- #[test]- fn test_styled_string_width() {- // ASCII strings- let s = StyledString::raw("hello");- assert_eq!(s.width(), 5);-- // Unicode arrows- let s = StyledString::raw("β3 β2");- assert_eq!(- s.width(),- 5,- "β3 β2 should have width 5, not {}",- s.text.len()- );-- // Mixed Unicode- let s = StyledString::raw("ζ₯ζ¬θͺ");- assert_eq!(s.width(), 6); // CJK characters are typically width 2-- // Emoji- let s = StyledString::raw("π");- assert_eq!(s.width(), 2); // Emoji are typically width 2- }-- // StyledLine tests- #[test]- fn test_styled_line_width() {- let mut line = StyledLine::new();- line.push_raw("Branch");- line.push_raw(" ");- line.push_raw("β3 β2");-- // "Branch" (6) + " " (2) + "β3 β2" (5) = 13- assert_eq!(line.width(), 13, "Line width should be 13");- }-- #[test]- fn test_styled_line_padding() {- let mut line = StyledLine::new();- line.push_raw("test");- assert_eq!(line.width(), 4);-- line.pad_to(10);- assert_eq!(line.width(), 10, "After padding to 10, width should be 10");-- // Padding when already at target should not change width- line.pad_to(10);- assert_eq!(line.width(), 10, "Padding again should not change width");- }-- #[test]- fn test_sparse_column_padding() {- // Build simplified lines to test sparse column padding- let mut line1 = StyledLine::new();- line1.push_raw(format!("{:8}", "branch-a"));- line1.push_raw(" ");- // Has ahead/behind- line1.push_raw(format!("{:5}", "β3 β2"));- line1.push_raw(" ");-- let mut line2 = StyledLine::new();- line2.push_raw(format!("{:8}", "branch-b"));- line2.push_raw(" ");- // No ahead/behind, should pad with spaces- line2.push_raw(" ".repeat(5));- line2.push_raw(" ");-- // Both lines should have same width up to this point- assert_eq!(- line1.width(),- line2.width(),- "Rows with and without sparse column data should have same width"- );- }-- // Word-wrapping tests- #[test]- fn test_wrap_text_no_wrapping_needed() {- let result = super::wrap_text_at_width("short line", 50);- assert_eq!(result, vec!["short line"]);- }-- #[test]- fn test_wrap_text_at_word_boundary() {- let text = "This is a very long line that needs to be wrapped at word boundaries";- let result = super::wrap_text_at_width(text, 30);-- // Should wrap at word boundaries- assert!(result.len() > 1, "Should wrap into multiple lines");-- // Each line should be within the width limit (or be a single long word)- for line in &result {- assert!(- line.width() <= 30 || !line.contains(' '),- "Line '{}' has width {} which exceeds 30 and contains spaces",- line,- line.width()- );- }-- // Joining should recover most of the original text (whitespace may differ)- let rejoined = result.join(" ");- assert_eq!(- rejoined.split_whitespace().collect::<Vec<_>>(),- text.split_whitespace().collect::<Vec<_>>()- );- }-- #[test]- fn test_wrap_text_single_long_word() {- // A single word longer than max_width should still be included- let result = super::wrap_text_at_width("verylongwordthatcannotbewrapped", 10);- assert_eq!(result.len(), 1);- assert_eq!(result[0], "verylongwordthatcannotbewrapped");- }-- #[test]- fn test_wrap_text_empty_input() {- let result = super::wrap_text_at_width("", 50);- assert_eq!(result, vec![""]);- }-- #[test]- fn test_wrap_text_unicode() {- // Unicode characters should be handled correctly by width- let text = "This line has emoji π and should wrap correctly when needed";- let result = super::wrap_text_at_width(text, 30);-- // Should wrap- assert!(result.len() > 1);-- // Should preserve the emoji- let rejoined = result.join(" ");- assert!(rejoined.contains("π"));- }-- #[test]- fn test_format_with_gutter_wrapping() {- // Create a very long line that would overflow a narrow terminal- let long_text = "This is a very long commit message that would normally overflow the terminal width and break the gutter formatting, but now it should wrap nicely at word boundaries.";-- // Use fixed width for consistent testing (80 columns)- let result = format_with_gutter(long_text, "", Some(80));-- // Should contain multiple lines (wrapped)- let line_count = result.lines().count();- assert!(- line_count > 1,- "Long text should wrap to multiple lines, got {} lines",- line_count- );-- // Each line should have the gutter- for line in result.lines() {- assert!(- line.contains("\x1b[40m"),- "Each line should contain gutter (Black background = 40)"- );- }- }-- #[test]- fn test_format_with_gutter_preserves_newlines() {- let multi_line = "Line 1\nLine 2\nLine 3";- let result = format_with_gutter(multi_line, "", None);-- // Should have at least 3 lines (one for each input line)- assert!(result.lines().count() >= 3);-- // Each original line should be present- assert!(result.contains("Line 1"));- assert!(result.contains("Line 2"));- assert!(result.contains("Line 3"));- }-- #[test]- fn test_format_with_gutter_long_paragraph() {- // Realistic commit message scenario - a long unbroken paragraph- let commit_msg = "This commit refactors the authentication system to use a more secure token-based approach instead of the previous session-based system which had several security vulnerabilities that were identified during the security audit last month. The new implementation follows industry best practices and includes proper token rotation and expiration handling.";-- // Use fixed width for consistent testing (80 columns)- let result = format_with_gutter(commit_msg, "", Some(80));-- insta::assert_snapshot!(result, @r"- [40m [0m This commit refactors the authentication system to use a more secure- [40m [0m token-based approach instead of the previous session-based system which had- [40m [0m several security vulnerabilities that were identified during the security- [40m [0m audit last month. The new implementation follows industry best practices and- [40m [0m includes proper token rotation and expiration handling.- ");- }-- #[test]- fn test_bash_gutter_formatting_ends_with_reset() {- // Test that bash gutter formatting properly resets colors at the end of each line- // to prevent color bleeding into subsequent output (like child process output)- let command = "pre-commit run --all-files";- let result = format_bash_with_gutter(command, "");-- // The output should end with ANSI reset code followed by newline- // ANSI reset is \x1b[0m (ESC[0m)- assert!(- result.ends_with("\x1b[0m\n"),- "Bash gutter formatting should end with ANSI reset code followed by newline, got: {:?}",- result.chars().rev().take(20).collect::<String>()- );-- // Verify the reset appears at the end of EVERY line (for multi-line commands)- let multi_line_command = "npm install && \\\n npm run build";- let multi_result = format_bash_with_gutter(multi_line_command, "");-- // Each line should end with reset code- for line in multi_result.lines() {- if !line.is_empty() {- // Check that line contains a reset code somewhere- // (The actual position depends on the highlighting, but it should be present)- assert!(- line.contains("\x1b[0m"),- "Each line should contain ANSI reset code, line: {:?}",- line- );- }- }-- // Most importantly: the final output should end with reset + newline- assert!(- multi_result.ends_with("\x1b[0m\n"),- "Multi-line bash gutter formatting should end with ANSI reset + newline"- );- }-- #[test]- fn test_reset_code_behavior() {- // IMPORTANT: {:#} on Style::new() produces an EMPTY STRING, not a reset!- // This is the root cause of color bleeding bugs.- let style_reset = format!("{:#}", Style::new());- assert_eq!(- style_reset, "",- "Style::new() with {{:#}} produces empty string (this is why we had color leaking!)"- );-- // The correct way to get a reset code is anstyle::Reset- let anstyle_reset = format!("{}", anstyle::Reset);- assert_eq!(- anstyle_reset, "\x1b[0m",- "anstyle::Reset produces proper ESC[0m reset code"- );-- // Document the fix: always use anstyle::Reset, never {:#} on Style::new()- assert_ne!(- style_reset, anstyle_reset,- "Style::new() and anstyle::Reset are NOT equivalent - always use anstyle::Reset"- );- }-}