1use crate::errors::{CascadeError, Result};
2use crate::git::{ConflictAnalyzer, GitRepository};
3use crate::stack::{Stack, StackManager};
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 Output::warning(format!("Could not reset working directory: {}", e));
267 }
268
269 let mut current_base = target_base.clone();
270 let entry_count = stack.entries.len();
271 let mut temp_branches: Vec<String> = Vec::new(); let mut branches_to_push: Vec<(String, String, usize)> = Vec::new(); if entry_count == 0 {
276 println!();
277 Output::info("Stack has no entries yet");
278 Output::tip("Use 'ca push' to add commits to this stack");
279
280 result.summary = "Stack is empty".to_string();
281
282 println!();
284 Output::success(&result.summary);
285
286 self.stack_manager.save_to_disk()?;
288 return Ok(result);
289 }
290
291 let all_up_to_date = stack.entries.iter().all(|entry| {
293 self.git_repo
294 .is_commit_based_on(&entry.commit_hash, &target_base)
295 .unwrap_or(false)
296 });
297
298 if all_up_to_date {
299 println!();
300 Output::success("Stack is already up-to-date with base branch");
301 result.summary = "Stack is up-to-date".to_string();
302 result.success = true;
303 return Ok(result);
304 }
305
306 for (index, entry) in stack.entries.iter().enumerate() {
308 let original_branch = &entry.branch;
309
310 if self
313 .git_repo
314 .is_commit_based_on(&entry.commit_hash, ¤t_base)
315 .unwrap_or(false)
316 {
317 tracing::debug!(
318 "Entry '{}' is already correctly based on '{}', skipping rebase",
319 original_branch,
320 current_base
321 );
322
323 if let Some(pr_num) = &entry.pull_request_id {
325 branches_to_push.push((original_branch.clone(), pr_num.clone(), index));
326 }
327
328 result
329 .branch_mapping
330 .insert(original_branch.clone(), original_branch.clone());
331
332 current_base = original_branch.clone();
334 continue;
335 }
336
337 if !result.success {
340 tracing::debug!(
341 "Skipping entry '{}' because previous entry failed",
342 original_branch
343 );
344 break;
345 }
346
347 let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
350 temp_branches.push(temp_branch.clone()); if let Err(e) = self
354 .git_repo
355 .create_branch(&temp_branch, Some(¤t_base))
356 {
357 if let Some(ref orig) = original_branch_for_cleanup {
359 let _ = self.git_repo.checkout_branch_unsafe(orig);
360 }
361 return Err(e);
362 }
363
364 if let Err(e) = self.git_repo.checkout_branch_silent(&temp_branch) {
365 if let Some(ref orig) = original_branch_for_cleanup {
367 let _ = self.git_repo.checkout_branch_unsafe(orig);
368 }
369 return Err(e);
370 }
371
372 match self.cherry_pick_commit(&entry.commit_hash) {
374 Ok(new_commit_hash) => {
375 result.new_commits.push(new_commit_hash.clone());
376
377 let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
379
380 self.git_repo
383 .update_branch_to_commit(original_branch, &rebased_commit_id)?;
384
385 if let Some(pr_num) = &entry.pull_request_id {
387 let tree_char = if index + 1 == entry_count {
388 "└─"
389 } else {
390 "├─"
391 };
392 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
393 branches_to_push.push((original_branch.clone(), pr_num.clone(), index));
394 }
395
396 result
397 .branch_mapping
398 .insert(original_branch.clone(), original_branch.clone());
399
400 self.update_stack_entry(
402 stack.id,
403 &entry.id,
404 original_branch,
405 &rebased_commit_id,
406 )?;
407
408 current_base = original_branch.clone();
410 }
411 Err(e) => {
412 result.conflicts.push(entry.commit_hash.clone());
413
414 if !self.options.auto_resolve {
415 println!();
416 Output::error(e.to_string());
417 result.success = false;
418 result.error = Some(format!(
419 "Conflict in {}: {}\n\n\
420 MANUAL CONFLICT RESOLUTION REQUIRED\n\
421 =====================================\n\n\
422 Step 1: Analyze conflicts\n\
423 → Run: ca conflicts\n\
424 → This shows which conflicts are in which files\n\n\
425 Step 2: Resolve conflicts in your editor\n\
426 → Open conflicted files and edit them\n\
427 → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
428 → Keep the code you want\n\
429 → Save the files\n\n\
430 Step 3: Mark conflicts as resolved\n\
431 → Run: git add <resolved-files>\n\
432 → Or: git add -A (to stage all resolved files)\n\n\
433 Step 4: Complete the sync\n\
434 → Run: ca sync\n\
435 → Cascade will detect resolved conflicts and continue\n\n\
436 Alternative: Abort and start over\n\
437 → Run: git cherry-pick --abort\n\
438 → Then: ca sync (starts fresh)\n\n\
439 TIP: Enable auto-resolution for simple conflicts:\n\
440 → Run: ca sync --auto-resolve\n\
441 → Only complex conflicts will require manual resolution",
442 entry.commit_hash, e
443 ));
444 break;
445 }
446
447 match self.auto_resolve_conflicts(&entry.commit_hash) {
449 Ok(fully_resolved) => {
450 if !fully_resolved {
451 result.success = false;
452 result.error = Some(format!(
453 "Conflicts in commit {}\n\n\
454 To resolve:\n\
455 1. Fix conflicts in your editor\n\
456 2. Run: ca sync --continue\n\n\
457 Or abort:\n\
458 → Run: git cherry-pick --abort",
459 &entry.commit_hash[..8]
460 ));
461 break;
462 }
463
464 let commit_message = entry.message.trim().to_string();
467
468 debug!("Checking staged files before commit");
470 let staged_files = self.git_repo.get_staged_files()?;
471
472 if staged_files.is_empty() {
473 result.success = false;
477 result.error = Some(format!(
478 "CRITICAL BUG DETECTED: Cherry-pick failed but no files were staged!\n\n\
479 This indicates a Git state issue after cherry-pick failure.\n\n\
480 RECOVERY STEPS:\n\
481 ================\n\n\
482 Step 1: Check Git status\n\
483 → Run: git status\n\
484 → Check if there are any changes in working directory\n\n\
485 Step 2: Check for conflicts manually\n\
486 → Run: git diff\n\
487 → Look for conflict markers (<<<<<<, ======, >>>>>>)\n\n\
488 Step 3: Abort the cherry-pick\n\
489 → Run: git cherry-pick --abort\n\n\
490 Step 4: Report this bug\n\
491 → This is a known issue we're investigating\n\
492 → Cherry-pick failed for commit {}\n\
493 → But Git reported no conflicts and no staged files\n\n\
494 Step 5: Try manual resolution\n\
495 → Run: ca sync --no-auto-resolve\n\
496 → Manually resolve conflicts as they appear",
497 &entry.commit_hash[..8]
498 ));
499 tracing::error!("CRITICAL - No files staged after auto-resolve!");
500 break;
501 }
502
503 debug!("{} files staged", staged_files.len());
504
505 match self.git_repo.commit(&commit_message) {
506 Ok(new_commit_id) => {
507 debug!(
508 "Created commit {} with message '{}'",
509 &new_commit_id[..8],
510 commit_message
511 );
512
513 Output::success("Auto-resolved conflicts");
514 result.new_commits.push(new_commit_id.clone());
515 let rebased_commit_id = new_commit_id;
516
517 self.cleanup_backup_files()?;
519
520 self.git_repo.update_branch_to_commit(
522 original_branch,
523 &rebased_commit_id,
524 )?;
525
526 if let Some(pr_num) = &entry.pull_request_id {
528 let tree_char = if index + 1 == entry_count {
529 "└─"
530 } else {
531 "├─"
532 };
533 println!(
534 " {} {} (PR #{})",
535 tree_char, original_branch, pr_num
536 );
537 branches_to_push.push((
538 original_branch.clone(),
539 pr_num.clone(),
540 index,
541 ));
542 }
543
544 result
545 .branch_mapping
546 .insert(original_branch.clone(), original_branch.clone());
547
548 self.update_stack_entry(
550 stack.id,
551 &entry.id,
552 original_branch,
553 &rebased_commit_id,
554 )?;
555
556 current_base = original_branch.clone();
558 }
559 Err(commit_err) => {
560 result.success = false;
561 result.error = Some(format!(
562 "Could not commit auto-resolved conflicts: {}\n\n\
563 This usually means:\n\
564 - Git index is locked (another process accessing repo)\n\
565 - File permissions issue\n\
566 - Disk space issue\n\n\
567 Recovery:\n\
568 1. Check if another Git operation is running\n\
569 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
570 3. Run 'git status' to check repo state\n\
571 4. Retry 'ca sync' after fixing the issue",
572 commit_err
573 ));
574 break;
575 }
576 }
577 }
578 Err(resolve_err) => {
579 result.success = false;
580 result.error = Some(format!(
581 "Could not resolve conflicts: {}\n\n\
582 Recovery:\n\
583 1. Check repo state: 'git status'\n\
584 2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
585 3. Remove any lock files: 'rm -f .git/index.lock'\n\
586 4. Retry 'ca sync'",
587 resolve_err
588 ));
589 break;
590 }
591 }
592 }
593 }
594 }
595
596 if !temp_branches.is_empty() {
599 if let Err(e) = self.git_repo.checkout_branch_unsafe(&target_base) {
602 debug!("Could not checkout base for cleanup: {}", e);
603 } else {
606 for temp_branch in &temp_branches {
608 if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
609 debug!("Could not delete temp branch {}: {}", temp_branch, e);
610 }
611 }
612 }
613 }
614
615 let pushed_count = branches_to_push.len();
621 let _skipped_count = entry_count - pushed_count; let mut successful_pushes = 0; if !result.success {
625 println!();
626 Output::error("Rebase failed - not pushing any branches");
627 } else {
630 if !branches_to_push.is_empty() {
634 println!();
635
636 let mut push_results = Vec::new();
638 for (branch_name, _pr_num, _index) in branches_to_push.iter() {
639 let result = self.git_repo.force_push_single_branch_auto(branch_name);
640 push_results.push((branch_name.clone(), result));
641 }
642
643 let mut failed_pushes = 0;
645 for (index, (branch_name, result)) in push_results.iter().enumerate() {
646 match result {
647 Ok(_) => {
648 debug!("Pushed {} successfully", branch_name);
649 successful_pushes += 1;
650 println!(
651 " ✓ Pushed {} ({}/{})",
652 branch_name,
653 index + 1,
654 pushed_count
655 );
656 }
657 Err(e) => {
658 failed_pushes += 1;
659 println!(" ⚠ Could not push '{}': {}", branch_name, e);
660 }
661 }
662 }
663
664 if failed_pushes > 0 {
666 println!(); Output::warning(format!(
668 "{} branch(es) failed to push to remote",
669 failed_pushes
670 ));
671 Output::tip("To retry failed pushes, run: ca sync");
672 }
673 }
674
675 let entries_word = if entry_count == 1 { "entry" } else { "entries" };
677 let pr_word = if successful_pushes == 1 { "PR" } else { "PRs" };
678
679 result.summary = if successful_pushes > 0 {
680 let not_submitted_count = entry_count - successful_pushes;
681 if not_submitted_count > 0 {
682 format!(
683 "{} {} rebased ({} {} updated, {} not yet submitted)",
684 entry_count, entries_word, successful_pushes, pr_word, not_submitted_count
685 )
686 } else {
687 format!(
688 "{} {} rebased ({} {} updated)",
689 entry_count, entries_word, successful_pushes, pr_word
690 )
691 }
692 } else {
693 format!(
694 "{} {} rebased (none submitted to Bitbucket yet)",
695 entry_count, entries_word
696 )
697 };
698 } if let Some(ref orig_branch) = original_branch {
703 if orig_branch != &target_base {
705 if let Some(last_entry) = stack.entries.last() {
707 let top_branch = &last_entry.branch;
708
709 if let (Ok(working_head), Ok(top_commit)) = (
712 self.git_repo.get_branch_head(orig_branch),
713 self.git_repo.get_branch_head(top_branch),
714 ) {
715 if working_head != top_commit {
717 if let Ok(commits) = self
719 .git_repo
720 .get_commits_between(&top_commit, &working_head)
721 {
722 if !commits.is_empty() {
723 let stack_messages: Vec<String> = stack
726 .entries
727 .iter()
728 .map(|e| e.message.trim().to_string())
729 .collect();
730
731 let all_match_stack = commits.iter().all(|commit| {
732 if let Some(msg) = commit.summary() {
733 stack_messages
734 .iter()
735 .any(|stack_msg| stack_msg == msg.trim())
736 } else {
737 false
738 }
739 });
740
741 if all_match_stack {
742 debug!(
747 "Working branch has old pre-rebase commits (matching stack messages) - safe to update"
748 );
749 } else {
750 Output::error(format!(
752 "Cannot sync: Working branch '{}' has {} commit(s) not in the stack",
753 orig_branch,
754 commits.len()
755 ));
756 println!();
757 Output::sub_item(
758 "These commits would be lost if we proceed:",
759 );
760 for (i, commit) in commits.iter().take(5).enumerate() {
761 let message =
762 commit.summary().unwrap_or("(no message)");
763 Output::sub_item(format!(
764 " {}. {} - {}",
765 i + 1,
766 &commit.id().to_string()[..8],
767 message
768 ));
769 }
770 if commits.len() > 5 {
771 Output::sub_item(format!(
772 " ... and {} more",
773 commits.len() - 5
774 ));
775 }
776 println!();
777 Output::tip("Add these commits to the stack first:");
778 Output::bullet("Run: ca stack push");
779 Output::bullet("Then run: ca sync");
780 println!();
781
782 if let Some(ref orig) = original_branch_for_cleanup {
784 let _ = self.git_repo.checkout_branch_unsafe(orig);
785 }
786
787 return Err(CascadeError::validation(
788 format!(
789 "Working branch '{}' has {} untracked commit(s). Add them to the stack with 'ca stack push' before syncing.",
790 orig_branch, commits.len()
791 )
792 ));
793 }
794 }
795 }
796 }
797
798 debug!(
800 "Updating working branch '{}' to match top of stack ({})",
801 orig_branch,
802 &top_commit[..8]
803 );
804
805 if let Err(e) = self
806 .git_repo
807 .update_branch_to_commit(orig_branch, &top_commit)
808 {
809 Output::warning(format!(
810 "Could not update working branch '{}' to top of stack: {}",
811 orig_branch, e
812 ));
813 }
814 }
815 }
816
817 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
820 debug!(
821 "Could not return to original branch '{}': {}",
822 orig_branch, e
823 );
824 }
826 } else {
827 debug!(
830 "Skipping working branch update - user was on base branch '{}'",
831 orig_branch
832 );
833 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
834 debug!("Could not return to base branch '{}': {}", orig_branch, e);
835 }
836 }
837 }
838 println!();
843 if result.success {
844 Output::success(&result.summary);
845 } else {
846 let error_msg = result
848 .error
849 .as_deref()
850 .unwrap_or("Rebase failed for unknown reason");
851 Output::error(error_msg);
852 }
853
854 self.stack_manager.save_to_disk()?;
856
857 if !result.success {
860 if let Some(ref orig_branch) = original_branch {
862 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
863 debug!(
864 "Could not return to original branch '{}' after error: {}",
865 orig_branch, e
866 );
867 }
868 }
869
870 let detailed_error = result.error.as_deref().unwrap_or("Rebase failed");
872 return Err(CascadeError::Branch(detailed_error.to_string()));
873 }
874
875 Ok(result)
876 }
877
878 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
880 tracing::debug!("Starting interactive rebase for stack '{}'", stack.name);
881
882 let mut result = RebaseResult {
883 success: true,
884 branch_mapping: HashMap::new(),
885 conflicts: Vec::new(),
886 new_commits: Vec::new(),
887 error: None,
888 summary: String::new(),
889 };
890
891 println!("Interactive Rebase for Stack: {}", stack.name);
892 println!(" Base branch: {}", stack.base_branch);
893 println!(" Entries: {}", stack.entries.len());
894
895 if self.options.interactive {
896 println!("\nChoose action for each commit:");
897 println!(" (p)ick - apply the commit");
898 println!(" (s)kip - skip this commit");
899 println!(" (e)dit - edit the commit message");
900 println!(" (q)uit - abort the rebase");
901 }
902
903 for entry in &stack.entries {
906 println!(
907 " {} {} - {}",
908 entry.short_hash(),
909 entry.branch,
910 entry.short_message(50)
911 );
912
913 match self.cherry_pick_commit(&entry.commit_hash) {
915 Ok(new_commit) => result.new_commits.push(new_commit),
916 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
917 }
918 }
919
920 result.summary = format!(
921 "Interactive rebase processed {} commits",
922 stack.entries.len()
923 );
924 Ok(result)
925 }
926
927 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
929 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
931
932 if let Ok(staged_files) = self.git_repo.get_staged_files() {
934 if !staged_files.is_empty() {
935 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
937 match self.git_repo.commit_staged_changes(&cleanup_message) {
938 Ok(Some(_)) => {
939 debug!(
940 "Committed {} leftover staged files after cherry-pick",
941 staged_files.len()
942 );
943 }
944 Ok(None) => {
945 debug!("Staged files were cleared before commit");
947 }
948 Err(e) => {
949 tracing::warn!(
951 "Failed to commit {} staged files after cherry-pick: {}. \
952 User may see checkout warning with staged changes.",
953 staged_files.len(),
954 e
955 );
956 }
958 }
959 }
960 }
961
962 Ok(new_commit_hash)
963 }
964
965 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
967 debug!("Starting auto-resolve for commit {}", commit_hash);
968
969 let has_conflicts = self.git_repo.has_conflicts()?;
971 debug!("has_conflicts() = {}", has_conflicts);
972
973 let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
975 let cherry_pick_in_progress = cherry_pick_head.exists();
976
977 if !has_conflicts {
978 debug!("No conflicts detected by Git index");
979
980 if cherry_pick_in_progress {
982 tracing::debug!(
983 "CHERRY_PICK_HEAD exists but no conflicts in index - aborting cherry-pick"
984 );
985
986 let _ = std::process::Command::new("git")
988 .args(["cherry-pick", "--abort"])
989 .current_dir(self.git_repo.path())
990 .output();
991
992 return Err(CascadeError::Branch(format!(
993 "Cherry-pick failed for {} but Git index shows no conflicts. \
994 This usually means the cherry-pick was aborted or failed in an unexpected way. \
995 Please try manual resolution.",
996 &commit_hash[..8]
997 )));
998 }
999
1000 return Ok(true);
1001 }
1002
1003 let conflicted_files = self.git_repo.get_conflicted_files()?;
1004
1005 if conflicted_files.is_empty() {
1006 debug!("Conflicted files list is empty");
1007 return Ok(true);
1008 }
1009
1010 debug!(
1011 "Found conflicts in {} files: {:?}",
1012 conflicted_files.len(),
1013 conflicted_files
1014 );
1015
1016 let analysis = self
1018 .conflict_analyzer
1019 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
1020
1021 debug!(
1022 "Conflict analysis: {} total conflicts, {} auto-resolvable",
1023 analysis.total_conflicts, analysis.auto_resolvable_count
1024 );
1025
1026 for recommendation in &analysis.recommendations {
1028 debug!("{}", recommendation);
1029 }
1030
1031 let mut resolved_count = 0;
1032 let mut resolved_files = Vec::new(); let mut failed_files = Vec::new();
1034
1035 for file_analysis in &analysis.files {
1036 debug!(
1037 "Processing file: {} (auto_resolvable: {}, conflicts: {})",
1038 file_analysis.file_path,
1039 file_analysis.auto_resolvable,
1040 file_analysis.conflicts.len()
1041 );
1042
1043 if file_analysis.auto_resolvable {
1044 match self.resolve_file_conflicts_enhanced(
1045 &file_analysis.file_path,
1046 &file_analysis.conflicts,
1047 ) {
1048 Ok(ConflictResolution::Resolved) => {
1049 resolved_count += 1;
1050 resolved_files.push(file_analysis.file_path.clone());
1051 debug!("Successfully resolved {}", file_analysis.file_path);
1052 }
1053 Ok(ConflictResolution::TooComplex) => {
1054 debug!(
1055 "{} too complex for auto-resolution",
1056 file_analysis.file_path
1057 );
1058 failed_files.push(file_analysis.file_path.clone());
1059 }
1060 Err(e) => {
1061 debug!("Failed to resolve {}: {}", file_analysis.file_path, e);
1062 failed_files.push(file_analysis.file_path.clone());
1063 }
1064 }
1065 } else {
1066 failed_files.push(file_analysis.file_path.clone());
1067 debug!(
1068 "{} requires manual resolution ({} conflicts)",
1069 file_analysis.file_path,
1070 file_analysis.conflicts.len()
1071 );
1072 }
1073 }
1074
1075 if resolved_count > 0 {
1076 debug!(
1077 "Resolved {}/{} files",
1078 resolved_count,
1079 conflicted_files.len()
1080 );
1081 debug!("Resolved files: {:?}", resolved_files);
1082
1083 let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
1086 debug!("Staging {} files", file_paths.len());
1087 self.git_repo.stage_files(&file_paths)?;
1088 debug!("Files staged successfully");
1089 } else {
1090 debug!("No files were resolved (resolved_count = 0)");
1091 }
1092
1093 let all_resolved = failed_files.is_empty();
1095
1096 debug!(
1097 "all_resolved = {}, failed_files = {:?}",
1098 all_resolved, failed_files
1099 );
1100
1101 if !all_resolved {
1102 debug!("{} files still need manual resolution", failed_files.len());
1103 }
1104
1105 debug!("Returning all_resolved = {}", all_resolved);
1106 Ok(all_resolved)
1107 }
1108
1109 fn resolve_file_conflicts_enhanced(
1111 &self,
1112 file_path: &str,
1113 conflicts: &[crate::git::ConflictRegion],
1114 ) -> Result<ConflictResolution> {
1115 let repo_path = self.git_repo.path();
1116 let full_path = repo_path.join(file_path);
1117
1118 let mut content = std::fs::read_to_string(&full_path)
1120 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
1121
1122 if conflicts.is_empty() {
1123 return Ok(ConflictResolution::Resolved);
1124 }
1125
1126 tracing::debug!(
1127 "Resolving {} conflicts in {} using enhanced analysis",
1128 conflicts.len(),
1129 file_path
1130 );
1131
1132 let mut any_resolved = false;
1133
1134 for conflict in conflicts.iter().rev() {
1136 match self.resolve_single_conflict_enhanced(conflict) {
1137 Ok(Some(resolution)) => {
1138 let before = &content[..conflict.start_pos];
1140 let after = &content[conflict.end_pos..];
1141 content = format!("{before}{resolution}{after}");
1142 any_resolved = true;
1143 debug!(
1144 "✅ Resolved {} conflict at lines {}-{} in {}",
1145 format!("{:?}", conflict.conflict_type).to_lowercase(),
1146 conflict.start_line,
1147 conflict.end_line,
1148 file_path
1149 );
1150 }
1151 Ok(None) => {
1152 debug!(
1153 "⚠️ {} conflict at lines {}-{} in {} requires manual resolution",
1154 format!("{:?}", conflict.conflict_type).to_lowercase(),
1155 conflict.start_line,
1156 conflict.end_line,
1157 file_path
1158 );
1159 return Ok(ConflictResolution::TooComplex);
1160 }
1161 Err(e) => {
1162 debug!("❌ Failed to resolve conflict in {}: {}", file_path, e);
1163 return Ok(ConflictResolution::TooComplex);
1164 }
1165 }
1166 }
1167
1168 if any_resolved {
1169 let remaining_conflicts = self.parse_conflict_markers(&content)?;
1171
1172 if remaining_conflicts.is_empty() {
1173 debug!(
1174 "All conflicts resolved in {}, content length: {} bytes",
1175 file_path,
1176 content.len()
1177 );
1178
1179 if content.trim().is_empty() {
1181 tracing::warn!(
1182 "SAFETY CHECK: Resolved content for {} is empty! Aborting auto-resolution.",
1183 file_path
1184 );
1185 return Ok(ConflictResolution::TooComplex);
1186 }
1187
1188 let backup_path = full_path.with_extension("cascade-backup");
1190 if let Ok(original_content) = std::fs::read_to_string(&full_path) {
1191 debug!(
1192 "Backup for {} (original: {} bytes, resolved: {} bytes)",
1193 file_path,
1194 original_content.len(),
1195 content.len()
1196 );
1197 let _ = std::fs::write(&backup_path, original_content);
1198 }
1199
1200 crate::utils::atomic_file::write_string(&full_path, &content)?;
1202
1203 debug!("Wrote {} bytes to {}", content.len(), file_path);
1204 return Ok(ConflictResolution::Resolved);
1205 } else {
1206 tracing::debug!(
1207 "Partially resolved conflicts in {} ({} remaining)",
1208 file_path,
1209 remaining_conflicts.len()
1210 );
1211 }
1212 }
1213
1214 Ok(ConflictResolution::TooComplex)
1215 }
1216
1217 #[allow(dead_code)]
1219 fn count_whitespace_consistency(content: &str) -> usize {
1220 let mut inconsistencies = 0;
1221 let lines: Vec<&str> = content.lines().collect();
1222
1223 for line in &lines {
1224 if line.contains('\t') && line.contains(' ') {
1226 inconsistencies += 1;
1227 }
1228 }
1229
1230 lines.len().saturating_sub(inconsistencies)
1232 }
1233
1234 fn cleanup_backup_files(&self) -> Result<()> {
1236 use std::fs;
1237 use std::path::Path;
1238
1239 let repo_path = self.git_repo.path();
1240
1241 fn remove_backups_recursive(dir: &Path) {
1243 if let Ok(entries) = fs::read_dir(dir) {
1244 for entry in entries.flatten() {
1245 let path = entry.path();
1246
1247 if path.is_dir() {
1248 if path.file_name().and_then(|n| n.to_str()) != Some(".git") {
1250 remove_backups_recursive(&path);
1251 }
1252 } else if let Some(ext) = path.extension() {
1253 if ext == "cascade-backup" {
1254 debug!("Cleaning up backup file: {}", path.display());
1255 if let Err(e) = fs::remove_file(&path) {
1256 tracing::warn!(
1258 "Could not remove backup file {}: {}",
1259 path.display(),
1260 e
1261 );
1262 }
1263 }
1264 }
1265 }
1266 }
1267 }
1268
1269 remove_backups_recursive(repo_path);
1270 Ok(())
1271 }
1272
1273 fn resolve_single_conflict_enhanced(
1275 &self,
1276 conflict: &crate::git::ConflictRegion,
1277 ) -> Result<Option<String>> {
1278 debug!(
1279 "Resolving {} conflict in {} (lines {}-{})",
1280 format!("{:?}", conflict.conflict_type).to_lowercase(),
1281 conflict.file_path,
1282 conflict.start_line,
1283 conflict.end_line
1284 );
1285
1286 use crate::git::ConflictType;
1287
1288 match conflict.conflict_type {
1289 ConflictType::Whitespace => {
1290 let our_normalized = conflict
1293 .our_content
1294 .split_whitespace()
1295 .collect::<Vec<_>>()
1296 .join(" ");
1297 let their_normalized = conflict
1298 .their_content
1299 .split_whitespace()
1300 .collect::<Vec<_>>()
1301 .join(" ");
1302
1303 if our_normalized == their_normalized {
1304 Ok(Some(conflict.their_content.clone()))
1309 } else {
1310 debug!(
1312 "Whitespace conflict has content differences - requires manual resolution"
1313 );
1314 Ok(None)
1315 }
1316 }
1317 ConflictType::LineEnding => {
1318 let normalized = conflict
1320 .our_content
1321 .replace("\r\n", "\n")
1322 .replace('\r', "\n");
1323 Ok(Some(normalized))
1324 }
1325 ConflictType::PureAddition => {
1326 if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1330 Ok(Some(conflict.their_content.clone()))
1332 } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1333 Ok(Some(String::new()))
1335 } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1336 Ok(Some(String::new()))
1338 } else {
1339 debug!(
1345 "PureAddition conflict has content on both sides - requires manual resolution"
1346 );
1347 Ok(None)
1348 }
1349 }
1350 ConflictType::ImportMerge => {
1351 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1356 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1357
1358 let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1360 let trimmed = line.trim();
1361 trimmed.starts_with("import ")
1362 || trimmed.starts_with("from ")
1363 || trimmed.starts_with("use ")
1364 || trimmed.starts_with("#include")
1365 || trimmed.is_empty()
1366 });
1367
1368 if !all_simple {
1369 debug!("ImportMerge contains non-import lines - requires manual resolution");
1370 return Ok(None);
1371 }
1372
1373 let mut all_imports: Vec<&str> = our_lines
1375 .into_iter()
1376 .chain(their_lines)
1377 .filter(|line| !line.trim().is_empty())
1378 .collect();
1379 all_imports.sort();
1380 all_imports.dedup();
1381 Ok(Some(all_imports.join("\n")))
1382 }
1383 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1384 Ok(None)
1386 }
1387 }
1388 }
1389
1390 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1392 let lines: Vec<&str> = content.lines().collect();
1393 let mut conflicts = Vec::new();
1394 let mut i = 0;
1395
1396 while i < lines.len() {
1397 if lines[i].starts_with("<<<<<<<") {
1398 let start_line = i + 1;
1400 let mut separator_line = None;
1401 let mut end_line = None;
1402
1403 for (j, line) in lines.iter().enumerate().skip(i + 1) {
1405 if line.starts_with("=======") {
1406 separator_line = Some(j + 1);
1407 } else if line.starts_with(">>>>>>>") {
1408 end_line = Some(j + 1);
1409 break;
1410 }
1411 }
1412
1413 if let (Some(sep), Some(end)) = (separator_line, end_line) {
1414 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1416 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1417
1418 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1419 let their_content = lines[sep..(end - 1)].join("\n");
1420
1421 conflicts.push(ConflictRegion {
1422 start: start_pos,
1423 end: end_pos,
1424 start_line,
1425 end_line: end,
1426 our_content,
1427 their_content,
1428 });
1429
1430 i = end;
1431 } else {
1432 i += 1;
1433 }
1434 } else {
1435 i += 1;
1436 }
1437 }
1438
1439 Ok(conflicts)
1440 }
1441
1442 fn update_stack_entry(
1445 &mut self,
1446 stack_id: Uuid,
1447 entry_id: &Uuid,
1448 _new_branch: &str,
1449 new_commit_hash: &str,
1450 ) -> Result<()> {
1451 debug!(
1452 "Updating entry {} in stack {} with new commit {}",
1453 entry_id, stack_id, new_commit_hash
1454 );
1455
1456 let stack = self
1458 .stack_manager
1459 .get_stack_mut(&stack_id)
1460 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1461
1462 let entry_exists = stack.entries.iter().any(|e| e.id == *entry_id);
1464
1465 if entry_exists {
1466 let old_hash = stack
1467 .entries
1468 .iter()
1469 .find(|e| e.id == *entry_id)
1470 .map(|e| e.commit_hash.clone())
1471 .unwrap();
1472
1473 debug!(
1474 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch)",
1475 entry_id, old_hash, new_commit_hash
1476 );
1477
1478 stack
1481 .update_entry_commit_hash(entry_id, new_commit_hash.to_string())
1482 .map_err(CascadeError::config)?;
1483
1484 debug!(
1487 "Successfully updated entry {} in stack {}",
1488 entry_id, stack_id
1489 );
1490 Ok(())
1491 } else {
1492 Err(CascadeError::config(format!(
1493 "Entry {entry_id} not found in stack {stack_id}"
1494 )))
1495 }
1496 }
1497
1498 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1500 tracing::debug!("Pulling latest changes for branch {}", branch);
1501
1502 match self.git_repo.fetch() {
1504 Ok(_) => {
1505 debug!("Fetch successful");
1506 match self.git_repo.pull(branch) {
1508 Ok(_) => {
1509 tracing::debug!("Pull completed successfully for {}", branch);
1510 Ok(())
1511 }
1512 Err(e) => {
1513 tracing::debug!("Pull failed for {}: {}", branch, e);
1514 Ok(())
1516 }
1517 }
1518 }
1519 Err(e) => {
1520 tracing::debug!("Fetch failed: {}", e);
1521 Ok(())
1523 }
1524 }
1525 }
1526
1527 pub fn is_rebase_in_progress(&self) -> bool {
1529 let git_dir = self.git_repo.path().join(".git");
1531 git_dir.join("REBASE_HEAD").exists()
1532 || git_dir.join("rebase-merge").exists()
1533 || git_dir.join("rebase-apply").exists()
1534 }
1535
1536 pub fn abort_rebase(&self) -> Result<()> {
1538 tracing::debug!("Aborting rebase operation");
1539
1540 let git_dir = self.git_repo.path().join(".git");
1541
1542 if git_dir.join("REBASE_HEAD").exists() {
1544 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1545 CascadeError::Git(git2::Error::from_str(&format!(
1546 "Failed to clean rebase state: {e}"
1547 )))
1548 })?;
1549 }
1550
1551 if git_dir.join("rebase-merge").exists() {
1552 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1553 CascadeError::Git(git2::Error::from_str(&format!(
1554 "Failed to clean rebase-merge: {e}"
1555 )))
1556 })?;
1557 }
1558
1559 if git_dir.join("rebase-apply").exists() {
1560 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1561 CascadeError::Git(git2::Error::from_str(&format!(
1562 "Failed to clean rebase-apply: {e}"
1563 )))
1564 })?;
1565 }
1566
1567 tracing::debug!("Rebase aborted successfully");
1568 Ok(())
1569 }
1570
1571 pub fn continue_rebase(&self) -> Result<()> {
1573 tracing::debug!("Continuing rebase operation");
1574
1575 if self.git_repo.has_conflicts()? {
1577 return Err(CascadeError::branch(
1578 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1579 ));
1580 }
1581
1582 self.git_repo.stage_conflict_resolved_files()?;
1584
1585 tracing::debug!("Rebase continued successfully");
1586 Ok(())
1587 }
1588
1589 fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1591 let git_dir = self.git_repo.path().join(".git");
1592 Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1593 }
1594
1595 fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1597 use crate::cli::output::Output;
1598
1599 let git_dir = self.git_repo.path().join(".git");
1600
1601 Output::section("Resuming in-progress sync");
1602 println!();
1603 Output::info("Detected unfinished cherry-pick from previous sync");
1604 println!();
1605
1606 if self.git_repo.has_conflicts()? {
1608 let conflicted_files = self.git_repo.get_conflicted_files()?;
1609
1610 let result = RebaseResult {
1611 success: false,
1612 branch_mapping: HashMap::new(),
1613 conflicts: conflicted_files.clone(),
1614 new_commits: Vec::new(),
1615 error: Some(format!(
1616 "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1617 MANUAL CONFLICT RESOLUTION REQUIRED\n\
1618 =====================================\n\n\
1619 Conflicted files:\n{}\n\n\
1620 Step 1: Analyze conflicts\n\
1621 → Run: ca conflicts\n\
1622 → Shows detailed conflict analysis\n\n\
1623 Step 2: Resolve conflicts in your editor\n\
1624 → Open conflicted files and edit them\n\
1625 → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1626 → Keep the code you want\n\
1627 → Save the files\n\n\
1628 Step 3: Mark conflicts as resolved\n\
1629 → Run: git add <resolved-files>\n\
1630 → Or: git add -A (to stage all resolved files)\n\n\
1631 Step 4: Complete the sync\n\
1632 → Run: ca sync\n\
1633 → Cascade will continue from where it left off\n\n\
1634 Alternative: Abort and start over\n\
1635 → Run: git cherry-pick --abort\n\
1636 → Then: ca sync (starts fresh)",
1637 conflicted_files.len(),
1638 conflicted_files
1639 .iter()
1640 .map(|f| format!(" - {}", f))
1641 .collect::<Vec<_>>()
1642 .join("\n")
1643 )),
1644 summary: "Sync paused - conflicts need resolution".to_string(),
1645 };
1646
1647 return Ok(result);
1648 }
1649
1650 Output::info("Conflicts resolved, continuing cherry-pick...");
1652
1653 self.git_repo.stage_conflict_resolved_files()?;
1655
1656 let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1658 let commit_message = if cherry_pick_msg_file.exists() {
1659 std::fs::read_to_string(&cherry_pick_msg_file)
1660 .unwrap_or_else(|_| "Resolved conflicts".to_string())
1661 } else {
1662 "Resolved conflicts".to_string()
1663 };
1664
1665 match self.git_repo.commit(&commit_message) {
1666 Ok(_new_commit_id) => {
1667 Output::success("Cherry-pick completed");
1668
1669 if git_dir.join("CHERRY_PICK_HEAD").exists() {
1671 let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1672 }
1673 if cherry_pick_msg_file.exists() {
1674 let _ = std::fs::remove_file(&cherry_pick_msg_file);
1675 }
1676
1677 println!();
1678 Output::info("Continuing with rest of stack...");
1679 println!();
1680
1681 self.rebase_with_force_push(stack)
1684 }
1685 Err(e) => {
1686 let result = RebaseResult {
1687 success: false,
1688 branch_mapping: HashMap::new(),
1689 conflicts: Vec::new(),
1690 new_commits: Vec::new(),
1691 error: Some(format!(
1692 "Failed to complete cherry-pick: {}\n\n\
1693 This usually means:\n\
1694 - Git index is locked (another process accessing repo)\n\
1695 - File permissions issue\n\
1696 - Disk space issue\n\n\
1697 Recovery:\n\
1698 1. Check if another Git operation is running\n\
1699 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1700 3. Run 'git status' to check repo state\n\
1701 4. Retry 'ca sync' after fixing the issue\n\n\
1702 Or abort and start fresh:\n\
1703 → Run: git cherry-pick --abort\n\
1704 → Then: ca sync",
1705 e
1706 )),
1707 summary: "Failed to complete cherry-pick".to_string(),
1708 };
1709
1710 Ok(result)
1711 }
1712 }
1713 }
1714}
1715
1716impl RebaseResult {
1717 pub fn get_summary(&self) -> String {
1719 if self.success {
1720 format!("✅ {}", self.summary)
1721 } else {
1722 format!(
1723 "❌ Rebase failed: {}",
1724 self.error.as_deref().unwrap_or("Unknown error")
1725 )
1726 }
1727 }
1728
1729 pub fn has_conflicts(&self) -> bool {
1731 !self.conflicts.is_empty()
1732 }
1733
1734 pub fn success_count(&self) -> usize {
1736 self.new_commits.len()
1737 }
1738}
1739
1740#[cfg(test)]
1741mod tests {
1742 use super::*;
1743 use std::path::PathBuf;
1744 use std::process::Command;
1745 use tempfile::TempDir;
1746
1747 #[allow(dead_code)]
1748 fn create_test_repo() -> (TempDir, PathBuf) {
1749 let temp_dir = TempDir::new().unwrap();
1750 let repo_path = temp_dir.path().to_path_buf();
1751
1752 Command::new("git")
1754 .args(["init"])
1755 .current_dir(&repo_path)
1756 .output()
1757 .unwrap();
1758 Command::new("git")
1759 .args(["config", "user.name", "Test"])
1760 .current_dir(&repo_path)
1761 .output()
1762 .unwrap();
1763 Command::new("git")
1764 .args(["config", "user.email", "test@test.com"])
1765 .current_dir(&repo_path)
1766 .output()
1767 .unwrap();
1768
1769 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1771 Command::new("git")
1772 .args(["add", "."])
1773 .current_dir(&repo_path)
1774 .output()
1775 .unwrap();
1776 Command::new("git")
1777 .args(["commit", "-m", "Initial"])
1778 .current_dir(&repo_path)
1779 .output()
1780 .unwrap();
1781
1782 (temp_dir, repo_path)
1783 }
1784
1785 #[test]
1786 fn test_conflict_region_creation() {
1787 let region = ConflictRegion {
1788 start: 0,
1789 end: 50,
1790 start_line: 1,
1791 end_line: 3,
1792 our_content: "function test() {\n return true;\n}".to_string(),
1793 their_content: "function test() {\n return true;\n}".to_string(),
1794 };
1795
1796 assert_eq!(region.start_line, 1);
1797 assert_eq!(region.end_line, 3);
1798 assert!(region.our_content.contains("return true"));
1799 assert!(region.their_content.contains("return true"));
1800 }
1801
1802 #[test]
1803 fn test_rebase_strategies() {
1804 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1805 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1806 }
1807
1808 #[test]
1809 fn test_rebase_options() {
1810 let options = RebaseOptions::default();
1811 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1812 assert!(!options.interactive);
1813 assert!(options.auto_resolve);
1814 assert_eq!(options.max_retries, 3);
1815 }
1816
1817 #[test]
1818 fn test_cleanup_guard_tracks_branches() {
1819 let mut guard = TempBranchCleanupGuard::new();
1820 assert!(guard.branches.is_empty());
1821
1822 guard.add_branch("test-branch-1".to_string());
1823 guard.add_branch("test-branch-2".to_string());
1824
1825 assert_eq!(guard.branches.len(), 2);
1826 assert_eq!(guard.branches[0], "test-branch-1");
1827 assert_eq!(guard.branches[1], "test-branch-2");
1828 }
1829
1830 #[test]
1831 fn test_cleanup_guard_prevents_double_cleanup() {
1832 use std::process::Command;
1833 use tempfile::TempDir;
1834
1835 let temp_dir = TempDir::new().unwrap();
1837 let repo_path = temp_dir.path();
1838
1839 Command::new("git")
1840 .args(["init"])
1841 .current_dir(repo_path)
1842 .output()
1843 .unwrap();
1844
1845 Command::new("git")
1846 .args(["config", "user.name", "Test"])
1847 .current_dir(repo_path)
1848 .output()
1849 .unwrap();
1850
1851 Command::new("git")
1852 .args(["config", "user.email", "test@test.com"])
1853 .current_dir(repo_path)
1854 .output()
1855 .unwrap();
1856
1857 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1859 Command::new("git")
1860 .args(["add", "."])
1861 .current_dir(repo_path)
1862 .output()
1863 .unwrap();
1864 Command::new("git")
1865 .args(["commit", "-m", "initial"])
1866 .current_dir(repo_path)
1867 .output()
1868 .unwrap();
1869
1870 let git_repo = GitRepository::open(repo_path).unwrap();
1871
1872 git_repo.create_branch("test-temp", None).unwrap();
1874
1875 let mut guard = TempBranchCleanupGuard::new();
1876 guard.add_branch("test-temp".to_string());
1877
1878 guard.cleanup(&git_repo);
1880 assert!(guard.cleaned);
1881
1882 guard.cleanup(&git_repo);
1884 assert!(guard.cleaned);
1885 }
1886
1887 #[test]
1888 fn test_rebase_result() {
1889 let result = RebaseResult {
1890 success: true,
1891 branch_mapping: std::collections::HashMap::new(),
1892 conflicts: vec!["abc123".to_string()],
1893 new_commits: vec!["def456".to_string()],
1894 error: None,
1895 summary: "Test summary".to_string(),
1896 };
1897
1898 assert!(result.success);
1899 assert!(result.has_conflicts());
1900 assert_eq!(result.success_count(), 1);
1901 }
1902}