Skip to main content

cascade_cli/git/
repository.rs

1use crate::cli::output::Output;
2use crate::errors::{CascadeError, Result};
3use chrono;
4use dialoguer::{theme::ColorfulTheme, Confirm, Select};
5use git2::{Oid, Repository, Signature};
6use std::path::{Path, PathBuf};
7use tracing::{debug, info, warn};
8
9/// Repository information
10#[derive(Debug, Clone)]
11pub struct RepositoryInfo {
12    pub path: PathBuf,
13    pub head_branch: Option<String>,
14    pub head_commit: Option<String>,
15    pub is_dirty: bool,
16    pub untracked_files: Vec<String>,
17}
18
19/// Backup information for force push operations
20#[derive(Debug, Clone)]
21struct ForceBackupInfo {
22    pub backup_branch_name: String,
23    pub remote_commit_id: String,
24    #[allow(dead_code)] // Used for logging/display purposes
25    pub commits_that_would_be_lost: usize,
26}
27
28/// Safety information for branch deletion operations
29#[derive(Debug, Clone)]
30struct BranchDeletionSafety {
31    pub unpushed_commits: Vec<String>,
32    pub remote_tracking_branch: Option<String>,
33    pub is_merged_to_main: bool,
34    pub main_branch_name: String,
35}
36
37/// Safety information for checkout operations
38#[derive(Debug, Clone)]
39struct CheckoutSafety {
40    #[allow(dead_code)] // Used in confirmation dialogs and future features
41    pub has_uncommitted_changes: bool,
42    pub modified_files: Vec<String>,
43    pub staged_files: Vec<String>,
44    pub untracked_files: Vec<String>,
45    #[allow(dead_code)] // Reserved for future automatic stashing implementation
46    pub stash_created: Option<String>,
47    #[allow(dead_code)] // Used for context in confirmation dialogs
48    pub current_branch: Option<String>,
49}
50
51/// SSL configuration for git operations
52#[derive(Debug, Clone)]
53pub struct GitSslConfig {
54    pub accept_invalid_certs: bool,
55    pub ca_bundle_path: Option<String>,
56}
57
58/// Summary of git repository status
59#[derive(Debug, Clone)]
60pub struct GitStatusSummary {
61    staged_files: usize,
62    unstaged_files: usize,
63    untracked_files: usize,
64}
65
66impl GitStatusSummary {
67    pub fn is_clean(&self) -> bool {
68        self.staged_files == 0 && self.unstaged_files == 0 && self.untracked_files == 0
69    }
70
71    pub fn has_staged_changes(&self) -> bool {
72        self.staged_files > 0
73    }
74
75    pub fn has_unstaged_changes(&self) -> bool {
76        self.unstaged_files > 0
77    }
78
79    pub fn has_untracked_files(&self) -> bool {
80        self.untracked_files > 0
81    }
82
83    pub fn staged_count(&self) -> usize {
84        self.staged_files
85    }
86
87    pub fn unstaged_count(&self) -> usize {
88        self.unstaged_files
89    }
90
91    pub fn untracked_count(&self) -> usize {
92        self.untracked_files
93    }
94}
95
96/// Wrapper around git2::Repository with safe operations
97///
98/// For thread safety, use the async variants (e.g., fetch_async, pull_async)
99/// which automatically handle threading using tokio::spawn_blocking.
100/// The async methods create new repository instances in background threads.
101pub struct GitRepository {
102    repo: Repository,
103    path: PathBuf,
104    ssl_config: Option<GitSslConfig>,
105    bitbucket_credentials: Option<BitbucketCredentials>,
106}
107
108#[derive(Debug, Clone)]
109struct BitbucketCredentials {
110    username: Option<String>,
111    token: Option<String>,
112}
113
114impl GitRepository {
115    /// Open a Git repository at the given path
116    /// Automatically loads SSL configuration from cascade config if available
117    pub fn open(path: &Path) -> Result<Self> {
118        let repo = Repository::discover(path)
119            .map_err(|e| CascadeError::config(format!("Not a git repository: {e}")))?;
120
121        let workdir = repo
122            .workdir()
123            .ok_or_else(|| CascadeError::config("Repository has no working directory"))?
124            .to_path_buf();
125
126        // Try to load SSL configuration from cascade config
127        let ssl_config = Self::load_ssl_config_from_cascade(&workdir);
128        let bitbucket_credentials = Self::load_bitbucket_credentials_from_cascade(&workdir);
129
130        Ok(Self {
131            repo,
132            path: workdir,
133            ssl_config,
134            bitbucket_credentials,
135        })
136    }
137
138    /// Load SSL configuration from cascade config file if it exists
139    fn load_ssl_config_from_cascade(repo_path: &Path) -> Option<GitSslConfig> {
140        // Try to load cascade configuration
141        let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
142        let config_path = config_dir.join("config.json");
143        let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
144
145        // Convert BitbucketConfig to GitSslConfig if SSL settings exist
146        if settings.bitbucket.accept_invalid_certs.is_some()
147            || settings.bitbucket.ca_bundle_path.is_some()
148        {
149            Some(GitSslConfig {
150                accept_invalid_certs: settings.bitbucket.accept_invalid_certs.unwrap_or(false),
151                ca_bundle_path: settings.bitbucket.ca_bundle_path,
152            })
153        } else {
154            None
155        }
156    }
157
158    /// Load Bitbucket credentials from cascade config file if it exists
159    fn load_bitbucket_credentials_from_cascade(repo_path: &Path) -> Option<BitbucketCredentials> {
160        // Try to load cascade configuration
161        let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
162        let config_path = config_dir.join("config.json");
163        let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
164
165        // Return credentials if any are configured
166        if settings.bitbucket.username.is_some() || settings.bitbucket.token.is_some() {
167            Some(BitbucketCredentials {
168                username: settings.bitbucket.username.clone(),
169                token: settings.bitbucket.token.clone(),
170            })
171        } else {
172            None
173        }
174    }
175
176    /// Get repository information
177    pub fn get_info(&self) -> Result<RepositoryInfo> {
178        let head_branch = self.get_current_branch().ok();
179        let head_commit = self.get_head_commit_hash().ok();
180        let is_dirty = self.is_dirty()?;
181        let untracked_files = self.get_untracked_files()?;
182
183        Ok(RepositoryInfo {
184            path: self.path.clone(),
185            head_branch,
186            head_commit,
187            is_dirty,
188            untracked_files,
189        })
190    }
191
192    /// Get the current branch name
193    pub fn get_current_branch(&self) -> Result<String> {
194        let head = self
195            .repo
196            .head()
197            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
198
199        if let Some(name) = head.shorthand() {
200            Ok(name.to_string())
201        } else {
202            // Detached HEAD - return commit hash
203            let commit = head
204                .peel_to_commit()
205                .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
206            Ok(format!("HEAD@{}", commit.id()))
207        }
208    }
209
210    /// Get the HEAD commit hash
211    pub fn get_head_commit_hash(&self) -> Result<String> {
212        let head = self
213            .repo
214            .head()
215            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
216
217        let commit = head
218            .peel_to_commit()
219            .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
220
221        Ok(commit.id().to_string())
222    }
223
224    /// Check if the working directory is dirty (has uncommitted changes)
225    /// Excludes .cascade/ directory changes as these are internal metadata
226    pub fn is_dirty(&self) -> Result<bool> {
227        let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
228
229        for status in statuses.iter() {
230            let flags = status.status();
231
232            // Skip .cascade/ directory - it's internal metadata that shouldn't block operations
233            if let Some(path) = status.path() {
234                if path.starts_with(".cascade/") || path == ".cascade" {
235                    continue;
236                }
237            }
238
239            // Check for any modifications, additions, or deletions
240            if flags.intersects(
241                git2::Status::INDEX_MODIFIED
242                    | git2::Status::INDEX_NEW
243                    | git2::Status::INDEX_DELETED
244                    | git2::Status::WT_MODIFIED
245                    | git2::Status::WT_NEW
246                    | git2::Status::WT_DELETED,
247            ) {
248                return Ok(true);
249            }
250        }
251
252        Ok(false)
253    }
254
255    /// Get list of untracked files
256    pub fn get_untracked_files(&self) -> Result<Vec<String>> {
257        let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
258
259        let mut untracked = Vec::new();
260        for status in statuses.iter() {
261            if status.status().contains(git2::Status::WT_NEW) {
262                if let Some(path) = status.path() {
263                    untracked.push(path.to_string());
264                }
265            }
266        }
267
268        Ok(untracked)
269    }
270
271    /// Create a new branch
272    pub fn create_branch(&self, name: &str, target: Option<&str>) -> Result<()> {
273        let target_commit = if let Some(target) = target {
274            // Find the specified target commit/branch
275            let target_obj = self.repo.revparse_single(target).map_err(|e| {
276                CascadeError::branch(format!("Could not find target '{target}': {e}"))
277            })?;
278            target_obj.peel_to_commit().map_err(|e| {
279                CascadeError::branch(format!("Target '{target}' is not a commit: {e}"))
280            })?
281        } else {
282            // Use current HEAD
283            let head = self
284                .repo
285                .head()
286                .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
287            head.peel_to_commit()
288                .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?
289        };
290
291        self.repo
292            .branch(name, &target_commit, false)
293            .map_err(|e| CascadeError::branch(format!("Could not create branch '{name}': {e}")))?;
294
295        // Branch creation logging is handled by the caller for clean output
296        Ok(())
297    }
298
299    /// Update a branch to point to a specific commit (local operation only)
300    /// Creates the branch if it doesn't exist, updates it if it does
301    pub fn update_branch_to_commit(&self, branch_name: &str, commit_id: &str) -> Result<()> {
302        let commit_oid = Oid::from_str(commit_id).map_err(|e| {
303            CascadeError::branch(format!("Invalid commit ID '{}': {}", commit_id, e))
304        })?;
305
306        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
307            CascadeError::branch(format!("Commit '{}' not found: {}", commit_id, e))
308        })?;
309
310        // Try to find existing branch
311        if self
312            .repo
313            .find_branch(branch_name, git2::BranchType::Local)
314            .is_ok()
315        {
316            // Update existing branch to point to new commit
317            let refname = format!("refs/heads/{}", branch_name);
318            self.repo
319                .reference(
320                    &refname,
321                    commit_oid,
322                    true,
323                    "update branch to rebased commit",
324                )
325                .map_err(|e| {
326                    CascadeError::branch(format!(
327                        "Failed to update branch '{}': {}",
328                        branch_name, e
329                    ))
330                })?;
331        } else {
332            // Create new branch
333            self.repo.branch(branch_name, &commit, false).map_err(|e| {
334                CascadeError::branch(format!("Failed to create branch '{}': {}", branch_name, e))
335            })?;
336        }
337
338        Ok(())
339    }
340
341    /// Force-push a single branch to remote (simpler version for when branch is already updated locally)
342    pub fn force_push_single_branch(&self, branch_name: &str) -> Result<()> {
343        self.force_push_single_branch_with_options(branch_name, false, false)
344    }
345
346    /// Force push with option to skip user confirmation (for automated operations like sync)
347    pub fn force_push_single_branch_auto(&self, branch_name: &str) -> Result<()> {
348        self.force_push_single_branch_with_options(branch_name, true, false)
349    }
350
351    /// Force push a single branch without fetching first (assumes fetch already done)
352    /// Used in batch operations where we fetch once before pushing multiple branches
353    pub fn force_push_single_branch_auto_no_fetch(&self, branch_name: &str) -> Result<()> {
354        self.force_push_single_branch_with_options(branch_name, true, true)
355    }
356
357    fn force_push_single_branch_with_options(
358        &self,
359        branch_name: &str,
360        auto_confirm: bool,
361        skip_fetch: bool,
362    ) -> Result<()> {
363        // Validate branch exists before attempting push
364        // This provides a clearer error message than a failed git push
365        if self.get_branch_commit_hash(branch_name).is_err() {
366            return Err(CascadeError::branch(format!(
367                "Cannot push '{}': branch does not exist locally",
368                branch_name
369            )));
370        }
371
372        // CRITICAL: Fetch with retry to ensure we have latest remote state
373        // Using stale refs could cause silent data loss on force push!
374        // Skip if caller already fetched (batch operations)
375        if !skip_fetch {
376            self.fetch_with_retry()?;
377        }
378
379        // Check safety and create backup if needed
380        let safety_result = if auto_confirm {
381            self.check_force_push_safety_auto_no_fetch(branch_name)?
382        } else {
383            self.check_force_push_safety_enhanced(branch_name)?
384        };
385
386        if let Some(backup_info) = safety_result {
387            self.create_backup_branch(branch_name, &backup_info.remote_commit_id)?;
388            Output::sub_item(format!(
389                "Created backup branch: {}",
390                backup_info.backup_branch_name
391            ));
392        }
393
394        // Ensure index is closed before CLI command to prevent lock conflicts
395        self.ensure_index_closed()?;
396
397        // Create marker file to signal pre-push hook to allow this internal push
398        // (Git hooks don't inherit env vars, so we use a file marker instead)
399        let marker_path = self.git_dir().join(".cascade-internal-push");
400        std::fs::write(&marker_path, "1")
401            .map_err(|e| CascadeError::branch(format!("Failed to create push marker: {}", e)))?;
402
403        // Force push using git CLI (more reliable than git2 for TLS)
404        let output = std::process::Command::new("git")
405            .args(["push", "--force", "origin", branch_name])
406            .current_dir(&self.path)
407            .output()
408            .map_err(|e| {
409                // Clean up marker on error
410                let _ = std::fs::remove_file(&marker_path);
411                CascadeError::branch(format!("Failed to execute git push: {}", e))
412            })?;
413
414        // Clean up marker file after push attempt
415        let _ = std::fs::remove_file(&marker_path);
416
417        if !output.status.success() {
418            let stderr = String::from_utf8_lossy(&output.stderr);
419            let stdout = String::from_utf8_lossy(&output.stdout);
420
421            // Combine stderr and stdout for full error context
422            let full_error = if !stdout.is_empty() {
423                format!("{}\n{}", stderr.trim(), stdout.trim())
424            } else {
425                stderr.trim().to_string()
426            };
427
428            return Err(CascadeError::branch(format!(
429                "Force push failed for '{}':\n{}",
430                branch_name, full_error
431            )));
432        }
433
434        Ok(())
435    }
436
437    /// Switch to a branch with safety checks
438    pub fn checkout_branch(&self, name: &str) -> Result<()> {
439        self.checkout_branch_with_options(name, false, true)
440    }
441
442    /// Switch to a branch silently (no output)
443    pub fn checkout_branch_silent(&self, name: &str) -> Result<()> {
444        self.checkout_branch_with_options(name, false, false)
445    }
446
447    /// Switch to a branch with force option to bypass safety checks
448    pub fn checkout_branch_unsafe(&self, name: &str) -> Result<()> {
449        self.checkout_branch_with_options(name, true, false)
450    }
451
452    /// Internal branch checkout implementation with safety options
453    fn checkout_branch_with_options(
454        &self,
455        name: &str,
456        force_unsafe: bool,
457        show_output: bool,
458    ) -> Result<()> {
459        debug!("Attempting to checkout branch: {}", name);
460
461        // Enhanced safety check: Detect uncommitted work before checkout
462        if !force_unsafe {
463            let safety_result = self.check_checkout_safety(name)?;
464            if let Some(safety_info) = safety_result {
465                // Repository has uncommitted changes, get user confirmation
466                self.handle_checkout_confirmation(name, &safety_info)?;
467            }
468        }
469
470        // Find the branch
471        let branch = self
472            .repo
473            .find_branch(name, git2::BranchType::Local)
474            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
475
476        let branch_ref = branch.get();
477        let tree = branch_ref.peel_to_tree().map_err(|e| {
478            CascadeError::branch(format!("Could not get tree for branch '{name}': {e}"))
479        })?;
480
481        // Update HEAD first — this validates that the branch can be checked out
482        // (e.g., not already checked out in another worktree). Doing this before
483        // checkout_tree prevents leaving the working directory in an inconsistent
484        // state if set_head fails.
485        let old_head = self.repo.head().ok();
486        self.repo
487            .set_head(&format!("refs/heads/{name}"))
488            .map_err(|e| CascadeError::branch(format!("Could not update HEAD to '{name}': {e}")))?;
489
490        // Now checkout the tree to update the working directory
491        let mut checkout_builder = git2::build::CheckoutBuilder::new();
492        checkout_builder.force(); // Overwrite modified files
493        checkout_builder.remove_untracked(false); // Keep untracked files
494
495        if let Err(e) = self
496            .repo
497            .checkout_tree(tree.as_object(), Some(&mut checkout_builder))
498        {
499            // Restore HEAD if checkout_tree fails so we don't leave HEAD
500            // pointing at a branch whose tree isn't checked out
501            if let Some(old) = old_head {
502                if let Some(old_name) = old.name() {
503                    let _ = self.repo.set_head(old_name);
504                }
505            }
506            return Err(CascadeError::branch(format!(
507                "Could not checkout branch '{name}': {e}"
508            )));
509        }
510
511        if show_output {
512            Output::success(format!("Switched to branch '{name}'"));
513        }
514        Ok(())
515    }
516
517    /// Checkout a specific commit (detached HEAD) with safety checks
518    pub fn checkout_commit(&self, commit_hash: &str) -> Result<()> {
519        self.checkout_commit_with_options(commit_hash, false)
520    }
521
522    /// Checkout a specific commit with force option to bypass safety checks
523    pub fn checkout_commit_unsafe(&self, commit_hash: &str) -> Result<()> {
524        self.checkout_commit_with_options(commit_hash, true)
525    }
526
527    /// Internal commit checkout implementation with safety options
528    fn checkout_commit_with_options(&self, commit_hash: &str, force_unsafe: bool) -> Result<()> {
529        debug!("Attempting to checkout commit: {}", commit_hash);
530
531        // Enhanced safety check: Detect uncommitted work before checkout
532        if !force_unsafe {
533            let safety_result = self.check_checkout_safety(&format!("commit:{commit_hash}"))?;
534            if let Some(safety_info) = safety_result {
535                // Repository has uncommitted changes, get user confirmation
536                self.handle_checkout_confirmation(&format!("commit {commit_hash}"), &safety_info)?;
537            }
538        }
539
540        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
541
542        let commit = self.repo.find_commit(oid).map_err(|e| {
543            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
544        })?;
545
546        let tree = commit.tree().map_err(|e| {
547            CascadeError::branch(format!(
548                "Could not get tree for commit '{commit_hash}': {e}"
549            ))
550        })?;
551
552        // Checkout the tree
553        self.repo
554            .checkout_tree(tree.as_object(), None)
555            .map_err(|e| {
556                CascadeError::branch(format!("Could not checkout commit '{commit_hash}': {e}"))
557            })?;
558
559        // Update HEAD to the commit (detached HEAD)
560        self.repo.set_head_detached(oid).map_err(|e| {
561            CascadeError::branch(format!(
562                "Could not update HEAD to commit '{commit_hash}': {e}"
563            ))
564        })?;
565
566        Output::success(format!(
567            "Checked out commit '{commit_hash}' (detached HEAD)"
568        ));
569        Ok(())
570    }
571
572    /// Check if a branch exists
573    pub fn branch_exists(&self, name: &str) -> bool {
574        self.repo.find_branch(name, git2::BranchType::Local).is_ok()
575    }
576
577    /// Check if a branch exists locally, and if not, attempt to fetch it from remote
578    pub fn branch_exists_or_fetch(&self, name: &str) -> Result<bool> {
579        // 1. Check if branch exists locally first
580        if self.repo.find_branch(name, git2::BranchType::Local).is_ok() {
581            return Ok(true);
582        }
583
584        // 2. Try to fetch it from remote
585        crate::cli::output::Output::info(format!(
586            "Branch '{name}' not found locally, trying to fetch from remote..."
587        ));
588
589        use std::process::Command;
590
591        // Try: git fetch origin release/12.34:release/12.34
592        let fetch_result = Command::new("git")
593            .args(["fetch", "origin", &format!("{name}:{name}")])
594            .current_dir(&self.path)
595            .output();
596
597        match fetch_result {
598            Ok(output) => {
599                if output.status.success() {
600                    println!("✅ Successfully fetched '{name}' from origin");
601                    // 3. Check again locally after fetch
602                    return Ok(self.repo.find_branch(name, git2::BranchType::Local).is_ok());
603                } else {
604                    let stderr = String::from_utf8_lossy(&output.stderr);
605                    tracing::debug!("Failed to fetch branch '{name}': {stderr}");
606                }
607            }
608            Err(e) => {
609                tracing::debug!("Git fetch command failed: {e}");
610            }
611        }
612
613        // 4. Try alternative fetch patterns for common branch naming
614        if name.contains('/') {
615            crate::cli::output::Output::info("Trying alternative fetch patterns...");
616
617            // Try: git fetch origin (to get all refs, then checkout locally)
618            let fetch_all_result = Command::new("git")
619                .args(["fetch", "origin"])
620                .current_dir(&self.path)
621                .output();
622
623            if let Ok(output) = fetch_all_result {
624                if output.status.success() {
625                    // Try to create local branch from remote
626                    let checkout_result = Command::new("git")
627                        .args(["checkout", "-b", name, &format!("origin/{name}")])
628                        .current_dir(&self.path)
629                        .output();
630
631                    if let Ok(checkout_output) = checkout_result {
632                        if checkout_output.status.success() {
633                            println!(
634                                "✅ Successfully created local branch '{name}' from origin/{name}"
635                            );
636                            return Ok(true);
637                        }
638                    }
639                }
640            }
641        }
642
643        // 5. Only fail if it doesn't exist anywhere
644        Ok(false)
645    }
646
647    /// Get the commit hash for a specific branch without switching branches
648    pub fn get_branch_commit_hash(&self, branch_name: &str) -> Result<String> {
649        let branch = self
650            .repo
651            .find_branch(branch_name, git2::BranchType::Local)
652            .map_err(|e| {
653                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
654            })?;
655
656        let commit = branch.get().peel_to_commit().map_err(|e| {
657            CascadeError::branch(format!(
658                "Could not get commit for branch '{branch_name}': {e}"
659            ))
660        })?;
661
662        Ok(commit.id().to_string())
663    }
664
665    /// List all local branches
666    pub fn list_branches(&self) -> Result<Vec<String>> {
667        let branches = self
668            .repo
669            .branches(Some(git2::BranchType::Local))
670            .map_err(CascadeError::Git)?;
671
672        let mut branch_names = Vec::new();
673        for branch in branches {
674            let (branch, _) = branch.map_err(CascadeError::Git)?;
675            if let Some(name) = branch.name().map_err(CascadeError::Git)? {
676                branch_names.push(name.to_string());
677            }
678        }
679
680        Ok(branch_names)
681    }
682
683    /// Get the upstream branch for a local branch
684    pub fn get_upstream_branch(&self, branch_name: &str) -> Result<Option<String>> {
685        // Try to get the upstream from git config
686        let config = self.repo.config().map_err(CascadeError::Git)?;
687
688        // Check for branch.{branch_name}.remote and branch.{branch_name}.merge
689        let remote_key = format!("branch.{branch_name}.remote");
690        let merge_key = format!("branch.{branch_name}.merge");
691
692        if let (Ok(remote), Ok(merge_ref)) = (
693            config.get_string(&remote_key),
694            config.get_string(&merge_key),
695        ) {
696            // Parse the merge ref (e.g., "refs/heads/feature-auth" -> "feature-auth")
697            if let Some(branch_part) = merge_ref.strip_prefix("refs/heads/") {
698                return Ok(Some(format!("{remote}/{branch_part}")));
699            }
700        }
701
702        // Fallback: check if there's a remote tracking branch with the same name
703        let potential_upstream = format!("origin/{branch_name}");
704        if self
705            .repo
706            .find_reference(&format!("refs/remotes/{potential_upstream}"))
707            .is_ok()
708        {
709            return Ok(Some(potential_upstream));
710        }
711
712        Ok(None)
713    }
714
715    /// Get ahead/behind counts compared to upstream
716    pub fn get_ahead_behind_counts(
717        &self,
718        local_branch: &str,
719        upstream_branch: &str,
720    ) -> Result<(usize, usize)> {
721        // Get the commit objects for both branches
722        let local_ref = self
723            .repo
724            .find_reference(&format!("refs/heads/{local_branch}"))
725            .map_err(|_| {
726                CascadeError::config(format!("Local branch '{local_branch}' not found"))
727            })?;
728        let local_commit = local_ref.peel_to_commit().map_err(CascadeError::Git)?;
729
730        let upstream_ref = self
731            .repo
732            .find_reference(&format!("refs/remotes/{upstream_branch}"))
733            .map_err(|_| {
734                CascadeError::config(format!("Upstream branch '{upstream_branch}' not found"))
735            })?;
736        let upstream_commit = upstream_ref.peel_to_commit().map_err(CascadeError::Git)?;
737
738        // Use git2's graph_ahead_behind to calculate the counts
739        let (ahead, behind) = self
740            .repo
741            .graph_ahead_behind(local_commit.id(), upstream_commit.id())
742            .map_err(CascadeError::Git)?;
743
744        Ok((ahead, behind))
745    }
746
747    /// Set upstream tracking for a branch
748    pub fn set_upstream(&self, branch_name: &str, remote: &str, remote_branch: &str) -> Result<()> {
749        let mut config = self.repo.config().map_err(CascadeError::Git)?;
750
751        // Set branch.{branch_name}.remote = remote
752        let remote_key = format!("branch.{branch_name}.remote");
753        config
754            .set_str(&remote_key, remote)
755            .map_err(CascadeError::Git)?;
756
757        // Set branch.{branch_name}.merge = refs/heads/{remote_branch}
758        let merge_key = format!("branch.{branch_name}.merge");
759        let merge_value = format!("refs/heads/{remote_branch}");
760        config
761            .set_str(&merge_key, &merge_value)
762            .map_err(CascadeError::Git)?;
763
764        Ok(())
765    }
766
767    /// Create a commit with all staged changes
768    pub fn commit(&self, message: &str) -> Result<String> {
769        // Validate git user configuration before attempting commit operations
770        self.validate_git_user_config()?;
771
772        let signature = self.get_signature()?;
773        let tree_id = self.get_index_tree()?;
774        let tree = self.repo.find_tree(tree_id).map_err(CascadeError::Git)?;
775
776        // Get parent commits
777        let head = self.repo.head().map_err(CascadeError::Git)?;
778        let parent_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
779
780        let commit_id = self
781            .repo
782            .commit(
783                Some("HEAD"),
784                &signature,
785                &signature,
786                message,
787                &tree,
788                &[&parent_commit],
789            )
790            .map_err(CascadeError::Git)?;
791
792        Output::success(format!("Created commit: {commit_id} - {message}"));
793        Ok(commit_id.to_string())
794    }
795
796    /// Commit any staged changes with a default message
797    pub fn commit_staged_changes(&self, default_message: &str) -> Result<Option<String>> {
798        // Check if there are staged changes
799        let staged_files = self.get_staged_files()?;
800        if staged_files.is_empty() {
801            tracing::debug!("No staged changes to commit");
802            return Ok(None);
803        }
804
805        tracing::debug!("Committing {} staged files", staged_files.len());
806        let commit_hash = self.commit(default_message)?;
807        Ok(Some(commit_hash))
808    }
809
810    /// Stage all changes
811    pub fn stage_all(&self) -> Result<()> {
812        let mut index = self.repo.index().map_err(CascadeError::Git)?;
813
814        index
815            .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
816            .map_err(CascadeError::Git)?;
817
818        index.write().map_err(CascadeError::Git)?;
819        drop(index); // Explicitly close index after staging
820
821        tracing::debug!("Staged all changes");
822        Ok(())
823    }
824
825    /// Ensure the Git index is fully written and closed before external git CLI operations
826    /// This prevents "index is locked" errors when mixing libgit2 and git CLI commands
827    fn ensure_index_closed(&self) -> Result<()> {
828        // Open and immediately close the index to ensure any pending writes are flushed
829        // and file handles are released before we spawn git CLI processes
830        let mut index = self.repo.index().map_err(CascadeError::Git)?;
831        index.write().map_err(CascadeError::Git)?;
832        drop(index); // Explicit drop to release file handle
833
834        // Give the OS a moment to release file handles
835        // This is necessary because even after Rust drops the index,
836        // the OS might not immediately release the lock
837        std::thread::sleep(std::time::Duration::from_millis(10));
838
839        Ok(())
840    }
841
842    /// Stage only specific files (safer than stage_all during rebase)
843    pub fn stage_files(&self, file_paths: &[&str]) -> Result<()> {
844        if file_paths.is_empty() {
845            tracing::debug!("No files to stage");
846            return Ok(());
847        }
848
849        let mut index = self.repo.index().map_err(CascadeError::Git)?;
850
851        for file_path in file_paths {
852            index
853                .add_path(std::path::Path::new(file_path))
854                .map_err(CascadeError::Git)?;
855        }
856
857        index.write().map_err(CascadeError::Git)?;
858        drop(index); // Explicitly close index after staging
859
860        tracing::debug!(
861            "Staged {} specific files: {:?}",
862            file_paths.len(),
863            file_paths
864        );
865        Ok(())
866    }
867
868    /// Stage only files that had conflicts (safer for rebase operations)
869    pub fn stage_conflict_resolved_files(&self) -> Result<()> {
870        let conflicted_files = self.get_conflicted_files()?;
871        if conflicted_files.is_empty() {
872            tracing::debug!("No conflicted files to stage");
873            return Ok(());
874        }
875
876        let file_paths: Vec<&str> = conflicted_files.iter().map(|s| s.as_str()).collect();
877        self.stage_files(&file_paths)?;
878
879        tracing::debug!("Staged {} conflict-resolved files", conflicted_files.len());
880        Ok(())
881    }
882
883    /// Clean up any in-progress merge/revert/cherry-pick state (removes CHERRY_PICK_HEAD etc.)
884    pub fn cleanup_state(&self) -> Result<()> {
885        let state = self.repo.state();
886        if state == git2::RepositoryState::Clean {
887            return Ok(());
888        }
889
890        tracing::debug!("Cleaning up repository state: {:?}", state);
891        self.repo.cleanup_state().map_err(|e| {
892            CascadeError::branch(format!(
893                "Failed to clean up repository state ({:?}): {}",
894                state, e
895            ))
896        })
897    }
898
899    /// Get repository path
900    pub fn path(&self) -> &Path {
901        &self.path
902    }
903
904    /// Per-worktree git directory.
905    /// Normal repos: /repo/.git/  |  Worktrees: /main/.git/worktrees/<name>/
906    pub fn git_dir(&self) -> &Path {
907        self.repo.path()
908    }
909
910    /// Shared common git directory (hooks, objects, refs).
911    /// Normal repos: same as git_dir()  |  Worktrees: /main/.git/
912    pub fn common_dir(&self) -> &Path {
913        self.repo.commondir()
914    }
915
916    /// Check if a commit exists
917    pub fn commit_exists(&self, commit_hash: &str) -> Result<bool> {
918        match Oid::from_str(commit_hash) {
919            Ok(oid) => match self.repo.find_commit(oid) {
920                Ok(_) => Ok(true),
921                Err(_) => Ok(false),
922            },
923            Err(_) => Ok(false),
924        }
925    }
926
927    /// Check if a commit is already correctly based on a given parent
928    /// Returns true if the commit's parent matches the expected base
929    pub fn is_commit_based_on(&self, commit_hash: &str, expected_base: &str) -> Result<bool> {
930        let commit_oid = Oid::from_str(commit_hash).map_err(|e| {
931            CascadeError::branch(format!("Invalid commit hash '{}': {}", commit_hash, e))
932        })?;
933
934        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
935            CascadeError::branch(format!("Commit '{}' not found: {}", commit_hash, e))
936        })?;
937
938        // Get the commit's parent (first parent for merge commits)
939        if commit.parent_count() == 0 {
940            // Root commit has no parent
941            return Ok(false);
942        }
943
944        let parent = commit.parent(0).map_err(|e| {
945            CascadeError::branch(format!(
946                "Could not get parent of commit '{}': {}",
947                commit_hash, e
948            ))
949        })?;
950        let parent_hash = parent.id().to_string();
951
952        // Check if expected_base is a commit hash or a branch name
953        let expected_base_oid = if let Ok(oid) = Oid::from_str(expected_base) {
954            oid
955        } else {
956            // Try to resolve as a branch name
957            let branch_ref = format!("refs/heads/{}", expected_base);
958            let reference = self.repo.find_reference(&branch_ref).map_err(|e| {
959                CascadeError::branch(format!("Could not find base '{}': {}", expected_base, e))
960            })?;
961            reference.target().ok_or_else(|| {
962                CascadeError::branch(format!("Base '{}' has no target commit", expected_base))
963            })?
964        };
965
966        let expected_base_hash = expected_base_oid.to_string();
967
968        tracing::debug!(
969            "Checking if commit {} is based on {}: parent={}, expected={}",
970            &commit_hash[..8],
971            expected_base,
972            &parent_hash[..8],
973            &expected_base_hash[..8]
974        );
975
976        Ok(parent_hash == expected_base_hash)
977    }
978
979    /// Check whether `descendant` commit contains `ancestor` in its history
980    pub fn is_descendant_of(&self, descendant: &str, ancestor: &str) -> Result<bool> {
981        let descendant_oid = Oid::from_str(descendant).map_err(|e| {
982            CascadeError::branch(format!(
983                "Invalid commit hash '{}' for descendant check: {}",
984                descendant, e
985            ))
986        })?;
987        let ancestor_oid = Oid::from_str(ancestor).map_err(|e| {
988            CascadeError::branch(format!(
989                "Invalid commit hash '{}' for descendant check: {}",
990                ancestor, e
991            ))
992        })?;
993
994        self.repo
995            .graph_descendant_of(descendant_oid, ancestor_oid)
996            .map_err(CascadeError::Git)
997    }
998
999    /// Get the HEAD commit object
1000    pub fn get_head_commit(&self) -> Result<git2::Commit<'_>> {
1001        let head = self
1002            .repo
1003            .head()
1004            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
1005        head.peel_to_commit()
1006            .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))
1007    }
1008
1009    /// Get a commit object by hash
1010    pub fn get_commit(&self, commit_hash: &str) -> Result<git2::Commit<'_>> {
1011        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1012
1013        self.repo.find_commit(oid).map_err(CascadeError::Git)
1014    }
1015
1016    /// Get the commit hash at the head of a branch
1017    pub fn get_branch_head(&self, branch_name: &str) -> Result<String> {
1018        let branch = self
1019            .repo
1020            .find_branch(branch_name, git2::BranchType::Local)
1021            .map_err(|e| {
1022                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
1023            })?;
1024
1025        let commit = branch.get().peel_to_commit().map_err(|e| {
1026            CascadeError::branch(format!(
1027                "Could not get commit for branch '{branch_name}': {e}"
1028            ))
1029        })?;
1030
1031        Ok(commit.id().to_string())
1032    }
1033
1034    /// Get the commit hash at the head of a remote branch
1035    pub fn get_remote_branch_head(&self, branch_name: &str) -> Result<String> {
1036        let refname = format!("refs/remotes/origin/{branch_name}");
1037        let reference = self.repo.find_reference(&refname).map_err(|e| {
1038            CascadeError::branch(format!("Remote branch '{branch_name}' not found: {e}"))
1039        })?;
1040
1041        let target = reference.target().ok_or_else(|| {
1042            CascadeError::branch(format!(
1043                "Remote branch '{branch_name}' does not have a target commit"
1044            ))
1045        })?;
1046
1047        Ok(target.to_string())
1048    }
1049
1050    /// Validate git user configuration is properly set
1051    pub fn validate_git_user_config(&self) -> Result<()> {
1052        if let Ok(config) = self.repo.config() {
1053            let name_result = config.get_string("user.name");
1054            let email_result = config.get_string("user.email");
1055
1056            if let (Ok(name), Ok(email)) = (name_result, email_result) {
1057                if !name.trim().is_empty() && !email.trim().is_empty() {
1058                    tracing::debug!("Git user config validated: {} <{}>", name, email);
1059                    return Ok(());
1060                }
1061            }
1062        }
1063
1064        // Check if this is a CI environment where validation can be skipped
1065        let is_ci = std::env::var("CI").is_ok();
1066
1067        if is_ci {
1068            tracing::debug!("CI environment - skipping git user config validation");
1069            return Ok(());
1070        }
1071
1072        Output::warning("Git user configuration missing or incomplete");
1073        Output::info("This can cause cherry-pick and commit operations to fail");
1074        Output::info("Please configure git user information:");
1075        Output::bullet("git config user.name \"Your Name\"".to_string());
1076        Output::bullet("git config user.email \"your.email@example.com\"".to_string());
1077        Output::info("Or set globally with the --global flag");
1078
1079        // Don't fail - let operations continue with fallback signature
1080        // This preserves backward compatibility while providing guidance
1081        Ok(())
1082    }
1083
1084    /// Read the configured git user name and email from git config
1085    pub fn get_user_info(&self) -> (Option<String>, Option<String>) {
1086        let config = match self.repo.config() {
1087            Ok(c) => c,
1088            Err(_) => return (None, None),
1089        };
1090        let name = config.get_string("user.name").ok();
1091        let email = config.get_string("user.email").ok();
1092        (name, email)
1093    }
1094
1095    /// Get a signature for commits with comprehensive fallback and validation
1096    fn get_signature(&self) -> Result<Signature<'_>> {
1097        // Try to get signature from Git config first
1098        if let Ok(config) = self.repo.config() {
1099            // Try global/system config first
1100            let name_result = config.get_string("user.name");
1101            let email_result = config.get_string("user.email");
1102
1103            if let (Ok(name), Ok(email)) = (name_result, email_result) {
1104                if !name.trim().is_empty() && !email.trim().is_empty() {
1105                    tracing::debug!("Using git config: {} <{}>", name, email);
1106                    return Signature::now(&name, &email).map_err(CascadeError::Git);
1107                }
1108            } else {
1109                tracing::debug!("Git user config incomplete or missing");
1110            }
1111        }
1112
1113        // Check if this is a CI environment where fallback is acceptable
1114        let is_ci = std::env::var("CI").is_ok();
1115
1116        if is_ci {
1117            tracing::debug!("CI environment detected, using fallback signature");
1118            return Signature::now("Cascade CLI", "cascade@example.com").map_err(CascadeError::Git);
1119        }
1120
1121        // Interactive environment - provide helpful guidance
1122        tracing::warn!("Git user configuration missing - this can cause commit operations to fail");
1123
1124        // Try fallback signature, but warn about the issue
1125        match Signature::now("Cascade CLI", "cascade@example.com") {
1126            Ok(sig) => {
1127                Output::warning("Git user not configured - using fallback signature");
1128                Output::info("For better git history, run:");
1129                Output::bullet("git config user.name \"Your Name\"".to_string());
1130                Output::bullet("git config user.email \"your.email@example.com\"".to_string());
1131                Output::info("Or set it globally with --global flag");
1132                Ok(sig)
1133            }
1134            Err(e) => {
1135                Err(CascadeError::branch(format!(
1136                    "Cannot create git signature: {e}. Please configure git user with:\n  git config user.name \"Your Name\"\n  git config user.email \"your.email@example.com\""
1137                )))
1138            }
1139        }
1140    }
1141
1142    /// Configure remote callbacks with SSL settings
1143    /// Priority: Cascade SSL config > Git config > Default
1144    fn configure_remote_callbacks(&self) -> Result<git2::RemoteCallbacks<'_>> {
1145        self.configure_remote_callbacks_with_fallback(false)
1146    }
1147
1148    /// Determine if we should retry with DefaultCredentials based on git2 error classification
1149    fn should_retry_with_default_credentials(&self, error: &git2::Error) -> bool {
1150        match error.class() {
1151            // Authentication errors that might be resolved with DefaultCredentials
1152            git2::ErrorClass::Http => {
1153                // HTTP errors often indicate authentication issues in corporate environments
1154                match error.code() {
1155                    git2::ErrorCode::Auth => true,
1156                    _ => {
1157                        // Check for specific HTTP authentication replay errors
1158                        let error_string = error.to_string();
1159                        error_string.contains("too many redirects")
1160                            || error_string.contains("authentication replays")
1161                            || error_string.contains("authentication required")
1162                    }
1163                }
1164            }
1165            git2::ErrorClass::Net => {
1166                // Network errors that might be authentication-related
1167                let error_string = error.to_string();
1168                error_string.contains("authentication")
1169                    || error_string.contains("unauthorized")
1170                    || error_string.contains("forbidden")
1171            }
1172            _ => false,
1173        }
1174    }
1175
1176    /// Determine if we should fallback to git CLI based on git2 error classification
1177    fn should_fallback_to_git_cli(&self, error: &git2::Error) -> bool {
1178        match error.class() {
1179            // SSL/TLS errors that git CLI handles better
1180            git2::ErrorClass::Ssl => true,
1181
1182            // Certificate errors
1183            git2::ErrorClass::Http if error.code() == git2::ErrorCode::Certificate => true,
1184
1185            // SSH errors that might need git CLI
1186            git2::ErrorClass::Ssh => {
1187                let error_string = error.to_string();
1188                error_string.contains("no callback set")
1189                    || error_string.contains("authentication required")
1190            }
1191
1192            // Network errors that might be proxy/firewall related
1193            git2::ErrorClass::Net => {
1194                let error_string = error.to_string();
1195                error_string.contains("TLS stream")
1196                    || error_string.contains("SSL")
1197                    || error_string.contains("proxy")
1198                    || error_string.contains("firewall")
1199            }
1200
1201            // General HTTP errors not handled by DefaultCredentials retry
1202            git2::ErrorClass::Http => {
1203                let error_string = error.to_string();
1204                error_string.contains("TLS stream")
1205                    || error_string.contains("SSL")
1206                    || error_string.contains("proxy")
1207            }
1208
1209            _ => false,
1210        }
1211    }
1212
1213    fn configure_remote_callbacks_with_fallback(
1214        &self,
1215        use_default_first: bool,
1216    ) -> Result<git2::RemoteCallbacks<'_>> {
1217        let mut callbacks = git2::RemoteCallbacks::new();
1218
1219        // Configure authentication with comprehensive credential support
1220        let bitbucket_credentials = self.bitbucket_credentials.clone();
1221        callbacks.credentials(move |url, username_from_url, allowed_types| {
1222            tracing::debug!(
1223                "Authentication requested for URL: {}, username: {:?}, allowed_types: {:?}",
1224                url,
1225                username_from_url,
1226                allowed_types
1227            );
1228
1229            // For SSH URLs with username
1230            if allowed_types.contains(git2::CredentialType::SSH_KEY) {
1231                if let Some(username) = username_from_url {
1232                    tracing::debug!("Trying SSH key authentication for user: {}", username);
1233                    return git2::Cred::ssh_key_from_agent(username);
1234                }
1235            }
1236
1237            // For HTTPS URLs, try multiple authentication methods in sequence
1238            if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
1239                // If we're in corporate network fallback mode, try DefaultCredentials first
1240                if use_default_first {
1241                    tracing::debug!("Corporate network mode: trying DefaultCredentials first");
1242                    return git2::Cred::default();
1243                }
1244
1245                if url.contains("bitbucket") {
1246                    if let Some(creds) = &bitbucket_credentials {
1247                        // Method 1: Username + Token (common for Bitbucket)
1248                        if let (Some(username), Some(token)) = (&creds.username, &creds.token) {
1249                            tracing::debug!("Trying Bitbucket username + token authentication");
1250                            return git2::Cred::userpass_plaintext(username, token);
1251                        }
1252
1253                        // Method 2: Token as username, empty password (alternate Bitbucket format)
1254                        if let Some(token) = &creds.token {
1255                            tracing::debug!("Trying Bitbucket token-as-username authentication");
1256                            return git2::Cred::userpass_plaintext(token, "");
1257                        }
1258
1259                        // Method 3: Just username (will prompt for password or use credential helper)
1260                        if let Some(username) = &creds.username {
1261                            tracing::debug!("Trying Bitbucket username authentication (will use credential helper)");
1262                            return git2::Cred::username(username);
1263                        }
1264                    }
1265                }
1266
1267                // Method 4: Default credential helper for all HTTPS URLs
1268                tracing::debug!("Trying default credential helper for HTTPS authentication");
1269                return git2::Cred::default();
1270            }
1271
1272            // Fallback to default for any other cases
1273            tracing::debug!("Using default credential fallback");
1274            git2::Cred::default()
1275        });
1276
1277        // Configure SSL certificate checking with system certificates by default
1278        // This matches what tools like Graphite, Sapling, and Phabricator do
1279        // Priority: 1. Use system certificates (default), 2. Manual overrides only if needed
1280
1281        let mut ssl_configured = false;
1282
1283        // Check for manual SSL overrides first (only when user explicitly needs them)
1284        if let Some(ssl_config) = &self.ssl_config {
1285            if ssl_config.accept_invalid_certs {
1286                Output::warning(
1287                    "SSL certificate verification DISABLED via Cascade config - this is insecure!",
1288                );
1289                callbacks.certificate_check(|_cert, _host| {
1290                    tracing::debug!("⚠️  Accepting invalid certificate for host: {}", _host);
1291                    Ok(git2::CertificateCheckStatus::CertificateOk)
1292                });
1293                ssl_configured = true;
1294            } else if let Some(ca_path) = &ssl_config.ca_bundle_path {
1295                Output::info(format!(
1296                    "Using custom CA bundle from Cascade config: {ca_path}"
1297                ));
1298                callbacks.certificate_check(|_cert, host| {
1299                    tracing::debug!("Using custom CA bundle for host: {}", host);
1300                    Ok(git2::CertificateCheckStatus::CertificateOk)
1301                });
1302                ssl_configured = true;
1303            }
1304        }
1305
1306        // Check git config for manual overrides
1307        if !ssl_configured {
1308            if let Ok(config) = self.repo.config() {
1309                let ssl_verify = config.get_bool("http.sslVerify").unwrap_or(true);
1310
1311                if !ssl_verify {
1312                    Output::warning(
1313                        "SSL certificate verification DISABLED via git config - this is insecure!",
1314                    );
1315                    callbacks.certificate_check(|_cert, host| {
1316                        tracing::debug!("⚠️  Bypassing SSL verification for host: {}", host);
1317                        Ok(git2::CertificateCheckStatus::CertificateOk)
1318                    });
1319                    ssl_configured = true;
1320                } else if let Ok(ca_path) = config.get_string("http.sslCAInfo") {
1321                    Output::info(format!("Using custom CA bundle from git config: {ca_path}"));
1322                    callbacks.certificate_check(|_cert, host| {
1323                        tracing::debug!("Using git config CA bundle for host: {}", host);
1324                        Ok(git2::CertificateCheckStatus::CertificateOk)
1325                    });
1326                    ssl_configured = true;
1327                }
1328            }
1329        }
1330
1331        // DEFAULT BEHAVIOR: Use system certificates (like git CLI and other modern tools)
1332        // This should work out-of-the-box in corporate environments
1333        if !ssl_configured {
1334            tracing::debug!(
1335                "Using system certificate store for SSL verification (default behavior)"
1336            );
1337
1338            // For macOS with SecureTransport backend, try default certificate validation first
1339            if cfg!(target_os = "macos") {
1340                tracing::debug!("macOS detected - using default certificate validation");
1341                // Don't set any certificate callback - let git2 use its default behavior
1342                // This often works better with SecureTransport backend on macOS
1343            } else {
1344                // Use CertificatePassthrough for other platforms
1345                callbacks.certificate_check(|_cert, host| {
1346                    tracing::debug!("System certificate validation for host: {}", host);
1347                    Ok(git2::CertificateCheckStatus::CertificatePassthrough)
1348                });
1349            }
1350        }
1351
1352        Ok(callbacks)
1353    }
1354
1355    /// Get the tree ID from the current index
1356    fn get_index_tree(&self) -> Result<Oid> {
1357        let mut index = self.repo.index().map_err(CascadeError::Git)?;
1358
1359        index.write_tree().map_err(CascadeError::Git)
1360    }
1361
1362    /// Get repository status
1363    pub fn get_status(&self) -> Result<git2::Statuses<'_>> {
1364        self.repo.statuses(None).map_err(CascadeError::Git)
1365    }
1366
1367    /// Get a summary of repository status
1368    pub fn get_status_summary(&self) -> Result<GitStatusSummary> {
1369        let statuses = self.get_status()?;
1370
1371        let mut staged_files = 0;
1372        let mut unstaged_files = 0;
1373        let mut untracked_files = 0;
1374
1375        for status in statuses.iter() {
1376            let flags = status.status();
1377
1378            if flags.intersects(
1379                git2::Status::INDEX_MODIFIED
1380                    | git2::Status::INDEX_NEW
1381                    | git2::Status::INDEX_DELETED
1382                    | git2::Status::INDEX_RENAMED
1383                    | git2::Status::INDEX_TYPECHANGE,
1384            ) {
1385                staged_files += 1;
1386            }
1387
1388            if flags.intersects(
1389                git2::Status::WT_MODIFIED
1390                    | git2::Status::WT_DELETED
1391                    | git2::Status::WT_TYPECHANGE
1392                    | git2::Status::WT_RENAMED,
1393            ) {
1394                unstaged_files += 1;
1395            }
1396
1397            if flags.intersects(git2::Status::WT_NEW) {
1398                untracked_files += 1;
1399            }
1400        }
1401
1402        Ok(GitStatusSummary {
1403            staged_files,
1404            unstaged_files,
1405            untracked_files,
1406        })
1407    }
1408
1409    /// Get the current commit hash (alias for get_head_commit_hash)
1410    pub fn get_current_commit_hash(&self) -> Result<String> {
1411        self.get_head_commit_hash()
1412    }
1413
1414    /// Get the count of commits between two commits
1415    pub fn get_commit_count_between(&self, from_commit: &str, to_commit: &str) -> Result<usize> {
1416        let from_oid = git2::Oid::from_str(from_commit).map_err(CascadeError::Git)?;
1417        let to_oid = git2::Oid::from_str(to_commit).map_err(CascadeError::Git)?;
1418
1419        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1420        revwalk.push(to_oid).map_err(CascadeError::Git)?;
1421        revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1422
1423        Ok(revwalk.count())
1424    }
1425
1426    /// Get remote URL for a given remote name
1427    pub fn get_remote_url(&self, name: &str) -> Result<String> {
1428        let remote = self.repo.find_remote(name).map_err(CascadeError::Git)?;
1429        Ok(remote.url().unwrap_or("unknown").to_string())
1430    }
1431
1432    /// Cherry-pick a specific commit to the current branch
1433    pub fn cherry_pick(&self, commit_hash: &str) -> Result<String> {
1434        tracing::debug!("Cherry-picking commit {}", commit_hash);
1435
1436        // Validate git user configuration before attempting commit operations
1437        self.validate_git_user_config()?;
1438
1439        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1440        let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1441
1442        // Get the commit's tree
1443        let commit_tree = commit.tree().map_err(CascadeError::Git)?;
1444
1445        // Get parent tree for merge base
1446        let parent_commit = if commit.parent_count() > 0 {
1447            commit.parent(0).map_err(CascadeError::Git)?
1448        } else {
1449            // Root commit - use empty tree
1450            let empty_tree_oid = self.repo.treebuilder(None)?.write()?;
1451            let empty_tree = self.repo.find_tree(empty_tree_oid)?;
1452            let sig = self.get_signature()?;
1453            return self
1454                .repo
1455                .commit(
1456                    Some("HEAD"),
1457                    &sig,
1458                    &sig,
1459                    commit.message().unwrap_or("Cherry-picked commit"),
1460                    &empty_tree,
1461                    &[],
1462                )
1463                .map(|oid| oid.to_string())
1464                .map_err(CascadeError::Git);
1465        };
1466
1467        let parent_tree = parent_commit.tree().map_err(CascadeError::Git)?;
1468
1469        // Get current HEAD tree for 3-way merge
1470        let head_commit = self.get_head_commit()?;
1471        let head_tree = head_commit.tree().map_err(CascadeError::Git)?;
1472
1473        // Perform 3-way merge
1474        let mut index = self
1475            .repo
1476            .merge_trees(&parent_tree, &head_tree, &commit_tree, None)
1477            .map_err(CascadeError::Git)?;
1478
1479        // Check for conflicts
1480        if index.has_conflicts() {
1481            // CRITICAL: Write the conflicted state to disk so auto-resolve can see it!
1482            // Without this, conflicts only exist in memory and Git's index stays clean
1483            debug!("Cherry-pick has conflicts - writing conflicted state to disk for resolution");
1484
1485            // The merge_trees() index is in-memory only. We need to:
1486            // 1. Get the repository's actual index
1487            // 2. Read entries from the merge result into it
1488            // 3. Write the repository index to disk
1489
1490            let mut repo_index = self.repo.index().map_err(CascadeError::Git)?;
1491
1492            // Clear the current index and read from the merge result
1493            repo_index.clear().map_err(CascadeError::Git)?;
1494            repo_index
1495                .read_tree(&head_tree)
1496                .map_err(CascadeError::Git)?;
1497
1498            // Now merge the commit tree into the repo index (this will create conflicts)
1499            repo_index
1500                .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
1501                .map_err(CascadeError::Git)?;
1502
1503            // Use git CLI to do the actual cherry-pick with conflicts
1504            // This is more reliable than trying to manually construct the conflicted index
1505
1506            // First, ensure our libgit2 index is closed so git CLI can work
1507            drop(repo_index);
1508            self.ensure_index_closed()?;
1509
1510            let cherry_pick_output = std::process::Command::new("git")
1511                .args(["cherry-pick", commit_hash])
1512                .current_dir(self.path())
1513                .output()
1514                .map_err(CascadeError::Io)?;
1515
1516            if !cherry_pick_output.status.success() {
1517                debug!("Git CLI cherry-pick failed as expected (has conflicts)");
1518                // This is expected - the cherry-pick failed due to conflicts
1519                // The conflicts are now in the working directory and index
1520            }
1521
1522            // CRITICAL: Reload the index from disk so libgit2 sees the conflicts
1523            // Git CLI wrote the conflicts to disk, but our in-memory index doesn't know yet
1524            self.repo
1525                .index()
1526                .and_then(|mut idx| idx.read(true).map(|_| ()))
1527                .map_err(CascadeError::Git)?;
1528
1529            debug!("Conflicted state written and index reloaded - auto-resolve can now process conflicts");
1530
1531            return Err(CascadeError::branch(format!(
1532                "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
1533            )));
1534        }
1535
1536        // Write merged tree
1537        let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
1538        let merged_tree = self
1539            .repo
1540            .find_tree(merged_tree_oid)
1541            .map_err(CascadeError::Git)?;
1542
1543        // Create new commit with original message (preserve it exactly)
1544        let signature = self.get_signature()?;
1545        let message = commit.message().unwrap_or("Cherry-picked commit");
1546
1547        let new_commit_oid = self
1548            .repo
1549            .commit(
1550                Some("HEAD"),
1551                &signature,
1552                &signature,
1553                message,
1554                &merged_tree,
1555                &[&head_commit],
1556            )
1557            .map_err(CascadeError::Git)?;
1558
1559        // Update working directory to reflect the new commit
1560        let new_commit = self
1561            .repo
1562            .find_commit(new_commit_oid)
1563            .map_err(CascadeError::Git)?;
1564        let new_tree = new_commit.tree().map_err(CascadeError::Git)?;
1565
1566        self.repo
1567            .checkout_tree(
1568                new_tree.as_object(),
1569                Some(git2::build::CheckoutBuilder::new().force()),
1570            )
1571            .map_err(CascadeError::Git)?;
1572
1573        tracing::debug!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
1574        Ok(new_commit_oid.to_string())
1575    }
1576
1577    /// Check for merge conflicts in the index
1578    pub fn has_conflicts(&self) -> Result<bool> {
1579        let index = self.repo.index().map_err(CascadeError::Git)?;
1580        Ok(index.has_conflicts())
1581    }
1582
1583    /// Get list of conflicted files
1584    pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
1585        let index = self.repo.index().map_err(CascadeError::Git)?;
1586
1587        let mut conflicts = Vec::new();
1588
1589        // Iterate through index conflicts
1590        let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;
1591
1592        for conflict in conflict_iter {
1593            let conflict = conflict.map_err(CascadeError::Git)?;
1594            if let Some(our) = conflict.our {
1595                if let Ok(path) = std::str::from_utf8(&our.path) {
1596                    conflicts.push(path.to_string());
1597                }
1598            } else if let Some(their) = conflict.their {
1599                if let Ok(path) = std::str::from_utf8(&their.path) {
1600                    conflicts.push(path.to_string());
1601                }
1602            }
1603        }
1604
1605        Ok(conflicts)
1606    }
1607
1608    /// Fetch from remote origin
1609    pub fn fetch(&self) -> Result<()> {
1610        tracing::debug!("Fetching from origin");
1611
1612        // CRITICAL: Ensure index is closed before fetch operation
1613        // This prevents "index is locked" errors when fetch is called after cherry-pick/commit
1614        self.ensure_index_closed()?;
1615
1616        let mut remote = self
1617            .repo
1618            .find_remote("origin")
1619            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1620
1621        // Configure callbacks with SSL settings from git config
1622        let callbacks = self.configure_remote_callbacks()?;
1623
1624        // Fetch options with authentication and SSL config
1625        let mut fetch_options = git2::FetchOptions::new();
1626        fetch_options.remote_callbacks(callbacks);
1627
1628        // Fetch with authentication
1629        match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1630            Ok(_) => {
1631                tracing::debug!("Fetch completed successfully");
1632                Ok(())
1633            }
1634            Err(e) => {
1635                if self.should_retry_with_default_credentials(&e) {
1636                    tracing::debug!(
1637                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1638                        e.class(), e.code(), e
1639                    );
1640
1641                    // Retry with DefaultCredentials for corporate networks
1642                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1643                    let mut fetch_options = git2::FetchOptions::new();
1644                    fetch_options.remote_callbacks(callbacks);
1645
1646                    match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1647                        Ok(_) => {
1648                            tracing::debug!("Fetch succeeded with DefaultCredentials");
1649                            return Ok(());
1650                        }
1651                        Err(retry_error) => {
1652                            tracing::debug!(
1653                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1654                                retry_error
1655                            );
1656                            return self.fetch_with_git_cli();
1657                        }
1658                    }
1659                }
1660
1661                if self.should_fallback_to_git_cli(&e) {
1662                    tracing::debug!(
1663                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for fetch operation",
1664                        e.class(), e.code(), e
1665                    );
1666                    return self.fetch_with_git_cli();
1667                }
1668                Err(CascadeError::Git(e))
1669            }
1670        }
1671    }
1672
1673    /// Fetch from remote with exponential backoff retry logic
1674    /// This is critical for force push safety checks to prevent data loss from stale refs
1675    pub fn fetch_with_retry(&self) -> Result<()> {
1676        const MAX_RETRIES: u32 = 3;
1677        const BASE_DELAY_MS: u64 = 500;
1678
1679        let mut last_error = None;
1680
1681        for attempt in 0..MAX_RETRIES {
1682            match self.fetch() {
1683                Ok(_) => return Ok(()),
1684                Err(e) => {
1685                    last_error = Some(e);
1686
1687                    if attempt < MAX_RETRIES - 1 {
1688                        let delay_ms = BASE_DELAY_MS * 2_u64.pow(attempt);
1689                        debug!(
1690                            "Fetch attempt {} failed, retrying in {}ms...",
1691                            attempt + 1,
1692                            delay_ms
1693                        );
1694                        std::thread::sleep(std::time::Duration::from_millis(delay_ms));
1695                    }
1696                }
1697            }
1698        }
1699
1700        // All retries failed - this is CRITICAL for force push safety
1701        Err(CascadeError::Git(git2::Error::from_str(&format!(
1702            "Critical: Failed to fetch remote refs after {} attempts. Cannot safely proceed with force push - \
1703             stale remote refs could cause data loss. Error: {}. Please check network connection.",
1704            MAX_RETRIES,
1705            last_error.unwrap()
1706        ))))
1707    }
1708
1709    /// Fetch and fast-forward a local branch ref to match origin, without checkout.
1710    /// Works safely in worktrees where the branch may be checked out elsewhere.
1711    pub fn update_local_branch_from_remote(&self, branch: &str) -> Result<()> {
1712        tracing::debug!(
1713            "Updating local branch '{}' from remote (worktree-safe)",
1714            branch
1715        );
1716
1717        // Retry fetch with backoff to handle transient index locks (e.g. an IDE or Git GUI)
1718        let mut last_error = None;
1719        for attempt in 0..3u32 {
1720            match self.fetch() {
1721                Ok(_) => {
1722                    last_error = None;
1723                    break;
1724                }
1725                Err(e) => {
1726                    let is_locked = e.to_string().contains("Locked")
1727                        || e.to_string().contains("index is locked");
1728                    last_error = Some(e);
1729                    if is_locked && attempt < 2 {
1730                        let delay = std::time::Duration::from_millis(500 * 2_u64.pow(attempt));
1731                        tracing::debug!(
1732                            "Index locked on fetch attempt {}, retrying in {:?}...",
1733                            attempt + 1,
1734                            delay
1735                        );
1736                        std::thread::sleep(delay);
1737                    } else {
1738                        break;
1739                    }
1740                }
1741            }
1742        }
1743        if let Some(e) = last_error {
1744            return Err(e);
1745        }
1746
1747        let remote_ref = format!("refs/remotes/origin/{branch}");
1748        let remote_oid = self.repo.refname_to_id(&remote_ref).map_err(|e| {
1749            CascadeError::branch(format!("Remote branch 'origin/{branch}' not found: {e}"))
1750        })?;
1751
1752        let local_ref = format!("refs/heads/{branch}");
1753        let local_oid = self.repo.refname_to_id(&local_ref).ok();
1754
1755        if let Some(local_oid) = local_oid {
1756            if local_oid == remote_oid {
1757                tracing::debug!("{branch} already up to date");
1758                return Ok(());
1759            }
1760
1761            let merge_base = self
1762                .repo
1763                .merge_base(local_oid, remote_oid)
1764                .map_err(CascadeError::Git)?;
1765
1766            if merge_base != local_oid {
1767                return Err(CascadeError::branch(format!(
1768                    "Branch '{branch}' has diverged from 'origin/{branch}'. \
1769                     Local has commits not in remote. Try: git reset --hard origin/{branch}"
1770                )));
1771            }
1772        }
1773
1774        self.repo
1775            .reference(
1776                &local_ref,
1777                remote_oid,
1778                true,
1779                "sync: fast-forward from origin",
1780            )
1781            .map_err(|e| CascadeError::branch(format!("Failed to update '{branch}': {e}")))?;
1782
1783        tracing::debug!("Fast-forwarded {branch} to {remote_oid}");
1784        Ok(())
1785    }
1786
1787    /// Pull changes from remote (fetch + merge)
1788    pub fn pull(&self, branch: &str) -> Result<()> {
1789        tracing::debug!("Pulling branch: {}", branch);
1790
1791        // First fetch - this now includes TLS fallback
1792        match self.fetch() {
1793            Ok(_) => {}
1794            Err(e) => {
1795                // If fetch failed even with CLI fallback, try full git pull as last resort
1796                let error_string = e.to_string();
1797                if error_string.contains("TLS stream") || error_string.contains("SSL") {
1798                    tracing::warn!(
1799                        "git2 error detected: {}, falling back to git CLI for pull operation",
1800                        e
1801                    );
1802                    return self.pull_with_git_cli(branch);
1803                }
1804                return Err(e);
1805            }
1806        }
1807
1808        // Get remote tracking branch
1809        let remote_branch_name = format!("origin/{branch}");
1810        let remote_oid = self
1811            .repo
1812            .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
1813            .map_err(|e| {
1814                CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
1815            })?;
1816
1817        let remote_commit = self
1818            .repo
1819            .find_commit(remote_oid)
1820            .map_err(CascadeError::Git)?;
1821
1822        // Get local branch tip (not HEAD — we may be on a different branch)
1823        let local_refname = format!("refs/heads/{branch}");
1824        let local_oid = self
1825            .repo
1826            .refname_to_id(&local_refname)
1827            .map_err(|e| CascadeError::branch(format!("Local branch {branch} not found: {e}")))?;
1828        let head_commit = self
1829            .repo
1830            .find_commit(local_oid)
1831            .map_err(CascadeError::Git)?;
1832
1833        // Check if already up to date
1834        if head_commit.id() == remote_commit.id() {
1835            tracing::debug!("Already up to date");
1836            return Ok(());
1837        }
1838
1839        // Check if we can fast-forward (local is ancestor of remote)
1840        let merge_base_oid = self
1841            .repo
1842            .merge_base(head_commit.id(), remote_commit.id())
1843            .map_err(CascadeError::Git)?;
1844
1845        if merge_base_oid == head_commit.id() {
1846            // Fast-forward: local is direct ancestor of remote, just move pointer
1847            tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());
1848
1849            // Update the branch reference to point to remote commit
1850            self.repo
1851                .reference(&local_refname, remote_oid, true, "pull: Fast-forward")
1852                .map_err(CascadeError::Git)?;
1853
1854            // Only update HEAD and working directory if we're on this branch
1855            let on_this_branch = self
1856                .repo
1857                .head()
1858                .ok()
1859                .and_then(|h| h.shorthand().map(|s| s.to_string()))
1860                .as_deref()
1861                == Some(branch);
1862
1863            if on_this_branch {
1864                self.repo
1865                    .set_head(&local_refname)
1866                    .map_err(CascadeError::Git)?;
1867                self.repo
1868                    .checkout_head(Some(
1869                        git2::build::CheckoutBuilder::new()
1870                            .force()
1871                            .remove_untracked(false),
1872                    ))
1873                    .map_err(CascadeError::Git)?;
1874            }
1875
1876            tracing::debug!("Fast-forwarded to {}", remote_commit.id());
1877            return Ok(());
1878        }
1879
1880        // If we can't fast-forward, the local branch has diverged
1881        // This should NOT happen on protected branches!
1882        Err(CascadeError::branch(format!(
1883            "Branch '{}' has diverged from remote. Local has commits not in remote. \
1884             Protected branches should not have local commits. \
1885             Try: git reset --hard origin/{}",
1886            branch, branch
1887        )))
1888    }
1889
1890    /// Push current branch to remote
1891    pub fn push(&self, branch: &str) -> Result<()> {
1892        // Pushing branch to remote
1893
1894        let mut remote = self
1895            .repo
1896            .find_remote("origin")
1897            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1898
1899        let remote_url = remote.url().unwrap_or("unknown").to_string();
1900        tracing::debug!("Remote URL: {}", remote_url);
1901
1902        let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1903        tracing::debug!("Push refspec: {}", refspec);
1904
1905        // Configure callbacks with enhanced SSL settings and error handling
1906        let mut callbacks = self.configure_remote_callbacks()?;
1907
1908        // Add enhanced progress and error callbacks for better debugging
1909        callbacks.push_update_reference(|refname, status| {
1910            if let Some(msg) = status {
1911                tracing::debug!("Push failed for ref {}: {}", refname, msg);
1912                return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1913            }
1914            tracing::debug!("Push succeeded for ref: {}", refname);
1915            Ok(())
1916        });
1917
1918        // Push options with authentication and SSL config
1919        let mut push_options = git2::PushOptions::new();
1920        push_options.remote_callbacks(callbacks);
1921
1922        // Attempt push with enhanced error reporting
1923        match remote.push(&[&refspec], Some(&mut push_options)) {
1924            Ok(_) => {
1925                tracing::debug!("Push completed successfully for branch: {}", branch);
1926                Ok(())
1927            }
1928            Err(e) => {
1929                tracing::debug!(
1930                    "git2 push error: {} (class: {:?}, code: {:?})",
1931                    e,
1932                    e.class(),
1933                    e.code()
1934                );
1935
1936                if self.should_retry_with_default_credentials(&e) {
1937                    tracing::debug!(
1938                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1939                        e.class(), e.code(), e
1940                    );
1941
1942                    // Retry with DefaultCredentials for corporate networks
1943                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1944                    let mut push_options = git2::PushOptions::new();
1945                    push_options.remote_callbacks(callbacks);
1946
1947                    match remote.push(&[&refspec], Some(&mut push_options)) {
1948                        Ok(_) => {
1949                            tracing::debug!("Push succeeded with DefaultCredentials");
1950                            return Ok(());
1951                        }
1952                        Err(retry_error) => {
1953                            tracing::debug!(
1954                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1955                                retry_error
1956                            );
1957                            return self.push_with_git_cli(branch);
1958                        }
1959                    }
1960                }
1961
1962                if self.should_fallback_to_git_cli(&e) {
1963                    tracing::debug!(
1964                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
1965                        e.class(), e.code(), e
1966                    );
1967                    return self.push_with_git_cli(branch);
1968                }
1969
1970                // Create concise error message
1971                let error_msg = if e.to_string().contains("authentication") {
1972                    format!(
1973                        "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1974                    )
1975                } else {
1976                    format!("Failed to push branch '{branch}': {e}")
1977                };
1978
1979                Err(CascadeError::branch(error_msg))
1980            }
1981        }
1982    }
1983
1984    /// Fallback push method using git CLI instead of git2
1985    /// This is used when git2 has TLS/SSL or auth issues but git CLI works fine
1986    fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1987        // Ensure index is closed before CLI command
1988        self.ensure_index_closed()?;
1989
1990        let output = std::process::Command::new("git")
1991            .args(["push", "origin", branch])
1992            .current_dir(&self.path)
1993            .output()
1994            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1995
1996        if output.status.success() {
1997            // Silent success - no need to log when fallback works
1998            Ok(())
1999        } else {
2000            let stderr = String::from_utf8_lossy(&output.stderr);
2001            let _stdout = String::from_utf8_lossy(&output.stdout);
2002            // Extract the most relevant error message
2003            let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
2004                "Network error: Unable to connect to repository (VPN may be required)".to_string()
2005            } else if stderr.contains("repository") && stderr.contains("not found") {
2006                "Repository not found - check your Bitbucket configuration".to_string()
2007            } else if stderr.contains("authentication") || stderr.contains("403") {
2008                "Authentication failed - check your credentials".to_string()
2009            } else {
2010                // For other errors, just show the stderr without the verbose prefix
2011                stderr.trim().to_string()
2012            };
2013            Err(CascadeError::branch(error_msg))
2014        }
2015    }
2016
2017    /// Fallback fetch method using git CLI instead of git2
2018    /// This is used when git2 has TLS/SSL issues but git CLI works fine
2019    fn fetch_with_git_cli(&self) -> Result<()> {
2020        tracing::debug!("Using git CLI fallback for fetch operation");
2021
2022        // Ensure index is closed before CLI command
2023        self.ensure_index_closed()?;
2024
2025        let output = std::process::Command::new("git")
2026            .args(["fetch", "origin"])
2027            .current_dir(&self.path)
2028            .output()
2029            .map_err(|e| {
2030                CascadeError::Git(git2::Error::from_str(&format!(
2031                    "Failed to execute git command: {e}"
2032                )))
2033            })?;
2034
2035        if output.status.success() {
2036            tracing::debug!("Git CLI fetch succeeded");
2037            Ok(())
2038        } else {
2039            let stderr = String::from_utf8_lossy(&output.stderr);
2040            let stdout = String::from_utf8_lossy(&output.stdout);
2041            let error_msg = format!(
2042                "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
2043                output.status, stdout, stderr
2044            );
2045            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
2046        }
2047    }
2048
2049    /// Fallback pull method using git CLI instead of git2
2050    /// This is used when git2 has TLS/SSL issues but git CLI works fine
2051    fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
2052        tracing::debug!("Using git CLI fallback for pull operation: {}", branch);
2053
2054        // Ensure index is closed before CLI command
2055        self.ensure_index_closed()?;
2056
2057        let output = std::process::Command::new("git")
2058            .args(["pull", "origin", branch])
2059            .current_dir(&self.path)
2060            .output()
2061            .map_err(|e| {
2062                CascadeError::Git(git2::Error::from_str(&format!(
2063                    "Failed to execute git command: {e}"
2064                )))
2065            })?;
2066
2067        if output.status.success() {
2068            tracing::debug!("Git CLI pull succeeded for branch: {}", branch);
2069            Ok(())
2070        } else {
2071            let stderr = String::from_utf8_lossy(&output.stderr);
2072            let stdout = String::from_utf8_lossy(&output.stdout);
2073            let error_msg = format!(
2074                "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
2075                branch, output.status, stdout, stderr
2076            );
2077            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
2078        }
2079    }
2080
2081    /// Fallback force push method using git CLI instead of git2
2082    /// This is used when git2 has TLS/SSL issues but git CLI works fine
2083    fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
2084        tracing::debug!(
2085            "Using git CLI fallback for force push operation: {}",
2086            branch
2087        );
2088
2089        let output = std::process::Command::new("git")
2090            .args(["push", "--force", "origin", branch])
2091            .current_dir(&self.path)
2092            .output()
2093            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
2094
2095        if output.status.success() {
2096            tracing::debug!("Git CLI force push succeeded for branch: {}", branch);
2097            Ok(())
2098        } else {
2099            let stderr = String::from_utf8_lossy(&output.stderr);
2100            let stdout = String::from_utf8_lossy(&output.stdout);
2101            let error_msg = format!(
2102                "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
2103                branch, output.status, stdout, stderr
2104            );
2105            Err(CascadeError::branch(error_msg))
2106        }
2107    }
2108
2109    /// Delete a local branch
2110    pub fn delete_branch(&self, name: &str) -> Result<()> {
2111        self.delete_branch_with_options(name, false)
2112    }
2113
2114    /// Delete a local branch with force option to bypass safety checks
2115    pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
2116        self.delete_branch_with_options(name, true)
2117    }
2118
2119    /// Internal branch deletion implementation with safety options
2120    fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
2121        debug!("Attempting to delete branch: {}", name);
2122
2123        // Enhanced safety check: Detect unpushed commits before deletion
2124        if !force_unsafe {
2125            let safety_result = self.check_branch_deletion_safety(name)?;
2126            if let Some(safety_info) = safety_result {
2127                // Branch has unpushed commits, get user confirmation
2128                self.handle_branch_deletion_confirmation(name, &safety_info)?;
2129            }
2130        }
2131
2132        let mut branch = self
2133            .repo
2134            .find_branch(name, git2::BranchType::Local)
2135            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
2136
2137        branch
2138            .delete()
2139            .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
2140
2141        debug!("Successfully deleted branch '{}'", name);
2142        Ok(())
2143    }
2144
2145    /// Get commits between two references
2146    pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
2147        let from_oid = self
2148            .repo
2149            .refname_to_id(&format!("refs/heads/{from}"))
2150            .or_else(|_| Oid::from_str(from))
2151            .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
2152
2153        let to_oid = self
2154            .repo
2155            .refname_to_id(&format!("refs/heads/{to}"))
2156            .or_else(|_| Oid::from_str(to))
2157            .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
2158
2159        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2160
2161        revwalk.push(to_oid).map_err(CascadeError::Git)?;
2162        revwalk.hide(from_oid).map_err(CascadeError::Git)?;
2163
2164        let mut commits = Vec::new();
2165        for oid in revwalk {
2166            let oid = oid.map_err(CascadeError::Git)?;
2167            let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
2168            commits.push(commit);
2169        }
2170
2171        Ok(commits)
2172    }
2173
2174    /// Force push one branch's content to another branch name
2175    /// This is used to preserve PR history while updating branch contents after rebase
2176    pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
2177        self.force_push_branch_with_options(target_branch, source_branch, false)
2178    }
2179
2180    /// Force push with explicit force flag to bypass safety checks
2181    pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
2182        self.force_push_branch_with_options(target_branch, source_branch, true)
2183    }
2184
2185    /// Internal force push implementation with safety options
2186    fn force_push_branch_with_options(
2187        &self,
2188        target_branch: &str,
2189        source_branch: &str,
2190        force_unsafe: bool,
2191    ) -> Result<()> {
2192        debug!(
2193            "Force pushing {} content to {} to preserve PR history",
2194            source_branch, target_branch
2195        );
2196
2197        // Enhanced safety check: Detect potential data loss and get user confirmation
2198        if !force_unsafe {
2199            let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
2200            if let Some(backup_info) = safety_result {
2201                // Create backup branch before force push
2202                self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
2203                Output::sub_item(format!(
2204                    "Created backup branch: {}",
2205                    backup_info.backup_branch_name
2206                ));
2207            }
2208        }
2209
2210        // First, ensure we have the latest changes for the source branch
2211        let source_ref = self
2212            .repo
2213            .find_reference(&format!("refs/heads/{source_branch}"))
2214            .map_err(|e| {
2215                CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
2216            })?;
2217        let _source_commit = source_ref.peel_to_commit().map_err(|e| {
2218            CascadeError::config(format!(
2219                "Failed to get commit for source branch {source_branch}: {e}"
2220            ))
2221        })?;
2222
2223        // Force push to remote without modifying local target branch
2224        let mut remote = self
2225            .repo
2226            .find_remote("origin")
2227            .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
2228
2229        // Push source branch content to remote target branch
2230        let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");
2231
2232        // Configure callbacks with SSL settings from git config
2233        let callbacks = self.configure_remote_callbacks()?;
2234
2235        // Push options for force push with SSL config
2236        let mut push_options = git2::PushOptions::new();
2237        push_options.remote_callbacks(callbacks);
2238
2239        match remote.push(&[&refspec], Some(&mut push_options)) {
2240            Ok(_) => {}
2241            Err(e) => {
2242                if self.should_retry_with_default_credentials(&e) {
2243                    tracing::debug!(
2244                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
2245                        e.class(), e.code(), e
2246                    );
2247
2248                    // Retry with DefaultCredentials for corporate networks
2249                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
2250                    let mut push_options = git2::PushOptions::new();
2251                    push_options.remote_callbacks(callbacks);
2252
2253                    match remote.push(&[&refspec], Some(&mut push_options)) {
2254                        Ok(_) => {
2255                            tracing::debug!("Force push succeeded with DefaultCredentials");
2256                            // Success - continue to normal success path
2257                        }
2258                        Err(retry_error) => {
2259                            tracing::debug!(
2260                                "DefaultCredentials retry failed: {}, falling back to git CLI",
2261                                retry_error
2262                            );
2263                            return self.force_push_with_git_cli(target_branch);
2264                        }
2265                    }
2266                } else if self.should_fallback_to_git_cli(&e) {
2267                    tracing::debug!(
2268                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
2269                        e.class(), e.code(), e
2270                    );
2271                    return self.force_push_with_git_cli(target_branch);
2272                } else {
2273                    return Err(CascadeError::config(format!(
2274                        "Failed to force push {target_branch}: {e}"
2275                    )));
2276                }
2277            }
2278        }
2279
2280        tracing::debug!(
2281            "Successfully force pushed {} to preserve PR history",
2282            target_branch
2283        );
2284        Ok(())
2285    }
2286
2287    /// Enhanced safety check for force push operations with user confirmation
2288    /// Returns backup info if data would be lost and user confirms
2289    fn check_force_push_safety_enhanced(
2290        &self,
2291        target_branch: &str,
2292    ) -> Result<Option<ForceBackupInfo>> {
2293        // First fetch latest remote changes to ensure we have up-to-date information
2294        match self.fetch() {
2295            Ok(_) => {}
2296            Err(e) => {
2297                // If fetch fails, warn but don't block the operation
2298                debug!("Could not fetch latest changes for safety check: {}", e);
2299            }
2300        }
2301
2302        // Check if there are commits on the remote that would be lost
2303        let remote_ref = format!("refs/remotes/origin/{target_branch}");
2304        let local_ref = format!("refs/heads/{target_branch}");
2305
2306        // Try to find both local and remote references
2307        let local_commit = match self.repo.find_reference(&local_ref) {
2308            Ok(reference) => reference.peel_to_commit().ok(),
2309            Err(_) => None,
2310        };
2311
2312        let remote_commit = match self.repo.find_reference(&remote_ref) {
2313            Ok(reference) => reference.peel_to_commit().ok(),
2314            Err(_) => None,
2315        };
2316
2317        // If we have both commits, check for divergence
2318        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2319            if local.id() != remote.id() {
2320                // Check if the remote has commits that the local doesn't have
2321                let merge_base_oid = self
2322                    .repo
2323                    .merge_base(local.id(), remote.id())
2324                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2325
2326                // If merge base != remote commit, remote has commits that would be lost
2327                if merge_base_oid != remote.id() {
2328                    let commits_to_lose = self.count_commits_between(
2329                        &merge_base_oid.to_string(),
2330                        &remote.id().to_string(),
2331                    )?;
2332
2333                    // Create backup branch name with timestamp
2334                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2335                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2336
2337                    debug!(
2338                        "Force push to '{}' would overwrite {} commits on remote",
2339                        target_branch, commits_to_lose
2340                    );
2341
2342                    // Check if we're in a non-interactive environment (CI/testing)
2343                    if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
2344                    {
2345                        info!(
2346                            "Non-interactive environment detected, proceeding with backup creation"
2347                        );
2348                        return Ok(Some(ForceBackupInfo {
2349                            backup_branch_name,
2350                            remote_commit_id: remote.id().to_string(),
2351                            commits_that_would_be_lost: commits_to_lose,
2352                        }));
2353                    }
2354
2355                    // Automatically create backup - this is normal stacked diff workflow
2356                    return Ok(Some(ForceBackupInfo {
2357                        backup_branch_name,
2358                        remote_commit_id: remote.id().to_string(),
2359                        commits_that_would_be_lost: commits_to_lose,
2360                    }));
2361                }
2362            }
2363        }
2364
2365        Ok(None)
2366    }
2367
2368    /// Check force push safety without user confirmation (auto-creates backup)
2369    /// Used for automated operations like sync where user already confirmed the operation
2370    ///
2371    /// When skip_fetch=false: Fetches latest remote state before checking (default behavior)
2372    /// When skip_fetch=true: Assumes fetch already done (batch operations)
2373    fn check_force_push_safety_auto_no_fetch(
2374        &self,
2375        target_branch: &str,
2376    ) -> Result<Option<ForceBackupInfo>> {
2377        // Check if there are commits on the remote that would be lost
2378        let remote_ref = format!("refs/remotes/origin/{target_branch}");
2379        let local_ref = format!("refs/heads/{target_branch}");
2380
2381        // Try to find both local and remote references
2382        let local_commit = match self.repo.find_reference(&local_ref) {
2383            Ok(reference) => reference.peel_to_commit().ok(),
2384            Err(_) => None,
2385        };
2386
2387        let remote_commit = match self.repo.find_reference(&remote_ref) {
2388            Ok(reference) => reference.peel_to_commit().ok(),
2389            Err(_) => None,
2390        };
2391
2392        // If we have both commits, check for divergence
2393        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2394            if local.id() != remote.id() {
2395                // Check if the remote has commits that the local doesn't have
2396                let merge_base_oid = self
2397                    .repo
2398                    .merge_base(local.id(), remote.id())
2399                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2400
2401                // If merge base != remote commit, remote has commits that would be lost
2402                if merge_base_oid != remote.id() {
2403                    let commits_to_lose = self.count_commits_between(
2404                        &merge_base_oid.to_string(),
2405                        &remote.id().to_string(),
2406                    )?;
2407
2408                    // Create backup branch name with timestamp
2409                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2410                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2411
2412                    tracing::debug!(
2413                        "Auto-creating backup '{}' for force push to '{}' (would overwrite {} commits)",
2414                        backup_branch_name, target_branch, commits_to_lose
2415                    );
2416
2417                    // Automatically create backup without confirmation
2418                    return Ok(Some(ForceBackupInfo {
2419                        backup_branch_name,
2420                        remote_commit_id: remote.id().to_string(),
2421                        commits_that_would_be_lost: commits_to_lose,
2422                    }));
2423                }
2424            }
2425        }
2426
2427        Ok(None)
2428    }
2429
2430    /// Create a backup branch pointing to the remote commit that would be lost
2431    fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
2432        let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2433        let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
2434
2435        // Parse the commit ID
2436        let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
2437            CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
2438        })?;
2439
2440        // Find the commit
2441        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
2442            CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
2443        })?;
2444
2445        // Create the backup branch
2446        self.repo
2447            .branch(&backup_branch_name, &commit, false)
2448            .map_err(|e| {
2449                CascadeError::config(format!(
2450                    "Failed to create backup branch {backup_branch_name}: {e}"
2451                ))
2452            })?;
2453
2454        debug!(
2455            "Created backup branch '{}' pointing to {}",
2456            backup_branch_name,
2457            &remote_commit_id[..8]
2458        );
2459        Ok(())
2460    }
2461
2462    /// Check if branch deletion is safe by detecting unpushed commits
2463    /// Returns safety info if there are concerns that need user attention
2464    fn check_branch_deletion_safety(
2465        &self,
2466        branch_name: &str,
2467    ) -> Result<Option<BranchDeletionSafety>> {
2468        // First, try to fetch latest remote changes
2469        match self.fetch() {
2470            Ok(_) => {}
2471            Err(e) => {
2472                warn!(
2473                    "Could not fetch latest changes for branch deletion safety check: {}",
2474                    e
2475                );
2476            }
2477        }
2478
2479        // Find the branch
2480        let branch = self
2481            .repo
2482            .find_branch(branch_name, git2::BranchType::Local)
2483            .map_err(|e| {
2484                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2485            })?;
2486
2487        let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
2488            CascadeError::branch(format!(
2489                "Could not get commit for branch '{branch_name}': {e}"
2490            ))
2491        })?;
2492
2493        // Determine the main branch (try common names)
2494        let main_branch_name = self.detect_main_branch()?;
2495
2496        // Check if branch is merged to main
2497        let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
2498
2499        // Find the upstream/remote tracking branch
2500        let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
2501
2502        let mut unpushed_commits = Vec::new();
2503
2504        // Check for unpushed commits compared to remote tracking branch
2505        if let Some(ref remote_branch) = remote_tracking_branch {
2506            match self.get_commits_between(remote_branch, branch_name) {
2507                Ok(commits) => {
2508                    unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2509                }
2510                Err(_) => {
2511                    // If we can't compare with remote, check against main branch
2512                    if !is_merged_to_main {
2513                        if let Ok(commits) =
2514                            self.get_commits_between(&main_branch_name, branch_name)
2515                        {
2516                            unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2517                        }
2518                    }
2519                }
2520            }
2521        } else if !is_merged_to_main {
2522            // No remote tracking branch, check against main
2523            if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
2524                unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2525            }
2526        }
2527
2528        // If there are concerns, return safety info
2529        if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
2530        {
2531            Ok(Some(BranchDeletionSafety {
2532                unpushed_commits,
2533                remote_tracking_branch,
2534                is_merged_to_main,
2535                main_branch_name,
2536            }))
2537        } else {
2538            Ok(None)
2539        }
2540    }
2541
2542    /// Handle user confirmation for branch deletion with safety concerns
2543    fn handle_branch_deletion_confirmation(
2544        &self,
2545        branch_name: &str,
2546        safety_info: &BranchDeletionSafety,
2547    ) -> Result<()> {
2548        // Check if we're in a non-interactive environment
2549        if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
2550            return Err(CascadeError::branch(
2551                format!(
2552                    "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
2553                    safety_info.unpushed_commits.len()
2554                )
2555            ));
2556        }
2557
2558        // Interactive warning and confirmation
2559        println!();
2560        Output::warning("BRANCH DELETION WARNING");
2561        println!("Branch '{branch_name}' has potential issues:");
2562
2563        if !safety_info.unpushed_commits.is_empty() {
2564            println!(
2565                "\n🔍 Unpushed commits ({} total):",
2566                safety_info.unpushed_commits.len()
2567            );
2568
2569            // Show details of unpushed commits
2570            for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
2571                if let Ok(oid) = Oid::from_str(commit_id) {
2572                    if let Ok(commit) = self.repo.find_commit(oid) {
2573                        let short_hash = &commit_id[..8];
2574                        let summary = commit.summary().unwrap_or("<no message>");
2575                        println!("  {}. {} - {}", i + 1, short_hash, summary);
2576                    }
2577                }
2578            }
2579
2580            if safety_info.unpushed_commits.len() > 5 {
2581                println!(
2582                    "  ... and {} more commits",
2583                    safety_info.unpushed_commits.len() - 5
2584                );
2585            }
2586        }
2587
2588        if !safety_info.is_merged_to_main {
2589            println!();
2590            crate::cli::output::Output::section("Branch status");
2591            crate::cli::output::Output::bullet(format!(
2592                "Not merged to '{}'",
2593                safety_info.main_branch_name
2594            ));
2595            if let Some(ref remote) = safety_info.remote_tracking_branch {
2596                crate::cli::output::Output::bullet(format!("Remote tracking branch: {remote}"));
2597            } else {
2598                crate::cli::output::Output::bullet("No remote tracking branch");
2599            }
2600        }
2601
2602        println!();
2603        crate::cli::output::Output::section("Safer alternatives");
2604        if !safety_info.unpushed_commits.is_empty() {
2605            if let Some(ref _remote) = safety_info.remote_tracking_branch {
2606                println!("  • Push commits first: git push origin {branch_name}");
2607            } else {
2608                println!("  • Create and push to remote: git push -u origin {branch_name}");
2609            }
2610        }
2611        if !safety_info.is_merged_to_main {
2612            println!(
2613                "  • Merge to {} first: git checkout {} && git merge {branch_name}",
2614                safety_info.main_branch_name, safety_info.main_branch_name
2615            );
2616        }
2617
2618        let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2619            .with_prompt("Do you want to proceed with deleting this branch?")
2620            .default(false)
2621            .interact()
2622            .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
2623
2624        if !confirmed {
2625            return Err(CascadeError::branch(
2626                "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
2627            ));
2628        }
2629
2630        Ok(())
2631    }
2632
2633    /// Detect the main branch name (main, master, develop)
2634    pub fn detect_main_branch(&self) -> Result<String> {
2635        let main_candidates = ["main", "master", "develop", "trunk"];
2636
2637        for candidate in &main_candidates {
2638            if self
2639                .repo
2640                .find_branch(candidate, git2::BranchType::Local)
2641                .is_ok()
2642            {
2643                return Ok(candidate.to_string());
2644            }
2645        }
2646
2647        // Fallback to HEAD's target if it's a symbolic reference
2648        if let Ok(head) = self.repo.head() {
2649            if let Some(name) = head.shorthand() {
2650                return Ok(name.to_string());
2651            }
2652        }
2653
2654        // Final fallback
2655        Ok("main".to_string())
2656    }
2657
2658    /// Check if a branch is merged to the main branch
2659    fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
2660        // Get the commits between main and the branch
2661        match self.get_commits_between(main_branch, branch_name) {
2662            Ok(commits) => Ok(commits.is_empty()),
2663            Err(_) => {
2664                // If we can't determine, assume not merged for safety
2665                Ok(false)
2666            }
2667        }
2668    }
2669
2670    /// Get the remote tracking branch for a local branch
2671    fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
2672        // Try common remote tracking branch patterns
2673        let remote_candidates = [
2674            format!("origin/{branch_name}"),
2675            format!("remotes/origin/{branch_name}"),
2676        ];
2677
2678        for candidate in &remote_candidates {
2679            if self
2680                .repo
2681                .find_reference(&format!(
2682                    "refs/remotes/{}",
2683                    candidate.replace("remotes/", "")
2684                ))
2685                .is_ok()
2686            {
2687                return Some(candidate.clone());
2688            }
2689        }
2690
2691        None
2692    }
2693
2694    /// Check if checkout operation is safe
2695    fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
2696        // Check if there are uncommitted changes
2697        let is_dirty = self.is_dirty()?;
2698        if !is_dirty {
2699            // No uncommitted changes, checkout is safe
2700            return Ok(None);
2701        }
2702
2703        // Get current branch for context
2704        let current_branch = self.get_current_branch().ok();
2705
2706        // Get detailed information about uncommitted changes
2707        let modified_files = self.get_modified_files()?;
2708        let staged_files = self.get_staged_files()?;
2709        let untracked_files = self.get_untracked_files()?;
2710
2711        let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
2712
2713        if has_uncommitted_changes || !untracked_files.is_empty() {
2714            return Ok(Some(CheckoutSafety {
2715                has_uncommitted_changes,
2716                modified_files,
2717                staged_files,
2718                untracked_files,
2719                stash_created: None,
2720                current_branch,
2721            }));
2722        }
2723
2724        Ok(None)
2725    }
2726
2727    /// Handle user confirmation for checkout operations with uncommitted changes
2728    fn handle_checkout_confirmation(
2729        &self,
2730        target: &str,
2731        safety_info: &CheckoutSafety,
2732    ) -> Result<()> {
2733        // Check if we're in a non-interactive environment FIRST (before any output)
2734        let is_ci = std::env::var("CI").is_ok();
2735        let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
2736        let is_non_interactive = is_ci || no_confirm;
2737
2738        if is_non_interactive {
2739            return Err(CascadeError::branch(
2740                format!(
2741                    "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
2742                )
2743            ));
2744        }
2745
2746        // Interactive warning and confirmation
2747        println!("\nCHECKOUT WARNING");
2748        println!("Attempting to checkout: {}", target);
2749        println!("You have uncommitted changes that could be lost:");
2750
2751        if !safety_info.modified_files.is_empty() {
2752            println!("\nModified files ({}):", safety_info.modified_files.len());
2753            for file in safety_info.modified_files.iter().take(10) {
2754                println!("   - {file}");
2755            }
2756            if safety_info.modified_files.len() > 10 {
2757                println!("   ... and {} more", safety_info.modified_files.len() - 10);
2758            }
2759        }
2760
2761        if !safety_info.staged_files.is_empty() {
2762            println!("\nStaged files ({}):", safety_info.staged_files.len());
2763            for file in safety_info.staged_files.iter().take(10) {
2764                println!("   - {file}");
2765            }
2766            if safety_info.staged_files.len() > 10 {
2767                println!("   ... and {} more", safety_info.staged_files.len() - 10);
2768            }
2769        }
2770
2771        if !safety_info.untracked_files.is_empty() {
2772            println!("\nUntracked files ({}):", safety_info.untracked_files.len());
2773            for file in safety_info.untracked_files.iter().take(5) {
2774                println!("   - {file}");
2775            }
2776            if safety_info.untracked_files.len() > 5 {
2777                println!("   ... and {} more", safety_info.untracked_files.len() - 5);
2778            }
2779        }
2780
2781        println!("\nOptions:");
2782        println!("1. Stash changes and checkout (recommended)");
2783        println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
2784        println!("3. Cancel checkout");
2785
2786        // Use proper selection dialog instead of y/n confirmation
2787        let selection = Select::with_theme(&ColorfulTheme::default())
2788            .with_prompt("Choose an action")
2789            .items(&[
2790                "Stash changes and checkout (recommended)",
2791                "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
2792                "Cancel checkout",
2793            ])
2794            .default(0)
2795            .interact()
2796            .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;
2797
2798        match selection {
2799            0 => {
2800                // Option 1: Stash changes and checkout
2801                let stash_message = format!(
2802                    "Auto-stash before checkout to {} at {}",
2803                    target,
2804                    chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
2805                );
2806
2807                match self.create_stash(&stash_message) {
2808                    Ok(stash_id) => {
2809                        crate::cli::output::Output::success(format!(
2810                            "Created stash: {stash_message} ({stash_id})"
2811                        ));
2812                        crate::cli::output::Output::tip("You can restore with: git stash pop");
2813                    }
2814                    Err(e) => {
2815                        crate::cli::output::Output::error(format!("Failed to create stash: {e}"));
2816
2817                        // If stash failed, provide better options
2818                        use dialoguer::Select;
2819                        let stash_failed_options = vec![
2820                            "Commit staged changes and proceed",
2821                            "Force checkout (WILL LOSE CHANGES)",
2822                            "Cancel and handle manually",
2823                        ];
2824
2825                        let stash_selection = Select::with_theme(&ColorfulTheme::default())
2826                            .with_prompt("Stash failed. What would you like to do?")
2827                            .items(&stash_failed_options)
2828                            .default(0)
2829                            .interact()
2830                            .map_err(|e| {
2831                                CascadeError::branch(format!("Could not get user selection: {e}"))
2832                            })?;
2833
2834                        match stash_selection {
2835                            0 => {
2836                                // Try to commit staged changes
2837                                let staged_files = self.get_staged_files()?;
2838                                if !staged_files.is_empty() {
2839                                    println!(
2840                                        "📝 Committing {} staged files...",
2841                                        staged_files.len()
2842                                    );
2843                                    match self
2844                                        .commit_staged_changes("WIP: Auto-commit before checkout")
2845                                    {
2846                                        Ok(Some(commit_hash)) => {
2847                                            crate::cli::output::Output::success(format!(
2848                                                "Committed staged changes as {}",
2849                                                &commit_hash[..8]
2850                                            ));
2851                                            crate::cli::output::Output::tip(
2852                                                "You can undo with: git reset HEAD~1",
2853                                            );
2854                                        }
2855                                        Ok(None) => {
2856                                            crate::cli::output::Output::info(
2857                                                "No staged changes found to commit",
2858                                            );
2859                                        }
2860                                        Err(commit_err) => {
2861                                            println!(
2862                                                "❌ Failed to commit staged changes: {commit_err}"
2863                                            );
2864                                            return Err(CascadeError::branch(
2865                                                "Could not commit staged changes".to_string(),
2866                                            ));
2867                                        }
2868                                    }
2869                                } else {
2870                                    println!("No staged changes to commit");
2871                                }
2872                            }
2873                            1 => {
2874                                // Force checkout anyway
2875                                Output::warning("Proceeding with force checkout - uncommitted changes will be lost!");
2876                            }
2877                            2 => {
2878                                // Cancel
2879                                return Err(CascadeError::branch(
2880                                    "Checkout cancelled. Please handle changes manually and try again.".to_string(),
2881                                ));
2882                            }
2883                            _ => unreachable!(),
2884                        }
2885                    }
2886                }
2887            }
2888            1 => {
2889                // Option 2: Force checkout (lose changes)
2890                Output::warning(
2891                    "Proceeding with force checkout - uncommitted changes will be lost!",
2892                );
2893            }
2894            2 => {
2895                // Option 3: Cancel
2896                return Err(CascadeError::branch(
2897                    "Checkout cancelled by user".to_string(),
2898                ));
2899            }
2900            _ => unreachable!(),
2901        }
2902
2903        Ok(())
2904    }
2905
2906    /// Create a stash with uncommitted changes
2907    fn create_stash(&self, message: &str) -> Result<String> {
2908        use crate::cli::output::Output;
2909
2910        tracing::debug!("Creating stash: {}", message);
2911
2912        // Use git CLI for stashing since git2 stashing is complex and unreliable
2913        let output = std::process::Command::new("git")
2914            .args(["stash", "push", "-m", message])
2915            .current_dir(&self.path)
2916            .output()
2917            .map_err(|e| {
2918                CascadeError::branch(format!("Failed to execute git stash command: {e}"))
2919            })?;
2920
2921        if output.status.success() {
2922            let stdout = String::from_utf8_lossy(&output.stdout);
2923
2924            // Extract stash hash if available (git stash outputs like "Saved working directory and index state WIP on branch: message")
2925            let stash_id = if stdout.contains("Saved working directory") {
2926                // Get the most recent stash ID
2927                let stash_list_output = std::process::Command::new("git")
2928                    .args(["stash", "list", "-n", "1", "--format=%H"])
2929                    .current_dir(&self.path)
2930                    .output()
2931                    .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;
2932
2933                if stash_list_output.status.success() {
2934                    String::from_utf8_lossy(&stash_list_output.stdout)
2935                        .trim()
2936                        .to_string()
2937                } else {
2938                    "stash@{0}".to_string() // fallback
2939                }
2940            } else {
2941                "stash@{0}".to_string() // fallback
2942            };
2943
2944            Output::success(format!("Created stash: {} ({})", message, stash_id));
2945            Output::tip("You can restore with: git stash pop");
2946            Ok(stash_id)
2947        } else {
2948            let stderr = String::from_utf8_lossy(&output.stderr);
2949            let stdout = String::from_utf8_lossy(&output.stdout);
2950
2951            // Check for common stash failure reasons
2952            if stderr.contains("No local changes to save")
2953                || stdout.contains("No local changes to save")
2954            {
2955                return Err(CascadeError::branch("No local changes to save".to_string()));
2956            }
2957
2958            Err(CascadeError::branch(format!(
2959                "Failed to create stash: {}\nStderr: {}\nStdout: {}",
2960                output.status, stderr, stdout
2961            )))
2962        }
2963    }
2964
2965    /// Get modified files in working directory
2966    fn get_modified_files(&self) -> Result<Vec<String>> {
2967        let mut opts = git2::StatusOptions::new();
2968        opts.include_untracked(false).include_ignored(false);
2969
2970        let statuses = self
2971            .repo
2972            .statuses(Some(&mut opts))
2973            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2974
2975        let mut modified_files = Vec::new();
2976        for status in statuses.iter() {
2977            let flags = status.status();
2978            if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
2979            {
2980                if let Some(path) = status.path() {
2981                    modified_files.push(path.to_string());
2982                }
2983            }
2984        }
2985
2986        Ok(modified_files)
2987    }
2988
2989    /// Get staged files in index
2990    pub fn get_staged_files(&self) -> Result<Vec<String>> {
2991        let mut opts = git2::StatusOptions::new();
2992        opts.include_untracked(false).include_ignored(false);
2993
2994        let statuses = self
2995            .repo
2996            .statuses(Some(&mut opts))
2997            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2998
2999        let mut staged_files = Vec::new();
3000        for status in statuses.iter() {
3001            let flags = status.status();
3002            if flags.contains(git2::Status::INDEX_MODIFIED)
3003                || flags.contains(git2::Status::INDEX_NEW)
3004                || flags.contains(git2::Status::INDEX_DELETED)
3005            {
3006                if let Some(path) = status.path() {
3007                    staged_files.push(path.to_string());
3008                }
3009            }
3010        }
3011
3012        Ok(staged_files)
3013    }
3014
3015    /// Count commits between two references
3016    fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
3017        let commits = self.get_commits_between(from, to)?;
3018        Ok(commits.len())
3019    }
3020
3021    /// Resolve a reference (branch name, tag, or commit hash) to a commit
3022    pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
3023        // Try to parse as commit hash first
3024        if let Ok(oid) = Oid::from_str(reference) {
3025            if let Ok(commit) = self.repo.find_commit(oid) {
3026                return Ok(commit);
3027            }
3028        }
3029
3030        // Try to resolve as a reference (branch, tag, etc.)
3031        let obj = self.repo.revparse_single(reference).map_err(|e| {
3032            CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
3033        })?;
3034
3035        obj.peel_to_commit().map_err(|e| {
3036            CascadeError::branch(format!(
3037                "Reference '{reference}' does not point to a commit: {e}"
3038            ))
3039        })
3040    }
3041
3042    /// Reset HEAD to a specific reference (soft reset)
3043    pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
3044        let target_commit = self.resolve_reference(target_ref)?;
3045
3046        self.repo
3047            .reset(target_commit.as_object(), git2::ResetType::Soft, None)
3048            .map_err(CascadeError::Git)?;
3049
3050        Ok(())
3051    }
3052
3053    /// Reset working directory and index to match HEAD (hard reset)
3054    /// This clears all uncommitted changes and staged files
3055    pub fn reset_to_head(&self) -> Result<()> {
3056        tracing::debug!("Resetting working directory and index to HEAD");
3057
3058        let repo_path = self.path();
3059
3060        // Use lock retry wrapper to handle stale locks automatically
3061        crate::utils::git_lock::with_lock_retry(repo_path, || {
3062            let head = self.repo.head()?;
3063            let head_commit = head.peel_to_commit()?;
3064
3065            // Hard reset: resets index and working tree
3066            let mut checkout_builder = git2::build::CheckoutBuilder::new();
3067            checkout_builder.force(); // Force checkout to overwrite any local changes
3068            checkout_builder.remove_untracked(false); // Don't remove untracked files
3069
3070            self.repo.reset(
3071                head_commit.as_object(),
3072                git2::ResetType::Hard,
3073                Some(&mut checkout_builder),
3074            )?;
3075
3076            Ok(())
3077        })?;
3078
3079        tracing::debug!("Successfully reset working directory to HEAD");
3080        Ok(())
3081    }
3082
3083    /// Find which branch contains a specific commit
3084    pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
3085        let oid = Oid::from_str(commit_hash).map_err(|e| {
3086            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
3087        })?;
3088
3089        // Get all local branches
3090        let branches = self
3091            .repo
3092            .branches(Some(git2::BranchType::Local))
3093            .map_err(CascadeError::Git)?;
3094
3095        for branch_result in branches {
3096            let (branch, _) = branch_result.map_err(CascadeError::Git)?;
3097
3098            if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
3099                // Check if this branch contains the commit
3100                if let Ok(branch_head) = branch.get().peel_to_commit() {
3101                    // Walk the commit history from this branch's HEAD
3102                    let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
3103                    revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
3104
3105                    for commit_oid in revwalk {
3106                        let commit_oid = commit_oid.map_err(CascadeError::Git)?;
3107                        if commit_oid == oid {
3108                            return Ok(branch_name.to_string());
3109                        }
3110                    }
3111                }
3112            }
3113        }
3114
3115        // If not found in any branch, might be on current HEAD
3116        Err(CascadeError::branch(format!(
3117            "Commit {commit_hash} not found in any local branch"
3118        )))
3119    }
3120
3121    // Async wrappers for potentially blocking operations
3122
3123    /// Fetch from remote origin (async)
3124    pub async fn fetch_async(&self) -> Result<()> {
3125        let repo_path = self.path.clone();
3126        crate::utils::async_ops::run_git_operation(move || {
3127            let repo = GitRepository::open(&repo_path)?;
3128            repo.fetch()
3129        })
3130        .await
3131    }
3132
3133    /// Pull changes from remote (async)
3134    pub async fn pull_async(&self, branch: &str) -> Result<()> {
3135        let repo_path = self.path.clone();
3136        let branch_name = branch.to_string();
3137        crate::utils::async_ops::run_git_operation(move || {
3138            let repo = GitRepository::open(&repo_path)?;
3139            repo.pull(&branch_name)
3140        })
3141        .await
3142    }
3143
3144    /// Push branch to remote (async)
3145    pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
3146        let repo_path = self.path.clone();
3147        let branch = branch_name.to_string();
3148        crate::utils::async_ops::run_git_operation(move || {
3149            let repo = GitRepository::open(&repo_path)?;
3150            repo.push(&branch)
3151        })
3152        .await
3153    }
3154
3155    /// Cherry-pick commit (async)
3156    pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
3157        let repo_path = self.path.clone();
3158        let hash = commit_hash.to_string();
3159        crate::utils::async_ops::run_git_operation(move || {
3160            let repo = GitRepository::open(&repo_path)?;
3161            repo.cherry_pick(&hash)
3162        })
3163        .await
3164    }
3165
3166    /// Get commit hashes between two refs (async)
3167    pub async fn get_commit_hashes_between_async(
3168        &self,
3169        from: &str,
3170        to: &str,
3171    ) -> Result<Vec<String>> {
3172        let repo_path = self.path.clone();
3173        let from_str = from.to_string();
3174        let to_str = to.to_string();
3175        crate::utils::async_ops::run_git_operation(move || {
3176            let repo = GitRepository::open(&repo_path)?;
3177            let commits = repo.get_commits_between(&from_str, &to_str)?;
3178            Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
3179        })
3180        .await
3181    }
3182
3183    /// Reset a branch to point to a specific commit
3184    pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
3185        info!(
3186            "Resetting branch '{}' to commit {}",
3187            branch_name,
3188            &commit_hash[..8]
3189        );
3190
3191        // Find the target commit
3192        let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
3193            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
3194        })?;
3195
3196        let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
3197            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
3198        })?;
3199
3200        // Find the branch
3201        let _branch = self
3202            .repo
3203            .find_branch(branch_name, git2::BranchType::Local)
3204            .map_err(|e| {
3205                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
3206            })?;
3207
3208        // Update the branch reference to point to the target commit
3209        let branch_ref_name = format!("refs/heads/{branch_name}");
3210        self.repo
3211            .reference(
3212                &branch_ref_name,
3213                target_oid,
3214                true,
3215                &format!("Reset {branch_name} to {commit_hash}"),
3216            )
3217            .map_err(|e| {
3218                CascadeError::branch(format!(
3219                    "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
3220                ))
3221            })?;
3222
3223        tracing::info!(
3224            "Successfully reset branch '{}' to commit {}",
3225            branch_name,
3226            &commit_hash[..8]
3227        );
3228        Ok(())
3229    }
3230
3231    /// Detect the parent branch of the current branch using multiple strategies
3232    pub fn detect_parent_branch(&self) -> Result<Option<String>> {
3233        let current_branch = self.get_current_branch()?;
3234
3235        // Strategy 1: Check if current branch has an upstream tracking branch
3236        if let Ok(Some(upstream)) = self.get_upstream_branch(&current_branch) {
3237            // Extract the branch name from "origin/branch-name" format
3238            if let Some(branch_name) = upstream.split('/').nth(1) {
3239                if self.branch_exists(branch_name) {
3240                    tracing::debug!(
3241                        "Detected parent branch '{}' from upstream tracking",
3242                        branch_name
3243                    );
3244                    return Ok(Some(branch_name.to_string()));
3245                }
3246            }
3247        }
3248
3249        // Strategy 2: Use git's default branch detection
3250        if let Ok(default_branch) = self.detect_main_branch() {
3251            // Don't suggest the current branch as its own parent
3252            if current_branch != default_branch {
3253                tracing::debug!(
3254                    "Detected parent branch '{}' as repository default",
3255                    default_branch
3256                );
3257                return Ok(Some(default_branch));
3258            }
3259        }
3260
3261        // Strategy 3: Find the branch with the most recent common ancestor
3262        // Get all local branches and find the one with the shortest commit distance
3263        if let Ok(branches) = self.list_branches() {
3264            let current_commit = self.get_head_commit()?;
3265            let current_commit_hash = current_commit.id().to_string();
3266            let current_oid = current_commit.id();
3267
3268            let mut best_candidate = None;
3269            let mut best_distance = usize::MAX;
3270
3271            for branch in branches {
3272                // Skip the current branch and any branches that look like version branches
3273                if branch == current_branch
3274                    || branch.contains("-v")
3275                    || branch.ends_with("-v2")
3276                    || branch.ends_with("-v3")
3277                {
3278                    continue;
3279                }
3280
3281                if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
3282                    if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
3283                        // Find merge base between current branch and this branch
3284                        if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
3285                            // Count commits from merge base to current head
3286                            if let Ok(distance) = self.count_commits_between(
3287                                &merge_base_oid.to_string(),
3288                                &current_commit_hash,
3289                            ) {
3290                                // Prefer branches with shorter distances (more recent common ancestor)
3291                                // Also prefer branches that look like base branches
3292                                let is_likely_base = self.is_likely_base_branch(&branch);
3293                                let adjusted_distance = if is_likely_base {
3294                                    distance
3295                                } else {
3296                                    distance + 1000
3297                                };
3298
3299                                if adjusted_distance < best_distance {
3300                                    best_distance = adjusted_distance;
3301                                    best_candidate = Some(branch.clone());
3302                                }
3303                            }
3304                        }
3305                    }
3306                }
3307            }
3308
3309            if let Some(ref candidate) = best_candidate {
3310                tracing::debug!(
3311                    "Detected parent branch '{}' with distance {}",
3312                    candidate,
3313                    best_distance
3314                );
3315            }
3316
3317            return Ok(best_candidate);
3318        }
3319
3320        tracing::debug!("Could not detect parent branch for '{}'", current_branch);
3321        Ok(None)
3322    }
3323
3324    /// Check if a branch name looks like a typical base branch
3325    fn is_likely_base_branch(&self, branch_name: &str) -> bool {
3326        let base_patterns = [
3327            "main",
3328            "master",
3329            "develop",
3330            "dev",
3331            "development",
3332            "staging",
3333            "stage",
3334            "release",
3335            "production",
3336            "prod",
3337        ];
3338
3339        base_patterns.contains(&branch_name)
3340    }
3341}
3342
3343#[cfg(test)]
3344mod tests {
3345    use super::*;
3346    use std::process::Command;
3347    use tempfile::TempDir;
3348
3349    fn create_test_repo() -> (TempDir, PathBuf) {
3350        let temp_dir = TempDir::new().unwrap();
3351        let repo_path = temp_dir.path().to_path_buf();
3352
3353        // Initialize git repository
3354        Command::new("git")
3355            .args(["init"])
3356            .current_dir(&repo_path)
3357            .output()
3358            .unwrap();
3359        Command::new("git")
3360            .args(["config", "user.name", "Test"])
3361            .current_dir(&repo_path)
3362            .output()
3363            .unwrap();
3364        Command::new("git")
3365            .args(["config", "user.email", "test@test.com"])
3366            .current_dir(&repo_path)
3367            .output()
3368            .unwrap();
3369
3370        // Create initial commit
3371        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
3372        Command::new("git")
3373            .args(["add", "."])
3374            .current_dir(&repo_path)
3375            .output()
3376            .unwrap();
3377        Command::new("git")
3378            .args(["commit", "-m", "Initial commit"])
3379            .current_dir(&repo_path)
3380            .output()
3381            .unwrap();
3382
3383        (temp_dir, repo_path)
3384    }
3385
3386    fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
3387        let file_path = repo_path.join(filename);
3388        std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
3389
3390        Command::new("git")
3391            .args(["add", filename])
3392            .current_dir(repo_path)
3393            .output()
3394            .unwrap();
3395        Command::new("git")
3396            .args(["commit", "-m", message])
3397            .current_dir(repo_path)
3398            .output()
3399            .unwrap();
3400    }
3401
3402    #[test]
3403    fn test_repository_info() {
3404        let (_temp_dir, repo_path) = create_test_repo();
3405        let repo = GitRepository::open(&repo_path).unwrap();
3406
3407        let info = repo.get_info().unwrap();
3408        assert!(!info.is_dirty); // Should be clean after commit
3409        assert!(
3410            info.head_branch == Some("master".to_string())
3411                || info.head_branch == Some("main".to_string()),
3412            "Expected default branch to be 'master' or 'main', got {:?}",
3413            info.head_branch
3414        );
3415        assert!(info.head_commit.is_some()); // Just check it exists
3416        assert!(info.untracked_files.is_empty()); // Should be empty after commit
3417    }
3418
3419    #[test]
3420    fn test_force_push_branch_basic() {
3421        let (_temp_dir, repo_path) = create_test_repo();
3422        let repo = GitRepository::open(&repo_path).unwrap();
3423
3424        // Get the actual default branch name
3425        let default_branch = repo.get_current_branch().unwrap();
3426
3427        // Create source branch with commits
3428        create_commit(&repo_path, "Feature commit 1", "feature1.rs");
3429        Command::new("git")
3430            .args(["checkout", "-b", "source-branch"])
3431            .current_dir(&repo_path)
3432            .output()
3433            .unwrap();
3434        create_commit(&repo_path, "Feature commit 2", "feature2.rs");
3435
3436        // Create target branch
3437        Command::new("git")
3438            .args(["checkout", &default_branch])
3439            .current_dir(&repo_path)
3440            .output()
3441            .unwrap();
3442        Command::new("git")
3443            .args(["checkout", "-b", "target-branch"])
3444            .current_dir(&repo_path)
3445            .output()
3446            .unwrap();
3447        create_commit(&repo_path, "Target commit", "target.rs");
3448
3449        // Test force push from source to target
3450        let result = repo.force_push_branch("target-branch", "source-branch");
3451
3452        // Should succeed in test environment (even though it doesn't actually push to remote)
3453        // The important thing is that the function doesn't panic and handles the git2 operations
3454        assert!(result.is_ok() || result.is_err()); // Either is acceptable for unit test
3455    }
3456
3457    #[test]
3458    fn test_force_push_branch_nonexistent_branches() {
3459        let (_temp_dir, repo_path) = create_test_repo();
3460        let repo = GitRepository::open(&repo_path).unwrap();
3461
3462        // Get the actual default branch name
3463        let default_branch = repo.get_current_branch().unwrap();
3464
3465        // Test force push with nonexistent source branch
3466        let result = repo.force_push_branch("target", "nonexistent-source");
3467        assert!(result.is_err());
3468
3469        // Test force push with nonexistent target branch
3470        let result = repo.force_push_branch("nonexistent-target", &default_branch);
3471        assert!(result.is_err());
3472    }
3473
3474    #[test]
3475    fn test_force_push_workflow_simulation() {
3476        let (_temp_dir, repo_path) = create_test_repo();
3477        let repo = GitRepository::open(&repo_path).unwrap();
3478
3479        // Simulate the smart force push workflow:
3480        // 1. Original branch exists with PR
3481        Command::new("git")
3482            .args(["checkout", "-b", "feature-auth"])
3483            .current_dir(&repo_path)
3484            .output()
3485            .unwrap();
3486        create_commit(&repo_path, "Add authentication", "auth.rs");
3487
3488        // 2. Rebase creates versioned branch
3489        Command::new("git")
3490            .args(["checkout", "-b", "feature-auth-v2"])
3491            .current_dir(&repo_path)
3492            .output()
3493            .unwrap();
3494        create_commit(&repo_path, "Fix auth validation", "auth.rs");
3495
3496        // 3. Smart force push: update original branch from versioned branch
3497        let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
3498
3499        // Verify the operation is handled properly (success or expected error)
3500        match result {
3501            Ok(_) => {
3502                // Force push succeeded - verify branch state if possible
3503                Command::new("git")
3504                    .args(["checkout", "feature-auth"])
3505                    .current_dir(&repo_path)
3506                    .output()
3507                    .unwrap();
3508                let log_output = Command::new("git")
3509                    .args(["log", "--oneline", "-2"])
3510                    .current_dir(&repo_path)
3511                    .output()
3512                    .unwrap();
3513                let log_str = String::from_utf8_lossy(&log_output.stdout);
3514                assert!(
3515                    log_str.contains("Fix auth validation")
3516                        || log_str.contains("Add authentication")
3517                );
3518            }
3519            Err(_) => {
3520                // Expected in test environment without remote - that's fine
3521                // The important thing is we tested the code path without panicking
3522            }
3523        }
3524    }
3525
3526    #[test]
3527    fn test_branch_operations() {
3528        let (_temp_dir, repo_path) = create_test_repo();
3529        let repo = GitRepository::open(&repo_path).unwrap();
3530
3531        // Test get current branch - accept either main or master
3532        let current = repo.get_current_branch().unwrap();
3533        assert!(
3534            current == "master" || current == "main",
3535            "Expected default branch to be 'master' or 'main', got '{current}'"
3536        );
3537
3538        // Test create branch
3539        Command::new("git")
3540            .args(["checkout", "-b", "test-branch"])
3541            .current_dir(&repo_path)
3542            .output()
3543            .unwrap();
3544        let current = repo.get_current_branch().unwrap();
3545        assert_eq!(current, "test-branch");
3546    }
3547
3548    #[test]
3549    fn test_commit_operations() {
3550        let (_temp_dir, repo_path) = create_test_repo();
3551        let repo = GitRepository::open(&repo_path).unwrap();
3552
3553        // Test get head commit
3554        let head = repo.get_head_commit().unwrap();
3555        assert_eq!(head.message().unwrap().trim(), "Initial commit");
3556
3557        // Test get commit by hash
3558        let hash = head.id().to_string();
3559        let same_commit = repo.get_commit(&hash).unwrap();
3560        assert_eq!(head.id(), same_commit.id());
3561    }
3562
3563    #[test]
3564    fn test_checkout_safety_clean_repo() {
3565        let (_temp_dir, repo_path) = create_test_repo();
3566        let repo = GitRepository::open(&repo_path).unwrap();
3567
3568        // Create a test branch
3569        create_commit(&repo_path, "Second commit", "test.txt");
3570        Command::new("git")
3571            .args(["checkout", "-b", "test-branch"])
3572            .current_dir(&repo_path)
3573            .output()
3574            .unwrap();
3575
3576        // Test checkout safety with clean repo
3577        let safety_result = repo.check_checkout_safety("main");
3578        assert!(safety_result.is_ok());
3579        assert!(safety_result.unwrap().is_none()); // Clean repo should return None
3580    }
3581
3582    #[test]
3583    fn test_checkout_safety_with_modified_files() {
3584        let (_temp_dir, repo_path) = create_test_repo();
3585        let repo = GitRepository::open(&repo_path).unwrap();
3586
3587        // Create a test branch
3588        Command::new("git")
3589            .args(["checkout", "-b", "test-branch"])
3590            .current_dir(&repo_path)
3591            .output()
3592            .unwrap();
3593
3594        // Modify a file to create uncommitted changes
3595        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3596
3597        // Test checkout safety with modified files
3598        let safety_result = repo.check_checkout_safety("main");
3599        assert!(safety_result.is_ok());
3600        let safety_info = safety_result.unwrap();
3601        assert!(safety_info.is_some());
3602
3603        let info = safety_info.unwrap();
3604        assert!(!info.modified_files.is_empty());
3605        assert!(info.modified_files.contains(&"README.md".to_string()));
3606    }
3607
3608    #[test]
3609    fn test_unsafe_checkout_methods() {
3610        let (_temp_dir, repo_path) = create_test_repo();
3611        let repo = GitRepository::open(&repo_path).unwrap();
3612
3613        // Create a test branch
3614        create_commit(&repo_path, "Second commit", "test.txt");
3615        Command::new("git")
3616            .args(["checkout", "-b", "test-branch"])
3617            .current_dir(&repo_path)
3618            .output()
3619            .unwrap();
3620
3621        // Modify a file to create uncommitted changes
3622        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3623
3624        // Test unsafe checkout methods bypass safety checks
3625        let _result = repo.checkout_branch_unsafe("main");
3626        // Note: This might still fail due to git2 restrictions, but shouldn't hit our safety code
3627        // The important thing is that it doesn't trigger our safety confirmation
3628
3629        // Test unsafe commit checkout
3630        let head_commit = repo.get_head_commit().unwrap();
3631        let commit_hash = head_commit.id().to_string();
3632        let _result = repo.checkout_commit_unsafe(&commit_hash);
3633        // Similar to above - testing that safety is bypassed
3634    }
3635
3636    #[test]
3637    fn test_get_modified_files() {
3638        let (_temp_dir, repo_path) = create_test_repo();
3639        let repo = GitRepository::open(&repo_path).unwrap();
3640
3641        // Initially should have no modified files
3642        let modified = repo.get_modified_files().unwrap();
3643        assert!(modified.is_empty());
3644
3645        // Modify a file
3646        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3647
3648        // Should now detect the modified file
3649        let modified = repo.get_modified_files().unwrap();
3650        assert_eq!(modified.len(), 1);
3651        assert!(modified.contains(&"README.md".to_string()));
3652    }
3653
3654    #[test]
3655    fn test_get_staged_files() {
3656        let (_temp_dir, repo_path) = create_test_repo();
3657        let repo = GitRepository::open(&repo_path).unwrap();
3658
3659        // Initially should have no staged files
3660        let staged = repo.get_staged_files().unwrap();
3661        assert!(staged.is_empty());
3662
3663        // Create and stage a new file
3664        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3665        Command::new("git")
3666            .args(["add", "staged.txt"])
3667            .current_dir(&repo_path)
3668            .output()
3669            .unwrap();
3670
3671        // Should now detect the staged file
3672        let staged = repo.get_staged_files().unwrap();
3673        assert_eq!(staged.len(), 1);
3674        assert!(staged.contains(&"staged.txt".to_string()));
3675    }
3676
3677    #[test]
3678    fn test_create_stash_fallback() {
3679        let (_temp_dir, repo_path) = create_test_repo();
3680        let repo = GitRepository::open(&repo_path).unwrap();
3681
3682        // Test stash creation - newer git versions allow empty stashes
3683        let result = repo.create_stash("test stash");
3684
3685        // Either succeeds (newer git with empty stash) or fails with helpful message
3686        match result {
3687            Ok(stash_id) => {
3688                // Modern git allows empty stashes, verify we got a stash ID
3689                assert!(!stash_id.is_empty());
3690                assert!(stash_id.contains("stash") || stash_id.len() >= 7); // SHA or stash@{n}
3691            }
3692            Err(error) => {
3693                // Older git should fail with helpful message
3694                let error_msg = error.to_string();
3695                assert!(
3696                    error_msg.contains("No local changes to save")
3697                        || error_msg.contains("git stash push")
3698                );
3699            }
3700        }
3701    }
3702
3703    #[test]
3704    fn test_delete_branch_unsafe() {
3705        let (_temp_dir, repo_path) = create_test_repo();
3706        let repo = GitRepository::open(&repo_path).unwrap();
3707
3708        // Create a test branch
3709        create_commit(&repo_path, "Second commit", "test.txt");
3710        Command::new("git")
3711            .args(["checkout", "-b", "test-branch"])
3712            .current_dir(&repo_path)
3713            .output()
3714            .unwrap();
3715
3716        // Add another commit to the test branch to make it different from main
3717        create_commit(&repo_path, "Branch-specific commit", "branch.txt");
3718
3719        // Go back to main
3720        Command::new("git")
3721            .args(["checkout", "main"])
3722            .current_dir(&repo_path)
3723            .output()
3724            .unwrap();
3725
3726        // Test unsafe delete bypasses safety checks
3727        // Note: This may still fail if the branch has unpushed commits, but it should bypass our safety confirmation
3728        let result = repo.delete_branch_unsafe("test-branch");
3729        // Even if it fails, the key is that it didn't prompt for user confirmation
3730        // So we just check that it attempted the operation without interactive prompts
3731        let _ = result; // Don't assert success since delete may fail for git reasons
3732    }
3733
3734    #[test]
3735    fn test_force_push_unsafe() {
3736        let (_temp_dir, repo_path) = create_test_repo();
3737        let repo = GitRepository::open(&repo_path).unwrap();
3738
3739        // Create a test branch
3740        create_commit(&repo_path, "Second commit", "test.txt");
3741        Command::new("git")
3742            .args(["checkout", "-b", "test-branch"])
3743            .current_dir(&repo_path)
3744            .output()
3745            .unwrap();
3746
3747        // Test unsafe force push bypasses safety checks
3748        // Note: This will likely fail due to no remote, but it tests the safety bypass
3749        let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
3750        // The key is that it doesn't trigger safety confirmation dialogs
3751    }
3752
3753    #[test]
3754    fn test_cherry_pick_basic() {
3755        let (_temp_dir, repo_path) = create_test_repo();
3756        let repo = GitRepository::open(&repo_path).unwrap();
3757
3758        // Create a branch with a commit to cherry-pick
3759        repo.create_branch("source", None).unwrap();
3760        repo.checkout_branch("source").unwrap();
3761
3762        std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
3763        Command::new("git")
3764            .args(["add", "."])
3765            .current_dir(&repo_path)
3766            .output()
3767            .unwrap();
3768
3769        Command::new("git")
3770            .args(["commit", "-m", "Cherry commit"])
3771            .current_dir(&repo_path)
3772            .output()
3773            .unwrap();
3774
3775        let cherry_commit = repo.get_head_commit_hash().unwrap();
3776
3777        // Switch back to previous branch (where source was created from)
3778        // Using `git checkout -` is environment-agnostic
3779        Command::new("git")
3780            .args(["checkout", "-"])
3781            .current_dir(&repo_path)
3782            .output()
3783            .unwrap();
3784
3785        repo.create_branch("target", None).unwrap();
3786        repo.checkout_branch("target").unwrap();
3787
3788        // Cherry-pick the commit
3789        let new_commit = repo.cherry_pick(&cherry_commit).unwrap();
3790
3791        // Verify cherry-pick succeeded (commit exists)
3792        repo.repo
3793            .find_commit(git2::Oid::from_str(&new_commit).unwrap())
3794            .unwrap();
3795
3796        // Verify file exists on target branch
3797        assert!(
3798            repo_path.join("cherry.txt").exists(),
3799            "Cherry-picked file should exist"
3800        );
3801
3802        // Verify source branch is unchanged
3803        repo.checkout_branch("source").unwrap();
3804        let source_head = repo.get_head_commit_hash().unwrap();
3805        assert_eq!(
3806            source_head, cherry_commit,
3807            "Source branch should be unchanged"
3808        );
3809    }
3810
3811    #[test]
3812    fn test_cherry_pick_preserves_commit_message() {
3813        let (_temp_dir, repo_path) = create_test_repo();
3814        let repo = GitRepository::open(&repo_path).unwrap();
3815
3816        // Create commit with specific message
3817        repo.create_branch("msg-test", None).unwrap();
3818        repo.checkout_branch("msg-test").unwrap();
3819
3820        std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
3821        Command::new("git")
3822            .args(["add", "."])
3823            .current_dir(&repo_path)
3824            .output()
3825            .unwrap();
3826
3827        let commit_msg = "Test: Special commit message\n\nWith body";
3828        Command::new("git")
3829            .args(["commit", "-m", commit_msg])
3830            .current_dir(&repo_path)
3831            .output()
3832            .unwrap();
3833
3834        let original_commit = repo.get_head_commit_hash().unwrap();
3835
3836        // Cherry-pick to another branch (use previous branch via git checkout -)
3837        Command::new("git")
3838            .args(["checkout", "-"])
3839            .current_dir(&repo_path)
3840            .output()
3841            .unwrap();
3842        let new_commit = repo.cherry_pick(&original_commit).unwrap();
3843
3844        // Get commit message of new commit
3845        let output = Command::new("git")
3846            .args(["log", "-1", "--format=%B", &new_commit])
3847            .current_dir(&repo_path)
3848            .output()
3849            .unwrap();
3850
3851        let new_msg = String::from_utf8_lossy(&output.stdout);
3852        assert!(
3853            new_msg.contains("Special commit message"),
3854            "Should preserve commit message"
3855        );
3856    }
3857
3858    #[test]
3859    fn test_cherry_pick_handles_conflicts() {
3860        let (_temp_dir, repo_path) = create_test_repo();
3861        let repo = GitRepository::open(&repo_path).unwrap();
3862
3863        // Create conflicting content
3864        std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
3865        Command::new("git")
3866            .args(["add", "."])
3867            .current_dir(&repo_path)
3868            .output()
3869            .unwrap();
3870
3871        Command::new("git")
3872            .args(["commit", "-m", "Add conflict file"])
3873            .current_dir(&repo_path)
3874            .output()
3875            .unwrap();
3876
3877        // Create branch with different content
3878        repo.create_branch("conflict-branch", None).unwrap();
3879        repo.checkout_branch("conflict-branch").unwrap();
3880
3881        std::fs::write(repo_path.join("conflict.txt"), "Modified").unwrap();
3882        Command::new("git")
3883            .args(["add", "."])
3884            .current_dir(&repo_path)
3885            .output()
3886            .unwrap();
3887
3888        Command::new("git")
3889            .args(["commit", "-m", "Modify conflict file"])
3890            .current_dir(&repo_path)
3891            .output()
3892            .unwrap();
3893
3894        let conflict_commit = repo.get_head_commit_hash().unwrap();
3895
3896        // Try to cherry-pick (should fail due to conflict)
3897        // Go back to previous branch
3898        Command::new("git")
3899            .args(["checkout", "-"])
3900            .current_dir(&repo_path)
3901            .output()
3902            .unwrap();
3903        std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
3904        Command::new("git")
3905            .args(["add", "."])
3906            .current_dir(&repo_path)
3907            .output()
3908            .unwrap();
3909
3910        Command::new("git")
3911            .args(["commit", "-m", "Different change"])
3912            .current_dir(&repo_path)
3913            .output()
3914            .unwrap();
3915
3916        // Cherry-pick should fail with conflict
3917        let result = repo.cherry_pick(&conflict_commit);
3918        assert!(result.is_err(), "Cherry-pick with conflict should fail");
3919    }
3920
3921    #[test]
3922    fn test_reset_to_head_clears_staged_files() {
3923        let (_temp_dir, repo_path) = create_test_repo();
3924        let repo = GitRepository::open(&repo_path).unwrap();
3925
3926        // Create and stage some files
3927        std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
3928        std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();
3929
3930        Command::new("git")
3931            .args(["add", "staged1.txt", "staged2.txt"])
3932            .current_dir(&repo_path)
3933            .output()
3934            .unwrap();
3935
3936        // Verify files are staged
3937        let staged_before = repo.get_staged_files().unwrap();
3938        assert_eq!(staged_before.len(), 2, "Should have 2 staged files");
3939
3940        // Reset to HEAD
3941        repo.reset_to_head().unwrap();
3942
3943        // Verify no files are staged after reset
3944        let staged_after = repo.get_staged_files().unwrap();
3945        assert_eq!(
3946            staged_after.len(),
3947            0,
3948            "Should have no staged files after reset"
3949        );
3950    }
3951
3952    #[test]
3953    fn test_reset_to_head_clears_modified_files() {
3954        let (_temp_dir, repo_path) = create_test_repo();
3955        let repo = GitRepository::open(&repo_path).unwrap();
3956
3957        // Modify an existing file
3958        std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();
3959
3960        // Stage the modification
3961        Command::new("git")
3962            .args(["add", "README.md"])
3963            .current_dir(&repo_path)
3964            .output()
3965            .unwrap();
3966
3967        // Verify file is modified and staged
3968        assert!(repo.is_dirty().unwrap(), "Repo should be dirty");
3969
3970        // Reset to HEAD
3971        repo.reset_to_head().unwrap();
3972
3973        // Verify repo is clean
3974        assert!(
3975            !repo.is_dirty().unwrap(),
3976            "Repo should be clean after reset"
3977        );
3978
3979        // Verify file content is restored
3980        let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
3981        assert_eq!(
3982            content, "# Test",
3983            "File should be restored to original content"
3984        );
3985    }
3986
3987    #[test]
3988    fn test_reset_to_head_preserves_untracked_files() {
3989        let (_temp_dir, repo_path) = create_test_repo();
3990        let repo = GitRepository::open(&repo_path).unwrap();
3991
3992        // Create untracked file
3993        std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();
3994
3995        // Stage some other file
3996        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3997        Command::new("git")
3998            .args(["add", "staged.txt"])
3999            .current_dir(&repo_path)
4000            .output()
4001            .unwrap();
4002
4003        // Reset to HEAD
4004        repo.reset_to_head().unwrap();
4005
4006        // Verify untracked file still exists
4007        assert!(
4008            repo_path.join("untracked.txt").exists(),
4009            "Untracked file should be preserved"
4010        );
4011
4012        // Verify staged file was removed (since it was never committed)
4013        assert!(
4014            !repo_path.join("staged.txt").exists(),
4015            "Staged but uncommitted file should be removed"
4016        );
4017    }
4018
4019    #[test]
4020    fn test_cherry_pick_does_not_modify_source() {
4021        let (_temp_dir, repo_path) = create_test_repo();
4022        let repo = GitRepository::open(&repo_path).unwrap();
4023
4024        // Create source branch with multiple commits
4025        repo.create_branch("feature", None).unwrap();
4026        repo.checkout_branch("feature").unwrap();
4027
4028        // Add multiple commits
4029        for i in 1..=3 {
4030            std::fs::write(
4031                repo_path.join(format!("file{i}.txt")),
4032                format!("Content {i}"),
4033            )
4034            .unwrap();
4035            Command::new("git")
4036                .args(["add", "."])
4037                .current_dir(&repo_path)
4038                .output()
4039                .unwrap();
4040
4041            Command::new("git")
4042                .args(["commit", "-m", &format!("Commit {i}")])
4043                .current_dir(&repo_path)
4044                .output()
4045                .unwrap();
4046        }
4047
4048        // Get source branch state
4049        let source_commits = Command::new("git")
4050            .args(["log", "--format=%H", "feature"])
4051            .current_dir(&repo_path)
4052            .output()
4053            .unwrap();
4054        let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();
4055
4056        // Cherry-pick middle commit to another branch
4057        let commits: Vec<&str> = source_state.lines().collect();
4058        let middle_commit = commits[1];
4059
4060        // Go back to previous branch
4061        Command::new("git")
4062            .args(["checkout", "-"])
4063            .current_dir(&repo_path)
4064            .output()
4065            .unwrap();
4066        repo.create_branch("target", None).unwrap();
4067        repo.checkout_branch("target").unwrap();
4068
4069        repo.cherry_pick(middle_commit).unwrap();
4070
4071        // Verify source branch is completely unchanged
4072        let after_commits = Command::new("git")
4073            .args(["log", "--format=%H", "feature"])
4074            .current_dir(&repo_path)
4075            .output()
4076            .unwrap();
4077        let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();
4078
4079        assert_eq!(
4080            source_state, after_state,
4081            "Source branch should be completely unchanged after cherry-pick"
4082        );
4083    }
4084
4085    #[test]
4086    fn test_detect_parent_branch() {
4087        let (_temp_dir, repo_path) = create_test_repo();
4088        let repo = GitRepository::open(&repo_path).unwrap();
4089
4090        // Create a custom base branch (not just main/master)
4091        repo.create_branch("dev123", None).unwrap();
4092        repo.checkout_branch("dev123").unwrap();
4093        create_commit(&repo_path, "Base commit on dev123", "base.txt");
4094
4095        // Create feature branch from dev123
4096        repo.create_branch("feature-branch", None).unwrap();
4097        repo.checkout_branch("feature-branch").unwrap();
4098        create_commit(&repo_path, "Feature commit", "feature.txt");
4099
4100        // Should detect dev123 as parent since it's the most recent common ancestor
4101        let detected_parent = repo.detect_parent_branch().unwrap();
4102
4103        // The algorithm should find dev123 through either Strategy 2 (default branch)
4104        // or Strategy 3 (common ancestor analysis)
4105        assert!(detected_parent.is_some(), "Should detect a parent branch");
4106
4107        // Since we can't guarantee which strategy will work in the test environment,
4108        // just verify it returns something reasonable
4109        let parent = detected_parent.unwrap();
4110        assert!(
4111            parent == "dev123" || parent == "main" || parent == "master",
4112            "Parent should be dev123, main, or master, got: {parent}"
4113        );
4114    }
4115}