cascade_cli/git/
repository.rs

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