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));
213
214 let mut result = RebaseResult {
215 success: true,
216 branch_mapping: HashMap::new(),
217 conflicts: Vec::new(),
218 new_commits: Vec::new(),
219 error: None,
220 summary: String::new(),
221 };
222
223 let target_base = self
224 .options
225 .target_base
226 .as_ref()
227 .unwrap_or(&stack.base_branch)
228 .clone(); let original_branch = self
234 .options
235 .original_working_branch
236 .clone()
237 .or_else(|| self.git_repo.get_current_branch().ok());
238
239 let original_branch_for_cleanup = original_branch.clone();
241
242 if let Some(ref orig) = original_branch {
245 if orig == &target_base {
246 debug!(
247 "Original working branch is base branch '{}' - will skip working branch update",
248 orig
249 );
250 }
251 }
252
253 if !self.options.skip_pull.unwrap_or(false) {
256 if let Err(e) = self.pull_latest_changes(&target_base) {
257 Output::warning(format!("Could not pull latest changes: {}", e));
258 }
259 }
260
261 if let Err(e) = self.git_repo.reset_to_head() {
263 Output::warning(format!("Could not reset working directory: {}", e));
264 }
265
266 let mut current_base = target_base.clone();
267 let entry_count = stack.entries.len();
268 let mut temp_branches: Vec<String> = Vec::new(); let mut branches_to_push: Vec<(String, String)> = Vec::new(); if entry_count == 0 {
273 println!(); Output::info("Stack has no entries yet");
275 Output::tip("Use 'ca push' to add commits to this stack");
276
277 result.summary = "Stack is empty".to_string();
278
279 println!(); Output::success(&result.summary);
282
283 self.stack_manager.save_to_disk()?;
285 return Ok(result);
286 }
287
288 println!(); let plural = if entry_count == 1 { "entry" } else { "entries" };
290 println!("Rebasing {} {}...", entry_count, plural);
291
292 for (index, entry) in stack.entries.iter().enumerate() {
294 let original_branch = &entry.branch;
295
296 if self
299 .git_repo
300 .is_commit_based_on(&entry.commit_hash, ¤t_base)
301 .unwrap_or(false)
302 {
303 tracing::debug!(
304 "Entry '{}' is already correctly based on '{}', skipping rebase",
305 original_branch,
306 current_base
307 );
308
309 let tree_char = if index + 1 == entry_count {
311 "└─"
312 } else {
313 "├─"
314 };
315
316 if let Some(pr_num) = &entry.pull_request_id {
317 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
318 branches_to_push.push((original_branch.clone(), pr_num.clone()));
319 } else {
320 println!(" {} {} (not submitted)", tree_char, original_branch);
321 }
322
323 result
324 .branch_mapping
325 .insert(original_branch.clone(), original_branch.clone());
326
327 current_base = original_branch.clone();
329 continue;
330 }
331
332 let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
335 temp_branches.push(temp_branch.clone()); if let Err(e) = self.git_repo.create_branch(&temp_branch, Some(¤t_base)) {
339 if let Some(ref orig) = original_branch_for_cleanup {
341 let _ = self.git_repo.checkout_branch_unsafe(orig);
342 }
343 return Err(e);
344 }
345
346 if let Err(e) = self.git_repo.checkout_branch_silent(&temp_branch) {
347 if let Some(ref orig) = original_branch_for_cleanup {
349 let _ = self.git_repo.checkout_branch_unsafe(orig);
350 }
351 return Err(e);
352 }
353
354 match self.cherry_pick_commit(&entry.commit_hash) {
356 Ok(new_commit_hash) => {
357 result.new_commits.push(new_commit_hash.clone());
358
359 let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
361
362 self.git_repo
365 .update_branch_to_commit(original_branch, &rebased_commit_id)?;
366
367 let tree_char = if index + 1 == entry_count {
369 "└─"
370 } else {
371 "├─"
372 };
373
374 if let Some(pr_num) = &entry.pull_request_id {
375 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
376 branches_to_push.push((original_branch.clone(), pr_num.clone()));
377 } else {
378 println!(" {} {} (not submitted)", tree_char, original_branch);
379 }
380
381 result
382 .branch_mapping
383 .insert(original_branch.clone(), original_branch.clone());
384
385 self.update_stack_entry(
387 stack.id,
388 &entry.id,
389 original_branch,
390 &rebased_commit_id,
391 )?;
392
393 current_base = original_branch.clone();
395 }
396 Err(e) => {
397 result.conflicts.push(entry.commit_hash.clone());
398
399 if !self.options.auto_resolve {
400 println!(); Output::error(e.to_string());
402 result.success = false;
403 result.error = Some(format!(
404 "Conflict in {}: {}\n\n\
405 MANUAL CONFLICT RESOLUTION REQUIRED\n\
406 =====================================\n\n\
407 Step 1: Analyze conflicts\n\
408 → Run: ca conflicts\n\
409 → This shows which conflicts are in which files\n\n\
410 Step 2: Resolve conflicts in your editor\n\
411 → Open conflicted files and edit them\n\
412 → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
413 → Keep the code you want\n\
414 → Save the files\n\n\
415 Step 3: Mark conflicts as resolved\n\
416 → Run: git add <resolved-files>\n\
417 → Or: git add -A (to stage all resolved files)\n\n\
418 Step 4: Complete the sync\n\
419 → Run: ca sync\n\
420 → Cascade will detect resolved conflicts and continue\n\n\
421 Alternative: Abort and start over\n\
422 → Run: git cherry-pick --abort\n\
423 → Then: ca sync (starts fresh)\n\n\
424 TIP: Enable auto-resolution for simple conflicts:\n\
425 → Run: ca sync --auto-resolve\n\
426 → Only complex conflicts will require manual resolution",
427 entry.commit_hash, e
428 ));
429 break;
430 }
431
432 match self.auto_resolve_conflicts(&entry.commit_hash) {
434 Ok(fully_resolved) => {
435 if !fully_resolved {
436 result.success = false;
437 result.error = Some(format!(
438 "Conflicts in commit {}\n\n\
439 To resolve:\n\
440 1. Fix conflicts in your editor\n\
441 2. Run: ca sync --continue\n\n\
442 Or abort:\n\
443 → Run: git cherry-pick --abort",
444 &entry.commit_hash[..8]
445 ));
446 break;
447 }
448
449 let commit_message =
451 format!("Auto-resolved conflicts in {}", &entry.commit_hash[..8]);
452
453 debug!("Checking staged files before commit");
455 let staged_files = self.git_repo.get_staged_files()?;
456
457 if staged_files.is_empty() {
458 result.success = false;
462 result.error = Some(format!(
463 "CRITICAL BUG DETECTED: Cherry-pick failed but no files were staged!\n\n\
464 This indicates a Git state issue after cherry-pick failure.\n\n\
465 RECOVERY STEPS:\n\
466 ================\n\n\
467 Step 1: Check Git status\n\
468 → Run: git status\n\
469 → Check if there are any changes in working directory\n\n\
470 Step 2: Check for conflicts manually\n\
471 → Run: git diff\n\
472 → Look for conflict markers (<<<<<<, ======, >>>>>>)\n\n\
473 Step 3: Abort the cherry-pick\n\
474 → Run: git cherry-pick --abort\n\n\
475 Step 4: Report this bug\n\
476 → This is a known issue we're investigating\n\
477 → Cherry-pick failed for commit {}\n\
478 → But Git reported no conflicts and no staged files\n\n\
479 Step 5: Try manual resolution\n\
480 → Run: ca sync --no-auto-resolve\n\
481 → Manually resolve conflicts as they appear",
482 &entry.commit_hash[..8]
483 ));
484 tracing::error!("CRITICAL - No files staged after auto-resolve!");
485 break;
486 }
487
488 debug!("{} files staged", staged_files.len());
489
490 match self.git_repo.commit(&commit_message) {
491 Ok(new_commit_id) => {
492 debug!(
493 "Created commit {} with message '{}'",
494 &new_commit_id[..8],
495 commit_message
496 );
497
498 Output::success("Auto-resolved conflicts");
499 result.new_commits.push(new_commit_id.clone());
500 let rebased_commit_id = new_commit_id;
501
502 self.git_repo.update_branch_to_commit(
504 original_branch,
505 &rebased_commit_id,
506 )?;
507
508 let tree_char = if index + 1 == entry_count {
510 "└─"
511 } else {
512 "├─"
513 };
514
515 if let Some(pr_num) = &entry.pull_request_id {
516 println!(
517 " {} {} (PR #{})",
518 tree_char, original_branch, pr_num
519 );
520 branches_to_push
521 .push((original_branch.clone(), pr_num.clone()));
522 } else {
523 println!(
524 " {} {} (not submitted)",
525 tree_char, original_branch
526 );
527 }
528
529 result
530 .branch_mapping
531 .insert(original_branch.clone(), original_branch.clone());
532
533 self.update_stack_entry(
535 stack.id,
536 &entry.id,
537 original_branch,
538 &rebased_commit_id,
539 )?;
540
541 current_base = original_branch.clone();
543 }
544 Err(commit_err) => {
545 result.success = false;
546 result.error = Some(format!(
547 "Could not commit auto-resolved conflicts: {}\n\n\
548 This usually means:\n\
549 - Git index is locked (another process accessing repo)\n\
550 - File permissions issue\n\
551 - Disk space issue\n\n\
552 Recovery:\n\
553 1. Check if another Git operation is running\n\
554 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
555 3. Run 'git status' to check repo state\n\
556 4. Retry 'ca sync' after fixing the issue",
557 commit_err
558 ));
559 break;
560 }
561 }
562 }
563 Err(resolve_err) => {
564 result.success = false;
565 result.error = Some(format!(
566 "Could not resolve conflicts: {}\n\n\
567 Recovery:\n\
568 1. Check repo state: 'git status'\n\
569 2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
570 3. Remove any lock files: 'rm -f .git/index.lock'\n\
571 4. Retry 'ca sync'",
572 resolve_err
573 ));
574 break;
575 }
576 }
577 }
578 }
579 }
580
581 if !temp_branches.is_empty() {
584 if let Err(e) = self.git_repo.checkout_branch_unsafe(&target_base) {
587 debug!("Could not checkout base for cleanup: {}", e);
588 } else {
591 for temp_branch in &temp_branches {
593 if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
594 debug!("Could not delete temp branch {}: {}", temp_branch, e);
595 }
596 }
597 }
598 }
599
600 let pushed_count = branches_to_push.len();
603 let skipped_count = entry_count - pushed_count;
604
605 if !branches_to_push.is_empty() {
606 for (branch_name, _pr_num) in &branches_to_push {
609 match self.git_repo.force_push_single_branch_auto(branch_name) {
610 Ok(_) => {
611 debug!("Pushed {} successfully", branch_name);
612 }
613 Err(e) => {
614 Output::warning(format!("Could not push '{}': {}", branch_name, e));
615 }
617 }
618 }
619 }
620
621 if let Some(ref orig_branch) = original_branch {
624 if orig_branch != &target_base {
626 if let Some(last_entry) = stack.entries.last() {
628 let top_branch = &last_entry.branch;
629
630 if let (Ok(working_head), Ok(top_commit)) = (
633 self.git_repo.get_branch_head(orig_branch),
634 self.git_repo.get_branch_head(top_branch),
635 ) {
636 if working_head != top_commit {
638 if let Ok(commits) = self
640 .git_repo
641 .get_commits_between(&top_commit, &working_head)
642 {
643 if !commits.is_empty() {
644 Output::error(format!(
646 "Cannot sync: Working branch '{}' has {} commit(s) not in the stack",
647 orig_branch,
648 commits.len()
649 ));
650 println!();
651 Output::sub_item("These commits would be lost if we proceed:");
652 for (i, commit) in commits.iter().take(5).enumerate() {
653 let message = commit.summary().unwrap_or("(no message)");
654 Output::sub_item(format!(
655 " {}. {} - {}",
656 i + 1,
657 &commit.id().to_string()[..8],
658 message
659 ));
660 }
661 if commits.len() > 5 {
662 Output::sub_item(format!(
663 " ... and {} more",
664 commits.len() - 5
665 ));
666 }
667 println!();
668 Output::tip("Add these commits to the stack first:");
669 Output::bullet("Run: ca stack push");
670 Output::bullet("Then run: ca sync");
671 println!();
672
673 return Err(CascadeError::validation(
674 format!(
675 "Working branch '{}' has {} untracked commit(s). Add them to the stack with 'ca stack push' before syncing.",
676 orig_branch, commits.len()
677 )
678 ));
679 }
680 }
681 }
682
683 debug!(
685 "Updating working branch '{}' to match top of stack ({})",
686 orig_branch,
687 &top_commit[..8]
688 );
689
690 if let Err(e) = self
691 .git_repo
692 .update_branch_to_commit(orig_branch, &top_commit)
693 {
694 Output::warning(format!(
695 "Could not update working branch '{}' to top of stack: {}",
696 orig_branch, e
697 ));
698 }
699 }
700 }
701
702 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
705 debug!(
706 "Could not return to original branch '{}': {}",
707 orig_branch, e
708 );
709 }
711 } else {
712 debug!(
715 "Skipping working branch update - user was on base branch '{}'",
716 orig_branch
717 );
718 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
719 debug!("Could not return to base branch '{}': {}", orig_branch, e);
720 }
721 }
722 }
723
724 result.summary = if pushed_count > 0 {
726 let pr_plural = if pushed_count == 1 { "" } else { "s" };
727 let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
728
729 if skipped_count > 0 {
730 format!(
731 "{} {} rebased ({} PR{} updated, {} not yet submitted)",
732 entry_count, entry_plural, pushed_count, pr_plural, skipped_count
733 )
734 } else {
735 format!(
736 "{} {} rebased ({} PR{} updated)",
737 entry_count, entry_plural, pushed_count, pr_plural
738 )
739 }
740 } else {
741 let plural = if entry_count == 1 { "entry" } else { "entries" };
742 format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
743 };
744
745 println!(); if result.success {
748 Output::success(&result.summary);
749 } else {
750 let error_msg = result
752 .error
753 .as_deref()
754 .unwrap_or("Rebase failed for unknown reason");
755 Output::error(error_msg);
756 }
757
758 self.stack_manager.save_to_disk()?;
760
761 if !result.success {
764 if let Some(ref orig_branch) = original_branch {
766 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
767 debug!("Could not return to original branch '{}' after error: {}", orig_branch, e);
768 }
769 }
770
771 let detailed_error = result.error.as_deref().unwrap_or("Rebase failed");
773 return Err(CascadeError::Branch(detailed_error.to_string()));
774 }
775
776 Ok(result)
777 }
778
779 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
781 tracing::debug!("Starting interactive rebase for stack '{}'", stack.name);
782
783 let mut result = RebaseResult {
784 success: true,
785 branch_mapping: HashMap::new(),
786 conflicts: Vec::new(),
787 new_commits: Vec::new(),
788 error: None,
789 summary: String::new(),
790 };
791
792 println!("Interactive Rebase for Stack: {}", stack.name);
793 println!(" Base branch: {}", stack.base_branch);
794 println!(" Entries: {}", stack.entries.len());
795
796 if self.options.interactive {
797 println!("\nChoose action for each commit:");
798 println!(" (p)ick - apply the commit");
799 println!(" (s)kip - skip this commit");
800 println!(" (e)dit - edit the commit message");
801 println!(" (q)uit - abort the rebase");
802 }
803
804 for entry in &stack.entries {
807 println!(
808 " {} {} - {}",
809 entry.short_hash(),
810 entry.branch,
811 entry.short_message(50)
812 );
813
814 match self.cherry_pick_commit(&entry.commit_hash) {
816 Ok(new_commit) => result.new_commits.push(new_commit),
817 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
818 }
819 }
820
821 result.summary = format!(
822 "Interactive rebase processed {} commits",
823 stack.entries.len()
824 );
825 Ok(result)
826 }
827
828 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
830 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
832
833 if let Ok(staged_files) = self.git_repo.get_staged_files() {
835 if !staged_files.is_empty() {
836 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
838 let _ = self.git_repo.commit_staged_changes(&cleanup_message);
839 }
840 }
841
842 Ok(new_commit_hash)
843 }
844
845 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
847 debug!("Starting auto-resolve for commit {}", commit_hash);
848
849 let has_conflicts = self.git_repo.has_conflicts()?;
851 debug!("has_conflicts() = {}", has_conflicts);
852
853 let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
855 let cherry_pick_in_progress = cherry_pick_head.exists();
856
857 if !has_conflicts {
858 debug!("No conflicts detected by Git index");
859
860 if cherry_pick_in_progress {
862 tracing::debug!(
863 "CHERRY_PICK_HEAD exists but no conflicts in index - aborting cherry-pick"
864 );
865
866 let _ = std::process::Command::new("git")
868 .args(["cherry-pick", "--abort"])
869 .current_dir(self.git_repo.path())
870 .output();
871
872 return Err(CascadeError::Branch(format!(
873 "Cherry-pick failed for {} but Git index shows no conflicts. \
874 This usually means the cherry-pick was aborted or failed in an unexpected way. \
875 Please try manual resolution.",
876 &commit_hash[..8]
877 )));
878 }
879
880 return Ok(true);
881 }
882
883 let conflicted_files = self.git_repo.get_conflicted_files()?;
884
885 if conflicted_files.is_empty() {
886 debug!("Conflicted files list is empty");
887 return Ok(true);
888 }
889
890 debug!(
891 "Found conflicts in {} files: {:?}",
892 conflicted_files.len(),
893 conflicted_files
894 );
895
896 let analysis = self
898 .conflict_analyzer
899 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
900
901 debug!(
902 "Conflict analysis: {} total conflicts, {} auto-resolvable",
903 analysis.total_conflicts, analysis.auto_resolvable_count
904 );
905
906 for recommendation in &analysis.recommendations {
908 debug!("{}", recommendation);
909 }
910
911 let mut resolved_count = 0;
912 let mut resolved_files = Vec::new(); let mut failed_files = Vec::new();
914
915 for file_analysis in &analysis.files {
916 debug!(
917 "Processing file: {} (auto_resolvable: {}, conflicts: {})",
918 file_analysis.file_path,
919 file_analysis.auto_resolvable,
920 file_analysis.conflicts.len()
921 );
922
923 if file_analysis.auto_resolvable {
924 match self.resolve_file_conflicts_enhanced(
925 &file_analysis.file_path,
926 &file_analysis.conflicts,
927 ) {
928 Ok(ConflictResolution::Resolved) => {
929 resolved_count += 1;
930 resolved_files.push(file_analysis.file_path.clone());
931 debug!("Successfully resolved {}", file_analysis.file_path);
932 }
933 Ok(ConflictResolution::TooComplex) => {
934 debug!(
935 "{} too complex for auto-resolution",
936 file_analysis.file_path
937 );
938 failed_files.push(file_analysis.file_path.clone());
939 }
940 Err(e) => {
941 debug!("Failed to resolve {}: {}", file_analysis.file_path, e);
942 failed_files.push(file_analysis.file_path.clone());
943 }
944 }
945 } else {
946 failed_files.push(file_analysis.file_path.clone());
947 debug!(
948 "{} requires manual resolution ({} conflicts)",
949 file_analysis.file_path,
950 file_analysis.conflicts.len()
951 );
952 }
953 }
954
955 if resolved_count > 0 {
956 debug!(
957 "Resolved {}/{} files",
958 resolved_count,
959 conflicted_files.len()
960 );
961 debug!("Resolved files: {:?}", resolved_files);
962
963 let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
966 debug!("Staging {} files", file_paths.len());
967 self.git_repo.stage_files(&file_paths)?;
968 debug!("Files staged successfully");
969 } else {
970 debug!("No files were resolved (resolved_count = 0)");
971 }
972
973 let all_resolved = failed_files.is_empty();
975
976 debug!(
977 "all_resolved = {}, failed_files = {:?}",
978 all_resolved, failed_files
979 );
980
981 if !all_resolved {
982 debug!("{} files still need manual resolution", failed_files.len());
983 }
984
985 debug!("Returning all_resolved = {}", all_resolved);
986 Ok(all_resolved)
987 }
988
989 fn resolve_file_conflicts_enhanced(
991 &self,
992 file_path: &str,
993 conflicts: &[crate::git::ConflictRegion],
994 ) -> Result<ConflictResolution> {
995 let repo_path = self.git_repo.path();
996 let full_path = repo_path.join(file_path);
997
998 let mut content = std::fs::read_to_string(&full_path)
1000 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
1001
1002 if conflicts.is_empty() {
1003 return Ok(ConflictResolution::Resolved);
1004 }
1005
1006 tracing::debug!(
1007 "Resolving {} conflicts in {} using enhanced analysis",
1008 conflicts.len(),
1009 file_path
1010 );
1011
1012 let mut any_resolved = false;
1013
1014 for conflict in conflicts.iter().rev() {
1016 match self.resolve_single_conflict_enhanced(conflict) {
1017 Ok(Some(resolution)) => {
1018 let before = &content[..conflict.start_pos];
1020 let after = &content[conflict.end_pos..];
1021 content = format!("{before}{resolution}{after}");
1022 any_resolved = true;
1023 debug!(
1024 "✅ Resolved {} conflict at lines {}-{} in {}",
1025 format!("{:?}", conflict.conflict_type).to_lowercase(),
1026 conflict.start_line,
1027 conflict.end_line,
1028 file_path
1029 );
1030 }
1031 Ok(None) => {
1032 debug!(
1033 "⚠️ {} conflict at lines {}-{} in {} requires manual resolution",
1034 format!("{:?}", conflict.conflict_type).to_lowercase(),
1035 conflict.start_line,
1036 conflict.end_line,
1037 file_path
1038 );
1039 return Ok(ConflictResolution::TooComplex);
1040 }
1041 Err(e) => {
1042 debug!("❌ Failed to resolve conflict in {}: {}", file_path, e);
1043 return Ok(ConflictResolution::TooComplex);
1044 }
1045 }
1046 }
1047
1048 if any_resolved {
1049 let remaining_conflicts = self.parse_conflict_markers(&content)?;
1051
1052 if remaining_conflicts.is_empty() {
1053 debug!(
1054 "All conflicts resolved in {}, content length: {} bytes",
1055 file_path,
1056 content.len()
1057 );
1058
1059 if content.trim().is_empty() {
1061 tracing::warn!(
1062 "SAFETY CHECK: Resolved content for {} is empty! Aborting auto-resolution.",
1063 file_path
1064 );
1065 return Ok(ConflictResolution::TooComplex);
1066 }
1067
1068 let backup_path = full_path.with_extension("cascade-backup");
1070 if let Ok(original_content) = std::fs::read_to_string(&full_path) {
1071 debug!(
1072 "Backup for {} (original: {} bytes, resolved: {} bytes)",
1073 file_path,
1074 original_content.len(),
1075 content.len()
1076 );
1077 let _ = std::fs::write(&backup_path, original_content);
1078 }
1079
1080 crate::utils::atomic_file::write_string(&full_path, &content)?;
1082
1083 debug!("Wrote {} bytes to {}", content.len(), file_path);
1084 return Ok(ConflictResolution::Resolved);
1085 } else {
1086 tracing::debug!(
1087 "Partially resolved conflicts in {} ({} remaining)",
1088 file_path,
1089 remaining_conflicts.len()
1090 );
1091 }
1092 }
1093
1094 Ok(ConflictResolution::TooComplex)
1095 }
1096
1097 #[allow(dead_code)]
1099 fn count_whitespace_consistency(content: &str) -> usize {
1100 let mut inconsistencies = 0;
1101 let lines: Vec<&str> = content.lines().collect();
1102
1103 for line in &lines {
1104 if line.contains('\t') && line.contains(' ') {
1106 inconsistencies += 1;
1107 }
1108 }
1109
1110 lines.len().saturating_sub(inconsistencies)
1112 }
1113
1114 fn resolve_single_conflict_enhanced(
1116 &self,
1117 conflict: &crate::git::ConflictRegion,
1118 ) -> Result<Option<String>> {
1119 debug!(
1120 "Resolving {} conflict in {} (lines {}-{})",
1121 format!("{:?}", conflict.conflict_type).to_lowercase(),
1122 conflict.file_path,
1123 conflict.start_line,
1124 conflict.end_line
1125 );
1126
1127 use crate::git::ConflictType;
1128
1129 match conflict.conflict_type {
1130 ConflictType::Whitespace => {
1131 let our_normalized = conflict
1134 .our_content
1135 .split_whitespace()
1136 .collect::<Vec<_>>()
1137 .join(" ");
1138 let their_normalized = conflict
1139 .their_content
1140 .split_whitespace()
1141 .collect::<Vec<_>>()
1142 .join(" ");
1143
1144 if our_normalized == their_normalized {
1145 Ok(Some(conflict.their_content.clone()))
1150 } else {
1151 debug!(
1153 "Whitespace conflict has content differences - requires manual resolution"
1154 );
1155 Ok(None)
1156 }
1157 }
1158 ConflictType::LineEnding => {
1159 let normalized = conflict
1161 .our_content
1162 .replace("\r\n", "\n")
1163 .replace('\r', "\n");
1164 Ok(Some(normalized))
1165 }
1166 ConflictType::PureAddition => {
1167 if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1171 Ok(Some(conflict.their_content.clone()))
1173 } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1174 Ok(Some(String::new()))
1176 } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1177 Ok(Some(String::new()))
1179 } else {
1180 debug!(
1186 "PureAddition conflict has content on both sides - requires manual resolution"
1187 );
1188 Ok(None)
1189 }
1190 }
1191 ConflictType::ImportMerge => {
1192 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1197 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1198
1199 let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1201 let trimmed = line.trim();
1202 trimmed.starts_with("import ")
1203 || trimmed.starts_with("from ")
1204 || trimmed.starts_with("use ")
1205 || trimmed.starts_with("#include")
1206 || trimmed.is_empty()
1207 });
1208
1209 if !all_simple {
1210 debug!("ImportMerge contains non-import lines - requires manual resolution");
1211 return Ok(None);
1212 }
1213
1214 let mut all_imports: Vec<&str> = our_lines
1216 .into_iter()
1217 .chain(their_lines)
1218 .filter(|line| !line.trim().is_empty())
1219 .collect();
1220 all_imports.sort();
1221 all_imports.dedup();
1222 Ok(Some(all_imports.join("\n")))
1223 }
1224 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1225 Ok(None)
1227 }
1228 }
1229 }
1230
1231 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1233 let lines: Vec<&str> = content.lines().collect();
1234 let mut conflicts = Vec::new();
1235 let mut i = 0;
1236
1237 while i < lines.len() {
1238 if lines[i].starts_with("<<<<<<<") {
1239 let start_line = i + 1;
1241 let mut separator_line = None;
1242 let mut end_line = None;
1243
1244 for (j, line) in lines.iter().enumerate().skip(i + 1) {
1246 if line.starts_with("=======") {
1247 separator_line = Some(j + 1);
1248 } else if line.starts_with(">>>>>>>") {
1249 end_line = Some(j + 1);
1250 break;
1251 }
1252 }
1253
1254 if let (Some(sep), Some(end)) = (separator_line, end_line) {
1255 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1257 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1258
1259 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1260 let their_content = lines[sep..(end - 1)].join("\n");
1261
1262 conflicts.push(ConflictRegion {
1263 start: start_pos,
1264 end: end_pos,
1265 start_line,
1266 end_line: end,
1267 our_content,
1268 their_content,
1269 });
1270
1271 i = end;
1272 } else {
1273 i += 1;
1274 }
1275 } else {
1276 i += 1;
1277 }
1278 }
1279
1280 Ok(conflicts)
1281 }
1282
1283 fn update_stack_entry(
1286 &mut self,
1287 stack_id: Uuid,
1288 entry_id: &Uuid,
1289 _new_branch: &str,
1290 new_commit_hash: &str,
1291 ) -> Result<()> {
1292 debug!(
1293 "Updating entry {} in stack {} with new commit {}",
1294 entry_id, stack_id, new_commit_hash
1295 );
1296
1297 let stack = self
1299 .stack_manager
1300 .get_stack_mut(&stack_id)
1301 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1302
1303 let entry_exists = stack.entries.iter().any(|e| e.id == *entry_id);
1305
1306 if entry_exists {
1307 let old_hash = stack
1308 .entries
1309 .iter()
1310 .find(|e| e.id == *entry_id)
1311 .map(|e| e.commit_hash.clone())
1312 .unwrap();
1313
1314 debug!(
1315 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch)",
1316 entry_id, old_hash, new_commit_hash
1317 );
1318
1319 stack
1322 .update_entry_commit_hash(entry_id, new_commit_hash.to_string())
1323 .map_err(CascadeError::config)?;
1324
1325 debug!(
1328 "Successfully updated entry {} in stack {}",
1329 entry_id, stack_id
1330 );
1331 Ok(())
1332 } else {
1333 Err(CascadeError::config(format!(
1334 "Entry {entry_id} not found in stack {stack_id}"
1335 )))
1336 }
1337 }
1338
1339 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1341 tracing::debug!("Pulling latest changes for branch {}", branch);
1342
1343 match self.git_repo.fetch() {
1345 Ok(_) => {
1346 debug!("Fetch successful");
1347 match self.git_repo.pull(branch) {
1349 Ok(_) => {
1350 tracing::debug!("Pull completed successfully for {}", branch);
1351 Ok(())
1352 }
1353 Err(e) => {
1354 tracing::debug!("Pull failed for {}: {}", branch, e);
1355 Ok(())
1357 }
1358 }
1359 }
1360 Err(e) => {
1361 tracing::debug!("Fetch failed: {}", e);
1362 Ok(())
1364 }
1365 }
1366 }
1367
1368 pub fn is_rebase_in_progress(&self) -> bool {
1370 let git_dir = self.git_repo.path().join(".git");
1372 git_dir.join("REBASE_HEAD").exists()
1373 || git_dir.join("rebase-merge").exists()
1374 || git_dir.join("rebase-apply").exists()
1375 }
1376
1377 pub fn abort_rebase(&self) -> Result<()> {
1379 tracing::debug!("Aborting rebase operation");
1380
1381 let git_dir = self.git_repo.path().join(".git");
1382
1383 if git_dir.join("REBASE_HEAD").exists() {
1385 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1386 CascadeError::Git(git2::Error::from_str(&format!(
1387 "Failed to clean rebase state: {e}"
1388 )))
1389 })?;
1390 }
1391
1392 if git_dir.join("rebase-merge").exists() {
1393 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1394 CascadeError::Git(git2::Error::from_str(&format!(
1395 "Failed to clean rebase-merge: {e}"
1396 )))
1397 })?;
1398 }
1399
1400 if git_dir.join("rebase-apply").exists() {
1401 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1402 CascadeError::Git(git2::Error::from_str(&format!(
1403 "Failed to clean rebase-apply: {e}"
1404 )))
1405 })?;
1406 }
1407
1408 tracing::debug!("Rebase aborted successfully");
1409 Ok(())
1410 }
1411
1412 pub fn continue_rebase(&self) -> Result<()> {
1414 tracing::debug!("Continuing rebase operation");
1415
1416 if self.git_repo.has_conflicts()? {
1418 return Err(CascadeError::branch(
1419 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1420 ));
1421 }
1422
1423 self.git_repo.stage_conflict_resolved_files()?;
1425
1426 tracing::debug!("Rebase continued successfully");
1427 Ok(())
1428 }
1429
1430 fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1432 let git_dir = self.git_repo.path().join(".git");
1433 Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1434 }
1435
1436 fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1438 use crate::cli::output::Output;
1439
1440 let git_dir = self.git_repo.path().join(".git");
1441
1442 Output::section("Resuming in-progress sync");
1443 println!();
1444 Output::info("Detected unfinished cherry-pick from previous sync");
1445 println!();
1446
1447 if self.git_repo.has_conflicts()? {
1449 let conflicted_files = self.git_repo.get_conflicted_files()?;
1450
1451 let result = RebaseResult {
1452 success: false,
1453 branch_mapping: HashMap::new(),
1454 conflicts: conflicted_files.clone(),
1455 new_commits: Vec::new(),
1456 error: Some(format!(
1457 "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1458 MANUAL CONFLICT RESOLUTION REQUIRED\n\
1459 =====================================\n\n\
1460 Conflicted files:\n{}\n\n\
1461 Step 1: Analyze conflicts\n\
1462 → Run: ca conflicts\n\
1463 → Shows detailed conflict analysis\n\n\
1464 Step 2: Resolve conflicts in your editor\n\
1465 → Open conflicted files and edit them\n\
1466 → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1467 → Keep the code you want\n\
1468 → Save the files\n\n\
1469 Step 3: Mark conflicts as resolved\n\
1470 → Run: git add <resolved-files>\n\
1471 → Or: git add -A (to stage all resolved files)\n\n\
1472 Step 4: Complete the sync\n\
1473 → Run: ca sync\n\
1474 → Cascade will continue from where it left off\n\n\
1475 Alternative: Abort and start over\n\
1476 → Run: git cherry-pick --abort\n\
1477 → Then: ca sync (starts fresh)",
1478 conflicted_files.len(),
1479 conflicted_files
1480 .iter()
1481 .map(|f| format!(" - {}", f))
1482 .collect::<Vec<_>>()
1483 .join("\n")
1484 )),
1485 summary: "Sync paused - conflicts need resolution".to_string(),
1486 };
1487
1488 return Ok(result);
1489 }
1490
1491 Output::info("Conflicts resolved, continuing cherry-pick...");
1493
1494 self.git_repo.stage_conflict_resolved_files()?;
1496
1497 let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1499 let commit_message = if cherry_pick_msg_file.exists() {
1500 std::fs::read_to_string(&cherry_pick_msg_file)
1501 .unwrap_or_else(|_| "Resolved conflicts".to_string())
1502 } else {
1503 "Resolved conflicts".to_string()
1504 };
1505
1506 match self.git_repo.commit(&commit_message) {
1507 Ok(_new_commit_id) => {
1508 Output::success("Cherry-pick completed");
1509
1510 if git_dir.join("CHERRY_PICK_HEAD").exists() {
1512 let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1513 }
1514 if cherry_pick_msg_file.exists() {
1515 let _ = std::fs::remove_file(&cherry_pick_msg_file);
1516 }
1517
1518 println!();
1519 Output::info("Continuing with rest of stack...");
1520 println!();
1521
1522 self.rebase_with_force_push(stack)
1525 }
1526 Err(e) => {
1527 let result = RebaseResult {
1528 success: false,
1529 branch_mapping: HashMap::new(),
1530 conflicts: Vec::new(),
1531 new_commits: Vec::new(),
1532 error: Some(format!(
1533 "Failed to complete cherry-pick: {}\n\n\
1534 This usually means:\n\
1535 - Git index is locked (another process accessing repo)\n\
1536 - File permissions issue\n\
1537 - Disk space issue\n\n\
1538 Recovery:\n\
1539 1. Check if another Git operation is running\n\
1540 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1541 3. Run 'git status' to check repo state\n\
1542 4. Retry 'ca sync' after fixing the issue\n\n\
1543 Or abort and start fresh:\n\
1544 → Run: git cherry-pick --abort\n\
1545 → Then: ca sync",
1546 e
1547 )),
1548 summary: "Failed to complete cherry-pick".to_string(),
1549 };
1550
1551 Ok(result)
1552 }
1553 }
1554 }
1555}
1556
1557impl RebaseResult {
1558 pub fn get_summary(&self) -> String {
1560 if self.success {
1561 format!("✅ {}", self.summary)
1562 } else {
1563 format!(
1564 "❌ Rebase failed: {}",
1565 self.error.as_deref().unwrap_or("Unknown error")
1566 )
1567 }
1568 }
1569
1570 pub fn has_conflicts(&self) -> bool {
1572 !self.conflicts.is_empty()
1573 }
1574
1575 pub fn success_count(&self) -> usize {
1577 self.new_commits.len()
1578 }
1579}
1580
1581#[cfg(test)]
1582mod tests {
1583 use super::*;
1584 use std::path::PathBuf;
1585 use std::process::Command;
1586 use tempfile::TempDir;
1587
1588 #[allow(dead_code)]
1589 fn create_test_repo() -> (TempDir, PathBuf) {
1590 let temp_dir = TempDir::new().unwrap();
1591 let repo_path = temp_dir.path().to_path_buf();
1592
1593 Command::new("git")
1595 .args(["init"])
1596 .current_dir(&repo_path)
1597 .output()
1598 .unwrap();
1599 Command::new("git")
1600 .args(["config", "user.name", "Test"])
1601 .current_dir(&repo_path)
1602 .output()
1603 .unwrap();
1604 Command::new("git")
1605 .args(["config", "user.email", "test@test.com"])
1606 .current_dir(&repo_path)
1607 .output()
1608 .unwrap();
1609
1610 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1612 Command::new("git")
1613 .args(["add", "."])
1614 .current_dir(&repo_path)
1615 .output()
1616 .unwrap();
1617 Command::new("git")
1618 .args(["commit", "-m", "Initial"])
1619 .current_dir(&repo_path)
1620 .output()
1621 .unwrap();
1622
1623 (temp_dir, repo_path)
1624 }
1625
1626 #[test]
1627 fn test_conflict_region_creation() {
1628 let region = ConflictRegion {
1629 start: 0,
1630 end: 50,
1631 start_line: 1,
1632 end_line: 3,
1633 our_content: "function test() {\n return true;\n}".to_string(),
1634 their_content: "function test() {\n return true;\n}".to_string(),
1635 };
1636
1637 assert_eq!(region.start_line, 1);
1638 assert_eq!(region.end_line, 3);
1639 assert!(region.our_content.contains("return true"));
1640 assert!(region.their_content.contains("return true"));
1641 }
1642
1643 #[test]
1644 fn test_rebase_strategies() {
1645 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1646 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1647 }
1648
1649 #[test]
1650 fn test_rebase_options() {
1651 let options = RebaseOptions::default();
1652 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1653 assert!(!options.interactive);
1654 assert!(options.auto_resolve);
1655 assert_eq!(options.max_retries, 3);
1656 }
1657
1658 #[test]
1659 fn test_cleanup_guard_tracks_branches() {
1660 let mut guard = TempBranchCleanupGuard::new();
1661 assert!(guard.branches.is_empty());
1662
1663 guard.add_branch("test-branch-1".to_string());
1664 guard.add_branch("test-branch-2".to_string());
1665
1666 assert_eq!(guard.branches.len(), 2);
1667 assert_eq!(guard.branches[0], "test-branch-1");
1668 assert_eq!(guard.branches[1], "test-branch-2");
1669 }
1670
1671 #[test]
1672 fn test_cleanup_guard_prevents_double_cleanup() {
1673 use std::process::Command;
1674 use tempfile::TempDir;
1675
1676 let temp_dir = TempDir::new().unwrap();
1678 let repo_path = temp_dir.path();
1679
1680 Command::new("git")
1681 .args(["init"])
1682 .current_dir(repo_path)
1683 .output()
1684 .unwrap();
1685
1686 Command::new("git")
1687 .args(["config", "user.name", "Test"])
1688 .current_dir(repo_path)
1689 .output()
1690 .unwrap();
1691
1692 Command::new("git")
1693 .args(["config", "user.email", "test@test.com"])
1694 .current_dir(repo_path)
1695 .output()
1696 .unwrap();
1697
1698 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1700 Command::new("git")
1701 .args(["add", "."])
1702 .current_dir(repo_path)
1703 .output()
1704 .unwrap();
1705 Command::new("git")
1706 .args(["commit", "-m", "initial"])
1707 .current_dir(repo_path)
1708 .output()
1709 .unwrap();
1710
1711 let git_repo = GitRepository::open(repo_path).unwrap();
1712
1713 git_repo.create_branch("test-temp", None).unwrap();
1715
1716 let mut guard = TempBranchCleanupGuard::new();
1717 guard.add_branch("test-temp".to_string());
1718
1719 guard.cleanup(&git_repo);
1721 assert!(guard.cleaned);
1722
1723 guard.cleanup(&git_repo);
1725 assert!(guard.cleaned);
1726 }
1727
1728 #[test]
1729 fn test_rebase_result() {
1730 let result = RebaseResult {
1731 success: true,
1732 branch_mapping: std::collections::HashMap::new(),
1733 conflicts: vec!["abc123".to_string()],
1734 new_commits: vec!["def456".to_string()],
1735 error: None,
1736 summary: "Test summary".to_string(),
1737 };
1738
1739 assert!(result.success);
1740 assert!(result.has_conflicts());
1741 assert_eq!(result.success_count(), 1);
1742 }
1743}