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