Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Replace path string manipulation with Path/PathBuf methods (#448)
Maximilian Roos6275c35a1429
diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rsindex 6a35317f2..25e916212 100644--- a/src/commands/list/ci_status.rs+++ b/src/commands/list/ci_status.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize, de::DeserializeOwned};use std::fs;-use std::path::PathBuf;+use std::path::{Path, PathBuf};use std::process::Command;use worktrunk::git::{Repository, parse_owner_repo, parse_remote_host, parse_remote_owner};use worktrunk::path::sanitize_for_filename;@@ -128,6 +128,8 @@ mod tests {#[test]fn test_ttl_jitter_range_and_determinism() {+ use std::path::Path;+// Check range: TTL should be in [30, 60)let paths = ["/tmp/repo1",@@ -136,7 +138,7 @@ mod tests {"/home/user/code",];for path in paths {- let ttl = CachedCiStatus::ttl_for_repo(path);+ let ttl = CachedCiStatus::ttl_for_repo(Path::new(path));assert!((30..60).contains(&ttl),"TTL {} for path {} should be in [30, 60)",@@ -146,7 +148,7 @@ mod tests {}// Check determinism: same path should always produce same TTL- let path = "/some/consistent/path";+ let path = Path::new("/some/consistent/path");let ttl1 = CachedCiStatus::ttl_for_repo(path);let ttl2 = CachedCiStatus::ttl_for_repo(path);assert_eq!(ttl1, ttl2, "Same path should produce same TTL");@@ -155,7 +157,7 @@ mod tests {let diverse_paths: Vec<_> = (0..20).map(|i| format!("/repo/path{}", i)).collect();let ttls: std::collections::HashSet<_> = diverse_paths.iter()- .map(|p| CachedCiStatus::ttl_for_repo(p))+ .map(|p| CachedCiStatus::ttl_for_repo(Path::new(p))).collect();// With 20 paths mapping to 30 possible values, we expect good diversityassert!(@@ -854,12 +856,13 @@ impl CachedCiStatus {////// Different directories get different TTLs [30, 60) seconds, which spreads/// out cache expirations when multiple statuslines run concurrently.- pub(crate) fn ttl_for_repo(repo_root: &str) -> u64 {+ pub(crate) fn ttl_for_repo(repo_root: &Path) -> u64 {use std::collections::hash_map::DefaultHasher;use std::hash::{Hash, Hasher};let mut hasher = DefaultHasher::new();- repo_root.hash(&mut hasher);+ // Hash the path bytes directly for consistent TTL across string representations+ repo_root.as_os_str().hash(&mut hasher);let hash = hasher.finish();// Map hash to jitter range [0, TTL_JITTER_SECS)@@ -868,7 +871,7 @@ impl CachedCiStatus {}/// Check if the cache is still valid- fn is_valid(&self, current_head: &str, now_secs: u64, repo_root: &str) -> bool {+ fn is_valid(&self, current_head: &str, now_secs: u64, repo_root: &Path) -> bool {// Cache is valid if:// 1. HEAD hasn't changed (same commit)// 2. TTL hasn't expired (with deterministic jitter based on repo path)@@ -877,21 +880,21 @@ impl CachedCiStatus {}/// Get the cache directory path: `.git/wt-cache/ci-status/`- fn cache_dir(repo_root: &str) -> Option<PathBuf> {+ fn cache_dir(repo_root: &Path) -> Option<PathBuf> {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> {+ fn cache_file(branch: &str, repo_root: &Path) -> Option<PathBuf> {let dir = Self::cache_dir(repo_root)?;let safe_branch = sanitize_for_filename(branch);Some(dir.join(format!("{safe_branch}.json")))}/// Read cached CI status from file.- fn read(branch: &str, repo_root: &str) -> Option<Self> {+ fn read(branch: &str, repo_root: &Path) -> Option<Self> {let path = Self::cache_file(branch, repo_root)?;let json = fs::read_to_string(&path).ok()?;serde_json::from_str(&json).ok()@@ -901,7 +904,7 @@ impl CachedCiStatus {////// Uses atomic write (write to temp file, then rename) to avoid corruption/// and minimize lock contention on Windows.- fn write(&self, branch: &str, repo_root: &str) {+ fn write(&self, branch: &str, repo_root: &Path) {let Some(path) = Self::cache_file(branch, repo_root) else {log::debug!("Failed to get cache path for {}", branch);return;@@ -941,7 +944,7 @@ impl CachedCiStatus {Err(_) => return Vec::new(),};- let Some(cache_dir) = Self::cache_dir(repo_root.to_str().unwrap_or_default()) else {+ let Some(cache_dir) = Self::cache_dir(repo_root) else {return Vec::new();};@@ -975,7 +978,7 @@ impl CachedCiStatus {Err(_) => return 0,};- let Some(cache_dir) = Self::cache_dir(repo_root.to_str().unwrap_or_default()) else {+ let Some(cache_dir) = Self::cache_dir(repo_root) else {return 0;};@@ -1100,20 +1103,16 @@ impl PrStatus {repo_path: &std::path::Path,has_upstream: bool,) -> Option<Self> {- // We run gh/glab commands from the repo directory to let them auto-detect the correct repo- // (including upstream repos for forks)- let repo_root = repo_path.to_str()?;-// Check cache first to avoid hitting API rate limitslet now_secs = get_now();- if let Some(cached) = CachedCiStatus::read(branch, repo_root) {- if cached.is_valid(local_head, now_secs, repo_root) {+ if let Some(cached) = CachedCiStatus::read(branch, repo_path) {+ if cached.is_valid(local_head, now_secs, repo_path) {log::debug!("Using cached CI status for {} (age={}s, ttl={}s, status={:?})",branch,now_secs - cached.checked_at,- CachedCiStatus::ttl_for_repo(repo_root),+ CachedCiStatus::ttl_for_repo(repo_path),cached.status.as_ref().map(|s| &s.ci_status));return cached.status;@@ -1122,13 +1121,16 @@ impl PrStatus {"Cache expired for {} (age={}s, ttl={}s, head_match={})",branch,now_secs - cached.checked_at,- CachedCiStatus::ttl_for_repo(repo_root),+ CachedCiStatus::ttl_for_repo(repo_path),cached.head == local_head);}// Cache miss or expired - fetch fresh status- let status = Self::detect_uncached(branch, local_head, repo_root, has_upstream);+ // We run gh/glab commands from the repo directory to let them auto-detect the correct repo+ // (including upstream repos for forks)+ let repo_root = repo_path.to_string_lossy();+ let status = Self::detect_uncached(branch, local_head, &repo_root, has_upstream);// Cache the result (including None - means no CI found for this branch)let cached = CachedCiStatus {@@ -1136,7 +1138,7 @@ impl PrStatus {checked_at: now_secs,head: local_head.to_string(),};- cached.write(branch, repo_root);+ cached.write(branch, repo_path);status}diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex f40a01d3e..aba280623 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -611,7 +611,8 @@ pub fn handle_switch(// Create the worktree// Build git worktree add command- let mut args = vec!["worktree", "add", worktree_path.to_str().unwrap()];+ let worktree_path_str = worktree_path.to_string_lossy();+ let mut args = vec!["worktree", "add", worktree_path_str.as_ref()];// Use the resolved base, or default to default branch if creating without a base.// For bare repos with no branches yet (bootstrap case), allow None to create orphan branch.@@ -975,6 +976,7 @@ pub fn handle_push(// Get git common dir for the pushlet git_common_dir = repo.git_common_dir()?;+ let git_common_dir_str = git_common_dir.to_string_lossy();// Perform the push - stash guard will auto-restore on any exit path// Use --receive-pack to pass config to the receiving end without permanently mutating repo config@@ -982,7 +984,7 @@ pub fn handle_push(repo.run_command(&["push","--receive-pack=git -c receive.denyCurrentBranch=updateInstead receive-pack",- git_common_dir.to_str().unwrap(),+ git_common_dir_str.as_ref(),&push_target,]).map_err(|e| {diff --git a/src/display.rs b/src/display.rsindex 20c8a4991..6add56fa5 100644--- a/src/display.rs+++ b/src/display.rs@@ -61,6 +61,8 @@ fn format_relative_time_impl(timestamp: i64, now: i64) -> String {/// - Sibling: `../sibling`/// - Unrelated paths fall back to `~/...` or absolutepub fn shorten_path(path: &Path, main_worktree_path: &Path) -> String {+ use std::path::Component;+// Same path = main worktreeif path == main_worktree_path {return ".".to_string();@@ -68,13 +70,12 @@ pub fn shorten_path(path: &Path, main_worktree_path: &Path) -> String {// Try to compute relative pathif let Some(relative) = pathdiff::diff_paths(path, main_worktree_path) {- let rel_str = relative.display().to_string();// If relative path starts with "..", it's a sibling/ancestor// Otherwise prefix with "./" (or ".\" on Windows) for clarity- if rel_str.starts_with("..") {- rel_str+ if relative.components().next() == Some(Component::ParentDir) {+ relative.display().to_string()} else {- format!(".{}{}", std::path::MAIN_SEPARATOR, rel_str)+ format!(".{}{}", std::path::MAIN_SEPARATOR, relative.display())}} else {// Can't compute relative path (e.g., different drives on Windows)diff --git a/src/shell.rs b/src/shell.rsindex 6d8fcc9c1..2906b5fb9 100644--- a/src/shell.rs+++ b/src/shell.rs@@ -1013,20 +1013,29 @@ mod tests {// Fish config path should include prefix in filenamelet fish_paths = Shell::Fish.config_paths(prefix).unwrap();assert!(- fish_paths[0].to_string_lossy().contains("custom-wt.fish"),+ fish_paths[0]+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains("custom-wt.fish")),"Fish config should include prefix in filename");// Bash and Zsh config paths are fixed (not affected by prefix)let bash_paths = Shell::Bash.config_paths(prefix).unwrap();assert!(- bash_paths[0].to_string_lossy().contains(".bashrc"),+ bash_paths[0]+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains(".bashrc")),"Bash config should be .bashrc");let zsh_paths = Shell::Zsh.config_paths(prefix).unwrap();assert!(- zsh_paths[0].to_string_lossy().contains(".zshrc"),+ zsh_paths[0]+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains(".zshrc")),"Zsh config should be .zshrc");}@@ -1038,21 +1047,30 @@ mod tests {// Bash completion should include prefix in pathlet bash_path = Shell::Bash.completion_path(prefix).unwrap();assert!(- bash_path.to_string_lossy().contains("my-prefix"),+ bash_path+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains("my-prefix")),"Bash completion should include prefix");// Fish completion should include prefix in filenamelet fish_path = Shell::Fish.completion_path(prefix).unwrap();assert!(- fish_path.to_string_lossy().contains("my-prefix.fish"),+ fish_path+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains("my-prefix.fish")),"Fish completion should include prefix in filename");// Zsh completion should include prefixlet zsh_path = Shell::Zsh.completion_path(prefix).unwrap();assert!(- zsh_path.to_string_lossy().contains("_my-prefix"),+ zsh_path+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains("_my-prefix")),"Zsh completion should include underscore prefix");}