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(working_head), Ok(top_commit)) = (
616 self.git_repo.get_branch_head(orig_branch),
617 self.git_repo.get_branch_head(top_branch),
618 ) {
619 if working_head != top_commit {
621 if let Ok(commits) = self
623 .git_repo
624 .get_commits_between(&top_commit, &working_head)
625 {
626 if !commits.is_empty() {
627 Output::error(format!(
629 "Cannot sync: Working branch '{}' has {} commit(s) not in the stack",
630 orig_branch,
631 commits.len()
632 ));
633 println!();
634 Output::sub_item("These commits would be lost if we proceed:");
635 for (i, commit) in commits.iter().take(5).enumerate() {
636 let message = commit.summary().unwrap_or("(no message)");
637 Output::sub_item(format!(
638 " {}. {} - {}",
639 i + 1,
640 &commit.id().to_string()[..8],
641 message
642 ));
643 }
644 if commits.len() > 5 {
645 Output::sub_item(format!(
646 " ... and {} more",
647 commits.len() - 5
648 ));
649 }
650 println!();
651 Output::tip("Add these commits to the stack first:");
652 Output::bullet("Run: ca stack push");
653 Output::bullet("Then run: ca sync");
654 println!();
655
656 return Err(CascadeError::validation(
657 format!(
658 "Working branch '{}' has {} untracked commit(s). Add them to the stack with 'ca stack push' before syncing.",
659 orig_branch, commits.len()
660 )
661 ));
662 }
663 }
664 }
665
666 debug!(
668 "Updating working branch '{}' to match top of stack ({})",
669 orig_branch,
670 &top_commit[..8]
671 );
672
673 if let Err(e) = self
674 .git_repo
675 .update_branch_to_commit(orig_branch, &top_commit)
676 {
677 Output::warning(format!(
678 "Could not update working branch '{}' to top of stack: {}",
679 orig_branch, e
680 ));
681 }
682 }
683 }
684
685 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
688 debug!(
689 "Could not return to original branch '{}': {}",
690 orig_branch, e
691 );
692 }
694 } else {
695 debug!(
698 "Skipping working branch update - user was on base branch '{}'",
699 orig_branch
700 );
701 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
702 debug!("Could not return to base branch '{}': {}", orig_branch, e);
703 }
704 }
705 }
706
707 result.summary = if pushed_count > 0 {
709 let pr_plural = if pushed_count == 1 { "" } else { "s" };
710 let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
711
712 if skipped_count > 0 {
713 format!(
714 "{} {} rebased ({} PR{} updated, {} not yet submitted)",
715 entry_count, entry_plural, pushed_count, pr_plural, skipped_count
716 )
717 } else {
718 format!(
719 "{} {} rebased ({} PR{} updated)",
720 entry_count, entry_plural, pushed_count, pr_plural
721 )
722 }
723 } else {
724 let plural = if entry_count == 1 { "entry" } else { "entries" };
725 format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
726 };
727
728 println!(); if result.success {
731 Output::success(&result.summary);
732 } else {
733 let error_msg = result
735 .error
736 .as_deref()
737 .unwrap_or("Rebase failed for unknown reason");
738 Output::error(error_msg);
739 }
740
741 self.stack_manager.save_to_disk()?;
743
744 if !result.success {
747 let detailed_error = result.error.as_deref().unwrap_or("Rebase failed");
749 return Err(CascadeError::Branch(detailed_error.to_string()));
750 }
751
752 Ok(result)
753 }
754
755 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
757 info!("Starting interactive rebase for stack '{}'", stack.name);
758
759 let mut result = RebaseResult {
760 success: true,
761 branch_mapping: HashMap::new(),
762 conflicts: Vec::new(),
763 new_commits: Vec::new(),
764 error: None,
765 summary: String::new(),
766 };
767
768 println!("Interactive Rebase for Stack: {}", stack.name);
769 println!(" Base branch: {}", stack.base_branch);
770 println!(" Entries: {}", stack.entries.len());
771
772 if self.options.interactive {
773 println!("\nChoose action for each commit:");
774 println!(" (p)ick - apply the commit");
775 println!(" (s)kip - skip this commit");
776 println!(" (e)dit - edit the commit message");
777 println!(" (q)uit - abort the rebase");
778 }
779
780 for entry in &stack.entries {
783 println!(
784 " {} {} - {}",
785 entry.short_hash(),
786 entry.branch,
787 entry.short_message(50)
788 );
789
790 match self.cherry_pick_commit(&entry.commit_hash) {
792 Ok(new_commit) => result.new_commits.push(new_commit),
793 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
794 }
795 }
796
797 result.summary = format!(
798 "Interactive rebase processed {} commits",
799 stack.entries.len()
800 );
801 Ok(result)
802 }
803
804 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
806 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
808
809 if let Ok(staged_files) = self.git_repo.get_staged_files() {
811 if !staged_files.is_empty() {
812 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
814 let _ = self.git_repo.commit_staged_changes(&cleanup_message);
815 }
816 }
817
818 Ok(new_commit_hash)
819 }
820
821 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
823 debug!("Starting auto-resolve for commit {}", commit_hash);
824
825 let has_conflicts = self.git_repo.has_conflicts()?;
827 debug!("has_conflicts() = {}", has_conflicts);
828
829 let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
831 let cherry_pick_in_progress = cherry_pick_head.exists();
832
833 if !has_conflicts {
834 debug!("No conflicts detected by Git index");
835
836 if cherry_pick_in_progress {
838 warn!("CHERRY_PICK_HEAD exists but no conflicts in index - aborting cherry-pick");
839
840 let _ = std::process::Command::new("git")
842 .args(["cherry-pick", "--abort"])
843 .current_dir(self.git_repo.path())
844 .output();
845
846 return Err(CascadeError::Branch(format!(
847 "Cherry-pick failed for {} but Git index shows no conflicts. \
848 This usually means the cherry-pick was aborted or failed in an unexpected way. \
849 Please try manual resolution.",
850 &commit_hash[..8]
851 )));
852 }
853
854 return Ok(true);
855 }
856
857 let conflicted_files = self.git_repo.get_conflicted_files()?;
858
859 if conflicted_files.is_empty() {
860 debug!("Conflicted files list is empty");
861 return Ok(true);
862 }
863
864 debug!(
865 "Found conflicts in {} files: {:?}",
866 conflicted_files.len(),
867 conflicted_files
868 );
869
870 let analysis = self
872 .conflict_analyzer
873 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
874
875 debug!(
876 "Conflict analysis: {} total conflicts, {} auto-resolvable",
877 analysis.total_conflicts, analysis.auto_resolvable_count
878 );
879
880 for recommendation in &analysis.recommendations {
882 debug!("{}", recommendation);
883 }
884
885 let mut resolved_count = 0;
886 let mut resolved_files = Vec::new(); let mut failed_files = Vec::new();
888
889 for file_analysis in &analysis.files {
890 debug!(
891 "Processing file: {} (auto_resolvable: {}, conflicts: {})",
892 file_analysis.file_path,
893 file_analysis.auto_resolvable,
894 file_analysis.conflicts.len()
895 );
896
897 if file_analysis.auto_resolvable {
898 match self.resolve_file_conflicts_enhanced(
899 &file_analysis.file_path,
900 &file_analysis.conflicts,
901 ) {
902 Ok(ConflictResolution::Resolved) => {
903 resolved_count += 1;
904 resolved_files.push(file_analysis.file_path.clone());
905 debug!("Successfully resolved {}", file_analysis.file_path);
906 }
907 Ok(ConflictResolution::TooComplex) => {
908 debug!(
909 "{} too complex for auto-resolution",
910 file_analysis.file_path
911 );
912 failed_files.push(file_analysis.file_path.clone());
913 }
914 Err(e) => {
915 debug!("Failed to resolve {}: {}", file_analysis.file_path, e);
916 failed_files.push(file_analysis.file_path.clone());
917 }
918 }
919 } else {
920 failed_files.push(file_analysis.file_path.clone());
921 debug!(
922 "{} requires manual resolution ({} conflicts)",
923 file_analysis.file_path,
924 file_analysis.conflicts.len()
925 );
926 }
927 }
928
929 if resolved_count > 0 {
930 debug!(
931 "Resolved {}/{} files",
932 resolved_count,
933 conflicted_files.len()
934 );
935 debug!("Resolved files: {:?}", resolved_files);
936
937 let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
940 debug!("Staging {} files", file_paths.len());
941 self.git_repo.stage_files(&file_paths)?;
942 debug!("Files staged successfully");
943 } else {
944 debug!("No files were resolved (resolved_count = 0)");
945 }
946
947 let all_resolved = failed_files.is_empty();
949
950 debug!(
951 "all_resolved = {}, failed_files = {:?}",
952 all_resolved, failed_files
953 );
954
955 if !all_resolved {
956 debug!("{} files still need manual resolution", failed_files.len());
957 }
958
959 debug!("Returning all_resolved = {}", all_resolved);
960 Ok(all_resolved)
961 }
962
963 fn resolve_file_conflicts_enhanced(
965 &self,
966 file_path: &str,
967 conflicts: &[crate::git::ConflictRegion],
968 ) -> Result<ConflictResolution> {
969 let repo_path = self.git_repo.path();
970 let full_path = repo_path.join(file_path);
971
972 let mut content = std::fs::read_to_string(&full_path)
974 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
975
976 if conflicts.is_empty() {
977 return Ok(ConflictResolution::Resolved);
978 }
979
980 info!(
981 "Resolving {} conflicts in {} using enhanced analysis",
982 conflicts.len(),
983 file_path
984 );
985
986 let mut any_resolved = false;
987
988 for conflict in conflicts.iter().rev() {
990 match self.resolve_single_conflict_enhanced(conflict) {
991 Ok(Some(resolution)) => {
992 let before = &content[..conflict.start_pos];
994 let after = &content[conflict.end_pos..];
995 content = format!("{before}{resolution}{after}");
996 any_resolved = true;
997 debug!(
998 "โ
Resolved {} conflict at lines {}-{} in {}",
999 format!("{:?}", conflict.conflict_type).to_lowercase(),
1000 conflict.start_line,
1001 conflict.end_line,
1002 file_path
1003 );
1004 }
1005 Ok(None) => {
1006 debug!(
1007 "โ ๏ธ {} conflict at lines {}-{} in {} requires manual resolution",
1008 format!("{:?}", conflict.conflict_type).to_lowercase(),
1009 conflict.start_line,
1010 conflict.end_line,
1011 file_path
1012 );
1013 return Ok(ConflictResolution::TooComplex);
1014 }
1015 Err(e) => {
1016 debug!("โ Failed to resolve conflict in {}: {}", file_path, e);
1017 return Ok(ConflictResolution::TooComplex);
1018 }
1019 }
1020 }
1021
1022 if any_resolved {
1023 let remaining_conflicts = self.parse_conflict_markers(&content)?;
1025
1026 if remaining_conflicts.is_empty() {
1027 debug!(
1028 "All conflicts resolved in {}, content length: {} bytes",
1029 file_path,
1030 content.len()
1031 );
1032
1033 if content.trim().is_empty() {
1035 warn!(
1036 "SAFETY CHECK: Resolved content for {} is empty! Aborting auto-resolution.",
1037 file_path
1038 );
1039 return Ok(ConflictResolution::TooComplex);
1040 }
1041
1042 let backup_path = full_path.with_extension("cascade-backup");
1044 if let Ok(original_content) = std::fs::read_to_string(&full_path) {
1045 debug!(
1046 "Backup for {} (original: {} bytes, resolved: {} bytes)",
1047 file_path,
1048 original_content.len(),
1049 content.len()
1050 );
1051 let _ = std::fs::write(&backup_path, original_content);
1052 }
1053
1054 crate::utils::atomic_file::write_string(&full_path, &content)?;
1056
1057 debug!("Wrote {} bytes to {}", content.len(), file_path);
1058 return Ok(ConflictResolution::Resolved);
1059 } else {
1060 info!(
1061 "Partially resolved conflicts in {} ({} remaining)",
1062 file_path,
1063 remaining_conflicts.len()
1064 );
1065 }
1066 }
1067
1068 Ok(ConflictResolution::TooComplex)
1069 }
1070
1071 #[allow(dead_code)]
1073 fn count_whitespace_consistency(content: &str) -> usize {
1074 let mut inconsistencies = 0;
1075 let lines: Vec<&str> = content.lines().collect();
1076
1077 for line in &lines {
1078 if line.contains('\t') && line.contains(' ') {
1080 inconsistencies += 1;
1081 }
1082 }
1083
1084 lines.len().saturating_sub(inconsistencies)
1086 }
1087
1088 fn resolve_single_conflict_enhanced(
1090 &self,
1091 conflict: &crate::git::ConflictRegion,
1092 ) -> Result<Option<String>> {
1093 debug!(
1094 "Resolving {} conflict in {} (lines {}-{})",
1095 format!("{:?}", conflict.conflict_type).to_lowercase(),
1096 conflict.file_path,
1097 conflict.start_line,
1098 conflict.end_line
1099 );
1100
1101 use crate::git::ConflictType;
1102
1103 match conflict.conflict_type {
1104 ConflictType::Whitespace => {
1105 let our_normalized = conflict
1108 .our_content
1109 .split_whitespace()
1110 .collect::<Vec<_>>()
1111 .join(" ");
1112 let their_normalized = conflict
1113 .their_content
1114 .split_whitespace()
1115 .collect::<Vec<_>>()
1116 .join(" ");
1117
1118 if our_normalized == their_normalized {
1119 Ok(Some(conflict.their_content.clone()))
1124 } else {
1125 debug!(
1127 "Whitespace conflict has content differences - requires manual resolution"
1128 );
1129 Ok(None)
1130 }
1131 }
1132 ConflictType::LineEnding => {
1133 let normalized = conflict
1135 .our_content
1136 .replace("\r\n", "\n")
1137 .replace('\r', "\n");
1138 Ok(Some(normalized))
1139 }
1140 ConflictType::PureAddition => {
1141 if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1145 Ok(Some(conflict.their_content.clone()))
1147 } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1148 Ok(Some(String::new()))
1150 } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1151 Ok(Some(String::new()))
1153 } else {
1154 debug!(
1160 "PureAddition conflict has content on both sides - requires manual resolution"
1161 );
1162 Ok(None)
1163 }
1164 }
1165 ConflictType::ImportMerge => {
1166 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1171 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1172
1173 let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1175 let trimmed = line.trim();
1176 trimmed.starts_with("import ")
1177 || trimmed.starts_with("from ")
1178 || trimmed.starts_with("use ")
1179 || trimmed.starts_with("#include")
1180 || trimmed.is_empty()
1181 });
1182
1183 if !all_simple {
1184 debug!("ImportMerge contains non-import lines - requires manual resolution");
1185 return Ok(None);
1186 }
1187
1188 let mut all_imports: Vec<&str> = our_lines
1190 .into_iter()
1191 .chain(their_lines)
1192 .filter(|line| !line.trim().is_empty())
1193 .collect();
1194 all_imports.sort();
1195 all_imports.dedup();
1196 Ok(Some(all_imports.join("\n")))
1197 }
1198 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1199 Ok(None)
1201 }
1202 }
1203 }
1204
1205 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1207 let lines: Vec<&str> = content.lines().collect();
1208 let mut conflicts = Vec::new();
1209 let mut i = 0;
1210
1211 while i < lines.len() {
1212 if lines[i].starts_with("<<<<<<<") {
1213 let start_line = i + 1;
1215 let mut separator_line = None;
1216 let mut end_line = None;
1217
1218 for (j, line) in lines.iter().enumerate().skip(i + 1) {
1220 if line.starts_with("=======") {
1221 separator_line = Some(j + 1);
1222 } else if line.starts_with(">>>>>>>") {
1223 end_line = Some(j + 1);
1224 break;
1225 }
1226 }
1227
1228 if let (Some(sep), Some(end)) = (separator_line, end_line) {
1229 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1231 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1232
1233 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1234 let their_content = lines[sep..(end - 1)].join("\n");
1235
1236 conflicts.push(ConflictRegion {
1237 start: start_pos,
1238 end: end_pos,
1239 start_line,
1240 end_line: end,
1241 our_content,
1242 their_content,
1243 });
1244
1245 i = end;
1246 } else {
1247 i += 1;
1248 }
1249 } else {
1250 i += 1;
1251 }
1252 }
1253
1254 Ok(conflicts)
1255 }
1256
1257 fn update_stack_entry(
1260 &mut self,
1261 stack_id: Uuid,
1262 entry_id: &Uuid,
1263 _new_branch: &str,
1264 new_commit_hash: &str,
1265 ) -> Result<()> {
1266 debug!(
1267 "Updating entry {} in stack {} with new commit {}",
1268 entry_id, stack_id, new_commit_hash
1269 );
1270
1271 let stack = self
1273 .stack_manager
1274 .get_stack_mut(&stack_id)
1275 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1276
1277 if let Some(entry) = stack.entries.iter_mut().find(|e| e.id == *entry_id) {
1279 debug!(
1280 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch '{}')",
1281 entry_id, entry.commit_hash, new_commit_hash, entry.branch
1282 );
1283
1284 entry.commit_hash = new_commit_hash.to_string();
1287
1288 debug!(
1291 "Successfully updated entry {} in stack {}",
1292 entry_id, stack_id
1293 );
1294 Ok(())
1295 } else {
1296 Err(CascadeError::config(format!(
1297 "Entry {entry_id} not found in stack {stack_id}"
1298 )))
1299 }
1300 }
1301
1302 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1304 info!("Pulling latest changes for branch {}", branch);
1305
1306 match self.git_repo.fetch() {
1308 Ok(_) => {
1309 debug!("Fetch successful");
1310 match self.git_repo.pull(branch) {
1312 Ok(_) => {
1313 info!("Pull completed successfully for {}", branch);
1314 Ok(())
1315 }
1316 Err(e) => {
1317 warn!("Pull failed for {}: {}", branch, e);
1318 Ok(())
1320 }
1321 }
1322 }
1323 Err(e) => {
1324 warn!("Fetch failed: {}", e);
1325 Ok(())
1327 }
1328 }
1329 }
1330
1331 pub fn is_rebase_in_progress(&self) -> bool {
1333 let git_dir = self.git_repo.path().join(".git");
1335 git_dir.join("REBASE_HEAD").exists()
1336 || git_dir.join("rebase-merge").exists()
1337 || git_dir.join("rebase-apply").exists()
1338 }
1339
1340 pub fn abort_rebase(&self) -> Result<()> {
1342 info!("Aborting rebase operation");
1343
1344 let git_dir = self.git_repo.path().join(".git");
1345
1346 if git_dir.join("REBASE_HEAD").exists() {
1348 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1349 CascadeError::Git(git2::Error::from_str(&format!(
1350 "Failed to clean rebase state: {e}"
1351 )))
1352 })?;
1353 }
1354
1355 if git_dir.join("rebase-merge").exists() {
1356 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1357 CascadeError::Git(git2::Error::from_str(&format!(
1358 "Failed to clean rebase-merge: {e}"
1359 )))
1360 })?;
1361 }
1362
1363 if git_dir.join("rebase-apply").exists() {
1364 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1365 CascadeError::Git(git2::Error::from_str(&format!(
1366 "Failed to clean rebase-apply: {e}"
1367 )))
1368 })?;
1369 }
1370
1371 info!("Rebase aborted successfully");
1372 Ok(())
1373 }
1374
1375 pub fn continue_rebase(&self) -> Result<()> {
1377 info!("Continuing rebase operation");
1378
1379 if self.git_repo.has_conflicts()? {
1381 return Err(CascadeError::branch(
1382 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1383 ));
1384 }
1385
1386 self.git_repo.stage_conflict_resolved_files()?;
1388
1389 info!("Rebase continued successfully");
1390 Ok(())
1391 }
1392
1393 fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1395 let git_dir = self.git_repo.path().join(".git");
1396 Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1397 }
1398
1399 fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1401 use crate::cli::output::Output;
1402
1403 let git_dir = self.git_repo.path().join(".git");
1404
1405 Output::section("Resuming in-progress sync");
1406 println!();
1407 Output::info("Detected unfinished cherry-pick from previous sync");
1408 println!();
1409
1410 if self.git_repo.has_conflicts()? {
1412 let conflicted_files = self.git_repo.get_conflicted_files()?;
1413
1414 let result = RebaseResult {
1415 success: false,
1416 branch_mapping: HashMap::new(),
1417 conflicts: conflicted_files.clone(),
1418 new_commits: Vec::new(),
1419 error: Some(format!(
1420 "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1421 MANUAL CONFLICT RESOLUTION REQUIRED\n\
1422 =====================================\n\n\
1423 Conflicted files:\n{}\n\n\
1424 Step 1: Analyze conflicts\n\
1425 โ Run: ca conflicts\n\
1426 โ Shows detailed conflict analysis\n\n\
1427 Step 2: Resolve conflicts in your editor\n\
1428 โ Open conflicted files and edit them\n\
1429 โ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1430 โ Keep the code you want\n\
1431 โ Save the files\n\n\
1432 Step 3: Mark conflicts as resolved\n\
1433 โ Run: git add <resolved-files>\n\
1434 โ Or: git add -A (to stage all resolved files)\n\n\
1435 Step 4: Complete the sync\n\
1436 โ Run: ca sync\n\
1437 โ Cascade will continue from where it left off\n\n\
1438 Alternative: Abort and start over\n\
1439 โ Run: git cherry-pick --abort\n\
1440 โ Then: ca sync (starts fresh)",
1441 conflicted_files.len(),
1442 conflicted_files
1443 .iter()
1444 .map(|f| format!(" - {}", f))
1445 .collect::<Vec<_>>()
1446 .join("\n")
1447 )),
1448 summary: "Sync paused - conflicts need resolution".to_string(),
1449 };
1450
1451 return Ok(result);
1452 }
1453
1454 Output::info("Conflicts resolved, continuing cherry-pick...");
1456
1457 self.git_repo.stage_conflict_resolved_files()?;
1459
1460 let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1462 let commit_message = if cherry_pick_msg_file.exists() {
1463 std::fs::read_to_string(&cherry_pick_msg_file)
1464 .unwrap_or_else(|_| "Resolved conflicts".to_string())
1465 } else {
1466 "Resolved conflicts".to_string()
1467 };
1468
1469 match self.git_repo.commit(&commit_message) {
1470 Ok(_new_commit_id) => {
1471 Output::success("Cherry-pick completed");
1472
1473 if git_dir.join("CHERRY_PICK_HEAD").exists() {
1475 let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1476 }
1477 if cherry_pick_msg_file.exists() {
1478 let _ = std::fs::remove_file(&cherry_pick_msg_file);
1479 }
1480
1481 println!();
1482 Output::info("Continuing with rest of stack...");
1483 println!();
1484
1485 self.rebase_with_force_push(stack)
1488 }
1489 Err(e) => {
1490 let result = RebaseResult {
1491 success: false,
1492 branch_mapping: HashMap::new(),
1493 conflicts: Vec::new(),
1494 new_commits: Vec::new(),
1495 error: Some(format!(
1496 "Failed to complete cherry-pick: {}\n\n\
1497 This usually means:\n\
1498 - Git index is locked (another process accessing repo)\n\
1499 - File permissions issue\n\
1500 - Disk space issue\n\n\
1501 Recovery:\n\
1502 1. Check if another Git operation is running\n\
1503 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1504 3. Run 'git status' to check repo state\n\
1505 4. Retry 'ca sync' after fixing the issue\n\n\
1506 Or abort and start fresh:\n\
1507 โ Run: git cherry-pick --abort\n\
1508 โ Then: ca sync",
1509 e
1510 )),
1511 summary: "Failed to complete cherry-pick".to_string(),
1512 };
1513
1514 Ok(result)
1515 }
1516 }
1517 }
1518}
1519
1520impl RebaseResult {
1521 pub fn get_summary(&self) -> String {
1523 if self.success {
1524 format!("โ
{}", self.summary)
1525 } else {
1526 format!(
1527 "โ Rebase failed: {}",
1528 self.error.as_deref().unwrap_or("Unknown error")
1529 )
1530 }
1531 }
1532
1533 pub fn has_conflicts(&self) -> bool {
1535 !self.conflicts.is_empty()
1536 }
1537
1538 pub fn success_count(&self) -> usize {
1540 self.new_commits.len()
1541 }
1542}
1543
1544#[cfg(test)]
1545mod tests {
1546 use super::*;
1547 use std::path::PathBuf;
1548 use std::process::Command;
1549 use tempfile::TempDir;
1550
1551 #[allow(dead_code)]
1552 fn create_test_repo() -> (TempDir, PathBuf) {
1553 let temp_dir = TempDir::new().unwrap();
1554 let repo_path = temp_dir.path().to_path_buf();
1555
1556 Command::new("git")
1558 .args(["init"])
1559 .current_dir(&repo_path)
1560 .output()
1561 .unwrap();
1562 Command::new("git")
1563 .args(["config", "user.name", "Test"])
1564 .current_dir(&repo_path)
1565 .output()
1566 .unwrap();
1567 Command::new("git")
1568 .args(["config", "user.email", "test@test.com"])
1569 .current_dir(&repo_path)
1570 .output()
1571 .unwrap();
1572
1573 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1575 Command::new("git")
1576 .args(["add", "."])
1577 .current_dir(&repo_path)
1578 .output()
1579 .unwrap();
1580 Command::new("git")
1581 .args(["commit", "-m", "Initial"])
1582 .current_dir(&repo_path)
1583 .output()
1584 .unwrap();
1585
1586 (temp_dir, repo_path)
1587 }
1588
1589 #[test]
1590 fn test_conflict_region_creation() {
1591 let region = ConflictRegion {
1592 start: 0,
1593 end: 50,
1594 start_line: 1,
1595 end_line: 3,
1596 our_content: "function test() {\n return true;\n}".to_string(),
1597 their_content: "function test() {\n return true;\n}".to_string(),
1598 };
1599
1600 assert_eq!(region.start_line, 1);
1601 assert_eq!(region.end_line, 3);
1602 assert!(region.our_content.contains("return true"));
1603 assert!(region.their_content.contains("return true"));
1604 }
1605
1606 #[test]
1607 fn test_rebase_strategies() {
1608 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1609 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1610 }
1611
1612 #[test]
1613 fn test_rebase_options() {
1614 let options = RebaseOptions::default();
1615 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1616 assert!(!options.interactive);
1617 assert!(options.auto_resolve);
1618 assert_eq!(options.max_retries, 3);
1619 }
1620
1621 #[test]
1622 fn test_cleanup_guard_tracks_branches() {
1623 let mut guard = TempBranchCleanupGuard::new();
1624 assert!(guard.branches.is_empty());
1625
1626 guard.add_branch("test-branch-1".to_string());
1627 guard.add_branch("test-branch-2".to_string());
1628
1629 assert_eq!(guard.branches.len(), 2);
1630 assert_eq!(guard.branches[0], "test-branch-1");
1631 assert_eq!(guard.branches[1], "test-branch-2");
1632 }
1633
1634 #[test]
1635 fn test_cleanup_guard_prevents_double_cleanup() {
1636 use std::process::Command;
1637 use tempfile::TempDir;
1638
1639 let temp_dir = TempDir::new().unwrap();
1641 let repo_path = temp_dir.path();
1642
1643 Command::new("git")
1644 .args(["init"])
1645 .current_dir(repo_path)
1646 .output()
1647 .unwrap();
1648
1649 Command::new("git")
1650 .args(["config", "user.name", "Test"])
1651 .current_dir(repo_path)
1652 .output()
1653 .unwrap();
1654
1655 Command::new("git")
1656 .args(["config", "user.email", "test@test.com"])
1657 .current_dir(repo_path)
1658 .output()
1659 .unwrap();
1660
1661 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1663 Command::new("git")
1664 .args(["add", "."])
1665 .current_dir(repo_path)
1666 .output()
1667 .unwrap();
1668 Command::new("git")
1669 .args(["commit", "-m", "initial"])
1670 .current_dir(repo_path)
1671 .output()
1672 .unwrap();
1673
1674 let git_repo = GitRepository::open(repo_path).unwrap();
1675
1676 git_repo.create_branch("test-temp", None).unwrap();
1678
1679 let mut guard = TempBranchCleanupGuard::new();
1680 guard.add_branch("test-temp".to_string());
1681
1682 guard.cleanup(&git_repo);
1684 assert!(guard.cleaned);
1685
1686 guard.cleanup(&git_repo);
1688 assert!(guard.cleaned);
1689 }
1690
1691 #[test]
1692 fn test_rebase_result() {
1693 let result = RebaseResult {
1694 success: true,
1695 branch_mapping: std::collections::HashMap::new(),
1696 conflicts: vec!["abc123".to_string()],
1697 new_commits: vec!["def456".to_string()],
1698 error: None,
1699 summary: "Test summary".to_string(),
1700 };
1701
1702 assert!(result.success);
1703 assert!(result.has_conflicts());
1704 assert_eq!(result.success_count(), 1);
1705 }
1706}