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