1use crate::errors::{CascadeError, Result};
2use crate::git::{ConflictAnalyzer, GitRepository};
3use crate::stack::{Stack, StackManager, SyncState};
4use chrono::Utc;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use tracing::debug;
8use uuid::Uuid;
9
10#[derive(Debug, Clone)]
12enum ConflictResolution {
13 Resolved,
15 TooComplex,
17}
18
19#[derive(Debug, Clone)]
21#[allow(dead_code)]
22struct ConflictRegion {
23 start: usize,
25 end: usize,
27 start_line: usize,
29 end_line: usize,
31 our_content: String,
33 their_content: String,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
39pub enum RebaseStrategy {
40 ForcePush,
43 Interactive,
45}
46
47#[derive(Debug, Clone)]
49pub struct RebaseOptions {
50 pub strategy: RebaseStrategy,
52 pub interactive: bool,
54 pub target_base: Option<String>,
56 pub preserve_merges: bool,
58 pub auto_resolve: bool,
60 pub max_retries: usize,
62 pub skip_pull: Option<bool>,
64 pub original_working_branch: Option<String>,
67}
68
69#[derive(Debug)]
71pub struct RebaseResult {
72 pub success: bool,
74 pub branch_mapping: HashMap<String, String>,
76 pub conflicts: Vec<String>,
78 pub new_commits: Vec<String>,
80 pub error: Option<String>,
82 pub summary: String,
84}
85
86#[allow(dead_code)]
92struct TempBranchCleanupGuard {
93 branches: Vec<String>,
94 cleaned: bool,
95}
96
97#[allow(dead_code)]
98impl TempBranchCleanupGuard {
99 fn new() -> Self {
100 Self {
101 branches: Vec::new(),
102 cleaned: false,
103 }
104 }
105
106 fn add_branch(&mut self, branch: String) {
107 self.branches.push(branch);
108 }
109
110 fn cleanup(&mut self, git_repo: &GitRepository) {
112 if self.cleaned || self.branches.is_empty() {
113 return;
114 }
115
116 tracing::debug!("Cleaning up {} temporary branches", self.branches.len());
117 for branch in &self.branches {
118 if let Err(e) = git_repo.delete_branch_unsafe(branch) {
119 tracing::debug!("Failed to delete temp branch {}: {}", branch, e);
120 }
122 }
123 self.cleaned = true;
124 }
125}
126
127impl Drop for TempBranchCleanupGuard {
128 fn drop(&mut self) {
129 if !self.cleaned && !self.branches.is_empty() {
130 tracing::warn!(
133 "{} temporary branches were not cleaned up: {}",
134 self.branches.len(),
135 self.branches.join(", ")
136 );
137 tracing::warn!("Run 'ca cleanup' to remove orphaned temporary branches");
138 }
139 }
140}
141
142pub struct RebaseManager {
144 stack_manager: StackManager,
145 git_repo: GitRepository,
146 options: RebaseOptions,
147 conflict_analyzer: ConflictAnalyzer,
148}
149
150impl Default for RebaseOptions {
151 fn default() -> Self {
152 Self {
153 strategy: RebaseStrategy::ForcePush,
154 interactive: false,
155 target_base: None,
156 preserve_merges: true,
157 auto_resolve: true,
158 max_retries: 3,
159 skip_pull: None,
160 original_working_branch: None,
161 }
162 }
163}
164
165impl RebaseManager {
166 pub fn new(
168 stack_manager: StackManager,
169 git_repo: GitRepository,
170 options: RebaseOptions,
171 ) -> Self {
172 Self {
173 stack_manager,
174 git_repo,
175 options,
176 conflict_analyzer: ConflictAnalyzer::new(),
177 }
178 }
179
180 pub fn into_stack_manager(self) -> StackManager {
182 self.stack_manager
183 }
184
185 pub fn rebase_stack(&mut self, stack_id: &Uuid) -> Result<RebaseResult> {
187 debug!("Starting rebase for stack {}", stack_id);
188
189 let stack = self
190 .stack_manager
191 .get_stack(stack_id)
192 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?
193 .clone();
194
195 match self.options.strategy {
196 RebaseStrategy::ForcePush => self.rebase_with_force_push(&stack),
197 RebaseStrategy::Interactive => self.rebase_interactive(&stack),
198 }
199 }
200
201 fn rebase_with_force_push(&mut self, stack: &Stack) -> Result<RebaseResult> {
205 use crate::cli::output::Output;
206
207 if self.has_in_progress_cherry_pick()? {
209 return self.handle_in_progress_cherry_pick(stack);
210 }
211
212 Output::section(format!("Rebasing stack: {}", stack.name));
214 Output::sub_item(format!("Base branch: {}", stack.base_branch));
215 Output::sub_item(format!("Entries: {}", stack.entries.len()));
216
217 let mut result = RebaseResult {
218 success: true,
219 branch_mapping: HashMap::new(),
220 conflicts: Vec::new(),
221 new_commits: Vec::new(),
222 error: None,
223 summary: String::new(),
224 };
225
226 let target_base = self
227 .options
228 .target_base
229 .as_ref()
230 .unwrap_or(&stack.base_branch)
231 .clone(); let original_branch = self
237 .options
238 .original_working_branch
239 .clone()
240 .or_else(|| self.git_repo.get_current_branch().ok());
241
242 let original_branch_for_cleanup = original_branch.clone();
244
245 if let Some(ref orig) = original_branch {
248 if orig == &target_base {
249 debug!(
250 "Original working branch is base branch '{}' - will skip working branch update",
251 orig
252 );
253 }
254 }
255
256 if !self.options.skip_pull.unwrap_or(false) {
259 if let Err(e) = self.pull_latest_changes(&target_base) {
260 Output::warning(format!("Could not pull latest changes: {}", e));
261 }
262 }
263
264 if let Err(e) = self.git_repo.reset_to_head() {
266 if let Some(ref orig) = original_branch_for_cleanup {
268 let _ = self.git_repo.checkout_branch_unsafe(orig);
269 }
270
271 return Err(CascadeError::branch(format!(
272 "Could not reset working directory to HEAD: {}.\n\
273 Another Git process may still be holding the index lock. \
274 Resolve the lock (remove .git/index.lock if safe) and retry.",
275 e
276 )));
277 }
278
279 let mut current_base = target_base.clone();
280 let entry_count = stack.entries.iter().filter(|e| !e.is_merged).count();
282 let mut temp_branches: Vec<String> = Vec::new(); if entry_count == 0 {
286 println!();
287 if stack.entries.is_empty() {
288 Output::info("Stack has no entries yet");
289 Output::tip("Use 'ca push' to add commits to this stack");
290 result.summary = "Stack is empty".to_string();
291 } else {
292 Output::info("All entries in this stack have been merged");
293 Output::tip("Use 'ca push' to add new commits, or 'ca stack cleanup' to prune merged branches");
294 result.summary = "All entries merged".to_string();
295 }
296
297 println!();
299 Output::success(&result.summary);
300
301 self.stack_manager.save_to_disk()?;
303 return Ok(result);
304 }
305
306 let all_up_to_date = stack
308 .entries
309 .iter()
310 .filter(|entry| !entry.is_merged) .all(|entry| {
312 self.git_repo
313 .is_commit_based_on(&entry.commit_hash, &target_base)
314 .unwrap_or(false)
315 });
316
317 if all_up_to_date {
318 println!();
319 Output::success("Stack is already up-to-date with base branch");
320 result.summary = "Stack is up-to-date".to_string();
321 result.success = true;
322 return Ok(result);
323 }
324
325 let repo_root = self.git_repo.path().to_path_buf();
326 let mut sync_state = SyncState {
327 stack_id: stack.id.to_string(),
328 stack_name: stack.name.clone(),
329 original_branch: original_branch_for_cleanup
330 .clone()
331 .unwrap_or_else(|| target_base.clone()),
332 target_base: target_base.clone(),
333 remaining_entry_ids: stack.entries.iter().map(|e| e.id.to_string()).collect(),
334 current_entry_id: String::new(),
335 current_entry_branch: String::new(),
336 current_temp_branch: String::new(),
337 temp_branches: Vec::new(),
338 };
339
340 let _ = SyncState::delete(&repo_root);
342
343 let mut branches_with_new_commits: std::collections::HashSet<String> =
346 std::collections::HashSet::new();
347 let mut branches_to_push: Vec<(String, String, usize)> = Vec::new(); let mut processed_entries: usize = 0; for (index, entry) in stack.entries.iter().enumerate() {
350 let original_branch = &entry.branch;
351 let entry_id_str = entry.id.to_string();
352
353 sync_state.remaining_entry_ids = stack
354 .entries
355 .iter()
356 .skip(index + 1)
357 .map(|e| e.id.to_string())
358 .collect();
359
360 if entry.is_merged {
362 tracing::debug!(
363 "Entry '{}' is merged into '{}', skipping rebase",
364 original_branch,
365 target_base
366 );
367 continue;
369 }
370
371 processed_entries += 1;
372
373 sync_state.current_entry_id = entry_id_str.clone();
374 sync_state.current_entry_branch = original_branch.clone();
375
376 if self
379 .git_repo
380 .is_commit_based_on(&entry.commit_hash, ¤t_base)
381 .unwrap_or(false)
382 {
383 tracing::debug!(
384 "Entry '{}' is already correctly based on '{}', skipping rebase",
385 original_branch,
386 current_base
387 );
388
389 result
390 .branch_mapping
391 .insert(original_branch.clone(), original_branch.clone());
392
393 current_base = original_branch.clone();
395 continue;
396 }
397
398 if !result.success {
401 tracing::debug!(
402 "Skipping entry '{}' because previous entry failed",
403 original_branch
404 );
405 break;
406 }
407
408 let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
411 temp_branches.push(temp_branch.clone()); sync_state.current_temp_branch = temp_branch.clone();
413
414 if let Err(e) = self
416 .git_repo
417 .create_branch(&temp_branch, Some(¤t_base))
418 {
419 if let Some(ref orig) = original_branch_for_cleanup {
421 let _ = self.git_repo.checkout_branch_unsafe(orig);
422 }
423 return Err(e);
424 }
425
426 if let Err(e) = self.git_repo.checkout_branch_silent(&temp_branch) {
427 if let Some(ref orig) = original_branch_for_cleanup {
429 let _ = self.git_repo.checkout_branch_unsafe(orig);
430 }
431 return Err(e);
432 }
433
434 sync_state.temp_branches = temp_branches.clone();
436 sync_state.save(&repo_root)?;
437
438 match self.cherry_pick_commit(&entry.commit_hash) {
440 Ok(new_commit_hash) => {
441 result.new_commits.push(new_commit_hash.clone());
442
443 let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
445
446 self.git_repo
449 .update_branch_to_commit(original_branch, &rebased_commit_id)?;
450
451 result
452 .branch_mapping
453 .insert(original_branch.clone(), original_branch.clone());
454
455 self.update_stack_entry(
457 stack.id,
458 &entry.id,
459 original_branch,
460 &rebased_commit_id,
461 )?;
462 branches_with_new_commits.insert(original_branch.clone());
463
464 if let Some(pr_num) = &entry.pull_request_id {
466 let tree_char = if processed_entries == entry_count {
467 "└─"
468 } else {
469 "├─"
470 };
471 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
472 branches_to_push.push((
473 original_branch.clone(),
474 pr_num.clone(),
475 processed_entries - 1,
476 ));
477 }
478
479 current_base = original_branch.clone();
481
482 let _ = SyncState::delete(&repo_root);
483 }
484 Err(e) => {
485 if self.git_repo.get_conflicted_files()?.is_empty() {
487 debug!(
488 "Cherry-pick produced no changes for {} ({}), skipping entry",
489 original_branch,
490 &entry.commit_hash[..8]
491 );
492
493 Output::warning(format!(
494 "Skipping entry '{}' - cherry-pick resulted in no changes",
495 original_branch
496 ));
497 Output::sub_item("This usually means the base branch has moved forward");
498 Output::sub_item("and this entry's changes are already present");
499
500 let _ = std::process::Command::new("git")
502 .args(["cherry-pick", "--abort"])
503 .current_dir(self.git_repo.path())
504 .output();
505
506 let _ = self.git_repo.checkout_branch_unsafe(&target_base);
508 let _ = self.git_repo.delete_branch_unsafe(&temp_branch);
509 let _ = temp_branches.pop();
510 let _ = SyncState::delete(&repo_root);
511
512 continue;
514 }
515
516 result.conflicts.push(entry.commit_hash.clone());
517
518 if !self.options.auto_resolve {
519 println!();
520 Output::error(e.to_string());
521 result.success = false;
522 result.error = Some(format!(
523 "Conflict in {}: {}\n\n\
524 MANUAL CONFLICT RESOLUTION REQUIRED\n\
525 =====================================\n\n\
526 Step 1: Analyze conflicts\n\
527 → Run: ca conflicts\n\
528 → This shows which conflicts are in which files\n\n\
529 Step 2: Resolve conflicts in your editor\n\
530 → Open conflicted files and edit them\n\
531 → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
532 → Keep the code you want\n\
533 → Save the files\n\n\
534 Step 3: Mark conflicts as resolved\n\
535 → Run: git add <resolved-files>\n\
536 → Or: git add -A (to stage all resolved files)\n\n\
537 Step 4: Complete the sync\n\
538 → Run: ca sync continue\n\
539 → Cascade will complete the cherry-pick and continue\n\n\
540 Alternative: Abort and start over\n\
541 → Run: ca sync abort\n\
542 → Then: ca sync (starts fresh)\n\n\
543 TIP: Enable auto-resolution for simple conflicts:\n\
544 → Run: ca sync --auto-resolve\n\
545 → Only complex conflicts will require manual resolution",
546 entry.commit_hash, e
547 ));
548 break;
549 }
550
551 match self.auto_resolve_conflicts(&entry.commit_hash) {
553 Ok(fully_resolved) => {
554 if !fully_resolved {
555 result.success = false;
556 result.error = Some(format!(
557 "Conflicts in commit {}\n\n\
558 To resolve:\n\
559 1. Fix conflicts in your editor\n\
560 2. Stage resolved files: git add <files>\n\
561 3. Continue: ca sync continue\n\n\
562 Or abort:\n\
563 → Run: ca sync abort",
564 &entry.commit_hash[..8]
565 ));
566 break;
567 }
568
569 let commit_message = entry.message.trim().to_string();
572
573 debug!("Checking staged files before commit");
575 let staged_files = self.git_repo.get_staged_files()?;
576
577 if staged_files.is_empty() {
578 debug!(
581 "Cherry-pick resulted in empty commit for {}",
582 &entry.commit_hash[..8]
583 );
584
585 Output::warning(format!(
587 "Skipping entry '{}' - cherry-pick resulted in no changes",
588 original_branch
589 ));
590 Output::sub_item(
591 "This usually means the base branch has moved forward",
592 );
593 Output::sub_item("and this entry's changes are already present");
594
595 let _ = std::process::Command::new("git")
597 .args(["cherry-pick", "--abort"])
598 .current_dir(self.git_repo.path())
599 .output();
600
601 let _ = self.git_repo.checkout_branch_unsafe(&target_base);
602 let _ = self.git_repo.delete_branch_unsafe(&temp_branch);
603 let _ = temp_branches.pop();
604
605 let _ = SyncState::delete(&repo_root);
606
607 continue;
609 }
610
611 debug!("{} files staged", staged_files.len());
612
613 match self.git_repo.commit(&commit_message) {
614 Ok(new_commit_id) => {
615 debug!(
616 "Created commit {} with message '{}'",
617 &new_commit_id[..8],
618 commit_message
619 );
620
621 if let Err(e) = self.git_repo.cleanup_state() {
623 tracing::warn!(
624 "Failed to clean up repository state after auto-resolve: {}",
625 e
626 );
627 }
628
629 Output::success("Auto-resolved conflicts");
630 result.new_commits.push(new_commit_id.clone());
631 let rebased_commit_id = new_commit_id;
632
633 self.cleanup_backup_files()?;
635
636 self.git_repo.update_branch_to_commit(
638 original_branch,
639 &rebased_commit_id,
640 )?;
641
642 branches_with_new_commits.insert(original_branch.clone());
643
644 if let Some(pr_num) = &entry.pull_request_id {
646 let tree_char = if processed_entries == entry_count {
647 "└─"
648 } else {
649 "├─"
650 };
651 println!(
652 " {} {} (PR #{})",
653 tree_char, original_branch, pr_num
654 );
655 branches_to_push.push((
656 original_branch.clone(),
657 pr_num.clone(),
658 processed_entries - 1,
659 ));
660 }
661
662 result
663 .branch_mapping
664 .insert(original_branch.clone(), original_branch.clone());
665
666 self.update_stack_entry(
668 stack.id,
669 &entry.id,
670 original_branch,
671 &rebased_commit_id,
672 )?;
673
674 current_base = original_branch.clone();
676 }
677 Err(commit_err) => {
678 result.success = false;
679 result.error = Some(format!(
680 "Could not commit auto-resolved conflicts: {}\n\n\
681 This usually means:\n\
682 - Git index is locked (another process accessing repo)\n\
683 - File permissions issue\n\
684 - Disk space issue\n\n\
685 Recovery:\n\
686 1. Check if another Git operation is running\n\
687 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
688 3. Run 'git status' to check repo state\n\
689 4. Retry 'ca sync' after fixing the issue",
690 commit_err
691 ));
692 break;
693 }
694 }
695 }
696 Err(resolve_err) => {
697 result.success = false;
698 result.error = Some(format!(
699 "Could not resolve conflicts: {}\n\n\
700 Recovery:\n\
701 1. Check repo state: 'git status'\n\
702 2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
703 3. Remove any lock files: 'rm -f .git/index.lock'\n\
704 4. Retry 'ca sync'",
705 resolve_err
706 ));
707 break;
708 }
709 }
710 }
711 }
712 }
713
714 if result.success && !temp_branches.is_empty() {
718 if let Err(e) = self.git_repo.checkout_branch_unsafe(&target_base) {
721 debug!("Could not checkout base for cleanup: {}", e);
722 } else {
725 for temp_branch in &temp_branches {
727 if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
728 debug!("Could not delete temp branch {}: {}", temp_branch, e);
729 }
730 }
731 }
732 }
733
734 let pushed_count = branches_to_push.len();
740 let _skipped_count = entry_count - pushed_count; let mut successful_pushes = 0; if !result.success {
744 println!();
745 Output::error("Rebase failed - not pushing any branches");
746 } else {
749 if !branches_to_push.is_empty() {
753 println!();
754
755 if let Err(e) = self.git_repo.fetch_with_retry() {
757 Output::warning(format!("Could not fetch latest remote state: {}", e));
758 Output::tip("Continuing with push, but backup branches may not be created if remote state is unknown");
759 }
760
761 let mut push_results = Vec::new();
763 for (branch_name, _pr_num, _index) in branches_to_push.iter() {
764 let result = self
765 .git_repo
766 .force_push_single_branch_auto_no_fetch(branch_name);
767 push_results.push((branch_name.clone(), result));
768 }
769
770 let mut failed_pushes = 0;
772 for (index, (branch_name, result)) in push_results.iter().enumerate() {
773 match result {
774 Ok(_) => {
775 debug!("Pushed {} successfully", branch_name);
776 successful_pushes += 1;
777 println!(
778 " ✓ Pushed {} ({}/{})",
779 branch_name,
780 index + 1,
781 pushed_count
782 );
783 }
784 Err(e) => {
785 failed_pushes += 1;
786 println!(" ⚠ Could not push '{}': {}", branch_name, e);
787 }
788 }
789 }
790
791 if failed_pushes > 0 {
793 println!(); Output::warning(format!(
795 "{} branch(es) failed to push to remote",
796 failed_pushes
797 ));
798 Output::tip("To retry failed pushes, run: ca sync");
799 }
800 }
801
802 let entries_word = if entry_count == 1 { "entry" } else { "entries" };
804 let pr_word = if successful_pushes == 1 { "PR" } else { "PRs" };
805
806 result.summary = if successful_pushes > 0 {
807 let not_submitted_count = entry_count - successful_pushes;
808 if not_submitted_count > 0 {
809 format!(
810 "{} {} rebased ({} {} updated, {} not yet submitted)",
811 entry_count, entries_word, successful_pushes, pr_word, not_submitted_count
812 )
813 } else {
814 format!(
815 "{} {} rebased ({} {} updated)",
816 entry_count, entries_word, successful_pushes, pr_word
817 )
818 }
819 } else {
820 format!(
821 "{} {} rebased (none submitted to Bitbucket yet)",
822 entry_count, entries_word
823 )
824 };
825 } if result.success {
828 if let Some(ref working_branch_name) = stack.working_branch {
833 if working_branch_name != &target_base {
835 if let Some(last_entry) = stack.entries.last() {
836 let top_branch = &last_entry.branch;
837
838 if let (Ok(working_head), Ok(top_commit)) = (
841 self.git_repo.get_branch_head(working_branch_name),
842 self.git_repo.get_branch_head(top_branch),
843 ) {
844 if working_head != top_commit {
846 if let Ok(commits) = self
848 .git_repo
849 .get_commits_between(&top_commit, &working_head)
850 {
851 if !commits.is_empty() {
852 let stack_messages: Vec<String> = stack
855 .entries
856 .iter()
857 .map(|e| e.message.trim().to_string())
858 .collect();
859
860 let all_match_stack = commits.iter().all(|commit| {
861 if let Some(msg) = commit.summary() {
862 stack_messages
863 .iter()
864 .any(|stack_msg| stack_msg == msg.trim())
865 } else {
866 false
867 }
868 });
869
870 if all_match_stack {
871 debug!(
876 "Working branch has old pre-rebase commits (matching stack messages) - safe to update"
877 );
878 } else {
879 Output::error(format!(
881 "Cannot sync: Working branch '{}' has {} commit(s) not in the stack",
882 working_branch_name,
883 commits.len()
884 ));
885 println!();
886 Output::sub_item(
887 "These commits would be lost if we proceed:",
888 );
889 for (i, commit) in commits.iter().take(5).enumerate() {
890 let message =
891 commit.summary().unwrap_or("(no message)");
892 Output::sub_item(format!(
893 " {}. {} - {}",
894 i + 1,
895 &commit.id().to_string()[..8],
896 message
897 ));
898 }
899 if commits.len() > 5 {
900 Output::sub_item(format!(
901 " ... and {} more",
902 commits.len() - 5
903 ));
904 }
905 println!();
906 Output::tip("Add these commits to the stack first:");
907 Output::bullet("Run: ca stack push");
908 Output::bullet("Then run: ca sync");
909 println!();
910
911 if let Some(ref orig) = original_branch_for_cleanup {
913 let _ = self.git_repo.checkout_branch_unsafe(orig);
914 }
915
916 return Err(CascadeError::validation(
917 format!(
918 "Working branch '{}' has {} untracked commit(s). Add them to the stack with 'ca stack push' before syncing.",
919 working_branch_name, commits.len()
920 )
921 ));
922 }
923 }
924 }
925 }
926
927 debug!(
929 "Updating working branch '{}' to match top of stack ({})",
930 working_branch_name,
931 &top_commit[..8]
932 );
933
934 if let Err(e) = self
935 .git_repo
936 .update_branch_to_commit(working_branch_name, &top_commit)
937 {
938 Output::warning(format!(
939 "Could not update working branch '{}' to top of stack: {}",
940 working_branch_name, e
941 ));
942 }
943 }
944 }
945 } else {
946 debug!(
948 "Skipping working branch update - working branch '{}' is the base branch",
949 working_branch_name
950 );
951 }
952 }
953
954 if let Some(ref orig_branch) = original_branch {
957 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
958 debug!(
959 "Could not return to original branch '{}': {}",
960 orig_branch, e
961 );
962 }
964 }
965 }
966 println!();
971 if result.success {
972 Output::success(&result.summary);
973 } else {
974 let error_msg = result
976 .error
977 .as_deref()
978 .unwrap_or("Rebase failed for unknown reason");
979 Output::error(error_msg);
980 }
981
982 self.stack_manager.save_to_disk()?;
984
985 if !result.success {
988 let detailed_error = result.error.as_deref().unwrap_or("Rebase failed");
989 return Err(CascadeError::Branch(detailed_error.to_string()));
990 }
991
992 Ok(result)
993 }
994
995 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
997 tracing::debug!("Starting interactive rebase for stack '{}'", stack.name);
998
999 let mut result = RebaseResult {
1000 success: true,
1001 branch_mapping: HashMap::new(),
1002 conflicts: Vec::new(),
1003 new_commits: Vec::new(),
1004 error: None,
1005 summary: String::new(),
1006 };
1007
1008 println!("Interactive Rebase for Stack: {}", stack.name);
1009 println!(" Base branch: {}", stack.base_branch);
1010 println!(" Entries: {}", stack.entries.len());
1011
1012 if self.options.interactive {
1013 println!("\nChoose action for each commit:");
1014 println!(" (p)ick - apply the commit");
1015 println!(" (s)kip - skip this commit");
1016 println!(" (e)dit - edit the commit message");
1017 println!(" (q)uit - abort the rebase");
1018 }
1019
1020 for entry in &stack.entries {
1023 println!(
1024 " {} {} - {}",
1025 entry.short_hash(),
1026 entry.branch,
1027 entry.short_message(50)
1028 );
1029
1030 match self.cherry_pick_commit(&entry.commit_hash) {
1032 Ok(new_commit) => result.new_commits.push(new_commit),
1033 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
1034 }
1035 }
1036
1037 result.summary = format!(
1038 "Interactive rebase processed {} commits",
1039 stack.entries.len()
1040 );
1041 Ok(result)
1042 }
1043
1044 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
1046 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
1048
1049 if let Ok(staged_files) = self.git_repo.get_staged_files() {
1051 if !staged_files.is_empty() {
1052 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
1054 match self.git_repo.commit_staged_changes(&cleanup_message) {
1055 Ok(Some(_)) => {
1056 debug!(
1057 "Committed {} leftover staged files after cherry-pick",
1058 staged_files.len()
1059 );
1060 }
1061 Ok(None) => {
1062 debug!("Staged files were cleared before commit");
1064 }
1065 Err(e) => {
1066 tracing::warn!(
1068 "Failed to commit {} staged files after cherry-pick: {}. \
1069 User may see checkout warning with staged changes.",
1070 staged_files.len(),
1071 e
1072 );
1073 }
1075 }
1076 }
1077 }
1078
1079 Ok(new_commit_hash)
1080 }
1081
1082 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
1084 debug!("Starting auto-resolve for commit {}", commit_hash);
1085
1086 let has_conflicts = self.git_repo.has_conflicts()?;
1088 debug!("has_conflicts() = {}", has_conflicts);
1089
1090 let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
1092 let cherry_pick_in_progress = cherry_pick_head.exists();
1093
1094 if !has_conflicts {
1095 debug!("No conflicts detected by Git index");
1096
1097 if cherry_pick_in_progress {
1099 tracing::debug!(
1100 "CHERRY_PICK_HEAD exists but no conflicts in index - aborting cherry-pick"
1101 );
1102
1103 let _ = std::process::Command::new("git")
1105 .args(["cherry-pick", "--abort"])
1106 .current_dir(self.git_repo.path())
1107 .output();
1108
1109 return Err(CascadeError::Branch(format!(
1110 "Cherry-pick failed for {} but Git index shows no conflicts. \
1111 This usually means the cherry-pick was aborted or failed in an unexpected way. \
1112 Please try manual resolution.",
1113 &commit_hash[..8]
1114 )));
1115 }
1116
1117 return Ok(true);
1118 }
1119
1120 let conflicted_files = self.git_repo.get_conflicted_files()?;
1121
1122 if conflicted_files.is_empty() {
1123 debug!("Conflicted files list is empty");
1124 return Ok(true);
1125 }
1126
1127 debug!(
1128 "Found conflicts in {} files: {:?}",
1129 conflicted_files.len(),
1130 conflicted_files
1131 );
1132
1133 let analysis = self
1135 .conflict_analyzer
1136 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
1137
1138 debug!(
1139 "Conflict analysis: {} total conflicts, {} auto-resolvable",
1140 analysis.total_conflicts, analysis.auto_resolvable_count
1141 );
1142
1143 for recommendation in &analysis.recommendations {
1145 debug!("{}", recommendation);
1146 }
1147
1148 let mut resolved_count = 0;
1149 let mut resolved_files = Vec::new(); let mut failed_files = Vec::new();
1151
1152 for file_analysis in &analysis.files {
1153 debug!(
1154 "Processing file: {} (auto_resolvable: {}, conflicts: {})",
1155 file_analysis.file_path,
1156 file_analysis.auto_resolvable,
1157 file_analysis.conflicts.len()
1158 );
1159
1160 if file_analysis.auto_resolvable {
1161 match self.resolve_file_conflicts_enhanced(
1162 &file_analysis.file_path,
1163 &file_analysis.conflicts,
1164 ) {
1165 Ok(ConflictResolution::Resolved) => {
1166 resolved_count += 1;
1167 resolved_files.push(file_analysis.file_path.clone());
1168 debug!("Successfully resolved {}", file_analysis.file_path);
1169 }
1170 Ok(ConflictResolution::TooComplex) => {
1171 debug!(
1172 "{} too complex for auto-resolution",
1173 file_analysis.file_path
1174 );
1175 failed_files.push(file_analysis.file_path.clone());
1176 }
1177 Err(e) => {
1178 debug!("Failed to resolve {}: {}", file_analysis.file_path, e);
1179 failed_files.push(file_analysis.file_path.clone());
1180 }
1181 }
1182 } else {
1183 failed_files.push(file_analysis.file_path.clone());
1184 debug!(
1185 "{} requires manual resolution ({} conflicts)",
1186 file_analysis.file_path,
1187 file_analysis.conflicts.len()
1188 );
1189 }
1190 }
1191
1192 if resolved_count > 0 {
1193 debug!(
1194 "Resolved {}/{} files",
1195 resolved_count,
1196 conflicted_files.len()
1197 );
1198 debug!("Resolved files: {:?}", resolved_files);
1199
1200 let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
1203 debug!("Staging {} files", file_paths.len());
1204 self.git_repo.stage_files(&file_paths)?;
1205 debug!("Files staged successfully");
1206 } else {
1207 debug!("No files were resolved (resolved_count = 0)");
1208 }
1209
1210 let all_resolved = failed_files.is_empty();
1212
1213 debug!(
1214 "all_resolved = {}, failed_files = {:?}",
1215 all_resolved, failed_files
1216 );
1217
1218 if !all_resolved {
1219 debug!("{} files still need manual resolution", failed_files.len());
1220 }
1221
1222 debug!("Returning all_resolved = {}", all_resolved);
1223 Ok(all_resolved)
1224 }
1225
1226 fn resolve_file_conflicts_enhanced(
1228 &self,
1229 file_path: &str,
1230 conflicts: &[crate::git::ConflictRegion],
1231 ) -> Result<ConflictResolution> {
1232 let repo_path = self.git_repo.path();
1233 let full_path = repo_path.join(file_path);
1234
1235 let mut content = std::fs::read_to_string(&full_path)
1237 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
1238
1239 if conflicts.is_empty() {
1240 return Ok(ConflictResolution::Resolved);
1241 }
1242
1243 tracing::debug!(
1244 "Resolving {} conflicts in {} using enhanced analysis",
1245 conflicts.len(),
1246 file_path
1247 );
1248
1249 let mut any_resolved = false;
1250
1251 for conflict in conflicts.iter().rev() {
1253 match self.resolve_single_conflict_enhanced(conflict) {
1254 Ok(Some(resolution)) => {
1255 let before = &content[..conflict.start_pos];
1257 let after = &content[conflict.end_pos..];
1258 content = format!("{before}{resolution}{after}");
1259 any_resolved = true;
1260 debug!(
1261 "✅ Resolved {} conflict at lines {}-{} in {}",
1262 format!("{:?}", conflict.conflict_type).to_lowercase(),
1263 conflict.start_line,
1264 conflict.end_line,
1265 file_path
1266 );
1267 }
1268 Ok(None) => {
1269 debug!(
1270 "⚠️ {} conflict at lines {}-{} in {} requires manual resolution",
1271 format!("{:?}", conflict.conflict_type).to_lowercase(),
1272 conflict.start_line,
1273 conflict.end_line,
1274 file_path
1275 );
1276 return Ok(ConflictResolution::TooComplex);
1277 }
1278 Err(e) => {
1279 debug!("❌ Failed to resolve conflict in {}: {}", file_path, e);
1280 return Ok(ConflictResolution::TooComplex);
1281 }
1282 }
1283 }
1284
1285 if any_resolved {
1286 let remaining_conflicts = self.parse_conflict_markers(&content)?;
1288
1289 if remaining_conflicts.is_empty() {
1290 debug!(
1291 "All conflicts resolved in {}, content length: {} bytes",
1292 file_path,
1293 content.len()
1294 );
1295
1296 if content.trim().is_empty() {
1298 tracing::warn!(
1299 "SAFETY CHECK: Resolved content for {} is empty! Aborting auto-resolution.",
1300 file_path
1301 );
1302 return Ok(ConflictResolution::TooComplex);
1303 }
1304
1305 let backup_path = full_path.with_extension("cascade-backup");
1307 if let Ok(original_content) = std::fs::read_to_string(&full_path) {
1308 debug!(
1309 "Backup for {} (original: {} bytes, resolved: {} bytes)",
1310 file_path,
1311 original_content.len(),
1312 content.len()
1313 );
1314 let _ = std::fs::write(&backup_path, original_content);
1315 }
1316
1317 crate::utils::atomic_file::write_string(&full_path, &content)?;
1319
1320 debug!("Wrote {} bytes to {}", content.len(), file_path);
1321 return Ok(ConflictResolution::Resolved);
1322 } else {
1323 tracing::debug!(
1324 "Partially resolved conflicts in {} ({} remaining)",
1325 file_path,
1326 remaining_conflicts.len()
1327 );
1328 }
1329 }
1330
1331 Ok(ConflictResolution::TooComplex)
1332 }
1333
1334 #[allow(dead_code)]
1336 fn count_whitespace_consistency(content: &str) -> usize {
1337 let mut inconsistencies = 0;
1338 let lines: Vec<&str> = content.lines().collect();
1339
1340 for line in &lines {
1341 if line.contains('\t') && line.contains(' ') {
1343 inconsistencies += 1;
1344 }
1345 }
1346
1347 lines.len().saturating_sub(inconsistencies)
1349 }
1350
1351 fn cleanup_backup_files(&self) -> Result<()> {
1353 use std::fs;
1354 use std::path::Path;
1355
1356 let repo_path = self.git_repo.path();
1357
1358 fn remove_backups_recursive(dir: &Path) {
1360 if let Ok(entries) = fs::read_dir(dir) {
1361 for entry in entries.flatten() {
1362 let path = entry.path();
1363
1364 if path.is_dir() {
1365 if path.file_name().and_then(|n| n.to_str()) != Some(".git") {
1367 remove_backups_recursive(&path);
1368 }
1369 } else if let Some(ext) = path.extension() {
1370 if ext == "cascade-backup" {
1371 debug!("Cleaning up backup file: {}", path.display());
1372 if let Err(e) = fs::remove_file(&path) {
1373 tracing::warn!(
1375 "Could not remove backup file {}: {}",
1376 path.display(),
1377 e
1378 );
1379 }
1380 }
1381 }
1382 }
1383 }
1384 }
1385
1386 remove_backups_recursive(repo_path);
1387 Ok(())
1388 }
1389
1390 fn resolve_single_conflict_enhanced(
1392 &self,
1393 conflict: &crate::git::ConflictRegion,
1394 ) -> Result<Option<String>> {
1395 debug!(
1396 "Resolving {} conflict in {} (lines {}-{})",
1397 format!("{:?}", conflict.conflict_type).to_lowercase(),
1398 conflict.file_path,
1399 conflict.start_line,
1400 conflict.end_line
1401 );
1402
1403 use crate::git::ConflictType;
1404
1405 match conflict.conflict_type {
1406 ConflictType::Whitespace => {
1407 let our_normalized = conflict
1410 .our_content
1411 .split_whitespace()
1412 .collect::<Vec<_>>()
1413 .join(" ");
1414 let their_normalized = conflict
1415 .their_content
1416 .split_whitespace()
1417 .collect::<Vec<_>>()
1418 .join(" ");
1419
1420 if our_normalized == their_normalized {
1421 Ok(Some(conflict.their_content.clone()))
1426 } else {
1427 debug!(
1429 "Whitespace conflict has content differences - requires manual resolution"
1430 );
1431 Ok(None)
1432 }
1433 }
1434 ConflictType::LineEnding => {
1435 let normalized = conflict
1437 .our_content
1438 .replace("\r\n", "\n")
1439 .replace('\r', "\n");
1440 Ok(Some(normalized))
1441 }
1442 ConflictType::PureAddition => {
1443 if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1447 Ok(Some(conflict.their_content.clone()))
1449 } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1450 Ok(Some(String::new()))
1452 } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1453 Ok(Some(String::new()))
1455 } else {
1456 debug!(
1462 "PureAddition conflict has content on both sides - requires manual resolution"
1463 );
1464 Ok(None)
1465 }
1466 }
1467 ConflictType::ImportMerge => {
1468 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1473 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1474
1475 let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1477 let trimmed = line.trim();
1478 trimmed.starts_with("import ")
1479 || trimmed.starts_with("from ")
1480 || trimmed.starts_with("use ")
1481 || trimmed.starts_with("#include")
1482 || trimmed.is_empty()
1483 });
1484
1485 if !all_simple {
1486 debug!("ImportMerge contains non-import lines - requires manual resolution");
1487 return Ok(None);
1488 }
1489
1490 let mut all_imports: Vec<&str> = our_lines
1492 .into_iter()
1493 .chain(their_lines)
1494 .filter(|line| !line.trim().is_empty())
1495 .collect();
1496 all_imports.sort();
1497 all_imports.dedup();
1498 Ok(Some(all_imports.join("\n")))
1499 }
1500 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1501 Ok(None)
1503 }
1504 }
1505 }
1506
1507 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1509 let lines: Vec<&str> = content.lines().collect();
1510 let mut conflicts = Vec::new();
1511 let mut i = 0;
1512
1513 while i < lines.len() {
1514 if lines[i].starts_with("<<<<<<<") {
1515 let start_line = i + 1;
1517 let mut separator_line = None;
1518 let mut end_line = None;
1519
1520 for (j, line) in lines.iter().enumerate().skip(i + 1) {
1522 if line.starts_with("=======") {
1523 separator_line = Some(j + 1);
1524 } else if line.starts_with(">>>>>>>") {
1525 end_line = Some(j + 1);
1526 break;
1527 }
1528 }
1529
1530 if let (Some(sep), Some(end)) = (separator_line, end_line) {
1531 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1533 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1534
1535 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1536 let their_content = lines[sep..(end - 1)].join("\n");
1537
1538 conflicts.push(ConflictRegion {
1539 start: start_pos,
1540 end: end_pos,
1541 start_line,
1542 end_line: end,
1543 our_content,
1544 their_content,
1545 });
1546
1547 i = end;
1548 } else {
1549 i += 1;
1550 }
1551 } else {
1552 i += 1;
1553 }
1554 }
1555
1556 Ok(conflicts)
1557 }
1558
1559 fn update_stack_entry(
1562 &mut self,
1563 stack_id: Uuid,
1564 entry_id: &Uuid,
1565 _new_branch: &str,
1566 new_commit_hash: &str,
1567 ) -> Result<()> {
1568 debug!(
1569 "Updating entry {} in stack {} with new commit {}",
1570 entry_id, stack_id, new_commit_hash
1571 );
1572
1573 let stack = self
1575 .stack_manager
1576 .get_stack_mut(&stack_id)
1577 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1578
1579 let entry_exists = stack.entries.iter().any(|e| e.id == *entry_id);
1581
1582 if entry_exists {
1583 let old_hash = stack
1584 .entries
1585 .iter()
1586 .find(|e| e.id == *entry_id)
1587 .map(|e| e.commit_hash.clone())
1588 .unwrap();
1589
1590 debug!(
1591 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch)",
1592 entry_id, old_hash, new_commit_hash
1593 );
1594
1595 stack
1598 .update_entry_commit_hash(entry_id, new_commit_hash.to_string())
1599 .map_err(CascadeError::config)?;
1600
1601 debug!(
1604 "Successfully updated entry {} in stack {}",
1605 entry_id, stack_id
1606 );
1607 Ok(())
1608 } else {
1609 Err(CascadeError::config(format!(
1610 "Entry {entry_id} not found in stack {stack_id}"
1611 )))
1612 }
1613 }
1614
1615 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1617 tracing::debug!("Pulling latest changes for branch {}", branch);
1618
1619 match self.git_repo.fetch() {
1621 Ok(_) => {
1622 debug!("Fetch successful");
1623 match self.git_repo.pull(branch) {
1625 Ok(_) => {
1626 tracing::debug!("Pull completed successfully for {}", branch);
1627 Ok(())
1628 }
1629 Err(e) => {
1630 tracing::debug!("Pull failed for {}: {}", branch, e);
1631 Ok(())
1633 }
1634 }
1635 }
1636 Err(e) => {
1637 tracing::debug!("Fetch failed: {}", e);
1638 Ok(())
1640 }
1641 }
1642 }
1643
1644 pub fn is_rebase_in_progress(&self) -> bool {
1646 let git_dir = self.git_repo.path().join(".git");
1648 git_dir.join("REBASE_HEAD").exists()
1649 || git_dir.join("rebase-merge").exists()
1650 || git_dir.join("rebase-apply").exists()
1651 }
1652
1653 pub fn abort_rebase(&self) -> Result<()> {
1655 tracing::debug!("Aborting rebase operation");
1656
1657 let git_dir = self.git_repo.path().join(".git");
1658
1659 if git_dir.join("REBASE_HEAD").exists() {
1661 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1662 CascadeError::Git(git2::Error::from_str(&format!(
1663 "Failed to clean rebase state: {e}"
1664 )))
1665 })?;
1666 }
1667
1668 if git_dir.join("rebase-merge").exists() {
1669 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1670 CascadeError::Git(git2::Error::from_str(&format!(
1671 "Failed to clean rebase-merge: {e}"
1672 )))
1673 })?;
1674 }
1675
1676 if git_dir.join("rebase-apply").exists() {
1677 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1678 CascadeError::Git(git2::Error::from_str(&format!(
1679 "Failed to clean rebase-apply: {e}"
1680 )))
1681 })?;
1682 }
1683
1684 tracing::debug!("Rebase aborted successfully");
1685 Ok(())
1686 }
1687
1688 pub fn continue_rebase(&self) -> Result<()> {
1690 tracing::debug!("Continuing rebase operation");
1691
1692 if self.git_repo.has_conflicts()? {
1694 return Err(CascadeError::branch(
1695 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1696 ));
1697 }
1698
1699 self.git_repo.stage_conflict_resolved_files()?;
1701
1702 tracing::debug!("Rebase continued successfully");
1703 Ok(())
1704 }
1705
1706 fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1708 let git_dir = self.git_repo.path().join(".git");
1709 Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1710 }
1711
1712 fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1714 use crate::cli::output::Output;
1715
1716 let git_dir = self.git_repo.path().join(".git");
1717
1718 Output::section("Resuming in-progress sync");
1719 println!();
1720 Output::info("Detected unfinished cherry-pick from previous sync");
1721 println!();
1722
1723 if self.git_repo.has_conflicts()? {
1725 let conflicted_files = self.git_repo.get_conflicted_files()?;
1726
1727 let result = RebaseResult {
1728 success: false,
1729 branch_mapping: HashMap::new(),
1730 conflicts: conflicted_files.clone(),
1731 new_commits: Vec::new(),
1732 error: Some(format!(
1733 "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1734 MANUAL CONFLICT RESOLUTION REQUIRED\n\
1735 =====================================\n\n\
1736 Conflicted files:\n{}\n\n\
1737 Step 1: Analyze conflicts\n\
1738 → Run: ca conflicts\n\
1739 → Shows detailed conflict analysis\n\n\
1740 Step 2: Resolve conflicts in your editor\n\
1741 → Open conflicted files and edit them\n\
1742 → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1743 → Keep the code you want\n\
1744 → Save the files\n\n\
1745 Step 3: Mark conflicts as resolved\n\
1746 → Run: git add <resolved-files>\n\
1747 → Or: git add -A (to stage all resolved files)\n\n\
1748 Step 4: Complete the sync\n\
1749 → Run: ca sync continue\n\
1750 → Cascade will complete the cherry-pick and continue\n\n\
1751 Alternative: Abort and start over\n\
1752 → Run: ca sync abort\n\
1753 → Then: ca sync (starts fresh)",
1754 conflicted_files.len(),
1755 conflicted_files
1756 .iter()
1757 .map(|f| format!(" - {}", f))
1758 .collect::<Vec<_>>()
1759 .join("\n")
1760 )),
1761 summary: "Sync paused - conflicts need resolution".to_string(),
1762 };
1763
1764 return Ok(result);
1765 }
1766
1767 Output::info("Conflicts resolved, continuing cherry-pick...");
1769
1770 self.git_repo.stage_conflict_resolved_files()?;
1772
1773 let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1775 let commit_message = if cherry_pick_msg_file.exists() {
1776 std::fs::read_to_string(&cherry_pick_msg_file)
1777 .unwrap_or_else(|_| "Resolved conflicts".to_string())
1778 } else {
1779 "Resolved conflicts".to_string()
1780 };
1781
1782 match self.git_repo.commit(&commit_message) {
1783 Ok(_new_commit_id) => {
1784 Output::success("Cherry-pick completed");
1785
1786 if git_dir.join("CHERRY_PICK_HEAD").exists() {
1788 let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1789 }
1790 if cherry_pick_msg_file.exists() {
1791 let _ = std::fs::remove_file(&cherry_pick_msg_file);
1792 }
1793
1794 println!();
1795 Output::info("Continuing with rest of stack...");
1796 println!();
1797
1798 self.rebase_with_force_push(stack)
1801 }
1802 Err(e) => {
1803 let result = RebaseResult {
1804 success: false,
1805 branch_mapping: HashMap::new(),
1806 conflicts: Vec::new(),
1807 new_commits: Vec::new(),
1808 error: Some(format!(
1809 "Failed to complete cherry-pick: {}\n\n\
1810 This usually means:\n\
1811 - Git index is locked (another process accessing repo)\n\
1812 - File permissions issue\n\
1813 - Disk space issue\n\n\
1814 Recovery:\n\
1815 1. Check if another Git operation is running\n\
1816 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1817 3. Run 'git status' to check repo state\n\
1818 4. Retry 'ca sync' after fixing the issue\n\n\
1819 Or abort and start fresh:\n\
1820 → Run: ca sync abort\n\
1821 → Then: ca sync",
1822 e
1823 )),
1824 summary: "Failed to complete cherry-pick".to_string(),
1825 };
1826
1827 Ok(result)
1828 }
1829 }
1830 }
1831}
1832
1833impl RebaseResult {
1834 pub fn get_summary(&self) -> String {
1836 if self.success {
1837 format!("✅ {}", self.summary)
1838 } else {
1839 format!(
1840 "❌ Rebase failed: {}",
1841 self.error.as_deref().unwrap_or("Unknown error")
1842 )
1843 }
1844 }
1845
1846 pub fn has_conflicts(&self) -> bool {
1848 !self.conflicts.is_empty()
1849 }
1850
1851 pub fn success_count(&self) -> usize {
1853 self.new_commits.len()
1854 }
1855}
1856
1857#[cfg(test)]
1858mod tests {
1859 use super::*;
1860 use std::path::PathBuf;
1861 use std::process::Command;
1862 use tempfile::TempDir;
1863
1864 #[allow(dead_code)]
1865 fn create_test_repo() -> (TempDir, PathBuf) {
1866 let temp_dir = TempDir::new().unwrap();
1867 let repo_path = temp_dir.path().to_path_buf();
1868
1869 Command::new("git")
1871 .args(["init"])
1872 .current_dir(&repo_path)
1873 .output()
1874 .unwrap();
1875 Command::new("git")
1876 .args(["config", "user.name", "Test"])
1877 .current_dir(&repo_path)
1878 .output()
1879 .unwrap();
1880 Command::new("git")
1881 .args(["config", "user.email", "test@test.com"])
1882 .current_dir(&repo_path)
1883 .output()
1884 .unwrap();
1885
1886 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1888 Command::new("git")
1889 .args(["add", "."])
1890 .current_dir(&repo_path)
1891 .output()
1892 .unwrap();
1893 Command::new("git")
1894 .args(["commit", "-m", "Initial"])
1895 .current_dir(&repo_path)
1896 .output()
1897 .unwrap();
1898
1899 (temp_dir, repo_path)
1900 }
1901
1902 #[test]
1903 fn test_conflict_region_creation() {
1904 let region = ConflictRegion {
1905 start: 0,
1906 end: 50,
1907 start_line: 1,
1908 end_line: 3,
1909 our_content: "function test() {\n return true;\n}".to_string(),
1910 their_content: "function test() {\n return true;\n}".to_string(),
1911 };
1912
1913 assert_eq!(region.start_line, 1);
1914 assert_eq!(region.end_line, 3);
1915 assert!(region.our_content.contains("return true"));
1916 assert!(region.their_content.contains("return true"));
1917 }
1918
1919 #[test]
1920 fn test_rebase_strategies() {
1921 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1922 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1923 }
1924
1925 #[test]
1926 fn test_rebase_options() {
1927 let options = RebaseOptions::default();
1928 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1929 assert!(!options.interactive);
1930 assert!(options.auto_resolve);
1931 assert_eq!(options.max_retries, 3);
1932 }
1933
1934 #[test]
1935 fn test_cleanup_guard_tracks_branches() {
1936 let mut guard = TempBranchCleanupGuard::new();
1937 assert!(guard.branches.is_empty());
1938
1939 guard.add_branch("test-branch-1".to_string());
1940 guard.add_branch("test-branch-2".to_string());
1941
1942 assert_eq!(guard.branches.len(), 2);
1943 assert_eq!(guard.branches[0], "test-branch-1");
1944 assert_eq!(guard.branches[1], "test-branch-2");
1945 }
1946
1947 #[test]
1948 fn test_cleanup_guard_prevents_double_cleanup() {
1949 use std::process::Command;
1950 use tempfile::TempDir;
1951
1952 let temp_dir = TempDir::new().unwrap();
1954 let repo_path = temp_dir.path();
1955
1956 Command::new("git")
1957 .args(["init"])
1958 .current_dir(repo_path)
1959 .output()
1960 .unwrap();
1961
1962 Command::new("git")
1963 .args(["config", "user.name", "Test"])
1964 .current_dir(repo_path)
1965 .output()
1966 .unwrap();
1967
1968 Command::new("git")
1969 .args(["config", "user.email", "test@test.com"])
1970 .current_dir(repo_path)
1971 .output()
1972 .unwrap();
1973
1974 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1976 Command::new("git")
1977 .args(["add", "."])
1978 .current_dir(repo_path)
1979 .output()
1980 .unwrap();
1981 Command::new("git")
1982 .args(["commit", "-m", "initial"])
1983 .current_dir(repo_path)
1984 .output()
1985 .unwrap();
1986
1987 let git_repo = GitRepository::open(repo_path).unwrap();
1988
1989 git_repo.create_branch("test-temp", None).unwrap();
1991
1992 let mut guard = TempBranchCleanupGuard::new();
1993 guard.add_branch("test-temp".to_string());
1994
1995 guard.cleanup(&git_repo);
1997 assert!(guard.cleaned);
1998
1999 guard.cleanup(&git_repo);
2001 assert!(guard.cleaned);
2002 }
2003
2004 #[test]
2005 fn test_rebase_result() {
2006 let result = RebaseResult {
2007 success: true,
2008 branch_mapping: std::collections::HashMap::new(),
2009 conflicts: vec!["abc123".to_string()],
2010 new_commits: vec!["def456".to_string()],
2011 error: None,
2012 summary: "Test summary".to_string(),
2013 };
2014
2015 assert!(result.success);
2016 assert!(result.has_conflicts());
2017 assert_eq!(result.success_count(), 1);
2018 }
2019}