Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Fix branch names with slashes breaking git config markers (#189)
kyleacmooney02b66ff1e767
diff --git a/.claude-plugin/hooks/hooks.json b/.claude-plugin/hooks/hooks.jsonindex 596bdddc8..4c1455b2e 100644--- a/.claude-plugin/hooks/hooks.json+++ b/.claude-plugin/hooks/hooks.json@@ -5,7 +5,7 @@"hooks": [{"type": "command",- "command": "git branch --show-current 2>/dev/null | xargs -I {} git config worktrunk.marker.{} π€"+ "command": "wt config state marker set π€ || true"}]}@@ -16,7 +16,7 @@"hooks": [{"type": "command",- "command": "git branch --show-current 2>/dev/null | xargs -I {} git config worktrunk.marker.{} π¬"+ "command": "wt config state marker set π¬ || true"}]}@@ -27,7 +27,7 @@"hooks": [{"type": "command",- "command": "git branch --show-current 2>/dev/null | xargs -I {} git config --unset worktrunk.marker.{} 2>/dev/null || true"+ "command": "wt config state marker clear || true"}]}diff --git a/src/commands/config.rs b/src/commands/config.rsindex 8478a695b..13ccf8153 100644--- a/src/commands/config.rs+++ b/src/commands/config.rs@@ -637,7 +637,7 @@ pub fn handle_state_get(key: &str, refresh: bool, branch: Option<String>) -> any// Clear cache to force refreshlet config_key = format!("worktrunk.ci.{}",- super::list::ci_status::CachedCiStatus::escape_branch(&branch_name)+ worktrunk::git::escape_branch_for_config(&branch_name));let _ = repo.run_command(&["config", "--unset", &config_key]);}@@ -759,7 +759,8 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any"set_at": now});- let config_key = format!("worktrunk.marker.{}", branch_name);+ let escaped = worktrunk::git::escape_branch_for_config(&branch_name);+ let config_key = format!("worktrunk.marker.{}", escaped);repo.run_command(&["config", &config_key, &json.to_string()])?;crate::output::print(success_message(cformat!(@@ -815,7 +816,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho};let config_key = format!("worktrunk.ci.{}",- super::list::ci_status::CachedCiStatus::escape_branch(&branch_name)+ worktrunk::git::escape_branch_for_config(&branch_name));if repo.run_command(&["config", "--unset", &config_key])@@ -859,7 +860,8 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyhoNone => repo.require_current_branch("clear marker for current branch")?,};- let config_key = format!("worktrunk.marker.{}", branch_name);+ let escaped = worktrunk::git::escape_branch_for_config(&branch_name);+ let config_key = format!("worktrunk.marker.{}", escaped);if repo.run_command(&["config", "--unset", &config_key]).is_ok()@@ -1211,10 +1213,11 @@ fn get_all_markers(repo: &Repository) -> Vec<MarkerEntry> {let mut markers = Vec::new();for line in output.lines() {- // Format: "worktrunk.marker.branch_name json_or_plain_value"+ // Format: "worktrunk.marker.escaped_branch json_or_plain_value"if let Some((key, value)) = line.split_once(' ')- && let Some(branch) = key.strip_prefix("worktrunk.marker.")+ && let Some(escaped_branch) = key.strip_prefix("worktrunk.marker."){+ let branch = worktrunk::git::unescape_branch_from_config(escaped_branch);// Try to parse as JSON, fall back to legacy plain-textif let Ok(parsed) = serde_json::from_str::<serde_json::Value>(value) {// Skip if "marker" field is missing (corrupted data)@@ -1223,14 +1226,14 @@ fn get_all_markers(repo: &Repository) -> Vec<MarkerEntry> {};let set_at = parsed.get("set_at").and_then(|v| v.as_u64()).unwrap_or(0);markers.push(MarkerEntry {- branch: branch.to_string(),+ branch,marker: marker.to_string(),set_at,});} else {// Legacy plain-text marker (no timestamp)markers.push(MarkerEntry {- branch: branch.to_string(),+ branch,marker: value.to_string(),set_at: 0, // Unknown age});diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rsindex b6bb06203..5436ba4f2 100644--- a/src/commands/list/ci_status.rs+++ b/src/commands/list/ci_status.rs@@ -270,6 +270,8 @@ mod tests {#[test]fn test_escape_branch_round_trip() {+ use worktrunk::git::{escape_branch_for_config, unescape_branch_from_config};+let cases = ["main","feature/test",@@ -289,8 +291,8 @@ mod tests {];for branch in cases {- let escaped = CachedCiStatus::escape_branch(branch);- let unescaped = CachedCiStatus::unescape_branch(&escaped);+ let escaped = escape_branch_for_config(branch);+ let unescaped = unescape_branch_from_config(&escaped);assert_eq!(unescaped, branch,"Round-trip failed for '{}': escaped='{}', unescaped='{}'",@@ -301,6 +303,8 @@ mod tests {#[test]fn test_escape_branch_git_config_compatible() {+ use worktrunk::git::escape_branch_for_config;+// Git config keys only allow alphanumeric, `-`, and `.`let is_valid_config_char = |c: char| c.is_ascii_alphanumeric() || c == '-' || c == '.';@@ -315,7 +319,7 @@ mod tests {];for branch in cases {- let escaped = CachedCiStatus::escape_branch(branch);+ let escaped = escape_branch_for_config(branch);assert!(escaped.chars().all(is_valid_config_char),"Escaped '{}' contains invalid git config chars: '{}'",@@ -648,62 +652,6 @@ impl CachedCiStatus {Self::TTL_BASE_SECS + jitter}- /// Escape branch name for use in git config key.- ///- /// Git config keys only allow alphanumeric, `-`, and `.` characters.- /// Branch names commonly contain `/` and `_`, so we encode them as `-XX`- /// where XX is the uppercase hex value. We also encode `-` itself to- /// ensure round-trip safety.- ///- /// NOTE: This encoding is verbose but necessary β standard percent-encoding- /// uses `%` which git config doesn't allow, and base64 uses `_`. Open to- /// simpler approaches if someone finds one.- pub(crate) fn escape_branch(branch: &str) -> String {- let mut escaped = String::with_capacity(branch.len());- for ch in branch.chars() {- match ch {- 'a'..='z' | 'A'..='Z' | '0'..='9' | '.' => escaped.push(ch),- '-' => escaped.push_str("-2D"),- _ => {- // Encode as -XX where XX is uppercase hex- for byte in ch.to_string().bytes() {- escaped.push_str(&format!("-{byte:02X}"));- }- }- }- }- escaped- }-- /// Unescape branch name from git config key.- pub(crate) fn unescape_branch(escaped: &str) -> String {- let mut bytes = Vec::with_capacity(escaped.len());- let mut chars = escaped.chars().peekable();-- while let Some(ch) = chars.next() {- if ch == '-' {- // Try to read two hex digits- let hex: String = chars.by_ref().take(2).collect();- if hex.len() == 2- && let Ok(byte) = u8::from_str_radix(&hex, 16)- {- bytes.push(byte);- continue;- }- // Invalid escape sequence, keep as-is- bytes.push(b'-');- bytes.extend(hex.bytes());- } else {- // Unescaped char - encode as UTF-8 bytes- bytes.extend(ch.to_string().bytes());- }- }-- // Decode collected bytes as UTF-8- String::from_utf8(bytes)- .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())- }-/// Check if the cache is still validfn is_valid(&self, current_head: &str, now_secs: u64, repo_root: &str) -> bool {// Cache is valid if:@@ -715,7 +663,10 @@ impl CachedCiStatus {/// Read cached CI status from git configfn read(branch: &str, repo_root: &str) -> Option<Self> {- let config_key = format!("worktrunk.ci.{}", Self::escape_branch(branch));+ let config_key = format!(+ "worktrunk.ci.{}",+ worktrunk::git::escape_branch_for_config(branch)+ );let output = Command::new("git").args(["config", "--get", &config_key]).current_dir(repo_root)@@ -732,7 +683,10 @@ impl CachedCiStatus {/// Write CI status to git config cachefn write(&self, branch: &str, repo_root: &str) {- let config_key = format!("worktrunk.ci.{}", Self::escape_branch(branch));+ let config_key = format!(+ "worktrunk.ci.{}",+ worktrunk::git::escape_branch_for_config(branch)+ );let Ok(json) = serde_json::to_string(self) else {log::debug!("Failed to serialize CI cache for {}", branch);return;@@ -757,7 +711,7 @@ impl CachedCiStatus {.filter_map(|line| {let (key, json) = line.split_once(' ')?;let escaped = key.strip_prefix("worktrunk.ci.")?;- let branch = Self::unescape_branch(escaped);+ let branch = worktrunk::git::unescape_branch_from_config(escaped);let cached: Self = serde_json::from_str(json).ok()?;Some((branch, cached))})diff --git a/src/git/mod.rs b/src/git/mod.rsindex 81688bfcf..3f28834ca 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -43,6 +43,57 @@ pub use error::{};pub use repository::{Repository, ResolvedWorktree, set_base_path};+/// Escape branch name for use in git config key.+///+/// Git config keys only allow alphanumeric, `-`, and `.` characters.+/// Branch names commonly contain `/` and `_`, so we encode them as `-XX`+/// where XX is the uppercase hex value. We also encode `-` itself to+/// ensure round-trip safety.+pub fn escape_branch_for_config(branch: &str) -> String {+ let mut escaped = String::with_capacity(branch.len());+ for ch in branch.chars() {+ match ch {+ 'a'..='z' | 'A'..='Z' | '0'..='9' | '.' => escaped.push(ch),+ '-' => escaped.push_str("-2D"),+ _ => {+ // Encode as -XX where XX is uppercase hex+ for byte in ch.to_string().bytes() {+ escaped.push_str(&format!("-{byte:02X}"));+ }+ }+ }+ }+ escaped+}++/// Unescape branch name from git config key.+pub fn unescape_branch_from_config(escaped: &str) -> String {+ let mut bytes = Vec::with_capacity(escaped.len());+ let mut chars = escaped.chars().peekable();++ while let Some(ch) = chars.next() {+ if ch == '-' {+ // Try to read two hex digits+ let hex: String = chars.by_ref().take(2).collect();+ if hex.len() == 2+ && let Ok(byte) = u8::from_str_radix(&hex, 16)+ {+ bytes.push(byte);+ continue;+ }+ // Invalid escape sequence, keep as-is+ bytes.push(b'-');+ bytes.extend(hex.bytes());+ } else {+ // Unescaped char - encode as UTF-8 bytes+ bytes.extend(ch.to_string().bytes());+ }+ }++ // Decode collected bytes as UTF-8+ String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())+}+/// Why branch content is considered integrated into the target branch.////// Used by both `wt list` (for status symbols) and `wt remove` (for messages).diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 2143733de..3cf9db6cc 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -277,7 +277,8 @@ impl Repository {/// Markers are stored as JSON: `{"marker": "text", "set_at": unix_timestamp}`./// Falls back to plain text for legacy markers without timestamps.pub fn branch_keyed_marker(&self, branch: &str) -> Option<String> {- let config_key = format!("worktrunk.marker.{}", branch);+ let escaped = super::escape_branch_for_config(branch);+ let config_key = format!("worktrunk.marker.{}", escaped);let raw = self.run_command(&["config", "--get", &config_key]).ok()diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex c1b66ab59..81a04932d 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -1541,6 +1541,18 @@ exit /b 1cmd.env("PATH", new_path);}}++ /// Set a marker for a branch with proper escaping for git config keys.+ ///+ /// This handles the branch name escaping required for git config keys,+ /// which only allow alphanumeric, `-`, and `.` characters.+ pub fn set_marker(&self, branch: &str, marker: &str) {+ let escaped = worktrunk::git::escape_branch_for_config(branch);+ let config_key = format!("worktrunk.marker.{}", escaped);+ self.git_command(&["config", &config_key, marker])+ .output()+ .unwrap();+ }}/// Add standard env var redactions to insta settingsdiff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex d0fe01c4e..17121c371 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -701,12 +701,7 @@ fn test_list_with_user_marker(mut repo: TestRepo) {"Add REST API endpoints",);// Set user marker- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.feature-api", "π€"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("feature-api", "π€");// Branch with uncommitted changes and user marker π¬let review_wt = repo.add_worktree_with_commit(@@ -718,12 +713,7 @@ fn test_list_with_user_marker(mut repo: TestRepo) {// Add uncommitted changesstd::fs::write(review_wt.join("styles.css"), "/* pending styles */").unwrap();// Set user marker- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.review-ui", "π¬"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("review-ui", "π¬");// Branch with uncommitted changes only (no user marker)let wip_wt = repo.add_worktree("wip-docs");@@ -740,12 +730,7 @@ fn test_list_json_with_user_marker(mut repo: TestRepo) {repo.add_worktree("with-status");// Set user marker (branch-keyed)- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.with-status", "π§"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("with-status", "π§");// Worktree without user markerrepo.add_worktree("without-status");@@ -824,12 +809,7 @@ fn test_list_branch_only_with_status(repo: TestRepo) {.unwrap();// Set branch-keyed status for the branch-only entry- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.branch-only", "πΏ"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("branch-only", "πΏ");// Use --branches flag to show branch-only entriessnapshot_list_with_branches("branch_only_with_status", &repo);@@ -839,23 +819,11 @@ fn test_list_branch_only_with_status(repo: TestRepo) {fn test_list_user_marker_with_special_characters(mut repo: TestRepo) {// Test with single emojirepo.add_worktree("emoji");-- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.emoji", "π"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("emoji", "π");// Test with compound emoji (multi-codepoint)repo.add_worktree("multi");-- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.multi", "π¨βπ»"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("multi", "π¨βπ»");snapshot_list("user_marker_special_chars", &repo);}@@ -1676,23 +1644,6 @@ fn run_git(repo: &TestRepo, args: &[&str], cwd: &std::path::Path) {}/// Mock CI status by writing to git config cache-/// Escape branch name for git config key (must match CachedCiStatus::escape_branch)-fn escape_branch_for_config(branch: &str) -> String {- let mut escaped = String::with_capacity(branch.len());- for ch in branch.chars() {- match ch {- 'a'..='z' | 'A'..='Z' | '0'..='9' | '.' => escaped.push(ch),- '-' => escaped.push_str("-2D"),- _ => {- for byte in ch.to_string().bytes() {- escaped.push_str(&format!("-{byte:02X}"));- }- }- }- }- escaped-}-fn mock_ci_status(repo: &TestRepo, branch: &str, status: &str, source: &str, is_stale: bool) {// Get HEAD commit for the branchlet mut cmd = Command::new("git");@@ -1718,7 +1669,10 @@ fn mock_ci_status(repo: &TestRepo, branch: &str, status: &str, source: &str, is_);// Write to git config (using escaped branch name)- let config_key = format!("worktrunk.ci.{}", escape_branch_for_config(branch));+ let config_key = format!(+ "worktrunk.ci.{}",+ worktrunk::git::escape_branch_for_config(branch)+ );let mut cmd = Command::new("git");repo.configure_git_cmd(&mut cmd);cmd.args(["config", &config_key, &cache_json])@@ -2024,24 +1978,14 @@ fn test_list_large_diffs_alignment(mut repo: TestRepo) {std::fs::write(large_wt.join("another.txt"), &another_large).unwrap();// Set user marker- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.feature-changes", "π€"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("feature-changes", "π€");// Worktree with short name to show gap before Status columnlet short_wt = repo.add_worktree("fix");std::fs::write(short_wt.join("quick.txt"), "quick fix").unwrap();// Set user marker for short branch- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.fix", "π¬"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("fix", "π¬");// Worktree with diverged status and working tree changeslet diverged_wt = repo.add_worktree("diverged");@@ -2073,12 +2017,7 @@ fn test_list_large_diffs_alignment(mut repo: TestRepo) {std::fs::write(diverged_wt.join("test.txt"), &modified_diverged).unwrap();// Set user marker- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.diverged", "π¬"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("diverged", "π¬");snapshot_list("large_diffs_alignment", &repo);}@@ -2125,12 +2064,7 @@ fn test_list_status_column_padding_with_emoji(mut repo: TestRepo) {std::fs::write(wli_seq.join("new.txt"), &new_content).unwrap();// Set user marker emoji π€- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.wli-sequence", "π€"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("wli-sequence", "π€");// Create "pr-link" worktree with different status (fewer symbols, same emoji type)let pr_link = repo.add_worktree("pr-link");@@ -2151,12 +2085,7 @@ fn test_list_status_column_padding_with_emoji(mut repo: TestRepo) {.unwrap();// Set same emoji type- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.pr-link", "π€"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("pr-link", "π€");// Create "main-symbol" with different emojilet main_sym = repo.add_worktree("main-symbol");@@ -2174,12 +2103,7 @@ fn test_list_status_column_padding_with_emoji(mut repo: TestRepo) {.output().unwrap();- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.main-symbol", "π¬"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("main-symbol", "π¬");snapshot_list("status_column_padding_emoji", &repo);}@@ -2345,12 +2269,7 @@ fn test_list_maximum_status_with_git_operation(mut repo: TestRepo) {.unwrap();// Set user marker emoji (π€)- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.feature", "π€"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("feature", "π€");// Result should show: ?!+ (working_tree) + = (conflicts) + β» (rebase) + β (diverged) + β (locked) + π€ (user marker)// Use --full to enable conflict detection@@ -2511,12 +2430,7 @@ fn test_list_maximum_status_symbols(mut repo: TestRepo) {.unwrap();// Set user marker emoji (π€)- let mut cmd = Command::new("git");- repo.configure_git_cmd(&mut cmd);- cmd.args(["config", "worktrunk.marker.feature", "π€"])- .current_dir(repo.root_path())- .output()- .unwrap();+ repo.set_marker("feature", "π€");// Result should show 11 chars: ?!+Β»β=β ββ π€let settings = setup_snapshot_settings(&repo);