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, info, warn};
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 info!("๐งน 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 warn!("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 warn!(
133 "โ ๏ธ {} temporary branches were not cleaned up: {}",
134 self.branches.len(),
135 self.branches.join(", ")
136 );
137 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 if let Some(ref orig) = original_branch {
242 if orig == &target_base {
243 debug!(
244 "Original working branch is base branch '{}' - will skip working branch update",
245 orig
246 );
247 }
248 }
249
250 if !self.options.skip_pull.unwrap_or(false) {
253 if let Err(e) = self.pull_latest_changes(&target_base) {
254 Output::warning(format!("Could not pull latest changes: {}", e));
255 }
256 }
257
258 if let Err(e) = self.git_repo.reset_to_head() {
260 Output::warning(format!("Could not reset working directory: {}", e));
261 }
262
263 let mut current_base = target_base.clone();
264 let entry_count = stack.entries.len();
265 let mut temp_branches: Vec<String> = Vec::new(); let mut branches_to_push: Vec<(String, String)> = Vec::new(); if entry_count == 0 {
270 println!(); Output::info("Stack has no entries yet");
272 Output::tip("Use 'ca push' to add commits to this stack");
273
274 result.summary = "Stack is empty".to_string();
275
276 println!(); Output::success(&result.summary);
279
280 self.stack_manager.save_to_disk()?;
282 return Ok(result);
283 }
284
285 println!(); let plural = if entry_count == 1 { "entry" } else { "entries" };
287 println!("Rebasing {} {}...", entry_count, plural);
288
289 for (index, entry) in stack.entries.iter().enumerate() {
291 let original_branch = &entry.branch;
292
293 if self
296 .git_repo
297 .is_commit_based_on(&entry.commit_hash, ¤t_base)
298 .unwrap_or(false)
299 {
300 tracing::debug!(
301 "Entry '{}' is already correctly based on '{}', skipping rebase",
302 original_branch,
303 current_base
304 );
305
306 let tree_char = if index + 1 == entry_count {
308 "โโ"
309 } else {
310 "โโ"
311 };
312
313 if let Some(pr_num) = &entry.pull_request_id {
314 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
315 branches_to_push.push((original_branch.clone(), pr_num.clone()));
316 } else {
317 println!(" {} {} (not submitted)", tree_char, original_branch);
318 }
319
320 result
321 .branch_mapping
322 .insert(original_branch.clone(), original_branch.clone());
323
324 current_base = original_branch.clone();
326 continue;
327 }
328
329 let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
332 temp_branches.push(temp_branch.clone()); self.git_repo
334 .create_branch(&temp_branch, Some(¤t_base))?;
335 self.git_repo.checkout_branch_silent(&temp_branch)?;
336
337 match self.cherry_pick_commit(&entry.commit_hash) {
339 Ok(new_commit_hash) => {
340 result.new_commits.push(new_commit_hash.clone());
341
342 let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
344
345 self.git_repo
348 .update_branch_to_commit(original_branch, &rebased_commit_id)?;
349
350 let tree_char = if index + 1 == entry_count {
352 "โโ"
353 } else {
354 "โโ"
355 };
356
357 if let Some(pr_num) = &entry.pull_request_id {
358 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
359 branches_to_push.push((original_branch.clone(), pr_num.clone()));
360 } else {
361 println!(" {} {} (not submitted)", tree_char, original_branch);
362 }
363
364 result
365 .branch_mapping
366 .insert(original_branch.clone(), original_branch.clone());
367
368 self.update_stack_entry(
370 stack.id,
371 &entry.id,
372 original_branch,
373 &rebased_commit_id,
374 )?;
375
376 current_base = original_branch.clone();
378 }
379 Err(e) => {
380 result.conflicts.push(entry.commit_hash.clone());
381
382 if !self.options.auto_resolve {
383 println!(); Output::error(e.to_string());
385 result.success = false;
386 result.error = Some(format!(
387 "Conflict in {}: {}\n\n\
388 MANUAL CONFLICT RESOLUTION REQUIRED\n\
389 =====================================\n\n\
390 Step 1: Analyze conflicts\n\
391 โ Run: ca conflicts\n\
392 โ This shows which conflicts are in which files\n\n\
393 Step 2: Resolve conflicts in your editor\n\
394 โ Open conflicted files and edit them\n\
395 โ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
396 โ Keep the code you want\n\
397 โ Save the files\n\n\
398 Step 3: Mark conflicts as resolved\n\
399 โ Run: git add <resolved-files>\n\
400 โ Or: git add -A (to stage all resolved files)\n\n\
401 Step 4: Complete the sync\n\
402 โ Run: ca sync\n\
403 โ Cascade will detect resolved conflicts and continue\n\n\
404 Alternative: Abort and start over\n\
405 โ Run: git cherry-pick --abort\n\
406 โ Then: ca sync (starts fresh)\n\n\
407 TIP: Enable auto-resolution for simple conflicts:\n\
408 โ Run: ca sync --auto-resolve\n\
409 โ Only complex conflicts will require manual resolution",
410 entry.commit_hash, e
411 ));
412 break;
413 }
414
415 match self.auto_resolve_conflicts(&entry.commit_hash) {
417 Ok(fully_resolved) => {
418 if !fully_resolved {
419 result.success = false;
420 result.error = Some(format!(
421 "Conflicts in commit {}\n\n\
422 To resolve:\n\
423 1. Fix conflicts in your editor\n\
424 2. Run: ca sync --continue\n\n\
425 Or abort:\n\
426 โ Run: git cherry-pick --abort",
427 &entry.commit_hash[..8]
428 ));
429 break;
430 }
431
432 let commit_message =
434 format!("Auto-resolved conflicts in {}", &entry.commit_hash[..8]);
435
436 debug!("Checking staged files before commit");
438 let staged_files = self.git_repo.get_staged_files()?;
439
440 if staged_files.is_empty() {
441 result.success = false;
445 result.error = Some(format!(
446 "CRITICAL BUG DETECTED: Cherry-pick failed but no files were staged!\n\n\
447 This indicates a Git state issue after cherry-pick failure.\n\n\
448 RECOVERY STEPS:\n\
449 ================\n\n\
450 Step 1: Check Git status\n\
451 โ Run: git status\n\
452 โ Check if there are any changes in working directory\n\n\
453 Step 2: Check for conflicts manually\n\
454 โ Run: git diff\n\
455 โ Look for conflict markers (<<<<<<, ======, >>>>>>)\n\n\
456 Step 3: Abort the cherry-pick\n\
457 โ Run: git cherry-pick --abort\n\n\
458 Step 4: Report this bug\n\
459 โ This is a known issue we're investigating\n\
460 โ Cherry-pick failed for commit {}\n\
461 โ But Git reported no conflicts and no staged files\n\n\
462 Step 5: Try manual resolution\n\
463 โ Run: ca sync --no-auto-resolve\n\
464 โ Manually resolve conflicts as they appear",
465 &entry.commit_hash[..8]
466 ));
467 warn!("CRITICAL - No files staged after auto-resolve!");
468 break;
469 }
470
471 debug!("{} files staged", staged_files.len());
472
473 match self.git_repo.commit(&commit_message) {
474 Ok(new_commit_id) => {
475 debug!(
476 "Created commit {} with message '{}'",
477 &new_commit_id[..8],
478 commit_message
479 );
480
481 Output::success("Auto-resolved conflicts");
482 result.new_commits.push(new_commit_id.clone());
483 let rebased_commit_id = new_commit_id;
484
485 self.git_repo.update_branch_to_commit(
487 original_branch,
488 &rebased_commit_id,
489 )?;
490
491 let tree_char = if index + 1 == entry_count {
493 "โโ"
494 } else {
495 "โโ"
496 };
497
498 if let Some(pr_num) = &entry.pull_request_id {
499 println!(
500 " {} {} (PR #{})",
501 tree_char, original_branch, pr_num
502 );
503 branches_to_push
504 .push((original_branch.clone(), pr_num.clone()));
505 } else {
506 println!(
507 " {} {} (not submitted)",
508 tree_char, original_branch
509 );
510 }
511
512 result
513 .branch_mapping
514 .insert(original_branch.clone(), original_branch.clone());
515
516 self.update_stack_entry(
518 stack.id,
519 &entry.id,
520 original_branch,
521 &rebased_commit_id,
522 )?;
523
524 current_base = original_branch.clone();
526 }
527 Err(commit_err) => {
528 result.success = false;
529 result.error = Some(format!(
530 "Could not commit auto-resolved conflicts: {}\n\n\
531 This usually means:\n\
532 - Git index is locked (another process accessing repo)\n\
533 - File permissions issue\n\
534 - Disk space issue\n\n\
535 Recovery:\n\
536 1. Check if another Git operation is running\n\
537 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
538 3. Run 'git status' to check repo state\n\
539 4. Retry 'ca sync' after fixing the issue",
540 commit_err
541 ));
542 break;
543 }
544 }
545 }
546 Err(resolve_err) => {
547 result.success = false;
548 result.error = Some(format!(
549 "Could not resolve conflicts: {}\n\n\
550 Recovery:\n\
551 1. Check repo state: 'git status'\n\
552 2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
553 3. Remove any lock files: 'rm -f .git/index.lock'\n\
554 4. Retry 'ca sync'",
555 resolve_err
556 ));
557 break;
558 }
559 }
560 }
561 }
562 }
563
564 if !temp_branches.is_empty() {
567 if let Err(e) = self.git_repo.checkout_branch_unsafe(&target_base) {
570 debug!("Could not checkout base for cleanup: {}", e);
571 } else {
574 for temp_branch in &temp_branches {
576 if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
577 debug!("Could not delete temp branch {}: {}", temp_branch, e);
578 }
579 }
580 }
581 }
582
583 let pushed_count = branches_to_push.len();
586 let skipped_count = entry_count - pushed_count;
587
588 if !branches_to_push.is_empty() {
589 for (branch_name, _pr_num) in &branches_to_push {
592 match self.git_repo.force_push_single_branch_auto(branch_name) {
593 Ok(_) => {
594 debug!("Pushed {} successfully", branch_name);
595 }
596 Err(e) => {
597 Output::warning(format!("Could not push '{}': {}", branch_name, e));
598 }
600 }
601 }
602 }
603
604 if let Some(ref orig_branch) = original_branch {
607 if orig_branch != &target_base {
609 if let Some(last_entry) = stack.entries.last() {
611 let top_branch = &last_entry.branch;
612
613 if let Ok(top_commit) = self.git_repo.get_branch_head(top_branch) {
615 debug!(
616 "Updating working branch '{}' to match top of stack ({})",
617 orig_branch,
618 &top_commit[..8]
619 );
620
621 if let Err(e) = self
622 .git_repo
623 .update_branch_to_commit(orig_branch, &top_commit)
624 {
625 Output::warning(format!(
626 "Could not update working branch '{}' to top of stack: {}",
627 orig_branch, e
628 ));
629 }
630 }
631 }
632
633 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
636 debug!(
637 "Could not return to original branch '{}': {}",
638 orig_branch, e
639 );
640 }
642 } else {
643 debug!(
646 "Skipping working branch update - user was on base branch '{}'",
647 orig_branch
648 );
649 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
650 debug!("Could not return to base branch '{}': {}", orig_branch, e);
651 }
652 }
653 }
654
655 result.summary = if pushed_count > 0 {
657 let pr_plural = if pushed_count == 1 { "" } else { "s" };
658 let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
659
660 if skipped_count > 0 {
661 format!(
662 "{} {} rebased ({} PR{} updated, {} not yet submitted)",
663 entry_count, entry_plural, pushed_count, pr_plural, skipped_count
664 )
665 } else {
666 format!(
667 "{} {} rebased ({} PR{} updated)",
668 entry_count, entry_plural, pushed_count, pr_plural
669 )
670 }
671 } else {
672 let plural = if entry_count == 1 { "entry" } else { "entries" };
673 format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
674 };
675
676 println!(); if result.success {
679 Output::success(&result.summary);
680 } else {
681 let error_msg = result
683 .error
684 .as_deref()
685 .unwrap_or("Rebase failed for unknown reason");
686 Output::error(error_msg);
687 }
688
689 self.stack_manager.save_to_disk()?;
691
692 if !result.success {
695 let detailed_error = result.error.as_deref().unwrap_or("Rebase failed");
697 return Err(CascadeError::Branch(detailed_error.to_string()));
698 }
699
700 Ok(result)
701 }
702
703 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
705 info!("Starting interactive rebase for stack '{}'", stack.name);
706
707 let mut result = RebaseResult {
708 success: true,
709 branch_mapping: HashMap::new(),
710 conflicts: Vec::new(),
711 new_commits: Vec::new(),
712 error: None,
713 summary: String::new(),
714 };
715
716 println!("Interactive Rebase for Stack: {}", stack.name);
717 println!(" Base branch: {}", stack.base_branch);
718 println!(" Entries: {}", stack.entries.len());
719
720 if self.options.interactive {
721 println!("\nChoose action for each commit:");
722 println!(" (p)ick - apply the commit");
723 println!(" (s)kip - skip this commit");
724 println!(" (e)dit - edit the commit message");
725 println!(" (q)uit - abort the rebase");
726 }
727
728 for entry in &stack.entries {
731 println!(
732 " {} {} - {}",
733 entry.short_hash(),
734 entry.branch,
735 entry.short_message(50)
736 );
737
738 match self.cherry_pick_commit(&entry.commit_hash) {
740 Ok(new_commit) => result.new_commits.push(new_commit),
741 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
742 }
743 }
744
745 result.summary = format!(
746 "Interactive rebase processed {} commits",
747 stack.entries.len()
748 );
749 Ok(result)
750 }
751
752 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
754 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
756
757 if let Ok(staged_files) = self.git_repo.get_staged_files() {
759 if !staged_files.is_empty() {
760 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
762 let _ = self.git_repo.commit_staged_changes(&cleanup_message);
763 }
764 }
765
766 Ok(new_commit_hash)
767 }
768
769 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
771 debug!("Starting auto-resolve for commit {}", commit_hash);
772
773 let has_conflicts = self.git_repo.has_conflicts()?;
775 debug!("has_conflicts() = {}", has_conflicts);
776
777 let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
779 let cherry_pick_in_progress = cherry_pick_head.exists();
780
781 if !has_conflicts {
782 debug!("No conflicts detected by Git index");
783
784 if cherry_pick_in_progress {
786 warn!("CHERRY_PICK_HEAD exists but no conflicts in index - aborting cherry-pick");
787
788 let _ = std::process::Command::new("git")
790 .args(["cherry-pick", "--abort"])
791 .current_dir(self.git_repo.path())
792 .output();
793
794 return Err(CascadeError::Branch(format!(
795 "Cherry-pick failed for {} but Git index shows no conflicts. \
796 This usually means the cherry-pick was aborted or failed in an unexpected way. \
797 Please try manual resolution.",
798 &commit_hash[..8]
799 )));
800 }
801
802 return Ok(true);
803 }
804
805 let conflicted_files = self.git_repo.get_conflicted_files()?;
806
807 if conflicted_files.is_empty() {
808 debug!("Conflicted files list is empty");
809 return Ok(true);
810 }
811
812 debug!(
813 "Found conflicts in {} files: {:?}",
814 conflicted_files.len(),
815 conflicted_files
816 );
817
818 let analysis = self
820 .conflict_analyzer
821 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
822
823 debug!(
824 "Conflict analysis: {} total conflicts, {} auto-resolvable",
825 analysis.total_conflicts, analysis.auto_resolvable_count
826 );
827
828 for recommendation in &analysis.recommendations {
830 debug!("{}", recommendation);
831 }
832
833 let mut resolved_count = 0;
834 let mut resolved_files = Vec::new(); let mut failed_files = Vec::new();
836
837 for file_analysis in &analysis.files {
838 debug!(
839 "Processing file: {} (auto_resolvable: {}, conflicts: {})",
840 file_analysis.file_path,
841 file_analysis.auto_resolvable,
842 file_analysis.conflicts.len()
843 );
844
845 if file_analysis.auto_resolvable {
846 match self.resolve_file_conflicts_enhanced(
847 &file_analysis.file_path,
848 &file_analysis.conflicts,
849 ) {
850 Ok(ConflictResolution::Resolved) => {
851 resolved_count += 1;
852 resolved_files.push(file_analysis.file_path.clone());
853 debug!("Successfully resolved {}", file_analysis.file_path);
854 }
855 Ok(ConflictResolution::TooComplex) => {
856 debug!(
857 "{} too complex for auto-resolution",
858 file_analysis.file_path
859 );
860 failed_files.push(file_analysis.file_path.clone());
861 }
862 Err(e) => {
863 debug!("Failed to resolve {}: {}", file_analysis.file_path, e);
864 failed_files.push(file_analysis.file_path.clone());
865 }
866 }
867 } else {
868 failed_files.push(file_analysis.file_path.clone());
869 debug!(
870 "{} requires manual resolution ({} conflicts)",
871 file_analysis.file_path,
872 file_analysis.conflicts.len()
873 );
874 }
875 }
876
877 if resolved_count > 0 {
878 debug!(
879 "Resolved {}/{} files",
880 resolved_count,
881 conflicted_files.len()
882 );
883 debug!("Resolved files: {:?}", resolved_files);
884
885 let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
888 debug!("Staging {} files", file_paths.len());
889 self.git_repo.stage_files(&file_paths)?;
890 debug!("Files staged successfully");
891 } else {
892 debug!("No files were resolved (resolved_count = 0)");
893 }
894
895 let all_resolved = failed_files.is_empty();
897
898 debug!(
899 "all_resolved = {}, failed_files = {:?}",
900 all_resolved, failed_files
901 );
902
903 if !all_resolved {
904 debug!("{} files still need manual resolution", failed_files.len());
905 }
906
907 debug!("Returning all_resolved = {}", all_resolved);
908 Ok(all_resolved)
909 }
910
911 fn resolve_file_conflicts_enhanced(
913 &self,
914 file_path: &str,
915 conflicts: &[crate::git::ConflictRegion],
916 ) -> Result<ConflictResolution> {
917 let repo_path = self.git_repo.path();
918 let full_path = repo_path.join(file_path);
919
920 let mut content = std::fs::read_to_string(&full_path)
922 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
923
924 if conflicts.is_empty() {
925 return Ok(ConflictResolution::Resolved);
926 }
927
928 info!(
929 "Resolving {} conflicts in {} using enhanced analysis",
930 conflicts.len(),
931 file_path
932 );
933
934 let mut any_resolved = false;
935
936 for conflict in conflicts.iter().rev() {
938 match self.resolve_single_conflict_enhanced(conflict) {
939 Ok(Some(resolution)) => {
940 let before = &content[..conflict.start_pos];
942 let after = &content[conflict.end_pos..];
943 content = format!("{before}{resolution}{after}");
944 any_resolved = true;
945 debug!(
946 "โ
Resolved {} conflict at lines {}-{} in {}",
947 format!("{:?}", conflict.conflict_type).to_lowercase(),
948 conflict.start_line,
949 conflict.end_line,
950 file_path
951 );
952 }
953 Ok(None) => {
954 debug!(
955 "โ ๏ธ {} conflict at lines {}-{} in {} requires manual resolution",
956 format!("{:?}", conflict.conflict_type).to_lowercase(),
957 conflict.start_line,
958 conflict.end_line,
959 file_path
960 );
961 return Ok(ConflictResolution::TooComplex);
962 }
963 Err(e) => {
964 debug!("โ Failed to resolve conflict in {}: {}", file_path, e);
965 return Ok(ConflictResolution::TooComplex);
966 }
967 }
968 }
969
970 if any_resolved {
971 let remaining_conflicts = self.parse_conflict_markers(&content)?;
973
974 if remaining_conflicts.is_empty() {
975 debug!(
976 "All conflicts resolved in {}, content length: {} bytes",
977 file_path,
978 content.len()
979 );
980
981 if content.trim().is_empty() {
983 warn!(
984 "SAFETY CHECK: Resolved content for {} is empty! Aborting auto-resolution.",
985 file_path
986 );
987 return Ok(ConflictResolution::TooComplex);
988 }
989
990 let backup_path = full_path.with_extension("cascade-backup");
992 if let Ok(original_content) = std::fs::read_to_string(&full_path) {
993 debug!(
994 "Backup for {} (original: {} bytes, resolved: {} bytes)",
995 file_path,
996 original_content.len(),
997 content.len()
998 );
999 let _ = std::fs::write(&backup_path, original_content);
1000 }
1001
1002 crate::utils::atomic_file::write_string(&full_path, &content)?;
1004
1005 debug!("Wrote {} bytes to {}", content.len(), file_path);
1006 return Ok(ConflictResolution::Resolved);
1007 } else {
1008 info!(
1009 "Partially resolved conflicts in {} ({} remaining)",
1010 file_path,
1011 remaining_conflicts.len()
1012 );
1013 }
1014 }
1015
1016 Ok(ConflictResolution::TooComplex)
1017 }
1018
1019 #[allow(dead_code)]
1021 fn count_whitespace_consistency(content: &str) -> usize {
1022 let mut inconsistencies = 0;
1023 let lines: Vec<&str> = content.lines().collect();
1024
1025 for line in &lines {
1026 if line.contains('\t') && line.contains(' ') {
1028 inconsistencies += 1;
1029 }
1030 }
1031
1032 lines.len().saturating_sub(inconsistencies)
1034 }
1035
1036 fn resolve_single_conflict_enhanced(
1038 &self,
1039 conflict: &crate::git::ConflictRegion,
1040 ) -> Result<Option<String>> {
1041 debug!(
1042 "Resolving {} conflict in {} (lines {}-{})",
1043 format!("{:?}", conflict.conflict_type).to_lowercase(),
1044 conflict.file_path,
1045 conflict.start_line,
1046 conflict.end_line
1047 );
1048
1049 use crate::git::ConflictType;
1050
1051 match conflict.conflict_type {
1052 ConflictType::Whitespace => {
1053 let our_normalized = conflict
1056 .our_content
1057 .split_whitespace()
1058 .collect::<Vec<_>>()
1059 .join(" ");
1060 let their_normalized = conflict
1061 .their_content
1062 .split_whitespace()
1063 .collect::<Vec<_>>()
1064 .join(" ");
1065
1066 if our_normalized == their_normalized {
1067 Ok(Some(conflict.their_content.clone()))
1072 } else {
1073 debug!(
1075 "Whitespace conflict has content differences - requires manual resolution"
1076 );
1077 Ok(None)
1078 }
1079 }
1080 ConflictType::LineEnding => {
1081 let normalized = conflict
1083 .our_content
1084 .replace("\r\n", "\n")
1085 .replace('\r', "\n");
1086 Ok(Some(normalized))
1087 }
1088 ConflictType::PureAddition => {
1089 if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1093 Ok(Some(conflict.their_content.clone()))
1095 } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1096 Ok(Some(String::new()))
1098 } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1099 Ok(Some(String::new()))
1101 } else {
1102 debug!(
1108 "PureAddition conflict has content on both sides - requires manual resolution"
1109 );
1110 Ok(None)
1111 }
1112 }
1113 ConflictType::ImportMerge => {
1114 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1119 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1120
1121 let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1123 let trimmed = line.trim();
1124 trimmed.starts_with("import ")
1125 || trimmed.starts_with("from ")
1126 || trimmed.starts_with("use ")
1127 || trimmed.starts_with("#include")
1128 || trimmed.is_empty()
1129 });
1130
1131 if !all_simple {
1132 debug!("ImportMerge contains non-import lines - requires manual resolution");
1133 return Ok(None);
1134 }
1135
1136 let mut all_imports: Vec<&str> = our_lines
1138 .into_iter()
1139 .chain(their_lines)
1140 .filter(|line| !line.trim().is_empty())
1141 .collect();
1142 all_imports.sort();
1143 all_imports.dedup();
1144 Ok(Some(all_imports.join("\n")))
1145 }
1146 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1147 Ok(None)
1149 }
1150 }
1151 }
1152
1153 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1155 let lines: Vec<&str> = content.lines().collect();
1156 let mut conflicts = Vec::new();
1157 let mut i = 0;
1158
1159 while i < lines.len() {
1160 if lines[i].starts_with("<<<<<<<") {
1161 let start_line = i + 1;
1163 let mut separator_line = None;
1164 let mut end_line = None;
1165
1166 for (j, line) in lines.iter().enumerate().skip(i + 1) {
1168 if line.starts_with("=======") {
1169 separator_line = Some(j + 1);
1170 } else if line.starts_with(">>>>>>>") {
1171 end_line = Some(j + 1);
1172 break;
1173 }
1174 }
1175
1176 if let (Some(sep), Some(end)) = (separator_line, end_line) {
1177 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1179 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1180
1181 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1182 let their_content = lines[sep..(end - 1)].join("\n");
1183
1184 conflicts.push(ConflictRegion {
1185 start: start_pos,
1186 end: end_pos,
1187 start_line,
1188 end_line: end,
1189 our_content,
1190 their_content,
1191 });
1192
1193 i = end;
1194 } else {
1195 i += 1;
1196 }
1197 } else {
1198 i += 1;
1199 }
1200 }
1201
1202 Ok(conflicts)
1203 }
1204
1205 fn update_stack_entry(
1208 &mut self,
1209 stack_id: Uuid,
1210 entry_id: &Uuid,
1211 _new_branch: &str,
1212 new_commit_hash: &str,
1213 ) -> Result<()> {
1214 debug!(
1215 "Updating entry {} in stack {} with new commit {}",
1216 entry_id, stack_id, new_commit_hash
1217 );
1218
1219 let stack = self
1221 .stack_manager
1222 .get_stack_mut(&stack_id)
1223 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1224
1225 if let Some(entry) = stack.entries.iter_mut().find(|e| e.id == *entry_id) {
1227 debug!(
1228 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch '{}')",
1229 entry_id, entry.commit_hash, new_commit_hash, entry.branch
1230 );
1231
1232 entry.commit_hash = new_commit_hash.to_string();
1235
1236 debug!(
1239 "Successfully updated entry {} in stack {}",
1240 entry_id, stack_id
1241 );
1242 Ok(())
1243 } else {
1244 Err(CascadeError::config(format!(
1245 "Entry {entry_id} not found in stack {stack_id}"
1246 )))
1247 }
1248 }
1249
1250 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1252 info!("Pulling latest changes for branch {}", branch);
1253
1254 match self.git_repo.fetch() {
1256 Ok(_) => {
1257 debug!("Fetch successful");
1258 match self.git_repo.pull(branch) {
1260 Ok(_) => {
1261 info!("Pull completed successfully for {}", branch);
1262 Ok(())
1263 }
1264 Err(e) => {
1265 warn!("Pull failed for {}: {}", branch, e);
1266 Ok(())
1268 }
1269 }
1270 }
1271 Err(e) => {
1272 warn!("Fetch failed: {}", e);
1273 Ok(())
1275 }
1276 }
1277 }
1278
1279 pub fn is_rebase_in_progress(&self) -> bool {
1281 let git_dir = self.git_repo.path().join(".git");
1283 git_dir.join("REBASE_HEAD").exists()
1284 || git_dir.join("rebase-merge").exists()
1285 || git_dir.join("rebase-apply").exists()
1286 }
1287
1288 pub fn abort_rebase(&self) -> Result<()> {
1290 info!("Aborting rebase operation");
1291
1292 let git_dir = self.git_repo.path().join(".git");
1293
1294 if git_dir.join("REBASE_HEAD").exists() {
1296 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1297 CascadeError::Git(git2::Error::from_str(&format!(
1298 "Failed to clean rebase state: {e}"
1299 )))
1300 })?;
1301 }
1302
1303 if git_dir.join("rebase-merge").exists() {
1304 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1305 CascadeError::Git(git2::Error::from_str(&format!(
1306 "Failed to clean rebase-merge: {e}"
1307 )))
1308 })?;
1309 }
1310
1311 if git_dir.join("rebase-apply").exists() {
1312 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1313 CascadeError::Git(git2::Error::from_str(&format!(
1314 "Failed to clean rebase-apply: {e}"
1315 )))
1316 })?;
1317 }
1318
1319 info!("Rebase aborted successfully");
1320 Ok(())
1321 }
1322
1323 pub fn continue_rebase(&self) -> Result<()> {
1325 info!("Continuing rebase operation");
1326
1327 if self.git_repo.has_conflicts()? {
1329 return Err(CascadeError::branch(
1330 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1331 ));
1332 }
1333
1334 self.git_repo.stage_conflict_resolved_files()?;
1336
1337 info!("Rebase continued successfully");
1338 Ok(())
1339 }
1340
1341 fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1343 let git_dir = self.git_repo.path().join(".git");
1344 Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1345 }
1346
1347 fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1349 use crate::cli::output::Output;
1350
1351 let git_dir = self.git_repo.path().join(".git");
1352
1353 Output::section("Resuming in-progress sync");
1354 println!();
1355 Output::info("Detected unfinished cherry-pick from previous sync");
1356 println!();
1357
1358 if self.git_repo.has_conflicts()? {
1360 let conflicted_files = self.git_repo.get_conflicted_files()?;
1361
1362 let result = RebaseResult {
1363 success: false,
1364 branch_mapping: HashMap::new(),
1365 conflicts: conflicted_files.clone(),
1366 new_commits: Vec::new(),
1367 error: Some(format!(
1368 "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1369 MANUAL CONFLICT RESOLUTION REQUIRED\n\
1370 =====================================\n\n\
1371 Conflicted files:\n{}\n\n\
1372 Step 1: Analyze conflicts\n\
1373 โ Run: ca conflicts\n\
1374 โ Shows detailed conflict analysis\n\n\
1375 Step 2: Resolve conflicts in your editor\n\
1376 โ Open conflicted files and edit them\n\
1377 โ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1378 โ Keep the code you want\n\
1379 โ Save the files\n\n\
1380 Step 3: Mark conflicts as resolved\n\
1381 โ Run: git add <resolved-files>\n\
1382 โ Or: git add -A (to stage all resolved files)\n\n\
1383 Step 4: Complete the sync\n\
1384 โ Run: ca sync\n\
1385 โ Cascade will continue from where it left off\n\n\
1386 Alternative: Abort and start over\n\
1387 โ Run: git cherry-pick --abort\n\
1388 โ Then: ca sync (starts fresh)",
1389 conflicted_files.len(),
1390 conflicted_files
1391 .iter()
1392 .map(|f| format!(" - {}", f))
1393 .collect::<Vec<_>>()
1394 .join("\n")
1395 )),
1396 summary: "Sync paused - conflicts need resolution".to_string(),
1397 };
1398
1399 return Ok(result);
1400 }
1401
1402 Output::info("Conflicts resolved, continuing cherry-pick...");
1404
1405 self.git_repo.stage_conflict_resolved_files()?;
1407
1408 let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1410 let commit_message = if cherry_pick_msg_file.exists() {
1411 std::fs::read_to_string(&cherry_pick_msg_file)
1412 .unwrap_or_else(|_| "Resolved conflicts".to_string())
1413 } else {
1414 "Resolved conflicts".to_string()
1415 };
1416
1417 match self.git_repo.commit(&commit_message) {
1418 Ok(_new_commit_id) => {
1419 Output::success("Cherry-pick completed");
1420
1421 if git_dir.join("CHERRY_PICK_HEAD").exists() {
1423 let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1424 }
1425 if cherry_pick_msg_file.exists() {
1426 let _ = std::fs::remove_file(&cherry_pick_msg_file);
1427 }
1428
1429 println!();
1430 Output::info("Continuing with rest of stack...");
1431 println!();
1432
1433 self.rebase_with_force_push(stack)
1436 }
1437 Err(e) => {
1438 let result = RebaseResult {
1439 success: false,
1440 branch_mapping: HashMap::new(),
1441 conflicts: Vec::new(),
1442 new_commits: Vec::new(),
1443 error: Some(format!(
1444 "Failed to complete cherry-pick: {}\n\n\
1445 This usually means:\n\
1446 - Git index is locked (another process accessing repo)\n\
1447 - File permissions issue\n\
1448 - Disk space issue\n\n\
1449 Recovery:\n\
1450 1. Check if another Git operation is running\n\
1451 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1452 3. Run 'git status' to check repo state\n\
1453 4. Retry 'ca sync' after fixing the issue\n\n\
1454 Or abort and start fresh:\n\
1455 โ Run: git cherry-pick --abort\n\
1456 โ Then: ca sync",
1457 e
1458 )),
1459 summary: "Failed to complete cherry-pick".to_string(),
1460 };
1461
1462 Ok(result)
1463 }
1464 }
1465 }
1466}
1467
1468impl RebaseResult {
1469 pub fn get_summary(&self) -> String {
1471 if self.success {
1472 format!("โ
{}", self.summary)
1473 } else {
1474 format!(
1475 "โ Rebase failed: {}",
1476 self.error.as_deref().unwrap_or("Unknown error")
1477 )
1478 }
1479 }
1480
1481 pub fn has_conflicts(&self) -> bool {
1483 !self.conflicts.is_empty()
1484 }
1485
1486 pub fn success_count(&self) -> usize {
1488 self.new_commits.len()
1489 }
1490}
1491
1492#[cfg(test)]
1493mod tests {
1494 use super::*;
1495 use std::path::PathBuf;
1496 use std::process::Command;
1497 use tempfile::TempDir;
1498
1499 #[allow(dead_code)]
1500 fn create_test_repo() -> (TempDir, PathBuf) {
1501 let temp_dir = TempDir::new().unwrap();
1502 let repo_path = temp_dir.path().to_path_buf();
1503
1504 Command::new("git")
1506 .args(["init"])
1507 .current_dir(&repo_path)
1508 .output()
1509 .unwrap();
1510 Command::new("git")
1511 .args(["config", "user.name", "Test"])
1512 .current_dir(&repo_path)
1513 .output()
1514 .unwrap();
1515 Command::new("git")
1516 .args(["config", "user.email", "test@test.com"])
1517 .current_dir(&repo_path)
1518 .output()
1519 .unwrap();
1520
1521 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1523 Command::new("git")
1524 .args(["add", "."])
1525 .current_dir(&repo_path)
1526 .output()
1527 .unwrap();
1528 Command::new("git")
1529 .args(["commit", "-m", "Initial"])
1530 .current_dir(&repo_path)
1531 .output()
1532 .unwrap();
1533
1534 (temp_dir, repo_path)
1535 }
1536
1537 #[test]
1538 fn test_conflict_region_creation() {
1539 let region = ConflictRegion {
1540 start: 0,
1541 end: 50,
1542 start_line: 1,
1543 end_line: 3,
1544 our_content: "function test() {\n return true;\n}".to_string(),
1545 their_content: "function test() {\n return true;\n}".to_string(),
1546 };
1547
1548 assert_eq!(region.start_line, 1);
1549 assert_eq!(region.end_line, 3);
1550 assert!(region.our_content.contains("return true"));
1551 assert!(region.their_content.contains("return true"));
1552 }
1553
1554 #[test]
1555 fn test_rebase_strategies() {
1556 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1557 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1558 }
1559
1560 #[test]
1561 fn test_rebase_options() {
1562 let options = RebaseOptions::default();
1563 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1564 assert!(!options.interactive);
1565 assert!(options.auto_resolve);
1566 assert_eq!(options.max_retries, 3);
1567 }
1568
1569 #[test]
1570 fn test_cleanup_guard_tracks_branches() {
1571 let mut guard = TempBranchCleanupGuard::new();
1572 assert!(guard.branches.is_empty());
1573
1574 guard.add_branch("test-branch-1".to_string());
1575 guard.add_branch("test-branch-2".to_string());
1576
1577 assert_eq!(guard.branches.len(), 2);
1578 assert_eq!(guard.branches[0], "test-branch-1");
1579 assert_eq!(guard.branches[1], "test-branch-2");
1580 }
1581
1582 #[test]
1583 fn test_cleanup_guard_prevents_double_cleanup() {
1584 use std::process::Command;
1585 use tempfile::TempDir;
1586
1587 let temp_dir = TempDir::new().unwrap();
1589 let repo_path = temp_dir.path();
1590
1591 Command::new("git")
1592 .args(["init"])
1593 .current_dir(repo_path)
1594 .output()
1595 .unwrap();
1596
1597 Command::new("git")
1598 .args(["config", "user.name", "Test"])
1599 .current_dir(repo_path)
1600 .output()
1601 .unwrap();
1602
1603 Command::new("git")
1604 .args(["config", "user.email", "test@test.com"])
1605 .current_dir(repo_path)
1606 .output()
1607 .unwrap();
1608
1609 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1611 Command::new("git")
1612 .args(["add", "."])
1613 .current_dir(repo_path)
1614 .output()
1615 .unwrap();
1616 Command::new("git")
1617 .args(["commit", "-m", "initial"])
1618 .current_dir(repo_path)
1619 .output()
1620 .unwrap();
1621
1622 let git_repo = GitRepository::open(repo_path).unwrap();
1623
1624 git_repo.create_branch("test-temp", None).unwrap();
1626
1627 let mut guard = TempBranchCleanupGuard::new();
1628 guard.add_branch("test-temp".to_string());
1629
1630 guard.cleanup(&git_repo);
1632 assert!(guard.cleaned);
1633
1634 guard.cleanup(&git_repo);
1636 assert!(guard.cleaned);
1637 }
1638
1639 #[test]
1640 fn test_rebase_result() {
1641 let result = RebaseResult {
1642 success: true,
1643 branch_mapping: std::collections::HashMap::new(),
1644 conflicts: vec!["abc123".to_string()],
1645 new_commits: vec!["def456".to_string()],
1646 error: None,
1647 summary: "Test summary".to_string(),
1648 };
1649
1650 assert!(result.success);
1651 assert!(result.has_conflicts());
1652 assert_eq!(result.success_count(), 1);
1653 }
1654}