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