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