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}
65
66#[derive(Debug)]
68pub struct RebaseResult {
69 pub success: bool,
71 pub branch_mapping: HashMap<String, String>,
73 pub conflicts: Vec<String>,
75 pub new_commits: Vec<String>,
77 pub error: Option<String>,
79 pub summary: String,
81}
82
83#[allow(dead_code)]
89struct TempBranchCleanupGuard {
90 branches: Vec<String>,
91 cleaned: bool,
92}
93
94#[allow(dead_code)]
95impl TempBranchCleanupGuard {
96 fn new() -> Self {
97 Self {
98 branches: Vec::new(),
99 cleaned: false,
100 }
101 }
102
103 fn add_branch(&mut self, branch: String) {
104 self.branches.push(branch);
105 }
106
107 fn cleanup(&mut self, git_repo: &GitRepository) {
109 if self.cleaned || self.branches.is_empty() {
110 return;
111 }
112
113 info!("๐งน Cleaning up {} temporary branches", self.branches.len());
114 for branch in &self.branches {
115 if let Err(e) = git_repo.delete_branch_unsafe(branch) {
116 warn!("Failed to delete temp branch {}: {}", branch, e);
117 }
119 }
120 self.cleaned = true;
121 }
122}
123
124impl Drop for TempBranchCleanupGuard {
125 fn drop(&mut self) {
126 if !self.cleaned && !self.branches.is_empty() {
127 warn!(
130 "โ ๏ธ {} temporary branches were not cleaned up: {}",
131 self.branches.len(),
132 self.branches.join(", ")
133 );
134 warn!("Run 'ca cleanup' to remove orphaned temporary branches");
135 }
136 }
137}
138
139pub struct RebaseManager {
141 stack_manager: StackManager,
142 git_repo: GitRepository,
143 options: RebaseOptions,
144 conflict_analyzer: ConflictAnalyzer,
145}
146
147impl Default for RebaseOptions {
148 fn default() -> Self {
149 Self {
150 strategy: RebaseStrategy::ForcePush,
151 interactive: false,
152 target_base: None,
153 preserve_merges: true,
154 auto_resolve: true,
155 max_retries: 3,
156 skip_pull: None,
157 }
158 }
159}
160
161impl RebaseManager {
162 pub fn new(
164 stack_manager: StackManager,
165 git_repo: GitRepository,
166 options: RebaseOptions,
167 ) -> Self {
168 Self {
169 stack_manager,
170 git_repo,
171 options,
172 conflict_analyzer: ConflictAnalyzer::new(),
173 }
174 }
175
176 pub fn into_stack_manager(self) -> StackManager {
178 self.stack_manager
179 }
180
181 pub fn rebase_stack(&mut self, stack_id: &Uuid) -> Result<RebaseResult> {
183 debug!("Starting rebase for stack {}", stack_id);
184
185 let stack = self
186 .stack_manager
187 .get_stack(stack_id)
188 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?
189 .clone();
190
191 match self.options.strategy {
192 RebaseStrategy::ForcePush => self.rebase_with_force_push(&stack),
193 RebaseStrategy::Interactive => self.rebase_interactive(&stack),
194 }
195 }
196
197 fn rebase_with_force_push(&mut self, stack: &Stack) -> Result<RebaseResult> {
201 use crate::cli::output::Output;
202
203 if self.has_in_progress_cherry_pick()? {
205 return self.handle_in_progress_cherry_pick(stack);
206 }
207
208 Output::section(format!("Rebasing stack: {}", stack.name));
209
210 let mut result = RebaseResult {
211 success: true,
212 branch_mapping: HashMap::new(),
213 conflicts: Vec::new(),
214 new_commits: Vec::new(),
215 error: None,
216 summary: String::new(),
217 };
218
219 let target_base = self
220 .options
221 .target_base
222 .as_ref()
223 .unwrap_or(&stack.base_branch)
224 .clone(); let original_branch = self.git_repo.get_current_branch().ok();
228
229 if !self.options.skip_pull.unwrap_or(false) {
232 if let Err(e) = self.pull_latest_changes(&target_base) {
233 Output::warning(format!("Could not pull latest changes: {}", e));
234 }
235 }
236
237 if let Err(e) = self.git_repo.reset_to_head() {
239 Output::warning(format!("Could not reset working directory: {}", e));
240 }
241
242 let mut current_base = target_base.clone();
243 let entry_count = stack.entries.len();
244 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" };
249 println!("Rebasing {} {}...", entry_count, plural);
250
251 for (index, entry) in stack.entries.iter().enumerate() {
253 let original_branch = &entry.branch;
254
255 let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
258 temp_branches.push(temp_branch.clone()); self.git_repo
260 .create_branch(&temp_branch, Some(¤t_base))?;
261 self.git_repo.checkout_branch(&temp_branch)?;
262
263 match self.cherry_pick_commit(&entry.commit_hash) {
265 Ok(new_commit_hash) => {
266 result.new_commits.push(new_commit_hash.clone());
267
268 let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
270
271 self.git_repo
274 .update_branch_to_commit(original_branch, &rebased_commit_id)?;
275
276 let tree_char = if index + 1 == entry_count {
278 "โโ"
279 } else {
280 "โโ"
281 };
282
283 if let Some(pr_num) = &entry.pull_request_id {
284 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
285 branches_to_push.push((original_branch.clone(), pr_num.clone()));
286 } else {
287 println!(" {} {} (not submitted)", tree_char, original_branch);
288 }
289
290 result
291 .branch_mapping
292 .insert(original_branch.clone(), original_branch.clone());
293
294 self.update_stack_entry(
296 stack.id,
297 &entry.id,
298 original_branch,
299 &rebased_commit_id,
300 )?;
301
302 current_base = original_branch.clone();
304 }
305 Err(e) => {
306 println!(); Output::error(format!("Conflict in {}: {}", &entry.commit_hash[..8], e));
308 result.conflicts.push(entry.commit_hash.clone());
309
310 if !self.options.auto_resolve {
311 result.success = false;
312 result.error = Some(format!(
313 "Conflict in {}: {}\n\n\
314 MANUAL CONFLICT RESOLUTION REQUIRED\n\
315 =====================================\n\n\
316 Step 1: Analyze conflicts\n\
317 โ Run: ca conflicts\n\
318 โ This shows which conflicts are in which files\n\n\
319 Step 2: Resolve conflicts in your editor\n\
320 โ Open conflicted files and edit them\n\
321 โ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
322 โ Keep the code you want\n\
323 โ Save the files\n\n\
324 Step 3: Mark conflicts as resolved\n\
325 โ Run: git add <resolved-files>\n\
326 โ Or: git add -A (to stage all resolved files)\n\n\
327 Step 4: Complete the sync\n\
328 โ Run: ca sync\n\
329 โ Cascade will detect resolved conflicts and continue\n\n\
330 Alternative: Abort and start over\n\
331 โ Run: git cherry-pick --abort\n\
332 โ Then: ca sync (starts fresh)\n\n\
333 TIP: Enable auto-resolution for simple conflicts:\n\
334 โ Run: ca sync --auto-resolve\n\
335 โ Only complex conflicts will require manual resolution",
336 entry.commit_hash, e
337 ));
338 break;
339 }
340
341 match self.auto_resolve_conflicts(&entry.commit_hash) {
343 Ok(fully_resolved) => {
344 if !fully_resolved {
345 result.success = false;
346 result.error = Some(format!(
347 "Could not auto-resolve all conflicts in {}\n\n\
348 MANUAL CONFLICT RESOLUTION REQUIRED\n\
349 =====================================\n\n\
350 Some conflicts are too complex for auto-resolution.\n\n\
351 Step 1: Analyze remaining conflicts\n\
352 โ Run: ca conflicts\n\
353 โ Shows which files still have conflicts\n\
354 โ Use --detailed flag for more info\n\n\
355 Step 2: Resolve conflicts in your editor\n\
356 โ Open conflicted files (marked with โ in ca conflicts output)\n\
357 โ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
358 โ Keep the code you want\n\
359 โ Save the files\n\n\
360 Step 3: Mark conflicts as resolved\n\
361 โ Run: git add <resolved-files>\n\
362 โ Or: git add -A (to stage all resolved files)\n\n\
363 Step 4: Complete the sync\n\
364 โ Run: ca sync\n\
365 โ Cascade will continue from where it left off\n\n\
366 Alternative: Abort and start over\n\
367 โ Run: git cherry-pick --abort\n\
368 โ Then: ca sync (starts fresh)\n\n\
369 BACKUP: If auto-resolution was wrong\n\
370 โ Check for .cascade-backup files in your repo\n\
371 โ These contain the original file content before auto-resolution",
372 &entry.commit_hash[..8]
373 ));
374 break;
375 }
376
377 let commit_message =
379 format!("Auto-resolved conflicts in {}", &entry.commit_hash[..8]);
380 match self.git_repo.commit(&commit_message) {
381 Ok(new_commit_id) => {
382 Output::success("Auto-resolved conflicts");
383 result.new_commits.push(new_commit_id.clone());
384 let rebased_commit_id = new_commit_id;
385
386 self.git_repo.update_branch_to_commit(
388 original_branch,
389 &rebased_commit_id,
390 )?;
391
392 let tree_char = if index + 1 == entry_count {
394 "โโ"
395 } else {
396 "โโ"
397 };
398
399 if let Some(pr_num) = &entry.pull_request_id {
400 println!(
401 " {} {} (PR #{})",
402 tree_char, original_branch, pr_num
403 );
404 branches_to_push
405 .push((original_branch.clone(), pr_num.clone()));
406 } else {
407 println!(
408 " {} {} (not submitted)",
409 tree_char, original_branch
410 );
411 }
412
413 result
414 .branch_mapping
415 .insert(original_branch.clone(), original_branch.clone());
416
417 self.update_stack_entry(
419 stack.id,
420 &entry.id,
421 original_branch,
422 &rebased_commit_id,
423 )?;
424
425 current_base = original_branch.clone();
427 }
428 Err(commit_err) => {
429 result.success = false;
430 result.error = Some(format!(
431 "Could not commit auto-resolved conflicts: {}\n\n\
432 This usually means:\n\
433 - Git index is locked (another process accessing repo)\n\
434 - File permissions issue\n\
435 - Disk space issue\n\n\
436 Recovery:\n\
437 1. Check if another Git operation is running\n\
438 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
439 3. Run 'git status' to check repo state\n\
440 4. Retry 'ca sync' after fixing the issue",
441 commit_err
442 ));
443 break;
444 }
445 }
446 }
447 Err(resolve_err) => {
448 result.success = false;
449 result.error = Some(format!(
450 "Could not resolve conflicts: {}\n\n\
451 Recovery:\n\
452 1. Check repo state: 'git status'\n\
453 2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
454 3. Remove any lock files: 'rm -f .git/index.lock'\n\
455 4. Retry 'ca sync'",
456 resolve_err
457 ));
458 break;
459 }
460 }
461 }
462 }
463 }
464
465 if !temp_branches.is_empty() {
468 if let Err(e) = self.git_repo.reset_to_head() {
471 debug!("Could not reset working directory: {}", e);
472 }
473
474 if let Err(e) = self.git_repo.checkout_branch_silent(&target_base) {
476 Output::warning(format!("Could not checkout base for cleanup: {}", e));
477 }
478
479 for temp_branch in &temp_branches {
481 if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
482 debug!("Could not delete temp branch {}: {}", temp_branch, e);
483 }
484 }
485 }
486
487 let pushed_count = branches_to_push.len();
490 let skipped_count = entry_count - pushed_count;
491
492 if !branches_to_push.is_empty() {
493 println!(); println!(
495 "Pushing {} branch{} to remote...",
496 pushed_count,
497 if pushed_count == 1 { "" } else { "es" }
498 );
499
500 for (branch_name, _pr_num) in &branches_to_push {
501 match self.git_repo.force_push_single_branch_auto(branch_name) {
502 Ok(_) => {
503 debug!("Pushed {} successfully", branch_name);
504 }
505 Err(e) => {
506 Output::warning(format!("Could not push '{}': {}", branch_name, e));
507 }
509 }
510 }
511 }
512
513 if let Some(ref orig_branch) = original_branch {
516 if let Some(last_entry) = stack.entries.last() {
518 let top_branch = &last_entry.branch;
519
520 if let Ok(top_commit) = self.git_repo.get_branch_head(top_branch) {
522 debug!(
523 "Updating working branch '{}' to match top of stack ({})",
524 orig_branch,
525 &top_commit[..8]
526 );
527
528 if let Err(e) = self
529 .git_repo
530 .update_branch_to_commit(orig_branch, &top_commit)
531 {
532 Output::warning(format!(
533 "Could not update working branch '{}' to top of stack: {}",
534 orig_branch, e
535 ));
536 }
537 }
538 }
539
540 if let Err(e) = self.git_repo.checkout_branch_silent(orig_branch) {
542 Output::warning(format!(
543 "Could not return to original branch '{}': {}",
544 orig_branch, e
545 ));
546 }
547 }
548
549 result.summary = if pushed_count > 0 {
551 let pr_plural = if pushed_count == 1 { "" } else { "s" };
552 let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
553
554 if skipped_count > 0 {
555 format!(
556 "{} {} rebased ({} PR{} updated, {} not yet submitted)",
557 entry_count, entry_plural, pushed_count, pr_plural, skipped_count
558 )
559 } else {
560 format!(
561 "{} {} rebased ({} PR{} updated)",
562 entry_count, entry_plural, pushed_count, pr_plural
563 )
564 }
565 } else {
566 let plural = if entry_count == 1 { "entry" } else { "entries" };
567 format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
568 };
569
570 println!(); if result.success {
573 Output::success(&result.summary);
574 } else {
575 Output::error(format!("Rebase failed: {:?}", result.error));
576 }
577
578 self.stack_manager.save_to_disk()?;
580
581 Ok(result)
582 }
583
584 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
586 info!("Starting interactive rebase for stack '{}'", stack.name);
587
588 let mut result = RebaseResult {
589 success: true,
590 branch_mapping: HashMap::new(),
591 conflicts: Vec::new(),
592 new_commits: Vec::new(),
593 error: None,
594 summary: String::new(),
595 };
596
597 println!("Interactive Rebase for Stack: {}", stack.name);
598 println!(" Base branch: {}", stack.base_branch);
599 println!(" Entries: {}", stack.entries.len());
600
601 if self.options.interactive {
602 println!("\nChoose action for each commit:");
603 println!(" (p)ick - apply the commit");
604 println!(" (s)kip - skip this commit");
605 println!(" (e)dit - edit the commit message");
606 println!(" (q)uit - abort the rebase");
607 }
608
609 for entry in &stack.entries {
612 println!(
613 " {} {} - {}",
614 entry.short_hash(),
615 entry.branch,
616 entry.short_message(50)
617 );
618
619 match self.cherry_pick_commit(&entry.commit_hash) {
621 Ok(new_commit) => result.new_commits.push(new_commit),
622 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
623 }
624 }
625
626 result.summary = format!(
627 "Interactive rebase processed {} commits",
628 stack.entries.len()
629 );
630 Ok(result)
631 }
632
633 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
635 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
637
638 if let Ok(staged_files) = self.git_repo.get_staged_files() {
640 if !staged_files.is_empty() {
641 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
643 let _ = self.git_repo.commit_staged_changes(&cleanup_message);
644 }
645 }
646
647 Ok(new_commit_hash)
648 }
649
650 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
652 debug!("Attempting to auto-resolve conflicts for {}", commit_hash);
653
654 if !self.git_repo.has_conflicts()? {
656 return Ok(true);
657 }
658
659 let conflicted_files = self.git_repo.get_conflicted_files()?;
660
661 if conflicted_files.is_empty() {
662 return Ok(true);
663 }
664
665 info!(
666 "Found conflicts in {} files: {:?}",
667 conflicted_files.len(),
668 conflicted_files
669 );
670
671 let analysis = self
673 .conflict_analyzer
674 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
675
676 info!(
677 "๐ Conflict analysis: {} total conflicts, {} auto-resolvable",
678 analysis.total_conflicts, analysis.auto_resolvable_count
679 );
680
681 for recommendation in &analysis.recommendations {
683 info!("๐ก {}", recommendation);
684 }
685
686 let mut resolved_count = 0;
687 let mut failed_files = Vec::new();
688
689 for file_analysis in &analysis.files {
690 if file_analysis.auto_resolvable {
691 match self.resolve_file_conflicts_enhanced(
692 &file_analysis.file_path,
693 &file_analysis.conflicts,
694 ) {
695 Ok(ConflictResolution::Resolved) => {
696 resolved_count += 1;
697 info!("โ
Auto-resolved conflicts in {}", file_analysis.file_path);
698 }
699 Ok(ConflictResolution::TooComplex) => {
700 debug!(
701 "โ ๏ธ Conflicts in {} are too complex for auto-resolution",
702 file_analysis.file_path
703 );
704 failed_files.push(file_analysis.file_path.clone());
705 }
706 Err(e) => {
707 warn!(
708 "โ Failed to resolve conflicts in {}: {}",
709 file_analysis.file_path, e
710 );
711 failed_files.push(file_analysis.file_path.clone());
712 }
713 }
714 } else {
715 failed_files.push(file_analysis.file_path.clone());
716 info!(
717 "โ ๏ธ {} requires manual resolution ({} conflicts)",
718 file_analysis.file_path,
719 file_analysis.conflicts.len()
720 );
721 }
722 }
723
724 if resolved_count > 0 {
725 info!(
726 "๐ Auto-resolved conflicts in {}/{} files",
727 resolved_count,
728 conflicted_files.len()
729 );
730
731 self.git_repo.stage_conflict_resolved_files()?;
733 }
734
735 let all_resolved = failed_files.is_empty();
737
738 if !all_resolved {
739 info!(
740 "โ ๏ธ {} files still need manual resolution: {:?}",
741 failed_files.len(),
742 failed_files
743 );
744 }
745
746 Ok(all_resolved)
747 }
748
749 fn resolve_file_conflicts_enhanced(
751 &self,
752 file_path: &str,
753 conflicts: &[crate::git::ConflictRegion],
754 ) -> Result<ConflictResolution> {
755 let repo_path = self.git_repo.path();
756 let full_path = repo_path.join(file_path);
757
758 let mut content = std::fs::read_to_string(&full_path)
760 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
761
762 if conflicts.is_empty() {
763 return Ok(ConflictResolution::Resolved);
764 }
765
766 info!(
767 "Resolving {} conflicts in {} using enhanced analysis",
768 conflicts.len(),
769 file_path
770 );
771
772 let mut any_resolved = false;
773
774 for conflict in conflicts.iter().rev() {
776 match self.resolve_single_conflict_enhanced(conflict) {
777 Ok(Some(resolution)) => {
778 let before = &content[..conflict.start_pos];
780 let after = &content[conflict.end_pos..];
781 content = format!("{before}{resolution}{after}");
782 any_resolved = true;
783 debug!(
784 "โ
Resolved {} conflict at lines {}-{} in {}",
785 format!("{:?}", conflict.conflict_type).to_lowercase(),
786 conflict.start_line,
787 conflict.end_line,
788 file_path
789 );
790 }
791 Ok(None) => {
792 debug!(
793 "โ ๏ธ {} conflict at lines {}-{} in {} requires manual resolution",
794 format!("{:?}", conflict.conflict_type).to_lowercase(),
795 conflict.start_line,
796 conflict.end_line,
797 file_path
798 );
799 return Ok(ConflictResolution::TooComplex);
800 }
801 Err(e) => {
802 debug!("โ Failed to resolve conflict in {}: {}", file_path, e);
803 return Ok(ConflictResolution::TooComplex);
804 }
805 }
806 }
807
808 if any_resolved {
809 let remaining_conflicts = self.parse_conflict_markers(&content)?;
811
812 if remaining_conflicts.is_empty() {
813 let backup_path = full_path.with_extension("cascade-backup");
816 if let Ok(original_content) = std::fs::read_to_string(&full_path) {
817 let _ = std::fs::write(&backup_path, original_content);
818 debug!("Created backup at {:?}", backup_path);
819 }
820
821 crate::utils::atomic_file::write_string(&full_path, &content)?;
823
824 debug!("Successfully resolved all conflicts in {}", file_path);
825 return Ok(ConflictResolution::Resolved);
826 } else {
827 info!(
828 "โ ๏ธ Partially resolved conflicts in {} ({} remaining)",
829 file_path,
830 remaining_conflicts.len()
831 );
832 }
833 }
834
835 Ok(ConflictResolution::TooComplex)
836 }
837
838 fn count_whitespace_consistency(content: &str) -> usize {
840 let mut inconsistencies = 0;
841 let lines: Vec<&str> = content.lines().collect();
842
843 for line in &lines {
844 if line.contains('\t') && line.contains(' ') {
846 inconsistencies += 1;
847 }
848 }
849
850 lines.len().saturating_sub(inconsistencies)
852 }
853
854 fn resolve_single_conflict_enhanced(
856 &self,
857 conflict: &crate::git::ConflictRegion,
858 ) -> Result<Option<String>> {
859 debug!(
860 "Resolving {} conflict in {} (lines {}-{})",
861 format!("{:?}", conflict.conflict_type).to_lowercase(),
862 conflict.file_path,
863 conflict.start_line,
864 conflict.end_line
865 );
866
867 use crate::git::ConflictType;
868
869 match conflict.conflict_type {
870 ConflictType::Whitespace => {
871 let our_normalized = conflict
874 .our_content
875 .split_whitespace()
876 .collect::<Vec<_>>()
877 .join(" ");
878 let their_normalized = conflict
879 .their_content
880 .split_whitespace()
881 .collect::<Vec<_>>()
882 .join(" ");
883
884 if our_normalized == their_normalized {
885 let our_consistency = Self::count_whitespace_consistency(&conflict.our_content);
888 let their_consistency =
889 Self::count_whitespace_consistency(&conflict.their_content);
890
891 if our_consistency >= their_consistency {
892 Ok(Some(conflict.our_content.clone()))
893 } else {
894 Ok(Some(conflict.their_content.clone()))
895 }
896 } else {
897 debug!(
899 "Whitespace conflict has content differences - requires manual resolution"
900 );
901 Ok(None)
902 }
903 }
904 ConflictType::LineEnding => {
905 let normalized = conflict
907 .our_content
908 .replace("\r\n", "\n")
909 .replace('\r', "\n");
910 Ok(Some(normalized))
911 }
912 ConflictType::PureAddition => {
913 if conflict.our_content.is_empty() {
916 Ok(Some(conflict.their_content.clone()))
917 } else if conflict.their_content.is_empty() {
918 Ok(Some(conflict.our_content.clone()))
919 } else {
920 debug!(
926 "PureAddition conflict has content on both sides - requires manual resolution"
927 );
928 Ok(None)
929 }
930 }
931 ConflictType::ImportMerge => {
932 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
937 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
938
939 let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
941 let trimmed = line.trim();
942 trimmed.starts_with("import ")
943 || trimmed.starts_with("from ")
944 || trimmed.starts_with("use ")
945 || trimmed.starts_with("#include")
946 || trimmed.is_empty()
947 });
948
949 if !all_simple {
950 debug!("ImportMerge contains non-import lines - requires manual resolution");
951 return Ok(None);
952 }
953
954 let mut all_imports: Vec<&str> = our_lines
956 .into_iter()
957 .chain(their_lines)
958 .filter(|line| !line.trim().is_empty())
959 .collect();
960 all_imports.sort();
961 all_imports.dedup();
962 Ok(Some(all_imports.join("\n")))
963 }
964 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
965 Ok(None)
967 }
968 }
969 }
970
971 #[allow(dead_code)]
973 fn resolve_file_conflicts(&self, file_path: &str) -> Result<ConflictResolution> {
974 let repo_path = self.git_repo.path();
975 let full_path = repo_path.join(file_path);
976
977 let content = std::fs::read_to_string(&full_path)
979 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
980
981 let conflicts = self.parse_conflict_markers(&content)?;
983
984 if conflicts.is_empty() {
985 return Ok(ConflictResolution::Resolved);
987 }
988
989 info!(
990 "Found {} conflict regions in {}",
991 conflicts.len(),
992 file_path
993 );
994
995 let mut resolved_content = content;
997 let mut any_resolved = false;
998
999 for conflict in conflicts.iter().rev() {
1001 match self.resolve_single_conflict(conflict, file_path) {
1002 Ok(Some(resolution)) => {
1003 let before = &resolved_content[..conflict.start];
1005 let after = &resolved_content[conflict.end..];
1006 resolved_content = format!("{before}{resolution}{after}");
1007 any_resolved = true;
1008 debug!(
1009 "โ
Resolved conflict at lines {}-{} in {}",
1010 conflict.start_line, conflict.end_line, file_path
1011 );
1012 }
1013 Ok(None) => {
1014 debug!(
1015 "โ ๏ธ Conflict at lines {}-{} in {} too complex for auto-resolution",
1016 conflict.start_line, conflict.end_line, file_path
1017 );
1018 }
1019 Err(e) => {
1020 debug!("โ Failed to resolve conflict in {}: {}", file_path, e);
1021 }
1022 }
1023 }
1024
1025 if any_resolved {
1026 let remaining_conflicts = self.parse_conflict_markers(&resolved_content)?;
1028
1029 if remaining_conflicts.is_empty() {
1030 crate::utils::atomic_file::write_string(&full_path, &resolved_content)?;
1032
1033 return Ok(ConflictResolution::Resolved);
1034 } else {
1035 info!(
1036 "โ ๏ธ Partially resolved conflicts in {} ({} remaining)",
1037 file_path,
1038 remaining_conflicts.len()
1039 );
1040 }
1041 }
1042
1043 Ok(ConflictResolution::TooComplex)
1044 }
1045
1046 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1048 let lines: Vec<&str> = content.lines().collect();
1049 let mut conflicts = Vec::new();
1050 let mut i = 0;
1051
1052 while i < lines.len() {
1053 if lines[i].starts_with("<<<<<<<") {
1054 let start_line = i + 1;
1056 let mut separator_line = None;
1057 let mut end_line = None;
1058
1059 for (j, line) in lines.iter().enumerate().skip(i + 1) {
1061 if line.starts_with("=======") {
1062 separator_line = Some(j + 1);
1063 } else if line.starts_with(">>>>>>>") {
1064 end_line = Some(j + 1);
1065 break;
1066 }
1067 }
1068
1069 if let (Some(sep), Some(end)) = (separator_line, end_line) {
1070 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1072 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1073
1074 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1075 let their_content = lines[sep..(end - 1)].join("\n");
1076
1077 conflicts.push(ConflictRegion {
1078 start: start_pos,
1079 end: end_pos,
1080 start_line,
1081 end_line: end,
1082 our_content,
1083 their_content,
1084 });
1085
1086 i = end;
1087 } else {
1088 i += 1;
1089 }
1090 } else {
1091 i += 1;
1092 }
1093 }
1094
1095 Ok(conflicts)
1096 }
1097
1098 fn resolve_single_conflict(
1100 &self,
1101 conflict: &ConflictRegion,
1102 file_path: &str,
1103 ) -> Result<Option<String>> {
1104 debug!(
1105 "Analyzing conflict in {} (lines {}-{})",
1106 file_path, conflict.start_line, conflict.end_line
1107 );
1108
1109 if let Some(resolved) = self.resolve_whitespace_conflict(conflict)? {
1111 debug!("Resolved as whitespace-only conflict");
1112 return Ok(Some(resolved));
1113 }
1114
1115 if let Some(resolved) = self.resolve_line_ending_conflict(conflict)? {
1117 debug!("Resolved as line ending conflict");
1118 return Ok(Some(resolved));
1119 }
1120
1121 if let Some(resolved) = self.resolve_addition_conflict(conflict)? {
1123 debug!("Resolved as pure addition conflict");
1124 return Ok(Some(resolved));
1125 }
1126
1127 if let Some(resolved) = self.resolve_import_conflict(conflict, file_path)? {
1129 debug!("Resolved as import reordering conflict");
1130 return Ok(Some(resolved));
1131 }
1132
1133 Ok(None)
1135 }
1136
1137 fn resolve_whitespace_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1139 let our_normalized = self.normalize_whitespace(&conflict.our_content);
1140 let their_normalized = self.normalize_whitespace(&conflict.their_content);
1141
1142 if our_normalized == their_normalized {
1143 let resolved =
1145 if conflict.our_content.trim().len() >= conflict.their_content.trim().len() {
1146 conflict.our_content.clone()
1147 } else {
1148 conflict.their_content.clone()
1149 };
1150
1151 return Ok(Some(resolved));
1152 }
1153
1154 Ok(None)
1155 }
1156
1157 fn resolve_line_ending_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1159 let our_normalized = conflict
1160 .our_content
1161 .replace("\r\n", "\n")
1162 .replace('\r', "\n");
1163 let their_normalized = conflict
1164 .their_content
1165 .replace("\r\n", "\n")
1166 .replace('\r', "\n");
1167
1168 if our_normalized == their_normalized {
1169 return Ok(Some(our_normalized));
1171 }
1172
1173 Ok(None)
1174 }
1175
1176 fn resolve_addition_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1178 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1179 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1180
1181 if our_lines.is_empty() {
1183 return Ok(Some(conflict.their_content.clone()));
1184 }
1185 if their_lines.is_empty() {
1186 return Ok(Some(conflict.our_content.clone()));
1187 }
1188
1189 let mut merged_lines = Vec::new();
1191 let mut our_idx = 0;
1192 let mut their_idx = 0;
1193
1194 while our_idx < our_lines.len() || their_idx < their_lines.len() {
1195 if our_idx >= our_lines.len() {
1196 merged_lines.extend_from_slice(&their_lines[their_idx..]);
1198 break;
1199 } else if their_idx >= their_lines.len() {
1200 merged_lines.extend_from_slice(&our_lines[our_idx..]);
1202 break;
1203 } else if our_lines[our_idx] == their_lines[their_idx] {
1204 merged_lines.push(our_lines[our_idx]);
1206 our_idx += 1;
1207 their_idx += 1;
1208 } else {
1209 return Ok(None);
1211 }
1212 }
1213
1214 Ok(Some(merged_lines.join("\n")))
1215 }
1216
1217 fn resolve_import_conflict(
1219 &self,
1220 conflict: &ConflictRegion,
1221 file_path: &str,
1222 ) -> Result<Option<String>> {
1223 let is_import_file = file_path.ends_with(".rs")
1225 || file_path.ends_with(".py")
1226 || file_path.ends_with(".js")
1227 || file_path.ends_with(".ts")
1228 || file_path.ends_with(".go")
1229 || file_path.ends_with(".java")
1230 || file_path.ends_with(".swift")
1231 || file_path.ends_with(".kt")
1232 || file_path.ends_with(".cs");
1233
1234 if !is_import_file {
1235 return Ok(None);
1236 }
1237
1238 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1239 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1240
1241 let our_imports = our_lines
1243 .iter()
1244 .all(|line| self.is_import_line(line, file_path));
1245 let their_imports = their_lines
1246 .iter()
1247 .all(|line| self.is_import_line(line, file_path));
1248
1249 if our_imports && their_imports {
1250 let mut all_imports: Vec<&str> = our_lines.into_iter().chain(their_lines).collect();
1252 all_imports.sort();
1253 all_imports.dedup();
1254
1255 return Ok(Some(all_imports.join("\n")));
1256 }
1257
1258 Ok(None)
1259 }
1260
1261 fn is_import_line(&self, line: &str, file_path: &str) -> bool {
1263 let trimmed = line.trim();
1264
1265 if trimmed.is_empty() {
1266 return true; }
1268
1269 if file_path.ends_with(".rs") {
1270 return trimmed.starts_with("use ") || trimmed.starts_with("extern crate");
1271 } else if file_path.ends_with(".py") {
1272 return trimmed.starts_with("import ") || trimmed.starts_with("from ");
1273 } else if file_path.ends_with(".js") || file_path.ends_with(".ts") {
1274 return trimmed.starts_with("import ")
1275 || trimmed.starts_with("const ")
1276 || trimmed.starts_with("require(");
1277 } else if file_path.ends_with(".go") {
1278 return trimmed.starts_with("import ") || trimmed == "import (" || trimmed == ")";
1279 } else if file_path.ends_with(".java") {
1280 return trimmed.starts_with("import ");
1281 } else if file_path.ends_with(".swift") {
1282 return trimmed.starts_with("import ") || trimmed.starts_with("@testable import ");
1283 } else if file_path.ends_with(".kt") {
1284 return trimmed.starts_with("import ") || trimmed.starts_with("@file:");
1285 } else if file_path.ends_with(".cs") {
1286 return trimmed.starts_with("using ") || trimmed.starts_with("extern alias ");
1287 }
1288
1289 false
1290 }
1291
1292 fn normalize_whitespace(&self, content: &str) -> String {
1294 content
1295 .lines()
1296 .map(|line| line.trim())
1297 .filter(|line| !line.is_empty())
1298 .collect::<Vec<_>>()
1299 .join("\n")
1300 }
1301
1302 fn update_stack_entry(
1305 &mut self,
1306 stack_id: Uuid,
1307 entry_id: &Uuid,
1308 _new_branch: &str,
1309 new_commit_hash: &str,
1310 ) -> Result<()> {
1311 debug!(
1312 "Updating entry {} in stack {} with new commit {}",
1313 entry_id, stack_id, new_commit_hash
1314 );
1315
1316 let stack = self
1318 .stack_manager
1319 .get_stack_mut(&stack_id)
1320 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1321
1322 if let Some(entry) = stack.entries.iter_mut().find(|e| e.id == *entry_id) {
1324 debug!(
1325 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch '{}')",
1326 entry_id, entry.commit_hash, new_commit_hash, entry.branch
1327 );
1328
1329 entry.commit_hash = new_commit_hash.to_string();
1332
1333 debug!(
1336 "Successfully updated entry {} in stack {}",
1337 entry_id, stack_id
1338 );
1339 Ok(())
1340 } else {
1341 Err(CascadeError::config(format!(
1342 "Entry {entry_id} not found in stack {stack_id}"
1343 )))
1344 }
1345 }
1346
1347 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1349 info!("Pulling latest changes for branch {}", branch);
1350
1351 match self.git_repo.fetch() {
1353 Ok(_) => {
1354 debug!("Fetch successful");
1355 match self.git_repo.pull(branch) {
1357 Ok(_) => {
1358 info!("Pull completed successfully for {}", branch);
1359 Ok(())
1360 }
1361 Err(e) => {
1362 warn!("Pull failed for {}: {}", branch, e);
1363 Ok(())
1365 }
1366 }
1367 }
1368 Err(e) => {
1369 warn!("Fetch failed: {}", e);
1370 Ok(())
1372 }
1373 }
1374 }
1375
1376 pub fn is_rebase_in_progress(&self) -> bool {
1378 let git_dir = self.git_repo.path().join(".git");
1380 git_dir.join("REBASE_HEAD").exists()
1381 || git_dir.join("rebase-merge").exists()
1382 || git_dir.join("rebase-apply").exists()
1383 }
1384
1385 pub fn abort_rebase(&self) -> Result<()> {
1387 info!("Aborting rebase operation");
1388
1389 let git_dir = self.git_repo.path().join(".git");
1390
1391 if git_dir.join("REBASE_HEAD").exists() {
1393 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1394 CascadeError::Git(git2::Error::from_str(&format!(
1395 "Failed to clean rebase state: {e}"
1396 )))
1397 })?;
1398 }
1399
1400 if git_dir.join("rebase-merge").exists() {
1401 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1402 CascadeError::Git(git2::Error::from_str(&format!(
1403 "Failed to clean rebase-merge: {e}"
1404 )))
1405 })?;
1406 }
1407
1408 if git_dir.join("rebase-apply").exists() {
1409 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1410 CascadeError::Git(git2::Error::from_str(&format!(
1411 "Failed to clean rebase-apply: {e}"
1412 )))
1413 })?;
1414 }
1415
1416 info!("Rebase aborted successfully");
1417 Ok(())
1418 }
1419
1420 pub fn continue_rebase(&self) -> Result<()> {
1422 info!("Continuing rebase operation");
1423
1424 if self.git_repo.has_conflicts()? {
1426 return Err(CascadeError::branch(
1427 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1428 ));
1429 }
1430
1431 self.git_repo.stage_conflict_resolved_files()?;
1433
1434 info!("Rebase continued successfully");
1435 Ok(())
1436 }
1437
1438 fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1440 let git_dir = self.git_repo.path().join(".git");
1441 Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1442 }
1443
1444 fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1446 use crate::cli::output::Output;
1447
1448 let git_dir = self.git_repo.path().join(".git");
1449
1450 Output::section("Resuming in-progress sync");
1451 println!();
1452 Output::info("Detected unfinished cherry-pick from previous sync");
1453 println!();
1454
1455 if self.git_repo.has_conflicts()? {
1457 let conflicted_files = self.git_repo.get_conflicted_files()?;
1458
1459 let result = RebaseResult {
1460 success: false,
1461 branch_mapping: HashMap::new(),
1462 conflicts: conflicted_files.clone(),
1463 new_commits: Vec::new(),
1464 error: Some(format!(
1465 "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1466 MANUAL CONFLICT RESOLUTION REQUIRED\n\
1467 =====================================\n\n\
1468 Conflicted files:\n{}\n\n\
1469 Step 1: Analyze conflicts\n\
1470 โ Run: ca conflicts\n\
1471 โ Shows detailed conflict analysis\n\n\
1472 Step 2: Resolve conflicts in your editor\n\
1473 โ Open conflicted files and edit them\n\
1474 โ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1475 โ Keep the code you want\n\
1476 โ Save the files\n\n\
1477 Step 3: Mark conflicts as resolved\n\
1478 โ Run: git add <resolved-files>\n\
1479 โ Or: git add -A (to stage all resolved files)\n\n\
1480 Step 4: Complete the sync\n\
1481 โ Run: ca sync\n\
1482 โ Cascade will continue from where it left off\n\n\
1483 Alternative: Abort and start over\n\
1484 โ Run: git cherry-pick --abort\n\
1485 โ Then: ca sync (starts fresh)",
1486 conflicted_files.len(),
1487 conflicted_files
1488 .iter()
1489 .map(|f| format!(" - {}", f))
1490 .collect::<Vec<_>>()
1491 .join("\n")
1492 )),
1493 summary: "Sync paused - conflicts need resolution".to_string(),
1494 };
1495
1496 return Ok(result);
1497 }
1498
1499 Output::info("Conflicts resolved, continuing cherry-pick...");
1501
1502 self.git_repo.stage_conflict_resolved_files()?;
1504
1505 let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1507 let commit_message = if cherry_pick_msg_file.exists() {
1508 std::fs::read_to_string(&cherry_pick_msg_file)
1509 .unwrap_or_else(|_| "Resolved conflicts".to_string())
1510 } else {
1511 "Resolved conflicts".to_string()
1512 };
1513
1514 match self.git_repo.commit(&commit_message) {
1515 Ok(_new_commit_id) => {
1516 Output::success("Cherry-pick completed");
1517
1518 if git_dir.join("CHERRY_PICK_HEAD").exists() {
1520 let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1521 }
1522 if cherry_pick_msg_file.exists() {
1523 let _ = std::fs::remove_file(&cherry_pick_msg_file);
1524 }
1525
1526 println!();
1527 Output::info("Continuing with rest of stack...");
1528 println!();
1529
1530 self.rebase_with_force_push(stack)
1533 }
1534 Err(e) => {
1535 let result = RebaseResult {
1536 success: false,
1537 branch_mapping: HashMap::new(),
1538 conflicts: Vec::new(),
1539 new_commits: Vec::new(),
1540 error: Some(format!(
1541 "Failed to complete cherry-pick: {}\n\n\
1542 This usually means:\n\
1543 - Git index is locked (another process accessing repo)\n\
1544 - File permissions issue\n\
1545 - Disk space issue\n\n\
1546 Recovery:\n\
1547 1. Check if another Git operation is running\n\
1548 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1549 3. Run 'git status' to check repo state\n\
1550 4. Retry 'ca sync' after fixing the issue\n\n\
1551 Or abort and start fresh:\n\
1552 โ Run: git cherry-pick --abort\n\
1553 โ Then: ca sync",
1554 e
1555 )),
1556 summary: "Failed to complete cherry-pick".to_string(),
1557 };
1558
1559 Ok(result)
1560 }
1561 }
1562 }
1563}
1564
1565impl RebaseResult {
1566 pub fn get_summary(&self) -> String {
1568 if self.success {
1569 format!("โ
{}", self.summary)
1570 } else {
1571 format!(
1572 "โ Rebase failed: {}",
1573 self.error.as_deref().unwrap_or("Unknown error")
1574 )
1575 }
1576 }
1577
1578 pub fn has_conflicts(&self) -> bool {
1580 !self.conflicts.is_empty()
1581 }
1582
1583 pub fn success_count(&self) -> usize {
1585 self.new_commits.len()
1586 }
1587}
1588
1589#[cfg(test)]
1590mod tests {
1591 use super::*;
1592 use std::path::PathBuf;
1593 use std::process::Command;
1594 use tempfile::TempDir;
1595
1596 #[allow(dead_code)]
1597 fn create_test_repo() -> (TempDir, PathBuf) {
1598 let temp_dir = TempDir::new().unwrap();
1599 let repo_path = temp_dir.path().to_path_buf();
1600
1601 Command::new("git")
1603 .args(["init"])
1604 .current_dir(&repo_path)
1605 .output()
1606 .unwrap();
1607 Command::new("git")
1608 .args(["config", "user.name", "Test"])
1609 .current_dir(&repo_path)
1610 .output()
1611 .unwrap();
1612 Command::new("git")
1613 .args(["config", "user.email", "test@test.com"])
1614 .current_dir(&repo_path)
1615 .output()
1616 .unwrap();
1617
1618 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1620 Command::new("git")
1621 .args(["add", "."])
1622 .current_dir(&repo_path)
1623 .output()
1624 .unwrap();
1625 Command::new("git")
1626 .args(["commit", "-m", "Initial"])
1627 .current_dir(&repo_path)
1628 .output()
1629 .unwrap();
1630
1631 (temp_dir, repo_path)
1632 }
1633
1634 #[test]
1635 fn test_conflict_region_creation() {
1636 let region = ConflictRegion {
1637 start: 0,
1638 end: 50,
1639 start_line: 1,
1640 end_line: 3,
1641 our_content: "function test() {\n return true;\n}".to_string(),
1642 their_content: "function test() {\n return true;\n}".to_string(),
1643 };
1644
1645 assert_eq!(region.start_line, 1);
1646 assert_eq!(region.end_line, 3);
1647 assert!(region.our_content.contains("return true"));
1648 assert!(region.their_content.contains("return true"));
1649 }
1650
1651 #[test]
1652 fn test_rebase_strategies() {
1653 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1654 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1655 }
1656
1657 #[test]
1658 fn test_rebase_options() {
1659 let options = RebaseOptions::default();
1660 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1661 assert!(!options.interactive);
1662 assert!(options.auto_resolve);
1663 assert_eq!(options.max_retries, 3);
1664 }
1665
1666 #[test]
1667 fn test_cleanup_guard_tracks_branches() {
1668 let mut guard = TempBranchCleanupGuard::new();
1669 assert!(guard.branches.is_empty());
1670
1671 guard.add_branch("test-branch-1".to_string());
1672 guard.add_branch("test-branch-2".to_string());
1673
1674 assert_eq!(guard.branches.len(), 2);
1675 assert_eq!(guard.branches[0], "test-branch-1");
1676 assert_eq!(guard.branches[1], "test-branch-2");
1677 }
1678
1679 #[test]
1680 fn test_cleanup_guard_prevents_double_cleanup() {
1681 use std::process::Command;
1682 use tempfile::TempDir;
1683
1684 let temp_dir = TempDir::new().unwrap();
1686 let repo_path = temp_dir.path();
1687
1688 Command::new("git")
1689 .args(["init"])
1690 .current_dir(repo_path)
1691 .output()
1692 .unwrap();
1693
1694 Command::new("git")
1695 .args(["config", "user.name", "Test"])
1696 .current_dir(repo_path)
1697 .output()
1698 .unwrap();
1699
1700 Command::new("git")
1701 .args(["config", "user.email", "test@test.com"])
1702 .current_dir(repo_path)
1703 .output()
1704 .unwrap();
1705
1706 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1708 Command::new("git")
1709 .args(["add", "."])
1710 .current_dir(repo_path)
1711 .output()
1712 .unwrap();
1713 Command::new("git")
1714 .args(["commit", "-m", "initial"])
1715 .current_dir(repo_path)
1716 .output()
1717 .unwrap();
1718
1719 let git_repo = GitRepository::open(repo_path).unwrap();
1720
1721 git_repo.create_branch("test-temp", None).unwrap();
1723
1724 let mut guard = TempBranchCleanupGuard::new();
1725 guard.add_branch("test-temp".to_string());
1726
1727 guard.cleanup(&git_repo);
1729 assert!(guard.cleaned);
1730
1731 guard.cleanup(&git_repo);
1733 assert!(guard.cleaned);
1734 }
1735
1736 #[test]
1737 fn test_rebase_result() {
1738 let result = RebaseResult {
1739 success: true,
1740 branch_mapping: std::collections::HashMap::new(),
1741 conflicts: vec!["abc123".to_string()],
1742 new_commits: vec!["def456".to_string()],
1743 error: None,
1744 summary: "Test summary".to_string(),
1745 };
1746
1747 assert!(result.success);
1748 assert!(result.has_conflicts());
1749 assert_eq!(result.success_count(), 1);
1750 }
1751
1752 #[test]
1753 fn test_import_line_detection() {
1754 let (_temp_dir, repo_path) = create_test_repo();
1755 let git_repo = crate::git::GitRepository::open(&repo_path).unwrap();
1756 let stack_manager = crate::stack::StackManager::new(&repo_path).unwrap();
1757 let options = RebaseOptions::default();
1758 let rebase_manager = RebaseManager::new(stack_manager, git_repo, options);
1759
1760 assert!(rebase_manager.is_import_line("import Foundation", "test.swift"));
1762 assert!(rebase_manager.is_import_line("@testable import MyModule", "test.swift"));
1763 assert!(!rebase_manager.is_import_line("class MyClass {", "test.swift"));
1764
1765 assert!(rebase_manager.is_import_line("import kotlin.collections.*", "test.kt"));
1767 assert!(rebase_manager.is_import_line("@file:JvmName(\"Utils\")", "test.kt"));
1768 assert!(!rebase_manager.is_import_line("fun myFunction() {", "test.kt"));
1769
1770 assert!(rebase_manager.is_import_line("using System;", "test.cs"));
1772 assert!(rebase_manager.is_import_line("using System.Collections.Generic;", "test.cs"));
1773 assert!(rebase_manager.is_import_line("extern alias GridV1;", "test.cs"));
1774 assert!(!rebase_manager.is_import_line("namespace MyNamespace {", "test.cs"));
1775
1776 assert!(rebase_manager.is_import_line("", "test.swift"));
1778 assert!(rebase_manager.is_import_line(" ", "test.kt"));
1779 assert!(rebase_manager.is_import_line("", "test.cs"));
1780 }
1781}