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