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