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 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" };
244 println!("Rebasing {} {}...", entry_count, plural);
245
246 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 let tree_char = if index + 1 == entry_count {
273 "โโ"
274 } else {
275 "โโ"
276 };
277
278 if let Some(pr_num) = &entry.pull_request_id {
279 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
280 branches_to_push.push((original_branch.clone(), pr_num.clone()));
281 } else {
282 println!(" {} {} (not submitted)", tree_char, original_branch);
283 }
284
285 result
286 .branch_mapping
287 .insert(original_branch.clone(), original_branch.clone());
288
289 self.update_stack_entry(
291 stack.id,
292 &entry.id,
293 original_branch,
294 &rebased_commit_id,
295 )?;
296
297 current_base = original_branch.clone();
299 }
300 Err(e) => {
301 println!(); Output::error(format!("Conflict in {}: {}", &entry.commit_hash[..8], e));
303 result.conflicts.push(entry.commit_hash.clone());
304
305 if !self.options.auto_resolve {
306 result.success = false;
307 result.error = Some(format!(
308 "Conflict in {}: {}\n\n\
309 Auto-resolution is disabled. To enable it, use 'ca sync --auto-resolve'\n\n\
310 Manual recovery:\n\
311 1. Resolve conflicts in the listed files\n\
312 2. Stage resolved files: 'git add <files>'\n\
313 3. Continue: 'git cherry-pick --continue'\n\
314 4. Or abort: 'git cherry-pick --abort' and retry 'ca sync'",
315 entry.commit_hash, e
316 ));
317 break;
318 }
319
320 match self.auto_resolve_conflicts(&entry.commit_hash) {
322 Ok(fully_resolved) => {
323 if !fully_resolved {
324 result.success = false;
325 result.error = Some(format!(
326 "Could not auto-resolve all conflicts in {}\n\n\
327 Recovery options:\n\
328 1. Run 'ca conflicts' to see detailed conflict analysis\n\
329 2. Manually resolve conflicts and run 'ca sync' again\n\
330 3. Use 'git reset --hard HEAD' to abort and start fresh",
331 &entry.commit_hash[..8]
332 ));
333 break;
334 }
335
336 let commit_message = format!("Auto-resolved conflicts in {}", &entry.commit_hash[..8]);
338 match self.git_repo.commit(&commit_message) {
339 Ok(new_commit_id) => {
340 Output::success("Auto-resolved conflicts");
341 result.new_commits.push(new_commit_id.clone());
342 let rebased_commit_id = new_commit_id;
343
344 self.git_repo
346 .update_branch_to_commit(original_branch, &rebased_commit_id)?;
347
348 let tree_char = if index + 1 == entry_count {
350 "โโ"
351 } else {
352 "โโ"
353 };
354
355 if let Some(pr_num) = &entry.pull_request_id {
356 println!(" {} {} (PR #{})", tree_char, original_branch, pr_num);
357 branches_to_push.push((original_branch.clone(), pr_num.clone()));
358 } else {
359 println!(" {} {} (not submitted)", tree_char, original_branch);
360 }
361
362 result
363 .branch_mapping
364 .insert(original_branch.clone(), original_branch.clone());
365
366 self.update_stack_entry(
368 stack.id,
369 &entry.id,
370 original_branch,
371 &rebased_commit_id,
372 )?;
373
374 current_base = original_branch.clone();
376 }
377 Err(commit_err) => {
378 result.success = false;
379 result.error = Some(format!(
380 "Could not commit auto-resolved conflicts: {}\n\n\
381 This usually means:\n\
382 - Git index is locked (another process accessing repo)\n\
383 - File permissions issue\n\
384 - Disk space issue\n\n\
385 Recovery:\n\
386 1. Check if another Git operation is running\n\
387 2. Run 'rm -f .git/index.lock' if stale lock exists\n\
388 3. Run 'git status' to check repo state\n\
389 4. Retry 'ca sync' after fixing the issue",
390 commit_err
391 ));
392 break;
393 }
394 }
395 }
396 Err(resolve_err) => {
397 result.success = false;
398 result.error = Some(format!(
399 "Could not resolve conflicts: {}\n\n\
400 Recovery:\n\
401 1. Check repo state: 'git status'\n\
402 2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
403 3. Remove any lock files: 'rm -f .git/index.lock'\n\
404 4. Retry 'ca sync'",
405 resolve_err
406 ));
407 break;
408 }
409 }
410 }
411 }
412 }
413
414 if !temp_branches.is_empty() {
417 if let Err(e) = self.git_repo.checkout_branch_silent(&target_base) {
419 Output::warning(format!("Could not checkout base for cleanup: {}", e));
420 }
421
422 for temp_branch in &temp_branches {
424 if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
425 debug!("Could not delete temp branch {}: {}", temp_branch, e);
426 }
427 }
428 }
429
430 let pushed_count = branches_to_push.len();
433 let skipped_count = entry_count - pushed_count;
434
435 if !branches_to_push.is_empty() {
436 println!(); println!("Pushing {} branch{} to remote...", pushed_count, if pushed_count == 1 { "" } else { "es" });
438
439 for (branch_name, _pr_num) in &branches_to_push {
440 match self.git_repo.force_push_single_branch_auto(branch_name) {
441 Ok(_) => {
442 debug!("Pushed {} successfully", branch_name);
443 }
444 Err(e) => {
445 Output::warning(format!("Could not push '{}': {}", branch_name, e));
446 }
448 }
449 }
450 }
451
452 if let Some(ref orig_branch) = original_branch {
455 if let Some(last_entry) = stack.entries.last() {
457 let top_branch = &last_entry.branch;
458
459 if let Ok(top_commit) = self.git_repo.get_branch_head(top_branch) {
461 debug!(
462 "Updating working branch '{}' to match top of stack ({})",
463 orig_branch, &top_commit[..8]
464 );
465
466 if let Err(e) = self.git_repo.update_branch_to_commit(orig_branch, &top_commit) {
467 Output::warning(format!(
468 "Could not update working branch '{}' to top of stack: {}",
469 orig_branch, e
470 ));
471 }
472 }
473 }
474
475 if let Err(e) = self.git_repo.checkout_branch_silent(orig_branch) {
477 Output::warning(format!(
478 "Could not return to original branch '{}': {}",
479 orig_branch, e
480 ));
481 }
482 }
483
484 result.summary = if pushed_count > 0 {
486 let pr_plural = if pushed_count == 1 { "" } else { "s" };
487 let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
488
489 if skipped_count > 0 {
490 format!(
491 "{} {} rebased ({} PR{} updated, {} not yet submitted)",
492 entry_count, entry_plural, pushed_count, pr_plural, skipped_count
493 )
494 } else {
495 format!(
496 "{} {} rebased ({} PR{} updated)",
497 entry_count, entry_plural, pushed_count, pr_plural
498 )
499 }
500 } else {
501 let plural = if entry_count == 1 { "entry" } else { "entries" };
502 format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
503 };
504
505 println!(); if result.success {
508 Output::success(&result.summary);
509 } else {
510 Output::error(format!("Rebase failed: {:?}", result.error));
511 }
512
513 self.stack_manager.save_to_disk()?;
515
516 Ok(result)
517 }
518
519 fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
521 info!("Starting interactive rebase for stack '{}'", stack.name);
522
523 let mut result = RebaseResult {
524 success: true,
525 branch_mapping: HashMap::new(),
526 conflicts: Vec::new(),
527 new_commits: Vec::new(),
528 error: None,
529 summary: String::new(),
530 };
531
532 println!("Interactive Rebase for Stack: {}", stack.name);
533 println!(" Base branch: {}", stack.base_branch);
534 println!(" Entries: {}", stack.entries.len());
535
536 if self.options.interactive {
537 println!("\nChoose action for each commit:");
538 println!(" (p)ick - apply the commit");
539 println!(" (s)kip - skip this commit");
540 println!(" (e)dit - edit the commit message");
541 println!(" (q)uit - abort the rebase");
542 }
543
544 for entry in &stack.entries {
547 println!(
548 " {} {} - {}",
549 entry.short_hash(),
550 entry.branch,
551 entry.short_message(50)
552 );
553
554 match self.cherry_pick_commit(&entry.commit_hash) {
556 Ok(new_commit) => result.new_commits.push(new_commit),
557 Err(_) => result.conflicts.push(entry.commit_hash.clone()),
558 }
559 }
560
561 result.summary = format!(
562 "Interactive rebase processed {} commits",
563 stack.entries.len()
564 );
565 Ok(result)
566 }
567
568 fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
570 let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
572
573 if let Ok(staged_files) = self.git_repo.get_staged_files() {
575 if !staged_files.is_empty() {
576 let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
578 let _ = self.git_repo.commit_staged_changes(&cleanup_message);
579 }
580 }
581
582 Ok(new_commit_hash)
583 }
584
585 fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
587 debug!("Attempting to auto-resolve conflicts for {}", commit_hash);
588
589 if !self.git_repo.has_conflicts()? {
591 return Ok(true);
592 }
593
594 let conflicted_files = self.git_repo.get_conflicted_files()?;
595
596 if conflicted_files.is_empty() {
597 return Ok(true);
598 }
599
600 info!(
601 "Found conflicts in {} files: {:?}",
602 conflicted_files.len(),
603 conflicted_files
604 );
605
606 let analysis = self
608 .conflict_analyzer
609 .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
610
611 info!(
612 "๐ Conflict analysis: {} total conflicts, {} auto-resolvable",
613 analysis.total_conflicts, analysis.auto_resolvable_count
614 );
615
616 for recommendation in &analysis.recommendations {
618 info!("๐ก {}", recommendation);
619 }
620
621 let mut resolved_count = 0;
622 let mut failed_files = Vec::new();
623
624 for file_analysis in &analysis.files {
625 if file_analysis.auto_resolvable {
626 match self.resolve_file_conflicts_enhanced(
627 &file_analysis.file_path,
628 &file_analysis.conflicts,
629 ) {
630 Ok(ConflictResolution::Resolved) => {
631 resolved_count += 1;
632 info!("โ
Auto-resolved conflicts in {}", file_analysis.file_path);
633 }
634 Ok(ConflictResolution::TooComplex) => {
635 debug!(
636 "โ ๏ธ Conflicts in {} are too complex for auto-resolution",
637 file_analysis.file_path
638 );
639 failed_files.push(file_analysis.file_path.clone());
640 }
641 Err(e) => {
642 warn!(
643 "โ Failed to resolve conflicts in {}: {}",
644 file_analysis.file_path, e
645 );
646 failed_files.push(file_analysis.file_path.clone());
647 }
648 }
649 } else {
650 failed_files.push(file_analysis.file_path.clone());
651 info!(
652 "โ ๏ธ {} requires manual resolution ({} conflicts)",
653 file_analysis.file_path,
654 file_analysis.conflicts.len()
655 );
656 }
657 }
658
659 if resolved_count > 0 {
660 info!(
661 "๐ Auto-resolved conflicts in {}/{} files",
662 resolved_count,
663 conflicted_files.len()
664 );
665
666 self.git_repo.stage_conflict_resolved_files()?;
668 }
669
670 let all_resolved = failed_files.is_empty();
672
673 if !all_resolved {
674 info!(
675 "โ ๏ธ {} files still need manual resolution: {:?}",
676 failed_files.len(),
677 failed_files
678 );
679 }
680
681 Ok(all_resolved)
682 }
683
684 fn resolve_file_conflicts_enhanced(
686 &self,
687 file_path: &str,
688 conflicts: &[crate::git::ConflictRegion],
689 ) -> Result<ConflictResolution> {
690 let repo_path = self.git_repo.path();
691 let full_path = repo_path.join(file_path);
692
693 let mut content = std::fs::read_to_string(&full_path)
695 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
696
697 if conflicts.is_empty() {
698 return Ok(ConflictResolution::Resolved);
699 }
700
701 info!(
702 "Resolving {} conflicts in {} using enhanced analysis",
703 conflicts.len(),
704 file_path
705 );
706
707 let mut any_resolved = false;
708
709 for conflict in conflicts.iter().rev() {
711 match self.resolve_single_conflict_enhanced(conflict) {
712 Ok(Some(resolution)) => {
713 let before = &content[..conflict.start_pos];
715 let after = &content[conflict.end_pos..];
716 content = format!("{before}{resolution}{after}");
717 any_resolved = true;
718 debug!(
719 "โ
Resolved {} conflict at lines {}-{} in {}",
720 format!("{:?}", conflict.conflict_type).to_lowercase(),
721 conflict.start_line,
722 conflict.end_line,
723 file_path
724 );
725 }
726 Ok(None) => {
727 debug!(
728 "โ ๏ธ {} conflict at lines {}-{} in {} requires manual resolution",
729 format!("{:?}", conflict.conflict_type).to_lowercase(),
730 conflict.start_line,
731 conflict.end_line,
732 file_path
733 );
734 return Ok(ConflictResolution::TooComplex);
735 }
736 Err(e) => {
737 debug!("โ Failed to resolve conflict in {}: {}", file_path, e);
738 return Ok(ConflictResolution::TooComplex);
739 }
740 }
741 }
742
743 if any_resolved {
744 let remaining_conflicts = self.parse_conflict_markers(&content)?;
746
747 if remaining_conflicts.is_empty() {
748 crate::utils::atomic_file::write_string(&full_path, &content)?;
750
751 return Ok(ConflictResolution::Resolved);
752 } else {
753 info!(
754 "โ ๏ธ Partially resolved conflicts in {} ({} remaining)",
755 file_path,
756 remaining_conflicts.len()
757 );
758 }
759 }
760
761 Ok(ConflictResolution::TooComplex)
762 }
763
764 fn resolve_single_conflict_enhanced(
766 &self,
767 conflict: &crate::git::ConflictRegion,
768 ) -> Result<Option<String>> {
769 debug!(
770 "Resolving {} conflict in {} (lines {}-{})",
771 format!("{:?}", conflict.conflict_type).to_lowercase(),
772 conflict.file_path,
773 conflict.start_line,
774 conflict.end_line
775 );
776
777 use crate::git::ConflictType;
778
779 match conflict.conflict_type {
780 ConflictType::Whitespace => {
781 if conflict.our_content.trim().len() >= conflict.their_content.trim().len() {
783 Ok(Some(conflict.our_content.clone()))
784 } else {
785 Ok(Some(conflict.their_content.clone()))
786 }
787 }
788 ConflictType::LineEnding => {
789 let normalized = conflict
791 .our_content
792 .replace("\r\n", "\n")
793 .replace('\r', "\n");
794 Ok(Some(normalized))
795 }
796 ConflictType::PureAddition => {
797 if conflict.our_content.is_empty() {
799 Ok(Some(conflict.their_content.clone()))
800 } else if conflict.their_content.is_empty() {
801 Ok(Some(conflict.our_content.clone()))
802 } else {
803 let combined = format!("{}\n{}", conflict.our_content, conflict.their_content);
805 Ok(Some(combined))
806 }
807 }
808 ConflictType::ImportMerge => {
809 let mut all_imports: Vec<&str> = conflict
811 .our_content
812 .lines()
813 .chain(conflict.their_content.lines())
814 .collect();
815 all_imports.sort();
816 all_imports.dedup();
817 Ok(Some(all_imports.join("\n")))
818 }
819 ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
820 Ok(None)
822 }
823 }
824 }
825
826 #[allow(dead_code)]
828 fn resolve_file_conflicts(&self, file_path: &str) -> Result<ConflictResolution> {
829 let repo_path = self.git_repo.path();
830 let full_path = repo_path.join(file_path);
831
832 let content = std::fs::read_to_string(&full_path)
834 .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
835
836 let conflicts = self.parse_conflict_markers(&content)?;
838
839 if conflicts.is_empty() {
840 return Ok(ConflictResolution::Resolved);
842 }
843
844 info!(
845 "Found {} conflict regions in {}",
846 conflicts.len(),
847 file_path
848 );
849
850 let mut resolved_content = content;
852 let mut any_resolved = false;
853
854 for conflict in conflicts.iter().rev() {
856 match self.resolve_single_conflict(conflict, file_path) {
857 Ok(Some(resolution)) => {
858 let before = &resolved_content[..conflict.start];
860 let after = &resolved_content[conflict.end..];
861 resolved_content = format!("{before}{resolution}{after}");
862 any_resolved = true;
863 debug!(
864 "โ
Resolved conflict at lines {}-{} in {}",
865 conflict.start_line, conflict.end_line, file_path
866 );
867 }
868 Ok(None) => {
869 debug!(
870 "โ ๏ธ Conflict at lines {}-{} in {} too complex for auto-resolution",
871 conflict.start_line, conflict.end_line, file_path
872 );
873 }
874 Err(e) => {
875 debug!("โ Failed to resolve conflict in {}: {}", file_path, e);
876 }
877 }
878 }
879
880 if any_resolved {
881 let remaining_conflicts = self.parse_conflict_markers(&resolved_content)?;
883
884 if remaining_conflicts.is_empty() {
885 crate::utils::atomic_file::write_string(&full_path, &resolved_content)?;
887
888 return Ok(ConflictResolution::Resolved);
889 } else {
890 info!(
891 "โ ๏ธ Partially resolved conflicts in {} ({} remaining)",
892 file_path,
893 remaining_conflicts.len()
894 );
895 }
896 }
897
898 Ok(ConflictResolution::TooComplex)
899 }
900
901 fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
903 let lines: Vec<&str> = content.lines().collect();
904 let mut conflicts = Vec::new();
905 let mut i = 0;
906
907 while i < lines.len() {
908 if lines[i].starts_with("<<<<<<<") {
909 let start_line = i + 1;
911 let mut separator_line = None;
912 let mut end_line = None;
913
914 for (j, line) in lines.iter().enumerate().skip(i + 1) {
916 if line.starts_with("=======") {
917 separator_line = Some(j + 1);
918 } else if line.starts_with(">>>>>>>") {
919 end_line = Some(j + 1);
920 break;
921 }
922 }
923
924 if let (Some(sep), Some(end)) = (separator_line, end_line) {
925 let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
927 let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
928
929 let our_content = lines[(i + 1)..(sep - 1)].join("\n");
930 let their_content = lines[sep..(end - 1)].join("\n");
931
932 conflicts.push(ConflictRegion {
933 start: start_pos,
934 end: end_pos,
935 start_line,
936 end_line: end,
937 our_content,
938 their_content,
939 });
940
941 i = end;
942 } else {
943 i += 1;
944 }
945 } else {
946 i += 1;
947 }
948 }
949
950 Ok(conflicts)
951 }
952
953 fn resolve_single_conflict(
955 &self,
956 conflict: &ConflictRegion,
957 file_path: &str,
958 ) -> Result<Option<String>> {
959 debug!(
960 "Analyzing conflict in {} (lines {}-{})",
961 file_path, conflict.start_line, conflict.end_line
962 );
963
964 if let Some(resolved) = self.resolve_whitespace_conflict(conflict)? {
966 debug!("Resolved as whitespace-only conflict");
967 return Ok(Some(resolved));
968 }
969
970 if let Some(resolved) = self.resolve_line_ending_conflict(conflict)? {
972 debug!("Resolved as line ending conflict");
973 return Ok(Some(resolved));
974 }
975
976 if let Some(resolved) = self.resolve_addition_conflict(conflict)? {
978 debug!("Resolved as pure addition conflict");
979 return Ok(Some(resolved));
980 }
981
982 if let Some(resolved) = self.resolve_import_conflict(conflict, file_path)? {
984 debug!("Resolved as import reordering conflict");
985 return Ok(Some(resolved));
986 }
987
988 Ok(None)
990 }
991
992 fn resolve_whitespace_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
994 let our_normalized = self.normalize_whitespace(&conflict.our_content);
995 let their_normalized = self.normalize_whitespace(&conflict.their_content);
996
997 if our_normalized == their_normalized {
998 let resolved =
1000 if conflict.our_content.trim().len() >= conflict.their_content.trim().len() {
1001 conflict.our_content.clone()
1002 } else {
1003 conflict.their_content.clone()
1004 };
1005
1006 return Ok(Some(resolved));
1007 }
1008
1009 Ok(None)
1010 }
1011
1012 fn resolve_line_ending_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1014 let our_normalized = conflict
1015 .our_content
1016 .replace("\r\n", "\n")
1017 .replace('\r', "\n");
1018 let their_normalized = conflict
1019 .their_content
1020 .replace("\r\n", "\n")
1021 .replace('\r', "\n");
1022
1023 if our_normalized == their_normalized {
1024 return Ok(Some(our_normalized));
1026 }
1027
1028 Ok(None)
1029 }
1030
1031 fn resolve_addition_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1033 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1034 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1035
1036 if our_lines.is_empty() {
1038 return Ok(Some(conflict.their_content.clone()));
1039 }
1040 if their_lines.is_empty() {
1041 return Ok(Some(conflict.our_content.clone()));
1042 }
1043
1044 let mut merged_lines = Vec::new();
1046 let mut our_idx = 0;
1047 let mut their_idx = 0;
1048
1049 while our_idx < our_lines.len() || their_idx < their_lines.len() {
1050 if our_idx >= our_lines.len() {
1051 merged_lines.extend_from_slice(&their_lines[their_idx..]);
1053 break;
1054 } else if their_idx >= their_lines.len() {
1055 merged_lines.extend_from_slice(&our_lines[our_idx..]);
1057 break;
1058 } else if our_lines[our_idx] == their_lines[their_idx] {
1059 merged_lines.push(our_lines[our_idx]);
1061 our_idx += 1;
1062 their_idx += 1;
1063 } else {
1064 return Ok(None);
1066 }
1067 }
1068
1069 Ok(Some(merged_lines.join("\n")))
1070 }
1071
1072 fn resolve_import_conflict(
1074 &self,
1075 conflict: &ConflictRegion,
1076 file_path: &str,
1077 ) -> Result<Option<String>> {
1078 let is_import_file = file_path.ends_with(".rs")
1080 || file_path.ends_with(".py")
1081 || file_path.ends_with(".js")
1082 || file_path.ends_with(".ts")
1083 || file_path.ends_with(".go")
1084 || file_path.ends_with(".java")
1085 || file_path.ends_with(".swift")
1086 || file_path.ends_with(".kt")
1087 || file_path.ends_with(".cs");
1088
1089 if !is_import_file {
1090 return Ok(None);
1091 }
1092
1093 let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1094 let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1095
1096 let our_imports = our_lines
1098 .iter()
1099 .all(|line| self.is_import_line(line, file_path));
1100 let their_imports = their_lines
1101 .iter()
1102 .all(|line| self.is_import_line(line, file_path));
1103
1104 if our_imports && their_imports {
1105 let mut all_imports: Vec<&str> = our_lines.into_iter().chain(their_lines).collect();
1107 all_imports.sort();
1108 all_imports.dedup();
1109
1110 return Ok(Some(all_imports.join("\n")));
1111 }
1112
1113 Ok(None)
1114 }
1115
1116 fn is_import_line(&self, line: &str, file_path: &str) -> bool {
1118 let trimmed = line.trim();
1119
1120 if trimmed.is_empty() {
1121 return true; }
1123
1124 if file_path.ends_with(".rs") {
1125 return trimmed.starts_with("use ") || trimmed.starts_with("extern crate");
1126 } else if file_path.ends_with(".py") {
1127 return trimmed.starts_with("import ") || trimmed.starts_with("from ");
1128 } else if file_path.ends_with(".js") || file_path.ends_with(".ts") {
1129 return trimmed.starts_with("import ")
1130 || trimmed.starts_with("const ")
1131 || trimmed.starts_with("require(");
1132 } else if file_path.ends_with(".go") {
1133 return trimmed.starts_with("import ") || trimmed == "import (" || trimmed == ")";
1134 } else if file_path.ends_with(".java") {
1135 return trimmed.starts_with("import ");
1136 } else if file_path.ends_with(".swift") {
1137 return trimmed.starts_with("import ") || trimmed.starts_with("@testable import ");
1138 } else if file_path.ends_with(".kt") {
1139 return trimmed.starts_with("import ") || trimmed.starts_with("@file:");
1140 } else if file_path.ends_with(".cs") {
1141 return trimmed.starts_with("using ") || trimmed.starts_with("extern alias ");
1142 }
1143
1144 false
1145 }
1146
1147 fn normalize_whitespace(&self, content: &str) -> String {
1149 content
1150 .lines()
1151 .map(|line| line.trim())
1152 .filter(|line| !line.is_empty())
1153 .collect::<Vec<_>>()
1154 .join("\n")
1155 }
1156
1157 fn update_stack_entry(
1160 &mut self,
1161 stack_id: Uuid,
1162 entry_id: &Uuid,
1163 _new_branch: &str,
1164 new_commit_hash: &str,
1165 ) -> Result<()> {
1166 debug!(
1167 "Updating entry {} in stack {} with new commit {}",
1168 entry_id, stack_id, new_commit_hash
1169 );
1170
1171 let stack = self
1173 .stack_manager
1174 .get_stack_mut(&stack_id)
1175 .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1176
1177 if let Some(entry) = stack.entries.iter_mut().find(|e| e.id == *entry_id) {
1179 debug!(
1180 "Found entry {} - updating commit from '{}' to '{}' (keeping original branch '{}')",
1181 entry_id, entry.commit_hash, new_commit_hash, entry.branch
1182 );
1183
1184 entry.commit_hash = new_commit_hash.to_string();
1187
1188 debug!(
1191 "Successfully updated entry {} in stack {}",
1192 entry_id, stack_id
1193 );
1194 Ok(())
1195 } else {
1196 Err(CascadeError::config(format!(
1197 "Entry {entry_id} not found in stack {stack_id}"
1198 )))
1199 }
1200 }
1201
1202 fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1204 info!("Pulling latest changes for branch {}", branch);
1205
1206 match self.git_repo.fetch() {
1208 Ok(_) => {
1209 debug!("Fetch successful");
1210 match self.git_repo.pull(branch) {
1212 Ok(_) => {
1213 info!("Pull completed successfully for {}", branch);
1214 Ok(())
1215 }
1216 Err(e) => {
1217 warn!("Pull failed for {}: {}", branch, e);
1218 Ok(())
1220 }
1221 }
1222 }
1223 Err(e) => {
1224 warn!("Fetch failed: {}", e);
1225 Ok(())
1227 }
1228 }
1229 }
1230
1231 pub fn is_rebase_in_progress(&self) -> bool {
1233 let git_dir = self.git_repo.path().join(".git");
1235 git_dir.join("REBASE_HEAD").exists()
1236 || git_dir.join("rebase-merge").exists()
1237 || git_dir.join("rebase-apply").exists()
1238 }
1239
1240 pub fn abort_rebase(&self) -> Result<()> {
1242 info!("Aborting rebase operation");
1243
1244 let git_dir = self.git_repo.path().join(".git");
1245
1246 if git_dir.join("REBASE_HEAD").exists() {
1248 std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1249 CascadeError::Git(git2::Error::from_str(&format!(
1250 "Failed to clean rebase state: {e}"
1251 )))
1252 })?;
1253 }
1254
1255 if git_dir.join("rebase-merge").exists() {
1256 std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1257 CascadeError::Git(git2::Error::from_str(&format!(
1258 "Failed to clean rebase-merge: {e}"
1259 )))
1260 })?;
1261 }
1262
1263 if git_dir.join("rebase-apply").exists() {
1264 std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1265 CascadeError::Git(git2::Error::from_str(&format!(
1266 "Failed to clean rebase-apply: {e}"
1267 )))
1268 })?;
1269 }
1270
1271 info!("Rebase aborted successfully");
1272 Ok(())
1273 }
1274
1275 pub fn continue_rebase(&self) -> Result<()> {
1277 info!("Continuing rebase operation");
1278
1279 if self.git_repo.has_conflicts()? {
1281 return Err(CascadeError::branch(
1282 "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1283 ));
1284 }
1285
1286 self.git_repo.stage_conflict_resolved_files()?;
1288
1289 info!("Rebase continued successfully");
1290 Ok(())
1291 }
1292}
1293
1294impl RebaseResult {
1295 pub fn get_summary(&self) -> String {
1297 if self.success {
1298 format!("โ
{}", self.summary)
1299 } else {
1300 format!(
1301 "โ Rebase failed: {}",
1302 self.error.as_deref().unwrap_or("Unknown error")
1303 )
1304 }
1305 }
1306
1307 pub fn has_conflicts(&self) -> bool {
1309 !self.conflicts.is_empty()
1310 }
1311
1312 pub fn success_count(&self) -> usize {
1314 self.new_commits.len()
1315 }
1316}
1317
1318#[cfg(test)]
1319mod tests {
1320 use super::*;
1321 use std::path::PathBuf;
1322 use std::process::Command;
1323 use tempfile::TempDir;
1324
1325 #[allow(dead_code)]
1326 fn create_test_repo() -> (TempDir, PathBuf) {
1327 let temp_dir = TempDir::new().unwrap();
1328 let repo_path = temp_dir.path().to_path_buf();
1329
1330 Command::new("git")
1332 .args(["init"])
1333 .current_dir(&repo_path)
1334 .output()
1335 .unwrap();
1336 Command::new("git")
1337 .args(["config", "user.name", "Test"])
1338 .current_dir(&repo_path)
1339 .output()
1340 .unwrap();
1341 Command::new("git")
1342 .args(["config", "user.email", "test@test.com"])
1343 .current_dir(&repo_path)
1344 .output()
1345 .unwrap();
1346
1347 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1349 Command::new("git")
1350 .args(["add", "."])
1351 .current_dir(&repo_path)
1352 .output()
1353 .unwrap();
1354 Command::new("git")
1355 .args(["commit", "-m", "Initial"])
1356 .current_dir(&repo_path)
1357 .output()
1358 .unwrap();
1359
1360 (temp_dir, repo_path)
1361 }
1362
1363 #[test]
1364 fn test_conflict_region_creation() {
1365 let region = ConflictRegion {
1366 start: 0,
1367 end: 50,
1368 start_line: 1,
1369 end_line: 3,
1370 our_content: "function test() {\n return true;\n}".to_string(),
1371 their_content: "function test() {\n return true;\n}".to_string(),
1372 };
1373
1374 assert_eq!(region.start_line, 1);
1375 assert_eq!(region.end_line, 3);
1376 assert!(region.our_content.contains("return true"));
1377 assert!(region.their_content.contains("return true"));
1378 }
1379
1380 #[test]
1381 fn test_rebase_strategies() {
1382 assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1383 assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1384 }
1385
1386 #[test]
1387 fn test_rebase_options() {
1388 let options = RebaseOptions::default();
1389 assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1390 assert!(!options.interactive);
1391 assert!(options.auto_resolve);
1392 assert_eq!(options.max_retries, 3);
1393 }
1394
1395 #[test]
1396 fn test_cleanup_guard_tracks_branches() {
1397 let mut guard = TempBranchCleanupGuard::new();
1398 assert!(guard.branches.is_empty());
1399
1400 guard.add_branch("test-branch-1".to_string());
1401 guard.add_branch("test-branch-2".to_string());
1402
1403 assert_eq!(guard.branches.len(), 2);
1404 assert_eq!(guard.branches[0], "test-branch-1");
1405 assert_eq!(guard.branches[1], "test-branch-2");
1406 }
1407
1408 #[test]
1409 fn test_cleanup_guard_prevents_double_cleanup() {
1410 use std::process::Command;
1411 use tempfile::TempDir;
1412
1413 let temp_dir = TempDir::new().unwrap();
1415 let repo_path = temp_dir.path();
1416
1417 Command::new("git")
1418 .args(["init"])
1419 .current_dir(repo_path)
1420 .output()
1421 .unwrap();
1422
1423 Command::new("git")
1424 .args(["config", "user.name", "Test"])
1425 .current_dir(repo_path)
1426 .output()
1427 .unwrap();
1428
1429 Command::new("git")
1430 .args(["config", "user.email", "test@test.com"])
1431 .current_dir(repo_path)
1432 .output()
1433 .unwrap();
1434
1435 std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1437 Command::new("git")
1438 .args(["add", "."])
1439 .current_dir(repo_path)
1440 .output()
1441 .unwrap();
1442 Command::new("git")
1443 .args(["commit", "-m", "initial"])
1444 .current_dir(repo_path)
1445 .output()
1446 .unwrap();
1447
1448 let git_repo = GitRepository::open(repo_path).unwrap();
1449
1450 git_repo.create_branch("test-temp", None).unwrap();
1452
1453 let mut guard = TempBranchCleanupGuard::new();
1454 guard.add_branch("test-temp".to_string());
1455
1456 guard.cleanup(&git_repo);
1458 assert!(guard.cleaned);
1459
1460 guard.cleanup(&git_repo);
1462 assert!(guard.cleaned);
1463 }
1464
1465 #[test]
1466 fn test_rebase_result() {
1467 let result = RebaseResult {
1468 success: true,
1469 branch_mapping: std::collections::HashMap::new(),
1470 conflicts: vec!["abc123".to_string()],
1471 new_commits: vec!["def456".to_string()],
1472 error: None,
1473 summary: "Test summary".to_string(),
1474 };
1475
1476 assert!(result.success);
1477 assert!(result.has_conflicts());
1478 assert_eq!(result.success_count(), 1);
1479 }
1480
1481 #[test]
1482 fn test_import_line_detection() {
1483 let (_temp_dir, repo_path) = create_test_repo();
1484 let git_repo = crate::git::GitRepository::open(&repo_path).unwrap();
1485 let stack_manager = crate::stack::StackManager::new(&repo_path).unwrap();
1486 let options = RebaseOptions::default();
1487 let rebase_manager = RebaseManager::new(stack_manager, git_repo, options);
1488
1489 assert!(rebase_manager.is_import_line("import Foundation", "test.swift"));
1491 assert!(rebase_manager.is_import_line("@testable import MyModule", "test.swift"));
1492 assert!(!rebase_manager.is_import_line("class MyClass {", "test.swift"));
1493
1494 assert!(rebase_manager.is_import_line("import kotlin.collections.*", "test.kt"));
1496 assert!(rebase_manager.is_import_line("@file:JvmName(\"Utils\")", "test.kt"));
1497 assert!(!rebase_manager.is_import_line("fun myFunction() {", "test.kt"));
1498
1499 assert!(rebase_manager.is_import_line("using System;", "test.cs"));
1501 assert!(rebase_manager.is_import_line("using System.Collections.Generic;", "test.cs"));
1502 assert!(rebase_manager.is_import_line("extern alias GridV1;", "test.cs"));
1503 assert!(!rebase_manager.is_import_line("namespace MyNamespace {", "test.cs"));
1504
1505 assert!(rebase_manager.is_import_line("", "test.swift"));
1507 assert!(rebase_manager.is_import_line(" ", "test.kt"));
1508 assert!(rebase_manager.is_import_line("", "test.cs"));
1509 }
1510}