cascade_cli/stack/
rebase.rs

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