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