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 working_branch_name) = stack.working_branch {
705 if working_branch_name != &target_base {
707 if let Some(last_entry) = stack.entries.last() {
708 let top_branch = &last_entry.branch;
709
710 if let (Ok(working_head), Ok(top_commit)) = (
713 self.git_repo.get_branch_head(working_branch_name),
714 self.git_repo.get_branch_head(top_branch),
715 ) {
716 if working_head != top_commit {
718 if let Ok(commits) = self
720 .git_repo
721 .get_commits_between(&top_commit, &working_head)
722 {
723 if !commits.is_empty() {
724 let stack_messages: Vec<String> = stack
727 .entries
728 .iter()
729 .map(|e| e.message.trim().to_string())
730 .collect();
731
732 let all_match_stack = commits.iter().all(|commit| {
733 if let Some(msg) = commit.summary() {
734 stack_messages
735 .iter()
736 .any(|stack_msg| stack_msg == msg.trim())
737 } else {
738 false
739 }
740 });
741
742 if all_match_stack {
743 debug!(
748 "Working branch has old pre-rebase commits (matching stack messages) - safe to update"
749 );
750 } else {
751 Output::error(format!(
753 "Cannot sync: Working branch '{}' has {} commit(s) not in the stack",
754 working_branch_name,
755 commits.len()
756 ));
757 println!();
758 Output::sub_item(
759 "These commits would be lost if we proceed:",
760 );
761 for (i, commit) in commits.iter().take(5).enumerate() {
762 let message =
763 commit.summary().unwrap_or("(no message)");
764 Output::sub_item(format!(
765 " {}. {} - {}",
766 i + 1,
767 &commit.id().to_string()[..8],
768 message
769 ));
770 }
771 if commits.len() > 5 {
772 Output::sub_item(format!(
773 " ... and {} more",
774 commits.len() - 5
775 ));
776 }
777 println!();
778 Output::tip("Add these commits to the stack first:");
779 Output::bullet("Run: ca stack push");
780 Output::bullet("Then run: ca sync");
781 println!();
782
783 if let Some(ref orig) = original_branch_for_cleanup {
785 let _ = self.git_repo.checkout_branch_unsafe(orig);
786 }
787
788 return Err(CascadeError::validation(
789 format!(
790 "Working branch '{}' has {} untracked commit(s). Add them to the stack with 'ca stack push' before syncing.",
791 working_branch_name, commits.len()
792 )
793 ));
794 }
795 }
796 }
797 }
798
799 debug!(
801 "Updating working branch '{}' to match top of stack ({})",
802 working_branch_name,
803 &top_commit[..8]
804 );
805
806 if let Err(e) = self
807 .git_repo
808 .update_branch_to_commit(working_branch_name, &top_commit)
809 {
810 Output::warning(format!(
811 "Could not update working branch '{}' to top of stack: {}",
812 working_branch_name, e
813 ));
814 }
815 }
816 }
817 } else {
818 debug!(
820 "Skipping working branch update - working branch '{}' is the base branch",
821 working_branch_name
822 );
823 }
824 }
825
826 if let Some(ref orig_branch) = original_branch {
829 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
830 debug!(
831 "Could not return to original branch '{}': {}",
832 orig_branch, e
833 );
834 }
836 }
837 println!();
842 if result.success {
843 Output::success(&result.summary);
844 } else {
845 let error_msg = result
847 .error
848 .as_deref()
849 .unwrap_or("Rebase failed for unknown reason");
850 Output::error(error_msg);
851 }
852
853 self.stack_manager.save_to_disk()?;
855
856 if !result.success {
859 if let Some(ref orig_branch) = original_branch {
861 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
862 debug!(
863 "Could not return to original branch '{}' after error: {}",
864 orig_branch, e
865 );
866 }
867 }
868
869 let detailed_error = result.error.as_deref().unwrap_or("Rebase failed");
871 return Err(CascadeError::Branch(detailed_error.to_string()));
872 }
873
874 Ok(result)
875 }
876
877 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
879 tracing::debug!("Starting interactive rebase for stack '{}'", stack.name);
880
881 let mut result = RebaseResult {
882 success: true,
883 branch_mapping: HashMap::new(),
884 conflicts: Vec::new(),
885 new_commits: Vec::new(),
886 error: None,
887 summary: String::new(),
888 };
889
890 println!("Interactive Rebase for Stack: {}", stack.name);
891 println!(" Base branch: {}", stack.base_branch);
892 println!(" Entries: {}", stack.entries.len());
893
894 if self.options.interactive {
895 println!("\nChoose action for each commit:");
896 println!(" (p)ick - apply the commit");
897 println!(" (s)kip - skip this commit");
898 println!(" (e)dit - edit the commit message");
899 println!(" (q)uit - abort the rebase");
900 }
901
902 for entry in &stack.entries {
905 println!(
906 " {} {} - {}",
907 entry.short_hash(),
908 entry.branch,
909 entry.short_message(50)
910 );
911
912 match self.cherry_pick_commit(&entry.commit_hash) {
914 Ok(new_commit) => result.new_commits.push(new_commit),
915 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
916 }
917 }
918
919 result.summary = format!(
920 "Interactive rebase processed {} commits",
921 stack.entries.len()
922 );
923 Ok(result)
924 }
925
926 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
928 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
930
931 if let Ok(staged_files) = self.git_repo.get_staged_files() {
933 if !staged_files.is_empty() {
934 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
936 match self.git_repo.commit_staged_changes(&cleanup_message) {
937 Ok(Some(_)) => {
938 debug!(
939 "Committed {} leftover staged files after cherry-pick",
940 staged_files.len()
941 );
942 }
943 Ok(None) => {
944 debug!("Staged files were cleared before commit");
946 }
947 Err(e) => {
948 tracing::warn!(
950 "Failed to commit {} staged files after cherry-pick: {}. \
951 User may see checkout warning with staged changes.",
952 staged_files.len(),
953 e
954 );
955 }
957 }
958 }
959 }
960
961 Ok(new_commit_hash)
962 }
963
964 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
966 debug!("Starting auto-resolve for commit {}", commit_hash);
967
968 let has_conflicts = self.git_repo.has_conflicts()?;
970 debug!("has_conflicts() = {}", has_conflicts);
971
972 let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
974 let cherry_pick_in_progress = cherry_pick_head.exists();
975
976 if !has_conflicts {
977 debug!("No conflicts detected by Git index");
978
979 if cherry_pick_in_progress {
981 tracing::debug!(
982 "CHERRY_PICK_HEAD exists but no conflicts in index - aborting cherry-pick"
983 );
984
985 let _ = std::process::Command::new("git")
987 .args(["cherry-pick", "--abort"])
988 .current_dir(self.git_repo.path())
989 .output();
990
991 return Err(CascadeError::Branch(format!(
992 "Cherry-pick failed for {} but Git index shows no conflicts. \
993 This usually means the cherry-pick was aborted or failed in an unexpected way. \
994 Please try manual resolution.",
995 &commit_hash[..8]
996 )));
997 }
998
999 return Ok(true);
1000 }
1001
1002 let conflicted_files = self.git_repo.get_conflicted_files()?;
1003
1004 if conflicted_files.is_empty() {
1005 debug!("Conflicted files list is empty");
1006 return Ok(true);
1007 }
1008
1009 debug!(
1010 "Found conflicts in {} files: {:?}",
1011 conflicted_files.len(),
1012 conflicted_files
1013 );
1014
1015 let analysis = self
1017 .conflict_analyzer
1018 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
1019
1020 debug!(
1021 "Conflict analysis: {} total conflicts, {} auto-resolvable",
1022 analysis.total_conflicts, analysis.auto_resolvable_count
1023 );
1024
1025 for recommendation in &analysis.recommendations {
1027 debug!("{}", recommendation);
1028 }
1029
1030 let mut resolved_count = 0;
1031 let mut resolved_files = Vec::new(); let mut failed_files = Vec::new();
1033
1034 for file_analysis in &analysis.files {
1035 debug!(
1036 "Processing file: {} (auto_resolvable: {}, conflicts: {})",
1037 file_analysis.file_path,
1038 file_analysis.auto_resolvable,
1039 file_analysis.conflicts.len()
1040 );
1041
1042 if file_analysis.auto_resolvable {
1043 match self.resolve_file_conflicts_enhanced(
1044 &file_analysis.file_path,
1045 &file_analysis.conflicts,
1046 ) {
1047 Ok(ConflictResolution::Resolved) => {
1048 resolved_count += 1;
1049 resolved_files.push(file_analysis.file_path.clone());
1050 debug!("Successfully resolved {}", file_analysis.file_path);
1051 }
1052 Ok(ConflictResolution::TooComplex) => {
1053 debug!(
1054 "{} too complex for auto-resolution",
1055 file_analysis.file_path
1056 );
1057 failed_files.push(file_analysis.file_path.clone());
1058 }
1059 Err(e) => {
1060 debug!("Failed to resolve {}: {}", file_analysis.file_path, e);
1061 failed_files.push(file_analysis.file_path.clone());
1062 }
1063 }
1064 } else {
1065 failed_files.push(file_analysis.file_path.clone());
1066 debug!(
1067 "{} requires manual resolution ({} conflicts)",
1068 file_analysis.file_path,
1069 file_analysis.conflicts.len()
1070 );
1071 }
1072 }
1073
1074 if resolved_count > 0 {
1075 debug!(
1076 "Resolved {}/{} files",
1077 resolved_count,
1078 conflicted_files.len()
1079 );
1080 debug!("Resolved files: {:?}", resolved_files);
1081
1082 let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
1085 debug!("Staging {} files", file_paths.len());
1086 self.git_repo.stage_files(&file_paths)?;
1087 debug!("Files staged successfully");
1088 } else {
1089 debug!("No files were resolved (resolved_count = 0)");
1090 }
1091
1092 let all_resolved = failed_files.is_empty();
1094
1095 debug!(
1096 "all_resolved = {}, failed_files = {:?}",
1097 all_resolved, failed_files
1098 );
1099
1100 if !all_resolved {
1101 debug!("{} files still need manual resolution", failed_files.len());
1102 }
1103
1104 debug!("Returning all_resolved = {}", all_resolved);
1105 Ok(all_resolved)
1106 }
1107
1108 fn resolve_file_conflicts_enhanced(
1110 &self,
1111 file_path: &str,
1112 conflicts: &[crate::git::ConflictRegion],
1113 ) -> Result<ConflictResolution> {
1114 let repo_path = self.git_repo.path();
1115 let full_path = repo_path.join(file_path);
1116
1117 let mut content = std::fs::read_to_string(&full_path)
1119 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
1120
1121 if conflicts.is_empty() {
1122 return Ok(ConflictResolution::Resolved);
1123 }
1124
1125 tracing::debug!(
1126 "Resolving {} conflicts in {} using enhanced analysis",
1127 conflicts.len(),
1128 file_path
1129 );
1130
1131 let mut any_resolved = false;
1132
1133 for conflict in conflicts.iter().rev() {
1135 match self.resolve_single_conflict_enhanced(conflict) {
1136 Ok(Some(resolution)) => {
1137 let before = &content[..conflict.start_pos];
1139 let after = &content[conflict.end_pos..];
1140 content = format!("{before}{resolution}{after}");
1141 any_resolved = true;
1142 debug!(
1143 "✅ Resolved {} conflict at lines {}-{} in {}",
1144 format!("{:?}", conflict.conflict_type).to_lowercase(),
1145 conflict.start_line,
1146 conflict.end_line,
1147 file_path
1148 );
1149 }
1150 Ok(None) => {
1151 debug!(
1152 "⚠️ {} conflict at lines {}-{} in {} requires manual resolution",
1153 format!("{:?}", conflict.conflict_type).to_lowercase(),
1154 conflict.start_line,
1155 conflict.end_line,
1156 file_path
1157 );
1158 return Ok(ConflictResolution::TooComplex);
1159 }
1160 Err(e) => {
1161 debug!("❌ Failed to resolve conflict in {}: {}", file_path, e);
1162 return Ok(ConflictResolution::TooComplex);
1163 }
1164 }
1165 }
1166
1167 if any_resolved {
1168 let remaining_conflicts = self.parse_conflict_markers(&content)?;
1170
1171 if remaining_conflicts.is_empty() {
1172 debug!(
1173 "All conflicts resolved in {}, content length: {} bytes",
1174 file_path,
1175 content.len()
1176 );
1177
1178 if content.trim().is_empty() {
1180 tracing::warn!(
1181 "SAFETY CHECK: Resolved content for {} is empty! Aborting auto-resolution.",
1182 file_path
1183 );
1184 return Ok(ConflictResolution::TooComplex);
1185 }
1186
1187 let backup_path = full_path.with_extension("cascade-backup");
1189 if let Ok(original_content) = std::fs::read_to_string(&full_path) {
1190 debug!(
1191 "Backup for {} (original: {} bytes, resolved: {} bytes)",
1192 file_path,
1193 original_content.len(),
1194 content.len()
1195 );
1196 let _ = std::fs::write(&backup_path, original_content);
1197 }
1198
1199 crate::utils::atomic_file::write_string(&full_path, &content)?;
1201
1202 debug!("Wrote {} bytes to {}", content.len(), file_path);
1203 return Ok(ConflictResolution::Resolved);
1204 } else {
1205 tracing::debug!(
1206 "Partially resolved conflicts in {} ({} remaining)",
1207 file_path,
1208 remaining_conflicts.len()
1209 );
1210 }
1211 }
1212
1213 Ok(ConflictResolution::TooComplex)
1214 }
1215
1216 #[allow(dead_code)]
1218 fn count_whitespace_consistency(content: &str) -> usize {
1219 let mut inconsistencies = 0;
1220 let lines: Vec<&str> = content.lines().collect();
1221
1222 for line in &lines {
1223 if line.contains('\t') && line.contains(' ') {
1225 inconsistencies += 1;
1226 }
1227 }
1228
1229 lines.len().saturating_sub(inconsistencies)
1231 }
1232
1233 fn cleanup_backup_files(&self) -> Result<()> {
1235 use std::fs;
1236 use std::path::Path;
1237
1238 let repo_path = self.git_repo.path();
1239
1240 fn remove_backups_recursive(dir: &Path) {
1242 if let Ok(entries) = fs::read_dir(dir) {
1243 for entry in entries.flatten() {
1244 let path = entry.path();
1245
1246 if path.is_dir() {
1247 if path.file_name().and_then(|n| n.to_str()) != Some(".git") {
1249 remove_backups_recursive(&path);
1250 }
1251 } else if let Some(ext) = path.extension() {
1252 if ext == "cascade-backup" {
1253 debug!("Cleaning up backup file: {}", path.display());
1254 if let Err(e) = fs::remove_file(&path) {
1255 tracing::warn!(
1257 "Could not remove backup file {}: {}",
1258 path.display(),
1259 e
1260 );
1261 }
1262 }
1263 }
1264 }
1265 }
1266 }
1267
1268 remove_backups_recursive(repo_path);
1269 Ok(())
1270 }
1271
1272 fn resolve_single_conflict_enhanced(
1274 &self,
1275 conflict: &crate::git::ConflictRegion,
1276 ) -> Result<Option<String>> {
1277 debug!(
1278 "Resolving {} conflict in {} (lines {}-{})",
1279 format!("{:?}", conflict.conflict_type).to_lowercase(),
1280 conflict.file_path,
1281 conflict.start_line,
1282 conflict.end_line
1283 );
1284
1285 use crate::git::ConflictType;
1286
1287 match conflict.conflict_type {
1288 ConflictType::Whitespace => {
1289 let our_normalized = conflict
1292 .our_content
1293 .split_whitespace()
1294 .collect::<Vec<_>>()
1295 .join(" ");
1296 let their_normalized = conflict
1297 .their_content
1298 .split_whitespace()
1299 .collect::<Vec<_>>()
1300 .join(" ");
1301
1302 if our_normalized == their_normalized {
1303 Ok(Some(conflict.their_content.clone()))
1308 } else {
1309 debug!(
1311 "Whitespace conflict has content differences - requires manual resolution"
1312 );
1313 Ok(None)
1314 }
1315 }
1316 ConflictType::LineEnding => {
1317 let normalized = conflict
1319 .our_content
1320 .replace("\r\n", "\n")
1321 .replace('\r', "\n");
1322 Ok(Some(normalized))
1323 }
1324 ConflictType::PureAddition => {
1325 if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1329 Ok(Some(conflict.their_content.clone()))
1331 } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1332 Ok(Some(String::new()))
1334 } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1335 Ok(Some(String::new()))
1337 } else {
1338 debug!(
1344 "PureAddition conflict has content on both sides - requires manual resolution"
1345 );
1346 Ok(None)
1347 }
1348 }
1349 ConflictType::ImportMerge => {
1350 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1355 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1356
1357 let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1359 let trimmed = line.trim();
1360 trimmed.starts_with("import ")
1361 || trimmed.starts_with("from ")
1362 || trimmed.starts_with("use ")
1363 || trimmed.starts_with("#include")
1364 || trimmed.is_empty()
1365 });
1366
1367 if !all_simple {
1368 debug!("ImportMerge contains non-import lines - requires manual resolution");
1369 return Ok(None);
1370 }
1371
1372 let mut all_imports: Vec<&str> = our_lines
1374 .into_iter()
1375 .chain(their_lines)
1376 .filter(|line| !line.trim().is_empty())
1377 .collect();
1378 all_imports.sort();
1379 all_imports.dedup();
1380 Ok(Some(all_imports.join("\n")))
1381 }
1382 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1383 Ok(None)
1385 }
1386 }
1387 }
1388
1389 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1391 let lines: Vec<&str> = content.lines().collect();
1392 let mut conflicts = Vec::new();
1393 let mut i = 0;
1394
1395 while i < lines.len() {
1396 if lines[i].starts_with("<<<<<<<") {
1397 let start_line = i + 1;
1399 let mut separator_line = None;
1400 let mut end_line = None;
1401
1402 for (j, line) in lines.iter().enumerate().skip(i + 1) {
1404 if line.starts_with("=======") {
1405 separator_line = Some(j + 1);
1406 } else if line.starts_with(">>>>>>>") {
1407 end_line = Some(j + 1);
1408 break;
1409 }
1410 }
1411
1412 if let (Some(sep), Some(end)) = (separator_line, end_line) {
1413 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1415 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1416
1417 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1418 let their_content = lines[sep..(end - 1)].join("\n");
1419
1420 conflicts.push(ConflictRegion {
1421 start: start_pos,
1422 end: end_pos,
1423 start_line,
1424 end_line: end,
1425 our_content,
1426 their_content,
1427 });
1428
1429 i = end;
1430 } else {
1431 i += 1;
1432 }
1433 } else {
1434 i += 1;
1435 }
1436 }
1437
1438 Ok(conflicts)
1439 }
1440
1441 fn update_stack_entry(
1444 &mut self,
1445 stack_id: Uuid,
1446 entry_id: &Uuid,
1447 _new_branch: &str,
1448 new_commit_hash: &str,
1449 ) -> Result<()> {
1450 debug!(
1451 "Updating entry {} in stack {} with new commit {}",
1452 entry_id, stack_id, new_commit_hash
1453 );
1454
1455 let stack = self
1457 .stack_manager
1458 .get_stack_mut(&stack_id)
1459 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1460
1461 let entry_exists = stack.entries.iter().any(|e| e.id == *entry_id);
1463
1464 if entry_exists {
1465 let old_hash = stack
1466 .entries
1467 .iter()
1468 .find(|e| e.id == *entry_id)
1469 .map(|e| e.commit_hash.clone())
1470 .unwrap();
1471
1472 debug!(
1473 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch)",
1474 entry_id, old_hash, new_commit_hash
1475 );
1476
1477 stack
1480 .update_entry_commit_hash(entry_id, new_commit_hash.to_string())
1481 .map_err(CascadeError::config)?;
1482
1483 debug!(
1486 "Successfully updated entry {} in stack {}",
1487 entry_id, stack_id
1488 );
1489 Ok(())
1490 } else {
1491 Err(CascadeError::config(format!(
1492 "Entry {entry_id} not found in stack {stack_id}"
1493 )))
1494 }
1495 }
1496
1497 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1499 tracing::debug!("Pulling latest changes for branch {}", branch);
1500
1501 match self.git_repo.fetch() {
1503 Ok(_) => {
1504 debug!("Fetch successful");
1505 match self.git_repo.pull(branch) {
1507 Ok(_) => {
1508 tracing::debug!("Pull completed successfully for {}", branch);
1509 Ok(())
1510 }
1511 Err(e) => {
1512 tracing::debug!("Pull failed for {}: {}", branch, e);
1513 Ok(())
1515 }
1516 }
1517 }
1518 Err(e) => {
1519 tracing::debug!("Fetch failed: {}", e);
1520 Ok(())
1522 }
1523 }
1524 }
1525
1526 pub fn is_rebase_in_progress(&self) -> bool {
1528 let git_dir = self.git_repo.path().join(".git");
1530 git_dir.join("REBASE_HEAD").exists()
1531 || git_dir.join("rebase-merge").exists()
1532 || git_dir.join("rebase-apply").exists()
1533 }
1534
1535 pub fn abort_rebase(&self) -> Result<()> {
1537 tracing::debug!("Aborting rebase operation");
1538
1539 let git_dir = self.git_repo.path().join(".git");
1540
1541 if git_dir.join("REBASE_HEAD").exists() {
1543 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1544 CascadeError::Git(git2::Error::from_str(&format!(
1545 "Failed to clean rebase state: {e}"
1546 )))
1547 })?;
1548 }
1549
1550 if git_dir.join("rebase-merge").exists() {
1551 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1552 CascadeError::Git(git2::Error::from_str(&format!(
1553 "Failed to clean rebase-merge: {e}"
1554 )))
1555 })?;
1556 }
1557
1558 if git_dir.join("rebase-apply").exists() {
1559 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1560 CascadeError::Git(git2::Error::from_str(&format!(
1561 "Failed to clean rebase-apply: {e}"
1562 )))
1563 })?;
1564 }
1565
1566 tracing::debug!("Rebase aborted successfully");
1567 Ok(())
1568 }
1569
1570 pub fn continue_rebase(&self) -> Result<()> {
1572 tracing::debug!("Continuing rebase operation");
1573
1574 if self.git_repo.has_conflicts()? {
1576 return Err(CascadeError::branch(
1577 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1578 ));
1579 }
1580
1581 self.git_repo.stage_conflict_resolved_files()?;
1583
1584 tracing::debug!("Rebase continued successfully");
1585 Ok(())
1586 }
1587
1588 fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1590 let git_dir = self.git_repo.path().join(".git");
1591 Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1592 }
1593
1594 fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1596 use crate::cli::output::Output;
1597
1598 let git_dir = self.git_repo.path().join(".git");
1599
1600 Output::section("Resuming in-progress sync");
1601 println!();
1602 Output::info("Detected unfinished cherry-pick from previous sync");
1603 println!();
1604
1605 if self.git_repo.has_conflicts()? {
1607 let conflicted_files = self.git_repo.get_conflicted_files()?;
1608
1609 let result = RebaseResult {
1610 success: false,
1611 branch_mapping: HashMap::new(),
1612 conflicts: conflicted_files.clone(),
1613 new_commits: Vec::new(),
1614 error: Some(format!(
1615 "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1616 MANUAL CONFLICT RESOLUTION REQUIRED\n\
1617 =====================================\n\n\
1618 Conflicted files:\n{}\n\n\
1619 Step 1: Analyze conflicts\n\
1620 → Run: ca conflicts\n\
1621 → Shows detailed conflict analysis\n\n\
1622 Step 2: Resolve conflicts in your editor\n\
1623 → Open conflicted files and edit them\n\
1624 → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1625 → Keep the code you want\n\
1626 → Save the files\n\n\
1627 Step 3: Mark conflicts as resolved\n\
1628 → Run: git add <resolved-files>\n\
1629 → Or: git add -A (to stage all resolved files)\n\n\
1630 Step 4: Complete the sync\n\
1631 → Run: ca sync\n\
1632 → Cascade will continue from where it left off\n\n\
1633 Alternative: Abort and start over\n\
1634 → Run: git cherry-pick --abort\n\
1635 → Then: ca sync (starts fresh)",
1636 conflicted_files.len(),
1637 conflicted_files
1638 .iter()
1639 .map(|f| format!(" - {}", f))
1640 .collect::<Vec<_>>()
1641 .join("\n")
1642 )),
1643 summary: "Sync paused - conflicts need resolution".to_string(),
1644 };
1645
1646 return Ok(result);
1647 }
1648
1649 Output::info("Conflicts resolved, continuing cherry-pick...");
1651
1652 self.git_repo.stage_conflict_resolved_files()?;
1654
1655 let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1657 let commit_message = if cherry_pick_msg_file.exists() {
1658 std::fs::read_to_string(&cherry_pick_msg_file)
1659 .unwrap_or_else(|_| "Resolved conflicts".to_string())
1660 } else {
1661 "Resolved conflicts".to_string()
1662 };
1663
1664 match self.git_repo.commit(&commit_message) {
1665 Ok(_new_commit_id) => {
1666 Output::success("Cherry-pick completed");
1667
1668 if git_dir.join("CHERRY_PICK_HEAD").exists() {
1670 let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1671 }
1672 if cherry_pick_msg_file.exists() {
1673 let _ = std::fs::remove_file(&cherry_pick_msg_file);
1674 }
1675
1676 println!();
1677 Output::info("Continuing with rest of stack...");
1678 println!();
1679
1680 self.rebase_with_force_push(stack)
1683 }
1684 Err(e) => {
1685 let result = RebaseResult {
1686 success: false,
1687 branch_mapping: HashMap::new(),
1688 conflicts: Vec::new(),
1689 new_commits: Vec::new(),
1690 error: Some(format!(
1691 "Failed to complete cherry-pick: {}\n\n\
1692 This usually means:\n\
1693 - Git index is locked (another process accessing repo)\n\
1694 - File permissions issue\n\
1695 - Disk space issue\n\n\
1696 Recovery:\n\
1697 1. Check if another Git operation is running\n\
1698 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1699 3. Run 'git status' to check repo state\n\
1700 4. Retry 'ca sync' after fixing the issue\n\n\
1701 Or abort and start fresh:\n\
1702 → Run: git cherry-pick --abort\n\
1703 → Then: ca sync",
1704 e
1705 )),
1706 summary: "Failed to complete cherry-pick".to_string(),
1707 };
1708
1709 Ok(result)
1710 }
1711 }
1712 }
1713}
1714
1715impl RebaseResult {
1716 pub fn get_summary(&self) -> String {
1718 if self.success {
1719 format!("✅ {}", self.summary)
1720 } else {
1721 format!(
1722 "❌ Rebase failed: {}",
1723 self.error.as_deref().unwrap_or("Unknown error")
1724 )
1725 }
1726 }
1727
1728 pub fn has_conflicts(&self) -> bool {
1730 !self.conflicts.is_empty()
1731 }
1732
1733 pub fn success_count(&self) -> usize {
1735 self.new_commits.len()
1736 }
1737}
1738
1739#[cfg(test)]
1740mod tests {
1741 use super::*;
1742 use std::path::PathBuf;
1743 use std::process::Command;
1744 use tempfile::TempDir;
1745
1746 #[allow(dead_code)]
1747 fn create_test_repo() -> (TempDir, PathBuf) {
1748 let temp_dir = TempDir::new().unwrap();
1749 let repo_path = temp_dir.path().to_path_buf();
1750
1751 Command::new("git")
1753 .args(["init"])
1754 .current_dir(&repo_path)
1755 .output()
1756 .unwrap();
1757 Command::new("git")
1758 .args(["config", "user.name", "Test"])
1759 .current_dir(&repo_path)
1760 .output()
1761 .unwrap();
1762 Command::new("git")
1763 .args(["config", "user.email", "test@test.com"])
1764 .current_dir(&repo_path)
1765 .output()
1766 .unwrap();
1767
1768 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1770 Command::new("git")
1771 .args(["add", "."])
1772 .current_dir(&repo_path)
1773 .output()
1774 .unwrap();
1775 Command::new("git")
1776 .args(["commit", "-m", "Initial"])
1777 .current_dir(&repo_path)
1778 .output()
1779 .unwrap();
1780
1781 (temp_dir, repo_path)
1782 }
1783
1784 #[test]
1785 fn test_conflict_region_creation() {
1786 let region = ConflictRegion {
1787 start: 0,
1788 end: 50,
1789 start_line: 1,
1790 end_line: 3,
1791 our_content: "function test() {\n return true;\n}".to_string(),
1792 their_content: "function test() {\n return true;\n}".to_string(),
1793 };
1794
1795 assert_eq!(region.start_line, 1);
1796 assert_eq!(region.end_line, 3);
1797 assert!(region.our_content.contains("return true"));
1798 assert!(region.their_content.contains("return true"));
1799 }
1800
1801 #[test]
1802 fn test_rebase_strategies() {
1803 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1804 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1805 }
1806
1807 #[test]
1808 fn test_rebase_options() {
1809 let options = RebaseOptions::default();
1810 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1811 assert!(!options.interactive);
1812 assert!(options.auto_resolve);
1813 assert_eq!(options.max_retries, 3);
1814 }
1815
1816 #[test]
1817 fn test_cleanup_guard_tracks_branches() {
1818 let mut guard = TempBranchCleanupGuard::new();
1819 assert!(guard.branches.is_empty());
1820
1821 guard.add_branch("test-branch-1".to_string());
1822 guard.add_branch("test-branch-2".to_string());
1823
1824 assert_eq!(guard.branches.len(), 2);
1825 assert_eq!(guard.branches[0], "test-branch-1");
1826 assert_eq!(guard.branches[1], "test-branch-2");
1827 }
1828
1829 #[test]
1830 fn test_cleanup_guard_prevents_double_cleanup() {
1831 use std::process::Command;
1832 use tempfile::TempDir;
1833
1834 let temp_dir = TempDir::new().unwrap();
1836 let repo_path = temp_dir.path();
1837
1838 Command::new("git")
1839 .args(["init"])
1840 .current_dir(repo_path)
1841 .output()
1842 .unwrap();
1843
1844 Command::new("git")
1845 .args(["config", "user.name", "Test"])
1846 .current_dir(repo_path)
1847 .output()
1848 .unwrap();
1849
1850 Command::new("git")
1851 .args(["config", "user.email", "test@test.com"])
1852 .current_dir(repo_path)
1853 .output()
1854 .unwrap();
1855
1856 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1858 Command::new("git")
1859 .args(["add", "."])
1860 .current_dir(repo_path)
1861 .output()
1862 .unwrap();
1863 Command::new("git")
1864 .args(["commit", "-m", "initial"])
1865 .current_dir(repo_path)
1866 .output()
1867 .unwrap();
1868
1869 let git_repo = GitRepository::open(repo_path).unwrap();
1870
1871 git_repo.create_branch("test-temp", None).unwrap();
1873
1874 let mut guard = TempBranchCleanupGuard::new();
1875 guard.add_branch("test-temp".to_string());
1876
1877 guard.cleanup(&git_repo);
1879 assert!(guard.cleaned);
1880
1881 guard.cleanup(&git_repo);
1883 assert!(guard.cleaned);
1884 }
1885
1886 #[test]
1887 fn test_rebase_result() {
1888 let result = RebaseResult {
1889 success: true,
1890 branch_mapping: std::collections::HashMap::new(),
1891 conflicts: vec!["abc123".to_string()],
1892 new_commits: vec!["def456".to_string()],
1893 error: None,
1894 summary: "Test summary".to_string(),
1895 };
1896
1897 assert!(result.success);
1898 assert!(result.has_conflicts());
1899 assert_eq!(result.success_count(), 1);
1900 }
1901}