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 Output::section(format!("Rebasing stack: {}", stack.name));
204
205 let mut result = RebaseResult {
206 success: true,
207 branch_mapping: HashMap::new(),
208 conflicts: Vec::new(),
209 new_commits: Vec::new(),
210 error: None,
211 summary: String::new(),
212 };
213
214 let target_base = self
215 .options
216 .target_base
217 .as_ref()
218 .unwrap_or(&stack.base_branch)
219 .clone(); let original_branch = self.git_repo.get_current_branch().ok();
223
224 if !self.options.skip_pull.unwrap_or(false) {
227 if let Err(e) = self.pull_latest_changes(&target_base) {
228 Output::warning(format!("Could not pull latest changes: {}", e));
229 }
230 }
231
232 if let Err(e) = self.git_repo.reset_to_head() {
234 Output::warning(format!("Could not reset working directory: {}", e));
235 }
236
237 let mut current_base = target_base.clone();
238 let entry_count = stack.entries.len();
239 let mut pushed_count = 0;
240 let mut skipped_count = 0;
241 let mut temp_branches: Vec<String> = Vec::new(); println!(); let plural = if entry_count == 1 { "entry" } else { "entries" };
245 println!("๐ Rebasing {} {}", entry_count, plural);
246
247 for (index, entry) in stack.entries.iter().enumerate() {
248 let original_branch = &entry.branch;
249
250 let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
253 temp_branches.push(temp_branch.clone()); self.git_repo
255 .create_branch(&temp_branch, Some(¤t_base))?;
256 self.git_repo.checkout_branch(&temp_branch)?;
257
258 match self.cherry_pick_commit(&entry.commit_hash) {
260 Ok(new_commit_hash) => {
261 result.new_commits.push(new_commit_hash.clone());
262
263 let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
265
266 self.git_repo
269 .update_branch_to_commit(original_branch, &rebased_commit_id)?;
270
271 if entry.pull_request_id.is_some() {
273 let pr_num = entry.pull_request_id.as_ref().unwrap();
274 let tree_char = if index + 1 == entry_count {
275 "โโ"
276 } else {
277 "โโ"
278 };
279 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
280
281 self.git_repo
285 .force_push_single_branch_auto(original_branch)?;
286 pushed_count += 1;
287 } else {
288 let tree_char = if index + 1 == entry_count {
289 "โโ"
290 } else {
291 "โโ"
292 };
293 println!(" {} {} (not submitted)", tree_char, original_branch);
294 skipped_count += 1;
295 }
296
297 result
298 .branch_mapping
299 .insert(original_branch.clone(), original_branch.clone());
300
301 self.update_stack_entry(
303 stack.id,
304 &entry.id,
305 original_branch,
306 &rebased_commit_id,
307 )?;
308
309 current_base = original_branch.clone();
311 }
312 Err(e) => {
313 println!(); Output::error(format!("Conflict in {}: {}", &entry.commit_hash[..8], e));
315 result.conflicts.push(entry.commit_hash.clone());
316
317 if !self.options.auto_resolve {
318 result.success = false;
319 result.error = Some(format!("Conflict in {}: {}", entry.commit_hash, e));
320 break;
321 }
322
323 match self.auto_resolve_conflicts(&entry.commit_hash) {
325 Ok(_) => {
326 Output::success("Auto-resolved conflicts");
327 }
328 Err(resolve_err) => {
329 result.success = false;
330 result.error =
331 Some(format!("Could not resolve conflicts: {resolve_err}"));
332 break;
333 }
334 }
335 }
336 }
337 }
338
339 if !temp_branches.is_empty() {
342 if let Err(e) = self.git_repo.checkout_branch_silent(&target_base) {
344 Output::warning(format!("Could not checkout base for cleanup: {}", e));
345 }
346
347 for temp_branch in &temp_branches {
349 if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
350 debug!("Could not delete temp branch {}: {}", temp_branch, e);
351 }
352 }
353 }
354
355 if let Some(ref orig_branch) = original_branch {
358 if let Some(last_entry) = stack.entries.last() {
360 let top_branch = &last_entry.branch;
361
362 if let Ok(top_commit) = self.git_repo.get_branch_head(top_branch) {
364 debug!(
365 "Updating working branch '{}' to match top of stack ({})",
366 orig_branch, &top_commit[..8]
367 );
368
369 if let Err(e) = self.git_repo.update_branch_to_commit(orig_branch, &top_commit) {
370 Output::warning(format!(
371 "Could not update working branch '{}' to top of stack: {}",
372 orig_branch, e
373 ));
374 }
375 }
376 }
377
378 if let Err(e) = self.git_repo.checkout_branch_silent(orig_branch) {
380 Output::warning(format!(
381 "Could not return to original branch '{}': {}",
382 orig_branch, e
383 ));
384 }
385 }
386
387 result.summary = if pushed_count > 0 {
389 let pr_plural = if pushed_count == 1 { "" } else { "s" };
390 let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
391
392 if skipped_count > 0 {
393 format!(
394 "{} {} rebased ({} PR{} updated, {} not yet submitted)",
395 entry_count, entry_plural, pushed_count, pr_plural, skipped_count
396 )
397 } else {
398 format!(
399 "{} {} rebased ({} PR{} updated)",
400 entry_count, entry_plural, pushed_count, pr_plural
401 )
402 }
403 } else {
404 let plural = if entry_count == 1 { "entry" } else { "entries" };
405 format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
406 };
407
408 println!(); if result.success {
411 Output::success(&result.summary);
412 } else {
413 Output::error(format!("Rebase failed: {:?}", result.error));
414 }
415
416 self.stack_manager.save_to_disk()?;
418
419 Ok(result)
420 }
421
422 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
424 info!("Starting interactive rebase for stack '{}'", stack.name);
425
426 let mut result = RebaseResult {
427 success: true,
428 branch_mapping: HashMap::new(),
429 conflicts: Vec::new(),
430 new_commits: Vec::new(),
431 error: None,
432 summary: String::new(),
433 };
434
435 println!("๐ Interactive Rebase for Stack: {}", stack.name);
436 println!(" Base branch: {}", stack.base_branch);
437 println!(" Entries: {}", stack.entries.len());
438
439 if self.options.interactive {
440 println!("\nChoose action for each commit:");
441 println!(" (p)ick - apply the commit");
442 println!(" (s)kip - skip this commit");
443 println!(" (e)dit - edit the commit message");
444 println!(" (q)uit - abort the rebase");
445 }
446
447 for entry in &stack.entries {
450 println!(
451 " {} {} - {}",
452 entry.short_hash(),
453 entry.branch,
454 entry.short_message(50)
455 );
456
457 match self.cherry_pick_commit(&entry.commit_hash) {
459 Ok(new_commit) => result.new_commits.push(new_commit),
460 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
461 }
462 }
463
464 result.summary = format!(
465 "Interactive rebase processed {} commits",
466 stack.entries.len()
467 );
468 Ok(result)
469 }
470
471 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
473 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
475
476 if let Ok(staged_files) = self.git_repo.get_staged_files() {
478 if !staged_files.is_empty() {
479 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
481 let _ = self.git_repo.commit_staged_changes(&cleanup_message);
482 }
483 }
484
485 Ok(new_commit_hash)
486 }
487
488 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
490 debug!("Attempting to auto-resolve conflicts for {}", commit_hash);
491
492 if !self.git_repo.has_conflicts()? {
494 return Ok(true);
495 }
496
497 let conflicted_files = self.git_repo.get_conflicted_files()?;
498
499 if conflicted_files.is_empty() {
500 return Ok(true);
501 }
502
503 info!(
504 "Found conflicts in {} files: {:?}",
505 conflicted_files.len(),
506 conflicted_files
507 );
508
509 let analysis = self
511 .conflict_analyzer
512 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
513
514 info!(
515 "๐ Conflict analysis: {} total conflicts, {} auto-resolvable",
516 analysis.total_conflicts, analysis.auto_resolvable_count
517 );
518
519 for recommendation in &analysis.recommendations {
521 info!("๐ก {}", recommendation);
522 }
523
524 let mut resolved_count = 0;
525 let mut failed_files = Vec::new();
526
527 for file_analysis in &analysis.files {
528 if file_analysis.auto_resolvable {
529 match self.resolve_file_conflicts_enhanced(
530 &file_analysis.file_path,
531 &file_analysis.conflicts,
532 ) {
533 Ok(ConflictResolution::Resolved) => {
534 resolved_count += 1;
535 info!("โ
Auto-resolved conflicts in {}", file_analysis.file_path);
536 }
537 Ok(ConflictResolution::TooComplex) => {
538 debug!(
539 "โ ๏ธ Conflicts in {} are too complex for auto-resolution",
540 file_analysis.file_path
541 );
542 failed_files.push(file_analysis.file_path.clone());
543 }
544 Err(e) => {
545 warn!(
546 "โ Failed to resolve conflicts in {}: {}",
547 file_analysis.file_path, e
548 );
549 failed_files.push(file_analysis.file_path.clone());
550 }
551 }
552 } else {
553 failed_files.push(file_analysis.file_path.clone());
554 info!(
555 "โ ๏ธ {} requires manual resolution ({} conflicts)",
556 file_analysis.file_path,
557 file_analysis.conflicts.len()
558 );
559 }
560 }
561
562 if resolved_count > 0 {
563 info!(
564 "๐ Auto-resolved conflicts in {}/{} files",
565 resolved_count,
566 conflicted_files.len()
567 );
568
569 self.git_repo.stage_conflict_resolved_files()?;
571 }
572
573 let all_resolved = failed_files.is_empty();
575
576 if !all_resolved {
577 info!(
578 "โ ๏ธ {} files still need manual resolution: {:?}",
579 failed_files.len(),
580 failed_files
581 );
582 }
583
584 Ok(all_resolved)
585 }
586
587 fn resolve_file_conflicts_enhanced(
589 &self,
590 file_path: &str,
591 conflicts: &[crate::git::ConflictRegion],
592 ) -> Result<ConflictResolution> {
593 let repo_path = self.git_repo.path();
594 let full_path = repo_path.join(file_path);
595
596 let mut content = std::fs::read_to_string(&full_path)
598 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
599
600 if conflicts.is_empty() {
601 return Ok(ConflictResolution::Resolved);
602 }
603
604 info!(
605 "Resolving {} conflicts in {} using enhanced analysis",
606 conflicts.len(),
607 file_path
608 );
609
610 let mut any_resolved = false;
611
612 for conflict in conflicts.iter().rev() {
614 match self.resolve_single_conflict_enhanced(conflict) {
615 Ok(Some(resolution)) => {
616 let before = &content[..conflict.start_pos];
618 let after = &content[conflict.end_pos..];
619 content = format!("{before}{resolution}{after}");
620 any_resolved = true;
621 debug!(
622 "โ
Resolved {} conflict at lines {}-{} in {}",
623 format!("{:?}", conflict.conflict_type).to_lowercase(),
624 conflict.start_line,
625 conflict.end_line,
626 file_path
627 );
628 }
629 Ok(None) => {
630 debug!(
631 "โ ๏ธ {} conflict at lines {}-{} in {} requires manual resolution",
632 format!("{:?}", conflict.conflict_type).to_lowercase(),
633 conflict.start_line,
634 conflict.end_line,
635 file_path
636 );
637 return Ok(ConflictResolution::TooComplex);
638 }
639 Err(e) => {
640 debug!("โ Failed to resolve conflict in {}: {}", file_path, e);
641 return Ok(ConflictResolution::TooComplex);
642 }
643 }
644 }
645
646 if any_resolved {
647 let remaining_conflicts = self.parse_conflict_markers(&content)?;
649
650 if remaining_conflicts.is_empty() {
651 crate::utils::atomic_file::write_string(&full_path, &content)?;
653
654 return Ok(ConflictResolution::Resolved);
655 } else {
656 info!(
657 "โ ๏ธ Partially resolved conflicts in {} ({} remaining)",
658 file_path,
659 remaining_conflicts.len()
660 );
661 }
662 }
663
664 Ok(ConflictResolution::TooComplex)
665 }
666
667 fn resolve_single_conflict_enhanced(
669 &self,
670 conflict: &crate::git::ConflictRegion,
671 ) -> Result<Option<String>> {
672 debug!(
673 "Resolving {} conflict in {} (lines {}-{})",
674 format!("{:?}", conflict.conflict_type).to_lowercase(),
675 conflict.file_path,
676 conflict.start_line,
677 conflict.end_line
678 );
679
680 use crate::git::ConflictType;
681
682 match conflict.conflict_type {
683 ConflictType::Whitespace => {
684 if conflict.our_content.trim().len() >= conflict.their_content.trim().len() {
686 Ok(Some(conflict.our_content.clone()))
687 } else {
688 Ok(Some(conflict.their_content.clone()))
689 }
690 }
691 ConflictType::LineEnding => {
692 let normalized = conflict
694 .our_content
695 .replace("\r\n", "\n")
696 .replace('\r', "\n");
697 Ok(Some(normalized))
698 }
699 ConflictType::PureAddition => {
700 if conflict.our_content.is_empty() {
702 Ok(Some(conflict.their_content.clone()))
703 } else if conflict.their_content.is_empty() {
704 Ok(Some(conflict.our_content.clone()))
705 } else {
706 let combined = format!("{}\n{}", conflict.our_content, conflict.their_content);
708 Ok(Some(combined))
709 }
710 }
711 ConflictType::ImportMerge => {
712 let mut all_imports: Vec<&str> = conflict
714 .our_content
715 .lines()
716 .chain(conflict.their_content.lines())
717 .collect();
718 all_imports.sort();
719 all_imports.dedup();
720 Ok(Some(all_imports.join("\n")))
721 }
722 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
723 Ok(None)
725 }
726 }
727 }
728
729 #[allow(dead_code)]
731 fn resolve_file_conflicts(&self, file_path: &str) -> Result<ConflictResolution> {
732 let repo_path = self.git_repo.path();
733 let full_path = repo_path.join(file_path);
734
735 let content = std::fs::read_to_string(&full_path)
737 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
738
739 let conflicts = self.parse_conflict_markers(&content)?;
741
742 if conflicts.is_empty() {
743 return Ok(ConflictResolution::Resolved);
745 }
746
747 info!(
748 "Found {} conflict regions in {}",
749 conflicts.len(),
750 file_path
751 );
752
753 let mut resolved_content = content;
755 let mut any_resolved = false;
756
757 for conflict in conflicts.iter().rev() {
759 match self.resolve_single_conflict(conflict, file_path) {
760 Ok(Some(resolution)) => {
761 let before = &resolved_content[..conflict.start];
763 let after = &resolved_content[conflict.end..];
764 resolved_content = format!("{before}{resolution}{after}");
765 any_resolved = true;
766 debug!(
767 "โ
Resolved conflict at lines {}-{} in {}",
768 conflict.start_line, conflict.end_line, file_path
769 );
770 }
771 Ok(None) => {
772 debug!(
773 "โ ๏ธ Conflict at lines {}-{} in {} too complex for auto-resolution",
774 conflict.start_line, conflict.end_line, file_path
775 );
776 }
777 Err(e) => {
778 debug!("โ Failed to resolve conflict in {}: {}", file_path, e);
779 }
780 }
781 }
782
783 if any_resolved {
784 let remaining_conflicts = self.parse_conflict_markers(&resolved_content)?;
786
787 if remaining_conflicts.is_empty() {
788 crate::utils::atomic_file::write_string(&full_path, &resolved_content)?;
790
791 return Ok(ConflictResolution::Resolved);
792 } else {
793 info!(
794 "โ ๏ธ Partially resolved conflicts in {} ({} remaining)",
795 file_path,
796 remaining_conflicts.len()
797 );
798 }
799 }
800
801 Ok(ConflictResolution::TooComplex)
802 }
803
804 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
806 let lines: Vec<&str> = content.lines().collect();
807 let mut conflicts = Vec::new();
808 let mut i = 0;
809
810 while i < lines.len() {
811 if lines[i].starts_with("<<<<<<<") {
812 let start_line = i + 1;
814 let mut separator_line = None;
815 let mut end_line = None;
816
817 for (j, line) in lines.iter().enumerate().skip(i + 1) {
819 if line.starts_with("=======") {
820 separator_line = Some(j + 1);
821 } else if line.starts_with(">>>>>>>") {
822 end_line = Some(j + 1);
823 break;
824 }
825 }
826
827 if let (Some(sep), Some(end)) = (separator_line, end_line) {
828 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
830 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
831
832 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
833 let their_content = lines[sep..(end - 1)].join("\n");
834
835 conflicts.push(ConflictRegion {
836 start: start_pos,
837 end: end_pos,
838 start_line,
839 end_line: end,
840 our_content,
841 their_content,
842 });
843
844 i = end;
845 } else {
846 i += 1;
847 }
848 } else {
849 i += 1;
850 }
851 }
852
853 Ok(conflicts)
854 }
855
856 fn resolve_single_conflict(
858 &self,
859 conflict: &ConflictRegion,
860 file_path: &str,
861 ) -> Result<Option<String>> {
862 debug!(
863 "Analyzing conflict in {} (lines {}-{})",
864 file_path, conflict.start_line, conflict.end_line
865 );
866
867 if let Some(resolved) = self.resolve_whitespace_conflict(conflict)? {
869 debug!("Resolved as whitespace-only conflict");
870 return Ok(Some(resolved));
871 }
872
873 if let Some(resolved) = self.resolve_line_ending_conflict(conflict)? {
875 debug!("Resolved as line ending conflict");
876 return Ok(Some(resolved));
877 }
878
879 if let Some(resolved) = self.resolve_addition_conflict(conflict)? {
881 debug!("Resolved as pure addition conflict");
882 return Ok(Some(resolved));
883 }
884
885 if let Some(resolved) = self.resolve_import_conflict(conflict, file_path)? {
887 debug!("Resolved as import reordering conflict");
888 return Ok(Some(resolved));
889 }
890
891 Ok(None)
893 }
894
895 fn resolve_whitespace_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
897 let our_normalized = self.normalize_whitespace(&conflict.our_content);
898 let their_normalized = self.normalize_whitespace(&conflict.their_content);
899
900 if our_normalized == their_normalized {
901 let resolved =
903 if conflict.our_content.trim().len() >= conflict.their_content.trim().len() {
904 conflict.our_content.clone()
905 } else {
906 conflict.their_content.clone()
907 };
908
909 return Ok(Some(resolved));
910 }
911
912 Ok(None)
913 }
914
915 fn resolve_line_ending_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
917 let our_normalized = conflict
918 .our_content
919 .replace("\r\n", "\n")
920 .replace('\r', "\n");
921 let their_normalized = conflict
922 .their_content
923 .replace("\r\n", "\n")
924 .replace('\r', "\n");
925
926 if our_normalized == their_normalized {
927 return Ok(Some(our_normalized));
929 }
930
931 Ok(None)
932 }
933
934 fn resolve_addition_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
936 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
937 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
938
939 if our_lines.is_empty() {
941 return Ok(Some(conflict.their_content.clone()));
942 }
943 if their_lines.is_empty() {
944 return Ok(Some(conflict.our_content.clone()));
945 }
946
947 let mut merged_lines = Vec::new();
949 let mut our_idx = 0;
950 let mut their_idx = 0;
951
952 while our_idx < our_lines.len() || their_idx < their_lines.len() {
953 if our_idx >= our_lines.len() {
954 merged_lines.extend_from_slice(&their_lines[their_idx..]);
956 break;
957 } else if their_idx >= their_lines.len() {
958 merged_lines.extend_from_slice(&our_lines[our_idx..]);
960 break;
961 } else if our_lines[our_idx] == their_lines[their_idx] {
962 merged_lines.push(our_lines[our_idx]);
964 our_idx += 1;
965 their_idx += 1;
966 } else {
967 return Ok(None);
969 }
970 }
971
972 Ok(Some(merged_lines.join("\n")))
973 }
974
975 fn resolve_import_conflict(
977 &self,
978 conflict: &ConflictRegion,
979 file_path: &str,
980 ) -> Result<Option<String>> {
981 let is_import_file = file_path.ends_with(".rs")
983 || file_path.ends_with(".py")
984 || file_path.ends_with(".js")
985 || file_path.ends_with(".ts")
986 || file_path.ends_with(".go")
987 || file_path.ends_with(".java")
988 || file_path.ends_with(".swift")
989 || file_path.ends_with(".kt")
990 || file_path.ends_with(".cs");
991
992 if !is_import_file {
993 return Ok(None);
994 }
995
996 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
997 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
998
999 let our_imports = our_lines
1001 .iter()
1002 .all(|line| self.is_import_line(line, file_path));
1003 let their_imports = their_lines
1004 .iter()
1005 .all(|line| self.is_import_line(line, file_path));
1006
1007 if our_imports && their_imports {
1008 let mut all_imports: Vec<&str> = our_lines.into_iter().chain(their_lines).collect();
1010 all_imports.sort();
1011 all_imports.dedup();
1012
1013 return Ok(Some(all_imports.join("\n")));
1014 }
1015
1016 Ok(None)
1017 }
1018
1019 fn is_import_line(&self, line: &str, file_path: &str) -> bool {
1021 let trimmed = line.trim();
1022
1023 if trimmed.is_empty() {
1024 return true; }
1026
1027 if file_path.ends_with(".rs") {
1028 return trimmed.starts_with("use ") || trimmed.starts_with("extern crate");
1029 } else if file_path.ends_with(".py") {
1030 return trimmed.starts_with("import ") || trimmed.starts_with("from ");
1031 } else if file_path.ends_with(".js") || file_path.ends_with(".ts") {
1032 return trimmed.starts_with("import ")
1033 || trimmed.starts_with("const ")
1034 || trimmed.starts_with("require(");
1035 } else if file_path.ends_with(".go") {
1036 return trimmed.starts_with("import ") || trimmed == "import (" || trimmed == ")";
1037 } else if file_path.ends_with(".java") {
1038 return trimmed.starts_with("import ");
1039 } else if file_path.ends_with(".swift") {
1040 return trimmed.starts_with("import ") || trimmed.starts_with("@testable import ");
1041 } else if file_path.ends_with(".kt") {
1042 return trimmed.starts_with("import ") || trimmed.starts_with("@file:");
1043 } else if file_path.ends_with(".cs") {
1044 return trimmed.starts_with("using ") || trimmed.starts_with("extern alias ");
1045 }
1046
1047 false
1048 }
1049
1050 fn normalize_whitespace(&self, content: &str) -> String {
1052 content
1053 .lines()
1054 .map(|line| line.trim())
1055 .filter(|line| !line.is_empty())
1056 .collect::<Vec<_>>()
1057 .join("\n")
1058 }
1059
1060 fn update_stack_entry(
1063 &mut self,
1064 stack_id: Uuid,
1065 entry_id: &Uuid,
1066 _new_branch: &str,
1067 new_commit_hash: &str,
1068 ) -> Result<()> {
1069 debug!(
1070 "Updating entry {} in stack {} with new commit {}",
1071 entry_id, stack_id, new_commit_hash
1072 );
1073
1074 let stack = self
1076 .stack_manager
1077 .get_stack_mut(&stack_id)
1078 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1079
1080 if let Some(entry) = stack.entries.iter_mut().find(|e| e.id == *entry_id) {
1082 debug!(
1083 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch '{}')",
1084 entry_id, entry.commit_hash, new_commit_hash, entry.branch
1085 );
1086
1087 entry.commit_hash = new_commit_hash.to_string();
1090
1091 debug!(
1094 "Successfully updated entry {} in stack {}",
1095 entry_id, stack_id
1096 );
1097 Ok(())
1098 } else {
1099 Err(CascadeError::config(format!(
1100 "Entry {entry_id} not found in stack {stack_id}"
1101 )))
1102 }
1103 }
1104
1105 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1107 info!("Pulling latest changes for branch {}", branch);
1108
1109 match self.git_repo.fetch() {
1111 Ok(_) => {
1112 debug!("Fetch successful");
1113 match self.git_repo.pull(branch) {
1115 Ok(_) => {
1116 info!("Pull completed successfully for {}", branch);
1117 Ok(())
1118 }
1119 Err(e) => {
1120 warn!("Pull failed for {}: {}", branch, e);
1121 Ok(())
1123 }
1124 }
1125 }
1126 Err(e) => {
1127 warn!("Fetch failed: {}", e);
1128 Ok(())
1130 }
1131 }
1132 }
1133
1134 pub fn is_rebase_in_progress(&self) -> bool {
1136 let git_dir = self.git_repo.path().join(".git");
1138 git_dir.join("REBASE_HEAD").exists()
1139 || git_dir.join("rebase-merge").exists()
1140 || git_dir.join("rebase-apply").exists()
1141 }
1142
1143 pub fn abort_rebase(&self) -> Result<()> {
1145 info!("Aborting rebase operation");
1146
1147 let git_dir = self.git_repo.path().join(".git");
1148
1149 if git_dir.join("REBASE_HEAD").exists() {
1151 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1152 CascadeError::Git(git2::Error::from_str(&format!(
1153 "Failed to clean rebase state: {e}"
1154 )))
1155 })?;
1156 }
1157
1158 if git_dir.join("rebase-merge").exists() {
1159 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1160 CascadeError::Git(git2::Error::from_str(&format!(
1161 "Failed to clean rebase-merge: {e}"
1162 )))
1163 })?;
1164 }
1165
1166 if git_dir.join("rebase-apply").exists() {
1167 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1168 CascadeError::Git(git2::Error::from_str(&format!(
1169 "Failed to clean rebase-apply: {e}"
1170 )))
1171 })?;
1172 }
1173
1174 info!("Rebase aborted successfully");
1175 Ok(())
1176 }
1177
1178 pub fn continue_rebase(&self) -> Result<()> {
1180 info!("Continuing rebase operation");
1181
1182 if self.git_repo.has_conflicts()? {
1184 return Err(CascadeError::branch(
1185 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1186 ));
1187 }
1188
1189 self.git_repo.stage_conflict_resolved_files()?;
1191
1192 info!("Rebase continued successfully");
1193 Ok(())
1194 }
1195}
1196
1197impl RebaseResult {
1198 pub fn get_summary(&self) -> String {
1200 if self.success {
1201 format!("โ
{}", self.summary)
1202 } else {
1203 format!(
1204 "โ Rebase failed: {}",
1205 self.error.as_deref().unwrap_or("Unknown error")
1206 )
1207 }
1208 }
1209
1210 pub fn has_conflicts(&self) -> bool {
1212 !self.conflicts.is_empty()
1213 }
1214
1215 pub fn success_count(&self) -> usize {
1217 self.new_commits.len()
1218 }
1219}
1220
1221#[cfg(test)]
1222mod tests {
1223 use super::*;
1224 use std::path::PathBuf;
1225 use std::process::Command;
1226 use tempfile::TempDir;
1227
1228 #[allow(dead_code)]
1229 fn create_test_repo() -> (TempDir, PathBuf) {
1230 let temp_dir = TempDir::new().unwrap();
1231 let repo_path = temp_dir.path().to_path_buf();
1232
1233 Command::new("git")
1235 .args(["init"])
1236 .current_dir(&repo_path)
1237 .output()
1238 .unwrap();
1239 Command::new("git")
1240 .args(["config", "user.name", "Test"])
1241 .current_dir(&repo_path)
1242 .output()
1243 .unwrap();
1244 Command::new("git")
1245 .args(["config", "user.email", "test@test.com"])
1246 .current_dir(&repo_path)
1247 .output()
1248 .unwrap();
1249
1250 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1252 Command::new("git")
1253 .args(["add", "."])
1254 .current_dir(&repo_path)
1255 .output()
1256 .unwrap();
1257 Command::new("git")
1258 .args(["commit", "-m", "Initial"])
1259 .current_dir(&repo_path)
1260 .output()
1261 .unwrap();
1262
1263 (temp_dir, repo_path)
1264 }
1265
1266 #[test]
1267 fn test_conflict_region_creation() {
1268 let region = ConflictRegion {
1269 start: 0,
1270 end: 50,
1271 start_line: 1,
1272 end_line: 3,
1273 our_content: "function test() {\n return true;\n}".to_string(),
1274 their_content: "function test() {\n return true;\n}".to_string(),
1275 };
1276
1277 assert_eq!(region.start_line, 1);
1278 assert_eq!(region.end_line, 3);
1279 assert!(region.our_content.contains("return true"));
1280 assert!(region.their_content.contains("return true"));
1281 }
1282
1283 #[test]
1284 fn test_rebase_strategies() {
1285 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1286 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1287 }
1288
1289 #[test]
1290 fn test_rebase_options() {
1291 let options = RebaseOptions::default();
1292 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1293 assert!(!options.interactive);
1294 assert!(options.auto_resolve);
1295 assert_eq!(options.max_retries, 3);
1296 }
1297
1298 #[test]
1299 fn test_cleanup_guard_tracks_branches() {
1300 let mut guard = TempBranchCleanupGuard::new();
1301 assert!(guard.branches.is_empty());
1302
1303 guard.add_branch("test-branch-1".to_string());
1304 guard.add_branch("test-branch-2".to_string());
1305
1306 assert_eq!(guard.branches.len(), 2);
1307 assert_eq!(guard.branches[0], "test-branch-1");
1308 assert_eq!(guard.branches[1], "test-branch-2");
1309 }
1310
1311 #[test]
1312 fn test_cleanup_guard_prevents_double_cleanup() {
1313 use std::process::Command;
1314 use tempfile::TempDir;
1315
1316 let temp_dir = TempDir::new().unwrap();
1318 let repo_path = temp_dir.path();
1319
1320 Command::new("git")
1321 .args(["init"])
1322 .current_dir(repo_path)
1323 .output()
1324 .unwrap();
1325
1326 Command::new("git")
1327 .args(["config", "user.name", "Test"])
1328 .current_dir(repo_path)
1329 .output()
1330 .unwrap();
1331
1332 Command::new("git")
1333 .args(["config", "user.email", "test@test.com"])
1334 .current_dir(repo_path)
1335 .output()
1336 .unwrap();
1337
1338 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1340 Command::new("git")
1341 .args(["add", "."])
1342 .current_dir(repo_path)
1343 .output()
1344 .unwrap();
1345 Command::new("git")
1346 .args(["commit", "-m", "initial"])
1347 .current_dir(repo_path)
1348 .output()
1349 .unwrap();
1350
1351 let git_repo = GitRepository::open(repo_path).unwrap();
1352
1353 git_repo.create_branch("test-temp", None).unwrap();
1355
1356 let mut guard = TempBranchCleanupGuard::new();
1357 guard.add_branch("test-temp".to_string());
1358
1359 guard.cleanup(&git_repo);
1361 assert!(guard.cleaned);
1362
1363 guard.cleanup(&git_repo);
1365 assert!(guard.cleaned);
1366 }
1367
1368 #[test]
1369 fn test_rebase_result() {
1370 let result = RebaseResult {
1371 success: true,
1372 branch_mapping: std::collections::HashMap::new(),
1373 conflicts: vec!["abc123".to_string()],
1374 new_commits: vec!["def456".to_string()],
1375 error: None,
1376 summary: "Test summary".to_string(),
1377 };
1378
1379 assert!(result.success);
1380 assert!(result.has_conflicts());
1381 assert_eq!(result.success_count(), 1);
1382 }
1383
1384 #[test]
1385 fn test_import_line_detection() {
1386 let (_temp_dir, repo_path) = create_test_repo();
1387 let git_repo = crate::git::GitRepository::open(&repo_path).unwrap();
1388 let stack_manager = crate::stack::StackManager::new(&repo_path).unwrap();
1389 let options = RebaseOptions::default();
1390 let rebase_manager = RebaseManager::new(stack_manager, git_repo, options);
1391
1392 assert!(rebase_manager.is_import_line("import Foundation", "test.swift"));
1394 assert!(rebase_manager.is_import_line("@testable import MyModule", "test.swift"));
1395 assert!(!rebase_manager.is_import_line("class MyClass {", "test.swift"));
1396
1397 assert!(rebase_manager.is_import_line("import kotlin.collections.*", "test.kt"));
1399 assert!(rebase_manager.is_import_line("@file:JvmName(\"Utils\")", "test.kt"));
1400 assert!(!rebase_manager.is_import_line("fun myFunction() {", "test.kt"));
1401
1402 assert!(rebase_manager.is_import_line("using System;", "test.cs"));
1404 assert!(rebase_manager.is_import_line("using System.Collections.Generic;", "test.cs"));
1405 assert!(rebase_manager.is_import_line("extern alias GridV1;", "test.cs"));
1406 assert!(!rebase_manager.is_import_line("namespace MyNamespace {", "test.cs"));
1407
1408 assert!(rebase_manager.is_import_line("", "test.swift"));
1410 assert!(rebase_manager.is_import_line(" ", "test.kt"));
1411 assert!(rebase_manager.is_import_line("", "test.cs"));
1412 }
1413}