cascade_cli/stack/
rebase.rs

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