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