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 current HEAD
1823        let head_commit = self.get_head_commit()?;
1824
1825        // Check if already up to date
1826        if head_commit.id() == remote_commit.id() {
1827            tracing::debug!("Already up to date");
1828            return Ok(());
1829        }
1830
1831        // Check if we can fast-forward (local is ancestor of remote)
1832        let merge_base_oid = self
1833            .repo
1834            .merge_base(head_commit.id(), remote_commit.id())
1835            .map_err(CascadeError::Git)?;
1836
1837        if merge_base_oid == head_commit.id() {
1838            // Fast-forward: local is direct ancestor of remote, just move pointer
1839            tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());
1840
1841            // Update the branch reference to point to remote commit
1842            let refname = format!("refs/heads/{}", branch);
1843            self.repo
1844                .reference(&refname, remote_oid, true, "pull: Fast-forward")
1845                .map_err(CascadeError::Git)?;
1846
1847            // Update HEAD to point to the new commit
1848            self.repo.set_head(&refname).map_err(CascadeError::Git)?;
1849
1850            // Checkout the new commit (update working directory)
1851            self.repo
1852                .checkout_head(Some(
1853                    git2::build::CheckoutBuilder::new()
1854                        .force()
1855                        .remove_untracked(false),
1856                ))
1857                .map_err(CascadeError::Git)?;
1858
1859            tracing::debug!("Fast-forwarded to {}", remote_commit.id());
1860            return Ok(());
1861        }
1862
1863        // If we can't fast-forward, the local branch has diverged
1864        // This should NOT happen on protected branches!
1865        Err(CascadeError::branch(format!(
1866            "Branch '{}' has diverged from remote. Local has commits not in remote. \
1867             Protected branches should not have local commits. \
1868             Try: git reset --hard origin/{}",
1869            branch, branch
1870        )))
1871    }
1872
1873    /// Push current branch to remote
1874    pub fn push(&self, branch: &str) -> Result<()> {
1875        // Pushing branch to remote
1876
1877        let mut remote = self
1878            .repo
1879            .find_remote("origin")
1880            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1881
1882        let remote_url = remote.url().unwrap_or("unknown").to_string();
1883        tracing::debug!("Remote URL: {}", remote_url);
1884
1885        let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1886        tracing::debug!("Push refspec: {}", refspec);
1887
1888        // Configure callbacks with enhanced SSL settings and error handling
1889        let mut callbacks = self.configure_remote_callbacks()?;
1890
1891        // Add enhanced progress and error callbacks for better debugging
1892        callbacks.push_update_reference(|refname, status| {
1893            if let Some(msg) = status {
1894                tracing::debug!("Push failed for ref {}: {}", refname, msg);
1895                return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1896            }
1897            tracing::debug!("Push succeeded for ref: {}", refname);
1898            Ok(())
1899        });
1900
1901        // Push options with authentication and SSL config
1902        let mut push_options = git2::PushOptions::new();
1903        push_options.remote_callbacks(callbacks);
1904
1905        // Attempt push with enhanced error reporting
1906        match remote.push(&[&refspec], Some(&mut push_options)) {
1907            Ok(_) => {
1908                tracing::debug!("Push completed successfully for branch: {}", branch);
1909                Ok(())
1910            }
1911            Err(e) => {
1912                tracing::debug!(
1913                    "git2 push error: {} (class: {:?}, code: {:?})",
1914                    e,
1915                    e.class(),
1916                    e.code()
1917                );
1918
1919                if self.should_retry_with_default_credentials(&e) {
1920                    tracing::debug!(
1921                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1922                        e.class(), e.code(), e
1923                    );
1924
1925                    // Retry with DefaultCredentials for corporate networks
1926                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1927                    let mut push_options = git2::PushOptions::new();
1928                    push_options.remote_callbacks(callbacks);
1929
1930                    match remote.push(&[&refspec], Some(&mut push_options)) {
1931                        Ok(_) => {
1932                            tracing::debug!("Push succeeded with DefaultCredentials");
1933                            return Ok(());
1934                        }
1935                        Err(retry_error) => {
1936                            tracing::debug!(
1937                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1938                                retry_error
1939                            );
1940                            return self.push_with_git_cli(branch);
1941                        }
1942                    }
1943                }
1944
1945                if self.should_fallback_to_git_cli(&e) {
1946                    tracing::debug!(
1947                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
1948                        e.class(), e.code(), e
1949                    );
1950                    return self.push_with_git_cli(branch);
1951                }
1952
1953                // Create concise error message
1954                let error_msg = if e.to_string().contains("authentication") {
1955                    format!(
1956                        "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1957                    )
1958                } else {
1959                    format!("Failed to push branch '{branch}': {e}")
1960                };
1961
1962                Err(CascadeError::branch(error_msg))
1963            }
1964        }
1965    }
1966
1967    /// Fallback push method using git CLI instead of git2
1968    /// This is used when git2 has TLS/SSL or auth issues but git CLI works fine
1969    fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1970        // Ensure index is closed before CLI command
1971        self.ensure_index_closed()?;
1972
1973        let output = std::process::Command::new("git")
1974            .args(["push", "origin", branch])
1975            .current_dir(&self.path)
1976            .output()
1977            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1978
1979        if output.status.success() {
1980            // Silent success - no need to log when fallback works
1981            Ok(())
1982        } else {
1983            let stderr = String::from_utf8_lossy(&output.stderr);
1984            let _stdout = String::from_utf8_lossy(&output.stdout);
1985            // Extract the most relevant error message
1986            let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
1987                "Network error: Unable to connect to repository (VPN may be required)".to_string()
1988            } else if stderr.contains("repository") && stderr.contains("not found") {
1989                "Repository not found - check your Bitbucket configuration".to_string()
1990            } else if stderr.contains("authentication") || stderr.contains("403") {
1991                "Authentication failed - check your credentials".to_string()
1992            } else {
1993                // For other errors, just show the stderr without the verbose prefix
1994                stderr.trim().to_string()
1995            };
1996            Err(CascadeError::branch(error_msg))
1997        }
1998    }
1999
2000    /// Fallback fetch method using git CLI instead of git2
2001    /// This is used when git2 has TLS/SSL issues but git CLI works fine
2002    fn fetch_with_git_cli(&self) -> Result<()> {
2003        tracing::debug!("Using git CLI fallback for fetch operation");
2004
2005        // Ensure index is closed before CLI command
2006        self.ensure_index_closed()?;
2007
2008        let output = std::process::Command::new("git")
2009            .args(["fetch", "origin"])
2010            .current_dir(&self.path)
2011            .output()
2012            .map_err(|e| {
2013                CascadeError::Git(git2::Error::from_str(&format!(
2014                    "Failed to execute git command: {e}"
2015                )))
2016            })?;
2017
2018        if output.status.success() {
2019            tracing::debug!("Git CLI fetch succeeded");
2020            Ok(())
2021        } else {
2022            let stderr = String::from_utf8_lossy(&output.stderr);
2023            let stdout = String::from_utf8_lossy(&output.stdout);
2024            let error_msg = format!(
2025                "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
2026                output.status, stdout, stderr
2027            );
2028            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
2029        }
2030    }
2031
2032    /// Fallback pull method using git CLI instead of git2
2033    /// This is used when git2 has TLS/SSL issues but git CLI works fine
2034    fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
2035        tracing::debug!("Using git CLI fallback for pull operation: {}", branch);
2036
2037        // Ensure index is closed before CLI command
2038        self.ensure_index_closed()?;
2039
2040        let output = std::process::Command::new("git")
2041            .args(["pull", "origin", branch])
2042            .current_dir(&self.path)
2043            .output()
2044            .map_err(|e| {
2045                CascadeError::Git(git2::Error::from_str(&format!(
2046                    "Failed to execute git command: {e}"
2047                )))
2048            })?;
2049
2050        if output.status.success() {
2051            tracing::debug!("Git CLI pull succeeded for branch: {}", branch);
2052            Ok(())
2053        } else {
2054            let stderr = String::from_utf8_lossy(&output.stderr);
2055            let stdout = String::from_utf8_lossy(&output.stdout);
2056            let error_msg = format!(
2057                "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
2058                branch, output.status, stdout, stderr
2059            );
2060            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
2061        }
2062    }
2063
2064    /// Fallback force push method using git CLI instead of git2
2065    /// This is used when git2 has TLS/SSL issues but git CLI works fine
2066    fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
2067        tracing::debug!(
2068            "Using git CLI fallback for force push operation: {}",
2069            branch
2070        );
2071
2072        let output = std::process::Command::new("git")
2073            .args(["push", "--force", "origin", branch])
2074            .current_dir(&self.path)
2075            .output()
2076            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
2077
2078        if output.status.success() {
2079            tracing::debug!("Git CLI force push succeeded for branch: {}", branch);
2080            Ok(())
2081        } else {
2082            let stderr = String::from_utf8_lossy(&output.stderr);
2083            let stdout = String::from_utf8_lossy(&output.stdout);
2084            let error_msg = format!(
2085                "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
2086                branch, output.status, stdout, stderr
2087            );
2088            Err(CascadeError::branch(error_msg))
2089        }
2090    }
2091
2092    /// Delete a local branch
2093    pub fn delete_branch(&self, name: &str) -> Result<()> {
2094        self.delete_branch_with_options(name, false)
2095    }
2096
2097    /// Delete a local branch with force option to bypass safety checks
2098    pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
2099        self.delete_branch_with_options(name, true)
2100    }
2101
2102    /// Internal branch deletion implementation with safety options
2103    fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
2104        debug!("Attempting to delete branch: {}", name);
2105
2106        // Enhanced safety check: Detect unpushed commits before deletion
2107        if !force_unsafe {
2108            let safety_result = self.check_branch_deletion_safety(name)?;
2109            if let Some(safety_info) = safety_result {
2110                // Branch has unpushed commits, get user confirmation
2111                self.handle_branch_deletion_confirmation(name, &safety_info)?;
2112            }
2113        }
2114
2115        let mut branch = self
2116            .repo
2117            .find_branch(name, git2::BranchType::Local)
2118            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
2119
2120        branch
2121            .delete()
2122            .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
2123
2124        debug!("Successfully deleted branch '{}'", name);
2125        Ok(())
2126    }
2127
2128    /// Get commits between two references
2129    pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
2130        let from_oid = self
2131            .repo
2132            .refname_to_id(&format!("refs/heads/{from}"))
2133            .or_else(|_| Oid::from_str(from))
2134            .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
2135
2136        let to_oid = self
2137            .repo
2138            .refname_to_id(&format!("refs/heads/{to}"))
2139            .or_else(|_| Oid::from_str(to))
2140            .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
2141
2142        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2143
2144        revwalk.push(to_oid).map_err(CascadeError::Git)?;
2145        revwalk.hide(from_oid).map_err(CascadeError::Git)?;
2146
2147        let mut commits = Vec::new();
2148        for oid in revwalk {
2149            let oid = oid.map_err(CascadeError::Git)?;
2150            let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
2151            commits.push(commit);
2152        }
2153
2154        Ok(commits)
2155    }
2156
2157    /// Force push one branch's content to another branch name
2158    /// This is used to preserve PR history while updating branch contents after rebase
2159    pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
2160        self.force_push_branch_with_options(target_branch, source_branch, false)
2161    }
2162
2163    /// Force push with explicit force flag to bypass safety checks
2164    pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
2165        self.force_push_branch_with_options(target_branch, source_branch, true)
2166    }
2167
2168    /// Internal force push implementation with safety options
2169    fn force_push_branch_with_options(
2170        &self,
2171        target_branch: &str,
2172        source_branch: &str,
2173        force_unsafe: bool,
2174    ) -> Result<()> {
2175        debug!(
2176            "Force pushing {} content to {} to preserve PR history",
2177            source_branch, target_branch
2178        );
2179
2180        // Enhanced safety check: Detect potential data loss and get user confirmation
2181        if !force_unsafe {
2182            let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
2183            if let Some(backup_info) = safety_result {
2184                // Create backup branch before force push
2185                self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
2186                Output::sub_item(format!(
2187                    "Created backup branch: {}",
2188                    backup_info.backup_branch_name
2189                ));
2190            }
2191        }
2192
2193        // First, ensure we have the latest changes for the source branch
2194        let source_ref = self
2195            .repo
2196            .find_reference(&format!("refs/heads/{source_branch}"))
2197            .map_err(|e| {
2198                CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
2199            })?;
2200        let _source_commit = source_ref.peel_to_commit().map_err(|e| {
2201            CascadeError::config(format!(
2202                "Failed to get commit for source branch {source_branch}: {e}"
2203            ))
2204        })?;
2205
2206        // Force push to remote without modifying local target branch
2207        let mut remote = self
2208            .repo
2209            .find_remote("origin")
2210            .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
2211
2212        // Push source branch content to remote target branch
2213        let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");
2214
2215        // Configure callbacks with SSL settings from git config
2216        let callbacks = self.configure_remote_callbacks()?;
2217
2218        // Push options for force push with SSL config
2219        let mut push_options = git2::PushOptions::new();
2220        push_options.remote_callbacks(callbacks);
2221
2222        match remote.push(&[&refspec], Some(&mut push_options)) {
2223            Ok(_) => {}
2224            Err(e) => {
2225                if self.should_retry_with_default_credentials(&e) {
2226                    tracing::debug!(
2227                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
2228                        e.class(), e.code(), e
2229                    );
2230
2231                    // Retry with DefaultCredentials for corporate networks
2232                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
2233                    let mut push_options = git2::PushOptions::new();
2234                    push_options.remote_callbacks(callbacks);
2235
2236                    match remote.push(&[&refspec], Some(&mut push_options)) {
2237                        Ok(_) => {
2238                            tracing::debug!("Force push succeeded with DefaultCredentials");
2239                            // Success - continue to normal success path
2240                        }
2241                        Err(retry_error) => {
2242                            tracing::debug!(
2243                                "DefaultCredentials retry failed: {}, falling back to git CLI",
2244                                retry_error
2245                            );
2246                            return self.force_push_with_git_cli(target_branch);
2247                        }
2248                    }
2249                } else if self.should_fallback_to_git_cli(&e) {
2250                    tracing::debug!(
2251                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
2252                        e.class(), e.code(), e
2253                    );
2254                    return self.force_push_with_git_cli(target_branch);
2255                } else {
2256                    return Err(CascadeError::config(format!(
2257                        "Failed to force push {target_branch}: {e}"
2258                    )));
2259                }
2260            }
2261        }
2262
2263        tracing::debug!(
2264            "Successfully force pushed {} to preserve PR history",
2265            target_branch
2266        );
2267        Ok(())
2268    }
2269
2270    /// Enhanced safety check for force push operations with user confirmation
2271    /// Returns backup info if data would be lost and user confirms
2272    fn check_force_push_safety_enhanced(
2273        &self,
2274        target_branch: &str,
2275    ) -> Result<Option<ForceBackupInfo>> {
2276        // First fetch latest remote changes to ensure we have up-to-date information
2277        match self.fetch() {
2278            Ok(_) => {}
2279            Err(e) => {
2280                // If fetch fails, warn but don't block the operation
2281                debug!("Could not fetch latest changes for safety check: {}", e);
2282            }
2283        }
2284
2285        // Check if there are commits on the remote that would be lost
2286        let remote_ref = format!("refs/remotes/origin/{target_branch}");
2287        let local_ref = format!("refs/heads/{target_branch}");
2288
2289        // Try to find both local and remote references
2290        let local_commit = match self.repo.find_reference(&local_ref) {
2291            Ok(reference) => reference.peel_to_commit().ok(),
2292            Err(_) => None,
2293        };
2294
2295        let remote_commit = match self.repo.find_reference(&remote_ref) {
2296            Ok(reference) => reference.peel_to_commit().ok(),
2297            Err(_) => None,
2298        };
2299
2300        // If we have both commits, check for divergence
2301        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2302            if local.id() != remote.id() {
2303                // Check if the remote has commits that the local doesn't have
2304                let merge_base_oid = self
2305                    .repo
2306                    .merge_base(local.id(), remote.id())
2307                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2308
2309                // If merge base != remote commit, remote has commits that would be lost
2310                if merge_base_oid != remote.id() {
2311                    let commits_to_lose = self.count_commits_between(
2312                        &merge_base_oid.to_string(),
2313                        &remote.id().to_string(),
2314                    )?;
2315
2316                    // Create backup branch name with timestamp
2317                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2318                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2319
2320                    debug!(
2321                        "Force push to '{}' would overwrite {} commits on remote",
2322                        target_branch, commits_to_lose
2323                    );
2324
2325                    // Check if we're in a non-interactive environment (CI/testing)
2326                    if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
2327                    {
2328                        info!(
2329                            "Non-interactive environment detected, proceeding with backup creation"
2330                        );
2331                        return Ok(Some(ForceBackupInfo {
2332                            backup_branch_name,
2333                            remote_commit_id: remote.id().to_string(),
2334                            commits_that_would_be_lost: commits_to_lose,
2335                        }));
2336                    }
2337
2338                    // Automatically create backup - this is normal stacked diff workflow
2339                    return Ok(Some(ForceBackupInfo {
2340                        backup_branch_name,
2341                        remote_commit_id: remote.id().to_string(),
2342                        commits_that_would_be_lost: commits_to_lose,
2343                    }));
2344                }
2345            }
2346        }
2347
2348        Ok(None)
2349    }
2350
2351    /// Check force push safety without user confirmation (auto-creates backup)
2352    /// Used for automated operations like sync where user already confirmed the operation
2353    ///
2354    /// When skip_fetch=false: Fetches latest remote state before checking (default behavior)
2355    /// When skip_fetch=true: Assumes fetch already done (batch operations)
2356    fn check_force_push_safety_auto_no_fetch(
2357        &self,
2358        target_branch: &str,
2359    ) -> Result<Option<ForceBackupInfo>> {
2360        // Check if there are commits on the remote that would be lost
2361        let remote_ref = format!("refs/remotes/origin/{target_branch}");
2362        let local_ref = format!("refs/heads/{target_branch}");
2363
2364        // Try to find both local and remote references
2365        let local_commit = match self.repo.find_reference(&local_ref) {
2366            Ok(reference) => reference.peel_to_commit().ok(),
2367            Err(_) => None,
2368        };
2369
2370        let remote_commit = match self.repo.find_reference(&remote_ref) {
2371            Ok(reference) => reference.peel_to_commit().ok(),
2372            Err(_) => None,
2373        };
2374
2375        // If we have both commits, check for divergence
2376        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2377            if local.id() != remote.id() {
2378                // Check if the remote has commits that the local doesn't have
2379                let merge_base_oid = self
2380                    .repo
2381                    .merge_base(local.id(), remote.id())
2382                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2383
2384                // If merge base != remote commit, remote has commits that would be lost
2385                if merge_base_oid != remote.id() {
2386                    let commits_to_lose = self.count_commits_between(
2387                        &merge_base_oid.to_string(),
2388                        &remote.id().to_string(),
2389                    )?;
2390
2391                    // Create backup branch name with timestamp
2392                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2393                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2394
2395                    tracing::debug!(
2396                        "Auto-creating backup '{}' for force push to '{}' (would overwrite {} commits)",
2397                        backup_branch_name, target_branch, commits_to_lose
2398                    );
2399
2400                    // Automatically create backup without confirmation
2401                    return Ok(Some(ForceBackupInfo {
2402                        backup_branch_name,
2403                        remote_commit_id: remote.id().to_string(),
2404                        commits_that_would_be_lost: commits_to_lose,
2405                    }));
2406                }
2407            }
2408        }
2409
2410        Ok(None)
2411    }
2412
2413    /// Create a backup branch pointing to the remote commit that would be lost
2414    fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
2415        let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2416        let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
2417
2418        // Parse the commit ID
2419        let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
2420            CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
2421        })?;
2422
2423        // Find the commit
2424        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
2425            CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
2426        })?;
2427
2428        // Create the backup branch
2429        self.repo
2430            .branch(&backup_branch_name, &commit, false)
2431            .map_err(|e| {
2432                CascadeError::config(format!(
2433                    "Failed to create backup branch {backup_branch_name}: {e}"
2434                ))
2435            })?;
2436
2437        debug!(
2438            "Created backup branch '{}' pointing to {}",
2439            backup_branch_name,
2440            &remote_commit_id[..8]
2441        );
2442        Ok(())
2443    }
2444
2445    /// Check if branch deletion is safe by detecting unpushed commits
2446    /// Returns safety info if there are concerns that need user attention
2447    fn check_branch_deletion_safety(
2448        &self,
2449        branch_name: &str,
2450    ) -> Result<Option<BranchDeletionSafety>> {
2451        // First, try to fetch latest remote changes
2452        match self.fetch() {
2453            Ok(_) => {}
2454            Err(e) => {
2455                warn!(
2456                    "Could not fetch latest changes for branch deletion safety check: {}",
2457                    e
2458                );
2459            }
2460        }
2461
2462        // Find the branch
2463        let branch = self
2464            .repo
2465            .find_branch(branch_name, git2::BranchType::Local)
2466            .map_err(|e| {
2467                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2468            })?;
2469
2470        let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
2471            CascadeError::branch(format!(
2472                "Could not get commit for branch '{branch_name}': {e}"
2473            ))
2474        })?;
2475
2476        // Determine the main branch (try common names)
2477        let main_branch_name = self.detect_main_branch()?;
2478
2479        // Check if branch is merged to main
2480        let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
2481
2482        // Find the upstream/remote tracking branch
2483        let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
2484
2485        let mut unpushed_commits = Vec::new();
2486
2487        // Check for unpushed commits compared to remote tracking branch
2488        if let Some(ref remote_branch) = remote_tracking_branch {
2489            match self.get_commits_between(remote_branch, branch_name) {
2490                Ok(commits) => {
2491                    unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2492                }
2493                Err(_) => {
2494                    // If we can't compare with remote, check against main branch
2495                    if !is_merged_to_main {
2496                        if let Ok(commits) =
2497                            self.get_commits_between(&main_branch_name, branch_name)
2498                        {
2499                            unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2500                        }
2501                    }
2502                }
2503            }
2504        } else if !is_merged_to_main {
2505            // No remote tracking branch, check against main
2506            if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
2507                unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2508            }
2509        }
2510
2511        // If there are concerns, return safety info
2512        if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
2513        {
2514            Ok(Some(BranchDeletionSafety {
2515                unpushed_commits,
2516                remote_tracking_branch,
2517                is_merged_to_main,
2518                main_branch_name,
2519            }))
2520        } else {
2521            Ok(None)
2522        }
2523    }
2524
2525    /// Handle user confirmation for branch deletion with safety concerns
2526    fn handle_branch_deletion_confirmation(
2527        &self,
2528        branch_name: &str,
2529        safety_info: &BranchDeletionSafety,
2530    ) -> Result<()> {
2531        // Check if we're in a non-interactive environment
2532        if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
2533            return Err(CascadeError::branch(
2534                format!(
2535                    "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
2536                    safety_info.unpushed_commits.len()
2537                )
2538            ));
2539        }
2540
2541        // Interactive warning and confirmation
2542        println!();
2543        Output::warning("BRANCH DELETION WARNING");
2544        println!("Branch '{branch_name}' has potential issues:");
2545
2546        if !safety_info.unpushed_commits.is_empty() {
2547            println!(
2548                "\n🔍 Unpushed commits ({} total):",
2549                safety_info.unpushed_commits.len()
2550            );
2551
2552            // Show details of unpushed commits
2553            for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
2554                if let Ok(oid) = Oid::from_str(commit_id) {
2555                    if let Ok(commit) = self.repo.find_commit(oid) {
2556                        let short_hash = &commit_id[..8];
2557                        let summary = commit.summary().unwrap_or("<no message>");
2558                        println!("  {}. {} - {}", i + 1, short_hash, summary);
2559                    }
2560                }
2561            }
2562
2563            if safety_info.unpushed_commits.len() > 5 {
2564                println!(
2565                    "  ... and {} more commits",
2566                    safety_info.unpushed_commits.len() - 5
2567                );
2568            }
2569        }
2570
2571        if !safety_info.is_merged_to_main {
2572            println!();
2573            crate::cli::output::Output::section("Branch status");
2574            crate::cli::output::Output::bullet(format!(
2575                "Not merged to '{}'",
2576                safety_info.main_branch_name
2577            ));
2578            if let Some(ref remote) = safety_info.remote_tracking_branch {
2579                crate::cli::output::Output::bullet(format!("Remote tracking branch: {remote}"));
2580            } else {
2581                crate::cli::output::Output::bullet("No remote tracking branch");
2582            }
2583        }
2584
2585        println!();
2586        crate::cli::output::Output::section("Safer alternatives");
2587        if !safety_info.unpushed_commits.is_empty() {
2588            if let Some(ref _remote) = safety_info.remote_tracking_branch {
2589                println!("  • Push commits first: git push origin {branch_name}");
2590            } else {
2591                println!("  • Create and push to remote: git push -u origin {branch_name}");
2592            }
2593        }
2594        if !safety_info.is_merged_to_main {
2595            println!(
2596                "  • Merge to {} first: git checkout {} && git merge {branch_name}",
2597                safety_info.main_branch_name, safety_info.main_branch_name
2598            );
2599        }
2600
2601        let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2602            .with_prompt("Do you want to proceed with deleting this branch?")
2603            .default(false)
2604            .interact()
2605            .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
2606
2607        if !confirmed {
2608            return Err(CascadeError::branch(
2609                "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
2610            ));
2611        }
2612
2613        Ok(())
2614    }
2615
2616    /// Detect the main branch name (main, master, develop)
2617    pub fn detect_main_branch(&self) -> Result<String> {
2618        let main_candidates = ["main", "master", "develop", "trunk"];
2619
2620        for candidate in &main_candidates {
2621            if self
2622                .repo
2623                .find_branch(candidate, git2::BranchType::Local)
2624                .is_ok()
2625            {
2626                return Ok(candidate.to_string());
2627            }
2628        }
2629
2630        // Fallback to HEAD's target if it's a symbolic reference
2631        if let Ok(head) = self.repo.head() {
2632            if let Some(name) = head.shorthand() {
2633                return Ok(name.to_string());
2634            }
2635        }
2636
2637        // Final fallback
2638        Ok("main".to_string())
2639    }
2640
2641    /// Check if a branch is merged to the main branch
2642    fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
2643        // Get the commits between main and the branch
2644        match self.get_commits_between(main_branch, branch_name) {
2645            Ok(commits) => Ok(commits.is_empty()),
2646            Err(_) => {
2647                // If we can't determine, assume not merged for safety
2648                Ok(false)
2649            }
2650        }
2651    }
2652
2653    /// Get the remote tracking branch for a local branch
2654    fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
2655        // Try common remote tracking branch patterns
2656        let remote_candidates = [
2657            format!("origin/{branch_name}"),
2658            format!("remotes/origin/{branch_name}"),
2659        ];
2660
2661        for candidate in &remote_candidates {
2662            if self
2663                .repo
2664                .find_reference(&format!(
2665                    "refs/remotes/{}",
2666                    candidate.replace("remotes/", "")
2667                ))
2668                .is_ok()
2669            {
2670                return Some(candidate.clone());
2671            }
2672        }
2673
2674        None
2675    }
2676
2677    /// Check if checkout operation is safe
2678    fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
2679        // Check if there are uncommitted changes
2680        let is_dirty = self.is_dirty()?;
2681        if !is_dirty {
2682            // No uncommitted changes, checkout is safe
2683            return Ok(None);
2684        }
2685
2686        // Get current branch for context
2687        let current_branch = self.get_current_branch().ok();
2688
2689        // Get detailed information about uncommitted changes
2690        let modified_files = self.get_modified_files()?;
2691        let staged_files = self.get_staged_files()?;
2692        let untracked_files = self.get_untracked_files()?;
2693
2694        let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
2695
2696        if has_uncommitted_changes || !untracked_files.is_empty() {
2697            return Ok(Some(CheckoutSafety {
2698                has_uncommitted_changes,
2699                modified_files,
2700                staged_files,
2701                untracked_files,
2702                stash_created: None,
2703                current_branch,
2704            }));
2705        }
2706
2707        Ok(None)
2708    }
2709
2710    /// Handle user confirmation for checkout operations with uncommitted changes
2711    fn handle_checkout_confirmation(
2712        &self,
2713        target: &str,
2714        safety_info: &CheckoutSafety,
2715    ) -> Result<()> {
2716        // Check if we're in a non-interactive environment FIRST (before any output)
2717        let is_ci = std::env::var("CI").is_ok();
2718        let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
2719        let is_non_interactive = is_ci || no_confirm;
2720
2721        if is_non_interactive {
2722            return Err(CascadeError::branch(
2723                format!(
2724                    "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
2725                )
2726            ));
2727        }
2728
2729        // Interactive warning and confirmation
2730        println!("\nCHECKOUT WARNING");
2731        println!("Attempting to checkout: {}", target);
2732        println!("You have uncommitted changes that could be lost:");
2733
2734        if !safety_info.modified_files.is_empty() {
2735            println!("\nModified files ({}):", safety_info.modified_files.len());
2736            for file in safety_info.modified_files.iter().take(10) {
2737                println!("   - {file}");
2738            }
2739            if safety_info.modified_files.len() > 10 {
2740                println!("   ... and {} more", safety_info.modified_files.len() - 10);
2741            }
2742        }
2743
2744        if !safety_info.staged_files.is_empty() {
2745            println!("\nStaged files ({}):", safety_info.staged_files.len());
2746            for file in safety_info.staged_files.iter().take(10) {
2747                println!("   - {file}");
2748            }
2749            if safety_info.staged_files.len() > 10 {
2750                println!("   ... and {} more", safety_info.staged_files.len() - 10);
2751            }
2752        }
2753
2754        if !safety_info.untracked_files.is_empty() {
2755            println!("\nUntracked files ({}):", safety_info.untracked_files.len());
2756            for file in safety_info.untracked_files.iter().take(5) {
2757                println!("   - {file}");
2758            }
2759            if safety_info.untracked_files.len() > 5 {
2760                println!("   ... and {} more", safety_info.untracked_files.len() - 5);
2761            }
2762        }
2763
2764        println!("\nOptions:");
2765        println!("1. Stash changes and checkout (recommended)");
2766        println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
2767        println!("3. Cancel checkout");
2768
2769        // Use proper selection dialog instead of y/n confirmation
2770        let selection = Select::with_theme(&ColorfulTheme::default())
2771            .with_prompt("Choose an action")
2772            .items(&[
2773                "Stash changes and checkout (recommended)",
2774                "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
2775                "Cancel checkout",
2776            ])
2777            .default(0)
2778            .interact()
2779            .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;
2780
2781        match selection {
2782            0 => {
2783                // Option 1: Stash changes and checkout
2784                let stash_message = format!(
2785                    "Auto-stash before checkout to {} at {}",
2786                    target,
2787                    chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
2788                );
2789
2790                match self.create_stash(&stash_message) {
2791                    Ok(stash_id) => {
2792                        crate::cli::output::Output::success(format!(
2793                            "Created stash: {stash_message} ({stash_id})"
2794                        ));
2795                        crate::cli::output::Output::tip("You can restore with: git stash pop");
2796                    }
2797                    Err(e) => {
2798                        crate::cli::output::Output::error(format!("Failed to create stash: {e}"));
2799
2800                        // If stash failed, provide better options
2801                        use dialoguer::Select;
2802                        let stash_failed_options = vec![
2803                            "Commit staged changes and proceed",
2804                            "Force checkout (WILL LOSE CHANGES)",
2805                            "Cancel and handle manually",
2806                        ];
2807
2808                        let stash_selection = Select::with_theme(&ColorfulTheme::default())
2809                            .with_prompt("Stash failed. What would you like to do?")
2810                            .items(&stash_failed_options)
2811                            .default(0)
2812                            .interact()
2813                            .map_err(|e| {
2814                                CascadeError::branch(format!("Could not get user selection: {e}"))
2815                            })?;
2816
2817                        match stash_selection {
2818                            0 => {
2819                                // Try to commit staged changes
2820                                let staged_files = self.get_staged_files()?;
2821                                if !staged_files.is_empty() {
2822                                    println!(
2823                                        "📝 Committing {} staged files...",
2824                                        staged_files.len()
2825                                    );
2826                                    match self
2827                                        .commit_staged_changes("WIP: Auto-commit before checkout")
2828                                    {
2829                                        Ok(Some(commit_hash)) => {
2830                                            crate::cli::output::Output::success(format!(
2831                                                "Committed staged changes as {}",
2832                                                &commit_hash[..8]
2833                                            ));
2834                                            crate::cli::output::Output::tip(
2835                                                "You can undo with: git reset HEAD~1",
2836                                            );
2837                                        }
2838                                        Ok(None) => {
2839                                            crate::cli::output::Output::info(
2840                                                "No staged changes found to commit",
2841                                            );
2842                                        }
2843                                        Err(commit_err) => {
2844                                            println!(
2845                                                "❌ Failed to commit staged changes: {commit_err}"
2846                                            );
2847                                            return Err(CascadeError::branch(
2848                                                "Could not commit staged changes".to_string(),
2849                                            ));
2850                                        }
2851                                    }
2852                                } else {
2853                                    println!("No staged changes to commit");
2854                                }
2855                            }
2856                            1 => {
2857                                // Force checkout anyway
2858                                Output::warning("Proceeding with force checkout - uncommitted changes will be lost!");
2859                            }
2860                            2 => {
2861                                // Cancel
2862                                return Err(CascadeError::branch(
2863                                    "Checkout cancelled. Please handle changes manually and try again.".to_string(),
2864                                ));
2865                            }
2866                            _ => unreachable!(),
2867                        }
2868                    }
2869                }
2870            }
2871            1 => {
2872                // Option 2: Force checkout (lose changes)
2873                Output::warning(
2874                    "Proceeding with force checkout - uncommitted changes will be lost!",
2875                );
2876            }
2877            2 => {
2878                // Option 3: Cancel
2879                return Err(CascadeError::branch(
2880                    "Checkout cancelled by user".to_string(),
2881                ));
2882            }
2883            _ => unreachable!(),
2884        }
2885
2886        Ok(())
2887    }
2888
2889    /// Create a stash with uncommitted changes
2890    fn create_stash(&self, message: &str) -> Result<String> {
2891        use crate::cli::output::Output;
2892
2893        tracing::debug!("Creating stash: {}", message);
2894
2895        // Use git CLI for stashing since git2 stashing is complex and unreliable
2896        let output = std::process::Command::new("git")
2897            .args(["stash", "push", "-m", message])
2898            .current_dir(&self.path)
2899            .output()
2900            .map_err(|e| {
2901                CascadeError::branch(format!("Failed to execute git stash command: {e}"))
2902            })?;
2903
2904        if output.status.success() {
2905            let stdout = String::from_utf8_lossy(&output.stdout);
2906
2907            // Extract stash hash if available (git stash outputs like "Saved working directory and index state WIP on branch: message")
2908            let stash_id = if stdout.contains("Saved working directory") {
2909                // Get the most recent stash ID
2910                let stash_list_output = std::process::Command::new("git")
2911                    .args(["stash", "list", "-n", "1", "--format=%H"])
2912                    .current_dir(&self.path)
2913                    .output()
2914                    .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;
2915
2916                if stash_list_output.status.success() {
2917                    String::from_utf8_lossy(&stash_list_output.stdout)
2918                        .trim()
2919                        .to_string()
2920                } else {
2921                    "stash@{0}".to_string() // fallback
2922                }
2923            } else {
2924                "stash@{0}".to_string() // fallback
2925            };
2926
2927            Output::success(format!("Created stash: {} ({})", message, stash_id));
2928            Output::tip("You can restore with: git stash pop");
2929            Ok(stash_id)
2930        } else {
2931            let stderr = String::from_utf8_lossy(&output.stderr);
2932            let stdout = String::from_utf8_lossy(&output.stdout);
2933
2934            // Check for common stash failure reasons
2935            if stderr.contains("No local changes to save")
2936                || stdout.contains("No local changes to save")
2937            {
2938                return Err(CascadeError::branch("No local changes to save".to_string()));
2939            }
2940
2941            Err(CascadeError::branch(format!(
2942                "Failed to create stash: {}\nStderr: {}\nStdout: {}",
2943                output.status, stderr, stdout
2944            )))
2945        }
2946    }
2947
2948    /// Get modified files in working directory
2949    fn get_modified_files(&self) -> Result<Vec<String>> {
2950        let mut opts = git2::StatusOptions::new();
2951        opts.include_untracked(false).include_ignored(false);
2952
2953        let statuses = self
2954            .repo
2955            .statuses(Some(&mut opts))
2956            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2957
2958        let mut modified_files = Vec::new();
2959        for status in statuses.iter() {
2960            let flags = status.status();
2961            if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
2962            {
2963                if let Some(path) = status.path() {
2964                    modified_files.push(path.to_string());
2965                }
2966            }
2967        }
2968
2969        Ok(modified_files)
2970    }
2971
2972    /// Get staged files in index
2973    pub fn get_staged_files(&self) -> Result<Vec<String>> {
2974        let mut opts = git2::StatusOptions::new();
2975        opts.include_untracked(false).include_ignored(false);
2976
2977        let statuses = self
2978            .repo
2979            .statuses(Some(&mut opts))
2980            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2981
2982        let mut staged_files = Vec::new();
2983        for status in statuses.iter() {
2984            let flags = status.status();
2985            if flags.contains(git2::Status::INDEX_MODIFIED)
2986                || flags.contains(git2::Status::INDEX_NEW)
2987                || flags.contains(git2::Status::INDEX_DELETED)
2988            {
2989                if let Some(path) = status.path() {
2990                    staged_files.push(path.to_string());
2991                }
2992            }
2993        }
2994
2995        Ok(staged_files)
2996    }
2997
2998    /// Count commits between two references
2999    fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
3000        let commits = self.get_commits_between(from, to)?;
3001        Ok(commits.len())
3002    }
3003
3004    /// Resolve a reference (branch name, tag, or commit hash) to a commit
3005    pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
3006        // Try to parse as commit hash first
3007        if let Ok(oid) = Oid::from_str(reference) {
3008            if let Ok(commit) = self.repo.find_commit(oid) {
3009                return Ok(commit);
3010            }
3011        }
3012
3013        // Try to resolve as a reference (branch, tag, etc.)
3014        let obj = self.repo.revparse_single(reference).map_err(|e| {
3015            CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
3016        })?;
3017
3018        obj.peel_to_commit().map_err(|e| {
3019            CascadeError::branch(format!(
3020                "Reference '{reference}' does not point to a commit: {e}"
3021            ))
3022        })
3023    }
3024
3025    /// Reset HEAD to a specific reference (soft reset)
3026    pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
3027        let target_commit = self.resolve_reference(target_ref)?;
3028
3029        self.repo
3030            .reset(target_commit.as_object(), git2::ResetType::Soft, None)
3031            .map_err(CascadeError::Git)?;
3032
3033        Ok(())
3034    }
3035
3036    /// Reset working directory and index to match HEAD (hard reset)
3037    /// This clears all uncommitted changes and staged files
3038    pub fn reset_to_head(&self) -> Result<()> {
3039        tracing::debug!("Resetting working directory and index to HEAD");
3040
3041        let repo_path = self.path();
3042
3043        // Use lock retry wrapper to handle stale locks automatically
3044        crate::utils::git_lock::with_lock_retry(repo_path, || {
3045            let head = self.repo.head()?;
3046            let head_commit = head.peel_to_commit()?;
3047
3048            // Hard reset: resets index and working tree
3049            let mut checkout_builder = git2::build::CheckoutBuilder::new();
3050            checkout_builder.force(); // Force checkout to overwrite any local changes
3051            checkout_builder.remove_untracked(false); // Don't remove untracked files
3052
3053            self.repo.reset(
3054                head_commit.as_object(),
3055                git2::ResetType::Hard,
3056                Some(&mut checkout_builder),
3057            )?;
3058
3059            Ok(())
3060        })?;
3061
3062        tracing::debug!("Successfully reset working directory to HEAD");
3063        Ok(())
3064    }
3065
3066    /// Find which branch contains a specific commit
3067    pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
3068        let oid = Oid::from_str(commit_hash).map_err(|e| {
3069            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
3070        })?;
3071
3072        // Get all local branches
3073        let branches = self
3074            .repo
3075            .branches(Some(git2::BranchType::Local))
3076            .map_err(CascadeError::Git)?;
3077
3078        for branch_result in branches {
3079            let (branch, _) = branch_result.map_err(CascadeError::Git)?;
3080
3081            if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
3082                // Check if this branch contains the commit
3083                if let Ok(branch_head) = branch.get().peel_to_commit() {
3084                    // Walk the commit history from this branch's HEAD
3085                    let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
3086                    revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
3087
3088                    for commit_oid in revwalk {
3089                        let commit_oid = commit_oid.map_err(CascadeError::Git)?;
3090                        if commit_oid == oid {
3091                            return Ok(branch_name.to_string());
3092                        }
3093                    }
3094                }
3095            }
3096        }
3097
3098        // If not found in any branch, might be on current HEAD
3099        Err(CascadeError::branch(format!(
3100            "Commit {commit_hash} not found in any local branch"
3101        )))
3102    }
3103
3104    // Async wrappers for potentially blocking operations
3105
3106    /// Fetch from remote origin (async)
3107    pub async fn fetch_async(&self) -> Result<()> {
3108        let repo_path = self.path.clone();
3109        crate::utils::async_ops::run_git_operation(move || {
3110            let repo = GitRepository::open(&repo_path)?;
3111            repo.fetch()
3112        })
3113        .await
3114    }
3115
3116    /// Pull changes from remote (async)
3117    pub async fn pull_async(&self, branch: &str) -> Result<()> {
3118        let repo_path = self.path.clone();
3119        let branch_name = branch.to_string();
3120        crate::utils::async_ops::run_git_operation(move || {
3121            let repo = GitRepository::open(&repo_path)?;
3122            repo.pull(&branch_name)
3123        })
3124        .await
3125    }
3126
3127    /// Push branch to remote (async)
3128    pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
3129        let repo_path = self.path.clone();
3130        let branch = branch_name.to_string();
3131        crate::utils::async_ops::run_git_operation(move || {
3132            let repo = GitRepository::open(&repo_path)?;
3133            repo.push(&branch)
3134        })
3135        .await
3136    }
3137
3138    /// Cherry-pick commit (async)
3139    pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
3140        let repo_path = self.path.clone();
3141        let hash = commit_hash.to_string();
3142        crate::utils::async_ops::run_git_operation(move || {
3143            let repo = GitRepository::open(&repo_path)?;
3144            repo.cherry_pick(&hash)
3145        })
3146        .await
3147    }
3148
3149    /// Get commit hashes between two refs (async)
3150    pub async fn get_commit_hashes_between_async(
3151        &self,
3152        from: &str,
3153        to: &str,
3154    ) -> Result<Vec<String>> {
3155        let repo_path = self.path.clone();
3156        let from_str = from.to_string();
3157        let to_str = to.to_string();
3158        crate::utils::async_ops::run_git_operation(move || {
3159            let repo = GitRepository::open(&repo_path)?;
3160            let commits = repo.get_commits_between(&from_str, &to_str)?;
3161            Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
3162        })
3163        .await
3164    }
3165
3166    /// Reset a branch to point to a specific commit
3167    pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
3168        info!(
3169            "Resetting branch '{}' to commit {}",
3170            branch_name,
3171            &commit_hash[..8]
3172        );
3173
3174        // Find the target commit
3175        let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
3176            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
3177        })?;
3178
3179        let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
3180            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
3181        })?;
3182
3183        // Find the branch
3184        let _branch = self
3185            .repo
3186            .find_branch(branch_name, git2::BranchType::Local)
3187            .map_err(|e| {
3188                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
3189            })?;
3190
3191        // Update the branch reference to point to the target commit
3192        let branch_ref_name = format!("refs/heads/{branch_name}");
3193        self.repo
3194            .reference(
3195                &branch_ref_name,
3196                target_oid,
3197                true,
3198                &format!("Reset {branch_name} to {commit_hash}"),
3199            )
3200            .map_err(|e| {
3201                CascadeError::branch(format!(
3202                    "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
3203                ))
3204            })?;
3205
3206        tracing::info!(
3207            "Successfully reset branch '{}' to commit {}",
3208            branch_name,
3209            &commit_hash[..8]
3210        );
3211        Ok(())
3212    }
3213
3214    /// Detect the parent branch of the current branch using multiple strategies
3215    pub fn detect_parent_branch(&self) -> Result<Option<String>> {
3216        let current_branch = self.get_current_branch()?;
3217
3218        // Strategy 1: Check if current branch has an upstream tracking branch
3219        if let Ok(Some(upstream)) = self.get_upstream_branch(&current_branch) {
3220            // Extract the branch name from "origin/branch-name" format
3221            if let Some(branch_name) = upstream.split('/').nth(1) {
3222                if self.branch_exists(branch_name) {
3223                    tracing::debug!(
3224                        "Detected parent branch '{}' from upstream tracking",
3225                        branch_name
3226                    );
3227                    return Ok(Some(branch_name.to_string()));
3228                }
3229            }
3230        }
3231
3232        // Strategy 2: Use git's default branch detection
3233        if let Ok(default_branch) = self.detect_main_branch() {
3234            // Don't suggest the current branch as its own parent
3235            if current_branch != default_branch {
3236                tracing::debug!(
3237                    "Detected parent branch '{}' as repository default",
3238                    default_branch
3239                );
3240                return Ok(Some(default_branch));
3241            }
3242        }
3243
3244        // Strategy 3: Find the branch with the most recent common ancestor
3245        // Get all local branches and find the one with the shortest commit distance
3246        if let Ok(branches) = self.list_branches() {
3247            let current_commit = self.get_head_commit()?;
3248            let current_commit_hash = current_commit.id().to_string();
3249            let current_oid = current_commit.id();
3250
3251            let mut best_candidate = None;
3252            let mut best_distance = usize::MAX;
3253
3254            for branch in branches {
3255                // Skip the current branch and any branches that look like version branches
3256                if branch == current_branch
3257                    || branch.contains("-v")
3258                    || branch.ends_with("-v2")
3259                    || branch.ends_with("-v3")
3260                {
3261                    continue;
3262                }
3263
3264                if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
3265                    if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
3266                        // Find merge base between current branch and this branch
3267                        if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
3268                            // Count commits from merge base to current head
3269                            if let Ok(distance) = self.count_commits_between(
3270                                &merge_base_oid.to_string(),
3271                                &current_commit_hash,
3272                            ) {
3273                                // Prefer branches with shorter distances (more recent common ancestor)
3274                                // Also prefer branches that look like base branches
3275                                let is_likely_base = self.is_likely_base_branch(&branch);
3276                                let adjusted_distance = if is_likely_base {
3277                                    distance
3278                                } else {
3279                                    distance + 1000
3280                                };
3281
3282                                if adjusted_distance < best_distance {
3283                                    best_distance = adjusted_distance;
3284                                    best_candidate = Some(branch.clone());
3285                                }
3286                            }
3287                        }
3288                    }
3289                }
3290            }
3291
3292            if let Some(ref candidate) = best_candidate {
3293                tracing::debug!(
3294                    "Detected parent branch '{}' with distance {}",
3295                    candidate,
3296                    best_distance
3297                );
3298            }
3299
3300            return Ok(best_candidate);
3301        }
3302
3303        tracing::debug!("Could not detect parent branch for '{}'", current_branch);
3304        Ok(None)
3305    }
3306
3307    /// Check if a branch name looks like a typical base branch
3308    fn is_likely_base_branch(&self, branch_name: &str) -> bool {
3309        let base_patterns = [
3310            "main",
3311            "master",
3312            "develop",
3313            "dev",
3314            "development",
3315            "staging",
3316            "stage",
3317            "release",
3318            "production",
3319            "prod",
3320        ];
3321
3322        base_patterns.contains(&branch_name)
3323    }
3324}
3325
3326#[cfg(test)]
3327mod tests {
3328    use super::*;
3329    use std::process::Command;
3330    use tempfile::TempDir;
3331
3332    fn create_test_repo() -> (TempDir, PathBuf) {
3333        let temp_dir = TempDir::new().unwrap();
3334        let repo_path = temp_dir.path().to_path_buf();
3335
3336        // Initialize git repository
3337        Command::new("git")
3338            .args(["init"])
3339            .current_dir(&repo_path)
3340            .output()
3341            .unwrap();
3342        Command::new("git")
3343            .args(["config", "user.name", "Test"])
3344            .current_dir(&repo_path)
3345            .output()
3346            .unwrap();
3347        Command::new("git")
3348            .args(["config", "user.email", "test@test.com"])
3349            .current_dir(&repo_path)
3350            .output()
3351            .unwrap();
3352
3353        // Create initial commit
3354        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
3355        Command::new("git")
3356            .args(["add", "."])
3357            .current_dir(&repo_path)
3358            .output()
3359            .unwrap();
3360        Command::new("git")
3361            .args(["commit", "-m", "Initial commit"])
3362            .current_dir(&repo_path)
3363            .output()
3364            .unwrap();
3365
3366        (temp_dir, repo_path)
3367    }
3368
3369    fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
3370        let file_path = repo_path.join(filename);
3371        std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
3372
3373        Command::new("git")
3374            .args(["add", filename])
3375            .current_dir(repo_path)
3376            .output()
3377            .unwrap();
3378        Command::new("git")
3379            .args(["commit", "-m", message])
3380            .current_dir(repo_path)
3381            .output()
3382            .unwrap();
3383    }
3384
3385    #[test]
3386    fn test_repository_info() {
3387        let (_temp_dir, repo_path) = create_test_repo();
3388        let repo = GitRepository::open(&repo_path).unwrap();
3389
3390        let info = repo.get_info().unwrap();
3391        assert!(!info.is_dirty); // Should be clean after commit
3392        assert!(
3393            info.head_branch == Some("master".to_string())
3394                || info.head_branch == Some("main".to_string()),
3395            "Expected default branch to be 'master' or 'main', got {:?}",
3396            info.head_branch
3397        );
3398        assert!(info.head_commit.is_some()); // Just check it exists
3399        assert!(info.untracked_files.is_empty()); // Should be empty after commit
3400    }
3401
3402    #[test]
3403    fn test_force_push_branch_basic() {
3404        let (_temp_dir, repo_path) = create_test_repo();
3405        let repo = GitRepository::open(&repo_path).unwrap();
3406
3407        // Get the actual default branch name
3408        let default_branch = repo.get_current_branch().unwrap();
3409
3410        // Create source branch with commits
3411        create_commit(&repo_path, "Feature commit 1", "feature1.rs");
3412        Command::new("git")
3413            .args(["checkout", "-b", "source-branch"])
3414            .current_dir(&repo_path)
3415            .output()
3416            .unwrap();
3417        create_commit(&repo_path, "Feature commit 2", "feature2.rs");
3418
3419        // Create target branch
3420        Command::new("git")
3421            .args(["checkout", &default_branch])
3422            .current_dir(&repo_path)
3423            .output()
3424            .unwrap();
3425        Command::new("git")
3426            .args(["checkout", "-b", "target-branch"])
3427            .current_dir(&repo_path)
3428            .output()
3429            .unwrap();
3430        create_commit(&repo_path, "Target commit", "target.rs");
3431
3432        // Test force push from source to target
3433        let result = repo.force_push_branch("target-branch", "source-branch");
3434
3435        // Should succeed in test environment (even though it doesn't actually push to remote)
3436        // The important thing is that the function doesn't panic and handles the git2 operations
3437        assert!(result.is_ok() || result.is_err()); // Either is acceptable for unit test
3438    }
3439
3440    #[test]
3441    fn test_force_push_branch_nonexistent_branches() {
3442        let (_temp_dir, repo_path) = create_test_repo();
3443        let repo = GitRepository::open(&repo_path).unwrap();
3444
3445        // Get the actual default branch name
3446        let default_branch = repo.get_current_branch().unwrap();
3447
3448        // Test force push with nonexistent source branch
3449        let result = repo.force_push_branch("target", "nonexistent-source");
3450        assert!(result.is_err());
3451
3452        // Test force push with nonexistent target branch
3453        let result = repo.force_push_branch("nonexistent-target", &default_branch);
3454        assert!(result.is_err());
3455    }
3456
3457    #[test]
3458    fn test_force_push_workflow_simulation() {
3459        let (_temp_dir, repo_path) = create_test_repo();
3460        let repo = GitRepository::open(&repo_path).unwrap();
3461
3462        // Simulate the smart force push workflow:
3463        // 1. Original branch exists with PR
3464        Command::new("git")
3465            .args(["checkout", "-b", "feature-auth"])
3466            .current_dir(&repo_path)
3467            .output()
3468            .unwrap();
3469        create_commit(&repo_path, "Add authentication", "auth.rs");
3470
3471        // 2. Rebase creates versioned branch
3472        Command::new("git")
3473            .args(["checkout", "-b", "feature-auth-v2"])
3474            .current_dir(&repo_path)
3475            .output()
3476            .unwrap();
3477        create_commit(&repo_path, "Fix auth validation", "auth.rs");
3478
3479        // 3. Smart force push: update original branch from versioned branch
3480        let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
3481
3482        // Verify the operation is handled properly (success or expected error)
3483        match result {
3484            Ok(_) => {
3485                // Force push succeeded - verify branch state if possible
3486                Command::new("git")
3487                    .args(["checkout", "feature-auth"])
3488                    .current_dir(&repo_path)
3489                    .output()
3490                    .unwrap();
3491                let log_output = Command::new("git")
3492                    .args(["log", "--oneline", "-2"])
3493                    .current_dir(&repo_path)
3494                    .output()
3495                    .unwrap();
3496                let log_str = String::from_utf8_lossy(&log_output.stdout);
3497                assert!(
3498                    log_str.contains("Fix auth validation")
3499                        || log_str.contains("Add authentication")
3500                );
3501            }
3502            Err(_) => {
3503                // Expected in test environment without remote - that's fine
3504                // The important thing is we tested the code path without panicking
3505            }
3506        }
3507    }
3508
3509    #[test]
3510    fn test_branch_operations() {
3511        let (_temp_dir, repo_path) = create_test_repo();
3512        let repo = GitRepository::open(&repo_path).unwrap();
3513
3514        // Test get current branch - accept either main or master
3515        let current = repo.get_current_branch().unwrap();
3516        assert!(
3517            current == "master" || current == "main",
3518            "Expected default branch to be 'master' or 'main', got '{current}'"
3519        );
3520
3521        // Test create branch
3522        Command::new("git")
3523            .args(["checkout", "-b", "test-branch"])
3524            .current_dir(&repo_path)
3525            .output()
3526            .unwrap();
3527        let current = repo.get_current_branch().unwrap();
3528        assert_eq!(current, "test-branch");
3529    }
3530
3531    #[test]
3532    fn test_commit_operations() {
3533        let (_temp_dir, repo_path) = create_test_repo();
3534        let repo = GitRepository::open(&repo_path).unwrap();
3535
3536        // Test get head commit
3537        let head = repo.get_head_commit().unwrap();
3538        assert_eq!(head.message().unwrap().trim(), "Initial commit");
3539
3540        // Test get commit by hash
3541        let hash = head.id().to_string();
3542        let same_commit = repo.get_commit(&hash).unwrap();
3543        assert_eq!(head.id(), same_commit.id());
3544    }
3545
3546    #[test]
3547    fn test_checkout_safety_clean_repo() {
3548        let (_temp_dir, repo_path) = create_test_repo();
3549        let repo = GitRepository::open(&repo_path).unwrap();
3550
3551        // Create a test branch
3552        create_commit(&repo_path, "Second commit", "test.txt");
3553        Command::new("git")
3554            .args(["checkout", "-b", "test-branch"])
3555            .current_dir(&repo_path)
3556            .output()
3557            .unwrap();
3558
3559        // Test checkout safety with clean repo
3560        let safety_result = repo.check_checkout_safety("main");
3561        assert!(safety_result.is_ok());
3562        assert!(safety_result.unwrap().is_none()); // Clean repo should return None
3563    }
3564
3565    #[test]
3566    fn test_checkout_safety_with_modified_files() {
3567        let (_temp_dir, repo_path) = create_test_repo();
3568        let repo = GitRepository::open(&repo_path).unwrap();
3569
3570        // Create a test branch
3571        Command::new("git")
3572            .args(["checkout", "-b", "test-branch"])
3573            .current_dir(&repo_path)
3574            .output()
3575            .unwrap();
3576
3577        // Modify a file to create uncommitted changes
3578        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3579
3580        // Test checkout safety with modified files
3581        let safety_result = repo.check_checkout_safety("main");
3582        assert!(safety_result.is_ok());
3583        let safety_info = safety_result.unwrap();
3584        assert!(safety_info.is_some());
3585
3586        let info = safety_info.unwrap();
3587        assert!(!info.modified_files.is_empty());
3588        assert!(info.modified_files.contains(&"README.md".to_string()));
3589    }
3590
3591    #[test]
3592    fn test_unsafe_checkout_methods() {
3593        let (_temp_dir, repo_path) = create_test_repo();
3594        let repo = GitRepository::open(&repo_path).unwrap();
3595
3596        // Create a test branch
3597        create_commit(&repo_path, "Second commit", "test.txt");
3598        Command::new("git")
3599            .args(["checkout", "-b", "test-branch"])
3600            .current_dir(&repo_path)
3601            .output()
3602            .unwrap();
3603
3604        // Modify a file to create uncommitted changes
3605        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3606
3607        // Test unsafe checkout methods bypass safety checks
3608        let _result = repo.checkout_branch_unsafe("main");
3609        // Note: This might still fail due to git2 restrictions, but shouldn't hit our safety code
3610        // The important thing is that it doesn't trigger our safety confirmation
3611
3612        // Test unsafe commit checkout
3613        let head_commit = repo.get_head_commit().unwrap();
3614        let commit_hash = head_commit.id().to_string();
3615        let _result = repo.checkout_commit_unsafe(&commit_hash);
3616        // Similar to above - testing that safety is bypassed
3617    }
3618
3619    #[test]
3620    fn test_get_modified_files() {
3621        let (_temp_dir, repo_path) = create_test_repo();
3622        let repo = GitRepository::open(&repo_path).unwrap();
3623
3624        // Initially should have no modified files
3625        let modified = repo.get_modified_files().unwrap();
3626        assert!(modified.is_empty());
3627
3628        // Modify a file
3629        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3630
3631        // Should now detect the modified file
3632        let modified = repo.get_modified_files().unwrap();
3633        assert_eq!(modified.len(), 1);
3634        assert!(modified.contains(&"README.md".to_string()));
3635    }
3636
3637    #[test]
3638    fn test_get_staged_files() {
3639        let (_temp_dir, repo_path) = create_test_repo();
3640        let repo = GitRepository::open(&repo_path).unwrap();
3641
3642        // Initially should have no staged files
3643        let staged = repo.get_staged_files().unwrap();
3644        assert!(staged.is_empty());
3645
3646        // Create and stage a new file
3647        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3648        Command::new("git")
3649            .args(["add", "staged.txt"])
3650            .current_dir(&repo_path)
3651            .output()
3652            .unwrap();
3653
3654        // Should now detect the staged file
3655        let staged = repo.get_staged_files().unwrap();
3656        assert_eq!(staged.len(), 1);
3657        assert!(staged.contains(&"staged.txt".to_string()));
3658    }
3659
3660    #[test]
3661    fn test_create_stash_fallback() {
3662        let (_temp_dir, repo_path) = create_test_repo();
3663        let repo = GitRepository::open(&repo_path).unwrap();
3664
3665        // Test stash creation - newer git versions allow empty stashes
3666        let result = repo.create_stash("test stash");
3667
3668        // Either succeeds (newer git with empty stash) or fails with helpful message
3669        match result {
3670            Ok(stash_id) => {
3671                // Modern git allows empty stashes, verify we got a stash ID
3672                assert!(!stash_id.is_empty());
3673                assert!(stash_id.contains("stash") || stash_id.len() >= 7); // SHA or stash@{n}
3674            }
3675            Err(error) => {
3676                // Older git should fail with helpful message
3677                let error_msg = error.to_string();
3678                assert!(
3679                    error_msg.contains("No local changes to save")
3680                        || error_msg.contains("git stash push")
3681                );
3682            }
3683        }
3684    }
3685
3686    #[test]
3687    fn test_delete_branch_unsafe() {
3688        let (_temp_dir, repo_path) = create_test_repo();
3689        let repo = GitRepository::open(&repo_path).unwrap();
3690
3691        // Create a test branch
3692        create_commit(&repo_path, "Second commit", "test.txt");
3693        Command::new("git")
3694            .args(["checkout", "-b", "test-branch"])
3695            .current_dir(&repo_path)
3696            .output()
3697            .unwrap();
3698
3699        // Add another commit to the test branch to make it different from main
3700        create_commit(&repo_path, "Branch-specific commit", "branch.txt");
3701
3702        // Go back to main
3703        Command::new("git")
3704            .args(["checkout", "main"])
3705            .current_dir(&repo_path)
3706            .output()
3707            .unwrap();
3708
3709        // Test unsafe delete bypasses safety checks
3710        // Note: This may still fail if the branch has unpushed commits, but it should bypass our safety confirmation
3711        let result = repo.delete_branch_unsafe("test-branch");
3712        // Even if it fails, the key is that it didn't prompt for user confirmation
3713        // So we just check that it attempted the operation without interactive prompts
3714        let _ = result; // Don't assert success since delete may fail for git reasons
3715    }
3716
3717    #[test]
3718    fn test_force_push_unsafe() {
3719        let (_temp_dir, repo_path) = create_test_repo();
3720        let repo = GitRepository::open(&repo_path).unwrap();
3721
3722        // Create a test branch
3723        create_commit(&repo_path, "Second commit", "test.txt");
3724        Command::new("git")
3725            .args(["checkout", "-b", "test-branch"])
3726            .current_dir(&repo_path)
3727            .output()
3728            .unwrap();
3729
3730        // Test unsafe force push bypasses safety checks
3731        // Note: This will likely fail due to no remote, but it tests the safety bypass
3732        let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
3733        // The key is that it doesn't trigger safety confirmation dialogs
3734    }
3735
3736    #[test]
3737    fn test_cherry_pick_basic() {
3738        let (_temp_dir, repo_path) = create_test_repo();
3739        let repo = GitRepository::open(&repo_path).unwrap();
3740
3741        // Create a branch with a commit to cherry-pick
3742        repo.create_branch("source", None).unwrap();
3743        repo.checkout_branch("source").unwrap();
3744
3745        std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
3746        Command::new("git")
3747            .args(["add", "."])
3748            .current_dir(&repo_path)
3749            .output()
3750            .unwrap();
3751
3752        Command::new("git")
3753            .args(["commit", "-m", "Cherry commit"])
3754            .current_dir(&repo_path)
3755            .output()
3756            .unwrap();
3757
3758        let cherry_commit = repo.get_head_commit_hash().unwrap();
3759
3760        // Switch back to previous branch (where source was created from)
3761        // Using `git checkout -` is environment-agnostic
3762        Command::new("git")
3763            .args(["checkout", "-"])
3764            .current_dir(&repo_path)
3765            .output()
3766            .unwrap();
3767
3768        repo.create_branch("target", None).unwrap();
3769        repo.checkout_branch("target").unwrap();
3770
3771        // Cherry-pick the commit
3772        let new_commit = repo.cherry_pick(&cherry_commit).unwrap();
3773
3774        // Verify cherry-pick succeeded (commit exists)
3775        repo.repo
3776            .find_commit(git2::Oid::from_str(&new_commit).unwrap())
3777            .unwrap();
3778
3779        // Verify file exists on target branch
3780        assert!(
3781            repo_path.join("cherry.txt").exists(),
3782            "Cherry-picked file should exist"
3783        );
3784
3785        // Verify source branch is unchanged
3786        repo.checkout_branch("source").unwrap();
3787        let source_head = repo.get_head_commit_hash().unwrap();
3788        assert_eq!(
3789            source_head, cherry_commit,
3790            "Source branch should be unchanged"
3791        );
3792    }
3793
3794    #[test]
3795    fn test_cherry_pick_preserves_commit_message() {
3796        let (_temp_dir, repo_path) = create_test_repo();
3797        let repo = GitRepository::open(&repo_path).unwrap();
3798
3799        // Create commit with specific message
3800        repo.create_branch("msg-test", None).unwrap();
3801        repo.checkout_branch("msg-test").unwrap();
3802
3803        std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
3804        Command::new("git")
3805            .args(["add", "."])
3806            .current_dir(&repo_path)
3807            .output()
3808            .unwrap();
3809
3810        let commit_msg = "Test: Special commit message\n\nWith body";
3811        Command::new("git")
3812            .args(["commit", "-m", commit_msg])
3813            .current_dir(&repo_path)
3814            .output()
3815            .unwrap();
3816
3817        let original_commit = repo.get_head_commit_hash().unwrap();
3818
3819        // Cherry-pick to another branch (use previous branch via git checkout -)
3820        Command::new("git")
3821            .args(["checkout", "-"])
3822            .current_dir(&repo_path)
3823            .output()
3824            .unwrap();
3825        let new_commit = repo.cherry_pick(&original_commit).unwrap();
3826
3827        // Get commit message of new commit
3828        let output = Command::new("git")
3829            .args(["log", "-1", "--format=%B", &new_commit])
3830            .current_dir(&repo_path)
3831            .output()
3832            .unwrap();
3833
3834        let new_msg = String::from_utf8_lossy(&output.stdout);
3835        assert!(
3836            new_msg.contains("Special commit message"),
3837            "Should preserve commit message"
3838        );
3839    }
3840
3841    #[test]
3842    fn test_cherry_pick_handles_conflicts() {
3843        let (_temp_dir, repo_path) = create_test_repo();
3844        let repo = GitRepository::open(&repo_path).unwrap();
3845
3846        // Create conflicting content
3847        std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
3848        Command::new("git")
3849            .args(["add", "."])
3850            .current_dir(&repo_path)
3851            .output()
3852            .unwrap();
3853
3854        Command::new("git")
3855            .args(["commit", "-m", "Add conflict file"])
3856            .current_dir(&repo_path)
3857            .output()
3858            .unwrap();
3859
3860        // Create branch with different content
3861        repo.create_branch("conflict-branch", None).unwrap();
3862        repo.checkout_branch("conflict-branch").unwrap();
3863
3864        std::fs::write(repo_path.join("conflict.txt"), "Modified").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", "Modify conflict file"])
3873            .current_dir(&repo_path)
3874            .output()
3875            .unwrap();
3876
3877        let conflict_commit = repo.get_head_commit_hash().unwrap();
3878
3879        // Try to cherry-pick (should fail due to conflict)
3880        // Go back to previous branch
3881        Command::new("git")
3882            .args(["checkout", "-"])
3883            .current_dir(&repo_path)
3884            .output()
3885            .unwrap();
3886        std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
3887        Command::new("git")
3888            .args(["add", "."])
3889            .current_dir(&repo_path)
3890            .output()
3891            .unwrap();
3892
3893        Command::new("git")
3894            .args(["commit", "-m", "Different change"])
3895            .current_dir(&repo_path)
3896            .output()
3897            .unwrap();
3898
3899        // Cherry-pick should fail with conflict
3900        let result = repo.cherry_pick(&conflict_commit);
3901        assert!(result.is_err(), "Cherry-pick with conflict should fail");
3902    }
3903
3904    #[test]
3905    fn test_reset_to_head_clears_staged_files() {
3906        let (_temp_dir, repo_path) = create_test_repo();
3907        let repo = GitRepository::open(&repo_path).unwrap();
3908
3909        // Create and stage some files
3910        std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
3911        std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();
3912
3913        Command::new("git")
3914            .args(["add", "staged1.txt", "staged2.txt"])
3915            .current_dir(&repo_path)
3916            .output()
3917            .unwrap();
3918
3919        // Verify files are staged
3920        let staged_before = repo.get_staged_files().unwrap();
3921        assert_eq!(staged_before.len(), 2, "Should have 2 staged files");
3922
3923        // Reset to HEAD
3924        repo.reset_to_head().unwrap();
3925
3926        // Verify no files are staged after reset
3927        let staged_after = repo.get_staged_files().unwrap();
3928        assert_eq!(
3929            staged_after.len(),
3930            0,
3931            "Should have no staged files after reset"
3932        );
3933    }
3934
3935    #[test]
3936    fn test_reset_to_head_clears_modified_files() {
3937        let (_temp_dir, repo_path) = create_test_repo();
3938        let repo = GitRepository::open(&repo_path).unwrap();
3939
3940        // Modify an existing file
3941        std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();
3942
3943        // Stage the modification
3944        Command::new("git")
3945            .args(["add", "README.md"])
3946            .current_dir(&repo_path)
3947            .output()
3948            .unwrap();
3949
3950        // Verify file is modified and staged
3951        assert!(repo.is_dirty().unwrap(), "Repo should be dirty");
3952
3953        // Reset to HEAD
3954        repo.reset_to_head().unwrap();
3955
3956        // Verify repo is clean
3957        assert!(
3958            !repo.is_dirty().unwrap(),
3959            "Repo should be clean after reset"
3960        );
3961
3962        // Verify file content is restored
3963        let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
3964        assert_eq!(
3965            content, "# Test",
3966            "File should be restored to original content"
3967        );
3968    }
3969
3970    #[test]
3971    fn test_reset_to_head_preserves_untracked_files() {
3972        let (_temp_dir, repo_path) = create_test_repo();
3973        let repo = GitRepository::open(&repo_path).unwrap();
3974
3975        // Create untracked file
3976        std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();
3977
3978        // Stage some other file
3979        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3980        Command::new("git")
3981            .args(["add", "staged.txt"])
3982            .current_dir(&repo_path)
3983            .output()
3984            .unwrap();
3985
3986        // Reset to HEAD
3987        repo.reset_to_head().unwrap();
3988
3989        // Verify untracked file still exists
3990        assert!(
3991            repo_path.join("untracked.txt").exists(),
3992            "Untracked file should be preserved"
3993        );
3994
3995        // Verify staged file was removed (since it was never committed)
3996        assert!(
3997            !repo_path.join("staged.txt").exists(),
3998            "Staged but uncommitted file should be removed"
3999        );
4000    }
4001
4002    #[test]
4003    fn test_cherry_pick_does_not_modify_source() {
4004        let (_temp_dir, repo_path) = create_test_repo();
4005        let repo = GitRepository::open(&repo_path).unwrap();
4006
4007        // Create source branch with multiple commits
4008        repo.create_branch("feature", None).unwrap();
4009        repo.checkout_branch("feature").unwrap();
4010
4011        // Add multiple commits
4012        for i in 1..=3 {
4013            std::fs::write(
4014                repo_path.join(format!("file{i}.txt")),
4015                format!("Content {i}"),
4016            )
4017            .unwrap();
4018            Command::new("git")
4019                .args(["add", "."])
4020                .current_dir(&repo_path)
4021                .output()
4022                .unwrap();
4023
4024            Command::new("git")
4025                .args(["commit", "-m", &format!("Commit {i}")])
4026                .current_dir(&repo_path)
4027                .output()
4028                .unwrap();
4029        }
4030
4031        // Get source branch state
4032        let source_commits = Command::new("git")
4033            .args(["log", "--format=%H", "feature"])
4034            .current_dir(&repo_path)
4035            .output()
4036            .unwrap();
4037        let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();
4038
4039        // Cherry-pick middle commit to another branch
4040        let commits: Vec<&str> = source_state.lines().collect();
4041        let middle_commit = commits[1];
4042
4043        // Go back to previous branch
4044        Command::new("git")
4045            .args(["checkout", "-"])
4046            .current_dir(&repo_path)
4047            .output()
4048            .unwrap();
4049        repo.create_branch("target", None).unwrap();
4050        repo.checkout_branch("target").unwrap();
4051
4052        repo.cherry_pick(middle_commit).unwrap();
4053
4054        // Verify source branch is completely unchanged
4055        let after_commits = Command::new("git")
4056            .args(["log", "--format=%H", "feature"])
4057            .current_dir(&repo_path)
4058            .output()
4059            .unwrap();
4060        let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();
4061
4062        assert_eq!(
4063            source_state, after_state,
4064            "Source branch should be completely unchanged after cherry-pick"
4065        );
4066    }
4067
4068    #[test]
4069    fn test_detect_parent_branch() {
4070        let (_temp_dir, repo_path) = create_test_repo();
4071        let repo = GitRepository::open(&repo_path).unwrap();
4072
4073        // Create a custom base branch (not just main/master)
4074        repo.create_branch("dev123", None).unwrap();
4075        repo.checkout_branch("dev123").unwrap();
4076        create_commit(&repo_path, "Base commit on dev123", "base.txt");
4077
4078        // Create feature branch from dev123
4079        repo.create_branch("feature-branch", None).unwrap();
4080        repo.checkout_branch("feature-branch").unwrap();
4081        create_commit(&repo_path, "Feature commit", "feature.txt");
4082
4083        // Should detect dev123 as parent since it's the most recent common ancestor
4084        let detected_parent = repo.detect_parent_branch().unwrap();
4085
4086        // The algorithm should find dev123 through either Strategy 2 (default branch)
4087        // or Strategy 3 (common ancestor analysis)
4088        assert!(detected_parent.is_some(), "Should detect a parent branch");
4089
4090        // Since we can't guarantee which strategy will work in the test environment,
4091        // just verify it returns something reasonable
4092        let parent = detected_parent.unwrap();
4093        assert!(
4094            parent == "dev123" || parent == "main" || parent == "master",
4095            "Parent should be dev123, main, or master, got: {parent}"
4096        );
4097    }
4098}