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                // All conflicts resolved - write the file back atomically
749                crate::utils::atomic_file::write_string(&full_path, &content)?;
750
751                return Ok(ConflictResolution::Resolved);
752            } else {
753                info!(
754                    "โš ๏ธ  Partially resolved conflicts in {} ({} remaining)",
755                    file_path,
756                    remaining_conflicts.len()
757                );
758            }
759        }
760
761        Ok(ConflictResolution::TooComplex)
762    }
763
764    /// Resolve a single conflict using enhanced analysis
765    fn resolve_single_conflict_enhanced(
766        &self,
767        conflict: &crate::git::ConflictRegion,
768    ) -> Result<Option<String>> {
769        debug!(
770            "Resolving {} conflict in {} (lines {}-{})",
771            format!("{:?}", conflict.conflict_type).to_lowercase(),
772            conflict.file_path,
773            conflict.start_line,
774            conflict.end_line
775        );
776
777        use crate::git::ConflictType;
778
779        match conflict.conflict_type {
780            ConflictType::Whitespace => {
781                // Use the version with better formatting
782                if conflict.our_content.trim().len() >= conflict.their_content.trim().len() {
783                    Ok(Some(conflict.our_content.clone()))
784                } else {
785                    Ok(Some(conflict.their_content.clone()))
786                }
787            }
788            ConflictType::LineEnding => {
789                // Normalize to Unix line endings
790                let normalized = conflict
791                    .our_content
792                    .replace("\r\n", "\n")
793                    .replace('\r', "\n");
794                Ok(Some(normalized))
795            }
796            ConflictType::PureAddition => {
797                // Merge both additions
798                if conflict.our_content.is_empty() {
799                    Ok(Some(conflict.their_content.clone()))
800                } else if conflict.their_content.is_empty() {
801                    Ok(Some(conflict.our_content.clone()))
802                } else {
803                    // Try to combine both
804                    let combined = format!("{}\n{}", conflict.our_content, conflict.their_content);
805                    Ok(Some(combined))
806                }
807            }
808            ConflictType::ImportMerge => {
809                // Sort and merge imports
810                let mut all_imports: Vec<&str> = conflict
811                    .our_content
812                    .lines()
813                    .chain(conflict.their_content.lines())
814                    .collect();
815                all_imports.sort();
816                all_imports.dedup();
817                Ok(Some(all_imports.join("\n")))
818            }
819            ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
820                // These require manual resolution
821                Ok(None)
822            }
823        }
824    }
825
826    /// Resolve conflicts in a single file using smart strategies
827    #[allow(dead_code)]
828    fn resolve_file_conflicts(&self, file_path: &str) -> Result<ConflictResolution> {
829        let repo_path = self.git_repo.path();
830        let full_path = repo_path.join(file_path);
831
832        // Read the file content with conflict markers
833        let content = std::fs::read_to_string(&full_path)
834            .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
835
836        // Parse conflicts from the file
837        let conflicts = self.parse_conflict_markers(&content)?;
838
839        if conflicts.is_empty() {
840            // No conflict markers found - file might already be resolved
841            return Ok(ConflictResolution::Resolved);
842        }
843
844        info!(
845            "Found {} conflict regions in {}",
846            conflicts.len(),
847            file_path
848        );
849
850        // Try to resolve each conflict using our strategies
851        let mut resolved_content = content;
852        let mut any_resolved = false;
853
854        // Process conflicts in reverse order to maintain string indices
855        for conflict in conflicts.iter().rev() {
856            match self.resolve_single_conflict(conflict, file_path) {
857                Ok(Some(resolution)) => {
858                    // Replace the conflict region with the resolved content
859                    let before = &resolved_content[..conflict.start];
860                    let after = &resolved_content[conflict.end..];
861                    resolved_content = format!("{before}{resolution}{after}");
862                    any_resolved = true;
863                    debug!(
864                        "โœ… Resolved conflict at lines {}-{} in {}",
865                        conflict.start_line, conflict.end_line, file_path
866                    );
867                }
868                Ok(None) => {
869                    debug!(
870                        "โš ๏ธ  Conflict at lines {}-{} in {} too complex for auto-resolution",
871                        conflict.start_line, conflict.end_line, file_path
872                    );
873                }
874                Err(e) => {
875                    debug!("โŒ Failed to resolve conflict in {}: {}", file_path, e);
876                }
877            }
878        }
879
880        if any_resolved {
881            // Check if we resolved ALL conflicts in this file
882            let remaining_conflicts = self.parse_conflict_markers(&resolved_content)?;
883
884            if remaining_conflicts.is_empty() {
885                // All conflicts resolved - write the file back atomically
886                crate::utils::atomic_file::write_string(&full_path, &resolved_content)?;
887
888                return Ok(ConflictResolution::Resolved);
889            } else {
890                info!(
891                    "โš ๏ธ  Partially resolved conflicts in {} ({} remaining)",
892                    file_path,
893                    remaining_conflicts.len()
894                );
895            }
896        }
897
898        Ok(ConflictResolution::TooComplex)
899    }
900
901    /// Parse conflict markers from file content
902    fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
903        let lines: Vec<&str> = content.lines().collect();
904        let mut conflicts = Vec::new();
905        let mut i = 0;
906
907        while i < lines.len() {
908            if lines[i].starts_with("<<<<<<<") {
909                // Found start of conflict
910                let start_line = i + 1;
911                let mut separator_line = None;
912                let mut end_line = None;
913
914                // Find the separator and end
915                for (j, line) in lines.iter().enumerate().skip(i + 1) {
916                    if line.starts_with("=======") {
917                        separator_line = Some(j + 1);
918                    } else if line.starts_with(">>>>>>>") {
919                        end_line = Some(j + 1);
920                        break;
921                    }
922                }
923
924                if let (Some(sep), Some(end)) = (separator_line, end_line) {
925                    // Calculate byte positions
926                    let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
927                    let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
928
929                    let our_content = lines[(i + 1)..(sep - 1)].join("\n");
930                    let their_content = lines[sep..(end - 1)].join("\n");
931
932                    conflicts.push(ConflictRegion {
933                        start: start_pos,
934                        end: end_pos,
935                        start_line,
936                        end_line: end,
937                        our_content,
938                        their_content,
939                    });
940
941                    i = end;
942                } else {
943                    i += 1;
944                }
945            } else {
946                i += 1;
947            }
948        }
949
950        Ok(conflicts)
951    }
952
953    /// Resolve a single conflict using smart strategies
954    fn resolve_single_conflict(
955        &self,
956        conflict: &ConflictRegion,
957        file_path: &str,
958    ) -> Result<Option<String>> {
959        debug!(
960            "Analyzing conflict in {} (lines {}-{})",
961            file_path, conflict.start_line, conflict.end_line
962        );
963
964        // Strategy 1: Whitespace-only differences
965        if let Some(resolved) = self.resolve_whitespace_conflict(conflict)? {
966            debug!("Resolved as whitespace-only conflict");
967            return Ok(Some(resolved));
968        }
969
970        // Strategy 2: Line ending differences
971        if let Some(resolved) = self.resolve_line_ending_conflict(conflict)? {
972            debug!("Resolved as line ending conflict");
973            return Ok(Some(resolved));
974        }
975
976        // Strategy 3: Pure addition conflicts (no overlapping changes)
977        if let Some(resolved) = self.resolve_addition_conflict(conflict)? {
978            debug!("Resolved as pure addition conflict");
979            return Ok(Some(resolved));
980        }
981
982        // Strategy 4: Import/dependency reordering
983        if let Some(resolved) = self.resolve_import_conflict(conflict, file_path)? {
984            debug!("Resolved as import reordering conflict");
985            return Ok(Some(resolved));
986        }
987
988        // No strategy could resolve this conflict
989        Ok(None)
990    }
991
992    /// Resolve conflicts that only differ by whitespace
993    fn resolve_whitespace_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
994        let our_normalized = self.normalize_whitespace(&conflict.our_content);
995        let their_normalized = self.normalize_whitespace(&conflict.their_content);
996
997        if our_normalized == their_normalized {
998            // Only whitespace differences - prefer the version with better formatting
999            let resolved =
1000                if conflict.our_content.trim().len() >= conflict.their_content.trim().len() {
1001                    conflict.our_content.clone()
1002                } else {
1003                    conflict.their_content.clone()
1004                };
1005
1006            return Ok(Some(resolved));
1007        }
1008
1009        Ok(None)
1010    }
1011
1012    /// Resolve conflicts that only differ by line endings
1013    fn resolve_line_ending_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1014        let our_normalized = conflict
1015            .our_content
1016            .replace("\r\n", "\n")
1017            .replace('\r', "\n");
1018        let their_normalized = conflict
1019            .their_content
1020            .replace("\r\n", "\n")
1021            .replace('\r', "\n");
1022
1023        if our_normalized == their_normalized {
1024            // Only line ending differences - prefer Unix line endings
1025            return Ok(Some(our_normalized));
1026        }
1027
1028        Ok(None)
1029    }
1030
1031    /// Resolve conflicts where both sides only add lines (no overlapping edits)
1032    fn resolve_addition_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1033        let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1034        let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1035
1036        // Check if one side is a subset of the other (pure addition)
1037        if our_lines.is_empty() {
1038            return Ok(Some(conflict.their_content.clone()));
1039        }
1040        if their_lines.is_empty() {
1041            return Ok(Some(conflict.our_content.clone()));
1042        }
1043
1044        // Try to merge additions intelligently
1045        let mut merged_lines = Vec::new();
1046        let mut our_idx = 0;
1047        let mut their_idx = 0;
1048
1049        while our_idx < our_lines.len() || their_idx < their_lines.len() {
1050            if our_idx >= our_lines.len() {
1051                // Only their lines left
1052                merged_lines.extend_from_slice(&their_lines[their_idx..]);
1053                break;
1054            } else if their_idx >= their_lines.len() {
1055                // Only our lines left
1056                merged_lines.extend_from_slice(&our_lines[our_idx..]);
1057                break;
1058            } else if our_lines[our_idx] == their_lines[their_idx] {
1059                // Same line - add once
1060                merged_lines.push(our_lines[our_idx]);
1061                our_idx += 1;
1062                their_idx += 1;
1063            } else {
1064                // Different lines - this might be too complex
1065                return Ok(None);
1066            }
1067        }
1068
1069        Ok(Some(merged_lines.join("\n")))
1070    }
1071
1072    /// Resolve import/dependency conflicts by sorting and merging
1073    fn resolve_import_conflict(
1074        &self,
1075        conflict: &ConflictRegion,
1076        file_path: &str,
1077    ) -> Result<Option<String>> {
1078        // Only apply to likely import sections in common file types
1079        let is_import_file = file_path.ends_with(".rs")
1080            || file_path.ends_with(".py")
1081            || file_path.ends_with(".js")
1082            || file_path.ends_with(".ts")
1083            || file_path.ends_with(".go")
1084            || file_path.ends_with(".java")
1085            || file_path.ends_with(".swift")
1086            || file_path.ends_with(".kt")
1087            || file_path.ends_with(".cs");
1088
1089        if !is_import_file {
1090            return Ok(None);
1091        }
1092
1093        let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1094        let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1095
1096        // Check if all lines look like imports/uses
1097        let our_imports = our_lines
1098            .iter()
1099            .all(|line| self.is_import_line(line, file_path));
1100        let their_imports = their_lines
1101            .iter()
1102            .all(|line| self.is_import_line(line, file_path));
1103
1104        if our_imports && their_imports {
1105            // Merge and sort imports
1106            let mut all_imports: Vec<&str> = our_lines.into_iter().chain(their_lines).collect();
1107            all_imports.sort();
1108            all_imports.dedup();
1109
1110            return Ok(Some(all_imports.join("\n")));
1111        }
1112
1113        Ok(None)
1114    }
1115
1116    /// Check if a line looks like an import statement
1117    fn is_import_line(&self, line: &str, file_path: &str) -> bool {
1118        let trimmed = line.trim();
1119
1120        if trimmed.is_empty() {
1121            return true; // Empty lines are OK in import sections
1122        }
1123
1124        if file_path.ends_with(".rs") {
1125            return trimmed.starts_with("use ") || trimmed.starts_with("extern crate");
1126        } else if file_path.ends_with(".py") {
1127            return trimmed.starts_with("import ") || trimmed.starts_with("from ");
1128        } else if file_path.ends_with(".js") || file_path.ends_with(".ts") {
1129            return trimmed.starts_with("import ")
1130                || trimmed.starts_with("const ")
1131                || trimmed.starts_with("require(");
1132        } else if file_path.ends_with(".go") {
1133            return trimmed.starts_with("import ") || trimmed == "import (" || trimmed == ")";
1134        } else if file_path.ends_with(".java") {
1135            return trimmed.starts_with("import ");
1136        } else if file_path.ends_with(".swift") {
1137            return trimmed.starts_with("import ") || trimmed.starts_with("@testable import ");
1138        } else if file_path.ends_with(".kt") {
1139            return trimmed.starts_with("import ") || trimmed.starts_with("@file:");
1140        } else if file_path.ends_with(".cs") {
1141            return trimmed.starts_with("using ") || trimmed.starts_with("extern alias ");
1142        }
1143
1144        false
1145    }
1146
1147    /// Normalize whitespace for comparison
1148    fn normalize_whitespace(&self, content: &str) -> String {
1149        content
1150            .lines()
1151            .map(|line| line.trim())
1152            .filter(|line| !line.is_empty())
1153            .collect::<Vec<_>>()
1154            .join("\n")
1155    }
1156
1157    /// Update a stack entry with new commit information
1158    /// NOTE: We keep the original branch name to preserve PR mapping, only update commit hash
1159    fn update_stack_entry(
1160        &mut self,
1161        stack_id: Uuid,
1162        entry_id: &Uuid,
1163        _new_branch: &str,
1164        new_commit_hash: &str,
1165    ) -> Result<()> {
1166        debug!(
1167            "Updating entry {} in stack {} with new commit {}",
1168            entry_id, stack_id, new_commit_hash
1169        );
1170
1171        // Get the stack and update the entry
1172        let stack = self
1173            .stack_manager
1174            .get_stack_mut(&stack_id)
1175            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1176
1177        // Find and update the entry
1178        if let Some(entry) = stack.entries.iter_mut().find(|e| e.id == *entry_id) {
1179            debug!(
1180                "Found entry {} - updating commit from '{}' to '{}' (keeping original branch '{}')",
1181                entry_id, entry.commit_hash, new_commit_hash, entry.branch
1182            );
1183
1184            // CRITICAL: Keep the original branch name to preserve PR mapping
1185            // Only update the commit hash to point to the new rebased commit
1186            entry.commit_hash = new_commit_hash.to_string();
1187
1188            // Note: Stack will be saved by the caller (StackManager) after rebase completes
1189
1190            debug!(
1191                "Successfully updated entry {} in stack {}",
1192                entry_id, stack_id
1193            );
1194            Ok(())
1195        } else {
1196            Err(CascadeError::config(format!(
1197                "Entry {entry_id} not found in stack {stack_id}"
1198            )))
1199        }
1200    }
1201
1202    /// Pull latest changes from remote
1203    fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1204        info!("Pulling latest changes for branch {}", branch);
1205
1206        // First try to fetch (this might fail if no remote exists)
1207        match self.git_repo.fetch() {
1208            Ok(_) => {
1209                debug!("Fetch successful");
1210                // Now try to pull the specific branch
1211                match self.git_repo.pull(branch) {
1212                    Ok(_) => {
1213                        info!("Pull completed successfully for {}", branch);
1214                        Ok(())
1215                    }
1216                    Err(e) => {
1217                        warn!("Pull failed for {}: {}", branch, e);
1218                        // Don't fail the entire rebase for pull issues
1219                        Ok(())
1220                    }
1221                }
1222            }
1223            Err(e) => {
1224                warn!("Fetch failed: {}", e);
1225                // Don't fail if there's no remote configured
1226                Ok(())
1227            }
1228        }
1229    }
1230
1231    /// Check if rebase is in progress
1232    pub fn is_rebase_in_progress(&self) -> bool {
1233        // Check for git rebase state files
1234        let git_dir = self.git_repo.path().join(".git");
1235        git_dir.join("REBASE_HEAD").exists()
1236            || git_dir.join("rebase-merge").exists()
1237            || git_dir.join("rebase-apply").exists()
1238    }
1239
1240    /// Abort an in-progress rebase
1241    pub fn abort_rebase(&self) -> Result<()> {
1242        info!("Aborting rebase operation");
1243
1244        let git_dir = self.git_repo.path().join(".git");
1245
1246        // Clean up rebase state files
1247        if git_dir.join("REBASE_HEAD").exists() {
1248            std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1249                CascadeError::Git(git2::Error::from_str(&format!(
1250                    "Failed to clean rebase state: {e}"
1251                )))
1252            })?;
1253        }
1254
1255        if git_dir.join("rebase-merge").exists() {
1256            std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1257                CascadeError::Git(git2::Error::from_str(&format!(
1258                    "Failed to clean rebase-merge: {e}"
1259                )))
1260            })?;
1261        }
1262
1263        if git_dir.join("rebase-apply").exists() {
1264            std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1265                CascadeError::Git(git2::Error::from_str(&format!(
1266                    "Failed to clean rebase-apply: {e}"
1267                )))
1268            })?;
1269        }
1270
1271        info!("Rebase aborted successfully");
1272        Ok(())
1273    }
1274
1275    /// Continue an in-progress rebase after conflict resolution
1276    pub fn continue_rebase(&self) -> Result<()> {
1277        info!("Continuing rebase operation");
1278
1279        // Check if there are still conflicts
1280        if self.git_repo.has_conflicts()? {
1281            return Err(CascadeError::branch(
1282                "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1283            ));
1284        }
1285
1286        // Stage resolved files
1287        self.git_repo.stage_conflict_resolved_files()?;
1288
1289        info!("Rebase continued successfully");
1290        Ok(())
1291    }
1292}
1293
1294impl RebaseResult {
1295    /// Get a summary of the rebase operation
1296    pub fn get_summary(&self) -> String {
1297        if self.success {
1298            format!("โœ… {}", self.summary)
1299        } else {
1300            format!(
1301                "โŒ Rebase failed: {}",
1302                self.error.as_deref().unwrap_or("Unknown error")
1303            )
1304        }
1305    }
1306
1307    /// Check if any conflicts occurred
1308    pub fn has_conflicts(&self) -> bool {
1309        !self.conflicts.is_empty()
1310    }
1311
1312    /// Get the number of successful operations
1313    pub fn success_count(&self) -> usize {
1314        self.new_commits.len()
1315    }
1316}
1317
1318#[cfg(test)]
1319mod tests {
1320    use super::*;
1321    use std::path::PathBuf;
1322    use std::process::Command;
1323    use tempfile::TempDir;
1324
1325    #[allow(dead_code)]
1326    fn create_test_repo() -> (TempDir, PathBuf) {
1327        let temp_dir = TempDir::new().unwrap();
1328        let repo_path = temp_dir.path().to_path_buf();
1329
1330        // Initialize git repository
1331        Command::new("git")
1332            .args(["init"])
1333            .current_dir(&repo_path)
1334            .output()
1335            .unwrap();
1336        Command::new("git")
1337            .args(["config", "user.name", "Test"])
1338            .current_dir(&repo_path)
1339            .output()
1340            .unwrap();
1341        Command::new("git")
1342            .args(["config", "user.email", "test@test.com"])
1343            .current_dir(&repo_path)
1344            .output()
1345            .unwrap();
1346
1347        // Create initial commit
1348        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1349        Command::new("git")
1350            .args(["add", "."])
1351            .current_dir(&repo_path)
1352            .output()
1353            .unwrap();
1354        Command::new("git")
1355            .args(["commit", "-m", "Initial"])
1356            .current_dir(&repo_path)
1357            .output()
1358            .unwrap();
1359
1360        (temp_dir, repo_path)
1361    }
1362
1363    #[test]
1364    fn test_conflict_region_creation() {
1365        let region = ConflictRegion {
1366            start: 0,
1367            end: 50,
1368            start_line: 1,
1369            end_line: 3,
1370            our_content: "function test() {\n    return true;\n}".to_string(),
1371            their_content: "function test() {\n  return true;\n}".to_string(),
1372        };
1373
1374        assert_eq!(region.start_line, 1);
1375        assert_eq!(region.end_line, 3);
1376        assert!(region.our_content.contains("return true"));
1377        assert!(region.their_content.contains("return true"));
1378    }
1379
1380    #[test]
1381    fn test_rebase_strategies() {
1382        assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1383        assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1384    }
1385
1386    #[test]
1387    fn test_rebase_options() {
1388        let options = RebaseOptions::default();
1389        assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1390        assert!(!options.interactive);
1391        assert!(options.auto_resolve);
1392        assert_eq!(options.max_retries, 3);
1393    }
1394
1395    #[test]
1396    fn test_cleanup_guard_tracks_branches() {
1397        let mut guard = TempBranchCleanupGuard::new();
1398        assert!(guard.branches.is_empty());
1399
1400        guard.add_branch("test-branch-1".to_string());
1401        guard.add_branch("test-branch-2".to_string());
1402
1403        assert_eq!(guard.branches.len(), 2);
1404        assert_eq!(guard.branches[0], "test-branch-1");
1405        assert_eq!(guard.branches[1], "test-branch-2");
1406    }
1407
1408    #[test]
1409    fn test_cleanup_guard_prevents_double_cleanup() {
1410        use std::process::Command;
1411        use tempfile::TempDir;
1412
1413        // Create a temporary git repo
1414        let temp_dir = TempDir::new().unwrap();
1415        let repo_path = temp_dir.path();
1416
1417        Command::new("git")
1418            .args(["init"])
1419            .current_dir(repo_path)
1420            .output()
1421            .unwrap();
1422
1423        Command::new("git")
1424            .args(["config", "user.name", "Test"])
1425            .current_dir(repo_path)
1426            .output()
1427            .unwrap();
1428
1429        Command::new("git")
1430            .args(["config", "user.email", "test@test.com"])
1431            .current_dir(repo_path)
1432            .output()
1433            .unwrap();
1434
1435        // Create initial commit
1436        std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1437        Command::new("git")
1438            .args(["add", "."])
1439            .current_dir(repo_path)
1440            .output()
1441            .unwrap();
1442        Command::new("git")
1443            .args(["commit", "-m", "initial"])
1444            .current_dir(repo_path)
1445            .output()
1446            .unwrap();
1447
1448        let git_repo = GitRepository::open(repo_path).unwrap();
1449
1450        // Create a test branch
1451        git_repo.create_branch("test-temp", None).unwrap();
1452
1453        let mut guard = TempBranchCleanupGuard::new();
1454        guard.add_branch("test-temp".to_string());
1455
1456        // First cleanup should work
1457        guard.cleanup(&git_repo);
1458        assert!(guard.cleaned);
1459
1460        // Second cleanup should be a no-op (shouldn't panic)
1461        guard.cleanup(&git_repo);
1462        assert!(guard.cleaned);
1463    }
1464
1465    #[test]
1466    fn test_rebase_result() {
1467        let result = RebaseResult {
1468            success: true,
1469            branch_mapping: std::collections::HashMap::new(),
1470            conflicts: vec!["abc123".to_string()],
1471            new_commits: vec!["def456".to_string()],
1472            error: None,
1473            summary: "Test summary".to_string(),
1474        };
1475
1476        assert!(result.success);
1477        assert!(result.has_conflicts());
1478        assert_eq!(result.success_count(), 1);
1479    }
1480
1481    #[test]
1482    fn test_import_line_detection() {
1483        let (_temp_dir, repo_path) = create_test_repo();
1484        let git_repo = crate::git::GitRepository::open(&repo_path).unwrap();
1485        let stack_manager = crate::stack::StackManager::new(&repo_path).unwrap();
1486        let options = RebaseOptions::default();
1487        let rebase_manager = RebaseManager::new(stack_manager, git_repo, options);
1488
1489        // Test Swift import detection
1490        assert!(rebase_manager.is_import_line("import Foundation", "test.swift"));
1491        assert!(rebase_manager.is_import_line("@testable import MyModule", "test.swift"));
1492        assert!(!rebase_manager.is_import_line("class MyClass {", "test.swift"));
1493
1494        // Test Kotlin import detection
1495        assert!(rebase_manager.is_import_line("import kotlin.collections.*", "test.kt"));
1496        assert!(rebase_manager.is_import_line("@file:JvmName(\"Utils\")", "test.kt"));
1497        assert!(!rebase_manager.is_import_line("fun myFunction() {", "test.kt"));
1498
1499        // Test C# import detection
1500        assert!(rebase_manager.is_import_line("using System;", "test.cs"));
1501        assert!(rebase_manager.is_import_line("using System.Collections.Generic;", "test.cs"));
1502        assert!(rebase_manager.is_import_line("extern alias GridV1;", "test.cs"));
1503        assert!(!rebase_manager.is_import_line("namespace MyNamespace {", "test.cs"));
1504
1505        // Test empty lines are allowed in import sections
1506        assert!(rebase_manager.is_import_line("", "test.swift"));
1507        assert!(rebase_manager.is_import_line("   ", "test.kt"));
1508        assert!(rebase_manager.is_import_line("", "test.cs"));
1509    }
1510}