1use crate::errors::{CascadeError, Result};
2use crate::git::{ConflictAnalyzer, GitRepository};
3use crate::stack::{Stack, StackManager, SyncState};
4use chrono::Utc;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use tracing::debug;
8use uuid::Uuid;
9
10#[derive(Debug, Clone)]
12enum ConflictResolution {
13 Resolved,
15 TooComplex,
17}
18
19#[derive(Debug, Clone)]
21#[allow(dead_code)]
22struct ConflictRegion {
23 start: usize,
25 end: usize,
27 start_line: usize,
29 end_line: usize,
31 our_content: String,
33 their_content: String,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
39pub enum RebaseStrategy {
40 ForcePush,
43 Interactive,
45}
46
47#[derive(Debug, Clone)]
49pub struct RebaseOptions {
50 pub strategy: RebaseStrategy,
52 pub interactive: bool,
54 pub target_base: Option<String>,
56 pub preserve_merges: bool,
58 pub auto_resolve: bool,
60 pub max_retries: usize,
62 pub skip_pull: Option<bool>,
64 pub original_working_branch: Option<String>,
67}
68
69#[derive(Debug)]
71pub struct RebaseResult {
72 pub success: bool,
74 pub branch_mapping: HashMap<String, String>,
76 pub conflicts: Vec<String>,
78 pub new_commits: Vec<String>,
80 pub error: Option<String>,
82 pub summary: String,
84}
85
86#[allow(dead_code)]
92struct TempBranchCleanupGuard {
93 branches: Vec<String>,
94 cleaned: bool,
95}
96
97#[allow(dead_code)]
98impl TempBranchCleanupGuard {
99 fn new() -> Self {
100 Self {
101 branches: Vec::new(),
102 cleaned: false,
103 }
104 }
105
106 fn add_branch(&mut self, branch: String) {
107 self.branches.push(branch);
108 }
109
110 fn cleanup(&mut self, git_repo: &GitRepository) {
112 if self.cleaned || self.branches.is_empty() {
113 return;
114 }
115
116 tracing::debug!("Cleaning up {} temporary branches", self.branches.len());
117 for branch in &self.branches {
118 if let Err(e) = git_repo.delete_branch_unsafe(branch) {
119 tracing::debug!("Failed to delete temp branch {}: {}", branch, e);
120 }
122 }
123 self.cleaned = true;
124 }
125}
126
127impl Drop for TempBranchCleanupGuard {
128 fn drop(&mut self) {
129 if !self.cleaned && !self.branches.is_empty() {
130 tracing::warn!(
133 "{} temporary branches were not cleaned up: {}",
134 self.branches.len(),
135 self.branches.join(", ")
136 );
137 tracing::warn!("Run 'ca cleanup' to remove orphaned temporary branches");
138 }
139 }
140}
141
142pub struct RebaseManager {
144 stack_manager: StackManager,
145 git_repo: GitRepository,
146 options: RebaseOptions,
147 conflict_analyzer: ConflictAnalyzer,
148}
149
150impl Default for RebaseOptions {
151 fn default() -> Self {
152 Self {
153 strategy: RebaseStrategy::ForcePush,
154 interactive: false,
155 target_base: None,
156 preserve_merges: true,
157 auto_resolve: true,
158 max_retries: 3,
159 skip_pull: None,
160 original_working_branch: None,
161 }
162 }
163}
164
165impl RebaseManager {
166 pub fn new(
168 stack_manager: StackManager,
169 git_repo: GitRepository,
170 options: RebaseOptions,
171 ) -> Self {
172 Self {
173 stack_manager,
174 git_repo,
175 options,
176 conflict_analyzer: ConflictAnalyzer::new(),
177 }
178 }
179
180 pub fn into_stack_manager(self) -> StackManager {
182 self.stack_manager
183 }
184
185 pub fn rebase_stack(&mut self, stack_id: &Uuid) -> Result<RebaseResult> {
187 debug!("Starting rebase for stack {}", stack_id);
188
189 let stack = self
190 .stack_manager
191 .get_stack(stack_id)
192 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?
193 .clone();
194
195 match self.options.strategy {
196 RebaseStrategy::ForcePush => self.rebase_with_force_push(&stack),
197 RebaseStrategy::Interactive => self.rebase_interactive(&stack),
198 }
199 }
200
201 fn rebase_with_force_push(&mut self, stack: &Stack) -> Result<RebaseResult> {
205 use crate::cli::output::Output;
206
207 if self.has_in_progress_cherry_pick()? {
209 return self.handle_in_progress_cherry_pick(stack);
210 }
211
212 Output::section(format!("Rebasing stack: {}", stack.name));
214 Output::sub_item(format!("Base branch: {}", stack.base_branch));
215
216 let total_entries = stack.entries.len();
218 let merged_count = stack.entries.iter().filter(|e| e.is_merged).count();
219 let unmerged_count = total_entries - merged_count;
220
221 if merged_count > 0 {
222 Output::sub_item(format!(
223 "Entries: {} total ({} merged, {} to rebase)",
224 total_entries, merged_count, unmerged_count
225 ));
226 } else {
227 Output::sub_item(format!("Entries: {}", total_entries));
228 }
229
230 let mut result = RebaseResult {
231 success: true,
232 branch_mapping: HashMap::new(),
233 conflicts: Vec::new(),
234 new_commits: Vec::new(),
235 error: None,
236 summary: String::new(),
237 };
238
239 let target_base = self
240 .options
241 .target_base
242 .as_ref()
243 .unwrap_or(&stack.base_branch)
244 .clone(); let original_branch = self
250 .options
251 .original_working_branch
252 .clone()
253 .or_else(|| self.git_repo.get_current_branch().ok());
254
255 let original_branch_for_cleanup = original_branch.clone();
257
258 if let Some(ref orig) = original_branch {
261 if orig == &target_base {
262 debug!(
263 "Original working branch is base branch '{}' - will skip working branch update",
264 orig
265 );
266 }
267 }
268
269 if !self.options.skip_pull.unwrap_or(false) {
272 if let Err(e) = self.pull_latest_changes(&target_base) {
273 Output::warning(format!("Could not pull latest changes: {}", e));
274 }
275 }
276
277 if let Err(e) = self.git_repo.reset_to_head() {
279 if let Some(ref orig) = original_branch_for_cleanup {
281 let _ = self.git_repo.checkout_branch_unsafe(orig);
282 }
283
284 return Err(CascadeError::branch(format!(
285 "Could not reset working directory to HEAD: {}.\n\
286 Another Git process may still be holding the index lock. \
287 Resolve the lock (remove .git/index.lock if safe) and retry.",
288 e
289 )));
290 }
291
292 let mut current_base = target_base.clone();
293 let entry_count = stack.entries.iter().filter(|e| !e.is_merged).count();
295 let mut temp_branches: Vec<String> = Vec::new(); if entry_count == 0 {
299 println!();
300 if stack.entries.is_empty() {
301 Output::info("Stack has no entries yet");
302 Output::tip("Use 'ca push' to add commits to this stack");
303 result.summary = "Stack is empty".to_string();
304 } else {
305 Output::info("All entries in this stack have been merged");
306 Output::tip("Use 'ca push' to add new commits, or 'ca stack cleanup' to prune merged branches");
307 result.summary = "All entries merged".to_string();
308 }
309
310 println!();
312 Output::success(&result.summary);
313
314 self.stack_manager.save_to_disk()?;
316 return Ok(result);
317 }
318
319 let all_up_to_date = stack
321 .entries
322 .iter()
323 .filter(|entry| !entry.is_merged) .all(|entry| {
325 self.git_repo
326 .is_commit_based_on(&entry.commit_hash, &target_base)
327 .unwrap_or(false)
328 });
329
330 if all_up_to_date {
331 println!();
332 Output::success("Stack is already up-to-date with base branch");
333 result.summary = "Stack is up-to-date".to_string();
334 result.success = true;
335 return Ok(result);
336 }
337
338 let repo_root = self.git_repo.path().to_path_buf();
339 let mut sync_state = SyncState {
340 stack_id: stack.id.to_string(),
341 stack_name: stack.name.clone(),
342 original_branch: original_branch_for_cleanup
343 .clone()
344 .unwrap_or_else(|| target_base.clone()),
345 target_base: target_base.clone(),
346 remaining_entry_ids: stack.entries.iter().map(|e| e.id.to_string()).collect(),
347 current_entry_id: String::new(),
348 current_entry_branch: String::new(),
349 current_temp_branch: String::new(),
350 temp_branches: Vec::new(),
351 };
352
353 let _ = SyncState::delete(&repo_root);
355
356 let mut branches_with_new_commits: std::collections::HashSet<String> =
359 std::collections::HashSet::new();
360 let mut branches_to_push: Vec<(String, String, usize)> = Vec::new(); let mut processed_entries: usize = 0; for (index, entry) in stack.entries.iter().enumerate() {
363 let original_branch = &entry.branch;
364 let entry_id_str = entry.id.to_string();
365
366 sync_state.remaining_entry_ids = stack
367 .entries
368 .iter()
369 .skip(index + 1)
370 .map(|e| e.id.to_string())
371 .collect();
372
373 if entry.is_merged {
375 tracing::debug!(
376 "Entry '{}' is merged into '{}', skipping rebase",
377 original_branch,
378 target_base
379 );
380 continue;
382 }
383
384 processed_entries += 1;
385
386 sync_state.current_entry_id = entry_id_str.clone();
387 sync_state.current_entry_branch = original_branch.clone();
388
389 if self
392 .git_repo
393 .is_commit_based_on(&entry.commit_hash, ¤t_base)
394 .unwrap_or(false)
395 {
396 tracing::debug!(
397 "Entry '{}' is already correctly based on '{}', skipping rebase",
398 original_branch,
399 current_base
400 );
401
402 result
403 .branch_mapping
404 .insert(original_branch.clone(), original_branch.clone());
405
406 current_base = original_branch.clone();
408 continue;
409 }
410
411 if !result.success {
414 tracing::debug!(
415 "Skipping entry '{}' because previous entry failed",
416 original_branch
417 );
418 break;
419 }
420
421 let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
424 temp_branches.push(temp_branch.clone()); sync_state.current_temp_branch = temp_branch.clone();
426
427 if let Err(e) = self
429 .git_repo
430 .create_branch(&temp_branch, Some(¤t_base))
431 {
432 if let Some(ref orig) = original_branch_for_cleanup {
434 let _ = self.git_repo.checkout_branch_unsafe(orig);
435 }
436 return Err(e);
437 }
438
439 if let Err(e) = self.git_repo.checkout_branch_silent(&temp_branch) {
440 if let Some(ref orig) = original_branch_for_cleanup {
442 let _ = self.git_repo.checkout_branch_unsafe(orig);
443 }
444 return Err(e);
445 }
446
447 sync_state.temp_branches = temp_branches.clone();
449 sync_state.save(&repo_root)?;
450
451 match self.cherry_pick_commit(&entry.commit_hash) {
453 Ok(new_commit_hash) => {
454 result.new_commits.push(new_commit_hash.clone());
455
456 let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
458
459 self.git_repo
462 .update_branch_to_commit(original_branch, &rebased_commit_id)?;
463
464 result
465 .branch_mapping
466 .insert(original_branch.clone(), original_branch.clone());
467
468 self.update_stack_entry(
470 stack.id,
471 &entry.id,
472 original_branch,
473 &rebased_commit_id,
474 )?;
475 branches_with_new_commits.insert(original_branch.clone());
476
477 if let Some(pr_num) = &entry.pull_request_id {
479 let tree_char = if processed_entries == entry_count {
480 "└─"
481 } else {
482 "├─"
483 };
484 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
485 branches_to_push.push((
486 original_branch.clone(),
487 pr_num.clone(),
488 processed_entries - 1,
489 ));
490 }
491
492 current_base = original_branch.clone();
494
495 let _ = SyncState::delete(&repo_root);
496 }
497 Err(e) => {
498 if self.git_repo.get_conflicted_files()?.is_empty() {
500 debug!(
501 "Cherry-pick produced no changes for {} ({}), skipping entry",
502 original_branch,
503 &entry.commit_hash[..8]
504 );
505
506 Output::warning(format!(
507 "Skipping entry '{}' - cherry-pick resulted in no changes",
508 original_branch
509 ));
510 Output::sub_item("This usually means the base branch has moved forward");
511 Output::sub_item("and this entry's changes are already present");
512
513 let _ = std::process::Command::new("git")
515 .args(["cherry-pick", "--abort"])
516 .current_dir(self.git_repo.path())
517 .output();
518
519 let _ = self.git_repo.checkout_branch_unsafe(&target_base);
521 let _ = self.git_repo.delete_branch_unsafe(&temp_branch);
522 let _ = temp_branches.pop();
523 let _ = SyncState::delete(&repo_root);
524
525 continue;
527 }
528
529 result.conflicts.push(entry.commit_hash.clone());
530
531 if !self.options.auto_resolve {
532 println!();
533 Output::error(e.to_string());
534 result.success = false;
535 result.error = Some(format!(
536 "Conflict in {}: {}\n\n\
537 MANUAL CONFLICT RESOLUTION REQUIRED\n\
538 =====================================\n\n\
539 Step 1: Analyze conflicts\n\
540 → Run: ca conflicts\n\
541 → This shows which conflicts are in which files\n\n\
542 Step 2: Resolve conflicts in your editor\n\
543 → Open conflicted files and edit them\n\
544 → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
545 → Keep the code you want\n\
546 → Save the files\n\n\
547 Step 3: Mark conflicts as resolved\n\
548 → Run: git add <resolved-files>\n\
549 → Or: git add -A (to stage all resolved files)\n\n\
550 Step 4: Complete the sync\n\
551 → Run: ca sync continue\n\
552 → Cascade will complete the cherry-pick and continue\n\n\
553 Alternative: Abort and start over\n\
554 → Run: ca sync abort\n\
555 → Then: ca sync (starts fresh)\n\n\
556 TIP: Enable auto-resolution for simple conflicts:\n\
557 → Run: ca sync --auto-resolve\n\
558 → Only complex conflicts will require manual resolution",
559 entry.commit_hash, e
560 ));
561 break;
562 }
563
564 match self.auto_resolve_conflicts(&entry.commit_hash) {
566 Ok(fully_resolved) => {
567 if !fully_resolved {
568 result.success = false;
569 result.error = Some(format!(
570 "Conflicts in commit {}\n\n\
571 To resolve:\n\
572 1. Fix conflicts in your editor\n\
573 2. Stage resolved files: git add <files>\n\
574 3. Continue: ca sync continue\n\n\
575 Or abort:\n\
576 → Run: ca sync abort",
577 &entry.commit_hash[..8]
578 ));
579 break;
580 }
581
582 let commit_message = entry.message.trim().to_string();
585
586 debug!("Checking staged files before commit");
588 let staged_files = self.git_repo.get_staged_files()?;
589
590 if staged_files.is_empty() {
591 debug!(
594 "Cherry-pick resulted in empty commit for {}",
595 &entry.commit_hash[..8]
596 );
597
598 Output::warning(format!(
600 "Skipping entry '{}' - cherry-pick resulted in no changes",
601 original_branch
602 ));
603 Output::sub_item(
604 "This usually means the base branch has moved forward",
605 );
606 Output::sub_item("and this entry's changes are already present");
607
608 let _ = std::process::Command::new("git")
610 .args(["cherry-pick", "--abort"])
611 .current_dir(self.git_repo.path())
612 .output();
613
614 let _ = self.git_repo.checkout_branch_unsafe(&target_base);
615 let _ = self.git_repo.delete_branch_unsafe(&temp_branch);
616 let _ = temp_branches.pop();
617
618 let _ = SyncState::delete(&repo_root);
619
620 continue;
622 }
623
624 debug!("{} files staged", staged_files.len());
625
626 match self.git_repo.commit(&commit_message) {
627 Ok(new_commit_id) => {
628 debug!(
629 "Created commit {} with message '{}'",
630 &new_commit_id[..8],
631 commit_message
632 );
633
634 if let Err(e) = self.git_repo.cleanup_state() {
636 tracing::warn!(
637 "Failed to clean up repository state after auto-resolve: {}",
638 e
639 );
640 }
641
642 Output::success("Auto-resolved conflicts");
643 result.new_commits.push(new_commit_id.clone());
644 let rebased_commit_id = new_commit_id;
645
646 self.cleanup_backup_files()?;
648
649 self.git_repo.update_branch_to_commit(
651 original_branch,
652 &rebased_commit_id,
653 )?;
654
655 branches_with_new_commits.insert(original_branch.clone());
656
657 if let Some(pr_num) = &entry.pull_request_id {
659 let tree_char = if processed_entries == entry_count {
660 "└─"
661 } else {
662 "├─"
663 };
664 println!(
665 " {} {} (PR #{})",
666 tree_char, original_branch, pr_num
667 );
668 branches_to_push.push((
669 original_branch.clone(),
670 pr_num.clone(),
671 processed_entries - 1,
672 ));
673 }
674
675 result
676 .branch_mapping
677 .insert(original_branch.clone(), original_branch.clone());
678
679 self.update_stack_entry(
681 stack.id,
682 &entry.id,
683 original_branch,
684 &rebased_commit_id,
685 )?;
686
687 current_base = original_branch.clone();
689 }
690 Err(commit_err) => {
691 result.success = false;
692 result.error = Some(format!(
693 "Could not commit auto-resolved conflicts: {}\n\n\
694 This usually means:\n\
695 - Git index is locked (another process accessing repo)\n\
696 - File permissions issue\n\
697 - Disk space issue\n\n\
698 Recovery:\n\
699 1. Check if another Git operation is running\n\
700 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
701 3. Run 'git status' to check repo state\n\
702 4. Retry 'ca sync' after fixing the issue",
703 commit_err
704 ));
705 break;
706 }
707 }
708 }
709 Err(resolve_err) => {
710 result.success = false;
711 result.error = Some(format!(
712 "Could not resolve conflicts: {}\n\n\
713 Recovery:\n\
714 1. Check repo state: 'git status'\n\
715 2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
716 3. Remove any lock files: 'rm -f .git/index.lock'\n\
717 4. Retry 'ca sync'",
718 resolve_err
719 ));
720 break;
721 }
722 }
723 }
724 }
725 }
726
727 if result.success && !temp_branches.is_empty() {
731 if let Err(e) = self.git_repo.checkout_branch_unsafe(&target_base) {
734 debug!("Could not checkout base for cleanup: {}", e);
735 } else {
738 for temp_branch in &temp_branches {
740 if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
741 debug!("Could not delete temp branch {}: {}", temp_branch, e);
742 }
743 }
744 }
745 }
746
747 let pushed_count = branches_to_push.len();
753 let _skipped_count = entry_count - pushed_count; let mut successful_pushes = 0; if !result.success {
757 println!();
758 Output::error("Rebase failed - not pushing any branches");
759 } else {
762 if !branches_to_push.is_empty() {
766 println!();
767
768 if let Err(e) = self.git_repo.fetch_with_retry() {
770 Output::warning(format!("Could not fetch latest remote state: {}", e));
771 Output::tip("Continuing with push, but backup branches may not be created if remote state is unknown");
772 }
773
774 let mut push_results = Vec::new();
776 for (branch_name, _pr_num, _index) in branches_to_push.iter() {
777 let result = self
778 .git_repo
779 .force_push_single_branch_auto_no_fetch(branch_name);
780 push_results.push((branch_name.clone(), result));
781 }
782
783 let mut failed_pushes = 0;
785 for (index, (branch_name, result)) in push_results.iter().enumerate() {
786 match result {
787 Ok(_) => {
788 debug!("Pushed {} successfully", branch_name);
789 successful_pushes += 1;
790 println!(
791 " ✓ Pushed {} ({}/{})",
792 branch_name,
793 index + 1,
794 pushed_count
795 );
796 }
797 Err(e) => {
798 failed_pushes += 1;
799 println!(" ⚠ Could not push '{}': {}", branch_name, e);
800 }
801 }
802 }
803
804 if failed_pushes > 0 {
806 println!(); Output::warning(format!(
808 "{} branch(es) failed to push to remote",
809 failed_pushes
810 ));
811 Output::tip("To retry failed pushes, run: ca sync");
812 }
813 }
814
815 let entries_word = if entry_count == 1 { "entry" } else { "entries" };
817 let pr_word = if successful_pushes == 1 { "PR" } else { "PRs" };
818
819 result.summary = if successful_pushes > 0 {
820 let not_submitted_count = entry_count - successful_pushes;
821 if not_submitted_count > 0 {
822 format!(
823 "{} {} rebased ({} {} updated, {} not yet submitted)",
824 entry_count, entries_word, successful_pushes, pr_word, not_submitted_count
825 )
826 } else {
827 format!(
828 "{} {} rebased ({} {} updated)",
829 entry_count, entries_word, successful_pushes, pr_word
830 )
831 }
832 } else {
833 format!(
834 "{} {} rebased (none submitted to Bitbucket yet)",
835 entry_count, entries_word
836 )
837 };
838 } if result.success {
841 if let Some(ref working_branch_name) = stack.working_branch {
846 if working_branch_name != &target_base {
848 if let Some(last_entry) = stack.entries.last() {
849 let top_branch = &last_entry.branch;
850
851 if let (Ok(working_head), Ok(top_commit)) = (
854 self.git_repo.get_branch_head(working_branch_name),
855 self.git_repo.get_branch_head(top_branch),
856 ) {
857 if working_head != top_commit {
859 if let Ok(commits) = self
861 .git_repo
862 .get_commits_between(&top_commit, &working_head)
863 {
864 if !commits.is_empty() {
865 let stack_messages: Vec<String> = stack
868 .entries
869 .iter()
870 .map(|e| e.message.trim().to_string())
871 .collect();
872
873 let all_match_stack = commits.iter().all(|commit| {
874 if let Some(msg) = commit.summary() {
875 stack_messages
876 .iter()
877 .any(|stack_msg| stack_msg == msg.trim())
878 } else {
879 false
880 }
881 });
882
883 if all_match_stack {
884 debug!(
889 "Working branch has old pre-rebase commits (matching stack messages) - safe to update"
890 );
891 } else {
892 Output::error(format!(
894 "Cannot sync: Working branch '{}' has {} commit(s) not in the stack",
895 working_branch_name,
896 commits.len()
897 ));
898 println!();
899 Output::sub_item(
900 "These commits would be lost if we proceed:",
901 );
902 for (i, commit) in commits.iter().take(5).enumerate() {
903 let message =
904 commit.summary().unwrap_or("(no message)");
905 Output::sub_item(format!(
906 " {}. {} - {}",
907 i + 1,
908 &commit.id().to_string()[..8],
909 message
910 ));
911 }
912 if commits.len() > 5 {
913 Output::sub_item(format!(
914 " ... and {} more",
915 commits.len() - 5
916 ));
917 }
918 println!();
919 Output::tip("Add these commits to the stack first:");
920 Output::bullet("Run: ca stack push");
921 Output::bullet("Then run: ca sync");
922 println!();
923
924 if let Some(ref orig) = original_branch_for_cleanup {
926 let _ = self.git_repo.checkout_branch_unsafe(orig);
927 }
928
929 return Err(CascadeError::validation(
930 format!(
931 "Working branch '{}' has {} untracked commit(s). Add them to the stack with 'ca stack push' before syncing.",
932 working_branch_name, commits.len()
933 )
934 ));
935 }
936 }
937 }
938 }
939
940 debug!(
942 "Updating working branch '{}' to match top of stack ({})",
943 working_branch_name,
944 &top_commit[..8]
945 );
946
947 if let Err(e) = self
948 .git_repo
949 .update_branch_to_commit(working_branch_name, &top_commit)
950 {
951 Output::warning(format!(
952 "Could not update working branch '{}' to top of stack: {}",
953 working_branch_name, e
954 ));
955 }
956 }
957 }
958 } else {
959 debug!(
961 "Skipping working branch update - working branch '{}' is the base branch",
962 working_branch_name
963 );
964 }
965 }
966
967 if let Some(ref orig_branch) = original_branch {
970 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
971 debug!(
972 "Could not return to original branch '{}': {}",
973 orig_branch, e
974 );
975 }
977 }
978 }
979 println!();
984 if result.success {
985 Output::success(&result.summary);
986 } else {
987 let error_msg = result
989 .error
990 .as_deref()
991 .unwrap_or("Rebase failed for unknown reason");
992 Output::error(error_msg);
993 }
994
995 self.stack_manager.save_to_disk()?;
997
998 if !result.success {
1001 let detailed_error = result.error.as_deref().unwrap_or("Rebase failed");
1002 return Err(CascadeError::Branch(detailed_error.to_string()));
1003 }
1004
1005 Ok(result)
1006 }
1007
1008 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
1010 tracing::debug!("Starting interactive rebase for stack '{}'", stack.name);
1011
1012 let mut result = RebaseResult {
1013 success: true,
1014 branch_mapping: HashMap::new(),
1015 conflicts: Vec::new(),
1016 new_commits: Vec::new(),
1017 error: None,
1018 summary: String::new(),
1019 };
1020
1021 println!("Interactive Rebase for Stack: {}", stack.name);
1022 println!(" Base branch: {}", stack.base_branch);
1023 println!(" Entries: {}", stack.entries.len());
1024
1025 if self.options.interactive {
1026 println!("\nChoose action for each commit:");
1027 println!(" (p)ick - apply the commit");
1028 println!(" (s)kip - skip this commit");
1029 println!(" (e)dit - edit the commit message");
1030 println!(" (q)uit - abort the rebase");
1031 }
1032
1033 for entry in &stack.entries {
1036 println!(
1037 " {} {} - {}",
1038 entry.short_hash(),
1039 entry.branch,
1040 entry.short_message(50)
1041 );
1042
1043 match self.cherry_pick_commit(&entry.commit_hash) {
1045 Ok(new_commit) => result.new_commits.push(new_commit),
1046 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
1047 }
1048 }
1049
1050 result.summary = format!(
1051 "Interactive rebase processed {} commits",
1052 stack.entries.len()
1053 );
1054 Ok(result)
1055 }
1056
1057 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
1059 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
1061
1062 if let Ok(staged_files) = self.git_repo.get_staged_files() {
1064 if !staged_files.is_empty() {
1065 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
1067 match self.git_repo.commit_staged_changes(&cleanup_message) {
1068 Ok(Some(_)) => {
1069 debug!(
1070 "Committed {} leftover staged files after cherry-pick",
1071 staged_files.len()
1072 );
1073 }
1074 Ok(None) => {
1075 debug!("Staged files were cleared before commit");
1077 }
1078 Err(e) => {
1079 tracing::warn!(
1081 "Failed to commit {} staged files after cherry-pick: {}. \
1082 User may see checkout warning with staged changes.",
1083 staged_files.len(),
1084 e
1085 );
1086 }
1088 }
1089 }
1090 }
1091
1092 Ok(new_commit_hash)
1093 }
1094
1095 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
1097 debug!("Starting auto-resolve for commit {}", commit_hash);
1098
1099 let has_conflicts = self.git_repo.has_conflicts()?;
1101 debug!("has_conflicts() = {}", has_conflicts);
1102
1103 let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
1105 let cherry_pick_in_progress = cherry_pick_head.exists();
1106
1107 if !has_conflicts {
1108 debug!("No conflicts detected by Git index");
1109
1110 if cherry_pick_in_progress {
1112 tracing::debug!(
1113 "CHERRY_PICK_HEAD exists but no conflicts in index - aborting cherry-pick"
1114 );
1115
1116 let _ = std::process::Command::new("git")
1118 .args(["cherry-pick", "--abort"])
1119 .current_dir(self.git_repo.path())
1120 .output();
1121
1122 return Err(CascadeError::Branch(format!(
1123 "Cherry-pick failed for {} but Git index shows no conflicts. \
1124 This usually means the cherry-pick was aborted or failed in an unexpected way. \
1125 Please try manual resolution.",
1126 &commit_hash[..8]
1127 )));
1128 }
1129
1130 return Ok(true);
1131 }
1132
1133 let conflicted_files = self.git_repo.get_conflicted_files()?;
1134
1135 if conflicted_files.is_empty() {
1136 debug!("Conflicted files list is empty");
1137 return Ok(true);
1138 }
1139
1140 debug!(
1141 "Found conflicts in {} files: {:?}",
1142 conflicted_files.len(),
1143 conflicted_files
1144 );
1145
1146 let analysis = self
1148 .conflict_analyzer
1149 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
1150
1151 debug!(
1152 "Conflict analysis: {} total conflicts, {} auto-resolvable",
1153 analysis.total_conflicts, analysis.auto_resolvable_count
1154 );
1155
1156 for recommendation in &analysis.recommendations {
1158 debug!("{}", recommendation);
1159 }
1160
1161 let mut resolved_count = 0;
1162 let mut resolved_files = Vec::new(); let mut failed_files = Vec::new();
1164
1165 for file_analysis in &analysis.files {
1166 debug!(
1167 "Processing file: {} (auto_resolvable: {}, conflicts: {})",
1168 file_analysis.file_path,
1169 file_analysis.auto_resolvable,
1170 file_analysis.conflicts.len()
1171 );
1172
1173 if file_analysis.auto_resolvable {
1174 match self.resolve_file_conflicts_enhanced(
1175 &file_analysis.file_path,
1176 &file_analysis.conflicts,
1177 ) {
1178 Ok(ConflictResolution::Resolved) => {
1179 resolved_count += 1;
1180 resolved_files.push(file_analysis.file_path.clone());
1181 debug!("Successfully resolved {}", file_analysis.file_path);
1182 }
1183 Ok(ConflictResolution::TooComplex) => {
1184 debug!(
1185 "{} too complex for auto-resolution",
1186 file_analysis.file_path
1187 );
1188 failed_files.push(file_analysis.file_path.clone());
1189 }
1190 Err(e) => {
1191 debug!("Failed to resolve {}: {}", file_analysis.file_path, e);
1192 failed_files.push(file_analysis.file_path.clone());
1193 }
1194 }
1195 } else {
1196 failed_files.push(file_analysis.file_path.clone());
1197 debug!(
1198 "{} requires manual resolution ({} conflicts)",
1199 file_analysis.file_path,
1200 file_analysis.conflicts.len()
1201 );
1202 }
1203 }
1204
1205 if resolved_count > 0 {
1206 debug!(
1207 "Resolved {}/{} files",
1208 resolved_count,
1209 conflicted_files.len()
1210 );
1211 debug!("Resolved files: {:?}", resolved_files);
1212
1213 let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
1216 debug!("Staging {} files", file_paths.len());
1217 self.git_repo.stage_files(&file_paths)?;
1218 debug!("Files staged successfully");
1219 } else {
1220 debug!("No files were resolved (resolved_count = 0)");
1221 }
1222
1223 let all_resolved = failed_files.is_empty();
1225
1226 debug!(
1227 "all_resolved = {}, failed_files = {:?}",
1228 all_resolved, failed_files
1229 );
1230
1231 if !all_resolved {
1232 debug!("{} files still need manual resolution", failed_files.len());
1233 }
1234
1235 debug!("Returning all_resolved = {}", all_resolved);
1236 Ok(all_resolved)
1237 }
1238
1239 fn resolve_file_conflicts_enhanced(
1241 &self,
1242 file_path: &str,
1243 conflicts: &[crate::git::ConflictRegion],
1244 ) -> Result<ConflictResolution> {
1245 let repo_path = self.git_repo.path();
1246 let full_path = repo_path.join(file_path);
1247
1248 let mut content = std::fs::read_to_string(&full_path)
1250 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
1251
1252 if conflicts.is_empty() {
1253 return Ok(ConflictResolution::Resolved);
1254 }
1255
1256 tracing::debug!(
1257 "Resolving {} conflicts in {} using enhanced analysis",
1258 conflicts.len(),
1259 file_path
1260 );
1261
1262 let mut any_resolved = false;
1263
1264 for conflict in conflicts.iter().rev() {
1266 match self.resolve_single_conflict_enhanced(conflict) {
1267 Ok(Some(resolution)) => {
1268 let before = &content[..conflict.start_pos];
1270 let after = &content[conflict.end_pos..];
1271 content = format!("{before}{resolution}{after}");
1272 any_resolved = true;
1273 debug!(
1274 "✅ Resolved {} conflict at lines {}-{} in {}",
1275 format!("{:?}", conflict.conflict_type).to_lowercase(),
1276 conflict.start_line,
1277 conflict.end_line,
1278 file_path
1279 );
1280 }
1281 Ok(None) => {
1282 debug!(
1283 "⚠️ {} conflict at lines {}-{} in {} requires manual resolution",
1284 format!("{:?}", conflict.conflict_type).to_lowercase(),
1285 conflict.start_line,
1286 conflict.end_line,
1287 file_path
1288 );
1289 return Ok(ConflictResolution::TooComplex);
1290 }
1291 Err(e) => {
1292 debug!("❌ Failed to resolve conflict in {}: {}", file_path, e);
1293 return Ok(ConflictResolution::TooComplex);
1294 }
1295 }
1296 }
1297
1298 if any_resolved {
1299 let remaining_conflicts = self.parse_conflict_markers(&content)?;
1301
1302 if remaining_conflicts.is_empty() {
1303 debug!(
1304 "All conflicts resolved in {}, content length: {} bytes",
1305 file_path,
1306 content.len()
1307 );
1308
1309 if content.trim().is_empty() {
1311 tracing::warn!(
1312 "SAFETY CHECK: Resolved content for {} is empty! Aborting auto-resolution.",
1313 file_path
1314 );
1315 return Ok(ConflictResolution::TooComplex);
1316 }
1317
1318 let backup_path = full_path.with_extension("cascade-backup");
1320 if let Ok(original_content) = std::fs::read_to_string(&full_path) {
1321 debug!(
1322 "Backup for {} (original: {} bytes, resolved: {} bytes)",
1323 file_path,
1324 original_content.len(),
1325 content.len()
1326 );
1327 let _ = std::fs::write(&backup_path, original_content);
1328 }
1329
1330 crate::utils::atomic_file::write_string(&full_path, &content)?;
1332
1333 debug!("Wrote {} bytes to {}", content.len(), file_path);
1334 return Ok(ConflictResolution::Resolved);
1335 } else {
1336 tracing::debug!(
1337 "Partially resolved conflicts in {} ({} remaining)",
1338 file_path,
1339 remaining_conflicts.len()
1340 );
1341 }
1342 }
1343
1344 Ok(ConflictResolution::TooComplex)
1345 }
1346
1347 #[allow(dead_code)]
1349 fn count_whitespace_consistency(content: &str) -> usize {
1350 let mut inconsistencies = 0;
1351 let lines: Vec<&str> = content.lines().collect();
1352
1353 for line in &lines {
1354 if line.contains('\t') && line.contains(' ') {
1356 inconsistencies += 1;
1357 }
1358 }
1359
1360 lines.len().saturating_sub(inconsistencies)
1362 }
1363
1364 fn cleanup_backup_files(&self) -> Result<()> {
1366 use std::fs;
1367 use std::path::Path;
1368
1369 let repo_path = self.git_repo.path();
1370
1371 fn remove_backups_recursive(dir: &Path) {
1373 if let Ok(entries) = fs::read_dir(dir) {
1374 for entry in entries.flatten() {
1375 let path = entry.path();
1376
1377 if path.is_dir() {
1378 if path.file_name().and_then(|n| n.to_str()) != Some(".git") {
1380 remove_backups_recursive(&path);
1381 }
1382 } else if let Some(ext) = path.extension() {
1383 if ext == "cascade-backup" {
1384 debug!("Cleaning up backup file: {}", path.display());
1385 if let Err(e) = fs::remove_file(&path) {
1386 tracing::warn!(
1388 "Could not remove backup file {}: {}",
1389 path.display(),
1390 e
1391 );
1392 }
1393 }
1394 }
1395 }
1396 }
1397 }
1398
1399 remove_backups_recursive(repo_path);
1400 Ok(())
1401 }
1402
1403 fn resolve_single_conflict_enhanced(
1405 &self,
1406 conflict: &crate::git::ConflictRegion,
1407 ) -> Result<Option<String>> {
1408 debug!(
1409 "Resolving {} conflict in {} (lines {}-{})",
1410 format!("{:?}", conflict.conflict_type).to_lowercase(),
1411 conflict.file_path,
1412 conflict.start_line,
1413 conflict.end_line
1414 );
1415
1416 use crate::git::ConflictType;
1417
1418 match conflict.conflict_type {
1419 ConflictType::Whitespace => {
1420 let our_normalized = conflict
1423 .our_content
1424 .split_whitespace()
1425 .collect::<Vec<_>>()
1426 .join(" ");
1427 let their_normalized = conflict
1428 .their_content
1429 .split_whitespace()
1430 .collect::<Vec<_>>()
1431 .join(" ");
1432
1433 if our_normalized == their_normalized {
1434 Ok(Some(conflict.their_content.clone()))
1439 } else {
1440 debug!(
1442 "Whitespace conflict has content differences - requires manual resolution"
1443 );
1444 Ok(None)
1445 }
1446 }
1447 ConflictType::LineEnding => {
1448 let normalized = conflict
1450 .our_content
1451 .replace("\r\n", "\n")
1452 .replace('\r', "\n");
1453 Ok(Some(normalized))
1454 }
1455 ConflictType::PureAddition => {
1456 if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1460 Ok(Some(conflict.their_content.clone()))
1462 } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1463 Ok(Some(String::new()))
1465 } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1466 Ok(Some(String::new()))
1468 } else {
1469 debug!(
1475 "PureAddition conflict has content on both sides - requires manual resolution"
1476 );
1477 Ok(None)
1478 }
1479 }
1480 ConflictType::ImportMerge => {
1481 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1486 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1487
1488 let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1490 let trimmed = line.trim();
1491 trimmed.starts_with("import ")
1492 || trimmed.starts_with("from ")
1493 || trimmed.starts_with("use ")
1494 || trimmed.starts_with("#include")
1495 || trimmed.is_empty()
1496 });
1497
1498 if !all_simple {
1499 debug!("ImportMerge contains non-import lines - requires manual resolution");
1500 return Ok(None);
1501 }
1502
1503 let mut all_imports: Vec<&str> = our_lines
1505 .into_iter()
1506 .chain(their_lines)
1507 .filter(|line| !line.trim().is_empty())
1508 .collect();
1509 all_imports.sort();
1510 all_imports.dedup();
1511 Ok(Some(all_imports.join("\n")))
1512 }
1513 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1514 Ok(None)
1516 }
1517 }
1518 }
1519
1520 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1522 let lines: Vec<&str> = content.lines().collect();
1523 let mut conflicts = Vec::new();
1524 let mut i = 0;
1525
1526 while i < lines.len() {
1527 if lines[i].starts_with("<<<<<<<") {
1528 let start_line = i + 1;
1530 let mut separator_line = None;
1531 let mut end_line = None;
1532
1533 for (j, line) in lines.iter().enumerate().skip(i + 1) {
1535 if line.starts_with("=======") {
1536 separator_line = Some(j + 1);
1537 } else if line.starts_with(">>>>>>>") {
1538 end_line = Some(j + 1);
1539 break;
1540 }
1541 }
1542
1543 if let (Some(sep), Some(end)) = (separator_line, end_line) {
1544 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1546 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1547
1548 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1549 let their_content = lines[sep..(end - 1)].join("\n");
1550
1551 conflicts.push(ConflictRegion {
1552 start: start_pos,
1553 end: end_pos,
1554 start_line,
1555 end_line: end,
1556 our_content,
1557 their_content,
1558 });
1559
1560 i = end;
1561 } else {
1562 i += 1;
1563 }
1564 } else {
1565 i += 1;
1566 }
1567 }
1568
1569 Ok(conflicts)
1570 }
1571
1572 fn update_stack_entry(
1575 &mut self,
1576 stack_id: Uuid,
1577 entry_id: &Uuid,
1578 _new_branch: &str,
1579 new_commit_hash: &str,
1580 ) -> Result<()> {
1581 debug!(
1582 "Updating entry {} in stack {} with new commit {}",
1583 entry_id, stack_id, new_commit_hash
1584 );
1585
1586 let stack = self
1588 .stack_manager
1589 .get_stack_mut(&stack_id)
1590 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1591
1592 let entry_exists = stack.entries.iter().any(|e| e.id == *entry_id);
1594
1595 if entry_exists {
1596 let old_hash = stack
1597 .entries
1598 .iter()
1599 .find(|e| e.id == *entry_id)
1600 .map(|e| e.commit_hash.clone())
1601 .unwrap();
1602
1603 debug!(
1604 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch)",
1605 entry_id, old_hash, new_commit_hash
1606 );
1607
1608 stack
1611 .update_entry_commit_hash(entry_id, new_commit_hash.to_string())
1612 .map_err(CascadeError::config)?;
1613
1614 debug!(
1617 "Successfully updated entry {} in stack {}",
1618 entry_id, stack_id
1619 );
1620 Ok(())
1621 } else {
1622 Err(CascadeError::config(format!(
1623 "Entry {entry_id} not found in stack {stack_id}"
1624 )))
1625 }
1626 }
1627
1628 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1630 tracing::debug!("Pulling latest changes for branch {}", branch);
1631
1632 match self.git_repo.fetch() {
1634 Ok(_) => {
1635 debug!("Fetch successful");
1636 match self.git_repo.pull(branch) {
1638 Ok(_) => {
1639 tracing::debug!("Pull completed successfully for {}", branch);
1640 Ok(())
1641 }
1642 Err(e) => {
1643 tracing::debug!("Pull failed for {}: {}", branch, e);
1644 Ok(())
1646 }
1647 }
1648 }
1649 Err(e) => {
1650 tracing::debug!("Fetch failed: {}", e);
1651 Ok(())
1653 }
1654 }
1655 }
1656
1657 pub fn is_rebase_in_progress(&self) -> bool {
1659 let git_dir = self.git_repo.path().join(".git");
1661 git_dir.join("REBASE_HEAD").exists()
1662 || git_dir.join("rebase-merge").exists()
1663 || git_dir.join("rebase-apply").exists()
1664 }
1665
1666 pub fn abort_rebase(&self) -> Result<()> {
1668 tracing::debug!("Aborting rebase operation");
1669
1670 let git_dir = self.git_repo.path().join(".git");
1671
1672 if git_dir.join("REBASE_HEAD").exists() {
1674 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1675 CascadeError::Git(git2::Error::from_str(&format!(
1676 "Failed to clean rebase state: {e}"
1677 )))
1678 })?;
1679 }
1680
1681 if git_dir.join("rebase-merge").exists() {
1682 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1683 CascadeError::Git(git2::Error::from_str(&format!(
1684 "Failed to clean rebase-merge: {e}"
1685 )))
1686 })?;
1687 }
1688
1689 if git_dir.join("rebase-apply").exists() {
1690 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1691 CascadeError::Git(git2::Error::from_str(&format!(
1692 "Failed to clean rebase-apply: {e}"
1693 )))
1694 })?;
1695 }
1696
1697 tracing::debug!("Rebase aborted successfully");
1698 Ok(())
1699 }
1700
1701 pub fn continue_rebase(&self) -> Result<()> {
1703 tracing::debug!("Continuing rebase operation");
1704
1705 if self.git_repo.has_conflicts()? {
1707 return Err(CascadeError::branch(
1708 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1709 ));
1710 }
1711
1712 self.git_repo.stage_conflict_resolved_files()?;
1714
1715 tracing::debug!("Rebase continued successfully");
1716 Ok(())
1717 }
1718
1719 fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1721 let git_dir = self.git_repo.path().join(".git");
1722 Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1723 }
1724
1725 fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1727 use crate::cli::output::Output;
1728
1729 let git_dir = self.git_repo.path().join(".git");
1730
1731 Output::section("Resuming in-progress sync");
1732 println!();
1733 Output::info("Detected unfinished cherry-pick from previous sync");
1734 println!();
1735
1736 if self.git_repo.has_conflicts()? {
1738 let conflicted_files = self.git_repo.get_conflicted_files()?;
1739
1740 let result = RebaseResult {
1741 success: false,
1742 branch_mapping: HashMap::new(),
1743 conflicts: conflicted_files.clone(),
1744 new_commits: Vec::new(),
1745 error: Some(format!(
1746 "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1747 MANUAL CONFLICT RESOLUTION REQUIRED\n\
1748 =====================================\n\n\
1749 Conflicted files:\n{}\n\n\
1750 Step 1: Analyze conflicts\n\
1751 → Run: ca conflicts\n\
1752 → Shows detailed conflict analysis\n\n\
1753 Step 2: Resolve conflicts in your editor\n\
1754 → Open conflicted files and edit them\n\
1755 → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1756 → Keep the code you want\n\
1757 → Save the files\n\n\
1758 Step 3: Mark conflicts as resolved\n\
1759 → Run: git add <resolved-files>\n\
1760 → Or: git add -A (to stage all resolved files)\n\n\
1761 Step 4: Complete the sync\n\
1762 → Run: ca sync continue\n\
1763 → Cascade will complete the cherry-pick and continue\n\n\
1764 Alternative: Abort and start over\n\
1765 → Run: ca sync abort\n\
1766 → Then: ca sync (starts fresh)",
1767 conflicted_files.len(),
1768 conflicted_files
1769 .iter()
1770 .map(|f| format!(" - {}", f))
1771 .collect::<Vec<_>>()
1772 .join("\n")
1773 )),
1774 summary: "Sync paused - conflicts need resolution".to_string(),
1775 };
1776
1777 return Ok(result);
1778 }
1779
1780 Output::info("Conflicts resolved, continuing cherry-pick...");
1782
1783 self.git_repo.stage_conflict_resolved_files()?;
1785
1786 let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1788 let commit_message = if cherry_pick_msg_file.exists() {
1789 std::fs::read_to_string(&cherry_pick_msg_file)
1790 .unwrap_or_else(|_| "Resolved conflicts".to_string())
1791 } else {
1792 "Resolved conflicts".to_string()
1793 };
1794
1795 match self.git_repo.commit(&commit_message) {
1796 Ok(_new_commit_id) => {
1797 Output::success("Cherry-pick completed");
1798
1799 if git_dir.join("CHERRY_PICK_HEAD").exists() {
1801 let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1802 }
1803 if cherry_pick_msg_file.exists() {
1804 let _ = std::fs::remove_file(&cherry_pick_msg_file);
1805 }
1806
1807 println!();
1808 Output::info("Continuing with rest of stack...");
1809 println!();
1810
1811 self.rebase_with_force_push(stack)
1814 }
1815 Err(e) => {
1816 let result = RebaseResult {
1817 success: false,
1818 branch_mapping: HashMap::new(),
1819 conflicts: Vec::new(),
1820 new_commits: Vec::new(),
1821 error: Some(format!(
1822 "Failed to complete cherry-pick: {}\n\n\
1823 This usually means:\n\
1824 - Git index is locked (another process accessing repo)\n\
1825 - File permissions issue\n\
1826 - Disk space issue\n\n\
1827 Recovery:\n\
1828 1. Check if another Git operation is running\n\
1829 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1830 3. Run 'git status' to check repo state\n\
1831 4. Retry 'ca sync' after fixing the issue\n\n\
1832 Or abort and start fresh:\n\
1833 → Run: ca sync abort\n\
1834 → Then: ca sync",
1835 e
1836 )),
1837 summary: "Failed to complete cherry-pick".to_string(),
1838 };
1839
1840 Ok(result)
1841 }
1842 }
1843 }
1844}
1845
1846impl RebaseResult {
1847 pub fn get_summary(&self) -> String {
1849 if self.success {
1850 format!("✅ {}", self.summary)
1851 } else {
1852 format!(
1853 "❌ Rebase failed: {}",
1854 self.error.as_deref().unwrap_or("Unknown error")
1855 )
1856 }
1857 }
1858
1859 pub fn has_conflicts(&self) -> bool {
1861 !self.conflicts.is_empty()
1862 }
1863
1864 pub fn success_count(&self) -> usize {
1866 self.new_commits.len()
1867 }
1868}
1869
1870#[cfg(test)]
1871mod tests {
1872 use super::*;
1873 use std::path::PathBuf;
1874 use std::process::Command;
1875 use tempfile::TempDir;
1876
1877 #[allow(dead_code)]
1878 fn create_test_repo() -> (TempDir, PathBuf) {
1879 let temp_dir = TempDir::new().unwrap();
1880 let repo_path = temp_dir.path().to_path_buf();
1881
1882 Command::new("git")
1884 .args(["init"])
1885 .current_dir(&repo_path)
1886 .output()
1887 .unwrap();
1888 Command::new("git")
1889 .args(["config", "user.name", "Test"])
1890 .current_dir(&repo_path)
1891 .output()
1892 .unwrap();
1893 Command::new("git")
1894 .args(["config", "user.email", "test@test.com"])
1895 .current_dir(&repo_path)
1896 .output()
1897 .unwrap();
1898
1899 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1901 Command::new("git")
1902 .args(["add", "."])
1903 .current_dir(&repo_path)
1904 .output()
1905 .unwrap();
1906 Command::new("git")
1907 .args(["commit", "-m", "Initial"])
1908 .current_dir(&repo_path)
1909 .output()
1910 .unwrap();
1911
1912 (temp_dir, repo_path)
1913 }
1914
1915 #[test]
1916 fn test_conflict_region_creation() {
1917 let region = ConflictRegion {
1918 start: 0,
1919 end: 50,
1920 start_line: 1,
1921 end_line: 3,
1922 our_content: "function test() {\n return true;\n}".to_string(),
1923 their_content: "function test() {\n return true;\n}".to_string(),
1924 };
1925
1926 assert_eq!(region.start_line, 1);
1927 assert_eq!(region.end_line, 3);
1928 assert!(region.our_content.contains("return true"));
1929 assert!(region.their_content.contains("return true"));
1930 }
1931
1932 #[test]
1933 fn test_rebase_strategies() {
1934 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1935 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1936 }
1937
1938 #[test]
1939 fn test_rebase_options() {
1940 let options = RebaseOptions::default();
1941 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1942 assert!(!options.interactive);
1943 assert!(options.auto_resolve);
1944 assert_eq!(options.max_retries, 3);
1945 }
1946
1947 #[test]
1948 fn test_cleanup_guard_tracks_branches() {
1949 let mut guard = TempBranchCleanupGuard::new();
1950 assert!(guard.branches.is_empty());
1951
1952 guard.add_branch("test-branch-1".to_string());
1953 guard.add_branch("test-branch-2".to_string());
1954
1955 assert_eq!(guard.branches.len(), 2);
1956 assert_eq!(guard.branches[0], "test-branch-1");
1957 assert_eq!(guard.branches[1], "test-branch-2");
1958 }
1959
1960 #[test]
1961 fn test_cleanup_guard_prevents_double_cleanup() {
1962 use std::process::Command;
1963 use tempfile::TempDir;
1964
1965 let temp_dir = TempDir::new().unwrap();
1967 let repo_path = temp_dir.path();
1968
1969 Command::new("git")
1970 .args(["init"])
1971 .current_dir(repo_path)
1972 .output()
1973 .unwrap();
1974
1975 Command::new("git")
1976 .args(["config", "user.name", "Test"])
1977 .current_dir(repo_path)
1978 .output()
1979 .unwrap();
1980
1981 Command::new("git")
1982 .args(["config", "user.email", "test@test.com"])
1983 .current_dir(repo_path)
1984 .output()
1985 .unwrap();
1986
1987 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1989 Command::new("git")
1990 .args(["add", "."])
1991 .current_dir(repo_path)
1992 .output()
1993 .unwrap();
1994 Command::new("git")
1995 .args(["commit", "-m", "initial"])
1996 .current_dir(repo_path)
1997 .output()
1998 .unwrap();
1999
2000 let git_repo = GitRepository::open(repo_path).unwrap();
2001
2002 git_repo.create_branch("test-temp", None).unwrap();
2004
2005 let mut guard = TempBranchCleanupGuard::new();
2006 guard.add_branch("test-temp".to_string());
2007
2008 guard.cleanup(&git_repo);
2010 assert!(guard.cleaned);
2011
2012 guard.cleanup(&git_repo);
2014 assert!(guard.cleaned);
2015 }
2016
2017 #[test]
2018 fn test_rebase_result() {
2019 let result = RebaseResult {
2020 success: true,
2021 branch_mapping: std::collections::HashMap::new(),
2022 conflicts: vec!["abc123".to_string()],
2023 new_commits: vec!["def456".to_string()],
2024 error: None,
2025 summary: "Test summary".to_string(),
2026 };
2027
2028 assert!(result.success);
2029 assert!(result.has_conflicts());
2030 assert_eq!(result.success_count(), 1);
2031 }
2032}