| 1 | //! Native worktree manager UI (list / create / switch / compare). |
| 2 | //! |
| 3 | //! Data lives in [`codewhale_engine::git_status`]; this module is pure presentation + |
| 4 | //! key handling. Never blocks the render path on git subprocesses — refresh |
| 5 | //! is scheduled via `git_status::refresh_if_stale` / `force_refresh` from |
| 6 | //! background-friendly call sites. |
| 7 | |
| 8 | use std::collections::HashMap; |
| 9 | use std::path::{Path, PathBuf}; |
| 10 | use std::sync::{Arc, Mutex}; |
| 11 | |
| 12 | use crate::tui::views::{ModalKind, ModalView, ViewAction, ViewEvent}; |
| 13 | use codewhale_dependencies::{ExternalTool, Git}; |
| 14 | use codewhale_engine::git_status::{self, GitStatusSnapshot, WorktreeEntry}; |
| 15 | use codewhale_lane::WorktreeProvision; |
| 16 | use codewhale_localization::{Locale, MessageId, tr}; |
| 17 | use codewhale_palette as palette; |
| 18 | use codewhale_tui_kit::menu_style; |
| 19 | use codewhale_tui_kit::ui_text::truncate_line_to_width; |
| 20 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; |
| 21 | use ratatui::{ |
| 22 | buffer::Buffer, |
| 23 | layout::Rect, |
| 24 | style::{Modifier, Style}, |
| 25 | text::{Line, Span}, |
| 26 | widgets::{Block, Borders, Clear, Paragraph, Widget}, |
| 27 | }; |
| 28 | |
| 29 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 30 | enum Mode { |
| 31 | List, |
| 32 | Create, |
| 33 | Compare, |
| 34 | } |
| 35 | |
| 36 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 37 | struct WorktreeLiveStatus { |
| 38 | dirty: bool, |
| 39 | summary: String, |
| 40 | branch_label: Option<String>, |
| 41 | ahead: u32, |
| 42 | behind: u32, |
| 43 | } |
| 44 | |
| 45 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 46 | struct WorktreeDiffSummary { |
| 47 | path: PathBuf, |
| 48 | branch: String, |
| 49 | base: String, |
| 50 | ahead: u32, |
| 51 | behind: u32, |
| 52 | stat_lines: Vec<String>, |
| 53 | dirty_summary: Option<String>, |
| 54 | } |
| 55 | |
| 56 | enum WorktreeOpOutcome { |
| 57 | Refreshed { |
| 58 | snapshot: GitStatusSnapshot, |
| 59 | statuses: HashMap<PathBuf, WorktreeLiveStatus>, |
| 60 | message: String, |
| 61 | }, |
| 62 | Created { |
| 63 | path: PathBuf, |
| 64 | snapshot: GitStatusSnapshot, |
| 65 | statuses: HashMap<PathBuf, WorktreeLiveStatus>, |
| 66 | setup_notice: Option<String>, |
| 67 | setup_error: Option<String>, |
| 68 | }, |
| 69 | DiffReady(Result<WorktreeDiffSummary, String>), |
| 70 | Merged { |
| 71 | result: Result<String, String>, |
| 72 | snapshot: GitStatusSnapshot, |
| 73 | statuses: HashMap<PathBuf, WorktreeLiveStatus>, |
| 74 | }, |
| 75 | Removed { |
| 76 | result: Result<String, String>, |
| 77 | snapshot: GitStatusSnapshot, |
| 78 | statuses: HashMap<PathBuf, WorktreeLiveStatus>, |
| 79 | }, |
| 80 | Failed(String), |
| 81 | } |
| 82 | |
| 83 | type WorktreeProbeResult = Arc<Mutex<Option<HashMap<PathBuf, WorktreeLiveStatus>>>>; |
| 84 | |
| 85 | pub struct WorktreeManagerView { |
| 86 | workspace: PathBuf, |
| 87 | selected: usize, |
| 88 | mode: Mode, |
| 89 | create_buffer: String, |
| 90 | create_as_new_branch: bool, |
| 91 | compare_against: Option<PathBuf>, |
| 92 | diff_summary: Option<WorktreeDiffSummary>, |
| 93 | status: Option<String>, |
| 94 | status_is_error: bool, |
| 95 | last_snapshot: GitStatusSnapshot, |
| 96 | current_flags: Vec<bool>, |
| 97 | worktree_statuses: HashMap<PathBuf, WorktreeLiveStatus>, |
| 98 | pending_probe: Option<WorktreeProbeResult>, |
| 99 | pending_op: Option<Arc<Mutex<Option<WorktreeOpOutcome>>>>, |
| 100 | locale: Locale, |
| 101 | } |
| 102 | |
| 103 | impl WorktreeManagerView { |
| 104 | #[must_use] |
| 105 | pub fn new(workspace: impl Into<PathBuf>) -> Self { |
| 106 | let workspace = workspace.into(); |
| 107 | git_status::refresh_if_stale(&workspace); |
| 108 | let last_snapshot = git_status::cached_status(); |
| 109 | let mut view = Self { |
| 110 | workspace, |
| 111 | selected: 0, |
| 112 | mode: Mode::List, |
| 113 | create_buffer: String::new(), |
| 114 | create_as_new_branch: true, |
| 115 | compare_against: None, |
| 116 | diff_summary: None, |
| 117 | status: None, |
| 118 | status_is_error: false, |
| 119 | last_snapshot, |
| 120 | current_flags: Vec::new(), |
| 121 | worktree_statuses: HashMap::new(), |
| 122 | pending_probe: None, |
| 123 | pending_op: None, |
| 124 | locale: Locale::En, |
| 125 | }; |
| 126 | view.recompute_current_flags(); |
| 127 | view.seed_current_live_status(); |
| 128 | view.schedule_status_probe(); |
| 129 | view |
| 130 | } |
| 131 | |
| 132 | fn seed_current_live_status(&mut self) { |
| 133 | for (idx, entry) in self.last_snapshot.worktrees.iter().enumerate() { |
| 134 | if self.current_flags.get(idx).copied().unwrap_or(false) { |
| 135 | self.worktree_statuses.insert( |
| 136 | entry.path.clone(), |
| 137 | WorktreeLiveStatus { |
| 138 | dirty: self.last_snapshot.dirty, |
| 139 | summary: self.last_snapshot.changes.summary(), |
| 140 | branch_label: self.last_snapshot.branch.clone(), |
| 141 | ahead: self.last_snapshot.ahead, |
| 142 | behind: self.last_snapshot.behind, |
| 143 | }, |
| 144 | ); |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | fn schedule_status_probe(&mut self) { |
| 150 | if self.last_snapshot.worktrees.is_empty() { |
| 151 | return; |
| 152 | } |
| 153 | let entries = self.last_snapshot.worktrees.clone(); |
| 154 | let cell = Arc::new(Mutex::new(None)); |
| 155 | let slot = Arc::clone(&cell); |
| 156 | codewhale_util::utils::spawn_blocking_supervised("worktree-probe", move || { |
| 157 | let statuses = probe_all_worktrees(&entries); |
| 158 | if let Ok(mut guard) = slot.lock() { |
| 159 | *guard = Some(statuses); |
| 160 | } |
| 161 | }); |
| 162 | self.pending_probe = Some(cell); |
| 163 | } |
| 164 | |
| 165 | fn adopt_snapshot(&mut self, snapshot: GitStatusSnapshot) { |
| 166 | self.last_snapshot = snapshot; |
| 167 | let n = self.last_snapshot.worktrees.len().max(1); |
| 168 | if self.selected >= n { |
| 169 | self.selected = n.saturating_sub(1); |
| 170 | } |
| 171 | self.recompute_current_flags(); |
| 172 | self.seed_current_live_status(); |
| 173 | } |
| 174 | |
| 175 | fn recompute_current_flags(&mut self) { |
| 176 | self.current_flags = self |
| 177 | .last_snapshot |
| 178 | .worktrees |
| 179 | .iter() |
| 180 | .map(|entry| same_path(&self.workspace, &entry.path)) |
| 181 | .collect(); |
| 182 | } |
| 183 | |
| 184 | fn entries(&self) -> &[WorktreeEntry] { |
| 185 | &self.last_snapshot.worktrees |
| 186 | } |
| 187 | |
| 188 | fn selected_entry(&self) -> Option<&WorktreeEntry> { |
| 189 | self.entries().get(self.selected) |
| 190 | } |
| 191 | |
| 192 | fn parent_checkout(&self) -> PathBuf { |
| 193 | self.entries() |
| 194 | .first() |
| 195 | .map(|entry| entry.path.clone()) |
| 196 | .or_else(|| self.last_snapshot.root.clone()) |
| 197 | .unwrap_or_else(|| self.workspace.clone()) |
| 198 | } |
| 199 | |
| 200 | fn set_status(&mut self, msg: impl Into<String>, is_error: bool) { |
| 201 | self.status = Some(msg.into()); |
| 202 | self.status_is_error = is_error; |
| 203 | } |
| 204 | |
| 205 | fn spawn_op<F>(&mut self, name: &'static str, work: F) |
| 206 | where |
| 207 | F: FnOnce() -> WorktreeOpOutcome + Send + 'static, |
| 208 | { |
| 209 | let cell = Arc::new(Mutex::new(None)); |
| 210 | let slot = Arc::clone(&cell); |
| 211 | codewhale_util::utils::spawn_blocking_supervised(name, move || { |
| 212 | let outcome = work(); |
| 213 | if let Ok(mut guard) = slot.lock() { |
| 214 | *guard = Some(outcome); |
| 215 | } |
| 216 | }); |
| 217 | self.pending_op = Some(cell); |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | fn same_path(a: &Path, b: &Path) -> bool { |
| 222 | let a = a.canonicalize().unwrap_or_else(|_| a.to_path_buf()); |
| 223 | let b = b.canonicalize().unwrap_or_else(|_| b.to_path_buf()); |
| 224 | a == b |
| 225 | } |
| 226 | |
| 227 | fn worktree_name_error(name: &str) -> Option<MessageId> { |
| 228 | if name.is_empty() { |
| 229 | Some(MessageId::WorktreeNameEmpty) |
| 230 | } else if name.starts_with('-') { |
| 231 | Some(MessageId::WorktreeNameLeadingDash) |
| 232 | } else if name.contains("..") { |
| 233 | Some(MessageId::WorktreeNameDotDot) |
| 234 | } else if name.contains('\\') { |
| 235 | Some(MessageId::WorktreeNameBackslash) |
| 236 | } else if name.chars().any(char::is_control) { |
| 237 | Some(MessageId::WorktreeNameControlChars) |
| 238 | } else { |
| 239 | None |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | fn probe_all_worktrees(entries: &[WorktreeEntry]) -> HashMap<PathBuf, WorktreeLiveStatus> { |
| 244 | let mut statuses = HashMap::with_capacity(entries.len()); |
| 245 | for entry in entries { |
| 246 | if entry.bare || !entry.path.exists() { |
| 247 | continue; |
| 248 | } |
| 249 | if let Ok(porcelain) = git_status::probe_workspace_status(&entry.path) { |
| 250 | statuses.insert( |
| 251 | entry.path.clone(), |
| 252 | WorktreeLiveStatus { |
| 253 | dirty: !porcelain.changes.is_clean(), |
| 254 | summary: porcelain.changes.summary(), |
| 255 | branch_label: porcelain.branch_label(), |
| 256 | ahead: porcelain.ahead, |
| 257 | behind: porcelain.behind, |
| 258 | }, |
| 259 | ); |
| 260 | } |
| 261 | } |
| 262 | statuses |
| 263 | } |
| 264 | |
| 265 | fn resolve_base_branch( |
| 266 | repo_root: &Path, |
| 267 | worktrees: &[WorktreeEntry], |
| 268 | target_branch: Option<&str>, |
| 269 | ) -> String { |
| 270 | if let Some(main_branch) = worktrees.first().and_then(|entry| entry.branch.as_deref()) |
| 271 | && target_branch != Some(main_branch) |
| 272 | { |
| 273 | return main_branch.to_string(); |
| 274 | } |
| 275 | if let Ok(output) = Git::output( |
| 276 | &[ |
| 277 | "symbolic-ref", |
| 278 | "--quiet", |
| 279 | "--short", |
| 280 | "refs/remotes/origin/HEAD", |
| 281 | ], |
| 282 | repo_root, |
| 283 | ) && output.status.success() |
| 284 | { |
| 285 | let raw = String::from_utf8_lossy(&output.stdout).trim().to_string(); |
| 286 | if let Some(stripped) = raw.strip_prefix("origin/") |
| 287 | && !stripped.is_empty() |
| 288 | { |
| 289 | return stripped.to_string(); |
| 290 | } |
| 291 | } |
| 292 | for candidate in ["main", "master"] { |
| 293 | if let Ok(output) = Git::output(&["rev-parse", "--verify", "--quiet", candidate], repo_root) |
| 294 | && output.status.success() |
| 295 | { |
| 296 | return candidate.to_string(); |
| 297 | } |
| 298 | } |
| 299 | "HEAD".to_string() |
| 300 | } |
| 301 | |
| 302 | fn compute_worktree_diff_summary( |
| 303 | repo_root: &Path, |
| 304 | worktrees: &[WorktreeEntry], |
| 305 | entry: &WorktreeEntry, |
| 306 | ) -> Result<WorktreeDiffSummary, String> { |
| 307 | let branch = entry |
| 308 | .branch |
| 309 | .clone() |
| 310 | .unwrap_or_else(|| "HEAD (detached)".to_string()); |
| 311 | let base = resolve_base_branch(repo_root, worktrees, entry.branch.as_deref()); |
| 312 | let range = format!("{base}...HEAD"); |
| 313 | |
| 314 | let (ahead, behind) = Git::output( |
| 315 | &["rev-list", "--left-right", "--count", &range], |
| 316 | &entry.path, |
| 317 | ) |
| 318 | .ok() |
| 319 | .filter(|out| out.status.success()) |
| 320 | .map(|out| { |
| 321 | let text = String::from_utf8_lossy(&out.stdout); |
| 322 | let mut parts = text.split_whitespace(); |
| 323 | let behind = parts |
| 324 | .next() |
| 325 | .and_then(|v| v.parse::<u32>().ok()) |
| 326 | .unwrap_or(0); |
| 327 | let ahead = parts |
| 328 | .next() |
| 329 | .and_then(|v| v.parse::<u32>().ok()) |
| 330 | .unwrap_or(0); |
| 331 | (ahead, behind) |
| 332 | }) |
| 333 | .unwrap_or((0, 0)); |
| 334 | |
| 335 | let diff_out = Git::output(&["diff", "--stat", &range], &entry.path) |
| 336 | .map_err(|err| format!("git diff --stat failed: {err}"))?; |
| 337 | if !diff_out.status.success() { |
| 338 | return Err(format!( |
| 339 | "git diff --stat failed: {}", |
| 340 | String::from_utf8_lossy(&diff_out.stderr).trim() |
| 341 | )); |
| 342 | } |
| 343 | let stat_lines = String::from_utf8_lossy(&diff_out.stdout) |
| 344 | .lines() |
| 345 | .map(|line| line.trim_end().to_string()) |
| 346 | .filter(|line| !line.is_empty()) |
| 347 | .take(12) |
| 348 | .collect::<Vec<_>>(); |
| 349 | |
| 350 | let dirty_summary = git_status::probe_workspace_status(&entry.path) |
| 351 | .ok() |
| 352 | .filter(|status| !status.changes.is_clean()) |
| 353 | .map(|status| status.changes.summary()); |
| 354 | |
| 355 | Ok(WorktreeDiffSummary { |
| 356 | path: entry.path.clone(), |
| 357 | branch, |
| 358 | base, |
| 359 | ahead, |
| 360 | behind, |
| 361 | stat_lines, |
| 362 | dirty_summary, |
| 363 | }) |
| 364 | } |
| 365 | |
| 366 | fn working_tree_is_clean(path: &Path, include_untracked_all: bool) -> Result<bool, String> { |
| 367 | let untracked = if include_untracked_all { |
| 368 | "--untracked-files=all" |
| 369 | } else { |
| 370 | "--untracked-files=normal" |
| 371 | }; |
| 372 | let output = Git::output(&["status", "--porcelain", untracked], path) |
| 373 | .map_err(|err| format!("git status failed: {err}"))?; |
| 374 | if !output.status.success() { |
| 375 | return Err(format!( |
| 376 | "git status failed: {}", |
| 377 | String::from_utf8_lossy(&output.stderr).trim() |
| 378 | )); |
| 379 | } |
| 380 | Ok(output.stdout.is_empty()) |
| 381 | } |
| 382 | |
| 383 | fn bring_back_worktree_branch(parent_checkout: &Path, branch: &str) -> Result<String, String> { |
| 384 | if branch.trim().is_empty() || branch.starts_with('-') { |
| 385 | return Err(format!("Refused merge: invalid branch '{branch}'")); |
| 386 | } |
| 387 | if !working_tree_is_clean(parent_checkout, false)? { |
| 388 | return Err( |
| 389 | "Refused merge: parent checkout is dirty; commit or stash changes first".to_string(), |
| 390 | ); |
| 391 | } |
| 392 | let parent_branch = Git::output( |
| 393 | &["symbolic-ref", "--quiet", "--short", "HEAD"], |
| 394 | parent_checkout, |
| 395 | ) |
| 396 | .ok() |
| 397 | .filter(|out| out.status.success()) |
| 398 | .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string()) |
| 399 | .filter(|name| !name.is_empty()) |
| 400 | .unwrap_or_else(|| "HEAD".to_string()); |
| 401 | if parent_branch == branch { |
| 402 | return Err(format!( |
| 403 | "Refused merge: parent checkout is already on '{branch}'" |
| 404 | )); |
| 405 | } |
| 406 | |
| 407 | let ff = Git::output(&["merge", "--ff-only", "--", branch], parent_checkout) |
| 408 | .map_err(|err| format!("git merge --ff-only failed: {err}"))?; |
| 409 | if ff.status.success() { |
| 410 | return Ok(format!("Fast-forward merged {branch} into {parent_branch}")); |
| 411 | } |
| 412 | |
| 413 | let merge = Git::output(&["merge", "--no-edit", "--", branch], parent_checkout) |
| 414 | .map_err(|err| format!("git merge failed: {err}"))?; |
| 415 | if merge.status.success() { |
| 416 | return Ok(format!("Merged {branch} into {parent_branch}")); |
| 417 | } |
| 418 | let detail = String::from_utf8_lossy(&merge.stderr).trim().to_string(); |
| 419 | let _ = Git::output(&["merge", "--abort"], parent_checkout); |
| 420 | Err(format!( |
| 421 | "Refused merge: conflicts merging {branch} into {parent_branch} (aborted cleanly){}{}", |
| 422 | if detail.is_empty() { "" } else { ": " }, |
| 423 | detail |
| 424 | )) |
| 425 | } |
| 426 | |
| 427 | fn remove_clean_worktree(parent_checkout: &Path, target_path: &Path) -> Result<String, String> { |
| 428 | if same_path(parent_checkout, target_path) { |
| 429 | return Err("Refused remove: cannot remove the main repository checkout".to_string()); |
| 430 | } |
| 431 | let dot_git = target_path.join(".git"); |
| 432 | if !dot_git.is_file() { |
| 433 | return Err("Refused remove: target is not a linked git worktree".to_string()); |
| 434 | } |
| 435 | if !working_tree_is_clean(target_path, true)? { |
| 436 | return Err( |
| 437 | "Refused remove: worktree is dirty (uncommitted or untracked changes)".to_string(), |
| 438 | ); |
| 439 | } |
| 440 | let target_str = target_path |
| 441 | .to_str() |
| 442 | .ok_or_else(|| "Refused remove: invalid worktree path".to_string())?; |
| 443 | let remove = Git::output(&["worktree", "remove", "--", target_str], parent_checkout) |
| 444 | .map_err(|err| format!("git worktree remove failed: {err}"))?; |
| 445 | if !remove.status.success() { |
| 446 | return Err(format!( |
| 447 | "Refused remove: {}", |
| 448 | String::from_utf8_lossy(&remove.stderr).trim() |
| 449 | )); |
| 450 | } |
| 451 | let _ = Git::output(&["worktree", "prune"], parent_checkout); |
| 452 | Ok(format!("Removed clean worktree {}", target_path.display())) |
| 453 | } |
| 454 | |
| 455 | fn format_pr_create_command(branch: &str) -> String { |
| 456 | let safe = branch |
| 457 | .chars() |
| 458 | .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '-' | '_' | '.')); |
| 459 | if safe { |
| 460 | format!("gh pr create --head {branch}") |
| 461 | } else { |
| 462 | let escaped = branch.replace('\'', "'\\''"); |
| 463 | format!("gh pr create --head '{escaped}'") |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | impl ModalView for WorktreeManagerView { |
| 468 | fn kind(&self) -> ModalKind { |
| 469 | ModalKind::WorktreeManager |
| 470 | } |
| 471 | |
| 472 | fn set_locale(&mut self, locale: Locale) { |
| 473 | self.locale = locale; |
| 474 | } |
| 475 | |
| 476 | fn as_any_mut(&mut self) -> &mut dyn std::any::Any { |
| 477 | self |
| 478 | } |
| 479 | |
| 480 | fn handle_key(&mut self, key: KeyEvent) -> ViewAction { |
| 481 | match self.mode { |
| 482 | Mode::List => self.handle_list_key(key), |
| 483 | Mode::Create => self.handle_create_key(key), |
| 484 | Mode::Compare => self.handle_compare_key(key), |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | fn handle_paste(&mut self, text: &str) -> bool { |
| 489 | if self.mode != Mode::Create { |
| 490 | return false; |
| 491 | } |
| 492 | let sanitized = text |
| 493 | .trim_end_matches(['\r', '\n']) |
| 494 | .replace("\r\n", "\n") |
| 495 | .replace(char::is_control, " "); |
| 496 | if !sanitized.is_empty() { |
| 497 | self.create_buffer.push_str(&sanitized); |
| 498 | } |
| 499 | true |
| 500 | } |
| 501 | |
| 502 | fn tick(&mut self) -> ViewAction { |
| 503 | let mut redraw = false; |
| 504 | |
| 505 | if let Some(statuses) = self |
| 506 | .pending_probe |
| 507 | .as_ref() |
| 508 | .and_then(|cell| cell.lock().ok().and_then(|mut guard| guard.take())) |
| 509 | { |
| 510 | self.pending_probe = None; |
| 511 | self.worktree_statuses = statuses; |
| 512 | redraw = true; |
| 513 | } |
| 514 | |
| 515 | if let Some(outcome) = self |
| 516 | .pending_op |
| 517 | .as_ref() |
| 518 | .and_then(|cell| cell.lock().ok().and_then(|mut guard| guard.take())) |
| 519 | { |
| 520 | self.pending_op = None; |
| 521 | redraw = true; |
| 522 | match outcome { |
| 523 | WorktreeOpOutcome::Refreshed { |
| 524 | snapshot, |
| 525 | statuses, |
| 526 | message, |
| 527 | } => { |
| 528 | self.adopt_snapshot(snapshot); |
| 529 | self.worktree_statuses = statuses; |
| 530 | self.set_status(message, false); |
| 531 | } |
| 532 | WorktreeOpOutcome::Created { |
| 533 | path, |
| 534 | snapshot, |
| 535 | statuses, |
| 536 | setup_notice, |
| 537 | setup_error, |
| 538 | } => { |
| 539 | self.adopt_snapshot(snapshot); |
| 540 | self.worktree_statuses = statuses; |
| 541 | self.mode = Mode::List; |
| 542 | if let Some(err) = setup_error { |
| 543 | self.set_status( |
| 544 | format!( |
| 545 | "Created worktree at {} · setup failed: {err}", |
| 546 | path.display() |
| 547 | ), |
| 548 | true, |
| 549 | ); |
| 550 | } else if let Some(notice) = setup_notice { |
| 551 | self.set_status( |
| 552 | format!("Created worktree at {} · {notice}", path.display()), |
| 553 | false, |
| 554 | ); |
| 555 | } else { |
| 556 | self.set_status(format!("Created worktree at {}", path.display()), false); |
| 557 | } |
| 558 | } |
| 559 | WorktreeOpOutcome::DiffReady(Ok(summary)) => { |
| 560 | self.set_status( |
| 561 | format!("Diff {} vs {}", summary.branch, summary.base), |
| 562 | false, |
| 563 | ); |
| 564 | self.diff_summary = Some(summary); |
| 565 | } |
| 566 | WorktreeOpOutcome::DiffReady(Err(err)) => { |
| 567 | self.diff_summary = None; |
| 568 | self.set_status(err, true); |
| 569 | } |
| 570 | WorktreeOpOutcome::Merged { |
| 571 | result, |
| 572 | snapshot, |
| 573 | statuses, |
| 574 | } => { |
| 575 | self.adopt_snapshot(snapshot); |
| 576 | self.worktree_statuses = statuses; |
| 577 | match result { |
| 578 | Ok(msg) => self.set_status(msg, false), |
| 579 | Err(err) => self.set_status(err, true), |
| 580 | } |
| 581 | } |
| 582 | WorktreeOpOutcome::Removed { |
| 583 | result, |
| 584 | snapshot, |
| 585 | statuses, |
| 586 | } => { |
| 587 | self.adopt_snapshot(snapshot); |
| 588 | self.worktree_statuses = statuses; |
| 589 | match result { |
| 590 | Ok(msg) => self.set_status(msg, false), |
| 591 | Err(err) => self.set_status(err, true), |
| 592 | } |
| 593 | } |
| 594 | WorktreeOpOutcome::Failed(err) => { |
| 595 | self.set_status(err, true); |
| 596 | } |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | if redraw { |
| 601 | ViewAction::Redraw |
| 602 | } else { |
| 603 | ViewAction::None |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 608 | let popup = centered(area, 84, 22.min(area.height.saturating_sub(2))); |
| 609 | Clear.render(popup, buf); |
| 610 | Block::default() |
| 611 | .borders(Borders::ALL) |
| 612 | .title(" Worktrees ") |
| 613 | .border_style(Style::default().fg(palette::BORDER_COLOR)) |
| 614 | .style( |
| 615 | Style::default() |
| 616 | .fg(palette::TEXT_PRIMARY) |
| 617 | .bg(palette::SURFACE_ELEVATED), |
| 618 | ) |
| 619 | .render(popup, buf); |
| 620 | |
| 621 | let inner = Rect { |
| 622 | x: popup.x.saturating_add(1), |
| 623 | y: popup.y.saturating_add(1), |
| 624 | width: popup.width.saturating_sub(2), |
| 625 | height: popup.height.saturating_sub(2), |
| 626 | }; |
| 627 | if inner.width == 0 || inner.height == 0 { |
| 628 | return; |
| 629 | } |
| 630 | |
| 631 | match self.mode { |
| 632 | Mode::List => self.render_list(inner, buf), |
| 633 | Mode::Create => self.render_create(inner, buf), |
| 634 | Mode::Compare => self.render_compare(inner, buf), |
| 635 | } |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | impl WorktreeManagerView { |
| 640 | fn handle_list_key(&mut self, key: KeyEvent) -> ViewAction { |
| 641 | match key.code { |
| 642 | KeyCode::Esc => ViewAction::Close, |
| 643 | KeyCode::Up | KeyCode::Char('k') => { |
| 644 | self.selected = self.selected.saturating_sub(1); |
| 645 | ViewAction::None |
| 646 | } |
| 647 | KeyCode::Down | KeyCode::Char('j') => { |
| 648 | let max = self.entries().len().saturating_sub(1); |
| 649 | self.selected = (self.selected + 1).min(max); |
| 650 | ViewAction::None |
| 651 | } |
| 652 | KeyCode::Char('r') |
| 653 | if key.modifiers.contains(KeyModifiers::CONTROL) |
| 654 | || key.modifiers == KeyModifiers::NONE => |
| 655 | { |
| 656 | if self.pending_op.is_some() { |
| 657 | return ViewAction::None; |
| 658 | } |
| 659 | let workspace = self.workspace.clone(); |
| 660 | self.set_status("Refreshing worktrees...", false); |
| 661 | self.spawn_op("worktree-refresh", move || { |
| 662 | let snapshot = git_status::force_refresh(&workspace); |
| 663 | let statuses = probe_all_worktrees(&snapshot.worktrees); |
| 664 | WorktreeOpOutcome::Refreshed { |
| 665 | snapshot, |
| 666 | statuses, |
| 667 | message: "Refreshed worktree list".to_string(), |
| 668 | } |
| 669 | }); |
| 670 | ViewAction::None |
| 671 | } |
| 672 | KeyCode::Char('c') | KeyCode::Char('n') => { |
| 673 | self.mode = Mode::Create; |
| 674 | self.create_buffer.clear(); |
| 675 | self.status = None; |
| 676 | self.status_is_error = false; |
| 677 | ViewAction::None |
| 678 | } |
| 679 | KeyCode::Char('d') => { |
| 680 | let Some(entry) = self.selected_entry().cloned() else { |
| 681 | return ViewAction::None; |
| 682 | }; |
| 683 | if self.pending_op.is_some() { |
| 684 | return ViewAction::None; |
| 685 | } |
| 686 | let repo_root = self.parent_checkout(); |
| 687 | let worktrees = self.entries().to_vec(); |
| 688 | self.compare_against = Some(entry.path.clone()); |
| 689 | self.diff_summary = None; |
| 690 | self.mode = Mode::Compare; |
| 691 | self.set_status("Loading diff summary...", false); |
| 692 | self.spawn_op("worktree-diff", move || { |
| 693 | WorktreeOpOutcome::DiffReady(compute_worktree_diff_summary( |
| 694 | &repo_root, &worktrees, &entry, |
| 695 | )) |
| 696 | }); |
| 697 | ViewAction::None |
| 698 | } |
| 699 | KeyCode::Char('m') => { |
| 700 | let Some(entry) = self.selected_entry().cloned() else { |
| 701 | return ViewAction::None; |
| 702 | }; |
| 703 | if self.pending_op.is_some() { |
| 704 | return ViewAction::None; |
| 705 | } |
| 706 | let parent = self.parent_checkout(); |
| 707 | if same_path(&entry.path, &parent) { |
| 708 | self.set_status( |
| 709 | "Refused merge: select a linked worktree to merge into parent checkout", |
| 710 | true, |
| 711 | ); |
| 712 | return ViewAction::None; |
| 713 | } |
| 714 | let Some(branch) = entry.branch.clone() else { |
| 715 | self.set_status("Refused merge: selected worktree is on detached HEAD", true); |
| 716 | return ViewAction::None; |
| 717 | }; |
| 718 | let workspace = self.workspace.clone(); |
| 719 | self.set_status(format!("Merging {branch} into parent checkout..."), false); |
| 720 | self.spawn_op("worktree-merge", move || { |
| 721 | let result = bring_back_worktree_branch(&parent, &branch); |
| 722 | let snapshot = git_status::force_refresh(&workspace); |
| 723 | let statuses = probe_all_worktrees(&snapshot.worktrees); |
| 724 | WorktreeOpOutcome::Merged { |
| 725 | result, |
| 726 | snapshot, |
| 727 | statuses, |
| 728 | } |
| 729 | }); |
| 730 | ViewAction::None |
| 731 | } |
| 732 | KeyCode::Char('p') => { |
| 733 | let Some(entry) = self.selected_entry() else { |
| 734 | return ViewAction::None; |
| 735 | }; |
| 736 | let Some(branch) = entry.branch.as_deref() else { |
| 737 | self.set_status("Cannot copy PR command: worktree is on detached HEAD", true); |
| 738 | return ViewAction::None; |
| 739 | }; |
| 740 | let cmd = format_pr_create_command(branch); |
| 741 | self.set_status(format!("Copied: {cmd}"), false); |
| 742 | ViewAction::Emit(ViewEvent::CopyToClipboard { |
| 743 | text: cmd, |
| 744 | label: "PR command".to_string(), |
| 745 | }) |
| 746 | } |
| 747 | KeyCode::Char('x') => { |
| 748 | let Some(entry) = self.selected_entry().cloned() else { |
| 749 | return ViewAction::None; |
| 750 | }; |
| 751 | if self.pending_op.is_some() { |
| 752 | return ViewAction::None; |
| 753 | } |
| 754 | if same_path(&entry.path, &self.workspace) { |
| 755 | self.set_status("Refused remove: cannot remove the active worktree", true); |
| 756 | return ViewAction::None; |
| 757 | } |
| 758 | if entry.locked { |
| 759 | self.set_status("Refused remove: worktree is locked", true); |
| 760 | return ViewAction::None; |
| 761 | } |
| 762 | let parent = self.parent_checkout(); |
| 763 | if same_path(&entry.path, &parent) { |
| 764 | self.set_status( |
| 765 | "Refused remove: cannot remove the main repository checkout", |
| 766 | true, |
| 767 | ); |
| 768 | return ViewAction::None; |
| 769 | } |
| 770 | let workspace = self.workspace.clone(); |
| 771 | self.set_status( |
| 772 | format!("Removing clean worktree {}...", entry.path.display()), |
| 773 | false, |
| 774 | ); |
| 775 | self.spawn_op("worktree-remove", move || { |
| 776 | let result = remove_clean_worktree(&parent, &entry.path); |
| 777 | let snapshot = git_status::force_refresh(&workspace); |
| 778 | let statuses = probe_all_worktrees(&snapshot.worktrees); |
| 779 | WorktreeOpOutcome::Removed { |
| 780 | result, |
| 781 | snapshot, |
| 782 | statuses, |
| 783 | } |
| 784 | }); |
| 785 | ViewAction::None |
| 786 | } |
| 787 | KeyCode::Enter => { |
| 788 | if let Some(entry) = self.selected_entry() { |
| 789 | let path = entry.path.display().to_string(); |
| 790 | let current = self |
| 791 | .current_flags |
| 792 | .get(self.selected) |
| 793 | .copied() |
| 794 | .unwrap_or(false); |
| 795 | if current { |
| 796 | self.set_status("Already in this worktree", false); |
| 797 | ViewAction::None |
| 798 | } else { |
| 799 | ViewAction::Emit(ViewEvent::StatusToast { |
| 800 | level: crate::tui::app::StatusToastLevel::Info, |
| 801 | message: format!( |
| 802 | "Switch: open a new session in {path} (cwd switch is session-scoped)" |
| 803 | ), |
| 804 | }) |
| 805 | } |
| 806 | } else { |
| 807 | ViewAction::None |
| 808 | } |
| 809 | } |
| 810 | _ => ViewAction::None, |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | fn handle_create_key(&mut self, key: KeyEvent) -> ViewAction { |
| 815 | match key.code { |
| 816 | KeyCode::Esc => { |
| 817 | self.mode = Mode::List; |
| 818 | ViewAction::None |
| 819 | } |
| 820 | KeyCode::Backspace => { |
| 821 | self.create_buffer.pop(); |
| 822 | ViewAction::None |
| 823 | } |
| 824 | KeyCode::Char('b') if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 825 | self.create_as_new_branch = !self.create_as_new_branch; |
| 826 | ViewAction::None |
| 827 | } |
| 828 | KeyCode::Enter => { |
| 829 | if self.pending_op.is_some() { |
| 830 | return ViewAction::None; |
| 831 | } |
| 832 | let name = self.create_buffer.trim(); |
| 833 | if let Some(message) = worktree_name_error(name) { |
| 834 | self.set_status(tr(self.locale, message).into_owned(), true); |
| 835 | return ViewAction::None; |
| 836 | } |
| 837 | let path = self |
| 838 | .workspace |
| 839 | .join(".cw-worktrees") |
| 840 | .join(name.replace('/', "-")); |
| 841 | let repo = self.parent_checkout(); |
| 842 | let branch = name.to_string(); |
| 843 | let new_branch = self.create_as_new_branch; |
| 844 | let workspace = self.workspace.clone(); |
| 845 | self.set_status(format!("Creating worktree {branch}..."), false); |
| 846 | self.spawn_op( |
| 847 | "worktree-create", |
| 848 | move || match git_status::create_worktree(&repo, &path, &branch, new_branch) { |
| 849 | Ok(()) => { |
| 850 | let trusted = codewhale_runtime::config::is_workspace_trusted(&repo); |
| 851 | let (setup_notice, setup_error) = |
| 852 | match WorktreeProvision::run_setup(&repo, &path, trusted) { |
| 853 | Ok(notice) => (notice, None), |
| 854 | Err(err) => (None, Some(format!("{err:#}"))), |
| 855 | }; |
| 856 | let snapshot = git_status::force_refresh(&workspace); |
| 857 | let statuses = probe_all_worktrees(&snapshot.worktrees); |
| 858 | WorktreeOpOutcome::Created { |
| 859 | path, |
| 860 | snapshot, |
| 861 | statuses, |
| 862 | setup_notice, |
| 863 | setup_error, |
| 864 | } |
| 865 | } |
| 866 | Err(err) => WorktreeOpOutcome::Failed(format!("Create failed: {err}")), |
| 867 | }, |
| 868 | ); |
| 869 | ViewAction::None |
| 870 | } |
| 871 | KeyCode::Char(c) |
| 872 | if !key.modifiers.contains(KeyModifiers::CONTROL) |
| 873 | && !key.modifiers.contains(KeyModifiers::ALT) => |
| 874 | { |
| 875 | self.create_buffer.push(c); |
| 876 | ViewAction::None |
| 877 | } |
| 878 | _ => ViewAction::None, |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | fn handle_compare_key(&mut self, key: KeyEvent) -> ViewAction { |
| 883 | match key.code { |
| 884 | KeyCode::Esc => { |
| 885 | self.mode = Mode::List; |
| 886 | self.compare_against = None; |
| 887 | self.diff_summary = None; |
| 888 | ViewAction::None |
| 889 | } |
| 890 | KeyCode::Enter => { |
| 891 | let Some(path) = self.compare_against.clone() else { |
| 892 | return ViewAction::None; |
| 893 | }; |
| 894 | ViewAction::Emit(ViewEvent::StatusToast { |
| 895 | level: crate::tui::app::StatusToastLevel::Info, |
| 896 | message: format!( |
| 897 | "Diff against {}: use /diff or context-menu Diff on a file", |
| 898 | path.display() |
| 899 | ), |
| 900 | }) |
| 901 | } |
| 902 | _ => ViewAction::None, |
| 903 | } |
| 904 | } |
| 905 | |
| 906 | fn render_list(&self, area: Rect, buf: &mut Buffer) { |
| 907 | let mut lines: Vec<Line<'static>> = Vec::new(); |
| 908 | let branch = self.last_snapshot.branch.as_deref().unwrap_or("detached"); |
| 909 | lines.push(Line::from(vec![ |
| 910 | Span::styled("repo ", Style::default().fg(palette::TEXT_MUTED)), |
| 911 | Span::styled( |
| 912 | branch.to_string(), |
| 913 | Style::default() |
| 914 | .fg(palette::WHALE_ACTION) |
| 915 | .add_modifier(Modifier::BOLD), |
| 916 | ), |
| 917 | if self.last_snapshot.dirty { |
| 918 | Span::styled(" *", Style::default().fg(palette::STATUS_WARNING)) |
| 919 | } else { |
| 920 | Span::raw("") |
| 921 | }, |
| 922 | ])); |
| 923 | lines.push(Line::from(Span::styled( |
| 924 | truncate_line_to_width( |
| 925 | "c create · d diff · m merge · p pr · x remove · r refresh · Esc close", |
| 926 | usize::from(area.width), |
| 927 | ), |
| 928 | Style::default().fg(palette::TEXT_HINT), |
| 929 | ))); |
| 930 | lines.push(Line::from("")); |
| 931 | |
| 932 | if self.entries().is_empty() { |
| 933 | lines.push(Line::from(Span::styled( |
| 934 | tr(self.locale, MessageId::WorktreeNoneListed), |
| 935 | Style::default().fg(palette::TEXT_MUTED), |
| 936 | ))); |
| 937 | } else { |
| 938 | let entries = self.entries(); |
| 939 | let header_lines = lines.len(); |
| 940 | let status_lines = if self.status.is_some() && area.height >= 5 { |
| 941 | 2 |
| 942 | } else { |
| 943 | 0 |
| 944 | }; |
| 945 | let visible_rows = usize::from(area.height) |
| 946 | .saturating_sub(header_lines + status_lines) |
| 947 | .max(1); |
| 948 | let selected_idx = self.selected.min(entries.len().saturating_sub(1)); |
| 949 | let scroll = selected_idx |
| 950 | .saturating_add(1) |
| 951 | .saturating_sub(visible_rows) |
| 952 | .min(entries.len().saturating_sub(visible_rows)); |
| 953 | for (i, entry) in entries.iter().enumerate().skip(scroll).take(visible_rows) { |
| 954 | let selected = i == selected_idx; |
| 955 | let current = self.current_flags.get(i).copied().unwrap_or(false); |
| 956 | let live = self.worktree_statuses.get(&entry.path); |
| 957 | let marker = if selected { "▸ " } else { " " }; |
| 958 | let cur = if current { " · current" } else { "" }; |
| 959 | let locked = if entry.locked { " 🔒" } else { "" }; |
| 960 | let branch = live |
| 961 | .and_then(|s| s.branch_label.as_deref()) |
| 962 | .or(entry.branch.as_deref()) |
| 963 | .unwrap_or("detached"); |
| 964 | let mut ab = String::new(); |
| 965 | if let Some(s) = live { |
| 966 | if s.ahead > 0 { |
| 967 | ab.push_str(&format!(" ↑{}", s.ahead)); |
| 968 | } |
| 969 | if s.behind > 0 { |
| 970 | ab.push_str(&format!(" ↓{}", s.behind)); |
| 971 | } |
| 972 | } |
| 973 | let state_badge = match live { |
| 974 | Some(s) if s.dirty => format!(" * ({})", s.summary), |
| 975 | Some(_) => " clean".to_string(), |
| 976 | None => String::new(), |
| 977 | }; |
| 978 | let path = entry |
| 979 | .path |
| 980 | .file_name() |
| 981 | .and_then(|s| s.to_str()) |
| 982 | .unwrap_or_else(|| entry.path.to_str().unwrap_or("?")); |
| 983 | let text = format!("{marker}{path} · {branch}{ab}{state_badge}{cur}{locked}"); |
| 984 | let style = if selected { |
| 985 | menu_style::selected_row_style_with_fg(palette::WHALE_ACTION) |
| 986 | } else if live.is_some_and(|s| s.dirty) { |
| 987 | Style::default().fg(palette::STATUS_WARNING) |
| 988 | } else if current { |
| 989 | Style::default().fg(palette::WHALE_LIVE) |
| 990 | } else { |
| 991 | Style::default().fg(palette::TEXT_PRIMARY) |
| 992 | }; |
| 993 | let rail = if selected { "▌" } else { " " }; |
| 994 | lines.push(Line::from(vec![ |
| 995 | Span::styled(rail, Style::default().fg(palette::WHALE_ACTION)), |
| 996 | Span::styled( |
| 997 | truncate_line_to_width(&text, usize::from(area.width.saturating_sub(2))), |
| 998 | style, |
| 999 | ), |
| 1000 | ])); |
| 1001 | } |
| 1002 | } |
| 1003 | |
| 1004 | if let Some(status) = &self.status { |
| 1005 | lines.push(Line::from("")); |
| 1006 | let status_color = if self.status_is_error { |
| 1007 | palette::STATUS_WARNING |
| 1008 | } else { |
| 1009 | palette::TEXT_MUTED |
| 1010 | }; |
| 1011 | lines.push(Line::from(Span::styled( |
| 1012 | truncate_line_to_width(status, usize::from(area.width)), |
| 1013 | Style::default().fg(status_color), |
| 1014 | ))); |
| 1015 | } |
| 1016 | |
| 1017 | Paragraph::new(lines).render(area, buf); |
| 1018 | } |
| 1019 | |
| 1020 | fn render_create(&self, area: Rect, buf: &mut Buffer) { |
| 1021 | let kind = if self.create_as_new_branch { |
| 1022 | "new branch" |
| 1023 | } else { |
| 1024 | "existing branch" |
| 1025 | }; |
| 1026 | let status_color = if self.status_is_error { |
| 1027 | palette::STATUS_WARNING |
| 1028 | } else { |
| 1029 | palette::TEXT_MUTED |
| 1030 | }; |
| 1031 | let lines = vec![ |
| 1032 | Line::from(Span::styled( |
| 1033 | "Create worktree", |
| 1034 | Style::default() |
| 1035 | .fg(palette::TEXT_PRIMARY) |
| 1036 | .add_modifier(Modifier::BOLD), |
| 1037 | )), |
| 1038 | Line::from(Span::styled( |
| 1039 | format!("Ctrl+B toggle · currently: {kind}"), |
| 1040 | Style::default().fg(palette::TEXT_HINT), |
| 1041 | )), |
| 1042 | Line::from(""), |
| 1043 | Line::from(vec![ |
| 1044 | Span::styled("name › ", Style::default().fg(palette::TEXT_MUTED)), |
| 1045 | Span::styled( |
| 1046 | self.create_buffer.clone(), |
| 1047 | Style::default().fg(palette::WHALE_ACTION), |
| 1048 | ), |
| 1049 | Span::styled("█", Style::default().fg(palette::TEXT_HINT)), |
| 1050 | ]), |
| 1051 | Line::from(""), |
| 1052 | Line::from(Span::styled( |
| 1053 | tr(self.locale, MessageId::WorktreeCreateFooter), |
| 1054 | Style::default().fg(palette::TEXT_HINT), |
| 1055 | )), |
| 1056 | if let Some(status) = &self.status { |
| 1057 | Line::from(Span::styled( |
| 1058 | truncate_line_to_width(status, usize::from(area.width)), |
| 1059 | Style::default().fg(status_color), |
| 1060 | )) |
| 1061 | } else { |
| 1062 | Line::from("") |
| 1063 | }, |
| 1064 | ]; |
| 1065 | Paragraph::new(lines).render(area, buf); |
| 1066 | } |
| 1067 | |
| 1068 | fn render_compare(&self, area: Rect, buf: &mut Buffer) { |
| 1069 | let path = self |
| 1070 | .compare_against |
| 1071 | .as_ref() |
| 1072 | .map(|p| p.display().to_string()) |
| 1073 | .unwrap_or_else(|| "(none)".into()); |
| 1074 | let mut lines = vec![ |
| 1075 | Line::from(Span::styled( |
| 1076 | "Diff summary against base branch", |
| 1077 | Style::default() |
| 1078 | .fg(palette::TEXT_PRIMARY) |
| 1079 | .add_modifier(Modifier::BOLD), |
| 1080 | )), |
| 1081 | Line::from(Span::styled( |
| 1082 | truncate_line_to_width(&path, usize::from(area.width)), |
| 1083 | Style::default().fg(palette::WHALE_LIVE), |
| 1084 | )), |
| 1085 | Line::from(""), |
| 1086 | ]; |
| 1087 | |
| 1088 | if let Some(summary) = &self.diff_summary { |
| 1089 | lines.push(Line::from(Span::styled( |
| 1090 | format!( |
| 1091 | "{} vs {} · ↑{} ahead · ↓{} behind", |
| 1092 | summary.branch, summary.base, summary.ahead, summary.behind |
| 1093 | ), |
| 1094 | Style::default().fg(palette::WHALE_ACTION), |
| 1095 | ))); |
| 1096 | if let Some(dirty) = &summary.dirty_summary { |
| 1097 | lines.push(Line::from(Span::styled( |
| 1098 | format!("Working tree: {dirty}"), |
| 1099 | Style::default().fg(palette::STATUS_WARNING), |
| 1100 | ))); |
| 1101 | } |
| 1102 | lines.push(Line::from("")); |
| 1103 | if summary.stat_lines.is_empty() { |
| 1104 | lines.push(Line::from(Span::styled( |
| 1105 | "No committed diff against base branch.", |
| 1106 | Style::default().fg(palette::TEXT_MUTED), |
| 1107 | ))); |
| 1108 | } else { |
| 1109 | let max_rows = usize::from(area.height).saturating_sub(8); |
| 1110 | for stat in summary.stat_lines.iter().take(max_rows) { |
| 1111 | lines.push(Line::from(Span::styled( |
| 1112 | truncate_line_to_width(stat, usize::from(area.width)), |
| 1113 | Style::default().fg(palette::TEXT_PRIMARY), |
| 1114 | ))); |
| 1115 | } |
| 1116 | } |
| 1117 | } else if let Some(status) = &self.status { |
| 1118 | let color = if self.status_is_error { |
| 1119 | palette::STATUS_WARNING |
| 1120 | } else { |
| 1121 | palette::TEXT_MUTED |
| 1122 | }; |
| 1123 | lines.push(Line::from(Span::styled( |
| 1124 | truncate_line_to_width(status, usize::from(area.width)), |
| 1125 | Style::default().fg(color), |
| 1126 | ))); |
| 1127 | } |
| 1128 | |
| 1129 | lines.push(Line::from("")); |
| 1130 | lines.push(Line::from(Span::styled( |
| 1131 | "Enter: diff workflow hint · Esc back", |
| 1132 | Style::default().fg(palette::TEXT_HINT), |
| 1133 | ))); |
| 1134 | Paragraph::new(lines).render(area, buf); |
| 1135 | } |
| 1136 | } |
| 1137 | |
| 1138 | fn centered(area: Rect, width: u16, height: u16) -> Rect { |
| 1139 | let width = width.min(area.width); |
| 1140 | let height = height.min(area.height); |
| 1141 | Rect { |
| 1142 | x: area.x.saturating_add(area.width.saturating_sub(width) / 2), |
| 1143 | y: area |
| 1144 | .y |
| 1145 | .saturating_add(area.height.saturating_sub(height) / 2), |
| 1146 | width, |
| 1147 | height, |
| 1148 | } |
| 1149 | } |
| 1150 | |
| 1151 | #[cfg(test)] |
| 1152 | mod tests { |
| 1153 | use super::*; |
| 1154 | use std::process::Command; |
| 1155 | use tempfile::tempdir; |
| 1156 | |
| 1157 | fn run_git(dir: &Path, args: &[&str]) { |
| 1158 | let out = Command::new("git") |
| 1159 | .args(args) |
| 1160 | .current_dir(dir) |
| 1161 | .output() |
| 1162 | .expect("git command"); |
| 1163 | assert!( |
| 1164 | out.status.success(), |
| 1165 | "git {:?} failed: {}", |
| 1166 | args, |
| 1167 | String::from_utf8_lossy(&out.stderr) |
| 1168 | ); |
| 1169 | } |
| 1170 | |
| 1171 | fn init_repo(dir: &Path) { |
| 1172 | run_git(dir, &["init", "-b", "main"]); |
| 1173 | run_git(dir, &["config", "user.email", "wt@test"]); |
| 1174 | run_git(dir, &["config", "user.name", "wt"]); |
| 1175 | std::fs::write(dir.join("base.txt"), "base\n").unwrap(); |
| 1176 | run_git(dir, &["add", "base.txt"]); |
| 1177 | run_git(dir, &["commit", "-m", "init"]); |
| 1178 | } |
| 1179 | |
| 1180 | #[test] |
| 1181 | fn manager_constructs_from_workspace() { |
| 1182 | let view = WorktreeManagerView::new(std::env::temp_dir()); |
| 1183 | assert_eq!(view.mode, Mode::List); |
| 1184 | } |
| 1185 | |
| 1186 | #[test] |
| 1187 | fn truncation_keeps_whole_emoji_and_cjk_clusters_within_width() { |
| 1188 | let family = "👨👩👧👦".repeat(8); |
| 1189 | let clipped = truncate_line_to_width(&family, 10); |
| 1190 | assert!(unicode_width::UnicodeWidthStr::width(clipped.as_str()) <= 10); |
| 1191 | assert!(clipped.ends_with("...")); |
| 1192 | assert!( |
| 1193 | clipped |
| 1194 | .trim_end_matches("...") |
| 1195 | .chars() |
| 1196 | .count() |
| 1197 | .is_multiple_of(7) |
| 1198 | ); |
| 1199 | let cjk = truncate_line_to_width("工作树工作树工作树", 7); |
| 1200 | assert!(unicode_width::UnicodeWidthStr::width(cjk.as_str()) <= 7); |
| 1201 | assert!(cjk.ends_with("...")); |
| 1202 | } |
| 1203 | |
| 1204 | #[test] |
| 1205 | fn create_mode_accepts_sanitized_paste_and_list_ignores_paste() { |
| 1206 | let mut view = WorktreeManagerView::new(std::env::temp_dir()); |
| 1207 | assert!(!view.handle_paste("feat/demo\r\n")); |
| 1208 | assert!(view.create_buffer.is_empty()); |
| 1209 | |
| 1210 | view.handle_key(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE)); |
| 1211 | assert_eq!(view.mode, Mode::Create); |
| 1212 | assert!(view.handle_paste("feat/demo\t1\r\n")); |
| 1213 | assert_eq!(view.create_buffer, "feat/demo 1"); |
| 1214 | assert!(view.handle_paste("\r\n")); |
| 1215 | assert_eq!(view.create_buffer, "feat/demo 1"); |
| 1216 | } |
| 1217 | |
| 1218 | #[test] |
| 1219 | fn c_enters_create_mode_and_p_copies_pr_command() { |
| 1220 | let mut view = WorktreeManagerView::new(std::env::temp_dir()); |
| 1221 | view.last_snapshot.worktrees = vec![WorktreeEntry { |
| 1222 | path: PathBuf::from("/tmp/repo-wt"), |
| 1223 | branch: Some("feat/worktree-loop".to_string()), |
| 1224 | bare: false, |
| 1225 | locked: false, |
| 1226 | }]; |
| 1227 | view.recompute_current_flags(); |
| 1228 | |
| 1229 | let action = view.handle_key(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::NONE)); |
| 1230 | match action { |
| 1231 | ViewAction::Emit(ViewEvent::CopyToClipboard { text, .. }) => { |
| 1232 | assert_eq!(text, "gh pr create --head feat/worktree-loop"); |
| 1233 | } |
| 1234 | other => panic!("expected CopyToClipboard, got {other:?}"), |
| 1235 | } |
| 1236 | |
| 1237 | view.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE)); |
| 1238 | assert_eq!(view.mode, Mode::Create); |
| 1239 | } |
| 1240 | |
| 1241 | #[test] |
| 1242 | fn render_shows_live_dirty_indicator_and_branch_status_without_subprocesses() { |
| 1243 | let mut view = WorktreeManagerView::new(std::env::temp_dir()); |
| 1244 | let wt_path = PathBuf::from("/nonexistent-path-never-shelled/wt-a"); |
| 1245 | view.last_snapshot.worktrees = vec![WorktreeEntry { |
| 1246 | path: wt_path.clone(), |
| 1247 | branch: Some("feat/live".to_string()), |
| 1248 | bare: false, |
| 1249 | locked: false, |
| 1250 | }]; |
| 1251 | view.worktree_statuses.insert( |
| 1252 | wt_path, |
| 1253 | WorktreeLiveStatus { |
| 1254 | dirty: true, |
| 1255 | summary: "1 modified".to_string(), |
| 1256 | branch_label: Some("feat/live".to_string()), |
| 1257 | ahead: 2, |
| 1258 | behind: 1, |
| 1259 | }, |
| 1260 | ); |
| 1261 | view.recompute_current_flags(); |
| 1262 | |
| 1263 | let area = Rect::new(0, 0, 90, 24); |
| 1264 | let mut buf = Buffer::empty(area); |
| 1265 | view.render(area, &mut buf); |
| 1266 | let rendered = buf |
| 1267 | .content() |
| 1268 | .iter() |
| 1269 | .map(|cell| cell.symbol()) |
| 1270 | .collect::<String>(); |
| 1271 | assert!(rendered.contains("feat/live"), "{rendered}"); |
| 1272 | assert!(rendered.contains("↑2"), "{rendered}"); |
| 1273 | assert!(rendered.contains("↓1"), "{rendered}"); |
| 1274 | assert!(rendered.contains("* (1 modified)"), "{rendered}"); |
| 1275 | } |
| 1276 | |
| 1277 | #[test] |
| 1278 | fn bring_back_refuses_dirty_parent_and_fast_forwards_when_clean() { |
| 1279 | let dir = tempdir().unwrap(); |
| 1280 | let repo = dir.path().join("repo"); |
| 1281 | std::fs::create_dir_all(&repo).unwrap(); |
| 1282 | init_repo(&repo); |
| 1283 | |
| 1284 | let wt = dir.path().join("wt-feature"); |
| 1285 | run_git( |
| 1286 | &repo, |
| 1287 | &[ |
| 1288 | "worktree", |
| 1289 | "add", |
| 1290 | "-b", |
| 1291 | "feat/bring-back", |
| 1292 | wt.to_str().unwrap(), |
| 1293 | ], |
| 1294 | ); |
| 1295 | std::fs::write(wt.join("feature.txt"), "hello\n").unwrap(); |
| 1296 | run_git(&wt, &["add", "feature.txt"]); |
| 1297 | run_git(&wt, &["commit", "-m", "add feature"]); |
| 1298 | |
| 1299 | std::fs::write(repo.join("dirty.txt"), "uncommitted\n").unwrap(); |
| 1300 | let err = bring_back_worktree_branch(&repo, "feat/bring-back") |
| 1301 | .expect_err("dirty parent checkout must refuse merge"); |
| 1302 | assert!(err.contains("parent checkout is dirty"), "{err}"); |
| 1303 | assert!(!repo.join("feature.txt").exists()); |
| 1304 | |
| 1305 | std::fs::remove_file(repo.join("dirty.txt")).unwrap(); |
| 1306 | let msg = bring_back_worktree_branch(&repo, "feat/bring-back") |
| 1307 | .expect("clean parent checkout must fast-forward merge"); |
| 1308 | assert!(msg.contains("Fast-forward merged"), "{msg}"); |
| 1309 | assert!(repo.join("feature.txt").is_file()); |
| 1310 | } |
| 1311 | |
| 1312 | #[test] |
| 1313 | fn remove_clean_worktree_refuses_dirty_and_removes_clean() { |
| 1314 | let dir = tempdir().unwrap(); |
| 1315 | let repo = dir.path().join("repo"); |
| 1316 | std::fs::create_dir_all(&repo).unwrap(); |
| 1317 | init_repo(&repo); |
| 1318 | |
| 1319 | let wt = dir.path().join("wt-remove"); |
| 1320 | run_git( |
| 1321 | &repo, |
| 1322 | &[ |
| 1323 | "worktree", |
| 1324 | "add", |
| 1325 | "-b", |
| 1326 | "feat/removable", |
| 1327 | wt.to_str().unwrap(), |
| 1328 | ], |
| 1329 | ); |
| 1330 | |
| 1331 | std::fs::write(wt.join("untracked.txt"), "keep\n").unwrap(); |
| 1332 | let err = |
| 1333 | remove_clean_worktree(&repo, &wt).expect_err("dirty worktree must not be removed"); |
| 1334 | assert!(err.contains("worktree is dirty"), "{err}"); |
| 1335 | assert!(wt.exists()); |
| 1336 | |
| 1337 | std::fs::remove_file(wt.join("untracked.txt")).unwrap(); |
| 1338 | let msg = remove_clean_worktree(&repo, &wt).expect("clean worktree must be removed"); |
| 1339 | assert!(msg.contains("Removed clean worktree"), "{msg}"); |
| 1340 | assert!(!wt.exists()); |
| 1341 | } |
| 1342 | |
| 1343 | #[test] |
| 1344 | fn diff_summary_reports_ahead_count_and_stat_against_base() { |
| 1345 | let dir = tempdir().unwrap(); |
| 1346 | let repo = dir.path().join("repo"); |
| 1347 | std::fs::create_dir_all(&repo).unwrap(); |
| 1348 | init_repo(&repo); |
| 1349 | |
| 1350 | let wt = dir.path().join("wt-diff"); |
| 1351 | run_git( |
| 1352 | &repo, |
| 1353 | &[ |
| 1354 | "worktree", |
| 1355 | "add", |
| 1356 | "-b", |
| 1357 | "feat/diff-check", |
| 1358 | wt.to_str().unwrap(), |
| 1359 | ], |
| 1360 | ); |
| 1361 | std::fs::write(wt.join("delta.txt"), "line1\nline2\n").unwrap(); |
| 1362 | run_git(&wt, &["add", "delta.txt"]); |
| 1363 | run_git(&wt, &["commit", "-m", "add delta"]); |
| 1364 | |
| 1365 | let entries = vec![ |
| 1366 | WorktreeEntry { |
| 1367 | path: repo.clone(), |
| 1368 | branch: Some("main".to_string()), |
| 1369 | bare: false, |
| 1370 | locked: false, |
| 1371 | }, |
| 1372 | WorktreeEntry { |
| 1373 | path: wt.clone(), |
| 1374 | branch: Some("feat/diff-check".to_string()), |
| 1375 | bare: false, |
| 1376 | locked: false, |
| 1377 | }, |
| 1378 | ]; |
| 1379 | let summary = |
| 1380 | compute_worktree_diff_summary(&repo, &entries, &entries[1]).expect("diff summary"); |
| 1381 | assert_eq!(summary.base, "main"); |
| 1382 | assert_eq!(summary.ahead, 1); |
| 1383 | assert_eq!(summary.behind, 0); |
| 1384 | assert!( |
| 1385 | summary.stat_lines.iter().any(|l| l.contains("delta.txt")), |
| 1386 | "{:?}", |
| 1387 | summary.stat_lines |
| 1388 | ); |
| 1389 | } |
| 1390 | |
| 1391 | #[test] |
| 1392 | fn render_list_clamps_scroll_window_to_keep_selected_row_visible() { |
| 1393 | let mut view = WorktreeManagerView::new(std::env::temp_dir()); |
| 1394 | view.last_snapshot.worktrees = (0..12) |
| 1395 | .map(|i| WorktreeEntry { |
| 1396 | path: PathBuf::from(format!("/nonexistent/wt-{i:02}")), |
| 1397 | branch: Some(format!("feat/branch-{i:02}")), |
| 1398 | bare: false, |
| 1399 | locked: false, |
| 1400 | }) |
| 1401 | .collect(); |
| 1402 | view.recompute_current_flags(); |
| 1403 | for _ in 0..11 { |
| 1404 | view.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); |
| 1405 | } |
| 1406 | assert_eq!(view.selected, 11); |
| 1407 | |
| 1408 | let area = Rect::new(0, 0, 84, 10); |
| 1409 | let mut buf = Buffer::empty(area); |
| 1410 | view.render(area, &mut buf); |
| 1411 | let rendered = buf |
| 1412 | .content() |
| 1413 | .iter() |
| 1414 | .map(|cell| cell.symbol()) |
| 1415 | .collect::<String>(); |
| 1416 | assert!(rendered.contains("wt-11"), "{rendered}"); |
| 1417 | assert!(rendered.contains("feat/branch-11"), "{rendered}"); |
| 1418 | } |
| 1419 | } |
| 1420 |