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(); println!(); let plural = if entry_count == 1 { "entry" } else { "entries" };
270 println!("Rebasing {} {}...", entry_count, plural);
271
272 for (index, entry) in stack.entries.iter().enumerate() {
274 let original_branch = &entry.branch;
275
276 let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
279 temp_branches.push(temp_branch.clone()); self.git_repo
281 .create_branch(&temp_branch, Some(¤t_base))?;
282 self.git_repo.checkout_branch(&temp_branch)?;
283
284 match self.cherry_pick_commit(&entry.commit_hash) {
286 Ok(new_commit_hash) => {
287 result.new_commits.push(new_commit_hash.clone());
288
289 let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
291
292 self.git_repo
295 .update_branch_to_commit(original_branch, &rebased_commit_id)?;
296
297 let tree_char = if index + 1 == entry_count {
299 "โโ"
300 } else {
301 "โโ"
302 };
303
304 if let Some(pr_num) = &entry.pull_request_id {
305 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
306 branches_to_push.push((original_branch.clone(), pr_num.clone()));
307 } else {
308 println!(" {} {} (not submitted)", tree_char, original_branch);
309 }
310
311 result
312 .branch_mapping
313 .insert(original_branch.clone(), original_branch.clone());
314
315 self.update_stack_entry(
317 stack.id,
318 &entry.id,
319 original_branch,
320 &rebased_commit_id,
321 )?;
322
323 current_base = original_branch.clone();
325 }
326 Err(e) => {
327 println!(); Output::error(format!("Conflict in {}: {}", &entry.commit_hash[..8], e));
329 result.conflicts.push(entry.commit_hash.clone());
330
331 if !self.options.auto_resolve {
332 result.success = false;
333 result.error = Some(format!(
334 "Conflict in {}: {}\n\n\
335 MANUAL CONFLICT RESOLUTION REQUIRED\n\
336 =====================================\n\n\
337 Step 1: Analyze conflicts\n\
338 โ Run: ca conflicts\n\
339 โ This shows which conflicts are in which files\n\n\
340 Step 2: Resolve conflicts in your editor\n\
341 โ Open conflicted files and edit them\n\
342 โ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
343 โ Keep the code you want\n\
344 โ Save the files\n\n\
345 Step 3: Mark conflicts as resolved\n\
346 โ Run: git add <resolved-files>\n\
347 โ Or: git add -A (to stage all resolved files)\n\n\
348 Step 4: Complete the sync\n\
349 โ Run: ca sync\n\
350 โ Cascade will detect resolved conflicts and continue\n\n\
351 Alternative: Abort and start over\n\
352 โ Run: git cherry-pick --abort\n\
353 โ Then: ca sync (starts fresh)\n\n\
354 TIP: Enable auto-resolution for simple conflicts:\n\
355 โ Run: ca sync --auto-resolve\n\
356 โ Only complex conflicts will require manual resolution",
357 entry.commit_hash, e
358 ));
359 break;
360 }
361
362 match self.auto_resolve_conflicts(&entry.commit_hash) {
364 Ok(fully_resolved) => {
365 if !fully_resolved {
366 result.success = false;
367 result.error = Some(format!(
368 "Could not auto-resolve all conflicts in {}\n\n\
369 MANUAL CONFLICT RESOLUTION REQUIRED\n\
370 =====================================\n\n\
371 Some conflicts are too complex for auto-resolution.\n\n\
372 Step 1: Analyze remaining conflicts\n\
373 โ Run: ca conflicts\n\
374 โ Shows which files still have conflicts\n\
375 โ Use --detailed flag for more info\n\n\
376 Step 2: Resolve conflicts in your editor\n\
377 โ Open conflicted files (marked with โ in ca conflicts output)\n\
378 โ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
379 โ Keep the code you want\n\
380 โ Save the files\n\n\
381 Step 3: Mark conflicts as resolved\n\
382 โ Run: git add <resolved-files>\n\
383 โ Or: git add -A (to stage all resolved files)\n\n\
384 Step 4: Complete the sync\n\
385 โ Run: ca sync\n\
386 โ Cascade will continue from where it left off\n\n\
387 Alternative: Abort and start over\n\
388 โ Run: git cherry-pick --abort\n\
389 โ Then: ca sync (starts fresh)\n\n\
390 BACKUP: If auto-resolution was wrong\n\
391 โ Check for .cascade-backup files in your repo\n\
392 โ These contain the original file content before auto-resolution",
393 &entry.commit_hash[..8]
394 ));
395 break;
396 }
397
398 let commit_message =
400 format!("Auto-resolved conflicts in {}", &entry.commit_hash[..8]);
401
402 warn!("AUTO-RESOLVE DEBUG: About to commit. Checking staged files...");
404 let staged_files = self.git_repo.get_staged_files()?;
405
406 if staged_files.is_empty() {
407 result.success = false;
411 result.error = Some(format!(
412 "CRITICAL BUG DETECTED: Cherry-pick failed but no files were staged!\n\n\
413 This indicates a Git state issue after cherry-pick failure.\n\n\
414 RECOVERY STEPS:\n\
415 ================\n\n\
416 Step 1: Check Git status\n\
417 โ Run: git status\n\
418 โ Check if there are any changes in working directory\n\n\
419 Step 2: Check for conflicts manually\n\
420 โ Run: git diff\n\
421 โ Look for conflict markers (<<<<<<, ======, >>>>>>)\n\n\
422 Step 3: Abort the cherry-pick\n\
423 โ Run: git cherry-pick --abort\n\n\
424 Step 4: Report this bug\n\
425 โ This is a known issue we're investigating\n\
426 โ Cherry-pick failed for commit {}\n\
427 โ But Git reported no conflicts and no staged files\n\n\
428 Step 5: Try manual resolution\n\
429 โ Run: ca sync --no-auto-resolve\n\
430 โ Manually resolve conflicts as they appear",
431 &entry.commit_hash[..8]
432 ));
433 warn!("AUTO-RESOLVE DEBUG: CRITICAL - No files staged after auto-resolve!");
434 break;
435 }
436
437 warn!("AUTO-RESOLVE DEBUG: {} files staged: {:?}", staged_files.len(), staged_files);
439 if let Ok(status) = std::process::Command::new("git")
440 .args(["diff", "--cached", "--stat"])
441 .current_dir(self.git_repo.path())
442 .output()
443 {
444 let stat_output = String::from_utf8_lossy(&status.stdout);
445 warn!("AUTO-RESOLVE DEBUG: Staged changes:\n{}", stat_output);
446 }
447
448 match self.git_repo.commit(&commit_message) {
449 Ok(new_commit_id) => {
450 warn!(
451 "AUTO-RESOLVE DEBUG: Created commit {} with message '{}'",
452 &new_commit_id[..8],
453 commit_message
454 );
455
456 if let Ok(show) = std::process::Command::new("git")
458 .args(["show", "--stat", &new_commit_id])
459 .current_dir(self.git_repo.path())
460 .output()
461 {
462 let show_output = String::from_utf8_lossy(&show.stdout);
463 warn!("AUTO-RESOLVE DEBUG: Commit contents:\n{}", show_output);
464 }
465
466 Output::success("Auto-resolved conflicts");
467 result.new_commits.push(new_commit_id.clone());
468 let rebased_commit_id = new_commit_id;
469
470 self.git_repo.update_branch_to_commit(
472 original_branch,
473 &rebased_commit_id,
474 )?;
475
476 let tree_char = if index + 1 == entry_count {
478 "โโ"
479 } else {
480 "โโ"
481 };
482
483 if let Some(pr_num) = &entry.pull_request_id {
484 println!(
485 " {} {} (PR #{})",
486 tree_char, original_branch, pr_num
487 );
488 branches_to_push
489 .push((original_branch.clone(), pr_num.clone()));
490 } else {
491 println!(
492 " {} {} (not submitted)",
493 tree_char, original_branch
494 );
495 }
496
497 result
498 .branch_mapping
499 .insert(original_branch.clone(), original_branch.clone());
500
501 self.update_stack_entry(
503 stack.id,
504 &entry.id,
505 original_branch,
506 &rebased_commit_id,
507 )?;
508
509 current_base = original_branch.clone();
511 }
512 Err(commit_err) => {
513 result.success = false;
514 result.error = Some(format!(
515 "Could not commit auto-resolved conflicts: {}\n\n\
516 This usually means:\n\
517 - Git index is locked (another process accessing repo)\n\
518 - File permissions issue\n\
519 - Disk space issue\n\n\
520 Recovery:\n\
521 1. Check if another Git operation is running\n\
522 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
523 3. Run 'git status' to check repo state\n\
524 4. Retry 'ca sync' after fixing the issue",
525 commit_err
526 ));
527 break;
528 }
529 }
530 }
531 Err(resolve_err) => {
532 result.success = false;
533 result.error = Some(format!(
534 "Could not resolve conflicts: {}\n\n\
535 Recovery:\n\
536 1. Check repo state: 'git status'\n\
537 2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
538 3. Remove any lock files: 'rm -f .git/index.lock'\n\
539 4. Retry 'ca sync'",
540 resolve_err
541 ));
542 break;
543 }
544 }
545 }
546 }
547 }
548
549 if !temp_branches.is_empty() {
552 if let Err(e) = self.git_repo.checkout_branch_unsafe(&target_base) {
555 Output::warning(format!("Could not checkout base for cleanup: {}", e));
556 } else {
559 for temp_branch in &temp_branches {
561 if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
562 debug!("Could not delete temp branch {}: {}", temp_branch, e);
563 }
564 }
565 }
566 }
567
568 let pushed_count = branches_to_push.len();
571 let skipped_count = entry_count - pushed_count;
572
573 if !branches_to_push.is_empty() {
574 println!(); println!(
576 "Pushing {} branch{} to remote...",
577 pushed_count,
578 if pushed_count == 1 { "" } else { "es" }
579 );
580
581 for (branch_name, _pr_num) in &branches_to_push {
582 match self.git_repo.force_push_single_branch_auto(branch_name) {
583 Ok(_) => {
584 debug!("Pushed {} successfully", branch_name);
585 }
586 Err(e) => {
587 Output::warning(format!("Could not push '{}': {}", branch_name, e));
588 }
590 }
591 }
592 }
593
594 if let Some(ref orig_branch) = original_branch {
597 if orig_branch != &target_base {
599 if let Some(last_entry) = stack.entries.last() {
601 let top_branch = &last_entry.branch;
602
603 if let Ok(top_commit) = self.git_repo.get_branch_head(top_branch) {
605 debug!(
606 "Updating working branch '{}' to match top of stack ({})",
607 orig_branch,
608 &top_commit[..8]
609 );
610
611 if let Err(e) = self
612 .git_repo
613 .update_branch_to_commit(orig_branch, &top_commit)
614 {
615 Output::warning(format!(
616 "Could not update working branch '{}' to top of stack: {}",
617 orig_branch, e
618 ));
619 }
620 }
621 }
622
623 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
626 debug!(
627 "Could not return to original branch '{}': {}",
628 orig_branch, e
629 );
630 }
632 } else {
633 debug!(
636 "Skipping working branch update - user was on base branch '{}'",
637 orig_branch
638 );
639 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
640 debug!("Could not return to base branch '{}': {}", orig_branch, e);
641 }
642 }
643 }
644
645 result.summary = if pushed_count > 0 {
647 let pr_plural = if pushed_count == 1 { "" } else { "s" };
648 let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
649
650 if skipped_count > 0 {
651 format!(
652 "{} {} rebased ({} PR{} updated, {} not yet submitted)",
653 entry_count, entry_plural, pushed_count, pr_plural, skipped_count
654 )
655 } else {
656 format!(
657 "{} {} rebased ({} PR{} updated)",
658 entry_count, entry_plural, pushed_count, pr_plural
659 )
660 }
661 } else {
662 let plural = if entry_count == 1 { "entry" } else { "entries" };
663 format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
664 };
665
666 println!(); if result.success {
669 Output::success(&result.summary);
670 } else {
671 Output::error(format!("Rebase failed: {:?}", result.error));
672 }
673
674 self.stack_manager.save_to_disk()?;
676
677 Ok(result)
678 }
679
680 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
682 info!("Starting interactive rebase for stack '{}'", stack.name);
683
684 let mut result = RebaseResult {
685 success: true,
686 branch_mapping: HashMap::new(),
687 conflicts: Vec::new(),
688 new_commits: Vec::new(),
689 error: None,
690 summary: String::new(),
691 };
692
693 println!("Interactive Rebase for Stack: {}", stack.name);
694 println!(" Base branch: {}", stack.base_branch);
695 println!(" Entries: {}", stack.entries.len());
696
697 if self.options.interactive {
698 println!("\nChoose action for each commit:");
699 println!(" (p)ick - apply the commit");
700 println!(" (s)kip - skip this commit");
701 println!(" (e)dit - edit the commit message");
702 println!(" (q)uit - abort the rebase");
703 }
704
705 for entry in &stack.entries {
708 println!(
709 " {} {} - {}",
710 entry.short_hash(),
711 entry.branch,
712 entry.short_message(50)
713 );
714
715 match self.cherry_pick_commit(&entry.commit_hash) {
717 Ok(new_commit) => result.new_commits.push(new_commit),
718 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
719 }
720 }
721
722 result.summary = format!(
723 "Interactive rebase processed {} commits",
724 stack.entries.len()
725 );
726 Ok(result)
727 }
728
729 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
731 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
733
734 if let Ok(staged_files) = self.git_repo.get_staged_files() {
736 if !staged_files.is_empty() {
737 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
739 let _ = self.git_repo.commit_staged_changes(&cleanup_message);
740 }
741 }
742
743 Ok(new_commit_hash)
744 }
745
746 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
748 warn!("=== AUTO-RESOLVE DEBUG: Starting for commit {} ===", commit_hash);
749
750 let has_conflicts = self.git_repo.has_conflicts()?;
752 warn!("AUTO-RESOLVE DEBUG: has_conflicts() = {}", has_conflicts);
753
754 if let Ok(status_output) = std::process::Command::new("git")
756 .args(["status", "--short"])
757 .current_dir(self.git_repo.path())
758 .output()
759 {
760 let status_str = String::from_utf8_lossy(&status_output.stdout);
761 warn!("AUTO-RESOLVE DEBUG: git status --short:\n{}", status_str);
762 }
763
764 let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
766 let cherry_pick_in_progress = cherry_pick_head.exists();
767 warn!("AUTO-RESOLVE DEBUG: CHERRY_PICK_HEAD exists = {}", cherry_pick_in_progress);
768
769 if !has_conflicts {
770 warn!("AUTO-RESOLVE DEBUG: No conflicts detected by Git index");
771 warn!("AUTO-RESOLVE DEBUG: But cherry-pick may have failed - checking working directory...");
772
773 if cherry_pick_in_progress {
775 warn!("AUTO-RESOLVE DEBUG: CHERRY_PICK_HEAD exists but no conflicts in index!");
776 warn!("AUTO-RESOLVE DEBUG: This indicates a Git state issue - aborting cherry-pick");
777
778 let _ = std::process::Command::new("git")
780 .args(["cherry-pick", "--abort"])
781 .current_dir(self.git_repo.path())
782 .output();
783
784 return Err(CascadeError::Branch(format!(
785 "Cherry-pick failed for {} but Git index shows no conflicts. \
786 This usually means the cherry-pick was aborted or failed in an unexpected way. \
787 Please try manual resolution.",
788 &commit_hash[..8]
789 )));
790 }
791
792 return Ok(true);
793 }
794
795 let conflicted_files = self.git_repo.get_conflicted_files()?;
796
797 if conflicted_files.is_empty() {
798 warn!("AUTO-RESOLVE DEBUG: Conflicted files list is empty");
799 return Ok(true);
800 }
801
802 warn!(
803 "AUTO-RESOLVE DEBUG: Found conflicts in {} files: {:?}",
804 conflicted_files.len(),
805 conflicted_files
806 );
807
808 let analysis = self
810 .conflict_analyzer
811 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
812
813 info!(
814 "๐ Conflict analysis: {} total conflicts, {} auto-resolvable",
815 analysis.total_conflicts, analysis.auto_resolvable_count
816 );
817
818 for recommendation in &analysis.recommendations {
820 info!("๐ก {}", recommendation);
821 }
822
823 let mut resolved_count = 0;
824 let mut resolved_files = Vec::new(); let mut failed_files = Vec::new();
826
827 for file_analysis in &analysis.files {
828 warn!(
829 "AUTO-RESOLVE DEBUG: Processing file: {} (auto_resolvable: {}, conflicts: {})",
830 file_analysis.file_path,
831 file_analysis.auto_resolvable,
832 file_analysis.conflicts.len()
833 );
834
835 if file_analysis.auto_resolvable {
836 match self.resolve_file_conflicts_enhanced(
837 &file_analysis.file_path,
838 &file_analysis.conflicts,
839 ) {
840 Ok(ConflictResolution::Resolved) => {
841 resolved_count += 1;
842 resolved_files.push(file_analysis.file_path.clone());
843 warn!(
844 "AUTO-RESOLVE DEBUG: Successfully resolved {}",
845 file_analysis.file_path
846 );
847 }
848 Ok(ConflictResolution::TooComplex) => {
849 warn!(
850 "AUTO-RESOLVE DEBUG: {} too complex for auto-resolution",
851 file_analysis.file_path
852 );
853 failed_files.push(file_analysis.file_path.clone());
854 }
855 Err(e) => {
856 warn!(
857 "AUTO-RESOLVE DEBUG: Failed to resolve {}: {}",
858 file_analysis.file_path, e
859 );
860 failed_files.push(file_analysis.file_path.clone());
861 }
862 }
863 } else {
864 failed_files.push(file_analysis.file_path.clone());
865 warn!(
866 "AUTO-RESOLVE DEBUG: {} requires manual resolution ({} conflicts)",
867 file_analysis.file_path,
868 file_analysis.conflicts.len()
869 );
870 }
871 }
872
873 if resolved_count > 0 {
874 warn!(
875 "AUTO-RESOLVE DEBUG: Resolved {}/{} files",
876 resolved_count,
877 conflicted_files.len()
878 );
879 warn!("AUTO-RESOLVE DEBUG: Resolved files: {:?}", resolved_files);
880
881 let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
884 warn!("AUTO-RESOLVE DEBUG: Staging {} files", file_paths.len());
885 self.git_repo.stage_files(&file_paths)?;
886 warn!("AUTO-RESOLVE DEBUG: Files staged successfully");
887 } else {
888 warn!("AUTO-RESOLVE DEBUG: No files were resolved (resolved_count = 0)");
889 }
890
891 let all_resolved = failed_files.is_empty();
893
894 warn!(
895 "AUTO-RESOLVE DEBUG: all_resolved = {}, failed_files = {:?}",
896 all_resolved, failed_files
897 );
898
899 if !all_resolved {
900 warn!(
901 "AUTO-RESOLVE DEBUG: {} files still need manual resolution",
902 failed_files.len()
903 );
904 }
905
906 warn!("AUTO-RESOLVE DEBUG: Returning all_resolved = {}", all_resolved);
907 Ok(all_resolved)
908 }
909
910 fn resolve_file_conflicts_enhanced(
912 &self,
913 file_path: &str,
914 conflicts: &[crate::git::ConflictRegion],
915 ) -> Result<ConflictResolution> {
916 let repo_path = self.git_repo.path();
917 let full_path = repo_path.join(file_path);
918
919 let mut content = std::fs::read_to_string(&full_path)
921 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
922
923 if conflicts.is_empty() {
924 return Ok(ConflictResolution::Resolved);
925 }
926
927 info!(
928 "Resolving {} conflicts in {} using enhanced analysis",
929 conflicts.len(),
930 file_path
931 );
932
933 let mut any_resolved = false;
934
935 for conflict in conflicts.iter().rev() {
937 match self.resolve_single_conflict_enhanced(conflict) {
938 Ok(Some(resolution)) => {
939 let before = &content[..conflict.start_pos];
941 let after = &content[conflict.end_pos..];
942 content = format!("{before}{resolution}{after}");
943 any_resolved = true;
944 debug!(
945 "โ
Resolved {} conflict at lines {}-{} in {}",
946 format!("{:?}", conflict.conflict_type).to_lowercase(),
947 conflict.start_line,
948 conflict.end_line,
949 file_path
950 );
951 }
952 Ok(None) => {
953 debug!(
954 "โ ๏ธ {} conflict at lines {}-{} in {} requires manual resolution",
955 format!("{:?}", conflict.conflict_type).to_lowercase(),
956 conflict.start_line,
957 conflict.end_line,
958 file_path
959 );
960 return Ok(ConflictResolution::TooComplex);
961 }
962 Err(e) => {
963 debug!("โ Failed to resolve conflict in {}: {}", file_path, e);
964 return Ok(ConflictResolution::TooComplex);
965 }
966 }
967 }
968
969 if any_resolved {
970 let remaining_conflicts = self.parse_conflict_markers(&content)?;
972
973 if remaining_conflicts.is_empty() {
974 warn!(
975 "AUTO-RESOLVE DEBUG: All conflicts resolved in {}, content length: {} bytes",
976 file_path,
977 content.len()
978 );
979
980 if content.trim().is_empty() {
982 warn!(
983 "AUTO-RESOLVE DEBUG: SAFETY CHECK TRIGGERED! Resolved content for {} is empty! Aborting.",
984 file_path
985 );
986 return Ok(ConflictResolution::TooComplex);
987 }
988
989 let backup_path = full_path.with_extension("cascade-backup");
991 if let Ok(original_content) = std::fs::read_to_string(&full_path) {
992 warn!(
993 "AUTO-RESOLVE DEBUG: Backup for {} (original: {} bytes, resolved: {} bytes)",
994 file_path,
995 original_content.len(),
996 content.len()
997 );
998 let _ = std::fs::write(&backup_path, original_content);
999 }
1000
1001 crate::utils::atomic_file::write_string(&full_path, &content)?;
1003
1004 warn!(
1005 "AUTO-RESOLVE DEBUG: Wrote {} bytes to {}",
1006 content.len(),
1007 file_path
1008 );
1009 return Ok(ConflictResolution::Resolved);
1010 } else {
1011 info!(
1012 "โ ๏ธ Partially resolved conflicts in {} ({} remaining)",
1013 file_path,
1014 remaining_conflicts.len()
1015 );
1016 }
1017 }
1018
1019 Ok(ConflictResolution::TooComplex)
1020 }
1021
1022 #[allow(dead_code)]
1024 fn count_whitespace_consistency(content: &str) -> usize {
1025 let mut inconsistencies = 0;
1026 let lines: Vec<&str> = content.lines().collect();
1027
1028 for line in &lines {
1029 if line.contains('\t') && line.contains(' ') {
1031 inconsistencies += 1;
1032 }
1033 }
1034
1035 lines.len().saturating_sub(inconsistencies)
1037 }
1038
1039 fn resolve_single_conflict_enhanced(
1041 &self,
1042 conflict: &crate::git::ConflictRegion,
1043 ) -> Result<Option<String>> {
1044 debug!(
1045 "Resolving {} conflict in {} (lines {}-{})",
1046 format!("{:?}", conflict.conflict_type).to_lowercase(),
1047 conflict.file_path,
1048 conflict.start_line,
1049 conflict.end_line
1050 );
1051
1052 use crate::git::ConflictType;
1053
1054 match conflict.conflict_type {
1055 ConflictType::Whitespace => {
1056 let our_normalized = conflict
1059 .our_content
1060 .split_whitespace()
1061 .collect::<Vec<_>>()
1062 .join(" ");
1063 let their_normalized = conflict
1064 .their_content
1065 .split_whitespace()
1066 .collect::<Vec<_>>()
1067 .join(" ");
1068
1069 if our_normalized == their_normalized {
1070 Ok(Some(conflict.their_content.clone()))
1075 } else {
1076 debug!(
1078 "Whitespace conflict has content differences - requires manual resolution"
1079 );
1080 Ok(None)
1081 }
1082 }
1083 ConflictType::LineEnding => {
1084 let normalized = conflict
1086 .our_content
1087 .replace("\r\n", "\n")
1088 .replace('\r', "\n");
1089 Ok(Some(normalized))
1090 }
1091 ConflictType::PureAddition => {
1092 if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1096 Ok(Some(conflict.their_content.clone()))
1098 } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1099 Ok(Some(String::new()))
1101 } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1102 Ok(Some(String::new()))
1104 } else {
1105 debug!(
1111 "PureAddition conflict has content on both sides - requires manual resolution"
1112 );
1113 Ok(None)
1114 }
1115 }
1116 ConflictType::ImportMerge => {
1117 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1122 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1123
1124 let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1126 let trimmed = line.trim();
1127 trimmed.starts_with("import ")
1128 || trimmed.starts_with("from ")
1129 || trimmed.starts_with("use ")
1130 || trimmed.starts_with("#include")
1131 || trimmed.is_empty()
1132 });
1133
1134 if !all_simple {
1135 debug!("ImportMerge contains non-import lines - requires manual resolution");
1136 return Ok(None);
1137 }
1138
1139 let mut all_imports: Vec<&str> = our_lines
1141 .into_iter()
1142 .chain(their_lines)
1143 .filter(|line| !line.trim().is_empty())
1144 .collect();
1145 all_imports.sort();
1146 all_imports.dedup();
1147 Ok(Some(all_imports.join("\n")))
1148 }
1149 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1150 Ok(None)
1152 }
1153 }
1154 }
1155
1156 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1158 let lines: Vec<&str> = content.lines().collect();
1159 let mut conflicts = Vec::new();
1160 let mut i = 0;
1161
1162 while i < lines.len() {
1163 if lines[i].starts_with("<<<<<<<") {
1164 let start_line = i + 1;
1166 let mut separator_line = None;
1167 let mut end_line = None;
1168
1169 for (j, line) in lines.iter().enumerate().skip(i + 1) {
1171 if line.starts_with("=======") {
1172 separator_line = Some(j + 1);
1173 } else if line.starts_with(">>>>>>>") {
1174 end_line = Some(j + 1);
1175 break;
1176 }
1177 }
1178
1179 if let (Some(sep), Some(end)) = (separator_line, end_line) {
1180 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1182 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1183
1184 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1185 let their_content = lines[sep..(end - 1)].join("\n");
1186
1187 conflicts.push(ConflictRegion {
1188 start: start_pos,
1189 end: end_pos,
1190 start_line,
1191 end_line: end,
1192 our_content,
1193 their_content,
1194 });
1195
1196 i = end;
1197 } else {
1198 i += 1;
1199 }
1200 } else {
1201 i += 1;
1202 }
1203 }
1204
1205 Ok(conflicts)
1206 }
1207
1208 fn resolve_single_conflict(
1210 &self,
1211 conflict: &ConflictRegion,
1212 file_path: &str,
1213 ) -> Result<Option<String>> {
1214 debug!(
1215 "Analyzing conflict in {} (lines {}-{})",
1216 file_path, conflict.start_line, conflict.end_line
1217 );
1218
1219 if let Some(resolved) = self.resolve_whitespace_conflict(conflict)? {
1221 debug!("Resolved as whitespace-only conflict");
1222 return Ok(Some(resolved));
1223 }
1224
1225 if let Some(resolved) = self.resolve_line_ending_conflict(conflict)? {
1227 debug!("Resolved as line ending conflict");
1228 return Ok(Some(resolved));
1229 }
1230
1231 if let Some(resolved) = self.resolve_addition_conflict(conflict)? {
1233 debug!("Resolved as pure addition conflict");
1234 return Ok(Some(resolved));
1235 }
1236
1237 if let Some(resolved) = self.resolve_import_conflict(conflict, file_path)? {
1239 debug!("Resolved as import reordering conflict");
1240 return Ok(Some(resolved));
1241 }
1242
1243 Ok(None)
1245 }
1246
1247 fn resolve_whitespace_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1249 let our_normalized = self.normalize_whitespace(&conflict.our_content);
1250 let their_normalized = self.normalize_whitespace(&conflict.their_content);
1251
1252 if our_normalized == their_normalized {
1253 let resolved =
1255 if conflict.our_content.trim().len() >= conflict.their_content.trim().len() {
1256 conflict.our_content.clone()
1257 } else {
1258 conflict.their_content.clone()
1259 };
1260
1261 return Ok(Some(resolved));
1262 }
1263
1264 Ok(None)
1265 }
1266
1267 fn resolve_line_ending_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1269 let our_normalized = conflict
1270 .our_content
1271 .replace("\r\n", "\n")
1272 .replace('\r', "\n");
1273 let their_normalized = conflict
1274 .their_content
1275 .replace("\r\n", "\n")
1276 .replace('\r', "\n");
1277
1278 if our_normalized == their_normalized {
1279 return Ok(Some(our_normalized));
1281 }
1282
1283 Ok(None)
1284 }
1285
1286 fn resolve_addition_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1288 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1289 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1290
1291 if our_lines.is_empty() {
1293 return Ok(Some(conflict.their_content.clone()));
1294 }
1295 if their_lines.is_empty() {
1296 return Ok(Some(conflict.our_content.clone()));
1297 }
1298
1299 let mut merged_lines = Vec::new();
1301 let mut our_idx = 0;
1302 let mut their_idx = 0;
1303
1304 while our_idx < our_lines.len() || their_idx < their_lines.len() {
1305 if our_idx >= our_lines.len() {
1306 merged_lines.extend_from_slice(&their_lines[their_idx..]);
1308 break;
1309 } else if their_idx >= their_lines.len() {
1310 merged_lines.extend_from_slice(&our_lines[our_idx..]);
1312 break;
1313 } else if our_lines[our_idx] == their_lines[their_idx] {
1314 merged_lines.push(our_lines[our_idx]);
1316 our_idx += 1;
1317 their_idx += 1;
1318 } else {
1319 return Ok(None);
1321 }
1322 }
1323
1324 Ok(Some(merged_lines.join("\n")))
1325 }
1326
1327 fn resolve_import_conflict(
1329 &self,
1330 conflict: &ConflictRegion,
1331 file_path: &str,
1332 ) -> Result<Option<String>> {
1333 let is_import_file = file_path.ends_with(".rs")
1335 || file_path.ends_with(".py")
1336 || file_path.ends_with(".js")
1337 || file_path.ends_with(".ts")
1338 || file_path.ends_with(".go")
1339 || file_path.ends_with(".java")
1340 || file_path.ends_with(".swift")
1341 || file_path.ends_with(".kt")
1342 || file_path.ends_with(".cs");
1343
1344 if !is_import_file {
1345 return Ok(None);
1346 }
1347
1348 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1349 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1350
1351 let our_imports = our_lines
1353 .iter()
1354 .all(|line| self.is_import_line(line, file_path));
1355 let their_imports = their_lines
1356 .iter()
1357 .all(|line| self.is_import_line(line, file_path));
1358
1359 if our_imports && their_imports {
1360 let mut all_imports: Vec<&str> = our_lines.into_iter().chain(their_lines).collect();
1362 all_imports.sort();
1363 all_imports.dedup();
1364
1365 return Ok(Some(all_imports.join("\n")));
1366 }
1367
1368 Ok(None)
1369 }
1370
1371 fn is_import_line(&self, line: &str, file_path: &str) -> bool {
1373 let trimmed = line.trim();
1374
1375 if trimmed.is_empty() {
1376 return true; }
1378
1379 if file_path.ends_with(".rs") {
1380 return trimmed.starts_with("use ") || trimmed.starts_with("extern crate");
1381 } else if file_path.ends_with(".py") {
1382 return trimmed.starts_with("import ") || trimmed.starts_with("from ");
1383 } else if file_path.ends_with(".js") || file_path.ends_with(".ts") {
1384 return trimmed.starts_with("import ")
1385 || trimmed.starts_with("const ")
1386 || trimmed.starts_with("require(");
1387 } else if file_path.ends_with(".go") {
1388 return trimmed.starts_with("import ") || trimmed == "import (" || trimmed == ")";
1389 } else if file_path.ends_with(".java") {
1390 return trimmed.starts_with("import ");
1391 } else if file_path.ends_with(".swift") {
1392 return trimmed.starts_with("import ") || trimmed.starts_with("@testable import ");
1393 } else if file_path.ends_with(".kt") {
1394 return trimmed.starts_with("import ") || trimmed.starts_with("@file:");
1395 } else if file_path.ends_with(".cs") {
1396 return trimmed.starts_with("using ") || trimmed.starts_with("extern alias ");
1397 }
1398
1399 false
1400 }
1401
1402 fn normalize_whitespace(&self, content: &str) -> String {
1404 content
1405 .lines()
1406 .map(|line| line.trim())
1407 .filter(|line| !line.is_empty())
1408 .collect::<Vec<_>>()
1409 .join("\n")
1410 }
1411
1412 fn update_stack_entry(
1415 &mut self,
1416 stack_id: Uuid,
1417 entry_id: &Uuid,
1418 _new_branch: &str,
1419 new_commit_hash: &str,
1420 ) -> Result<()> {
1421 debug!(
1422 "Updating entry {} in stack {} with new commit {}",
1423 entry_id, stack_id, new_commit_hash
1424 );
1425
1426 let stack = self
1428 .stack_manager
1429 .get_stack_mut(&stack_id)
1430 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1431
1432 if let Some(entry) = stack.entries.iter_mut().find(|e| e.id == *entry_id) {
1434 debug!(
1435 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch '{}')",
1436 entry_id, entry.commit_hash, new_commit_hash, entry.branch
1437 );
1438
1439 entry.commit_hash = new_commit_hash.to_string();
1442
1443 debug!(
1446 "Successfully updated entry {} in stack {}",
1447 entry_id, stack_id
1448 );
1449 Ok(())
1450 } else {
1451 Err(CascadeError::config(format!(
1452 "Entry {entry_id} not found in stack {stack_id}"
1453 )))
1454 }
1455 }
1456
1457 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1459 info!("Pulling latest changes for branch {}", branch);
1460
1461 match self.git_repo.fetch() {
1463 Ok(_) => {
1464 debug!("Fetch successful");
1465 match self.git_repo.pull(branch) {
1467 Ok(_) => {
1468 info!("Pull completed successfully for {}", branch);
1469 Ok(())
1470 }
1471 Err(e) => {
1472 warn!("Pull failed for {}: {}", branch, e);
1473 Ok(())
1475 }
1476 }
1477 }
1478 Err(e) => {
1479 warn!("Fetch failed: {}", e);
1480 Ok(())
1482 }
1483 }
1484 }
1485
1486 pub fn is_rebase_in_progress(&self) -> bool {
1488 let git_dir = self.git_repo.path().join(".git");
1490 git_dir.join("REBASE_HEAD").exists()
1491 || git_dir.join("rebase-merge").exists()
1492 || git_dir.join("rebase-apply").exists()
1493 }
1494
1495 pub fn abort_rebase(&self) -> Result<()> {
1497 info!("Aborting rebase operation");
1498
1499 let git_dir = self.git_repo.path().join(".git");
1500
1501 if git_dir.join("REBASE_HEAD").exists() {
1503 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1504 CascadeError::Git(git2::Error::from_str(&format!(
1505 "Failed to clean rebase state: {e}"
1506 )))
1507 })?;
1508 }
1509
1510 if git_dir.join("rebase-merge").exists() {
1511 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1512 CascadeError::Git(git2::Error::from_str(&format!(
1513 "Failed to clean rebase-merge: {e}"
1514 )))
1515 })?;
1516 }
1517
1518 if git_dir.join("rebase-apply").exists() {
1519 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1520 CascadeError::Git(git2::Error::from_str(&format!(
1521 "Failed to clean rebase-apply: {e}"
1522 )))
1523 })?;
1524 }
1525
1526 info!("Rebase aborted successfully");
1527 Ok(())
1528 }
1529
1530 pub fn continue_rebase(&self) -> Result<()> {
1532 info!("Continuing rebase operation");
1533
1534 if self.git_repo.has_conflicts()? {
1536 return Err(CascadeError::branch(
1537 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1538 ));
1539 }
1540
1541 self.git_repo.stage_conflict_resolved_files()?;
1543
1544 info!("Rebase continued successfully");
1545 Ok(())
1546 }
1547
1548 fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1550 let git_dir = self.git_repo.path().join(".git");
1551 Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1552 }
1553
1554 fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1556 use crate::cli::output::Output;
1557
1558 let git_dir = self.git_repo.path().join(".git");
1559
1560 Output::section("Resuming in-progress sync");
1561 println!();
1562 Output::info("Detected unfinished cherry-pick from previous sync");
1563 println!();
1564
1565 if self.git_repo.has_conflicts()? {
1567 let conflicted_files = self.git_repo.get_conflicted_files()?;
1568
1569 let result = RebaseResult {
1570 success: false,
1571 branch_mapping: HashMap::new(),
1572 conflicts: conflicted_files.clone(),
1573 new_commits: Vec::new(),
1574 error: Some(format!(
1575 "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1576 MANUAL CONFLICT RESOLUTION REQUIRED\n\
1577 =====================================\n\n\
1578 Conflicted files:\n{}\n\n\
1579 Step 1: Analyze conflicts\n\
1580 โ Run: ca conflicts\n\
1581 โ Shows detailed conflict analysis\n\n\
1582 Step 2: Resolve conflicts in your editor\n\
1583 โ Open conflicted files and edit them\n\
1584 โ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1585 โ Keep the code you want\n\
1586 โ Save the files\n\n\
1587 Step 3: Mark conflicts as resolved\n\
1588 โ Run: git add <resolved-files>\n\
1589 โ Or: git add -A (to stage all resolved files)\n\n\
1590 Step 4: Complete the sync\n\
1591 โ Run: ca sync\n\
1592 โ Cascade will continue from where it left off\n\n\
1593 Alternative: Abort and start over\n\
1594 โ Run: git cherry-pick --abort\n\
1595 โ Then: ca sync (starts fresh)",
1596 conflicted_files.len(),
1597 conflicted_files
1598 .iter()
1599 .map(|f| format!(" - {}", f))
1600 .collect::<Vec<_>>()
1601 .join("\n")
1602 )),
1603 summary: "Sync paused - conflicts need resolution".to_string(),
1604 };
1605
1606 return Ok(result);
1607 }
1608
1609 Output::info("Conflicts resolved, continuing cherry-pick...");
1611
1612 self.git_repo.stage_conflict_resolved_files()?;
1614
1615 let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1617 let commit_message = if cherry_pick_msg_file.exists() {
1618 std::fs::read_to_string(&cherry_pick_msg_file)
1619 .unwrap_or_else(|_| "Resolved conflicts".to_string())
1620 } else {
1621 "Resolved conflicts".to_string()
1622 };
1623
1624 match self.git_repo.commit(&commit_message) {
1625 Ok(_new_commit_id) => {
1626 Output::success("Cherry-pick completed");
1627
1628 if git_dir.join("CHERRY_PICK_HEAD").exists() {
1630 let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1631 }
1632 if cherry_pick_msg_file.exists() {
1633 let _ = std::fs::remove_file(&cherry_pick_msg_file);
1634 }
1635
1636 println!();
1637 Output::info("Continuing with rest of stack...");
1638 println!();
1639
1640 self.rebase_with_force_push(stack)
1643 }
1644 Err(e) => {
1645 let result = RebaseResult {
1646 success: false,
1647 branch_mapping: HashMap::new(),
1648 conflicts: Vec::new(),
1649 new_commits: Vec::new(),
1650 error: Some(format!(
1651 "Failed to complete cherry-pick: {}\n\n\
1652 This usually means:\n\
1653 - Git index is locked (another process accessing repo)\n\
1654 - File permissions issue\n\
1655 - Disk space issue\n\n\
1656 Recovery:\n\
1657 1. Check if another Git operation is running\n\
1658 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1659 3. Run 'git status' to check repo state\n\
1660 4. Retry 'ca sync' after fixing the issue\n\n\
1661 Or abort and start fresh:\n\
1662 โ Run: git cherry-pick --abort\n\
1663 โ Then: ca sync",
1664 e
1665 )),
1666 summary: "Failed to complete cherry-pick".to_string(),
1667 };
1668
1669 Ok(result)
1670 }
1671 }
1672 }
1673}
1674
1675impl RebaseResult {
1676 pub fn get_summary(&self) -> String {
1678 if self.success {
1679 format!("โ
{}", self.summary)
1680 } else {
1681 format!(
1682 "โ Rebase failed: {}",
1683 self.error.as_deref().unwrap_or("Unknown error")
1684 )
1685 }
1686 }
1687
1688 pub fn has_conflicts(&self) -> bool {
1690 !self.conflicts.is_empty()
1691 }
1692
1693 pub fn success_count(&self) -> usize {
1695 self.new_commits.len()
1696 }
1697}
1698
1699#[cfg(test)]
1700mod tests {
1701 use super::*;
1702 use std::path::PathBuf;
1703 use std::process::Command;
1704 use tempfile::TempDir;
1705
1706 #[allow(dead_code)]
1707 fn create_test_repo() -> (TempDir, PathBuf) {
1708 let temp_dir = TempDir::new().unwrap();
1709 let repo_path = temp_dir.path().to_path_buf();
1710
1711 Command::new("git")
1713 .args(["init"])
1714 .current_dir(&repo_path)
1715 .output()
1716 .unwrap();
1717 Command::new("git")
1718 .args(["config", "user.name", "Test"])
1719 .current_dir(&repo_path)
1720 .output()
1721 .unwrap();
1722 Command::new("git")
1723 .args(["config", "user.email", "test@test.com"])
1724 .current_dir(&repo_path)
1725 .output()
1726 .unwrap();
1727
1728 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1730 Command::new("git")
1731 .args(["add", "."])
1732 .current_dir(&repo_path)
1733 .output()
1734 .unwrap();
1735 Command::new("git")
1736 .args(["commit", "-m", "Initial"])
1737 .current_dir(&repo_path)
1738 .output()
1739 .unwrap();
1740
1741 (temp_dir, repo_path)
1742 }
1743
1744 #[test]
1745 fn test_conflict_region_creation() {
1746 let region = ConflictRegion {
1747 start: 0,
1748 end: 50,
1749 start_line: 1,
1750 end_line: 3,
1751 our_content: "function test() {\n return true;\n}".to_string(),
1752 their_content: "function test() {\n return true;\n}".to_string(),
1753 };
1754
1755 assert_eq!(region.start_line, 1);
1756 assert_eq!(region.end_line, 3);
1757 assert!(region.our_content.contains("return true"));
1758 assert!(region.their_content.contains("return true"));
1759 }
1760
1761 #[test]
1762 fn test_rebase_strategies() {
1763 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1764 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1765 }
1766
1767 #[test]
1768 fn test_rebase_options() {
1769 let options = RebaseOptions::default();
1770 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1771 assert!(!options.interactive);
1772 assert!(options.auto_resolve);
1773 assert_eq!(options.max_retries, 3);
1774 }
1775
1776 #[test]
1777 fn test_cleanup_guard_tracks_branches() {
1778 let mut guard = TempBranchCleanupGuard::new();
1779 assert!(guard.branches.is_empty());
1780
1781 guard.add_branch("test-branch-1".to_string());
1782 guard.add_branch("test-branch-2".to_string());
1783
1784 assert_eq!(guard.branches.len(), 2);
1785 assert_eq!(guard.branches[0], "test-branch-1");
1786 assert_eq!(guard.branches[1], "test-branch-2");
1787 }
1788
1789 #[test]
1790 fn test_cleanup_guard_prevents_double_cleanup() {
1791 use std::process::Command;
1792 use tempfile::TempDir;
1793
1794 let temp_dir = TempDir::new().unwrap();
1796 let repo_path = temp_dir.path();
1797
1798 Command::new("git")
1799 .args(["init"])
1800 .current_dir(repo_path)
1801 .output()
1802 .unwrap();
1803
1804 Command::new("git")
1805 .args(["config", "user.name", "Test"])
1806 .current_dir(repo_path)
1807 .output()
1808 .unwrap();
1809
1810 Command::new("git")
1811 .args(["config", "user.email", "test@test.com"])
1812 .current_dir(repo_path)
1813 .output()
1814 .unwrap();
1815
1816 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1818 Command::new("git")
1819 .args(["add", "."])
1820 .current_dir(repo_path)
1821 .output()
1822 .unwrap();
1823 Command::new("git")
1824 .args(["commit", "-m", "initial"])
1825 .current_dir(repo_path)
1826 .output()
1827 .unwrap();
1828
1829 let git_repo = GitRepository::open(repo_path).unwrap();
1830
1831 git_repo.create_branch("test-temp", None).unwrap();
1833
1834 let mut guard = TempBranchCleanupGuard::new();
1835 guard.add_branch("test-temp".to_string());
1836
1837 guard.cleanup(&git_repo);
1839 assert!(guard.cleaned);
1840
1841 guard.cleanup(&git_repo);
1843 assert!(guard.cleaned);
1844 }
1845
1846 #[test]
1847 fn test_rebase_result() {
1848 let result = RebaseResult {
1849 success: true,
1850 branch_mapping: std::collections::HashMap::new(),
1851 conflicts: vec!["abc123".to_string()],
1852 new_commits: vec!["def456".to_string()],
1853 error: None,
1854 summary: "Test summary".to_string(),
1855 };
1856
1857 assert!(result.success);
1858 assert!(result.has_conflicts());
1859 assert_eq!(result.success_count(), 1);
1860 }
1861
1862 #[test]
1863 fn test_import_line_detection() {
1864 let (_temp_dir, repo_path) = create_test_repo();
1865 let git_repo = crate::git::GitRepository::open(&repo_path).unwrap();
1866 let stack_manager = crate::stack::StackManager::new(&repo_path).unwrap();
1867 let options = RebaseOptions::default();
1868 let rebase_manager = RebaseManager::new(stack_manager, git_repo, options);
1869
1870 assert!(rebase_manager.is_import_line("import Foundation", "test.swift"));
1872 assert!(rebase_manager.is_import_line("@testable import MyModule", "test.swift"));
1873 assert!(!rebase_manager.is_import_line("class MyClass {", "test.swift"));
1874
1875 assert!(rebase_manager.is_import_line("import kotlin.collections.*", "test.kt"));
1877 assert!(rebase_manager.is_import_line("@file:JvmName(\"Utils\")", "test.kt"));
1878 assert!(!rebase_manager.is_import_line("fun myFunction() {", "test.kt"));
1879
1880 assert!(rebase_manager.is_import_line("using System;", "test.cs"));
1882 assert!(rebase_manager.is_import_line("using System.Collections.Generic;", "test.cs"));
1883 assert!(rebase_manager.is_import_line("extern alias GridV1;", "test.cs"));
1884 assert!(!rebase_manager.is_import_line("namespace MyNamespace {", "test.cs"));
1885
1886 assert!(rebase_manager.is_import_line("", "test.swift"));
1888 assert!(rebase_manager.is_import_line(" ", "test.kt"));
1889 assert!(rebase_manager.is_import_line("", "test.cs"));
1890 }
1891}