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