cascade_cli/stack/
rebase.rs

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/// Conflict resolution result
11#[derive(Debug, Clone)]
12enum ConflictResolution {
13    /// Conflict was successfully resolved
14    Resolved,
15    /// Conflict is too complex for automatic resolution
16    TooComplex,
17}
18
19/// Represents a conflict region in a file
20#[derive(Debug, Clone)]
21#[allow(dead_code)]
22struct ConflictRegion {
23    /// Byte position where conflict starts
24    start: usize,
25    /// Byte position where conflict ends  
26    end: usize,
27    /// Line number where conflict starts
28    start_line: usize,
29    /// Line number where conflict ends
30    end_line: usize,
31    /// Content from "our" side (before separator)
32    our_content: String,
33    /// Content from "their" side (after separator)
34    their_content: String,
35}
36
37/// Strategy for rebasing stacks (force-push is the only valid approach for preserving PR history)
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
39pub enum RebaseStrategy {
40    /// Force-push rebased commits to original branches (preserves PR history)
41    /// This is the industry standard used by Graphite, Phabricator, spr, etc.
42    ForcePush,
43    /// Interactive rebase with conflict resolution
44    Interactive,
45}
46
47/// Options for rebase operations
48#[derive(Debug, Clone)]
49pub struct RebaseOptions {
50    /// The rebase strategy to use
51    pub strategy: RebaseStrategy,
52    /// Whether to run interactively (prompt for user input)
53    pub interactive: bool,
54    /// Target base branch to rebase onto
55    pub target_base: Option<String>,
56    /// Whether to preserve merge commits
57    pub preserve_merges: bool,
58    /// Whether to auto-resolve simple conflicts
59    pub auto_resolve: bool,
60    /// Maximum number of retries for conflict resolution
61    pub max_retries: usize,
62    /// Skip pulling latest changes (when already done by caller)
63    pub skip_pull: Option<bool>,
64}
65
66/// Result of a rebase operation
67#[derive(Debug)]
68pub struct RebaseResult {
69    /// Whether the rebase was successful
70    pub success: bool,
71    /// Old branch to new branch mapping
72    pub branch_mapping: HashMap<String, String>,
73    /// Commits that had conflicts
74    pub conflicts: Vec<String>,
75    /// New commit hashes
76    pub new_commits: Vec<String>,
77    /// Error message if rebase failed
78    pub error: Option<String>,
79    /// Summary of changes made
80    pub summary: String,
81}
82
83/// RAII guard to ensure temporary branches are cleaned up even on error/panic
84///
85/// This stores branch names and provides a cleanup method that can be called
86/// with a GitRepository reference. The Drop trait ensures cleanup happens
87/// even if the rebase function panics or returns early with an error.
88#[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    /// Perform cleanup with provided git repository
108    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                // Continue with cleanup even if one fails
118            }
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            // This path is only hit on panic or unexpected early return
128            // We can't access git_repo here, so just log the branches that need manual cleanup
129            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
139/// Manages rebase operations for stacks
140pub 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    /// Create a new rebase manager
163    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    /// Consume the rebase manager and return the updated stack manager
177    pub fn into_stack_manager(self) -> StackManager {
178        self.stack_manager
179    }
180
181    /// Rebase an entire stack onto a new base
182    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    /// Rebase using force-push strategy (industry standard for stacked diffs)
198    /// This updates local branches in-place, then force-pushes ONLY branches with existing PRs
199    /// to preserve PR history - the approach used by Graphite, Phabricator, spr, etc.
200    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(); // Clone to avoid borrow issues
220
221        // Save original working branch to restore later
222        let original_branch = self.git_repo.get_current_branch().ok();
223
224        // Note: Caller (sync_stack) has already checked out base branch when skip_pull=true
225        // Only pull if not already done by caller (like sync command)
226        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        // Reset working directory to clean state before rebase
233        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(); // Track temp branches for cleanup
242
243        println!(); // Spacing before tree
244        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            // Create a temporary branch from the current base
251            // This avoids committing directly to protected branches like develop/main
252            let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
253            temp_branches.push(temp_branch.clone()); // Track for cleanup
254            self.git_repo
255                .create_branch(&temp_branch, Some(&current_base))?;
256            self.git_repo.checkout_branch(&temp_branch)?;
257
258            // Cherry-pick the commit onto the temp branch (NOT the protected base!)
259            match self.cherry_pick_commit(&entry.commit_hash) {
260                Ok(new_commit_hash) => {
261                    result.new_commits.push(new_commit_hash.clone());
262
263                    // Get the commit that's now at HEAD (the cherry-picked commit)
264                    let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
265
266                    // Update the original branch to point to this rebased commit
267                    // This is LOCAL ONLY - moves refs/heads/<branch> to the commit on temp branch
268                    self.git_repo
269                        .update_branch_to_commit(original_branch, &rebased_commit_id)?;
270
271                    // Only force-push to REMOTE if this entry has a PR
272                    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                        // NOW do the actual force-push to remote (git push --force origin <branch>)
282                        // This updates the PR with the rebased commits
283                        // Use auto-confirm version since user already confirmed sync operation
284                        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                    // Update stack entry with new commit hash
302                    self.update_stack_entry(
303                        stack.id,
304                        &entry.id,
305                        original_branch,
306                        &rebased_commit_id,
307                    )?;
308
309                    // This branch becomes the base for the next entry
310                    current_base = original_branch.clone();
311                }
312                Err(e) => {
313                    println!(); // Spacing before error
314                    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                    // Try to resolve automatically
324                    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        // Cleanup temp branches before returning to original branch
340        // Must checkout away from temp branches first
341        if !temp_branches.is_empty() {
342            // Checkout base branch silently to allow temp branch deletion
343            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            // Delete all temp branches
348            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        // Update working branch to point to the top of the rebased stack
356        // This ensures subsequent `ca push` doesn't re-add old commits
357        if let Some(ref orig_branch) = original_branch {
358            // Get the last entry's branch (top of stack)
359            if let Some(last_entry) = stack.entries.last() {
360                let top_branch = &last_entry.branch;
361                
362                // Force-update working branch to point to same commit as top entry
363                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            // Return to original working branch silently
379            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        // Build summary message
388        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        // Display result with proper formatting
409        println!(); // Spacing after tree
410        if result.success {
411            Output::success(&result.summary);
412        } else {
413            Output::error(format!("Rebase failed: {:?}", result.error));
414        }
415
416        // Save the updated stack metadata to disk
417        self.stack_manager.save_to_disk()?;
418
419        Ok(result)
420    }
421
422    /// Interactive rebase with user input
423    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 now, automatically pick all commits
448        // In a real implementation, this would prompt the user
449        for entry in &stack.entries {
450            println!(
451                "  {} {} - {}",
452                entry.short_hash(),
453                entry.branch,
454                entry.short_message(50)
455            );
456
457            // Auto-pick for demo purposes
458            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    /// Cherry-pick a commit onto the current branch
472    fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
473        // Use the real cherry-pick implementation from GitRepository
474        let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
475
476        // Check for any leftover staged changes after successful cherry-pick
477        if let Ok(staged_files) = self.git_repo.get_staged_files() {
478            if !staged_files.is_empty() {
479                // Commit any leftover staged changes silently
480                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    /// Attempt to automatically resolve conflicts
489    fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
490        debug!("Attempting to auto-resolve conflicts for {}", commit_hash);
491
492        // Check if there are actually conflicts
493        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        // Use the new conflict analyzer for detailed analysis
510        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        // Display recommendations
520        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            // Stage all resolved files
570            self.git_repo.stage_conflict_resolved_files()?;
571        }
572
573        // Return true only if ALL conflicts were resolved
574        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    /// Resolve conflicts using enhanced analysis
588    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        // Read the file content with conflict markers
597        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        // Process conflicts in reverse order to maintain string indices
613        for conflict in conflicts.iter().rev() {
614            match self.resolve_single_conflict_enhanced(conflict) {
615                Ok(Some(resolution)) => {
616                    // Replace the conflict region with the resolved content
617                    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            // Check if we resolved ALL conflicts in this file
648            let remaining_conflicts = self.parse_conflict_markers(&content)?;
649
650            if remaining_conflicts.is_empty() {
651                // All conflicts resolved - write the file back atomically
652                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    /// Resolve a single conflict using enhanced analysis
668    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                // Use the version with better formatting
685                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                // Normalize to Unix line endings
693                let normalized = conflict
694                    .our_content
695                    .replace("\r\n", "\n")
696                    .replace('\r', "\n");
697                Ok(Some(normalized))
698            }
699            ConflictType::PureAddition => {
700                // Merge both additions
701                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                    // Try to combine both
707                    let combined = format!("{}\n{}", conflict.our_content, conflict.their_content);
708                    Ok(Some(combined))
709                }
710            }
711            ConflictType::ImportMerge => {
712                // Sort and merge imports
713                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                // These require manual resolution
724                Ok(None)
725            }
726        }
727    }
728
729    /// Resolve conflicts in a single file using smart strategies
730    #[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        // Read the file content with conflict markers
736        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        // Parse conflicts from the file
740        let conflicts = self.parse_conflict_markers(&content)?;
741
742        if conflicts.is_empty() {
743            // No conflict markers found - file might already be resolved
744            return Ok(ConflictResolution::Resolved);
745        }
746
747        info!(
748            "Found {} conflict regions in {}",
749            conflicts.len(),
750            file_path
751        );
752
753        // Try to resolve each conflict using our strategies
754        let mut resolved_content = content;
755        let mut any_resolved = false;
756
757        // Process conflicts in reverse order to maintain string indices
758        for conflict in conflicts.iter().rev() {
759            match self.resolve_single_conflict(conflict, file_path) {
760                Ok(Some(resolution)) => {
761                    // Replace the conflict region with the resolved content
762                    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            // Check if we resolved ALL conflicts in this file
785            let remaining_conflicts = self.parse_conflict_markers(&resolved_content)?;
786
787            if remaining_conflicts.is_empty() {
788                // All conflicts resolved - write the file back atomically
789                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    /// Parse conflict markers from file content
805    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                // Found start of conflict
813                let start_line = i + 1;
814                let mut separator_line = None;
815                let mut end_line = None;
816
817                // Find the separator and end
818                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                    // Calculate byte positions
829                    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    /// Resolve a single conflict using smart strategies
857    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        // Strategy 1: Whitespace-only differences
868        if let Some(resolved) = self.resolve_whitespace_conflict(conflict)? {
869            debug!("Resolved as whitespace-only conflict");
870            return Ok(Some(resolved));
871        }
872
873        // Strategy 2: Line ending differences
874        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        // Strategy 3: Pure addition conflicts (no overlapping changes)
880        if let Some(resolved) = self.resolve_addition_conflict(conflict)? {
881            debug!("Resolved as pure addition conflict");
882            return Ok(Some(resolved));
883        }
884
885        // Strategy 4: Import/dependency reordering
886        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        // No strategy could resolve this conflict
892        Ok(None)
893    }
894
895    /// Resolve conflicts that only differ by whitespace
896    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            // Only whitespace differences - prefer the version with better formatting
902            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    /// Resolve conflicts that only differ by line endings
916    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            // Only line ending differences - prefer Unix line endings
928            return Ok(Some(our_normalized));
929        }
930
931        Ok(None)
932    }
933
934    /// Resolve conflicts where both sides only add lines (no overlapping edits)
935    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        // Check if one side is a subset of the other (pure addition)
940        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        // Try to merge additions intelligently
948        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                // Only their lines left
955                merged_lines.extend_from_slice(&their_lines[their_idx..]);
956                break;
957            } else if their_idx >= their_lines.len() {
958                // Only our lines left
959                merged_lines.extend_from_slice(&our_lines[our_idx..]);
960                break;
961            } else if our_lines[our_idx] == their_lines[their_idx] {
962                // Same line - add once
963                merged_lines.push(our_lines[our_idx]);
964                our_idx += 1;
965                their_idx += 1;
966            } else {
967                // Different lines - this might be too complex
968                return Ok(None);
969            }
970        }
971
972        Ok(Some(merged_lines.join("\n")))
973    }
974
975    /// Resolve import/dependency conflicts by sorting and merging
976    fn resolve_import_conflict(
977        &self,
978        conflict: &ConflictRegion,
979        file_path: &str,
980    ) -> Result<Option<String>> {
981        // Only apply to likely import sections in common file types
982        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        // Check if all lines look like imports/uses
1000        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            // Merge and sort imports
1009            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    /// Check if a line looks like an import statement
1020    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; // Empty lines are OK in import sections
1025        }
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    /// Normalize whitespace for comparison
1051    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    /// Update a stack entry with new commit information
1061    /// NOTE: We keep the original branch name to preserve PR mapping, only update commit hash
1062    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        // Get the stack and update the entry
1075        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        // Find and update the entry
1081        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            // CRITICAL: Keep the original branch name to preserve PR mapping
1088            // Only update the commit hash to point to the new rebased commit
1089            entry.commit_hash = new_commit_hash.to_string();
1090
1091            // Note: Stack will be saved by the caller (StackManager) after rebase completes
1092
1093            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    /// Pull latest changes from remote
1106    fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1107        info!("Pulling latest changes for branch {}", branch);
1108
1109        // First try to fetch (this might fail if no remote exists)
1110        match self.git_repo.fetch() {
1111            Ok(_) => {
1112                debug!("Fetch successful");
1113                // Now try to pull the specific branch
1114                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                        // Don't fail the entire rebase for pull issues
1122                        Ok(())
1123                    }
1124                }
1125            }
1126            Err(e) => {
1127                warn!("Fetch failed: {}", e);
1128                // Don't fail if there's no remote configured
1129                Ok(())
1130            }
1131        }
1132    }
1133
1134    /// Check if rebase is in progress
1135    pub fn is_rebase_in_progress(&self) -> bool {
1136        // Check for git rebase state files
1137        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    /// Abort an in-progress rebase
1144    pub fn abort_rebase(&self) -> Result<()> {
1145        info!("Aborting rebase operation");
1146
1147        let git_dir = self.git_repo.path().join(".git");
1148
1149        // Clean up rebase state files
1150        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    /// Continue an in-progress rebase after conflict resolution
1179    pub fn continue_rebase(&self) -> Result<()> {
1180        info!("Continuing rebase operation");
1181
1182        // Check if there are still conflicts
1183        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        // Stage resolved files
1190        self.git_repo.stage_conflict_resolved_files()?;
1191
1192        info!("Rebase continued successfully");
1193        Ok(())
1194    }
1195}
1196
1197impl RebaseResult {
1198    /// Get a summary of the rebase operation
1199    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    /// Check if any conflicts occurred
1211    pub fn has_conflicts(&self) -> bool {
1212        !self.conflicts.is_empty()
1213    }
1214
1215    /// Get the number of successful operations
1216    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        // Initialize git repository
1234        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        // Create initial commit
1251        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        // Create a temporary git repo
1317        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        // Create initial commit
1339        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        // Create a test branch
1354        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        // First cleanup should work
1360        guard.cleanup(&git_repo);
1361        assert!(guard.cleaned);
1362
1363        // Second cleanup should be a no-op (shouldn't panic)
1364        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        // Test Swift import detection
1393        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        // Test Kotlin import detection
1398        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        // Test C# import detection
1403        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        // Test empty lines are allowed in import sections
1409        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}