cascade_cli/git/
repository.rs

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