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 match self.git_repo.commit(&commit_message) {
402 Ok(new_commit_id) => {
403 Output::success("Auto-resolved conflicts");
404 result.new_commits.push(new_commit_id.clone());
405 let rebased_commit_id = new_commit_id;
406
407 self.git_repo.update_branch_to_commit(
409 original_branch,
410 &rebased_commit_id,
411 )?;
412
413 let tree_char = if index + 1 == entry_count {
415 "โโ"
416 } else {
417 "โโ"
418 };
419
420 if let Some(pr_num) = &entry.pull_request_id {
421 println!(
422 " {} {} (PR #{})",
423 tree_char, original_branch, pr_num
424 );
425 branches_to_push
426 .push((original_branch.clone(), pr_num.clone()));
427 } else {
428 println!(
429 " {} {} (not submitted)",
430 tree_char, original_branch
431 );
432 }
433
434 result
435 .branch_mapping
436 .insert(original_branch.clone(), original_branch.clone());
437
438 self.update_stack_entry(
440 stack.id,
441 &entry.id,
442 original_branch,
443 &rebased_commit_id,
444 )?;
445
446 current_base = original_branch.clone();
448 }
449 Err(commit_err) => {
450 result.success = false;
451 result.error = Some(format!(
452 "Could not commit auto-resolved conflicts: {}\n\n\
453 This usually means:\n\
454 - Git index is locked (another process accessing repo)\n\
455 - File permissions issue\n\
456 - Disk space issue\n\n\
457 Recovery:\n\
458 1. Check if another Git operation is running\n\
459 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
460 3. Run 'git status' to check repo state\n\
461 4. Retry 'ca sync' after fixing the issue",
462 commit_err
463 ));
464 break;
465 }
466 }
467 }
468 Err(resolve_err) => {
469 result.success = false;
470 result.error = Some(format!(
471 "Could not resolve conflicts: {}\n\n\
472 Recovery:\n\
473 1. Check repo state: 'git status'\n\
474 2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
475 3. Remove any lock files: 'rm -f .git/index.lock'\n\
476 4. Retry 'ca sync'",
477 resolve_err
478 ));
479 break;
480 }
481 }
482 }
483 }
484 }
485
486 if !temp_branches.is_empty() {
489 if let Err(e) = self.git_repo.checkout_branch_unsafe(&target_base) {
492 Output::warning(format!("Could not checkout base for cleanup: {}", e));
493 } else {
496 for temp_branch in &temp_branches {
498 if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
499 debug!("Could not delete temp branch {}: {}", temp_branch, e);
500 }
501 }
502 }
503 }
504
505 let pushed_count = branches_to_push.len();
508 let skipped_count = entry_count - pushed_count;
509
510 if !branches_to_push.is_empty() {
511 println!(); println!(
513 "Pushing {} branch{} to remote...",
514 pushed_count,
515 if pushed_count == 1 { "" } else { "es" }
516 );
517
518 for (branch_name, _pr_num) in &branches_to_push {
519 match self.git_repo.force_push_single_branch_auto(branch_name) {
520 Ok(_) => {
521 debug!("Pushed {} successfully", branch_name);
522 }
523 Err(e) => {
524 Output::warning(format!("Could not push '{}': {}", branch_name, e));
525 }
527 }
528 }
529 }
530
531 if let Some(ref orig_branch) = original_branch {
534 if orig_branch != &target_base {
536 if let Some(last_entry) = stack.entries.last() {
538 let top_branch = &last_entry.branch;
539
540 if let Ok(top_commit) = self.git_repo.get_branch_head(top_branch) {
542 debug!(
543 "Updating working branch '{}' to match top of stack ({})",
544 orig_branch,
545 &top_commit[..8]
546 );
547
548 if let Err(e) = self
549 .git_repo
550 .update_branch_to_commit(orig_branch, &top_commit)
551 {
552 Output::warning(format!(
553 "Could not update working branch '{}' to top of stack: {}",
554 orig_branch, e
555 ));
556 }
557 }
558 }
559
560 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
563 debug!(
564 "Could not return to original branch '{}': {}",
565 orig_branch, e
566 );
567 }
569 } else {
570 debug!(
573 "Skipping working branch update - user was on base branch '{}'",
574 orig_branch
575 );
576 if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
577 debug!("Could not return to base branch '{}': {}", orig_branch, e);
578 }
579 }
580 }
581
582 result.summary = if pushed_count > 0 {
584 let pr_plural = if pushed_count == 1 { "" } else { "s" };
585 let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
586
587 if skipped_count > 0 {
588 format!(
589 "{} {} rebased ({} PR{} updated, {} not yet submitted)",
590 entry_count, entry_plural, pushed_count, pr_plural, skipped_count
591 )
592 } else {
593 format!(
594 "{} {} rebased ({} PR{} updated)",
595 entry_count, entry_plural, pushed_count, pr_plural
596 )
597 }
598 } else {
599 let plural = if entry_count == 1 { "entry" } else { "entries" };
600 format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
601 };
602
603 println!(); if result.success {
606 Output::success(&result.summary);
607 } else {
608 Output::error(format!("Rebase failed: {:?}", result.error));
609 }
610
611 self.stack_manager.save_to_disk()?;
613
614 Ok(result)
615 }
616
617 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
619 info!("Starting interactive rebase for stack '{}'", stack.name);
620
621 let mut result = RebaseResult {
622 success: true,
623 branch_mapping: HashMap::new(),
624 conflicts: Vec::new(),
625 new_commits: Vec::new(),
626 error: None,
627 summary: String::new(),
628 };
629
630 println!("Interactive Rebase for Stack: {}", stack.name);
631 println!(" Base branch: {}", stack.base_branch);
632 println!(" Entries: {}", stack.entries.len());
633
634 if self.options.interactive {
635 println!("\nChoose action for each commit:");
636 println!(" (p)ick - apply the commit");
637 println!(" (s)kip - skip this commit");
638 println!(" (e)dit - edit the commit message");
639 println!(" (q)uit - abort the rebase");
640 }
641
642 for entry in &stack.entries {
645 println!(
646 " {} {} - {}",
647 entry.short_hash(),
648 entry.branch,
649 entry.short_message(50)
650 );
651
652 match self.cherry_pick_commit(&entry.commit_hash) {
654 Ok(new_commit) => result.new_commits.push(new_commit),
655 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
656 }
657 }
658
659 result.summary = format!(
660 "Interactive rebase processed {} commits",
661 stack.entries.len()
662 );
663 Ok(result)
664 }
665
666 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
668 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
670
671 if let Ok(staged_files) = self.git_repo.get_staged_files() {
673 if !staged_files.is_empty() {
674 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
676 let _ = self.git_repo.commit_staged_changes(&cleanup_message);
677 }
678 }
679
680 Ok(new_commit_hash)
681 }
682
683 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
685 debug!("Attempting to auto-resolve conflicts for {}", commit_hash);
686
687 if !self.git_repo.has_conflicts()? {
689 return Ok(true);
690 }
691
692 let conflicted_files = self.git_repo.get_conflicted_files()?;
693
694 if conflicted_files.is_empty() {
695 return Ok(true);
696 }
697
698 info!(
699 "Found conflicts in {} files: {:?}",
700 conflicted_files.len(),
701 conflicted_files
702 );
703
704 let analysis = self
706 .conflict_analyzer
707 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
708
709 info!(
710 "๐ Conflict analysis: {} total conflicts, {} auto-resolvable",
711 analysis.total_conflicts, analysis.auto_resolvable_count
712 );
713
714 for recommendation in &analysis.recommendations {
716 info!("๐ก {}", recommendation);
717 }
718
719 let mut resolved_count = 0;
720 let mut resolved_files = Vec::new(); let mut failed_files = Vec::new();
722
723 for file_analysis in &analysis.files {
724 if file_analysis.auto_resolvable {
725 match self.resolve_file_conflicts_enhanced(
726 &file_analysis.file_path,
727 &file_analysis.conflicts,
728 ) {
729 Ok(ConflictResolution::Resolved) => {
730 resolved_count += 1;
731 resolved_files.push(file_analysis.file_path.clone()); info!("โ
Auto-resolved conflicts in {}", file_analysis.file_path);
733 }
734 Ok(ConflictResolution::TooComplex) => {
735 debug!(
736 "โ ๏ธ Conflicts in {} are too complex for auto-resolution",
737 file_analysis.file_path
738 );
739 failed_files.push(file_analysis.file_path.clone());
740 }
741 Err(e) => {
742 warn!(
743 "โ Failed to resolve conflicts in {}: {}",
744 file_analysis.file_path, e
745 );
746 failed_files.push(file_analysis.file_path.clone());
747 }
748 }
749 } else {
750 failed_files.push(file_analysis.file_path.clone());
751 info!(
752 "โ ๏ธ {} requires manual resolution ({} conflicts)",
753 file_analysis.file_path,
754 file_analysis.conflicts.len()
755 );
756 }
757 }
758
759 if resolved_count > 0 {
760 info!(
761 "๐ Auto-resolved conflicts in {}/{} files",
762 resolved_count,
763 conflicted_files.len()
764 );
765
766 let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
769 self.git_repo.stage_files(&file_paths)?;
770 }
771
772 let all_resolved = failed_files.is_empty();
774
775 if !all_resolved {
776 info!(
777 "โ ๏ธ {} files still need manual resolution: {:?}",
778 failed_files.len(),
779 failed_files
780 );
781 }
782
783 Ok(all_resolved)
784 }
785
786 fn resolve_file_conflicts_enhanced(
788 &self,
789 file_path: &str,
790 conflicts: &[crate::git::ConflictRegion],
791 ) -> Result<ConflictResolution> {
792 let repo_path = self.git_repo.path();
793 let full_path = repo_path.join(file_path);
794
795 let mut content = std::fs::read_to_string(&full_path)
797 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
798
799 if conflicts.is_empty() {
800 return Ok(ConflictResolution::Resolved);
801 }
802
803 info!(
804 "Resolving {} conflicts in {} using enhanced analysis",
805 conflicts.len(),
806 file_path
807 );
808
809 let mut any_resolved = false;
810
811 for conflict in conflicts.iter().rev() {
813 match self.resolve_single_conflict_enhanced(conflict) {
814 Ok(Some(resolution)) => {
815 let before = &content[..conflict.start_pos];
817 let after = &content[conflict.end_pos..];
818 content = format!("{before}{resolution}{after}");
819 any_resolved = true;
820 debug!(
821 "โ
Resolved {} conflict at lines {}-{} in {}",
822 format!("{:?}", conflict.conflict_type).to_lowercase(),
823 conflict.start_line,
824 conflict.end_line,
825 file_path
826 );
827 }
828 Ok(None) => {
829 debug!(
830 "โ ๏ธ {} conflict at lines {}-{} in {} requires manual resolution",
831 format!("{:?}", conflict.conflict_type).to_lowercase(),
832 conflict.start_line,
833 conflict.end_line,
834 file_path
835 );
836 return Ok(ConflictResolution::TooComplex);
837 }
838 Err(e) => {
839 debug!("โ Failed to resolve conflict in {}: {}", file_path, e);
840 return Ok(ConflictResolution::TooComplex);
841 }
842 }
843 }
844
845 if any_resolved {
846 let remaining_conflicts = self.parse_conflict_markers(&content)?;
848
849 if remaining_conflicts.is_empty() {
850 let backup_path = full_path.with_extension("cascade-backup");
853 if let Ok(original_content) = std::fs::read_to_string(&full_path) {
854 let _ = std::fs::write(&backup_path, original_content);
855 debug!("Created backup at {:?}", backup_path);
856 }
857
858 crate::utils::atomic_file::write_string(&full_path, &content)?;
860
861 debug!("Successfully resolved all conflicts in {}", file_path);
862 return Ok(ConflictResolution::Resolved);
863 } else {
864 info!(
865 "โ ๏ธ Partially resolved conflicts in {} ({} remaining)",
866 file_path,
867 remaining_conflicts.len()
868 );
869 }
870 }
871
872 Ok(ConflictResolution::TooComplex)
873 }
874
875 #[allow(dead_code)]
877 fn count_whitespace_consistency(content: &str) -> usize {
878 let mut inconsistencies = 0;
879 let lines: Vec<&str> = content.lines().collect();
880
881 for line in &lines {
882 if line.contains('\t') && line.contains(' ') {
884 inconsistencies += 1;
885 }
886 }
887
888 lines.len().saturating_sub(inconsistencies)
890 }
891
892 fn resolve_single_conflict_enhanced(
894 &self,
895 conflict: &crate::git::ConflictRegion,
896 ) -> Result<Option<String>> {
897 debug!(
898 "Resolving {} conflict in {} (lines {}-{})",
899 format!("{:?}", conflict.conflict_type).to_lowercase(),
900 conflict.file_path,
901 conflict.start_line,
902 conflict.end_line
903 );
904
905 use crate::git::ConflictType;
906
907 match conflict.conflict_type {
908 ConflictType::Whitespace => {
909 let our_normalized = conflict
912 .our_content
913 .split_whitespace()
914 .collect::<Vec<_>>()
915 .join(" ");
916 let their_normalized = conflict
917 .their_content
918 .split_whitespace()
919 .collect::<Vec<_>>()
920 .join(" ");
921
922 if our_normalized == their_normalized {
923 Ok(Some(conflict.their_content.clone()))
928 } else {
929 debug!(
931 "Whitespace conflict has content differences - requires manual resolution"
932 );
933 Ok(None)
934 }
935 }
936 ConflictType::LineEnding => {
937 let normalized = conflict
939 .our_content
940 .replace("\r\n", "\n")
941 .replace('\r', "\n");
942 Ok(Some(normalized))
943 }
944 ConflictType::PureAddition => {
945 if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
949 Ok(Some(conflict.their_content.clone()))
951 } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
952 Ok(Some(String::new()))
954 } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
955 Ok(Some(String::new()))
957 } else {
958 debug!(
964 "PureAddition conflict has content on both sides - requires manual resolution"
965 );
966 Ok(None)
967 }
968 }
969 ConflictType::ImportMerge => {
970 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
975 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
976
977 let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
979 let trimmed = line.trim();
980 trimmed.starts_with("import ")
981 || trimmed.starts_with("from ")
982 || trimmed.starts_with("use ")
983 || trimmed.starts_with("#include")
984 || trimmed.is_empty()
985 });
986
987 if !all_simple {
988 debug!("ImportMerge contains non-import lines - requires manual resolution");
989 return Ok(None);
990 }
991
992 let mut all_imports: Vec<&str> = our_lines
994 .into_iter()
995 .chain(their_lines)
996 .filter(|line| !line.trim().is_empty())
997 .collect();
998 all_imports.sort();
999 all_imports.dedup();
1000 Ok(Some(all_imports.join("\n")))
1001 }
1002 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1003 Ok(None)
1005 }
1006 }
1007 }
1008
1009 #[allow(dead_code)]
1011 fn resolve_file_conflicts(&self, file_path: &str) -> Result<ConflictResolution> {
1012 let repo_path = self.git_repo.path();
1013 let full_path = repo_path.join(file_path);
1014
1015 let content = std::fs::read_to_string(&full_path)
1017 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
1018
1019 let conflicts = self.parse_conflict_markers(&content)?;
1021
1022 if conflicts.is_empty() {
1023 return Ok(ConflictResolution::Resolved);
1025 }
1026
1027 info!(
1028 "Found {} conflict regions in {}",
1029 conflicts.len(),
1030 file_path
1031 );
1032
1033 let mut resolved_content = content;
1035 let mut any_resolved = false;
1036
1037 for conflict in conflicts.iter().rev() {
1039 match self.resolve_single_conflict(conflict, file_path) {
1040 Ok(Some(resolution)) => {
1041 let before = &resolved_content[..conflict.start];
1043 let after = &resolved_content[conflict.end..];
1044 resolved_content = format!("{before}{resolution}{after}");
1045 any_resolved = true;
1046 debug!(
1047 "โ
Resolved conflict at lines {}-{} in {}",
1048 conflict.start_line, conflict.end_line, file_path
1049 );
1050 }
1051 Ok(None) => {
1052 debug!(
1053 "โ ๏ธ Conflict at lines {}-{} in {} too complex for auto-resolution",
1054 conflict.start_line, conflict.end_line, file_path
1055 );
1056 }
1057 Err(e) => {
1058 debug!("โ Failed to resolve conflict in {}: {}", file_path, e);
1059 }
1060 }
1061 }
1062
1063 if any_resolved {
1064 let remaining_conflicts = self.parse_conflict_markers(&resolved_content)?;
1066
1067 if remaining_conflicts.is_empty() {
1068 crate::utils::atomic_file::write_string(&full_path, &resolved_content)?;
1070
1071 return Ok(ConflictResolution::Resolved);
1072 } else {
1073 info!(
1074 "โ ๏ธ Partially resolved conflicts in {} ({} remaining)",
1075 file_path,
1076 remaining_conflicts.len()
1077 );
1078 }
1079 }
1080
1081 Ok(ConflictResolution::TooComplex)
1082 }
1083
1084 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1086 let lines: Vec<&str> = content.lines().collect();
1087 let mut conflicts = Vec::new();
1088 let mut i = 0;
1089
1090 while i < lines.len() {
1091 if lines[i].starts_with("<<<<<<<") {
1092 let start_line = i + 1;
1094 let mut separator_line = None;
1095 let mut end_line = None;
1096
1097 for (j, line) in lines.iter().enumerate().skip(i + 1) {
1099 if line.starts_with("=======") {
1100 separator_line = Some(j + 1);
1101 } else if line.starts_with(">>>>>>>") {
1102 end_line = Some(j + 1);
1103 break;
1104 }
1105 }
1106
1107 if let (Some(sep), Some(end)) = (separator_line, end_line) {
1108 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1110 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1111
1112 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1113 let their_content = lines[sep..(end - 1)].join("\n");
1114
1115 conflicts.push(ConflictRegion {
1116 start: start_pos,
1117 end: end_pos,
1118 start_line,
1119 end_line: end,
1120 our_content,
1121 their_content,
1122 });
1123
1124 i = end;
1125 } else {
1126 i += 1;
1127 }
1128 } else {
1129 i += 1;
1130 }
1131 }
1132
1133 Ok(conflicts)
1134 }
1135
1136 fn resolve_single_conflict(
1138 &self,
1139 conflict: &ConflictRegion,
1140 file_path: &str,
1141 ) -> Result<Option<String>> {
1142 debug!(
1143 "Analyzing conflict in {} (lines {}-{})",
1144 file_path, conflict.start_line, conflict.end_line
1145 );
1146
1147 if let Some(resolved) = self.resolve_whitespace_conflict(conflict)? {
1149 debug!("Resolved as whitespace-only conflict");
1150 return Ok(Some(resolved));
1151 }
1152
1153 if let Some(resolved) = self.resolve_line_ending_conflict(conflict)? {
1155 debug!("Resolved as line ending conflict");
1156 return Ok(Some(resolved));
1157 }
1158
1159 if let Some(resolved) = self.resolve_addition_conflict(conflict)? {
1161 debug!("Resolved as pure addition conflict");
1162 return Ok(Some(resolved));
1163 }
1164
1165 if let Some(resolved) = self.resolve_import_conflict(conflict, file_path)? {
1167 debug!("Resolved as import reordering conflict");
1168 return Ok(Some(resolved));
1169 }
1170
1171 Ok(None)
1173 }
1174
1175 fn resolve_whitespace_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1177 let our_normalized = self.normalize_whitespace(&conflict.our_content);
1178 let their_normalized = self.normalize_whitespace(&conflict.their_content);
1179
1180 if our_normalized == their_normalized {
1181 let resolved =
1183 if conflict.our_content.trim().len() >= conflict.their_content.trim().len() {
1184 conflict.our_content.clone()
1185 } else {
1186 conflict.their_content.clone()
1187 };
1188
1189 return Ok(Some(resolved));
1190 }
1191
1192 Ok(None)
1193 }
1194
1195 fn resolve_line_ending_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1197 let our_normalized = conflict
1198 .our_content
1199 .replace("\r\n", "\n")
1200 .replace('\r', "\n");
1201 let their_normalized = conflict
1202 .their_content
1203 .replace("\r\n", "\n")
1204 .replace('\r', "\n");
1205
1206 if our_normalized == their_normalized {
1207 return Ok(Some(our_normalized));
1209 }
1210
1211 Ok(None)
1212 }
1213
1214 fn resolve_addition_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1216 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1217 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1218
1219 if our_lines.is_empty() {
1221 return Ok(Some(conflict.their_content.clone()));
1222 }
1223 if their_lines.is_empty() {
1224 return Ok(Some(conflict.our_content.clone()));
1225 }
1226
1227 let mut merged_lines = Vec::new();
1229 let mut our_idx = 0;
1230 let mut their_idx = 0;
1231
1232 while our_idx < our_lines.len() || their_idx < their_lines.len() {
1233 if our_idx >= our_lines.len() {
1234 merged_lines.extend_from_slice(&their_lines[their_idx..]);
1236 break;
1237 } else if their_idx >= their_lines.len() {
1238 merged_lines.extend_from_slice(&our_lines[our_idx..]);
1240 break;
1241 } else if our_lines[our_idx] == their_lines[their_idx] {
1242 merged_lines.push(our_lines[our_idx]);
1244 our_idx += 1;
1245 their_idx += 1;
1246 } else {
1247 return Ok(None);
1249 }
1250 }
1251
1252 Ok(Some(merged_lines.join("\n")))
1253 }
1254
1255 fn resolve_import_conflict(
1257 &self,
1258 conflict: &ConflictRegion,
1259 file_path: &str,
1260 ) -> Result<Option<String>> {
1261 let is_import_file = file_path.ends_with(".rs")
1263 || file_path.ends_with(".py")
1264 || file_path.ends_with(".js")
1265 || file_path.ends_with(".ts")
1266 || file_path.ends_with(".go")
1267 || file_path.ends_with(".java")
1268 || file_path.ends_with(".swift")
1269 || file_path.ends_with(".kt")
1270 || file_path.ends_with(".cs");
1271
1272 if !is_import_file {
1273 return Ok(None);
1274 }
1275
1276 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1277 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1278
1279 let our_imports = our_lines
1281 .iter()
1282 .all(|line| self.is_import_line(line, file_path));
1283 let their_imports = their_lines
1284 .iter()
1285 .all(|line| self.is_import_line(line, file_path));
1286
1287 if our_imports && their_imports {
1288 let mut all_imports: Vec<&str> = our_lines.into_iter().chain(their_lines).collect();
1290 all_imports.sort();
1291 all_imports.dedup();
1292
1293 return Ok(Some(all_imports.join("\n")));
1294 }
1295
1296 Ok(None)
1297 }
1298
1299 fn is_import_line(&self, line: &str, file_path: &str) -> bool {
1301 let trimmed = line.trim();
1302
1303 if trimmed.is_empty() {
1304 return true; }
1306
1307 if file_path.ends_with(".rs") {
1308 return trimmed.starts_with("use ") || trimmed.starts_with("extern crate");
1309 } else if file_path.ends_with(".py") {
1310 return trimmed.starts_with("import ") || trimmed.starts_with("from ");
1311 } else if file_path.ends_with(".js") || file_path.ends_with(".ts") {
1312 return trimmed.starts_with("import ")
1313 || trimmed.starts_with("const ")
1314 || trimmed.starts_with("require(");
1315 } else if file_path.ends_with(".go") {
1316 return trimmed.starts_with("import ") || trimmed == "import (" || trimmed == ")";
1317 } else if file_path.ends_with(".java") {
1318 return trimmed.starts_with("import ");
1319 } else if file_path.ends_with(".swift") {
1320 return trimmed.starts_with("import ") || trimmed.starts_with("@testable import ");
1321 } else if file_path.ends_with(".kt") {
1322 return trimmed.starts_with("import ") || trimmed.starts_with("@file:");
1323 } else if file_path.ends_with(".cs") {
1324 return trimmed.starts_with("using ") || trimmed.starts_with("extern alias ");
1325 }
1326
1327 false
1328 }
1329
1330 fn normalize_whitespace(&self, content: &str) -> String {
1332 content
1333 .lines()
1334 .map(|line| line.trim())
1335 .filter(|line| !line.is_empty())
1336 .collect::<Vec<_>>()
1337 .join("\n")
1338 }
1339
1340 fn update_stack_entry(
1343 &mut self,
1344 stack_id: Uuid,
1345 entry_id: &Uuid,
1346 _new_branch: &str,
1347 new_commit_hash: &str,
1348 ) -> Result<()> {
1349 debug!(
1350 "Updating entry {} in stack {} with new commit {}",
1351 entry_id, stack_id, new_commit_hash
1352 );
1353
1354 let stack = self
1356 .stack_manager
1357 .get_stack_mut(&stack_id)
1358 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1359
1360 if let Some(entry) = stack.entries.iter_mut().find(|e| e.id == *entry_id) {
1362 debug!(
1363 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch '{}')",
1364 entry_id, entry.commit_hash, new_commit_hash, entry.branch
1365 );
1366
1367 entry.commit_hash = new_commit_hash.to_string();
1370
1371 debug!(
1374 "Successfully updated entry {} in stack {}",
1375 entry_id, stack_id
1376 );
1377 Ok(())
1378 } else {
1379 Err(CascadeError::config(format!(
1380 "Entry {entry_id} not found in stack {stack_id}"
1381 )))
1382 }
1383 }
1384
1385 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1387 info!("Pulling latest changes for branch {}", branch);
1388
1389 match self.git_repo.fetch() {
1391 Ok(_) => {
1392 debug!("Fetch successful");
1393 match self.git_repo.pull(branch) {
1395 Ok(_) => {
1396 info!("Pull completed successfully for {}", branch);
1397 Ok(())
1398 }
1399 Err(e) => {
1400 warn!("Pull failed for {}: {}", branch, e);
1401 Ok(())
1403 }
1404 }
1405 }
1406 Err(e) => {
1407 warn!("Fetch failed: {}", e);
1408 Ok(())
1410 }
1411 }
1412 }
1413
1414 pub fn is_rebase_in_progress(&self) -> bool {
1416 let git_dir = self.git_repo.path().join(".git");
1418 git_dir.join("REBASE_HEAD").exists()
1419 || git_dir.join("rebase-merge").exists()
1420 || git_dir.join("rebase-apply").exists()
1421 }
1422
1423 pub fn abort_rebase(&self) -> Result<()> {
1425 info!("Aborting rebase operation");
1426
1427 let git_dir = self.git_repo.path().join(".git");
1428
1429 if git_dir.join("REBASE_HEAD").exists() {
1431 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1432 CascadeError::Git(git2::Error::from_str(&format!(
1433 "Failed to clean rebase state: {e}"
1434 )))
1435 })?;
1436 }
1437
1438 if git_dir.join("rebase-merge").exists() {
1439 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1440 CascadeError::Git(git2::Error::from_str(&format!(
1441 "Failed to clean rebase-merge: {e}"
1442 )))
1443 })?;
1444 }
1445
1446 if git_dir.join("rebase-apply").exists() {
1447 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1448 CascadeError::Git(git2::Error::from_str(&format!(
1449 "Failed to clean rebase-apply: {e}"
1450 )))
1451 })?;
1452 }
1453
1454 info!("Rebase aborted successfully");
1455 Ok(())
1456 }
1457
1458 pub fn continue_rebase(&self) -> Result<()> {
1460 info!("Continuing rebase operation");
1461
1462 if self.git_repo.has_conflicts()? {
1464 return Err(CascadeError::branch(
1465 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1466 ));
1467 }
1468
1469 self.git_repo.stage_conflict_resolved_files()?;
1471
1472 info!("Rebase continued successfully");
1473 Ok(())
1474 }
1475
1476 fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1478 let git_dir = self.git_repo.path().join(".git");
1479 Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1480 }
1481
1482 fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1484 use crate::cli::output::Output;
1485
1486 let git_dir = self.git_repo.path().join(".git");
1487
1488 Output::section("Resuming in-progress sync");
1489 println!();
1490 Output::info("Detected unfinished cherry-pick from previous sync");
1491 println!();
1492
1493 if self.git_repo.has_conflicts()? {
1495 let conflicted_files = self.git_repo.get_conflicted_files()?;
1496
1497 let result = RebaseResult {
1498 success: false,
1499 branch_mapping: HashMap::new(),
1500 conflicts: conflicted_files.clone(),
1501 new_commits: Vec::new(),
1502 error: Some(format!(
1503 "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1504 MANUAL CONFLICT RESOLUTION REQUIRED\n\
1505 =====================================\n\n\
1506 Conflicted files:\n{}\n\n\
1507 Step 1: Analyze conflicts\n\
1508 โ Run: ca conflicts\n\
1509 โ Shows detailed conflict analysis\n\n\
1510 Step 2: Resolve conflicts in your editor\n\
1511 โ Open conflicted files and edit them\n\
1512 โ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1513 โ Keep the code you want\n\
1514 โ Save the files\n\n\
1515 Step 3: Mark conflicts as resolved\n\
1516 โ Run: git add <resolved-files>\n\
1517 โ Or: git add -A (to stage all resolved files)\n\n\
1518 Step 4: Complete the sync\n\
1519 โ Run: ca sync\n\
1520 โ Cascade will continue from where it left off\n\n\
1521 Alternative: Abort and start over\n\
1522 โ Run: git cherry-pick --abort\n\
1523 โ Then: ca sync (starts fresh)",
1524 conflicted_files.len(),
1525 conflicted_files
1526 .iter()
1527 .map(|f| format!(" - {}", f))
1528 .collect::<Vec<_>>()
1529 .join("\n")
1530 )),
1531 summary: "Sync paused - conflicts need resolution".to_string(),
1532 };
1533
1534 return Ok(result);
1535 }
1536
1537 Output::info("Conflicts resolved, continuing cherry-pick...");
1539
1540 self.git_repo.stage_conflict_resolved_files()?;
1542
1543 let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1545 let commit_message = if cherry_pick_msg_file.exists() {
1546 std::fs::read_to_string(&cherry_pick_msg_file)
1547 .unwrap_or_else(|_| "Resolved conflicts".to_string())
1548 } else {
1549 "Resolved conflicts".to_string()
1550 };
1551
1552 match self.git_repo.commit(&commit_message) {
1553 Ok(_new_commit_id) => {
1554 Output::success("Cherry-pick completed");
1555
1556 if git_dir.join("CHERRY_PICK_HEAD").exists() {
1558 let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1559 }
1560 if cherry_pick_msg_file.exists() {
1561 let _ = std::fs::remove_file(&cherry_pick_msg_file);
1562 }
1563
1564 println!();
1565 Output::info("Continuing with rest of stack...");
1566 println!();
1567
1568 self.rebase_with_force_push(stack)
1571 }
1572 Err(e) => {
1573 let result = RebaseResult {
1574 success: false,
1575 branch_mapping: HashMap::new(),
1576 conflicts: Vec::new(),
1577 new_commits: Vec::new(),
1578 error: Some(format!(
1579 "Failed to complete cherry-pick: {}\n\n\
1580 This usually means:\n\
1581 - Git index is locked (another process accessing repo)\n\
1582 - File permissions issue\n\
1583 - Disk space issue\n\n\
1584 Recovery:\n\
1585 1. Check if another Git operation is running\n\
1586 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1587 3. Run 'git status' to check repo state\n\
1588 4. Retry 'ca sync' after fixing the issue\n\n\
1589 Or abort and start fresh:\n\
1590 โ Run: git cherry-pick --abort\n\
1591 โ Then: ca sync",
1592 e
1593 )),
1594 summary: "Failed to complete cherry-pick".to_string(),
1595 };
1596
1597 Ok(result)
1598 }
1599 }
1600 }
1601}
1602
1603impl RebaseResult {
1604 pub fn get_summary(&self) -> String {
1606 if self.success {
1607 format!("โ
{}", self.summary)
1608 } else {
1609 format!(
1610 "โ Rebase failed: {}",
1611 self.error.as_deref().unwrap_or("Unknown error")
1612 )
1613 }
1614 }
1615
1616 pub fn has_conflicts(&self) -> bool {
1618 !self.conflicts.is_empty()
1619 }
1620
1621 pub fn success_count(&self) -> usize {
1623 self.new_commits.len()
1624 }
1625}
1626
1627#[cfg(test)]
1628mod tests {
1629 use super::*;
1630 use std::path::PathBuf;
1631 use std::process::Command;
1632 use tempfile::TempDir;
1633
1634 #[allow(dead_code)]
1635 fn create_test_repo() -> (TempDir, PathBuf) {
1636 let temp_dir = TempDir::new().unwrap();
1637 let repo_path = temp_dir.path().to_path_buf();
1638
1639 Command::new("git")
1641 .args(["init"])
1642 .current_dir(&repo_path)
1643 .output()
1644 .unwrap();
1645 Command::new("git")
1646 .args(["config", "user.name", "Test"])
1647 .current_dir(&repo_path)
1648 .output()
1649 .unwrap();
1650 Command::new("git")
1651 .args(["config", "user.email", "test@test.com"])
1652 .current_dir(&repo_path)
1653 .output()
1654 .unwrap();
1655
1656 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1658 Command::new("git")
1659 .args(["add", "."])
1660 .current_dir(&repo_path)
1661 .output()
1662 .unwrap();
1663 Command::new("git")
1664 .args(["commit", "-m", "Initial"])
1665 .current_dir(&repo_path)
1666 .output()
1667 .unwrap();
1668
1669 (temp_dir, repo_path)
1670 }
1671
1672 #[test]
1673 fn test_conflict_region_creation() {
1674 let region = ConflictRegion {
1675 start: 0,
1676 end: 50,
1677 start_line: 1,
1678 end_line: 3,
1679 our_content: "function test() {\n return true;\n}".to_string(),
1680 their_content: "function test() {\n return true;\n}".to_string(),
1681 };
1682
1683 assert_eq!(region.start_line, 1);
1684 assert_eq!(region.end_line, 3);
1685 assert!(region.our_content.contains("return true"));
1686 assert!(region.their_content.contains("return true"));
1687 }
1688
1689 #[test]
1690 fn test_rebase_strategies() {
1691 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1692 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1693 }
1694
1695 #[test]
1696 fn test_rebase_options() {
1697 let options = RebaseOptions::default();
1698 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1699 assert!(!options.interactive);
1700 assert!(options.auto_resolve);
1701 assert_eq!(options.max_retries, 3);
1702 }
1703
1704 #[test]
1705 fn test_cleanup_guard_tracks_branches() {
1706 let mut guard = TempBranchCleanupGuard::new();
1707 assert!(guard.branches.is_empty());
1708
1709 guard.add_branch("test-branch-1".to_string());
1710 guard.add_branch("test-branch-2".to_string());
1711
1712 assert_eq!(guard.branches.len(), 2);
1713 assert_eq!(guard.branches[0], "test-branch-1");
1714 assert_eq!(guard.branches[1], "test-branch-2");
1715 }
1716
1717 #[test]
1718 fn test_cleanup_guard_prevents_double_cleanup() {
1719 use std::process::Command;
1720 use tempfile::TempDir;
1721
1722 let temp_dir = TempDir::new().unwrap();
1724 let repo_path = temp_dir.path();
1725
1726 Command::new("git")
1727 .args(["init"])
1728 .current_dir(repo_path)
1729 .output()
1730 .unwrap();
1731
1732 Command::new("git")
1733 .args(["config", "user.name", "Test"])
1734 .current_dir(repo_path)
1735 .output()
1736 .unwrap();
1737
1738 Command::new("git")
1739 .args(["config", "user.email", "test@test.com"])
1740 .current_dir(repo_path)
1741 .output()
1742 .unwrap();
1743
1744 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1746 Command::new("git")
1747 .args(["add", "."])
1748 .current_dir(repo_path)
1749 .output()
1750 .unwrap();
1751 Command::new("git")
1752 .args(["commit", "-m", "initial"])
1753 .current_dir(repo_path)
1754 .output()
1755 .unwrap();
1756
1757 let git_repo = GitRepository::open(repo_path).unwrap();
1758
1759 git_repo.create_branch("test-temp", None).unwrap();
1761
1762 let mut guard = TempBranchCleanupGuard::new();
1763 guard.add_branch("test-temp".to_string());
1764
1765 guard.cleanup(&git_repo);
1767 assert!(guard.cleaned);
1768
1769 guard.cleanup(&git_repo);
1771 assert!(guard.cleaned);
1772 }
1773
1774 #[test]
1775 fn test_rebase_result() {
1776 let result = RebaseResult {
1777 success: true,
1778 branch_mapping: std::collections::HashMap::new(),
1779 conflicts: vec!["abc123".to_string()],
1780 new_commits: vec!["def456".to_string()],
1781 error: None,
1782 summary: "Test summary".to_string(),
1783 };
1784
1785 assert!(result.success);
1786 assert!(result.has_conflicts());
1787 assert_eq!(result.success_count(), 1);
1788 }
1789
1790 #[test]
1791 fn test_import_line_detection() {
1792 let (_temp_dir, repo_path) = create_test_repo();
1793 let git_repo = crate::git::GitRepository::open(&repo_path).unwrap();
1794 let stack_manager = crate::stack::StackManager::new(&repo_path).unwrap();
1795 let options = RebaseOptions::default();
1796 let rebase_manager = RebaseManager::new(stack_manager, git_repo, options);
1797
1798 assert!(rebase_manager.is_import_line("import Foundation", "test.swift"));
1800 assert!(rebase_manager.is_import_line("@testable import MyModule", "test.swift"));
1801 assert!(!rebase_manager.is_import_line("class MyClass {", "test.swift"));
1802
1803 assert!(rebase_manager.is_import_line("import kotlin.collections.*", "test.kt"));
1805 assert!(rebase_manager.is_import_line("@file:JvmName(\"Utils\")", "test.kt"));
1806 assert!(!rebase_manager.is_import_line("fun myFunction() {", "test.kt"));
1807
1808 assert!(rebase_manager.is_import_line("using System;", "test.cs"));
1810 assert!(rebase_manager.is_import_line("using System.Collections.Generic;", "test.cs"));
1811 assert!(rebase_manager.is_import_line("extern alias GridV1;", "test.cs"));
1812 assert!(!rebase_manager.is_import_line("namespace MyNamespace {", "test.cs"));
1813
1814 assert!(rebase_manager.is_import_line("", "test.swift"));
1816 assert!(rebase_manager.is_import_line(" ", "test.kt"));
1817 assert!(rebase_manager.is_import_line("", "test.cs"));
1818 }
1819}