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;
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    /// Original working branch to restore after rebase (if different from base)
65    /// This is critical to prevent updating the base branch when sync checks out to it
66    pub original_working_branch: Option<String>,
67}
68
69/// Result of a rebase operation
70#[derive(Debug)]
71pub struct RebaseResult {
72    /// Whether the rebase was successful
73    pub success: bool,
74    /// Old branch to new branch mapping
75    pub branch_mapping: HashMap<String, String>,
76    /// Commits that had conflicts
77    pub conflicts: Vec<String>,
78    /// New commit hashes
79    pub new_commits: Vec<String>,
80    /// Error message if rebase failed
81    pub error: Option<String>,
82    /// Summary of changes made
83    pub summary: String,
84}
85
86/// RAII guard to ensure temporary branches are cleaned up even on error/panic
87///
88/// This stores branch names and provides a cleanup method that can be called
89/// with a GitRepository reference. The Drop trait ensures cleanup happens
90/// even if the rebase function panics or returns early with an error.
91#[allow(dead_code)]
92struct TempBranchCleanupGuard {
93    branches: Vec<String>,
94    cleaned: bool,
95}
96
97#[allow(dead_code)]
98impl TempBranchCleanupGuard {
99    fn new() -> Self {
100        Self {
101            branches: Vec::new(),
102            cleaned: false,
103        }
104    }
105
106    fn add_branch(&mut self, branch: String) {
107        self.branches.push(branch);
108    }
109
110    /// Perform cleanup with provided git repository
111    fn cleanup(&mut self, git_repo: &GitRepository) {
112        if self.cleaned || self.branches.is_empty() {
113            return;
114        }
115
116        tracing::debug!("Cleaning up {} temporary branches", self.branches.len());
117        for branch in &self.branches {
118            if let Err(e) = git_repo.delete_branch_unsafe(branch) {
119                tracing::debug!("Failed to delete temp branch {}: {}", branch, e);
120                // Continue with cleanup even if one fails
121            }
122        }
123        self.cleaned = true;
124    }
125}
126
127impl Drop for TempBranchCleanupGuard {
128    fn drop(&mut self) {
129        if !self.cleaned && !self.branches.is_empty() {
130            // This path is only hit on panic or unexpected early return
131            // We can't access git_repo here, so just log the branches that need manual cleanup
132            tracing::warn!(
133                "{} temporary branches were not cleaned up: {}",
134                self.branches.len(),
135                self.branches.join(", ")
136            );
137            tracing::warn!("Run 'ca cleanup' to remove orphaned temporary branches");
138        }
139    }
140}
141
142/// Manages rebase operations for stacks
143pub struct RebaseManager {
144    stack_manager: StackManager,
145    git_repo: GitRepository,
146    options: RebaseOptions,
147    conflict_analyzer: ConflictAnalyzer,
148}
149
150impl Default for RebaseOptions {
151    fn default() -> Self {
152        Self {
153            strategy: RebaseStrategy::ForcePush,
154            interactive: false,
155            target_base: None,
156            preserve_merges: true,
157            auto_resolve: true,
158            max_retries: 3,
159            skip_pull: None,
160            original_working_branch: None,
161        }
162    }
163}
164
165impl RebaseManager {
166    /// Create a new rebase manager
167    pub fn new(
168        stack_manager: StackManager,
169        git_repo: GitRepository,
170        options: RebaseOptions,
171    ) -> Self {
172        Self {
173            stack_manager,
174            git_repo,
175            options,
176            conflict_analyzer: ConflictAnalyzer::new(),
177        }
178    }
179
180    /// Consume the rebase manager and return the updated stack manager
181    pub fn into_stack_manager(self) -> StackManager {
182        self.stack_manager
183    }
184
185    /// Rebase an entire stack onto a new base
186    pub fn rebase_stack(&mut self, stack_id: &Uuid) -> Result<RebaseResult> {
187        debug!("Starting rebase for stack {}", stack_id);
188
189        let stack = self
190            .stack_manager
191            .get_stack(stack_id)
192            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?
193            .clone();
194
195        match self.options.strategy {
196            RebaseStrategy::ForcePush => self.rebase_with_force_push(&stack),
197            RebaseStrategy::Interactive => self.rebase_interactive(&stack),
198        }
199    }
200
201    /// Rebase using force-push strategy (industry standard for stacked diffs)
202    /// This updates local branches in-place, then force-pushes ONLY branches with existing PRs
203    /// to preserve PR history - the approach used by Graphite, Phabricator, spr, etc.
204    fn rebase_with_force_push(&mut self, stack: &Stack) -> Result<RebaseResult> {
205        use crate::cli::output::Output;
206
207        // Check if there's an in-progress cherry-pick from a previous failed sync
208        if self.has_in_progress_cherry_pick()? {
209            return self.handle_in_progress_cherry_pick(stack);
210        }
211
212        Output::section(format!("Rebasing stack: {}", stack.name));
213
214        let mut result = RebaseResult {
215            success: true,
216            branch_mapping: HashMap::new(),
217            conflicts: Vec::new(),
218            new_commits: Vec::new(),
219            error: None,
220            summary: String::new(),
221        };
222
223        let target_base = self
224            .options
225            .target_base
226            .as_ref()
227            .unwrap_or(&stack.base_branch)
228            .clone(); // Clone to avoid borrow issues
229
230        // Use the original working branch passed in options, or detect current branch
231        // CRITICAL: sync_stack passes the original branch before it checks out to base
232        // This prevents us from thinking we started on the base branch
233        let original_branch = self
234            .options
235            .original_working_branch
236            .clone()
237            .or_else(|| self.git_repo.get_current_branch().ok());
238        
239        // Store original branch for cleanup on early error returns
240        let original_branch_for_cleanup = original_branch.clone();
241
242        // SAFETY: Warn if we're starting on the base branch (unusual but valid)
243        // This can happen if user manually runs rebase while on base branch
244        if let Some(ref orig) = original_branch {
245            if orig == &target_base {
246                debug!(
247                    "Original working branch is base branch '{}' - will skip working branch update",
248                    orig
249                );
250            }
251        }
252
253        // Note: Caller (sync_stack) has already checked out base branch when skip_pull=true
254        // Only pull if not already done by caller (like sync command)
255        if !self.options.skip_pull.unwrap_or(false) {
256            if let Err(e) = self.pull_latest_changes(&target_base) {
257                Output::warning(format!("Could not pull latest changes: {}", e));
258            }
259        }
260
261        // Reset working directory to clean state before rebase
262        if let Err(e) = self.git_repo.reset_to_head() {
263            Output::warning(format!("Could not reset working directory: {}", e));
264        }
265
266        let mut current_base = target_base.clone();
267        let entry_count = stack.entries.len();
268        let mut temp_branches: Vec<String> = Vec::new(); // Track temp branches for cleanup
269        let mut branches_to_push: Vec<(String, String)> = Vec::new(); // (branch_name, pr_number)
270
271        // Handle empty stack early
272        if entry_count == 0 {
273            println!(); // Spacing
274            Output::info("Stack has no entries yet");
275            Output::tip("Use 'ca push' to add commits to this stack");
276
277            result.summary = "Stack is empty".to_string();
278
279            // Print success with summary (consistent with non-empty path)
280            println!(); // Spacing
281            Output::success(&result.summary);
282
283            // Save metadata and return
284            self.stack_manager.save_to_disk()?;
285            return Ok(result);
286        }
287
288        println!(); // Spacing before tree
289        let plural = if entry_count == 1 { "entry" } else { "entries" };
290        println!("Rebasing {} {}...", entry_count, plural);
291
292        // Phase 1: Rebase all entries locally (libgit2 only - no CLI commands)
293        for (index, entry) in stack.entries.iter().enumerate() {
294            let original_branch = &entry.branch;
295
296            // Check if this entry is already correctly based on the current base
297            // If so, skip rebasing it (avoids creating duplicate commits)
298            if self
299                .git_repo
300                .is_commit_based_on(&entry.commit_hash, &current_base)
301                .unwrap_or(false)
302            {
303                tracing::debug!(
304                    "Entry '{}' is already correctly based on '{}', skipping rebase",
305                    original_branch,
306                    current_base
307                );
308
309                // Track which branches need to be pushed (only those with PRs)
310                let tree_char = if index + 1 == entry_count {
311                    "└─"
312                } else {
313                    "├─"
314                };
315
316                if let Some(pr_num) = &entry.pull_request_id {
317                    println!("   {} {} (PR #{})", tree_char, original_branch, pr_num);
318                    branches_to_push.push((original_branch.clone(), pr_num.clone()));
319                } else {
320                    println!("   {} {} (not submitted)", tree_char, original_branch);
321                }
322
323                result
324                    .branch_mapping
325                    .insert(original_branch.clone(), original_branch.clone());
326
327                // This branch becomes the base for the next entry
328                current_base = original_branch.clone();
329                continue;
330            }
331
332            // Create a temporary branch from the current base
333            // This avoids committing directly to protected branches like develop/main
334            let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
335            temp_branches.push(temp_branch.clone()); // Track for cleanup
336            
337            // Create and checkout temp branch - restore original branch on error
338            if let Err(e) = self.git_repo.create_branch(&temp_branch, Some(&current_base)) {
339                // Restore original branch before returning error
340                if let Some(ref orig) = original_branch_for_cleanup {
341                    let _ = self.git_repo.checkout_branch_unsafe(orig);
342                }
343                return Err(e);
344            }
345            
346            if let Err(e) = self.git_repo.checkout_branch_silent(&temp_branch) {
347                // Restore original branch before returning error
348                if let Some(ref orig) = original_branch_for_cleanup {
349                    let _ = self.git_repo.checkout_branch_unsafe(orig);
350                }
351                return Err(e);
352            }
353
354            // Cherry-pick the commit onto the temp branch (NOT the protected base!)
355            match self.cherry_pick_commit(&entry.commit_hash) {
356                Ok(new_commit_hash) => {
357                    result.new_commits.push(new_commit_hash.clone());
358
359                    // Get the commit that's now at HEAD (the cherry-picked commit)
360                    let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
361
362                    // Update the original branch to point to this rebased commit
363                    // This is LOCAL ONLY - moves refs/heads/<branch> to the commit on temp branch
364                    self.git_repo
365                        .update_branch_to_commit(original_branch, &rebased_commit_id)?;
366
367                    // Track which branches need to be pushed (only those with PRs)
368                    let tree_char = if index + 1 == entry_count {
369                        "└─"
370                    } else {
371                        "├─"
372                    };
373
374                    if let Some(pr_num) = &entry.pull_request_id {
375                        println!("   {} {} (PR #{})", tree_char, original_branch, pr_num);
376                        branches_to_push.push((original_branch.clone(), pr_num.clone()));
377                    } else {
378                        println!("   {} {} (not submitted)", tree_char, original_branch);
379                    }
380
381                    result
382                        .branch_mapping
383                        .insert(original_branch.clone(), original_branch.clone());
384
385                    // Update stack entry with new commit hash
386                    self.update_stack_entry(
387                        stack.id,
388                        &entry.id,
389                        original_branch,
390                        &rebased_commit_id,
391                    )?;
392
393                    // This branch becomes the base for the next entry
394                    current_base = original_branch.clone();
395                }
396                Err(e) => {
397                    result.conflicts.push(entry.commit_hash.clone());
398
399                    if !self.options.auto_resolve {
400                        println!(); // Spacing before error
401                        Output::error(e.to_string());
402                        result.success = false;
403                        result.error = Some(format!(
404                            "Conflict in {}: {}\n\n\
405                            MANUAL CONFLICT RESOLUTION REQUIRED\n\
406                            =====================================\n\n\
407                            Step 1: Analyze conflicts\n\
408                            → Run: ca conflicts\n\
409                            → This shows which conflicts are in which files\n\n\
410                            Step 2: Resolve conflicts in your editor\n\
411                            → Open conflicted files and edit them\n\
412                            → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
413                            → Keep the code you want\n\
414                            → Save the files\n\n\
415                            Step 3: Mark conflicts as resolved\n\
416                            → Run: git add <resolved-files>\n\
417                            → Or: git add -A (to stage all resolved files)\n\n\
418                            Step 4: Complete the sync\n\
419                            → Run: ca sync\n\
420                            → Cascade will detect resolved conflicts and continue\n\n\
421                            Alternative: Abort and start over\n\
422                            → Run: git cherry-pick --abort\n\
423                            → Then: ca sync (starts fresh)\n\n\
424                            TIP: Enable auto-resolution for simple conflicts:\n\
425                            → Run: ca sync --auto-resolve\n\
426                            → Only complex conflicts will require manual resolution",
427                            entry.commit_hash, e
428                        ));
429                        break;
430                    }
431
432                    // Try to resolve automatically
433                    match self.auto_resolve_conflicts(&entry.commit_hash) {
434                        Ok(fully_resolved) => {
435                            if !fully_resolved {
436                                result.success = false;
437                                result.error = Some(format!(
438                                    "Conflicts in commit {}\n\n\
439                                    To resolve:\n\
440                                    1. Fix conflicts in your editor\n\
441                                    2. Run: ca sync --continue\n\n\
442                                    Or abort:\n\
443                                    → Run: git cherry-pick --abort",
444                                    &entry.commit_hash[..8]
445                                ));
446                                break;
447                            }
448
449                            // Commit the resolved changes
450                            let commit_message =
451                                format!("Auto-resolved conflicts in {}", &entry.commit_hash[..8]);
452
453                            // CRITICAL: Check if there are actually changes to commit
454                            debug!("Checking staged files before commit");
455                            let staged_files = self.git_repo.get_staged_files()?;
456
457                            if staged_files.is_empty() {
458                                // NO FILES STAGED! This means auto-resolve didn't actually stage anything
459                                // This is the bug - cherry-pick failed, but has_conflicts() returned false
460                                // so auto-resolve exited early without staging anything
461                                result.success = false;
462                                result.error = Some(format!(
463                                    "CRITICAL BUG DETECTED: Cherry-pick failed but no files were staged!\n\n\
464                                    This indicates a Git state issue after cherry-pick failure.\n\n\
465                                    RECOVERY STEPS:\n\
466                                    ================\n\n\
467                                    Step 1: Check Git status\n\
468                                    → Run: git status\n\
469                                    → Check if there are any changes in working directory\n\n\
470                                    Step 2: Check for conflicts manually\n\
471                                    → Run: git diff\n\
472                                    → Look for conflict markers (<<<<<<, ======, >>>>>>)\n\n\
473                                    Step 3: Abort the cherry-pick\n\
474                                    → Run: git cherry-pick --abort\n\n\
475                                    Step 4: Report this bug\n\
476                                    → This is a known issue we're investigating\n\
477                                    → Cherry-pick failed for commit {}\n\
478                                    → But Git reported no conflicts and no staged files\n\n\
479                                    Step 5: Try manual resolution\n\
480                                    → Run: ca sync --no-auto-resolve\n\
481                                    → Manually resolve conflicts as they appear",
482                                    &entry.commit_hash[..8]
483                                ));
484                                tracing::error!("CRITICAL - No files staged after auto-resolve!");
485                                break;
486                            }
487
488                            debug!("{} files staged", staged_files.len());
489
490                            match self.git_repo.commit(&commit_message) {
491                                Ok(new_commit_id) => {
492                                    debug!(
493                                        "Created commit {} with message '{}'",
494                                        &new_commit_id[..8],
495                                        commit_message
496                                    );
497
498                                    Output::success("Auto-resolved conflicts");
499                                    result.new_commits.push(new_commit_id.clone());
500                                    let rebased_commit_id = new_commit_id;
501
502                                    // Update the original branch to point to this rebased commit
503                                    self.git_repo.update_branch_to_commit(
504                                        original_branch,
505                                        &rebased_commit_id,
506                                    )?;
507
508                                    // Track which branches need to be pushed (only those with PRs)
509                                    let tree_char = if index + 1 == entry_count {
510                                        "└─"
511                                    } else {
512                                        "├─"
513                                    };
514
515                                    if let Some(pr_num) = &entry.pull_request_id {
516                                        println!(
517                                            "   {} {} (PR #{})",
518                                            tree_char, original_branch, pr_num
519                                        );
520                                        branches_to_push
521                                            .push((original_branch.clone(), pr_num.clone()));
522                                    } else {
523                                        println!(
524                                            "   {} {} (not submitted)",
525                                            tree_char, original_branch
526                                        );
527                                    }
528
529                                    result
530                                        .branch_mapping
531                                        .insert(original_branch.clone(), original_branch.clone());
532
533                                    // Update stack entry with new commit hash
534                                    self.update_stack_entry(
535                                        stack.id,
536                                        &entry.id,
537                                        original_branch,
538                                        &rebased_commit_id,
539                                    )?;
540
541                                    // This branch becomes the base for the next entry
542                                    current_base = original_branch.clone();
543                                }
544                                Err(commit_err) => {
545                                    result.success = false;
546                                    result.error = Some(format!(
547                                        "Could not commit auto-resolved conflicts: {}\n\n\
548                                        This usually means:\n\
549                                        - Git index is locked (another process accessing repo)\n\
550                                        - File permissions issue\n\
551                                        - Disk space issue\n\n\
552                                        Recovery:\n\
553                                        1. Check if another Git operation is running\n\
554                                        2. Run 'rm -f .git/index.lock' if stale lock exists\n\
555                                        3. Run 'git status' to check repo state\n\
556                                        4. Retry 'ca sync' after fixing the issue",
557                                        commit_err
558                                    ));
559                                    break;
560                                }
561                            }
562                        }
563                        Err(resolve_err) => {
564                            result.success = false;
565                            result.error = Some(format!(
566                                "Could not resolve conflicts: {}\n\n\
567                                Recovery:\n\
568                                1. Check repo state: 'git status'\n\
569                                2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
570                                3. Remove any lock files: 'rm -f .git/index.lock'\n\
571                                4. Retry 'ca sync'",
572                                resolve_err
573                            ));
574                            break;
575                        }
576                    }
577                }
578            }
579        }
580
581        // Cleanup temp branches before returning to original branch
582        // Must checkout away from temp branches first
583        if !temp_branches.is_empty() {
584            // Force checkout to base branch to allow temp branch deletion
585            // Use unsafe checkout to bypass safety checks since we know this is cleanup
586            if let Err(e) = self.git_repo.checkout_branch_unsafe(&target_base) {
587                debug!("Could not checkout base for cleanup: {}", e);
588                // If we can't checkout, we can't delete temp branches
589                // This is non-critical - temp branches will be cleaned up eventually
590            } else {
591                // Successfully checked out - now delete temp branches
592                for temp_branch in &temp_branches {
593                    if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
594                        debug!("Could not delete temp branch {}: {}", temp_branch, e);
595                    }
596                }
597            }
598        }
599
600        // Phase 2: Push all branches with PRs to remote (git CLI - after all libgit2 operations)
601        // This batch approach prevents index lock conflicts between libgit2 and git CLI
602        let pushed_count = branches_to_push.len();
603        let skipped_count = entry_count - pushed_count;
604
605        if !branches_to_push.is_empty() {
606            // Push branches silently - user will see the summary
607
608            for (branch_name, _pr_num) in &branches_to_push {
609                match self.git_repo.force_push_single_branch_auto(branch_name) {
610                    Ok(_) => {
611                        debug!("Pushed {} successfully", branch_name);
612                    }
613                    Err(e) => {
614                        Output::warning(format!("Could not push '{}': {}", branch_name, e));
615                        // Continue pushing other branches even if one fails
616                    }
617                }
618            }
619        }
620
621        // Update working branch to point to the top of the rebased stack
622        // This ensures subsequent `ca push` doesn't re-add old commits
623        if let Some(ref orig_branch) = original_branch {
624            // CRITICAL: Never update the base branch! Only update working branches
625            if orig_branch != &target_base {
626                // Get the last entry's branch (top of stack)
627                if let Some(last_entry) = stack.entries.last() {
628                    let top_branch = &last_entry.branch;
629
630                    // SAFETY CHECK: Detect if working branch has commits beyond the last stack entry
631                    // If it does, we need to preserve them - don't force-update the working branch
632                    if let (Ok(working_head), Ok(top_commit)) = (
633                        self.git_repo.get_branch_head(orig_branch),
634                        self.git_repo.get_branch_head(top_branch),
635                    ) {
636                        // Check if working branch is ahead of top stack entry
637                        if working_head != top_commit {
638                            // Get commits between top of stack and working branch head
639                            if let Ok(commits) = self
640                                .git_repo
641                                .get_commits_between(&top_commit, &working_head)
642                            {
643                                if !commits.is_empty() {
644                                    // Working branch has extra commits!
645                                    Output::error(format!(
646                                        "Cannot sync: Working branch '{}' has {} commit(s) not in the stack",
647                                        orig_branch,
648                                        commits.len()
649                                    ));
650                                    println!();
651                                    Output::sub_item("These commits would be lost if we proceed:");
652                                    for (i, commit) in commits.iter().take(5).enumerate() {
653                                        let message = commit.summary().unwrap_or("(no message)");
654                                        Output::sub_item(format!(
655                                            "  {}. {} - {}",
656                                            i + 1,
657                                            &commit.id().to_string()[..8],
658                                            message
659                                        ));
660                                    }
661                                    if commits.len() > 5 {
662                                        Output::sub_item(format!(
663                                            "  ... and {} more",
664                                            commits.len() - 5
665                                        ));
666                                    }
667                                    println!();
668                                    Output::tip("Add these commits to the stack first:");
669                                    Output::bullet("Run: ca stack push");
670                                    Output::bullet("Then run: ca sync");
671                                    println!();
672
673                                    return Err(CascadeError::validation(
674                                        format!(
675                                            "Working branch '{}' has {} untracked commit(s). Add them to the stack with 'ca stack push' before syncing.",
676                                            orig_branch, commits.len()
677                                        )
678                                    ));
679                                }
680                            }
681                        }
682
683                        // Safe to update - working branch matches top of stack or is behind
684                        debug!(
685                            "Updating working branch '{}' to match top of stack ({})",
686                            orig_branch,
687                            &top_commit[..8]
688                        );
689
690                        if let Err(e) = self
691                            .git_repo
692                            .update_branch_to_commit(orig_branch, &top_commit)
693                        {
694                            Output::warning(format!(
695                                "Could not update working branch '{}' to top of stack: {}",
696                                orig_branch, e
697                            ));
698                        }
699                    }
700                }
701
702                // Return to original working branch
703                // Use unsafe checkout to force it (we're in cleanup phase, no uncommitted changes)
704                if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
705                    debug!(
706                        "Could not return to original branch '{}': {}",
707                        orig_branch, e
708                    );
709                    // Non-critical: User is left on base branch instead of working branch
710                }
711            } else {
712                // User was on base branch - this is unusual but valid
713                // Don't update base branch, just checkout back to it
714                debug!(
715                    "Skipping working branch update - user was on base branch '{}'",
716                    orig_branch
717                );
718                if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
719                    debug!("Could not return to base branch '{}': {}", orig_branch, e);
720                }
721            }
722        }
723
724        // Build summary message
725        result.summary = if pushed_count > 0 {
726            let pr_plural = if pushed_count == 1 { "" } else { "s" };
727            let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
728
729            if skipped_count > 0 {
730                format!(
731                    "{} {} rebased ({} PR{} updated, {} not yet submitted)",
732                    entry_count, entry_plural, pushed_count, pr_plural, skipped_count
733                )
734            } else {
735                format!(
736                    "{} {} rebased ({} PR{} updated)",
737                    entry_count, entry_plural, pushed_count, pr_plural
738                )
739            }
740        } else {
741            let plural = if entry_count == 1 { "entry" } else { "entries" };
742            format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
743        };
744
745        // Display result with proper formatting
746        println!(); // Spacing after tree
747        if result.success {
748            Output::success(&result.summary);
749        } else {
750            // Display error with proper icon
751            let error_msg = result
752                .error
753                .as_deref()
754                .unwrap_or("Rebase failed for unknown reason");
755            Output::error(error_msg);
756        }
757
758        // Save the updated stack metadata to disk
759        self.stack_manager.save_to_disk()?;
760
761        // CRITICAL: Return error if rebase failed
762        // Don't return Ok(result) with result.success = false - that's confusing!
763        if !result.success {
764            // Before returning error, try to restore original branch
765            if let Some(ref orig_branch) = original_branch {
766                if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
767                    debug!("Could not return to original branch '{}' after error: {}", orig_branch, e);
768                }
769            }
770            
771            // Include the detailed error message (which contains conflict info)
772            let detailed_error = result.error.as_deref().unwrap_or("Rebase failed");
773            return Err(CascadeError::Branch(detailed_error.to_string()));
774        }
775
776        Ok(result)
777    }
778
779    /// Interactive rebase with user input
780    fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
781        tracing::debug!("Starting interactive rebase for stack '{}'", stack.name);
782
783        let mut result = RebaseResult {
784            success: true,
785            branch_mapping: HashMap::new(),
786            conflicts: Vec::new(),
787            new_commits: Vec::new(),
788            error: None,
789            summary: String::new(),
790        };
791
792        println!("Interactive Rebase for Stack: {}", stack.name);
793        println!("   Base branch: {}", stack.base_branch);
794        println!("   Entries: {}", stack.entries.len());
795
796        if self.options.interactive {
797            println!("\nChoose action for each commit:");
798            println!("  (p)ick   - apply the commit");
799            println!("  (s)kip   - skip this commit");
800            println!("  (e)dit   - edit the commit message");
801            println!("  (q)uit   - abort the rebase");
802        }
803
804        // For now, automatically pick all commits
805        // In a real implementation, this would prompt the user
806        for entry in &stack.entries {
807            println!(
808                "  {} {} - {}",
809                entry.short_hash(),
810                entry.branch,
811                entry.short_message(50)
812            );
813
814            // Auto-pick for demo purposes
815            match self.cherry_pick_commit(&entry.commit_hash) {
816                Ok(new_commit) => result.new_commits.push(new_commit),
817                Err(_) => result.conflicts.push(entry.commit_hash.clone()),
818            }
819        }
820
821        result.summary = format!(
822            "Interactive rebase processed {} commits",
823            stack.entries.len()
824        );
825        Ok(result)
826    }
827
828    /// Cherry-pick a commit onto the current branch
829    fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
830        // Use the real cherry-pick implementation from GitRepository
831        let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
832
833        // Check for any leftover staged changes after successful cherry-pick
834        if let Ok(staged_files) = self.git_repo.get_staged_files() {
835            if !staged_files.is_empty() {
836                // Commit any leftover staged changes silently
837                let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
838                let _ = self.git_repo.commit_staged_changes(&cleanup_message);
839            }
840        }
841
842        Ok(new_commit_hash)
843    }
844
845    /// Attempt to automatically resolve conflicts
846    fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
847        debug!("Starting auto-resolve for commit {}", commit_hash);
848
849        // Check if there are actually conflicts
850        let has_conflicts = self.git_repo.has_conflicts()?;
851        debug!("has_conflicts() = {}", has_conflicts);
852
853        // Check if cherry-pick is in progress
854        let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
855        let cherry_pick_in_progress = cherry_pick_head.exists();
856
857        if !has_conflicts {
858            debug!("No conflicts detected by Git index");
859
860            // If cherry-pick is in progress but no conflicts detected, something is wrong
861            if cherry_pick_in_progress {
862                tracing::debug!(
863                    "CHERRY_PICK_HEAD exists but no conflicts in index - aborting cherry-pick"
864                );
865
866                // Abort the cherry-pick to clean up
867                let _ = std::process::Command::new("git")
868                    .args(["cherry-pick", "--abort"])
869                    .current_dir(self.git_repo.path())
870                    .output();
871
872                return Err(CascadeError::Branch(format!(
873                    "Cherry-pick failed for {} but Git index shows no conflicts. \
874                     This usually means the cherry-pick was aborted or failed in an unexpected way. \
875                     Please try manual resolution.",
876                    &commit_hash[..8]
877                )));
878            }
879
880            return Ok(true);
881        }
882
883        let conflicted_files = self.git_repo.get_conflicted_files()?;
884
885        if conflicted_files.is_empty() {
886            debug!("Conflicted files list is empty");
887            return Ok(true);
888        }
889
890        debug!(
891            "Found conflicts in {} files: {:?}",
892            conflicted_files.len(),
893            conflicted_files
894        );
895
896        // Use the new conflict analyzer for detailed analysis
897        let analysis = self
898            .conflict_analyzer
899            .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
900
901        debug!(
902            "Conflict analysis: {} total conflicts, {} auto-resolvable",
903            analysis.total_conflicts, analysis.auto_resolvable_count
904        );
905
906        // Display recommendations
907        for recommendation in &analysis.recommendations {
908            debug!("{}", recommendation);
909        }
910
911        let mut resolved_count = 0;
912        let mut resolved_files = Vec::new(); // Track which files were actually resolved
913        let mut failed_files = Vec::new();
914
915        for file_analysis in &analysis.files {
916            debug!(
917                "Processing file: {} (auto_resolvable: {}, conflicts: {})",
918                file_analysis.file_path,
919                file_analysis.auto_resolvable,
920                file_analysis.conflicts.len()
921            );
922
923            if file_analysis.auto_resolvable {
924                match self.resolve_file_conflicts_enhanced(
925                    &file_analysis.file_path,
926                    &file_analysis.conflicts,
927                ) {
928                    Ok(ConflictResolution::Resolved) => {
929                        resolved_count += 1;
930                        resolved_files.push(file_analysis.file_path.clone());
931                        debug!("Successfully resolved {}", file_analysis.file_path);
932                    }
933                    Ok(ConflictResolution::TooComplex) => {
934                        debug!(
935                            "{} too complex for auto-resolution",
936                            file_analysis.file_path
937                        );
938                        failed_files.push(file_analysis.file_path.clone());
939                    }
940                    Err(e) => {
941                        debug!("Failed to resolve {}: {}", file_analysis.file_path, e);
942                        failed_files.push(file_analysis.file_path.clone());
943                    }
944                }
945            } else {
946                failed_files.push(file_analysis.file_path.clone());
947                debug!(
948                    "{} requires manual resolution ({} conflicts)",
949                    file_analysis.file_path,
950                    file_analysis.conflicts.len()
951                );
952            }
953        }
954
955        if resolved_count > 0 {
956            debug!(
957                "Resolved {}/{} files",
958                resolved_count,
959                conflicted_files.len()
960            );
961            debug!("Resolved files: {:?}", resolved_files);
962
963            // CRITICAL: Only stage files that were successfully resolved
964            // This prevents staging files that still have conflict markers
965            let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
966            debug!("Staging {} files", file_paths.len());
967            self.git_repo.stage_files(&file_paths)?;
968            debug!("Files staged successfully");
969        } else {
970            debug!("No files were resolved (resolved_count = 0)");
971        }
972
973        // Return true only if ALL conflicts were resolved
974        let all_resolved = failed_files.is_empty();
975
976        debug!(
977            "all_resolved = {}, failed_files = {:?}",
978            all_resolved, failed_files
979        );
980
981        if !all_resolved {
982            debug!("{} files still need manual resolution", failed_files.len());
983        }
984
985        debug!("Returning all_resolved = {}", all_resolved);
986        Ok(all_resolved)
987    }
988
989    /// Resolve conflicts using enhanced analysis
990    fn resolve_file_conflicts_enhanced(
991        &self,
992        file_path: &str,
993        conflicts: &[crate::git::ConflictRegion],
994    ) -> Result<ConflictResolution> {
995        let repo_path = self.git_repo.path();
996        let full_path = repo_path.join(file_path);
997
998        // Read the file content with conflict markers
999        let mut content = std::fs::read_to_string(&full_path)
1000            .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
1001
1002        if conflicts.is_empty() {
1003            return Ok(ConflictResolution::Resolved);
1004        }
1005
1006        tracing::debug!(
1007            "Resolving {} conflicts in {} using enhanced analysis",
1008            conflicts.len(),
1009            file_path
1010        );
1011
1012        let mut any_resolved = false;
1013
1014        // Process conflicts in reverse order to maintain string indices
1015        for conflict in conflicts.iter().rev() {
1016            match self.resolve_single_conflict_enhanced(conflict) {
1017                Ok(Some(resolution)) => {
1018                    // Replace the conflict region with the resolved content
1019                    let before = &content[..conflict.start_pos];
1020                    let after = &content[conflict.end_pos..];
1021                    content = format!("{before}{resolution}{after}");
1022                    any_resolved = true;
1023                    debug!(
1024                        "✅ Resolved {} conflict at lines {}-{} in {}",
1025                        format!("{:?}", conflict.conflict_type).to_lowercase(),
1026                        conflict.start_line,
1027                        conflict.end_line,
1028                        file_path
1029                    );
1030                }
1031                Ok(None) => {
1032                    debug!(
1033                        "⚠️  {} conflict at lines {}-{} in {} requires manual resolution",
1034                        format!("{:?}", conflict.conflict_type).to_lowercase(),
1035                        conflict.start_line,
1036                        conflict.end_line,
1037                        file_path
1038                    );
1039                    return Ok(ConflictResolution::TooComplex);
1040                }
1041                Err(e) => {
1042                    debug!("❌ Failed to resolve conflict in {}: {}", file_path, e);
1043                    return Ok(ConflictResolution::TooComplex);
1044                }
1045            }
1046        }
1047
1048        if any_resolved {
1049            // Check if we resolved ALL conflicts in this file
1050            let remaining_conflicts = self.parse_conflict_markers(&content)?;
1051
1052            if remaining_conflicts.is_empty() {
1053                debug!(
1054                    "All conflicts resolved in {}, content length: {} bytes",
1055                    file_path,
1056                    content.len()
1057                );
1058
1059                // CRITICAL SAFETY CHECK: Don't write empty files!
1060                if content.trim().is_empty() {
1061                    tracing::warn!(
1062                        "SAFETY CHECK: Resolved content for {} is empty! Aborting auto-resolution.",
1063                        file_path
1064                    );
1065                    return Ok(ConflictResolution::TooComplex);
1066                }
1067
1068                // SAFETY: Create backup before writing resolved content
1069                let backup_path = full_path.with_extension("cascade-backup");
1070                if let Ok(original_content) = std::fs::read_to_string(&full_path) {
1071                    debug!(
1072                        "Backup for {} (original: {} bytes, resolved: {} bytes)",
1073                        file_path,
1074                        original_content.len(),
1075                        content.len()
1076                    );
1077                    let _ = std::fs::write(&backup_path, original_content);
1078                }
1079
1080                // All conflicts resolved - write the file back atomically
1081                crate::utils::atomic_file::write_string(&full_path, &content)?;
1082
1083                debug!("Wrote {} bytes to {}", content.len(), file_path);
1084                return Ok(ConflictResolution::Resolved);
1085            } else {
1086                tracing::debug!(
1087                    "Partially resolved conflicts in {} ({} remaining)",
1088                    file_path,
1089                    remaining_conflicts.len()
1090                );
1091            }
1092        }
1093
1094        Ok(ConflictResolution::TooComplex)
1095    }
1096
1097    /// Helper to count whitespace consistency (lower is better)
1098    #[allow(dead_code)]
1099    fn count_whitespace_consistency(content: &str) -> usize {
1100        let mut inconsistencies = 0;
1101        let lines: Vec<&str> = content.lines().collect();
1102
1103        for line in &lines {
1104            // Check for mixed tabs and spaces
1105            if line.contains('\t') && line.contains(' ') {
1106                inconsistencies += 1;
1107            }
1108        }
1109
1110        // Penalize for inconsistencies
1111        lines.len().saturating_sub(inconsistencies)
1112    }
1113
1114    /// Resolve a single conflict using enhanced analysis
1115    fn resolve_single_conflict_enhanced(
1116        &self,
1117        conflict: &crate::git::ConflictRegion,
1118    ) -> Result<Option<String>> {
1119        debug!(
1120            "Resolving {} conflict in {} (lines {}-{})",
1121            format!("{:?}", conflict.conflict_type).to_lowercase(),
1122            conflict.file_path,
1123            conflict.start_line,
1124            conflict.end_line
1125        );
1126
1127        use crate::git::ConflictType;
1128
1129        match conflict.conflict_type {
1130            ConflictType::Whitespace => {
1131                // SAFETY: Only resolve if the content is truly identical except for whitespace
1132                // Otherwise, it might be intentional formatting changes
1133                let our_normalized = conflict
1134                    .our_content
1135                    .split_whitespace()
1136                    .collect::<Vec<_>>()
1137                    .join(" ");
1138                let their_normalized = conflict
1139                    .their_content
1140                    .split_whitespace()
1141                    .collect::<Vec<_>>()
1142                    .join(" ");
1143
1144                if our_normalized == their_normalized {
1145                    // Content is identical - in cherry-pick context, ALWAYS prefer THEIRS
1146                    // CRITICAL: In cherry-pick, OURS=base branch, THEIRS=commit being applied
1147                    // We must keep the commit's changes (THEIRS), not the base (OURS)
1148                    // Otherwise we delete the user's code!
1149                    Ok(Some(conflict.their_content.clone()))
1150                } else {
1151                    // Content differs beyond whitespace - not safe to auto-resolve
1152                    debug!(
1153                        "Whitespace conflict has content differences - requires manual resolution"
1154                    );
1155                    Ok(None)
1156                }
1157            }
1158            ConflictType::LineEnding => {
1159                // Normalize to Unix line endings
1160                let normalized = conflict
1161                    .our_content
1162                    .replace("\r\n", "\n")
1163                    .replace('\r', "\n");
1164                Ok(Some(normalized))
1165            }
1166            ConflictType::PureAddition => {
1167                // CRITICAL: In cherry-pick, OURS=base, THEIRS=commit being applied
1168                // We must respect what the commit does (THEIRS), not what the base has (OURS)
1169
1170                if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1171                    // Base is empty, commit adds content → keep the addition
1172                    Ok(Some(conflict.their_content.clone()))
1173                } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1174                    // Base has content, commit removes it → keep it removed (empty)
1175                    Ok(Some(String::new()))
1176                } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1177                    // Both empty → keep empty
1178                    Ok(Some(String::new()))
1179                } else {
1180                    // Both sides have content - this could be:
1181                    // - Duplicate function definitions
1182                    // - Conflicting logic
1183                    // - Different implementations of same feature
1184                    // Too risky to auto-merge - require manual resolution
1185                    debug!(
1186                        "PureAddition conflict has content on both sides - requires manual resolution"
1187                    );
1188                    Ok(None)
1189                }
1190            }
1191            ConflictType::ImportMerge => {
1192                // SAFETY: Only merge simple single-line imports
1193                // Multi-line imports or complex cases require manual resolution
1194
1195                // Check if all imports are single-line and look like imports
1196                let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1197                let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1198
1199                // Verify all lines look like simple imports (heuristic check)
1200                let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1201                    let trimmed = line.trim();
1202                    trimmed.starts_with("import ")
1203                        || trimmed.starts_with("from ")
1204                        || trimmed.starts_with("use ")
1205                        || trimmed.starts_with("#include")
1206                        || trimmed.is_empty()
1207                });
1208
1209                if !all_simple {
1210                    debug!("ImportMerge contains non-import lines - requires manual resolution");
1211                    return Ok(None);
1212                }
1213
1214                // Merge and deduplicate imports
1215                let mut all_imports: Vec<&str> = our_lines
1216                    .into_iter()
1217                    .chain(their_lines)
1218                    .filter(|line| !line.trim().is_empty())
1219                    .collect();
1220                all_imports.sort();
1221                all_imports.dedup();
1222                Ok(Some(all_imports.join("\n")))
1223            }
1224            ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1225                // These require manual resolution
1226                Ok(None)
1227            }
1228        }
1229    }
1230
1231    /// Parse conflict markers from file content
1232    fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1233        let lines: Vec<&str> = content.lines().collect();
1234        let mut conflicts = Vec::new();
1235        let mut i = 0;
1236
1237        while i < lines.len() {
1238            if lines[i].starts_with("<<<<<<<") {
1239                // Found start of conflict
1240                let start_line = i + 1;
1241                let mut separator_line = None;
1242                let mut end_line = None;
1243
1244                // Find the separator and end
1245                for (j, line) in lines.iter().enumerate().skip(i + 1) {
1246                    if line.starts_with("=======") {
1247                        separator_line = Some(j + 1);
1248                    } else if line.starts_with(">>>>>>>") {
1249                        end_line = Some(j + 1);
1250                        break;
1251                    }
1252                }
1253
1254                if let (Some(sep), Some(end)) = (separator_line, end_line) {
1255                    // Calculate byte positions
1256                    let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1257                    let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1258
1259                    let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1260                    let their_content = lines[sep..(end - 1)].join("\n");
1261
1262                    conflicts.push(ConflictRegion {
1263                        start: start_pos,
1264                        end: end_pos,
1265                        start_line,
1266                        end_line: end,
1267                        our_content,
1268                        their_content,
1269                    });
1270
1271                    i = end;
1272                } else {
1273                    i += 1;
1274                }
1275            } else {
1276                i += 1;
1277            }
1278        }
1279
1280        Ok(conflicts)
1281    }
1282
1283    /// Update a stack entry with new commit information
1284    /// NOTE: We keep the original branch name to preserve PR mapping, only update commit hash
1285    fn update_stack_entry(
1286        &mut self,
1287        stack_id: Uuid,
1288        entry_id: &Uuid,
1289        _new_branch: &str,
1290        new_commit_hash: &str,
1291    ) -> Result<()> {
1292        debug!(
1293            "Updating entry {} in stack {} with new commit {}",
1294            entry_id, stack_id, new_commit_hash
1295        );
1296
1297        // Get the stack and update the entry
1298        let stack = self
1299            .stack_manager
1300            .get_stack_mut(&stack_id)
1301            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1302
1303        // Get entry info before mutation
1304        let entry_exists = stack.entries.iter().any(|e| e.id == *entry_id);
1305
1306        if entry_exists {
1307            let old_hash = stack
1308                .entries
1309                .iter()
1310                .find(|e| e.id == *entry_id)
1311                .map(|e| e.commit_hash.clone())
1312                .unwrap();
1313
1314            debug!(
1315                "Found entry {} - updating commit from '{}' to '{}' (keeping original branch)",
1316                entry_id, old_hash, new_commit_hash
1317            );
1318
1319            // CRITICAL: Keep the original branch name to preserve PR mapping
1320            // Only update the commit hash to point to the new rebased commit using safe wrapper
1321            stack
1322                .update_entry_commit_hash(entry_id, new_commit_hash.to_string())
1323                .map_err(CascadeError::config)?;
1324
1325            // Note: Stack will be saved by the caller (StackManager) after rebase completes
1326
1327            debug!(
1328                "Successfully updated entry {} in stack {}",
1329                entry_id, stack_id
1330            );
1331            Ok(())
1332        } else {
1333            Err(CascadeError::config(format!(
1334                "Entry {entry_id} not found in stack {stack_id}"
1335            )))
1336        }
1337    }
1338
1339    /// Pull latest changes from remote
1340    fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1341        tracing::debug!("Pulling latest changes for branch {}", branch);
1342
1343        // First try to fetch (this might fail if no remote exists)
1344        match self.git_repo.fetch() {
1345            Ok(_) => {
1346                debug!("Fetch successful");
1347                // Now try to pull the specific branch
1348                match self.git_repo.pull(branch) {
1349                    Ok(_) => {
1350                        tracing::debug!("Pull completed successfully for {}", branch);
1351                        Ok(())
1352                    }
1353                    Err(e) => {
1354                        tracing::debug!("Pull failed for {}: {}", branch, e);
1355                        // Don't fail the entire rebase for pull issues
1356                        Ok(())
1357                    }
1358                }
1359            }
1360            Err(e) => {
1361                tracing::debug!("Fetch failed: {}", e);
1362                // Don't fail if there's no remote configured
1363                Ok(())
1364            }
1365        }
1366    }
1367
1368    /// Check if rebase is in progress
1369    pub fn is_rebase_in_progress(&self) -> bool {
1370        // Check for git rebase state files
1371        let git_dir = self.git_repo.path().join(".git");
1372        git_dir.join("REBASE_HEAD").exists()
1373            || git_dir.join("rebase-merge").exists()
1374            || git_dir.join("rebase-apply").exists()
1375    }
1376
1377    /// Abort an in-progress rebase
1378    pub fn abort_rebase(&self) -> Result<()> {
1379        tracing::debug!("Aborting rebase operation");
1380
1381        let git_dir = self.git_repo.path().join(".git");
1382
1383        // Clean up rebase state files
1384        if git_dir.join("REBASE_HEAD").exists() {
1385            std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1386                CascadeError::Git(git2::Error::from_str(&format!(
1387                    "Failed to clean rebase state: {e}"
1388                )))
1389            })?;
1390        }
1391
1392        if git_dir.join("rebase-merge").exists() {
1393            std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1394                CascadeError::Git(git2::Error::from_str(&format!(
1395                    "Failed to clean rebase-merge: {e}"
1396                )))
1397            })?;
1398        }
1399
1400        if git_dir.join("rebase-apply").exists() {
1401            std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1402                CascadeError::Git(git2::Error::from_str(&format!(
1403                    "Failed to clean rebase-apply: {e}"
1404                )))
1405            })?;
1406        }
1407
1408        tracing::debug!("Rebase aborted successfully");
1409        Ok(())
1410    }
1411
1412    /// Continue an in-progress rebase after conflict resolution
1413    pub fn continue_rebase(&self) -> Result<()> {
1414        tracing::debug!("Continuing rebase operation");
1415
1416        // Check if there are still conflicts
1417        if self.git_repo.has_conflicts()? {
1418            return Err(CascadeError::branch(
1419                "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1420            ));
1421        }
1422
1423        // Stage resolved files
1424        self.git_repo.stage_conflict_resolved_files()?;
1425
1426        tracing::debug!("Rebase continued successfully");
1427        Ok(())
1428    }
1429
1430    /// Check if there's an in-progress cherry-pick operation
1431    fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1432        let git_dir = self.git_repo.path().join(".git");
1433        Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1434    }
1435
1436    /// Handle resuming an in-progress cherry-pick from a previous failed sync
1437    fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1438        use crate::cli::output::Output;
1439
1440        let git_dir = self.git_repo.path().join(".git");
1441
1442        Output::section("Resuming in-progress sync");
1443        println!();
1444        Output::info("Detected unfinished cherry-pick from previous sync");
1445        println!();
1446
1447        // Check if conflicts are resolved
1448        if self.git_repo.has_conflicts()? {
1449            let conflicted_files = self.git_repo.get_conflicted_files()?;
1450
1451            let result = RebaseResult {
1452                success: false,
1453                branch_mapping: HashMap::new(),
1454                conflicts: conflicted_files.clone(),
1455                new_commits: Vec::new(),
1456                error: Some(format!(
1457                    "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1458                    MANUAL CONFLICT RESOLUTION REQUIRED\n\
1459                    =====================================\n\n\
1460                    Conflicted files:\n{}\n\n\
1461                    Step 1: Analyze conflicts\n\
1462                    → Run: ca conflicts\n\
1463                    → Shows detailed conflict analysis\n\n\
1464                    Step 2: Resolve conflicts in your editor\n\
1465                    → Open conflicted files and edit them\n\
1466                    → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1467                    → Keep the code you want\n\
1468                    → Save the files\n\n\
1469                    Step 3: Mark conflicts as resolved\n\
1470                    → Run: git add <resolved-files>\n\
1471                    → Or: git add -A (to stage all resolved files)\n\n\
1472                    Step 4: Complete the sync\n\
1473                    → Run: ca sync\n\
1474                    → Cascade will continue from where it left off\n\n\
1475                    Alternative: Abort and start over\n\
1476                    → Run: git cherry-pick --abort\n\
1477                    → Then: ca sync (starts fresh)",
1478                    conflicted_files.len(),
1479                    conflicted_files
1480                        .iter()
1481                        .map(|f| format!("  - {}", f))
1482                        .collect::<Vec<_>>()
1483                        .join("\n")
1484                )),
1485                summary: "Sync paused - conflicts need resolution".to_string(),
1486            };
1487
1488            return Ok(result);
1489        }
1490
1491        // Conflicts are resolved - continue the cherry-pick
1492        Output::info("Conflicts resolved, continuing cherry-pick...");
1493
1494        // Stage all resolved files
1495        self.git_repo.stage_conflict_resolved_files()?;
1496
1497        // Complete the cherry-pick by committing
1498        let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1499        let commit_message = if cherry_pick_msg_file.exists() {
1500            std::fs::read_to_string(&cherry_pick_msg_file)
1501                .unwrap_or_else(|_| "Resolved conflicts".to_string())
1502        } else {
1503            "Resolved conflicts".to_string()
1504        };
1505
1506        match self.git_repo.commit(&commit_message) {
1507            Ok(_new_commit_id) => {
1508                Output::success("Cherry-pick completed");
1509
1510                // Clean up cherry-pick state
1511                if git_dir.join("CHERRY_PICK_HEAD").exists() {
1512                    let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1513                }
1514                if cherry_pick_msg_file.exists() {
1515                    let _ = std::fs::remove_file(&cherry_pick_msg_file);
1516                }
1517
1518                println!();
1519                Output::info("Continuing with rest of stack...");
1520                println!();
1521
1522                // Now continue with the rest of the rebase
1523                // We need to restart the full rebase since we don't track which entry we were on
1524                self.rebase_with_force_push(stack)
1525            }
1526            Err(e) => {
1527                let result = RebaseResult {
1528                    success: false,
1529                    branch_mapping: HashMap::new(),
1530                    conflicts: Vec::new(),
1531                    new_commits: Vec::new(),
1532                    error: Some(format!(
1533                        "Failed to complete cherry-pick: {}\n\n\
1534                        This usually means:\n\
1535                        - Git index is locked (another process accessing repo)\n\
1536                        - File permissions issue\n\
1537                        - Disk space issue\n\n\
1538                        Recovery:\n\
1539                        1. Check if another Git operation is running\n\
1540                        2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1541                        3. Run 'git status' to check repo state\n\
1542                        4. Retry 'ca sync' after fixing the issue\n\n\
1543                        Or abort and start fresh:\n\
1544                        → Run: git cherry-pick --abort\n\
1545                        → Then: ca sync",
1546                        e
1547                    )),
1548                    summary: "Failed to complete cherry-pick".to_string(),
1549                };
1550
1551                Ok(result)
1552            }
1553        }
1554    }
1555}
1556
1557impl RebaseResult {
1558    /// Get a summary of the rebase operation
1559    pub fn get_summary(&self) -> String {
1560        if self.success {
1561            format!("✅ {}", self.summary)
1562        } else {
1563            format!(
1564                "❌ Rebase failed: {}",
1565                self.error.as_deref().unwrap_or("Unknown error")
1566            )
1567        }
1568    }
1569
1570    /// Check if any conflicts occurred
1571    pub fn has_conflicts(&self) -> bool {
1572        !self.conflicts.is_empty()
1573    }
1574
1575    /// Get the number of successful operations
1576    pub fn success_count(&self) -> usize {
1577        self.new_commits.len()
1578    }
1579}
1580
1581#[cfg(test)]
1582mod tests {
1583    use super::*;
1584    use std::path::PathBuf;
1585    use std::process::Command;
1586    use tempfile::TempDir;
1587
1588    #[allow(dead_code)]
1589    fn create_test_repo() -> (TempDir, PathBuf) {
1590        let temp_dir = TempDir::new().unwrap();
1591        let repo_path = temp_dir.path().to_path_buf();
1592
1593        // Initialize git repository
1594        Command::new("git")
1595            .args(["init"])
1596            .current_dir(&repo_path)
1597            .output()
1598            .unwrap();
1599        Command::new("git")
1600            .args(["config", "user.name", "Test"])
1601            .current_dir(&repo_path)
1602            .output()
1603            .unwrap();
1604        Command::new("git")
1605            .args(["config", "user.email", "test@test.com"])
1606            .current_dir(&repo_path)
1607            .output()
1608            .unwrap();
1609
1610        // Create initial commit
1611        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1612        Command::new("git")
1613            .args(["add", "."])
1614            .current_dir(&repo_path)
1615            .output()
1616            .unwrap();
1617        Command::new("git")
1618            .args(["commit", "-m", "Initial"])
1619            .current_dir(&repo_path)
1620            .output()
1621            .unwrap();
1622
1623        (temp_dir, repo_path)
1624    }
1625
1626    #[test]
1627    fn test_conflict_region_creation() {
1628        let region = ConflictRegion {
1629            start: 0,
1630            end: 50,
1631            start_line: 1,
1632            end_line: 3,
1633            our_content: "function test() {\n    return true;\n}".to_string(),
1634            their_content: "function test() {\n  return true;\n}".to_string(),
1635        };
1636
1637        assert_eq!(region.start_line, 1);
1638        assert_eq!(region.end_line, 3);
1639        assert!(region.our_content.contains("return true"));
1640        assert!(region.their_content.contains("return true"));
1641    }
1642
1643    #[test]
1644    fn test_rebase_strategies() {
1645        assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1646        assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1647    }
1648
1649    #[test]
1650    fn test_rebase_options() {
1651        let options = RebaseOptions::default();
1652        assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1653        assert!(!options.interactive);
1654        assert!(options.auto_resolve);
1655        assert_eq!(options.max_retries, 3);
1656    }
1657
1658    #[test]
1659    fn test_cleanup_guard_tracks_branches() {
1660        let mut guard = TempBranchCleanupGuard::new();
1661        assert!(guard.branches.is_empty());
1662
1663        guard.add_branch("test-branch-1".to_string());
1664        guard.add_branch("test-branch-2".to_string());
1665
1666        assert_eq!(guard.branches.len(), 2);
1667        assert_eq!(guard.branches[0], "test-branch-1");
1668        assert_eq!(guard.branches[1], "test-branch-2");
1669    }
1670
1671    #[test]
1672    fn test_cleanup_guard_prevents_double_cleanup() {
1673        use std::process::Command;
1674        use tempfile::TempDir;
1675
1676        // Create a temporary git repo
1677        let temp_dir = TempDir::new().unwrap();
1678        let repo_path = temp_dir.path();
1679
1680        Command::new("git")
1681            .args(["init"])
1682            .current_dir(repo_path)
1683            .output()
1684            .unwrap();
1685
1686        Command::new("git")
1687            .args(["config", "user.name", "Test"])
1688            .current_dir(repo_path)
1689            .output()
1690            .unwrap();
1691
1692        Command::new("git")
1693            .args(["config", "user.email", "test@test.com"])
1694            .current_dir(repo_path)
1695            .output()
1696            .unwrap();
1697
1698        // Create initial commit
1699        std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1700        Command::new("git")
1701            .args(["add", "."])
1702            .current_dir(repo_path)
1703            .output()
1704            .unwrap();
1705        Command::new("git")
1706            .args(["commit", "-m", "initial"])
1707            .current_dir(repo_path)
1708            .output()
1709            .unwrap();
1710
1711        let git_repo = GitRepository::open(repo_path).unwrap();
1712
1713        // Create a test branch
1714        git_repo.create_branch("test-temp", None).unwrap();
1715
1716        let mut guard = TempBranchCleanupGuard::new();
1717        guard.add_branch("test-temp".to_string());
1718
1719        // First cleanup should work
1720        guard.cleanup(&git_repo);
1721        assert!(guard.cleaned);
1722
1723        // Second cleanup should be a no-op (shouldn't panic)
1724        guard.cleanup(&git_repo);
1725        assert!(guard.cleaned);
1726    }
1727
1728    #[test]
1729    fn test_rebase_result() {
1730        let result = RebaseResult {
1731            success: true,
1732            branch_mapping: std::collections::HashMap::new(),
1733            conflicts: vec!["abc123".to_string()],
1734            new_commits: vec!["def456".to_string()],
1735            error: None,
1736            summary: "Test summary".to_string(),
1737        };
1738
1739        assert!(result.success);
1740        assert!(result.has_conflicts());
1741        assert_eq!(result.success_count(), 1);
1742    }
1743}