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