1use crate::errors::{CascadeError, Result};
2use crate::git::{ConflictAnalyzer, GitRepository};
3use crate::stack::{Stack, StackManager};
4use crate::utils::spinner::{Spinner, SpinnerPrinter};
5use chrono::Utc;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use tracing::debug;
9use uuid::Uuid;
10
11#[derive(Debug, Clone)]
13enum ConflictResolution {
14 Resolved,
16 TooComplex,
18}
19
20#[derive(Debug, Clone)]
22#[allow(dead_code)]
23struct ConflictRegion {
24 start: usize,
26 end: usize,
28 start_line: usize,
30 end_line: usize,
32 our_content: String,
34 their_content: String,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
40pub enum RebaseStrategy {
41 ForcePush,
44 Interactive,
46}
47
48#[derive(Debug, Clone)]
50pub struct RebaseOptions {
51 pub strategy: RebaseStrategy,
53 pub interactive: bool,
55 pub target_base: Option<String>,
57 pub preserve_merges: bool,
59 pub auto_resolve: bool,
61 pub max_retries: usize,
63 pub skip_pull: Option<bool>,
65 pub original_working_branch: Option<String>,
68 pub progress_printer: Option<SpinnerPrinter>,
70}
71
72#[derive(Debug)]
74pub struct RebaseResult {
75 pub success: bool,
77 pub branch_mapping: HashMap<String, String>,
79 pub conflicts: Vec<String>,
81 pub new_commits: Vec<String>,
83 pub error: Option<String>,
85 pub summary: String,
87}
88
89#[allow(dead_code)]
95struct TempBranchCleanupGuard {
96 branches: Vec<String>,
97 cleaned: bool,
98}
99
100#[allow(dead_code)]
101impl TempBranchCleanupGuard {
102 fn new() -> Self {
103 Self {
104 branches: Vec::new(),
105 cleaned: false,
106 }
107 }
108
109 fn add_branch(&mut self, branch: String) {
110 self.branches.push(branch);
111 }
112
113 fn cleanup(&mut self, git_repo: &GitRepository) {
115 if self.cleaned || self.branches.is_empty() {
116 return;
117 }
118
119 tracing::debug!("Cleaning up {} temporary branches", self.branches.len());
120 for branch in &self.branches {
121 if let Err(e) = git_repo.delete_branch_unsafe(branch) {
122 tracing::debug!("Failed to delete temp branch {}: {}", branch, e);
123 }
125 }
126 self.cleaned = true;
127 }
128}
129
130impl Drop for TempBranchCleanupGuard {
131 fn drop(&mut self) {
132 if !self.cleaned && !self.branches.is_empty() {
133 tracing::warn!(
136 "{} temporary branches were not cleaned up: {}",
137 self.branches.len(),
138 self.branches.join(", ")
139 );
140 tracing::warn!("Run 'ca cleanup' to remove orphaned temporary branches");
141 }
142 }
143}
144
145pub struct RebaseManager {
147 stack_manager: StackManager,
148 git_repo: GitRepository,
149 options: RebaseOptions,
150 conflict_analyzer: ConflictAnalyzer,
151}
152
153impl Default for RebaseOptions {
154 fn default() -> Self {
155 Self {
156 strategy: RebaseStrategy::ForcePush,
157 interactive: false,
158 target_base: None,
159 preserve_merges: true,
160 auto_resolve: true,
161 max_retries: 3,
162 skip_pull: None,
163 original_working_branch: None,
164 progress_printer: None,
165 }
166 }
167}
168
169impl RebaseManager {
170 pub fn new(
172 stack_manager: StackManager,
173 git_repo: GitRepository,
174 options: RebaseOptions,
175 ) -> Self {
176 Self {
177 stack_manager,
178 git_repo,
179 options,
180 conflict_analyzer: ConflictAnalyzer::new(),
181 }
182 }
183
184 pub fn into_stack_manager(self) -> StackManager {
186 self.stack_manager
187 }
188
189 pub fn rebase_stack(&mut self, stack_id: &Uuid) -> Result<RebaseResult> {
191 debug!("Starting rebase for stack {}", stack_id);
192
193 let stack = self
194 .stack_manager
195 .get_stack(stack_id)
196 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?
197 .clone();
198
199 match self.options.strategy {
200 RebaseStrategy::ForcePush => self.rebase_with_force_push(&stack),
201 RebaseStrategy::Interactive => self.rebase_interactive(&stack),
202 }
203 }
204
205 fn rebase_with_force_push(&mut self, stack: &Stack) -> Result<RebaseResult> {
209 use crate::cli::output::Output;
210
211 if self.has_in_progress_cherry_pick()? {
213 return self.handle_in_progress_cherry_pick(stack);
214 }
215
216 Output::section(format!("Rebasing stack: {}", stack.name));
218 Output::sub_item(format!("Base branch: {}", stack.base_branch));
219 Output::sub_item(format!("Entries: {}", stack.entries.len()));
220
221 let mut result = RebaseResult {
222 success: true,
223 branch_mapping: HashMap::new(),
224 conflicts: Vec::new(),
225 new_commits: Vec::new(),
226 error: None,
227 summary: String::new(),
228 };
229
230 let target_base = self
231 .options
232 .target_base
233 .as_ref()
234 .unwrap_or(&stack.base_branch)
235 .clone(); let original_branch = self
241 .options
242 .original_working_branch
243 .clone()
244 .or_else(|| self.git_repo.get_current_branch().ok());
245
246 let original_branch_for_cleanup = original_branch.clone();
248
249 if let Some(ref orig) = original_branch {
252 if orig == &target_base {
253 debug!(
254 "Original working branch is base branch '{}' - will skip working branch update",
255 orig
256 );
257 }
258 }
259
260 if !self.options.skip_pull.unwrap_or(false) {
263 if let Err(e) = self.pull_latest_changes(&target_base) {
264 Output::warning(format!("Could not pull latest changes: {}", e));
265 }
266 }
267
268 if let Err(e) = self.git_repo.reset_to_head() {
270 Output::warning(format!("Could not reset working directory: {}", e));
271 }
272
273 let mut current_base = target_base.clone();
274 let entry_count = stack.entries.len();
275 let printer = self.options.progress_printer.clone();
276 let print_line = |line: &str| {
277 if let Some(ref printer) = printer {
278 printer.println(line);
279 } else {
280 println!("{}", line);
281 }
282 };
283 let print_blank = || {
284 if let Some(ref printer) = printer {
285 printer.println("");
286 } else {
287 println!();
288 }
289 };
290 let mut temp_branches: Vec<String> = Vec::new(); let mut branches_to_push: Vec<(String, String, usize)> = Vec::new(); if entry_count == 0 {
295 print_blank();
296 Output::info("Stack has no entries yet");
297 Output::tip("Use 'ca push' to add commits to this stack");
298
299 result.summary = "Stack is empty".to_string();
300
301 print_blank();
303 Output::success(&result.summary);
304
305 self.stack_manager.save_to_disk()?;
307 return Ok(result);
308 }
309
310 let all_up_to_date = stack.entries.iter().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 print_blank();
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 for (index, entry) in stack.entries.iter().enumerate() {
329 let original_branch = &entry.branch;
330
331 if self
334 .git_repo
335 .is_commit_based_on(&entry.commit_hash, ¤t_base)
336 .unwrap_or(false)
337 {
338 tracing::debug!(
339 "Entry '{}' is already correctly based on '{}', skipping rebase",
340 original_branch,
341 current_base
342 );
343
344 if let Some(pr_num) = &entry.pull_request_id {
346 let tree_char = if index + 1 == entry_count {
347 "└─"
348 } else {
349 "├─"
350 };
351 print_line(&format!(
352 " {} {} (PR #{})",
353 tree_char, original_branch, pr_num
354 ));
355 branches_to_push.push((original_branch.clone(), pr_num.clone(), index));
356 }
357
358 result
359 .branch_mapping
360 .insert(original_branch.clone(), original_branch.clone());
361
362 current_base = original_branch.clone();
364 continue;
365 }
366
367 let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
370 temp_branches.push(temp_branch.clone()); if let Err(e) = self
374 .git_repo
375 .create_branch(&temp_branch, Some(¤t_base))
376 {
377 if let Some(ref orig) = original_branch_for_cleanup {
379 let _ = self.git_repo.checkout_branch_unsafe(orig);
380 }
381 return Err(e);
382 }
383
384 if let Err(e) = self.git_repo.checkout_branch_silent(&temp_branch) {
385 if let Some(ref orig) = original_branch_for_cleanup {
387 let _ = self.git_repo.checkout_branch_unsafe(orig);
388 }
389 return Err(e);
390 }
391
392 match self.cherry_pick_commit(&entry.commit_hash) {
394 Ok(new_commit_hash) => {
395 result.new_commits.push(new_commit_hash.clone());
396
397 let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
399
400 self.git_repo
403 .update_branch_to_commit(original_branch, &rebased_commit_id)?;
404
405 if let Some(pr_num) = &entry.pull_request_id {
407 let tree_char = if index + 1 == entry_count {
408 "└─"
409 } else {
410 "├─"
411 };
412 print_line(&format!(
413 " {} {} (PR #{})",
414 tree_char, original_branch, pr_num
415 ));
416 branches_to_push.push((original_branch.clone(), pr_num.clone(), index));
417 }
418
419 result
420 .branch_mapping
421 .insert(original_branch.clone(), original_branch.clone());
422
423 self.update_stack_entry(
425 stack.id,
426 &entry.id,
427 original_branch,
428 &rebased_commit_id,
429 )?;
430
431 current_base = original_branch.clone();
433 }
434 Err(e) => {
435 result.conflicts.push(entry.commit_hash.clone());
436
437 if !self.options.auto_resolve {
438 print_blank();
439 Output::error(e.to_string());
440 result.success = false;
441 result.error = Some(format!(
442 "Conflict in {}: {}\n\n\
443 MANUAL CONFLICT RESOLUTION REQUIRED\n\
444 =====================================\n\n\
445 Step 1: Analyze conflicts\n\
446 → Run: ca conflicts\n\
447 → This shows which conflicts are in which files\n\n\
448 Step 2: Resolve conflicts in your editor\n\
449 → Open conflicted files and edit them\n\
450 → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
451 → Keep the code you want\n\
452 → Save the files\n\n\
453 Step 3: Mark conflicts as resolved\n\
454 → Run: git add <resolved-files>\n\
455 → Or: git add -A (to stage all resolved files)\n\n\
456 Step 4: Complete the sync\n\
457 → Run: ca sync\n\
458 → Cascade will detect resolved conflicts and continue\n\n\
459 Alternative: Abort and start over\n\
460 → Run: git cherry-pick --abort\n\
461 → Then: ca sync (starts fresh)\n\n\
462 TIP: Enable auto-resolution for simple conflicts:\n\
463 → Run: ca sync --auto-resolve\n\
464 → Only complex conflicts will require manual resolution",
465 entry.commit_hash, e
466 ));
467 break;
468 }
469
470 match self.auto_resolve_conflicts(&entry.commit_hash) {
472 Ok(fully_resolved) => {
473 if !fully_resolved {
474 result.success = false;
475 result.error = Some(format!(
476 "Conflicts in commit {}\n\n\
477 To resolve:\n\
478 1. Fix conflicts in your editor\n\
479 2. Run: ca sync --continue\n\n\
480 Or abort:\n\
481 → Run: git cherry-pick --abort",
482 &entry.commit_hash[..8]
483 ));
484 break;
485 }
486
487 let commit_message =
489 format!("Auto-resolved conflicts in {}", &entry.commit_hash[..8]);
490
491 debug!("Checking staged files before commit");
493 let staged_files = self.git_repo.get_staged_files()?;
494
495 if staged_files.is_empty() {
496 result.success = false;
500 result.error = Some(format!(
501 "CRITICAL BUG DETECTED: Cherry-pick failed but no files were staged!\n\n\
502 This indicates a Git state issue after cherry-pick failure.\n\n\
503 RECOVERY STEPS:\n\
504 ================\n\n\
505 Step 1: Check Git status\n\
506 → Run: git status\n\
507 → Check if there are any changes in working directory\n\n\
508 Step 2: Check for conflicts manually\n\
509 → Run: git diff\n\
510 → Look for conflict markers (<<<<<<, ======, >>>>>>)\n\n\
511 Step 3: Abort the cherry-pick\n\
512 → Run: git cherry-pick --abort\n\n\
513 Step 4: Report this bug\n\
514 → This is a known issue we're investigating\n\
515 → Cherry-pick failed for commit {}\n\
516 → But Git reported no conflicts and no staged files\n\n\
517 Step 5: Try manual resolution\n\
518 → Run: ca sync --no-auto-resolve\n\
519 → Manually resolve conflicts as they appear",
520 &entry.commit_hash[..8]
521 ));
522 tracing::error!("CRITICAL - No files staged after auto-resolve!");
523 break;
524 }
525
526 debug!("{} files staged", staged_files.len());
527
528 match self.git_repo.commit(&commit_message) {
529 Ok(new_commit_id) => {
530 debug!(
531 "Created commit {} with message '{}'",
532 &new_commit_id[..8],
533 commit_message
534 );
535
536 Output::success("Auto-resolved conflicts");
537 result.new_commits.push(new_commit_id.clone());
538 let rebased_commit_id = new_commit_id;
539
540 self.git_repo.update_branch_to_commit(
542 original_branch,
543 &rebased_commit_id,
544 )?;
545
546 if let Some(pr_num) = &entry.pull_request_id {
548 let tree_char = if index + 1 == entry_count {
549 "└─"
550 } else {
551 "├─"
552 };
553 println!(
554 " {} {} (PR #{})",
555 tree_char, original_branch, pr_num
556 );
557 branches_to_push.push((
558 original_branch.clone(),
559 pr_num.clone(),
560 index,
561 ));
562 }
563
564 result
565 .branch_mapping
566 .insert(original_branch.clone(), original_branch.clone());
567
568 self.update_stack_entry(
570 stack.id,
571 &entry.id,
572 original_branch,
573 &rebased_commit_id,
574 )?;
575
576 current_base = original_branch.clone();
578 }
579 Err(commit_err) => {
580 result.success = false;
581 result.error = Some(format!(
582 "Could not commit auto-resolved conflicts: {}\n\n\
583 This usually means:\n\
584 - Git index is locked (another process accessing repo)\n\
585 - File permissions issue\n\
586 - Disk space issue\n\n\
587 Recovery:\n\
588 1. Check if another Git operation is running\n\
589 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
590 3. Run 'git status' to check repo state\n\
591 4. Retry 'ca sync' after fixing the issue",
592 commit_err
593 ));
594 break;
595 }
596 }
597 }
598 Err(resolve_err) => {
599 result.success = false;
600 result.error = Some(format!(
601 "Could not resolve conflicts: {}\n\n\
602 Recovery:\n\
603 1. Check repo state: 'git status'\n\
604 2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
605 3. Remove any lock files: 'rm -f .git/index.lock'\n\
606 4. Retry 'ca sync'",
607 resolve_err
608 ));
609 break;
610 }
611 }
612 }
613 }
614 }
615
616 if !temp_branches.is_empty() {
619 if let Err(e) = self.git_repo.checkout_branch_unsafe(&target_base) {
622 debug!("Could not checkout base for cleanup: {}", e);
623 } else {
626 for temp_branch in &temp_branches {
628 if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
629 debug!("Could not delete temp branch {}: {}", temp_branch, e);
630 }
631 }
632 }
633 }
634
635 let pushed_count = branches_to_push.len();
638 let skipped_count = entry_count - pushed_count;
639 let mut successful_pushes = 0; if !branches_to_push.is_empty() {
642 print_blank();
643
644 let branch_word = if pushed_count == 1 {
646 "branch"
647 } else {
648 "branches"
649 };
650 let push_spinner = Spinner::new_with_output_below(format!(
651 "Pushing {} updated stack {}",
652 pushed_count, branch_word
653 ));
654
655 let mut push_results = Vec::new();
657 for (branch_name, _pr_num, _index) in branches_to_push.iter() {
658 let result = self.git_repo.force_push_single_branch_auto(branch_name);
659 push_results.push((branch_name.clone(), result));
660 }
661
662 push_spinner.stop();
664
665 let mut failed_pushes = 0;
667 for (index, (branch_name, result)) in push_results.iter().enumerate() {
668 match result {
669 Ok(_) => {
670 debug!("Pushed {} successfully", branch_name);
671 successful_pushes += 1;
672 println!(
673 " ✓ Pushed {} ({}/{})",
674 branch_name,
675 index + 1,
676 pushed_count
677 );
678 }
679 Err(e) => {
680 failed_pushes += 1;
681 Output::warning(format!("Could not push '{}': {}", branch_name, e));
682 }
683 }
684 }
685
686 if failed_pushes > 0 {
688 println!(); Output::warning(format!(
690 "{} branch(es) failed to push to remote",
691 failed_pushes
692 ));
693 Output::tip("To retry failed pushes, run: ca sync");
694 }
695 }
696
697 if let Some(ref orig_branch) = original_branch {
700 if orig_branch != &target_base {
702 if let Some(last_entry) = stack.entries.last() {
704 let top_branch = &last_entry.branch;
705
706 if let (Ok(working_head), Ok(top_commit)) = (
709 self.git_repo.get_branch_head(orig_branch),
710 self.git_repo.get_branch_head(top_branch),
711 ) {
712 if working_head != top_commit {
714 if let Ok(commits) = self
716 .git_repo
717 .get_commits_between(&top_commit, &working_head)
718 {
719 if !commits.is_empty() {
720 let stack_messages: Vec<String> = stack
723 .entries
724 .iter()
725 .map(|e| e.message.trim().to_string())
726 .collect();
727
728 let all_match_stack = commits.iter().all(|commit| {
729 if let Some(msg) = commit.summary() {
730 stack_messages
731 .iter()
732 .any(|stack_msg| stack_msg == msg.trim())
733 } else {
734 false
735 }
736 });
737
738 if all_match_stack && commits.len() == stack.entries.len() {
739 debug!(
742 "Working branch has old pre-rebase commits (matching stack messages) - safe to update"
743 );
744 } else {
745 Output::error(format!(
747 "Cannot sync: Working branch '{}' has {} commit(s) not in the stack",
748 orig_branch,
749 commits.len()
750 ));
751 println!();
752 Output::sub_item(
753 "These commits would be lost if we proceed:",
754 );
755 for (i, commit) in commits.iter().take(5).enumerate() {
756 let message =
757 commit.summary().unwrap_or("(no message)");
758 Output::sub_item(format!(
759 " {}. {} - {}",
760 i + 1,
761 &commit.id().to_string()[..8],
762 message
763 ));
764 }
765 if commits.len() > 5 {
766 Output::sub_item(format!(
767 " ... and {} more",
768 commits.len() - 5
769 ));
770 }
771 println!();
772 Output::tip("Add these commits to the stack first:");
773 Output::bullet("Run: ca stack push");
774 Output::bullet("Then run: ca sync");
775 println!();
776
777 if let Some(ref orig) = original_branch_for_cleanup {
779 let _ = self.git_repo.checkout_branch_unsafe(orig);
780 }
781
782 return Err(CascadeError::validation(
783 format!(
784 "Working branch '{}' has {} untracked commit(s). Add them to the stack with 'ca stack push' before syncing.",
785 orig_branch, commits.len()
786 )
787 ));
788 }
789 }
790 }
791 }
792
793 debug!(
795 "Updating working branch '{}' to match top of stack ({})",
796 orig_branch,
797 &top_commit[..8]
798 );
799
800 if let Err(e) = self
801 .git_repo
802 .update_branch_to_commit(orig_branch, &top_commit)
803 {
804 Output::warning(format!(
805 "Could not update working branch '{}' to top of stack: {}",
806 orig_branch, e
807 ));
808 }
809 }
810 }
811
812 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
815 debug!(
816 "Could not return to original branch '{}': {}",
817 orig_branch, e
818 );
819 }
821 } else {
822 debug!(
825 "Skipping working branch update - user was on base branch '{}'",
826 orig_branch
827 );
828 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
829 debug!("Could not return to base branch '{}': {}", orig_branch, e);
830 }
831 }
832 }
833
834 result.summary = if successful_pushes > 0 {
837 let pr_plural = if successful_pushes == 1 { "" } else { "s" };
838 let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
839
840 if skipped_count > 0 {
841 format!(
842 "{} {} rebased ({} PR{} updated, {} not yet submitted)",
843 entry_count, entry_plural, successful_pushes, pr_plural, skipped_count
844 )
845 } else {
846 format!(
847 "{} {} rebased ({} PR{} updated)",
848 entry_count, entry_plural, successful_pushes, pr_plural
849 )
850 }
851 } else if pushed_count > 0 {
852 let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
854 format!(
855 "{} {} rebased (pushes failed - retry with 'ca sync')",
856 entry_count, entry_plural
857 )
858 } else {
859 let plural = if entry_count == 1 { "entry" } else { "entries" };
860 format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
861 };
862
863 print_blank();
865 if result.success {
866 Output::success(&result.summary);
867 } else {
868 let error_msg = result
870 .error
871 .as_deref()
872 .unwrap_or("Rebase failed for unknown reason");
873 Output::error(error_msg);
874 }
875
876 self.stack_manager.save_to_disk()?;
878
879 if !result.success {
882 if let Some(ref orig_branch) = original_branch {
884 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
885 debug!(
886 "Could not return to original branch '{}' after error: {}",
887 orig_branch, e
888 );
889 }
890 }
891
892 let detailed_error = result.error.as_deref().unwrap_or("Rebase failed");
894 return Err(CascadeError::Branch(detailed_error.to_string()));
895 }
896
897 Ok(result)
898 }
899
900 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
902 tracing::debug!("Starting interactive rebase for stack '{}'", stack.name);
903
904 let mut result = RebaseResult {
905 success: true,
906 branch_mapping: HashMap::new(),
907 conflicts: Vec::new(),
908 new_commits: Vec::new(),
909 error: None,
910 summary: String::new(),
911 };
912
913 println!("Interactive Rebase for Stack: {}", stack.name);
914 println!(" Base branch: {}", stack.base_branch);
915 println!(" Entries: {}", stack.entries.len());
916
917 if self.options.interactive {
918 println!("\nChoose action for each commit:");
919 println!(" (p)ick - apply the commit");
920 println!(" (s)kip - skip this commit");
921 println!(" (e)dit - edit the commit message");
922 println!(" (q)uit - abort the rebase");
923 }
924
925 for entry in &stack.entries {
928 println!(
929 " {} {} - {}",
930 entry.short_hash(),
931 entry.branch,
932 entry.short_message(50)
933 );
934
935 match self.cherry_pick_commit(&entry.commit_hash) {
937 Ok(new_commit) => result.new_commits.push(new_commit),
938 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
939 }
940 }
941
942 result.summary = format!(
943 "Interactive rebase processed {} commits",
944 stack.entries.len()
945 );
946 Ok(result)
947 }
948
949 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
951 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
953
954 if let Ok(staged_files) = self.git_repo.get_staged_files() {
956 if !staged_files.is_empty() {
957 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
959 match self.git_repo.commit_staged_changes(&cleanup_message) {
960 Ok(Some(_)) => {
961 debug!(
962 "Committed {} leftover staged files after cherry-pick",
963 staged_files.len()
964 );
965 }
966 Ok(None) => {
967 debug!("Staged files were cleared before commit");
969 }
970 Err(e) => {
971 tracing::warn!(
973 "Failed to commit {} staged files after cherry-pick: {}. \
974 User may see checkout warning with staged changes.",
975 staged_files.len(),
976 e
977 );
978 }
980 }
981 }
982 }
983
984 Ok(new_commit_hash)
985 }
986
987 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
989 debug!("Starting auto-resolve for commit {}", commit_hash);
990
991 let has_conflicts = self.git_repo.has_conflicts()?;
993 debug!("has_conflicts() = {}", has_conflicts);
994
995 let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
997 let cherry_pick_in_progress = cherry_pick_head.exists();
998
999 if !has_conflicts {
1000 debug!("No conflicts detected by Git index");
1001
1002 if cherry_pick_in_progress {
1004 tracing::debug!(
1005 "CHERRY_PICK_HEAD exists but no conflicts in index - aborting cherry-pick"
1006 );
1007
1008 let _ = std::process::Command::new("git")
1010 .args(["cherry-pick", "--abort"])
1011 .current_dir(self.git_repo.path())
1012 .output();
1013
1014 return Err(CascadeError::Branch(format!(
1015 "Cherry-pick failed for {} but Git index shows no conflicts. \
1016 This usually means the cherry-pick was aborted or failed in an unexpected way. \
1017 Please try manual resolution.",
1018 &commit_hash[..8]
1019 )));
1020 }
1021
1022 return Ok(true);
1023 }
1024
1025 let conflicted_files = self.git_repo.get_conflicted_files()?;
1026
1027 if conflicted_files.is_empty() {
1028 debug!("Conflicted files list is empty");
1029 return Ok(true);
1030 }
1031
1032 debug!(
1033 "Found conflicts in {} files: {:?}",
1034 conflicted_files.len(),
1035 conflicted_files
1036 );
1037
1038 let analysis = self
1040 .conflict_analyzer
1041 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
1042
1043 debug!(
1044 "Conflict analysis: {} total conflicts, {} auto-resolvable",
1045 analysis.total_conflicts, analysis.auto_resolvable_count
1046 );
1047
1048 for recommendation in &analysis.recommendations {
1050 debug!("{}", recommendation);
1051 }
1052
1053 let mut resolved_count = 0;
1054 let mut resolved_files = Vec::new(); let mut failed_files = Vec::new();
1056
1057 for file_analysis in &analysis.files {
1058 debug!(
1059 "Processing file: {} (auto_resolvable: {}, conflicts: {})",
1060 file_analysis.file_path,
1061 file_analysis.auto_resolvable,
1062 file_analysis.conflicts.len()
1063 );
1064
1065 if file_analysis.auto_resolvable {
1066 match self.resolve_file_conflicts_enhanced(
1067 &file_analysis.file_path,
1068 &file_analysis.conflicts,
1069 ) {
1070 Ok(ConflictResolution::Resolved) => {
1071 resolved_count += 1;
1072 resolved_files.push(file_analysis.file_path.clone());
1073 debug!("Successfully resolved {}", file_analysis.file_path);
1074 }
1075 Ok(ConflictResolution::TooComplex) => {
1076 debug!(
1077 "{} too complex for auto-resolution",
1078 file_analysis.file_path
1079 );
1080 failed_files.push(file_analysis.file_path.clone());
1081 }
1082 Err(e) => {
1083 debug!("Failed to resolve {}: {}", file_analysis.file_path, e);
1084 failed_files.push(file_analysis.file_path.clone());
1085 }
1086 }
1087 } else {
1088 failed_files.push(file_analysis.file_path.clone());
1089 debug!(
1090 "{} requires manual resolution ({} conflicts)",
1091 file_analysis.file_path,
1092 file_analysis.conflicts.len()
1093 );
1094 }
1095 }
1096
1097 if resolved_count > 0 {
1098 debug!(
1099 "Resolved {}/{} files",
1100 resolved_count,
1101 conflicted_files.len()
1102 );
1103 debug!("Resolved files: {:?}", resolved_files);
1104
1105 let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
1108 debug!("Staging {} files", file_paths.len());
1109 self.git_repo.stage_files(&file_paths)?;
1110 debug!("Files staged successfully");
1111 } else {
1112 debug!("No files were resolved (resolved_count = 0)");
1113 }
1114
1115 let all_resolved = failed_files.is_empty();
1117
1118 debug!(
1119 "all_resolved = {}, failed_files = {:?}",
1120 all_resolved, failed_files
1121 );
1122
1123 if !all_resolved {
1124 debug!("{} files still need manual resolution", failed_files.len());
1125 }
1126
1127 debug!("Returning all_resolved = {}", all_resolved);
1128 Ok(all_resolved)
1129 }
1130
1131 fn resolve_file_conflicts_enhanced(
1133 &self,
1134 file_path: &str,
1135 conflicts: &[crate::git::ConflictRegion],
1136 ) -> Result<ConflictResolution> {
1137 let repo_path = self.git_repo.path();
1138 let full_path = repo_path.join(file_path);
1139
1140 let mut content = std::fs::read_to_string(&full_path)
1142 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
1143
1144 if conflicts.is_empty() {
1145 return Ok(ConflictResolution::Resolved);
1146 }
1147
1148 tracing::debug!(
1149 "Resolving {} conflicts in {} using enhanced analysis",
1150 conflicts.len(),
1151 file_path
1152 );
1153
1154 let mut any_resolved = false;
1155
1156 for conflict in conflicts.iter().rev() {
1158 match self.resolve_single_conflict_enhanced(conflict) {
1159 Ok(Some(resolution)) => {
1160 let before = &content[..conflict.start_pos];
1162 let after = &content[conflict.end_pos..];
1163 content = format!("{before}{resolution}{after}");
1164 any_resolved = true;
1165 debug!(
1166 "✅ Resolved {} conflict at lines {}-{} in {}",
1167 format!("{:?}", conflict.conflict_type).to_lowercase(),
1168 conflict.start_line,
1169 conflict.end_line,
1170 file_path
1171 );
1172 }
1173 Ok(None) => {
1174 debug!(
1175 "⚠️ {} conflict at lines {}-{} in {} requires manual resolution",
1176 format!("{:?}", conflict.conflict_type).to_lowercase(),
1177 conflict.start_line,
1178 conflict.end_line,
1179 file_path
1180 );
1181 return Ok(ConflictResolution::TooComplex);
1182 }
1183 Err(e) => {
1184 debug!("❌ Failed to resolve conflict in {}: {}", file_path, e);
1185 return Ok(ConflictResolution::TooComplex);
1186 }
1187 }
1188 }
1189
1190 if any_resolved {
1191 let remaining_conflicts = self.parse_conflict_markers(&content)?;
1193
1194 if remaining_conflicts.is_empty() {
1195 debug!(
1196 "All conflicts resolved in {}, content length: {} bytes",
1197 file_path,
1198 content.len()
1199 );
1200
1201 if content.trim().is_empty() {
1203 tracing::warn!(
1204 "SAFETY CHECK: Resolved content for {} is empty! Aborting auto-resolution.",
1205 file_path
1206 );
1207 return Ok(ConflictResolution::TooComplex);
1208 }
1209
1210 let backup_path = full_path.with_extension("cascade-backup");
1212 if let Ok(original_content) = std::fs::read_to_string(&full_path) {
1213 debug!(
1214 "Backup for {} (original: {} bytes, resolved: {} bytes)",
1215 file_path,
1216 original_content.len(),
1217 content.len()
1218 );
1219 let _ = std::fs::write(&backup_path, original_content);
1220 }
1221
1222 crate::utils::atomic_file::write_string(&full_path, &content)?;
1224
1225 debug!("Wrote {} bytes to {}", content.len(), file_path);
1226 return Ok(ConflictResolution::Resolved);
1227 } else {
1228 tracing::debug!(
1229 "Partially resolved conflicts in {} ({} remaining)",
1230 file_path,
1231 remaining_conflicts.len()
1232 );
1233 }
1234 }
1235
1236 Ok(ConflictResolution::TooComplex)
1237 }
1238
1239 #[allow(dead_code)]
1241 fn count_whitespace_consistency(content: &str) -> usize {
1242 let mut inconsistencies = 0;
1243 let lines: Vec<&str> = content.lines().collect();
1244
1245 for line in &lines {
1246 if line.contains('\t') && line.contains(' ') {
1248 inconsistencies += 1;
1249 }
1250 }
1251
1252 lines.len().saturating_sub(inconsistencies)
1254 }
1255
1256 fn resolve_single_conflict_enhanced(
1258 &self,
1259 conflict: &crate::git::ConflictRegion,
1260 ) -> Result<Option<String>> {
1261 debug!(
1262 "Resolving {} conflict in {} (lines {}-{})",
1263 format!("{:?}", conflict.conflict_type).to_lowercase(),
1264 conflict.file_path,
1265 conflict.start_line,
1266 conflict.end_line
1267 );
1268
1269 use crate::git::ConflictType;
1270
1271 match conflict.conflict_type {
1272 ConflictType::Whitespace => {
1273 let our_normalized = conflict
1276 .our_content
1277 .split_whitespace()
1278 .collect::<Vec<_>>()
1279 .join(" ");
1280 let their_normalized = conflict
1281 .their_content
1282 .split_whitespace()
1283 .collect::<Vec<_>>()
1284 .join(" ");
1285
1286 if our_normalized == their_normalized {
1287 Ok(Some(conflict.their_content.clone()))
1292 } else {
1293 debug!(
1295 "Whitespace conflict has content differences - requires manual resolution"
1296 );
1297 Ok(None)
1298 }
1299 }
1300 ConflictType::LineEnding => {
1301 let normalized = conflict
1303 .our_content
1304 .replace("\r\n", "\n")
1305 .replace('\r', "\n");
1306 Ok(Some(normalized))
1307 }
1308 ConflictType::PureAddition => {
1309 if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1313 Ok(Some(conflict.their_content.clone()))
1315 } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1316 Ok(Some(String::new()))
1318 } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1319 Ok(Some(String::new()))
1321 } else {
1322 debug!(
1328 "PureAddition conflict has content on both sides - requires manual resolution"
1329 );
1330 Ok(None)
1331 }
1332 }
1333 ConflictType::ImportMerge => {
1334 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1339 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1340
1341 let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1343 let trimmed = line.trim();
1344 trimmed.starts_with("import ")
1345 || trimmed.starts_with("from ")
1346 || trimmed.starts_with("use ")
1347 || trimmed.starts_with("#include")
1348 || trimmed.is_empty()
1349 });
1350
1351 if !all_simple {
1352 debug!("ImportMerge contains non-import lines - requires manual resolution");
1353 return Ok(None);
1354 }
1355
1356 let mut all_imports: Vec<&str> = our_lines
1358 .into_iter()
1359 .chain(their_lines)
1360 .filter(|line| !line.trim().is_empty())
1361 .collect();
1362 all_imports.sort();
1363 all_imports.dedup();
1364 Ok(Some(all_imports.join("\n")))
1365 }
1366 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1367 Ok(None)
1369 }
1370 }
1371 }
1372
1373 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1375 let lines: Vec<&str> = content.lines().collect();
1376 let mut conflicts = Vec::new();
1377 let mut i = 0;
1378
1379 while i < lines.len() {
1380 if lines[i].starts_with("<<<<<<<") {
1381 let start_line = i + 1;
1383 let mut separator_line = None;
1384 let mut end_line = None;
1385
1386 for (j, line) in lines.iter().enumerate().skip(i + 1) {
1388 if line.starts_with("=======") {
1389 separator_line = Some(j + 1);
1390 } else if line.starts_with(">>>>>>>") {
1391 end_line = Some(j + 1);
1392 break;
1393 }
1394 }
1395
1396 if let (Some(sep), Some(end)) = (separator_line, end_line) {
1397 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1399 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1400
1401 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1402 let their_content = lines[sep..(end - 1)].join("\n");
1403
1404 conflicts.push(ConflictRegion {
1405 start: start_pos,
1406 end: end_pos,
1407 start_line,
1408 end_line: end,
1409 our_content,
1410 their_content,
1411 });
1412
1413 i = end;
1414 } else {
1415 i += 1;
1416 }
1417 } else {
1418 i += 1;
1419 }
1420 }
1421
1422 Ok(conflicts)
1423 }
1424
1425 fn update_stack_entry(
1428 &mut self,
1429 stack_id: Uuid,
1430 entry_id: &Uuid,
1431 _new_branch: &str,
1432 new_commit_hash: &str,
1433 ) -> Result<()> {
1434 debug!(
1435 "Updating entry {} in stack {} with new commit {}",
1436 entry_id, stack_id, new_commit_hash
1437 );
1438
1439 let stack = self
1441 .stack_manager
1442 .get_stack_mut(&stack_id)
1443 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1444
1445 let entry_exists = stack.entries.iter().any(|e| e.id == *entry_id);
1447
1448 if entry_exists {
1449 let old_hash = stack
1450 .entries
1451 .iter()
1452 .find(|e| e.id == *entry_id)
1453 .map(|e| e.commit_hash.clone())
1454 .unwrap();
1455
1456 debug!(
1457 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch)",
1458 entry_id, old_hash, new_commit_hash
1459 );
1460
1461 stack
1464 .update_entry_commit_hash(entry_id, new_commit_hash.to_string())
1465 .map_err(CascadeError::config)?;
1466
1467 debug!(
1470 "Successfully updated entry {} in stack {}",
1471 entry_id, stack_id
1472 );
1473 Ok(())
1474 } else {
1475 Err(CascadeError::config(format!(
1476 "Entry {entry_id} not found in stack {stack_id}"
1477 )))
1478 }
1479 }
1480
1481 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1483 tracing::debug!("Pulling latest changes for branch {}", branch);
1484
1485 match self.git_repo.fetch() {
1487 Ok(_) => {
1488 debug!("Fetch successful");
1489 match self.git_repo.pull(branch) {
1491 Ok(_) => {
1492 tracing::debug!("Pull completed successfully for {}", branch);
1493 Ok(())
1494 }
1495 Err(e) => {
1496 tracing::debug!("Pull failed for {}: {}", branch, e);
1497 Ok(())
1499 }
1500 }
1501 }
1502 Err(e) => {
1503 tracing::debug!("Fetch failed: {}", e);
1504 Ok(())
1506 }
1507 }
1508 }
1509
1510 pub fn is_rebase_in_progress(&self) -> bool {
1512 let git_dir = self.git_repo.path().join(".git");
1514 git_dir.join("REBASE_HEAD").exists()
1515 || git_dir.join("rebase-merge").exists()
1516 || git_dir.join("rebase-apply").exists()
1517 }
1518
1519 pub fn abort_rebase(&self) -> Result<()> {
1521 tracing::debug!("Aborting rebase operation");
1522
1523 let git_dir = self.git_repo.path().join(".git");
1524
1525 if git_dir.join("REBASE_HEAD").exists() {
1527 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1528 CascadeError::Git(git2::Error::from_str(&format!(
1529 "Failed to clean rebase state: {e}"
1530 )))
1531 })?;
1532 }
1533
1534 if git_dir.join("rebase-merge").exists() {
1535 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1536 CascadeError::Git(git2::Error::from_str(&format!(
1537 "Failed to clean rebase-merge: {e}"
1538 )))
1539 })?;
1540 }
1541
1542 if git_dir.join("rebase-apply").exists() {
1543 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1544 CascadeError::Git(git2::Error::from_str(&format!(
1545 "Failed to clean rebase-apply: {e}"
1546 )))
1547 })?;
1548 }
1549
1550 tracing::debug!("Rebase aborted successfully");
1551 Ok(())
1552 }
1553
1554 pub fn continue_rebase(&self) -> Result<()> {
1556 tracing::debug!("Continuing rebase operation");
1557
1558 if self.git_repo.has_conflicts()? {
1560 return Err(CascadeError::branch(
1561 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1562 ));
1563 }
1564
1565 self.git_repo.stage_conflict_resolved_files()?;
1567
1568 tracing::debug!("Rebase continued successfully");
1569 Ok(())
1570 }
1571
1572 fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1574 let git_dir = self.git_repo.path().join(".git");
1575 Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1576 }
1577
1578 fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1580 use crate::cli::output::Output;
1581
1582 let git_dir = self.git_repo.path().join(".git");
1583
1584 Output::section("Resuming in-progress sync");
1585 println!();
1586 Output::info("Detected unfinished cherry-pick from previous sync");
1587 println!();
1588
1589 if self.git_repo.has_conflicts()? {
1591 let conflicted_files = self.git_repo.get_conflicted_files()?;
1592
1593 let result = RebaseResult {
1594 success: false,
1595 branch_mapping: HashMap::new(),
1596 conflicts: conflicted_files.clone(),
1597 new_commits: Vec::new(),
1598 error: Some(format!(
1599 "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1600 MANUAL CONFLICT RESOLUTION REQUIRED\n\
1601 =====================================\n\n\
1602 Conflicted files:\n{}\n\n\
1603 Step 1: Analyze conflicts\n\
1604 → Run: ca conflicts\n\
1605 → Shows detailed conflict analysis\n\n\
1606 Step 2: Resolve conflicts in your editor\n\
1607 → Open conflicted files and edit them\n\
1608 → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1609 → Keep the code you want\n\
1610 → Save the files\n\n\
1611 Step 3: Mark conflicts as resolved\n\
1612 → Run: git add <resolved-files>\n\
1613 → Or: git add -A (to stage all resolved files)\n\n\
1614 Step 4: Complete the sync\n\
1615 → Run: ca sync\n\
1616 → Cascade will continue from where it left off\n\n\
1617 Alternative: Abort and start over\n\
1618 → Run: git cherry-pick --abort\n\
1619 → Then: ca sync (starts fresh)",
1620 conflicted_files.len(),
1621 conflicted_files
1622 .iter()
1623 .map(|f| format!(" - {}", f))
1624 .collect::<Vec<_>>()
1625 .join("\n")
1626 )),
1627 summary: "Sync paused - conflicts need resolution".to_string(),
1628 };
1629
1630 return Ok(result);
1631 }
1632
1633 Output::info("Conflicts resolved, continuing cherry-pick...");
1635
1636 self.git_repo.stage_conflict_resolved_files()?;
1638
1639 let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1641 let commit_message = if cherry_pick_msg_file.exists() {
1642 std::fs::read_to_string(&cherry_pick_msg_file)
1643 .unwrap_or_else(|_| "Resolved conflicts".to_string())
1644 } else {
1645 "Resolved conflicts".to_string()
1646 };
1647
1648 match self.git_repo.commit(&commit_message) {
1649 Ok(_new_commit_id) => {
1650 Output::success("Cherry-pick completed");
1651
1652 if git_dir.join("CHERRY_PICK_HEAD").exists() {
1654 let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1655 }
1656 if cherry_pick_msg_file.exists() {
1657 let _ = std::fs::remove_file(&cherry_pick_msg_file);
1658 }
1659
1660 println!();
1661 Output::info("Continuing with rest of stack...");
1662 println!();
1663
1664 self.rebase_with_force_push(stack)
1667 }
1668 Err(e) => {
1669 let result = RebaseResult {
1670 success: false,
1671 branch_mapping: HashMap::new(),
1672 conflicts: Vec::new(),
1673 new_commits: Vec::new(),
1674 error: Some(format!(
1675 "Failed to complete cherry-pick: {}\n\n\
1676 This usually means:\n\
1677 - Git index is locked (another process accessing repo)\n\
1678 - File permissions issue\n\
1679 - Disk space issue\n\n\
1680 Recovery:\n\
1681 1. Check if another Git operation is running\n\
1682 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1683 3. Run 'git status' to check repo state\n\
1684 4. Retry 'ca sync' after fixing the issue\n\n\
1685 Or abort and start fresh:\n\
1686 → Run: git cherry-pick --abort\n\
1687 → Then: ca sync",
1688 e
1689 )),
1690 summary: "Failed to complete cherry-pick".to_string(),
1691 };
1692
1693 Ok(result)
1694 }
1695 }
1696 }
1697}
1698
1699impl RebaseResult {
1700 pub fn get_summary(&self) -> String {
1702 if self.success {
1703 format!("✅ {}", self.summary)
1704 } else {
1705 format!(
1706 "❌ Rebase failed: {}",
1707 self.error.as_deref().unwrap_or("Unknown error")
1708 )
1709 }
1710 }
1711
1712 pub fn has_conflicts(&self) -> bool {
1714 !self.conflicts.is_empty()
1715 }
1716
1717 pub fn success_count(&self) -> usize {
1719 self.new_commits.len()
1720 }
1721}
1722
1723#[cfg(test)]
1724mod tests {
1725 use super::*;
1726 use std::path::PathBuf;
1727 use std::process::Command;
1728 use tempfile::TempDir;
1729
1730 #[allow(dead_code)]
1731 fn create_test_repo() -> (TempDir, PathBuf) {
1732 let temp_dir = TempDir::new().unwrap();
1733 let repo_path = temp_dir.path().to_path_buf();
1734
1735 Command::new("git")
1737 .args(["init"])
1738 .current_dir(&repo_path)
1739 .output()
1740 .unwrap();
1741 Command::new("git")
1742 .args(["config", "user.name", "Test"])
1743 .current_dir(&repo_path)
1744 .output()
1745 .unwrap();
1746 Command::new("git")
1747 .args(["config", "user.email", "test@test.com"])
1748 .current_dir(&repo_path)
1749 .output()
1750 .unwrap();
1751
1752 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1754 Command::new("git")
1755 .args(["add", "."])
1756 .current_dir(&repo_path)
1757 .output()
1758 .unwrap();
1759 Command::new("git")
1760 .args(["commit", "-m", "Initial"])
1761 .current_dir(&repo_path)
1762 .output()
1763 .unwrap();
1764
1765 (temp_dir, repo_path)
1766 }
1767
1768 #[test]
1769 fn test_conflict_region_creation() {
1770 let region = ConflictRegion {
1771 start: 0,
1772 end: 50,
1773 start_line: 1,
1774 end_line: 3,
1775 our_content: "function test() {\n return true;\n}".to_string(),
1776 their_content: "function test() {\n return true;\n}".to_string(),
1777 };
1778
1779 assert_eq!(region.start_line, 1);
1780 assert_eq!(region.end_line, 3);
1781 assert!(region.our_content.contains("return true"));
1782 assert!(region.their_content.contains("return true"));
1783 }
1784
1785 #[test]
1786 fn test_rebase_strategies() {
1787 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1788 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1789 }
1790
1791 #[test]
1792 fn test_rebase_options() {
1793 let options = RebaseOptions::default();
1794 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1795 assert!(!options.interactive);
1796 assert!(options.auto_resolve);
1797 assert_eq!(options.max_retries, 3);
1798 }
1799
1800 #[test]
1801 fn test_cleanup_guard_tracks_branches() {
1802 let mut guard = TempBranchCleanupGuard::new();
1803 assert!(guard.branches.is_empty());
1804
1805 guard.add_branch("test-branch-1".to_string());
1806 guard.add_branch("test-branch-2".to_string());
1807
1808 assert_eq!(guard.branches.len(), 2);
1809 assert_eq!(guard.branches[0], "test-branch-1");
1810 assert_eq!(guard.branches[1], "test-branch-2");
1811 }
1812
1813 #[test]
1814 fn test_cleanup_guard_prevents_double_cleanup() {
1815 use std::process::Command;
1816 use tempfile::TempDir;
1817
1818 let temp_dir = TempDir::new().unwrap();
1820 let repo_path = temp_dir.path();
1821
1822 Command::new("git")
1823 .args(["init"])
1824 .current_dir(repo_path)
1825 .output()
1826 .unwrap();
1827
1828 Command::new("git")
1829 .args(["config", "user.name", "Test"])
1830 .current_dir(repo_path)
1831 .output()
1832 .unwrap();
1833
1834 Command::new("git")
1835 .args(["config", "user.email", "test@test.com"])
1836 .current_dir(repo_path)
1837 .output()
1838 .unwrap();
1839
1840 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1842 Command::new("git")
1843 .args(["add", "."])
1844 .current_dir(repo_path)
1845 .output()
1846 .unwrap();
1847 Command::new("git")
1848 .args(["commit", "-m", "initial"])
1849 .current_dir(repo_path)
1850 .output()
1851 .unwrap();
1852
1853 let git_repo = GitRepository::open(repo_path).unwrap();
1854
1855 git_repo.create_branch("test-temp", None).unwrap();
1857
1858 let mut guard = TempBranchCleanupGuard::new();
1859 guard.add_branch("test-temp".to_string());
1860
1861 guard.cleanup(&git_repo);
1863 assert!(guard.cleaned);
1864
1865 guard.cleanup(&git_repo);
1867 assert!(guard.cleaned);
1868 }
1869
1870 #[test]
1871 fn test_rebase_result() {
1872 let result = RebaseResult {
1873 success: true,
1874 branch_mapping: std::collections::HashMap::new(),
1875 conflicts: vec!["abc123".to_string()],
1876 new_commits: vec!["def456".to_string()],
1877 error: None,
1878 summary: "Test summary".to_string(),
1879 };
1880
1881 assert!(result.success);
1882 assert!(result.has_conflicts());
1883 assert_eq!(result.success_count(), 1);
1884 }
1885}