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