cascade_cli/git/
repository.rs

1use crate::cli::output::Output;
2use crate::errors::{CascadeError, Result};
3use chrono;
4use dialoguer::{theme::ColorfulTheme, Confirm};
5use git2::{Oid, Repository, Signature};
6use std::path::{Path, PathBuf};
7use tracing::{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/// Wrapper around git2::Repository with safe operations
59///
60/// For thread safety, use the async variants (e.g., fetch_async, pull_async)
61/// which automatically handle threading using tokio::spawn_blocking.
62/// The async methods create new repository instances in background threads.
63pub struct GitRepository {
64    repo: Repository,
65    path: PathBuf,
66    ssl_config: Option<GitSslConfig>,
67    bitbucket_credentials: Option<BitbucketCredentials>,
68}
69
70#[derive(Debug, Clone)]
71struct BitbucketCredentials {
72    username: Option<String>,
73    token: Option<String>,
74}
75
76impl GitRepository {
77    /// Open a Git repository at the given path
78    /// Automatically loads SSL configuration from cascade config if available
79    pub fn open(path: &Path) -> Result<Self> {
80        let repo = Repository::discover(path)
81            .map_err(|e| CascadeError::config(format!("Not a git repository: {e}")))?;
82
83        let workdir = repo
84            .workdir()
85            .ok_or_else(|| CascadeError::config("Repository has no working directory"))?
86            .to_path_buf();
87
88        // Try to load SSL configuration from cascade config
89        let ssl_config = Self::load_ssl_config_from_cascade(&workdir);
90        let bitbucket_credentials = Self::load_bitbucket_credentials_from_cascade(&workdir);
91
92        Ok(Self {
93            repo,
94            path: workdir,
95            ssl_config,
96            bitbucket_credentials,
97        })
98    }
99
100    /// Load SSL configuration from cascade config file if it exists
101    fn load_ssl_config_from_cascade(repo_path: &Path) -> Option<GitSslConfig> {
102        // Try to load cascade configuration
103        let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
104        let config_path = config_dir.join("config.json");
105        let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
106
107        // Convert BitbucketConfig to GitSslConfig if SSL settings exist
108        if settings.bitbucket.accept_invalid_certs.is_some()
109            || settings.bitbucket.ca_bundle_path.is_some()
110        {
111            Some(GitSslConfig {
112                accept_invalid_certs: settings.bitbucket.accept_invalid_certs.unwrap_or(false),
113                ca_bundle_path: settings.bitbucket.ca_bundle_path,
114            })
115        } else {
116            None
117        }
118    }
119
120    /// Load Bitbucket credentials from cascade config file if it exists
121    fn load_bitbucket_credentials_from_cascade(repo_path: &Path) -> Option<BitbucketCredentials> {
122        // Try to load cascade configuration
123        let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
124        let config_path = config_dir.join("config.json");
125        let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
126
127        // Return credentials if any are configured
128        if settings.bitbucket.username.is_some() || settings.bitbucket.token.is_some() {
129            Some(BitbucketCredentials {
130                username: settings.bitbucket.username.clone(),
131                token: settings.bitbucket.token.clone(),
132            })
133        } else {
134            None
135        }
136    }
137
138    /// Get repository information
139    pub fn get_info(&self) -> Result<RepositoryInfo> {
140        let head_branch = self.get_current_branch().ok();
141        let head_commit = self.get_head_commit_hash().ok();
142        let is_dirty = self.is_dirty()?;
143        let untracked_files = self.get_untracked_files()?;
144
145        Ok(RepositoryInfo {
146            path: self.path.clone(),
147            head_branch,
148            head_commit,
149            is_dirty,
150            untracked_files,
151        })
152    }
153
154    /// Get the current branch name
155    pub fn get_current_branch(&self) -> Result<String> {
156        let head = self
157            .repo
158            .head()
159            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
160
161        if let Some(name) = head.shorthand() {
162            Ok(name.to_string())
163        } else {
164            // Detached HEAD - return commit hash
165            let commit = head
166                .peel_to_commit()
167                .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
168            Ok(format!("HEAD@{}", commit.id()))
169        }
170    }
171
172    /// Get the HEAD commit hash
173    pub fn get_head_commit_hash(&self) -> Result<String> {
174        let head = self
175            .repo
176            .head()
177            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
178
179        let commit = head
180            .peel_to_commit()
181            .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
182
183        Ok(commit.id().to_string())
184    }
185
186    /// Check if the working directory is dirty (has uncommitted changes)
187    pub fn is_dirty(&self) -> Result<bool> {
188        let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
189
190        for status in statuses.iter() {
191            let flags = status.status();
192
193            // Check for any modifications, additions, or deletions
194            if flags.intersects(
195                git2::Status::INDEX_MODIFIED
196                    | git2::Status::INDEX_NEW
197                    | git2::Status::INDEX_DELETED
198                    | git2::Status::WT_MODIFIED
199                    | git2::Status::WT_NEW
200                    | git2::Status::WT_DELETED,
201            ) {
202                return Ok(true);
203            }
204        }
205
206        Ok(false)
207    }
208
209    /// Get list of untracked files
210    pub fn get_untracked_files(&self) -> Result<Vec<String>> {
211        let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
212
213        let mut untracked = Vec::new();
214        for status in statuses.iter() {
215            if status.status().contains(git2::Status::WT_NEW) {
216                if let Some(path) = status.path() {
217                    untracked.push(path.to_string());
218                }
219            }
220        }
221
222        Ok(untracked)
223    }
224
225    /// Create a new branch
226    pub fn create_branch(&self, name: &str, target: Option<&str>) -> Result<()> {
227        let target_commit = if let Some(target) = target {
228            // Find the specified target commit/branch
229            let target_obj = self.repo.revparse_single(target).map_err(|e| {
230                CascadeError::branch(format!("Could not find target '{target}': {e}"))
231            })?;
232            target_obj.peel_to_commit().map_err(|e| {
233                CascadeError::branch(format!("Target '{target}' is not a commit: {e}"))
234            })?
235        } else {
236            // Use current HEAD
237            let head = self
238                .repo
239                .head()
240                .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
241            head.peel_to_commit()
242                .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?
243        };
244
245        self.repo
246            .branch(name, &target_commit, false)
247            .map_err(|e| CascadeError::branch(format!("Could not create branch '{name}': {e}")))?;
248
249        // Branch creation logging is handled by the caller for clean output
250        Ok(())
251    }
252
253    /// Switch to a branch with safety checks
254    pub fn checkout_branch(&self, name: &str) -> Result<()> {
255        self.checkout_branch_with_options(name, false)
256    }
257
258    /// Switch to a branch with force option to bypass safety checks
259    pub fn checkout_branch_unsafe(&self, name: &str) -> Result<()> {
260        self.checkout_branch_with_options(name, true)
261    }
262
263    /// Internal branch checkout implementation with safety options
264    fn checkout_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
265        info!("Attempting to checkout branch: {}", name);
266
267        // Enhanced safety check: Detect uncommitted work before checkout
268        if !force_unsafe {
269            let safety_result = self.check_checkout_safety(name)?;
270            if let Some(safety_info) = safety_result {
271                // Repository has uncommitted changes, get user confirmation
272                self.handle_checkout_confirmation(name, &safety_info)?;
273            }
274        }
275
276        // Find the branch
277        let branch = self
278            .repo
279            .find_branch(name, git2::BranchType::Local)
280            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
281
282        let branch_ref = branch.get();
283        let tree = branch_ref.peel_to_tree().map_err(|e| {
284            CascadeError::branch(format!("Could not get tree for branch '{name}': {e}"))
285        })?;
286
287        // Checkout the tree
288        self.repo
289            .checkout_tree(tree.as_object(), None)
290            .map_err(|e| {
291                CascadeError::branch(format!("Could not checkout branch '{name}': {e}"))
292            })?;
293
294        // Update HEAD
295        self.repo
296            .set_head(&format!("refs/heads/{name}"))
297            .map_err(|e| CascadeError::branch(format!("Could not update HEAD to '{name}': {e}")))?;
298
299        Output::success(format!("Switched to branch '{name}'"));
300        Ok(())
301    }
302
303    /// Checkout a specific commit (detached HEAD) with safety checks
304    pub fn checkout_commit(&self, commit_hash: &str) -> Result<()> {
305        self.checkout_commit_with_options(commit_hash, false)
306    }
307
308    /// Checkout a specific commit with force option to bypass safety checks
309    pub fn checkout_commit_unsafe(&self, commit_hash: &str) -> Result<()> {
310        self.checkout_commit_with_options(commit_hash, true)
311    }
312
313    /// Internal commit checkout implementation with safety options
314    fn checkout_commit_with_options(&self, commit_hash: &str, force_unsafe: bool) -> Result<()> {
315        info!("Attempting to checkout commit: {}", commit_hash);
316
317        // Enhanced safety check: Detect uncommitted work before checkout
318        if !force_unsafe {
319            let safety_result = self.check_checkout_safety(&format!("commit:{commit_hash}"))?;
320            if let Some(safety_info) = safety_result {
321                // Repository has uncommitted changes, get user confirmation
322                self.handle_checkout_confirmation(&format!("commit {commit_hash}"), &safety_info)?;
323            }
324        }
325
326        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
327
328        let commit = self.repo.find_commit(oid).map_err(|e| {
329            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
330        })?;
331
332        let tree = commit.tree().map_err(|e| {
333            CascadeError::branch(format!(
334                "Could not get tree for commit '{commit_hash}': {e}"
335            ))
336        })?;
337
338        // Checkout the tree
339        self.repo
340            .checkout_tree(tree.as_object(), None)
341            .map_err(|e| {
342                CascadeError::branch(format!("Could not checkout commit '{commit_hash}': {e}"))
343            })?;
344
345        // Update HEAD to the commit (detached HEAD)
346        self.repo.set_head_detached(oid).map_err(|e| {
347            CascadeError::branch(format!(
348                "Could not update HEAD to commit '{commit_hash}': {e}"
349            ))
350        })?;
351
352        Output::success(format!(
353            "Checked out commit '{commit_hash}' (detached HEAD)"
354        ));
355        Ok(())
356    }
357
358    /// Check if a branch exists
359    pub fn branch_exists(&self, name: &str) -> bool {
360        self.repo.find_branch(name, git2::BranchType::Local).is_ok()
361    }
362
363    /// Check if a branch exists locally, and if not, attempt to fetch it from remote
364    pub fn branch_exists_or_fetch(&self, name: &str) -> Result<bool> {
365        // 1. Check if branch exists locally first
366        if self.repo.find_branch(name, git2::BranchType::Local).is_ok() {
367            return Ok(true);
368        }
369
370        // 2. Try to fetch it from remote
371        println!("🔍 Branch '{name}' not found locally, trying to fetch from remote...");
372
373        use std::process::Command;
374
375        // Try: git fetch origin release/12.34:release/12.34
376        let fetch_result = Command::new("git")
377            .args(["fetch", "origin", &format!("{name}:{name}")])
378            .current_dir(&self.path)
379            .output();
380
381        match fetch_result {
382            Ok(output) => {
383                if output.status.success() {
384                    println!("✅ Successfully fetched '{name}' from origin");
385                    // 3. Check again locally after fetch
386                    return Ok(self.repo.find_branch(name, git2::BranchType::Local).is_ok());
387                } else {
388                    let stderr = String::from_utf8_lossy(&output.stderr);
389                    tracing::debug!("Failed to fetch branch '{name}': {stderr}");
390                }
391            }
392            Err(e) => {
393                tracing::debug!("Git fetch command failed: {e}");
394            }
395        }
396
397        // 4. Try alternative fetch patterns for common branch naming
398        if name.contains('/') {
399            println!("🔍 Trying alternative fetch patterns...");
400
401            // Try: git fetch origin (to get all refs, then checkout locally)
402            let fetch_all_result = Command::new("git")
403                .args(["fetch", "origin"])
404                .current_dir(&self.path)
405                .output();
406
407            if let Ok(output) = fetch_all_result {
408                if output.status.success() {
409                    // Try to create local branch from remote
410                    let checkout_result = Command::new("git")
411                        .args(["checkout", "-b", name, &format!("origin/{name}")])
412                        .current_dir(&self.path)
413                        .output();
414
415                    if let Ok(checkout_output) = checkout_result {
416                        if checkout_output.status.success() {
417                            println!(
418                                "✅ Successfully created local branch '{name}' from origin/{name}"
419                            );
420                            return Ok(true);
421                        }
422                    }
423                }
424            }
425        }
426
427        // 5. Only fail if it doesn't exist anywhere
428        Ok(false)
429    }
430
431    /// Get the commit hash for a specific branch without switching branches
432    pub fn get_branch_commit_hash(&self, branch_name: &str) -> Result<String> {
433        let branch = self
434            .repo
435            .find_branch(branch_name, git2::BranchType::Local)
436            .map_err(|e| {
437                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
438            })?;
439
440        let commit = branch.get().peel_to_commit().map_err(|e| {
441            CascadeError::branch(format!(
442                "Could not get commit for branch '{branch_name}': {e}"
443            ))
444        })?;
445
446        Ok(commit.id().to_string())
447    }
448
449    /// List all local branches
450    pub fn list_branches(&self) -> Result<Vec<String>> {
451        let branches = self
452            .repo
453            .branches(Some(git2::BranchType::Local))
454            .map_err(CascadeError::Git)?;
455
456        let mut branch_names = Vec::new();
457        for branch in branches {
458            let (branch, _) = branch.map_err(CascadeError::Git)?;
459            if let Some(name) = branch.name().map_err(CascadeError::Git)? {
460                branch_names.push(name.to_string());
461            }
462        }
463
464        Ok(branch_names)
465    }
466
467    /// Create a commit with all staged changes
468    pub fn commit(&self, message: &str) -> Result<String> {
469        let signature = self.get_signature()?;
470        let tree_id = self.get_index_tree()?;
471        let tree = self.repo.find_tree(tree_id).map_err(CascadeError::Git)?;
472
473        // Get parent commits
474        let head = self.repo.head().map_err(CascadeError::Git)?;
475        let parent_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
476
477        let commit_id = self
478            .repo
479            .commit(
480                Some("HEAD"),
481                &signature,
482                &signature,
483                message,
484                &tree,
485                &[&parent_commit],
486            )
487            .map_err(CascadeError::Git)?;
488
489        Output::success(format!("Created commit: {commit_id} - {message}"));
490        Ok(commit_id.to_string())
491    }
492
493    /// Stage all changes
494    pub fn stage_all(&self) -> Result<()> {
495        let mut index = self.repo.index().map_err(CascadeError::Git)?;
496
497        index
498            .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
499            .map_err(CascadeError::Git)?;
500
501        index.write().map_err(CascadeError::Git)?;
502
503        tracing::debug!("Staged all changes");
504        Ok(())
505    }
506
507    /// Stage only specific files (safer than stage_all during rebase)
508    pub fn stage_files(&self, file_paths: &[&str]) -> Result<()> {
509        if file_paths.is_empty() {
510            tracing::debug!("No files to stage");
511            return Ok(());
512        }
513
514        let mut index = self.repo.index().map_err(CascadeError::Git)?;
515
516        for file_path in file_paths {
517            index
518                .add_path(std::path::Path::new(file_path))
519                .map_err(CascadeError::Git)?;
520        }
521
522        index.write().map_err(CascadeError::Git)?;
523
524        tracing::debug!(
525            "Staged {} specific files: {:?}",
526            file_paths.len(),
527            file_paths
528        );
529        Ok(())
530    }
531
532    /// Stage only files that had conflicts (safer for rebase operations)
533    pub fn stage_conflict_resolved_files(&self) -> Result<()> {
534        let conflicted_files = self.get_conflicted_files()?;
535        if conflicted_files.is_empty() {
536            tracing::debug!("No conflicted files to stage");
537            return Ok(());
538        }
539
540        let file_paths: Vec<&str> = conflicted_files.iter().map(|s| s.as_str()).collect();
541        self.stage_files(&file_paths)?;
542
543        tracing::debug!("Staged {} conflict-resolved files", conflicted_files.len());
544        Ok(())
545    }
546
547    /// Get repository path
548    pub fn path(&self) -> &Path {
549        &self.path
550    }
551
552    /// Check if a commit exists
553    pub fn commit_exists(&self, commit_hash: &str) -> Result<bool> {
554        match Oid::from_str(commit_hash) {
555            Ok(oid) => match self.repo.find_commit(oid) {
556                Ok(_) => Ok(true),
557                Err(_) => Ok(false),
558            },
559            Err(_) => Ok(false),
560        }
561    }
562
563    /// Get the HEAD commit object
564    pub fn get_head_commit(&self) -> Result<git2::Commit<'_>> {
565        let head = self
566            .repo
567            .head()
568            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
569        head.peel_to_commit()
570            .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))
571    }
572
573    /// Get a commit object by hash
574    pub fn get_commit(&self, commit_hash: &str) -> Result<git2::Commit<'_>> {
575        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
576
577        self.repo.find_commit(oid).map_err(CascadeError::Git)
578    }
579
580    /// Get the commit hash at the head of a branch
581    pub fn get_branch_head(&self, branch_name: &str) -> Result<String> {
582        let branch = self
583            .repo
584            .find_branch(branch_name, git2::BranchType::Local)
585            .map_err(|e| {
586                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
587            })?;
588
589        let commit = branch.get().peel_to_commit().map_err(|e| {
590            CascadeError::branch(format!(
591                "Could not get commit for branch '{branch_name}': {e}"
592            ))
593        })?;
594
595        Ok(commit.id().to_string())
596    }
597
598    /// Get a signature for commits
599    fn get_signature(&self) -> Result<Signature<'_>> {
600        // Try to get signature from Git config
601        if let Ok(config) = self.repo.config() {
602            if let (Ok(name), Ok(email)) = (
603                config.get_string("user.name"),
604                config.get_string("user.email"),
605            ) {
606                return Signature::now(&name, &email).map_err(CascadeError::Git);
607            }
608        }
609
610        // Fallback to default signature
611        Signature::now("Cascade CLI", "cascade@example.com").map_err(CascadeError::Git)
612    }
613
614    /// Configure remote callbacks with SSL settings
615    /// Priority: Cascade SSL config > Git config > Default
616    fn configure_remote_callbacks(&self) -> Result<git2::RemoteCallbacks<'_>> {
617        let mut callbacks = git2::RemoteCallbacks::new();
618
619        // Configure authentication with comprehensive credential support
620        let bitbucket_credentials = self.bitbucket_credentials.clone();
621        callbacks.credentials(move |url, username_from_url, allowed_types| {
622            tracing::debug!(
623                "Authentication requested for URL: {}, username: {:?}, allowed_types: {:?}",
624                url,
625                username_from_url,
626                allowed_types
627            );
628
629            // For SSH URLs with username
630            if allowed_types.contains(git2::CredentialType::SSH_KEY) {
631                if let Some(username) = username_from_url {
632                    tracing::debug!("Trying SSH key authentication for user: {}", username);
633                    return git2::Cred::ssh_key_from_agent(username);
634                }
635            }
636
637            // For HTTPS URLs, try multiple authentication methods in sequence
638            if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
639                if url.contains("bitbucket") {
640                    if let Some(creds) = &bitbucket_credentials {
641                        // Method 1: Username + Token (common for Bitbucket)
642                        if let (Some(username), Some(token)) = (&creds.username, &creds.token) {
643                            tracing::debug!("Trying Bitbucket username + token authentication");
644                            return git2::Cred::userpass_plaintext(username, token);
645                        }
646
647                        // Method 2: Token as username, empty password (alternate Bitbucket format)
648                        if let Some(token) = &creds.token {
649                            tracing::debug!("Trying Bitbucket token-as-username authentication");
650                            return git2::Cred::userpass_plaintext(token, "");
651                        }
652
653                        // Method 3: Just username (will prompt for password or use credential helper)
654                        if let Some(username) = &creds.username {
655                            tracing::debug!("Trying Bitbucket username authentication (will use credential helper)");
656                            return git2::Cred::username(username);
657                        }
658                    }
659                }
660
661                // Method 4: Default credential helper for all HTTPS URLs
662                tracing::debug!("Trying default credential helper for HTTPS authentication");
663                return git2::Cred::default();
664            }
665
666            // Fallback to default for any other cases
667            tracing::debug!("Using default credential fallback");
668            git2::Cred::default()
669        });
670
671        // Configure SSL certificate checking with system certificates by default
672        // This matches what tools like Graphite, Sapling, and Phabricator do
673        // Priority: 1. Use system certificates (default), 2. Manual overrides only if needed
674
675        let mut ssl_configured = false;
676
677        // Check for manual SSL overrides first (only when user explicitly needs them)
678        if let Some(ssl_config) = &self.ssl_config {
679            if ssl_config.accept_invalid_certs {
680                Output::warning(
681                    "SSL certificate verification DISABLED via Cascade config - this is insecure!",
682                );
683                callbacks.certificate_check(|_cert, _host| {
684                    tracing::debug!("⚠️  Accepting invalid certificate for host: {}", _host);
685                    Ok(git2::CertificateCheckStatus::CertificateOk)
686                });
687                ssl_configured = true;
688            } else if let Some(ca_path) = &ssl_config.ca_bundle_path {
689                Output::info(format!(
690                    "Using custom CA bundle from Cascade config: {ca_path}"
691                ));
692                callbacks.certificate_check(|_cert, host| {
693                    tracing::debug!("Using custom CA bundle for host: {}", host);
694                    Ok(git2::CertificateCheckStatus::CertificateOk)
695                });
696                ssl_configured = true;
697            }
698        }
699
700        // Check git config for manual overrides
701        if !ssl_configured {
702            if let Ok(config) = self.repo.config() {
703                let ssl_verify = config.get_bool("http.sslVerify").unwrap_or(true);
704
705                if !ssl_verify {
706                    Output::warning(
707                        "SSL certificate verification DISABLED via git config - this is insecure!",
708                    );
709                    callbacks.certificate_check(|_cert, host| {
710                        tracing::debug!("⚠️  Bypassing SSL verification for host: {}", host);
711                        Ok(git2::CertificateCheckStatus::CertificateOk)
712                    });
713                    ssl_configured = true;
714                } else if let Ok(ca_path) = config.get_string("http.sslCAInfo") {
715                    Output::info(format!("Using custom CA bundle from git config: {ca_path}"));
716                    callbacks.certificate_check(|_cert, host| {
717                        tracing::debug!("Using git config CA bundle for host: {}", host);
718                        Ok(git2::CertificateCheckStatus::CertificateOk)
719                    });
720                    ssl_configured = true;
721                }
722            }
723        }
724
725        // DEFAULT BEHAVIOR: Use system certificates (like git CLI and other modern tools)
726        // This should work out-of-the-box in corporate environments
727        if !ssl_configured {
728            tracing::debug!(
729                "Using system certificate store for SSL verification (default behavior)"
730            );
731
732            // For macOS with SecureTransport backend, try default certificate validation first
733            if cfg!(target_os = "macos") {
734                tracing::debug!("macOS detected - using default certificate validation");
735                // Don't set any certificate callback - let git2 use its default behavior
736                // This often works better with SecureTransport backend on macOS
737            } else {
738                // Use CertificatePassthrough for other platforms
739                callbacks.certificate_check(|_cert, host| {
740                    tracing::debug!("System certificate validation for host: {}", host);
741                    Ok(git2::CertificateCheckStatus::CertificatePassthrough)
742                });
743            }
744        }
745
746        Ok(callbacks)
747    }
748
749    /// Get the tree ID from the current index
750    fn get_index_tree(&self) -> Result<Oid> {
751        let mut index = self.repo.index().map_err(CascadeError::Git)?;
752
753        index.write_tree().map_err(CascadeError::Git)
754    }
755
756    /// Get repository status
757    pub fn get_status(&self) -> Result<git2::Statuses<'_>> {
758        self.repo.statuses(None).map_err(CascadeError::Git)
759    }
760
761    /// Get remote URL for a given remote name
762    pub fn get_remote_url(&self, name: &str) -> Result<String> {
763        let remote = self.repo.find_remote(name).map_err(CascadeError::Git)?;
764        Ok(remote.url().unwrap_or("unknown").to_string())
765    }
766
767    /// Diagnose git2 TLS and SSH support capabilities
768    /// This helps debug why TLS streams might not be found
769    pub fn diagnose_git2_support(&self) -> Result<()> {
770        let version = git2::Version::get();
771
772        println!("🔍 Git2 Feature Support Diagnosis:");
773        println!("  HTTPS/TLS support: {}", version.https());
774        println!("  SSH support: {}", version.ssh());
775
776        if !version.https() {
777            println!("❌ TLS streams NOT available - this explains TLS connection failures!");
778            println!("   Solution: Add 'https' feature to git2 dependency in Cargo.toml");
779            println!("   Current: git2 = {{ version = \"0.20.2\", default-features = false, features = [\"vendored-libgit2\"] }}");
780            println!("   Fixed:   git2 = {{ version = \"0.20.2\", features = [\"vendored-libgit2\", \"https\", \"ssh\"] }}");
781        } else {
782            println!("✅ TLS streams available");
783        }
784
785        if !version.ssh() {
786            println!("❌ SSH support NOT available");
787            println!("   Add 'ssh' feature to git2 dependency");
788        } else {
789            println!("✅ SSH support available");
790        }
791
792        // Additional git2 feature information
793        println!("\n📋 Additional git2 build information:");
794        let libgit2_version = version.libgit2_version();
795        println!(
796            "  libgit2 version: {}.{}.{}",
797            libgit2_version.0, libgit2_version.1, libgit2_version.2
798        );
799
800        println!("\n💡 Recommendation:");
801        if !version.https() || !version.ssh() {
802            println!("  Your git2 is built without TLS/SSH support, causing fallback to git CLI.");
803            println!("  Enable the missing features in Cargo.toml for better performance and reliability.");
804        } else {
805            println!(
806                "  git2 has full TLS/SSH support. Network issues may be configuration-related."
807            );
808        }
809
810        Ok(())
811    }
812
813    /// Cherry-pick a specific commit to the current branch
814    pub fn cherry_pick(&self, commit_hash: &str) -> Result<String> {
815        tracing::debug!("Cherry-picking commit {}", commit_hash);
816
817        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
818        let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
819
820        // Get the commit's tree
821        let commit_tree = commit.tree().map_err(CascadeError::Git)?;
822
823        // Get parent tree for merge base
824        let parent_commit = if commit.parent_count() > 0 {
825            commit.parent(0).map_err(CascadeError::Git)?
826        } else {
827            // Root commit - use empty tree
828            let empty_tree_oid = self.repo.treebuilder(None)?.write()?;
829            let empty_tree = self.repo.find_tree(empty_tree_oid)?;
830            let sig = self.get_signature()?;
831            return self
832                .repo
833                .commit(
834                    Some("HEAD"),
835                    &sig,
836                    &sig,
837                    commit.message().unwrap_or("Cherry-picked commit"),
838                    &empty_tree,
839                    &[],
840                )
841                .map(|oid| oid.to_string())
842                .map_err(CascadeError::Git);
843        };
844
845        let parent_tree = parent_commit.tree().map_err(CascadeError::Git)?;
846
847        // Get current HEAD tree for 3-way merge
848        let head_commit = self.get_head_commit()?;
849        let head_tree = head_commit.tree().map_err(CascadeError::Git)?;
850
851        // Perform 3-way merge
852        let mut index = self
853            .repo
854            .merge_trees(&parent_tree, &head_tree, &commit_tree, None)
855            .map_err(CascadeError::Git)?;
856
857        // Check for conflicts
858        if index.has_conflicts() {
859            return Err(CascadeError::branch(format!(
860                "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
861            )));
862        }
863
864        // Write merged tree
865        let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
866        let merged_tree = self
867            .repo
868            .find_tree(merged_tree_oid)
869            .map_err(CascadeError::Git)?;
870
871        // Create new commit
872        let signature = self.get_signature()?;
873        let message = format!("Cherry-pick: {}", commit.message().unwrap_or(""));
874
875        let new_commit_oid = self
876            .repo
877            .commit(
878                Some("HEAD"),
879                &signature,
880                &signature,
881                &message,
882                &merged_tree,
883                &[&head_commit],
884            )
885            .map_err(CascadeError::Git)?;
886
887        tracing::info!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
888        Ok(new_commit_oid.to_string())
889    }
890
891    /// Check for merge conflicts in the index
892    pub fn has_conflicts(&self) -> Result<bool> {
893        let index = self.repo.index().map_err(CascadeError::Git)?;
894        Ok(index.has_conflicts())
895    }
896
897    /// Get list of conflicted files
898    pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
899        let index = self.repo.index().map_err(CascadeError::Git)?;
900
901        let mut conflicts = Vec::new();
902
903        // Iterate through index conflicts
904        let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;
905
906        for conflict in conflict_iter {
907            let conflict = conflict.map_err(CascadeError::Git)?;
908            if let Some(our) = conflict.our {
909                if let Ok(path) = std::str::from_utf8(&our.path) {
910                    conflicts.push(path.to_string());
911                }
912            } else if let Some(their) = conflict.their {
913                if let Ok(path) = std::str::from_utf8(&their.path) {
914                    conflicts.push(path.to_string());
915                }
916            }
917        }
918
919        Ok(conflicts)
920    }
921
922    /// Fetch from remote origin
923    pub fn fetch(&self) -> Result<()> {
924        tracing::info!("Fetching from origin");
925
926        let mut remote = self
927            .repo
928            .find_remote("origin")
929            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
930
931        // Configure callbacks with SSL settings from git config
932        let callbacks = self.configure_remote_callbacks()?;
933
934        // Fetch options with authentication and SSL config
935        let mut fetch_options = git2::FetchOptions::new();
936        fetch_options.remote_callbacks(callbacks);
937
938        // Fetch with authentication
939        match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
940            Ok(_) => {
941                tracing::debug!("Fetch completed successfully");
942                Ok(())
943            }
944            Err(e) => {
945                // Check if this is a TLS/SSL error that might be resolved by falling back to git CLI
946                let error_string = e.to_string();
947                if error_string.contains("TLS stream") || error_string.contains("SSL") {
948                    tracing::warn!(
949                        "git2 TLS error detected: {}, falling back to git CLI for fetch operation",
950                        e
951                    );
952                    return self.fetch_with_git_cli();
953                }
954                Err(CascadeError::Git(e))
955            }
956        }
957    }
958
959    /// Pull changes from remote (fetch + merge)
960    pub fn pull(&self, branch: &str) -> Result<()> {
961        tracing::info!("Pulling branch: {}", branch);
962
963        // First fetch - this now includes TLS fallback
964        match self.fetch() {
965            Ok(_) => {}
966            Err(e) => {
967                // If fetch failed even with CLI fallback, try full git pull as last resort
968                let error_string = e.to_string();
969                if error_string.contains("TLS stream") || error_string.contains("SSL") {
970                    tracing::warn!(
971                        "git2 TLS error detected: {}, falling back to git CLI for pull operation",
972                        e
973                    );
974                    return self.pull_with_git_cli(branch);
975                }
976                return Err(e);
977            }
978        }
979
980        // Get remote tracking branch
981        let remote_branch_name = format!("origin/{branch}");
982        let remote_oid = self
983            .repo
984            .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
985            .map_err(|e| {
986                CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
987            })?;
988
989        let remote_commit = self
990            .repo
991            .find_commit(remote_oid)
992            .map_err(CascadeError::Git)?;
993
994        // Get current HEAD
995        let head_commit = self.get_head_commit()?;
996
997        // Check if we need to merge
998        if head_commit.id() == remote_commit.id() {
999            tracing::debug!("Already up to date");
1000            return Ok(());
1001        }
1002
1003        // Perform merge
1004        let head_tree = head_commit.tree().map_err(CascadeError::Git)?;
1005        let remote_tree = remote_commit.tree().map_err(CascadeError::Git)?;
1006
1007        // Find merge base
1008        let merge_base_oid = self
1009            .repo
1010            .merge_base(head_commit.id(), remote_commit.id())
1011            .map_err(CascadeError::Git)?;
1012        let merge_base_commit = self
1013            .repo
1014            .find_commit(merge_base_oid)
1015            .map_err(CascadeError::Git)?;
1016        let merge_base_tree = merge_base_commit.tree().map_err(CascadeError::Git)?;
1017
1018        // 3-way merge
1019        let mut index = self
1020            .repo
1021            .merge_trees(&merge_base_tree, &head_tree, &remote_tree, None)
1022            .map_err(CascadeError::Git)?;
1023
1024        if index.has_conflicts() {
1025            return Err(CascadeError::branch(
1026                "Pull has conflicts that need manual resolution".to_string(),
1027            ));
1028        }
1029
1030        // Write merged tree and create merge commit
1031        let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
1032        let merged_tree = self
1033            .repo
1034            .find_tree(merged_tree_oid)
1035            .map_err(CascadeError::Git)?;
1036
1037        let signature = self.get_signature()?;
1038        let message = format!("Merge branch '{branch}' from origin");
1039
1040        self.repo
1041            .commit(
1042                Some("HEAD"),
1043                &signature,
1044                &signature,
1045                &message,
1046                &merged_tree,
1047                &[&head_commit, &remote_commit],
1048            )
1049            .map_err(CascadeError::Git)?;
1050
1051        tracing::info!("Pull completed successfully");
1052        Ok(())
1053    }
1054
1055    /// Push current branch to remote
1056    pub fn push(&self, branch: &str) -> Result<()> {
1057        // Pushing branch to remote
1058
1059        let mut remote = self
1060            .repo
1061            .find_remote("origin")
1062            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1063
1064        let remote_url = remote.url().unwrap_or("unknown").to_string();
1065        tracing::debug!("Remote URL: {}", remote_url);
1066
1067        let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1068        tracing::debug!("Push refspec: {}", refspec);
1069
1070        // Configure callbacks with enhanced SSL settings and error handling
1071        let mut callbacks = self.configure_remote_callbacks()?;
1072
1073        // Add enhanced progress and error callbacks for better debugging
1074        callbacks.push_update_reference(|refname, status| {
1075            if let Some(msg) = status {
1076                tracing::error!("Push failed for ref {}: {}", refname, msg);
1077                return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1078            }
1079            tracing::debug!("Push succeeded for ref: {}", refname);
1080            Ok(())
1081        });
1082
1083        // Push options with authentication and SSL config
1084        let mut push_options = git2::PushOptions::new();
1085        push_options.remote_callbacks(callbacks);
1086
1087        // Attempt push with enhanced error reporting
1088        match remote.push(&[&refspec], Some(&mut push_options)) {
1089            Ok(_) => {
1090                tracing::info!("Push completed successfully for branch: {}", branch);
1091                Ok(())
1092            }
1093            Err(e) => {
1094                // Check if this is a TLS/SSL or auth error that might be resolved by falling back to git CLI
1095                let error_string = e.to_string();
1096                tracing::debug!("git2 push error: {} (class: {:?})", error_string, e.class());
1097
1098                if error_string.contains("TLS stream")
1099                    || error_string.contains("SSL")
1100                    || e.class() == git2::ErrorClass::Ssl
1101                    || error_string.contains("authentication required")
1102                    || error_string.contains("no callback set")
1103                    || e.class() == git2::ErrorClass::Http
1104                {
1105                    // Silently fall back to git CLI without logging
1106                    return self.push_with_git_cli(branch);
1107                }
1108
1109                // Create concise error message
1110                let error_msg = if e.to_string().contains("authentication") {
1111                    format!(
1112                        "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1113                    )
1114                } else {
1115                    format!("Failed to push branch '{branch}': {e}")
1116                };
1117
1118                tracing::error!("{}", error_msg);
1119                Err(CascadeError::branch(error_msg))
1120            }
1121        }
1122    }
1123
1124    /// Fallback push method using git CLI instead of git2
1125    /// This is used when git2 has TLS/SSL or auth issues but git CLI works fine
1126    fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1127        let output = std::process::Command::new("git")
1128            .args(["push", "origin", branch])
1129            .current_dir(&self.path)
1130            .output()
1131            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1132
1133        if output.status.success() {
1134            // Silent success - no need to log when fallback works
1135            Ok(())
1136        } else {
1137            let stderr = String::from_utf8_lossy(&output.stderr);
1138            let _stdout = String::from_utf8_lossy(&output.stdout);
1139            // Extract the most relevant error message
1140            let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
1141                "Network error: Unable to connect to repository (VPN may be required)".to_string()
1142            } else if stderr.contains("repository") && stderr.contains("not found") {
1143                "Repository not found - check your Bitbucket configuration".to_string()
1144            } else if stderr.contains("authentication") || stderr.contains("403") {
1145                "Authentication failed - check your credentials".to_string()
1146            } else {
1147                // For other errors, just show the stderr without the verbose prefix
1148                stderr.trim().to_string()
1149            };
1150            tracing::error!("{}", error_msg);
1151            Err(CascadeError::branch(error_msg))
1152        }
1153    }
1154
1155    /// Fallback fetch method using git CLI instead of git2
1156    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1157    fn fetch_with_git_cli(&self) -> Result<()> {
1158        tracing::info!("Using git CLI fallback for fetch operation");
1159
1160        let output = std::process::Command::new("git")
1161            .args(["fetch", "origin"])
1162            .current_dir(&self.path)
1163            .output()
1164            .map_err(|e| {
1165                CascadeError::Git(git2::Error::from_str(&format!(
1166                    "Failed to execute git command: {e}"
1167                )))
1168            })?;
1169
1170        if output.status.success() {
1171            tracing::info!("✅ Git CLI fetch succeeded");
1172            Ok(())
1173        } else {
1174            let stderr = String::from_utf8_lossy(&output.stderr);
1175            let stdout = String::from_utf8_lossy(&output.stdout);
1176            let error_msg = format!(
1177                "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
1178                output.status, stdout, stderr
1179            );
1180            tracing::error!("{}", error_msg);
1181            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1182        }
1183    }
1184
1185    /// Fallback pull method using git CLI instead of git2
1186    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1187    fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
1188        tracing::info!("Using git CLI fallback for pull operation: {}", branch);
1189
1190        let output = std::process::Command::new("git")
1191            .args(["pull", "origin", branch])
1192            .current_dir(&self.path)
1193            .output()
1194            .map_err(|e| {
1195                CascadeError::Git(git2::Error::from_str(&format!(
1196                    "Failed to execute git command: {e}"
1197                )))
1198            })?;
1199
1200        if output.status.success() {
1201            tracing::info!("✅ Git CLI pull succeeded for branch: {}", branch);
1202            Ok(())
1203        } else {
1204            let stderr = String::from_utf8_lossy(&output.stderr);
1205            let stdout = String::from_utf8_lossy(&output.stdout);
1206            let error_msg = format!(
1207                "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1208                branch, output.status, stdout, stderr
1209            );
1210            tracing::error!("{}", error_msg);
1211            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1212        }
1213    }
1214
1215    /// Fallback force push method using git CLI instead of git2
1216    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1217    fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
1218        tracing::info!(
1219            "Using git CLI fallback for force push operation: {}",
1220            branch
1221        );
1222
1223        let output = std::process::Command::new("git")
1224            .args(["push", "--force", "origin", branch])
1225            .current_dir(&self.path)
1226            .output()
1227            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1228
1229        if output.status.success() {
1230            tracing::info!("✅ Git CLI force push succeeded for branch: {}", branch);
1231            Ok(())
1232        } else {
1233            let stderr = String::from_utf8_lossy(&output.stderr);
1234            let stdout = String::from_utf8_lossy(&output.stdout);
1235            let error_msg = format!(
1236                "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1237                branch, output.status, stdout, stderr
1238            );
1239            tracing::error!("{}", error_msg);
1240            Err(CascadeError::branch(error_msg))
1241        }
1242    }
1243
1244    /// Delete a local branch
1245    pub fn delete_branch(&self, name: &str) -> Result<()> {
1246        self.delete_branch_with_options(name, false)
1247    }
1248
1249    /// Delete a local branch with force option to bypass safety checks
1250    pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
1251        self.delete_branch_with_options(name, true)
1252    }
1253
1254    /// Internal branch deletion implementation with safety options
1255    fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
1256        info!("Attempting to delete branch: {}", name);
1257
1258        // Enhanced safety check: Detect unpushed commits before deletion
1259        if !force_unsafe {
1260            let safety_result = self.check_branch_deletion_safety(name)?;
1261            if let Some(safety_info) = safety_result {
1262                // Branch has unpushed commits, get user confirmation
1263                self.handle_branch_deletion_confirmation(name, &safety_info)?;
1264            }
1265        }
1266
1267        let mut branch = self
1268            .repo
1269            .find_branch(name, git2::BranchType::Local)
1270            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
1271
1272        branch
1273            .delete()
1274            .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
1275
1276        info!("Successfully deleted branch '{}'", name);
1277        Ok(())
1278    }
1279
1280    /// Get commits between two references
1281    pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
1282        let from_oid = self
1283            .repo
1284            .refname_to_id(&format!("refs/heads/{from}"))
1285            .or_else(|_| Oid::from_str(from))
1286            .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
1287
1288        let to_oid = self
1289            .repo
1290            .refname_to_id(&format!("refs/heads/{to}"))
1291            .or_else(|_| Oid::from_str(to))
1292            .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
1293
1294        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1295
1296        revwalk.push(to_oid).map_err(CascadeError::Git)?;
1297        revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1298
1299        let mut commits = Vec::new();
1300        for oid in revwalk {
1301            let oid = oid.map_err(CascadeError::Git)?;
1302            let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1303            commits.push(commit);
1304        }
1305
1306        Ok(commits)
1307    }
1308
1309    /// Force push one branch's content to another branch name
1310    /// This is used to preserve PR history while updating branch contents after rebase
1311    pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1312        self.force_push_branch_with_options(target_branch, source_branch, false)
1313    }
1314
1315    /// Force push with explicit force flag to bypass safety checks
1316    pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1317        self.force_push_branch_with_options(target_branch, source_branch, true)
1318    }
1319
1320    /// Internal force push implementation with safety options
1321    fn force_push_branch_with_options(
1322        &self,
1323        target_branch: &str,
1324        source_branch: &str,
1325        force_unsafe: bool,
1326    ) -> Result<()> {
1327        info!(
1328            "Force pushing {} content to {} to preserve PR history",
1329            source_branch, target_branch
1330        );
1331
1332        // Enhanced safety check: Detect potential data loss and get user confirmation
1333        if !force_unsafe {
1334            let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
1335            if let Some(backup_info) = safety_result {
1336                // Create backup branch before force push
1337                self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
1338                info!(
1339                    "✅ Created backup branch: {}",
1340                    backup_info.backup_branch_name
1341                );
1342            }
1343        }
1344
1345        // First, ensure we have the latest changes for the source branch
1346        let source_ref = self
1347            .repo
1348            .find_reference(&format!("refs/heads/{source_branch}"))
1349            .map_err(|e| {
1350                CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
1351            })?;
1352        let source_commit = source_ref.peel_to_commit().map_err(|e| {
1353            CascadeError::config(format!(
1354                "Failed to get commit for source branch {source_branch}: {e}"
1355            ))
1356        })?;
1357
1358        // Update the target branch to point to the source commit
1359        let mut target_ref = self
1360            .repo
1361            .find_reference(&format!("refs/heads/{target_branch}"))
1362            .map_err(|e| {
1363                CascadeError::config(format!("Failed to find target branch {target_branch}: {e}"))
1364            })?;
1365
1366        target_ref
1367            .set_target(source_commit.id(), "Force push from rebase")
1368            .map_err(|e| {
1369                CascadeError::config(format!(
1370                    "Failed to update target branch {target_branch}: {e}"
1371                ))
1372            })?;
1373
1374        // Force push to remote
1375        let mut remote = self
1376            .repo
1377            .find_remote("origin")
1378            .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
1379
1380        let refspec = format!("+refs/heads/{target_branch}:refs/heads/{target_branch}");
1381
1382        // Configure callbacks with SSL settings from git config
1383        let callbacks = self.configure_remote_callbacks()?;
1384
1385        // Push options for force push with SSL config
1386        let mut push_options = git2::PushOptions::new();
1387        push_options.remote_callbacks(callbacks);
1388
1389        match remote.push(&[&refspec], Some(&mut push_options)) {
1390            Ok(_) => {}
1391            Err(e) => {
1392                // Check if this is a TLS/SSL error that might be resolved by falling back to git CLI
1393                let error_string = e.to_string();
1394                if error_string.contains("TLS stream") || error_string.contains("SSL") {
1395                    tracing::warn!(
1396                        "git2 TLS error detected: {}, falling back to git CLI for force push operation",
1397                        e
1398                    );
1399                    return self.force_push_with_git_cli(target_branch);
1400                }
1401                return Err(CascadeError::config(format!(
1402                    "Failed to force push {target_branch}: {e}"
1403                )));
1404            }
1405        }
1406
1407        info!(
1408            "✅ Successfully force pushed {} to preserve PR history",
1409            target_branch
1410        );
1411        Ok(())
1412    }
1413
1414    /// Enhanced safety check for force push operations with user confirmation
1415    /// Returns backup info if data would be lost and user confirms
1416    fn check_force_push_safety_enhanced(
1417        &self,
1418        target_branch: &str,
1419    ) -> Result<Option<ForceBackupInfo>> {
1420        // First fetch latest remote changes to ensure we have up-to-date information
1421        match self.fetch() {
1422            Ok(_) => {}
1423            Err(e) => {
1424                // If fetch fails, warn but don't block the operation
1425                warn!("Could not fetch latest changes for safety check: {}", e);
1426            }
1427        }
1428
1429        // Check if there are commits on the remote that would be lost
1430        let remote_ref = format!("refs/remotes/origin/{target_branch}");
1431        let local_ref = format!("refs/heads/{target_branch}");
1432
1433        // Try to find both local and remote references
1434        let local_commit = match self.repo.find_reference(&local_ref) {
1435            Ok(reference) => reference.peel_to_commit().ok(),
1436            Err(_) => None,
1437        };
1438
1439        let remote_commit = match self.repo.find_reference(&remote_ref) {
1440            Ok(reference) => reference.peel_to_commit().ok(),
1441            Err(_) => None,
1442        };
1443
1444        // If we have both commits, check for divergence
1445        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
1446            if local.id() != remote.id() {
1447                // Check if the remote has commits that the local doesn't have
1448                let merge_base_oid = self
1449                    .repo
1450                    .merge_base(local.id(), remote.id())
1451                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
1452
1453                // If merge base != remote commit, remote has commits that would be lost
1454                if merge_base_oid != remote.id() {
1455                    let commits_to_lose = self.count_commits_between(
1456                        &merge_base_oid.to_string(),
1457                        &remote.id().to_string(),
1458                    )?;
1459
1460                    // Create backup branch name with timestamp
1461                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
1462                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
1463
1464                    warn!(
1465                        "⚠️  Force push to '{}' would overwrite {} commits on remote",
1466                        target_branch, commits_to_lose
1467                    );
1468
1469                    // Check if we're in a non-interactive environment (CI/testing)
1470                    if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
1471                    {
1472                        info!(
1473                            "Non-interactive environment detected, proceeding with backup creation"
1474                        );
1475                        return Ok(Some(ForceBackupInfo {
1476                            backup_branch_name,
1477                            remote_commit_id: remote.id().to_string(),
1478                            commits_that_would_be_lost: commits_to_lose,
1479                        }));
1480                    }
1481
1482                    // Interactive confirmation
1483                    println!("\n⚠️  FORCE PUSH WARNING ⚠️");
1484                    println!("Force push to '{target_branch}' would overwrite {commits_to_lose} commits on remote:");
1485
1486                    // Show the commits that would be lost
1487                    match self
1488                        .get_commits_between(&merge_base_oid.to_string(), &remote.id().to_string())
1489                    {
1490                        Ok(commits) => {
1491                            println!("\nCommits that would be lost:");
1492                            for (i, commit) in commits.iter().take(5).enumerate() {
1493                                let short_hash = &commit.id().to_string()[..8];
1494                                let summary = commit.summary().unwrap_or("<no message>");
1495                                println!("  {}. {} - {}", i + 1, short_hash, summary);
1496                            }
1497                            if commits.len() > 5 {
1498                                println!("  ... and {} more commits", commits.len() - 5);
1499                            }
1500                        }
1501                        Err(_) => {
1502                            println!("  (Unable to retrieve commit details)");
1503                        }
1504                    }
1505
1506                    println!("\nA backup branch '{backup_branch_name}' will be created before proceeding.");
1507
1508                    let confirmed = Confirm::with_theme(&ColorfulTheme::default())
1509                        .with_prompt("Do you want to proceed with the force push?")
1510                        .default(false)
1511                        .interact()
1512                        .map_err(|e| {
1513                            CascadeError::config(format!("Failed to get user confirmation: {e}"))
1514                        })?;
1515
1516                    if !confirmed {
1517                        return Err(CascadeError::config(
1518                            "Force push cancelled by user. Use --force to bypass this check."
1519                                .to_string(),
1520                        ));
1521                    }
1522
1523                    return Ok(Some(ForceBackupInfo {
1524                        backup_branch_name,
1525                        remote_commit_id: remote.id().to_string(),
1526                        commits_that_would_be_lost: commits_to_lose,
1527                    }));
1528                }
1529            }
1530        }
1531
1532        Ok(None)
1533    }
1534
1535    /// Create a backup branch pointing to the remote commit that would be lost
1536    fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
1537        let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
1538        let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
1539
1540        // Parse the commit ID
1541        let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
1542            CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
1543        })?;
1544
1545        // Find the commit
1546        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
1547            CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
1548        })?;
1549
1550        // Create the backup branch
1551        self.repo
1552            .branch(&backup_branch_name, &commit, false)
1553            .map_err(|e| {
1554                CascadeError::config(format!(
1555                    "Failed to create backup branch {backup_branch_name}: {e}"
1556                ))
1557            })?;
1558
1559        info!(
1560            "✅ Created backup branch '{}' pointing to {}",
1561            backup_branch_name,
1562            &remote_commit_id[..8]
1563        );
1564        Ok(())
1565    }
1566
1567    /// Check if branch deletion is safe by detecting unpushed commits
1568    /// Returns safety info if there are concerns that need user attention
1569    fn check_branch_deletion_safety(
1570        &self,
1571        branch_name: &str,
1572    ) -> Result<Option<BranchDeletionSafety>> {
1573        // First, try to fetch latest remote changes
1574        match self.fetch() {
1575            Ok(_) => {}
1576            Err(e) => {
1577                warn!(
1578                    "Could not fetch latest changes for branch deletion safety check: {}",
1579                    e
1580                );
1581            }
1582        }
1583
1584        // Find the branch
1585        let branch = self
1586            .repo
1587            .find_branch(branch_name, git2::BranchType::Local)
1588            .map_err(|e| {
1589                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
1590            })?;
1591
1592        let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
1593            CascadeError::branch(format!(
1594                "Could not get commit for branch '{branch_name}': {e}"
1595            ))
1596        })?;
1597
1598        // Determine the main branch (try common names)
1599        let main_branch_name = self.detect_main_branch()?;
1600
1601        // Check if branch is merged to main
1602        let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
1603
1604        // Find the upstream/remote tracking branch
1605        let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
1606
1607        let mut unpushed_commits = Vec::new();
1608
1609        // Check for unpushed commits compared to remote tracking branch
1610        if let Some(ref remote_branch) = remote_tracking_branch {
1611            match self.get_commits_between(remote_branch, branch_name) {
1612                Ok(commits) => {
1613                    unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
1614                }
1615                Err(_) => {
1616                    // If we can't compare with remote, check against main branch
1617                    if !is_merged_to_main {
1618                        if let Ok(commits) =
1619                            self.get_commits_between(&main_branch_name, branch_name)
1620                        {
1621                            unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
1622                        }
1623                    }
1624                }
1625            }
1626        } else if !is_merged_to_main {
1627            // No remote tracking branch, check against main
1628            if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
1629                unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
1630            }
1631        }
1632
1633        // If there are concerns, return safety info
1634        if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
1635        {
1636            Ok(Some(BranchDeletionSafety {
1637                unpushed_commits,
1638                remote_tracking_branch,
1639                is_merged_to_main,
1640                main_branch_name,
1641            }))
1642        } else {
1643            Ok(None)
1644        }
1645    }
1646
1647    /// Handle user confirmation for branch deletion with safety concerns
1648    fn handle_branch_deletion_confirmation(
1649        &self,
1650        branch_name: &str,
1651        safety_info: &BranchDeletionSafety,
1652    ) -> Result<()> {
1653        // Check if we're in a non-interactive environment
1654        if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
1655            return Err(CascadeError::branch(
1656                format!(
1657                    "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
1658                    safety_info.unpushed_commits.len()
1659                )
1660            ));
1661        }
1662
1663        // Interactive warning and confirmation
1664        println!("\n⚠️  BRANCH DELETION WARNING ⚠️");
1665        println!("Branch '{branch_name}' has potential issues:");
1666
1667        if !safety_info.unpushed_commits.is_empty() {
1668            println!(
1669                "\n🔍 Unpushed commits ({} total):",
1670                safety_info.unpushed_commits.len()
1671            );
1672
1673            // Show details of unpushed commits
1674            for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
1675                if let Ok(commit) = self.repo.find_commit(Oid::from_str(commit_id).unwrap()) {
1676                    let short_hash = &commit_id[..8];
1677                    let summary = commit.summary().unwrap_or("<no message>");
1678                    println!("  {}. {} - {}", i + 1, short_hash, summary);
1679                }
1680            }
1681
1682            if safety_info.unpushed_commits.len() > 5 {
1683                println!(
1684                    "  ... and {} more commits",
1685                    safety_info.unpushed_commits.len() - 5
1686                );
1687            }
1688        }
1689
1690        if !safety_info.is_merged_to_main {
1691            println!("\n📋 Branch status:");
1692            println!("  • Not merged to '{}'", safety_info.main_branch_name);
1693            if let Some(ref remote) = safety_info.remote_tracking_branch {
1694                println!("  • Remote tracking branch: {remote}");
1695            } else {
1696                println!("  • No remote tracking branch");
1697            }
1698        }
1699
1700        println!("\n💡 Safer alternatives:");
1701        if !safety_info.unpushed_commits.is_empty() {
1702            if let Some(ref _remote) = safety_info.remote_tracking_branch {
1703                println!("  • Push commits first: git push origin {branch_name}");
1704            } else {
1705                println!("  • Create and push to remote: git push -u origin {branch_name}");
1706            }
1707        }
1708        if !safety_info.is_merged_to_main {
1709            println!(
1710                "  • Merge to {} first: git checkout {} && git merge {branch_name}",
1711                safety_info.main_branch_name, safety_info.main_branch_name
1712            );
1713        }
1714
1715        let confirmed = Confirm::with_theme(&ColorfulTheme::default())
1716            .with_prompt("Do you want to proceed with deleting this branch?")
1717            .default(false)
1718            .interact()
1719            .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
1720
1721        if !confirmed {
1722            return Err(CascadeError::branch(
1723                "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
1724            ));
1725        }
1726
1727        Ok(())
1728    }
1729
1730    /// Detect the main branch name (main, master, develop)
1731    pub fn detect_main_branch(&self) -> Result<String> {
1732        let main_candidates = ["main", "master", "develop", "trunk"];
1733
1734        for candidate in &main_candidates {
1735            if self
1736                .repo
1737                .find_branch(candidate, git2::BranchType::Local)
1738                .is_ok()
1739            {
1740                return Ok(candidate.to_string());
1741            }
1742        }
1743
1744        // Fallback to HEAD's target if it's a symbolic reference
1745        if let Ok(head) = self.repo.head() {
1746            if let Some(name) = head.shorthand() {
1747                return Ok(name.to_string());
1748            }
1749        }
1750
1751        // Final fallback
1752        Ok("main".to_string())
1753    }
1754
1755    /// Check if a branch is merged to the main branch
1756    fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
1757        // Get the commits between main and the branch
1758        match self.get_commits_between(main_branch, branch_name) {
1759            Ok(commits) => Ok(commits.is_empty()),
1760            Err(_) => {
1761                // If we can't determine, assume not merged for safety
1762                Ok(false)
1763            }
1764        }
1765    }
1766
1767    /// Get the remote tracking branch for a local branch
1768    fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
1769        // Try common remote tracking branch patterns
1770        let remote_candidates = [
1771            format!("origin/{branch_name}"),
1772            format!("remotes/origin/{branch_name}"),
1773        ];
1774
1775        for candidate in &remote_candidates {
1776            if self
1777                .repo
1778                .find_reference(&format!(
1779                    "refs/remotes/{}",
1780                    candidate.replace("remotes/", "")
1781                ))
1782                .is_ok()
1783            {
1784                return Some(candidate.clone());
1785            }
1786        }
1787
1788        None
1789    }
1790
1791    /// Check if checkout operation is safe
1792    fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
1793        // Check if there are uncommitted changes
1794        let is_dirty = self.is_dirty()?;
1795        if !is_dirty {
1796            // No uncommitted changes, checkout is safe
1797            return Ok(None);
1798        }
1799
1800        // Get current branch for context
1801        let current_branch = self.get_current_branch().ok();
1802
1803        // Get detailed information about uncommitted changes
1804        let modified_files = self.get_modified_files()?;
1805        let staged_files = self.get_staged_files()?;
1806        let untracked_files = self.get_untracked_files()?;
1807
1808        let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
1809
1810        if has_uncommitted_changes || !untracked_files.is_empty() {
1811            return Ok(Some(CheckoutSafety {
1812                has_uncommitted_changes,
1813                modified_files,
1814                staged_files,
1815                untracked_files,
1816                stash_created: None,
1817                current_branch,
1818            }));
1819        }
1820
1821        Ok(None)
1822    }
1823
1824    /// Handle user confirmation for checkout operations with uncommitted changes
1825    fn handle_checkout_confirmation(
1826        &self,
1827        target: &str,
1828        safety_info: &CheckoutSafety,
1829    ) -> Result<()> {
1830        // Check if we're in a non-interactive environment FIRST (before any output)
1831        let is_ci = std::env::var("CI").is_ok();
1832        let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
1833        let is_non_interactive = is_ci || no_confirm;
1834
1835        if is_non_interactive {
1836            return Err(CascadeError::branch(
1837                format!(
1838                    "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
1839                )
1840            ));
1841        }
1842
1843        // Interactive warning and confirmation
1844        println!("\n⚠️  CHECKOUT WARNING ⚠️");
1845        println!("You have uncommitted changes that could be lost:");
1846
1847        if !safety_info.modified_files.is_empty() {
1848            println!(
1849                "\n📝 Modified files ({}):",
1850                safety_info.modified_files.len()
1851            );
1852            for file in safety_info.modified_files.iter().take(10) {
1853                println!("   - {file}");
1854            }
1855            if safety_info.modified_files.len() > 10 {
1856                println!("   ... and {} more", safety_info.modified_files.len() - 10);
1857            }
1858        }
1859
1860        if !safety_info.staged_files.is_empty() {
1861            println!("\n📁 Staged files ({}):", safety_info.staged_files.len());
1862            for file in safety_info.staged_files.iter().take(10) {
1863                println!("   - {file}");
1864            }
1865            if safety_info.staged_files.len() > 10 {
1866                println!("   ... and {} more", safety_info.staged_files.len() - 10);
1867            }
1868        }
1869
1870        if !safety_info.untracked_files.is_empty() {
1871            println!(
1872                "\n❓ Untracked files ({}):",
1873                safety_info.untracked_files.len()
1874            );
1875            for file in safety_info.untracked_files.iter().take(5) {
1876                println!("   - {file}");
1877            }
1878            if safety_info.untracked_files.len() > 5 {
1879                println!("   ... and {} more", safety_info.untracked_files.len() - 5);
1880            }
1881        }
1882
1883        println!("\n🔄 Options:");
1884        println!("1. Stash changes and checkout (recommended)");
1885        println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
1886        println!("3. Cancel checkout");
1887
1888        let confirmation = Confirm::with_theme(&ColorfulTheme::default())
1889            .with_prompt("Would you like to stash your changes and proceed with checkout?")
1890            .interact()
1891            .map_err(|e| CascadeError::branch(format!("Could not get user confirmation: {e}")))?;
1892
1893        if confirmation {
1894            // Create stash before checkout
1895            let stash_message = format!(
1896                "Auto-stash before checkout to {} at {}",
1897                target,
1898                chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
1899            );
1900
1901            match self.create_stash(&stash_message) {
1902                Ok(stash_oid) => {
1903                    println!("✅ Created stash: {stash_message} ({stash_oid})");
1904                    println!("💡 You can restore with: git stash pop");
1905                }
1906                Err(e) => {
1907                    println!("❌ Failed to create stash: {e}");
1908
1909                    let force_confirm = Confirm::with_theme(&ColorfulTheme::default())
1910                        .with_prompt("Stash failed. Force checkout anyway? (WILL LOSE CHANGES)")
1911                        .interact()
1912                        .map_err(|e| {
1913                            CascadeError::branch(format!("Could not get confirmation: {e}"))
1914                        })?;
1915
1916                    if !force_confirm {
1917                        return Err(CascadeError::branch(
1918                            "Checkout cancelled by user".to_string(),
1919                        ));
1920                    }
1921                }
1922            }
1923        } else {
1924            return Err(CascadeError::branch(
1925                "Checkout cancelled by user".to_string(),
1926            ));
1927        }
1928
1929        Ok(())
1930    }
1931
1932    /// Create a stash with uncommitted changes
1933    fn create_stash(&self, message: &str) -> Result<String> {
1934        // For now, we'll use a different approach that doesn't require mutable access
1935        // This is a simplified version that recommends manual stashing
1936
1937        warn!("Automatic stashing not yet implemented - please stash manually");
1938        Err(CascadeError::branch(format!(
1939            "Please manually stash your changes first: git stash push -m \"{message}\""
1940        )))
1941    }
1942
1943    /// Get modified files in working directory
1944    fn get_modified_files(&self) -> Result<Vec<String>> {
1945        let mut opts = git2::StatusOptions::new();
1946        opts.include_untracked(false).include_ignored(false);
1947
1948        let statuses = self
1949            .repo
1950            .statuses(Some(&mut opts))
1951            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
1952
1953        let mut modified_files = Vec::new();
1954        for status in statuses.iter() {
1955            let flags = status.status();
1956            if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
1957            {
1958                if let Some(path) = status.path() {
1959                    modified_files.push(path.to_string());
1960                }
1961            }
1962        }
1963
1964        Ok(modified_files)
1965    }
1966
1967    /// Get staged files in index
1968    fn get_staged_files(&self) -> Result<Vec<String>> {
1969        let mut opts = git2::StatusOptions::new();
1970        opts.include_untracked(false).include_ignored(false);
1971
1972        let statuses = self
1973            .repo
1974            .statuses(Some(&mut opts))
1975            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
1976
1977        let mut staged_files = Vec::new();
1978        for status in statuses.iter() {
1979            let flags = status.status();
1980            if flags.contains(git2::Status::INDEX_MODIFIED)
1981                || flags.contains(git2::Status::INDEX_NEW)
1982                || flags.contains(git2::Status::INDEX_DELETED)
1983            {
1984                if let Some(path) = status.path() {
1985                    staged_files.push(path.to_string());
1986                }
1987            }
1988        }
1989
1990        Ok(staged_files)
1991    }
1992
1993    /// Count commits between two references
1994    fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
1995        let commits = self.get_commits_between(from, to)?;
1996        Ok(commits.len())
1997    }
1998
1999    /// Resolve a reference (branch name, tag, or commit hash) to a commit
2000    pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
2001        // Try to parse as commit hash first
2002        if let Ok(oid) = Oid::from_str(reference) {
2003            if let Ok(commit) = self.repo.find_commit(oid) {
2004                return Ok(commit);
2005            }
2006        }
2007
2008        // Try to resolve as a reference (branch, tag, etc.)
2009        let obj = self.repo.revparse_single(reference).map_err(|e| {
2010            CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
2011        })?;
2012
2013        obj.peel_to_commit().map_err(|e| {
2014            CascadeError::branch(format!(
2015                "Reference '{reference}' does not point to a commit: {e}"
2016            ))
2017        })
2018    }
2019
2020    /// Reset HEAD to a specific reference (soft reset)
2021    pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
2022        let target_commit = self.resolve_reference(target_ref)?;
2023
2024        self.repo
2025            .reset(target_commit.as_object(), git2::ResetType::Soft, None)
2026            .map_err(CascadeError::Git)?;
2027
2028        Ok(())
2029    }
2030
2031    /// Find which branch contains a specific commit
2032    pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
2033        let oid = Oid::from_str(commit_hash).map_err(|e| {
2034            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2035        })?;
2036
2037        // Get all local branches
2038        let branches = self
2039            .repo
2040            .branches(Some(git2::BranchType::Local))
2041            .map_err(CascadeError::Git)?;
2042
2043        for branch_result in branches {
2044            let (branch, _) = branch_result.map_err(CascadeError::Git)?;
2045
2046            if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
2047                // Check if this branch contains the commit
2048                if let Ok(branch_head) = branch.get().peel_to_commit() {
2049                    // Walk the commit history from this branch's HEAD
2050                    let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2051                    revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
2052
2053                    for commit_oid in revwalk {
2054                        let commit_oid = commit_oid.map_err(CascadeError::Git)?;
2055                        if commit_oid == oid {
2056                            return Ok(branch_name.to_string());
2057                        }
2058                    }
2059                }
2060            }
2061        }
2062
2063        // If not found in any branch, might be on current HEAD
2064        Err(CascadeError::branch(format!(
2065            "Commit {commit_hash} not found in any local branch"
2066        )))
2067    }
2068
2069    // Async wrappers for potentially blocking operations
2070
2071    /// Fetch from remote origin (async)
2072    pub async fn fetch_async(&self) -> Result<()> {
2073        let repo_path = self.path.clone();
2074        crate::utils::async_ops::run_git_operation(move || {
2075            let repo = GitRepository::open(&repo_path)?;
2076            repo.fetch()
2077        })
2078        .await
2079    }
2080
2081    /// Pull changes from remote (async)
2082    pub async fn pull_async(&self, branch: &str) -> Result<()> {
2083        let repo_path = self.path.clone();
2084        let branch_name = branch.to_string();
2085        crate::utils::async_ops::run_git_operation(move || {
2086            let repo = GitRepository::open(&repo_path)?;
2087            repo.pull(&branch_name)
2088        })
2089        .await
2090    }
2091
2092    /// Push branch to remote (async)
2093    pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
2094        let repo_path = self.path.clone();
2095        let branch = branch_name.to_string();
2096        crate::utils::async_ops::run_git_operation(move || {
2097            let repo = GitRepository::open(&repo_path)?;
2098            repo.push(&branch)
2099        })
2100        .await
2101    }
2102
2103    /// Cherry-pick commit (async)
2104    pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
2105        let repo_path = self.path.clone();
2106        let hash = commit_hash.to_string();
2107        crate::utils::async_ops::run_git_operation(move || {
2108            let repo = GitRepository::open(&repo_path)?;
2109            repo.cherry_pick(&hash)
2110        })
2111        .await
2112    }
2113
2114    /// Get commit hashes between two refs (async)
2115    pub async fn get_commit_hashes_between_async(
2116        &self,
2117        from: &str,
2118        to: &str,
2119    ) -> Result<Vec<String>> {
2120        let repo_path = self.path.clone();
2121        let from_str = from.to_string();
2122        let to_str = to.to_string();
2123        crate::utils::async_ops::run_git_operation(move || {
2124            let repo = GitRepository::open(&repo_path)?;
2125            let commits = repo.get_commits_between(&from_str, &to_str)?;
2126            Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
2127        })
2128        .await
2129    }
2130
2131    /// Reset a branch to point to a specific commit
2132    pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
2133        info!(
2134            "Resetting branch '{}' to commit {}",
2135            branch_name,
2136            &commit_hash[..8]
2137        );
2138
2139        // Find the target commit
2140        let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
2141            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2142        })?;
2143
2144        let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
2145            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
2146        })?;
2147
2148        // Find the branch
2149        let _branch = self
2150            .repo
2151            .find_branch(branch_name, git2::BranchType::Local)
2152            .map_err(|e| {
2153                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2154            })?;
2155
2156        // Update the branch reference to point to the target commit
2157        let branch_ref_name = format!("refs/heads/{branch_name}");
2158        self.repo
2159            .reference(
2160                &branch_ref_name,
2161                target_oid,
2162                true,
2163                &format!("Reset {branch_name} to {commit_hash}"),
2164            )
2165            .map_err(|e| {
2166                CascadeError::branch(format!(
2167                    "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
2168                ))
2169            })?;
2170
2171        tracing::info!(
2172            "Successfully reset branch '{}' to commit {}",
2173            branch_name,
2174            &commit_hash[..8]
2175        );
2176        Ok(())
2177    }
2178}
2179
2180#[cfg(test)]
2181mod tests {
2182    use super::*;
2183    use std::process::Command;
2184    use tempfile::TempDir;
2185
2186    fn create_test_repo() -> (TempDir, PathBuf) {
2187        let temp_dir = TempDir::new().unwrap();
2188        let repo_path = temp_dir.path().to_path_buf();
2189
2190        // Initialize git repository
2191        Command::new("git")
2192            .args(["init"])
2193            .current_dir(&repo_path)
2194            .output()
2195            .unwrap();
2196        Command::new("git")
2197            .args(["config", "user.name", "Test"])
2198            .current_dir(&repo_path)
2199            .output()
2200            .unwrap();
2201        Command::new("git")
2202            .args(["config", "user.email", "test@test.com"])
2203            .current_dir(&repo_path)
2204            .output()
2205            .unwrap();
2206
2207        // Create initial commit
2208        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
2209        Command::new("git")
2210            .args(["add", "."])
2211            .current_dir(&repo_path)
2212            .output()
2213            .unwrap();
2214        Command::new("git")
2215            .args(["commit", "-m", "Initial commit"])
2216            .current_dir(&repo_path)
2217            .output()
2218            .unwrap();
2219
2220        (temp_dir, repo_path)
2221    }
2222
2223    fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
2224        let file_path = repo_path.join(filename);
2225        std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
2226
2227        Command::new("git")
2228            .args(["add", filename])
2229            .current_dir(repo_path)
2230            .output()
2231            .unwrap();
2232        Command::new("git")
2233            .args(["commit", "-m", message])
2234            .current_dir(repo_path)
2235            .output()
2236            .unwrap();
2237    }
2238
2239    #[test]
2240    fn test_repository_info() {
2241        let (_temp_dir, repo_path) = create_test_repo();
2242        let repo = GitRepository::open(&repo_path).unwrap();
2243
2244        let info = repo.get_info().unwrap();
2245        assert!(!info.is_dirty); // Should be clean after commit
2246        assert!(
2247            info.head_branch == Some("master".to_string())
2248                || info.head_branch == Some("main".to_string()),
2249            "Expected default branch to be 'master' or 'main', got {:?}",
2250            info.head_branch
2251        );
2252        assert!(info.head_commit.is_some()); // Just check it exists
2253        assert!(info.untracked_files.is_empty()); // Should be empty after commit
2254    }
2255
2256    #[test]
2257    fn test_force_push_branch_basic() {
2258        let (_temp_dir, repo_path) = create_test_repo();
2259        let repo = GitRepository::open(&repo_path).unwrap();
2260
2261        // Get the actual default branch name
2262        let default_branch = repo.get_current_branch().unwrap();
2263
2264        // Create source branch with commits
2265        create_commit(&repo_path, "Feature commit 1", "feature1.rs");
2266        Command::new("git")
2267            .args(["checkout", "-b", "source-branch"])
2268            .current_dir(&repo_path)
2269            .output()
2270            .unwrap();
2271        create_commit(&repo_path, "Feature commit 2", "feature2.rs");
2272
2273        // Create target branch
2274        Command::new("git")
2275            .args(["checkout", &default_branch])
2276            .current_dir(&repo_path)
2277            .output()
2278            .unwrap();
2279        Command::new("git")
2280            .args(["checkout", "-b", "target-branch"])
2281            .current_dir(&repo_path)
2282            .output()
2283            .unwrap();
2284        create_commit(&repo_path, "Target commit", "target.rs");
2285
2286        // Test force push from source to target
2287        let result = repo.force_push_branch("target-branch", "source-branch");
2288
2289        // Should succeed in test environment (even though it doesn't actually push to remote)
2290        // The important thing is that the function doesn't panic and handles the git2 operations
2291        assert!(result.is_ok() || result.is_err()); // Either is acceptable for unit test
2292    }
2293
2294    #[test]
2295    fn test_force_push_branch_nonexistent_branches() {
2296        let (_temp_dir, repo_path) = create_test_repo();
2297        let repo = GitRepository::open(&repo_path).unwrap();
2298
2299        // Get the actual default branch name
2300        let default_branch = repo.get_current_branch().unwrap();
2301
2302        // Test force push with nonexistent source branch
2303        let result = repo.force_push_branch("target", "nonexistent-source");
2304        assert!(result.is_err());
2305
2306        // Test force push with nonexistent target branch
2307        let result = repo.force_push_branch("nonexistent-target", &default_branch);
2308        assert!(result.is_err());
2309    }
2310
2311    #[test]
2312    fn test_force_push_workflow_simulation() {
2313        let (_temp_dir, repo_path) = create_test_repo();
2314        let repo = GitRepository::open(&repo_path).unwrap();
2315
2316        // Simulate the smart force push workflow:
2317        // 1. Original branch exists with PR
2318        Command::new("git")
2319            .args(["checkout", "-b", "feature-auth"])
2320            .current_dir(&repo_path)
2321            .output()
2322            .unwrap();
2323        create_commit(&repo_path, "Add authentication", "auth.rs");
2324
2325        // 2. Rebase creates versioned branch
2326        Command::new("git")
2327            .args(["checkout", "-b", "feature-auth-v2"])
2328            .current_dir(&repo_path)
2329            .output()
2330            .unwrap();
2331        create_commit(&repo_path, "Fix auth validation", "auth.rs");
2332
2333        // 3. Smart force push: update original branch from versioned branch
2334        let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
2335
2336        // Verify the operation is handled properly (success or expected error)
2337        match result {
2338            Ok(_) => {
2339                // Force push succeeded - verify branch state if possible
2340                Command::new("git")
2341                    .args(["checkout", "feature-auth"])
2342                    .current_dir(&repo_path)
2343                    .output()
2344                    .unwrap();
2345                let log_output = Command::new("git")
2346                    .args(["log", "--oneline", "-2"])
2347                    .current_dir(&repo_path)
2348                    .output()
2349                    .unwrap();
2350                let log_str = String::from_utf8_lossy(&log_output.stdout);
2351                assert!(
2352                    log_str.contains("Fix auth validation")
2353                        || log_str.contains("Add authentication")
2354                );
2355            }
2356            Err(_) => {
2357                // Expected in test environment without remote - that's fine
2358                // The important thing is we tested the code path without panicking
2359            }
2360        }
2361    }
2362
2363    #[test]
2364    fn test_branch_operations() {
2365        let (_temp_dir, repo_path) = create_test_repo();
2366        let repo = GitRepository::open(&repo_path).unwrap();
2367
2368        // Test get current branch - accept either main or master
2369        let current = repo.get_current_branch().unwrap();
2370        assert!(
2371            current == "master" || current == "main",
2372            "Expected default branch to be 'master' or 'main', got '{current}'"
2373        );
2374
2375        // Test create branch
2376        Command::new("git")
2377            .args(["checkout", "-b", "test-branch"])
2378            .current_dir(&repo_path)
2379            .output()
2380            .unwrap();
2381        let current = repo.get_current_branch().unwrap();
2382        assert_eq!(current, "test-branch");
2383    }
2384
2385    #[test]
2386    fn test_commit_operations() {
2387        let (_temp_dir, repo_path) = create_test_repo();
2388        let repo = GitRepository::open(&repo_path).unwrap();
2389
2390        // Test get head commit
2391        let head = repo.get_head_commit().unwrap();
2392        assert_eq!(head.message().unwrap().trim(), "Initial commit");
2393
2394        // Test get commit by hash
2395        let hash = head.id().to_string();
2396        let same_commit = repo.get_commit(&hash).unwrap();
2397        assert_eq!(head.id(), same_commit.id());
2398    }
2399
2400    #[test]
2401    fn test_checkout_safety_clean_repo() {
2402        let (_temp_dir, repo_path) = create_test_repo();
2403        let repo = GitRepository::open(&repo_path).unwrap();
2404
2405        // Create a test branch
2406        create_commit(&repo_path, "Second commit", "test.txt");
2407        Command::new("git")
2408            .args(["checkout", "-b", "test-branch"])
2409            .current_dir(&repo_path)
2410            .output()
2411            .unwrap();
2412
2413        // Test checkout safety with clean repo
2414        let safety_result = repo.check_checkout_safety("main");
2415        assert!(safety_result.is_ok());
2416        assert!(safety_result.unwrap().is_none()); // Clean repo should return None
2417    }
2418
2419    #[test]
2420    fn test_checkout_safety_with_modified_files() {
2421        let (_temp_dir, repo_path) = create_test_repo();
2422        let repo = GitRepository::open(&repo_path).unwrap();
2423
2424        // Create a test branch
2425        Command::new("git")
2426            .args(["checkout", "-b", "test-branch"])
2427            .current_dir(&repo_path)
2428            .output()
2429            .unwrap();
2430
2431        // Modify a file to create uncommitted changes
2432        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
2433
2434        // Test checkout safety with modified files
2435        let safety_result = repo.check_checkout_safety("main");
2436        assert!(safety_result.is_ok());
2437        let safety_info = safety_result.unwrap();
2438        assert!(safety_info.is_some());
2439
2440        let info = safety_info.unwrap();
2441        assert!(!info.modified_files.is_empty());
2442        assert!(info.modified_files.contains(&"README.md".to_string()));
2443    }
2444
2445    #[test]
2446    fn test_unsafe_checkout_methods() {
2447        let (_temp_dir, repo_path) = create_test_repo();
2448        let repo = GitRepository::open(&repo_path).unwrap();
2449
2450        // Create a test branch
2451        create_commit(&repo_path, "Second commit", "test.txt");
2452        Command::new("git")
2453            .args(["checkout", "-b", "test-branch"])
2454            .current_dir(&repo_path)
2455            .output()
2456            .unwrap();
2457
2458        // Modify a file to create uncommitted changes
2459        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
2460
2461        // Test unsafe checkout methods bypass safety checks
2462        let _result = repo.checkout_branch_unsafe("master");
2463        // Note: This might still fail due to git2 restrictions, but shouldn't hit our safety code
2464        // The important thing is that it doesn't trigger our safety confirmation
2465
2466        // Test unsafe commit checkout
2467        let head_commit = repo.get_head_commit().unwrap();
2468        let commit_hash = head_commit.id().to_string();
2469        let _result = repo.checkout_commit_unsafe(&commit_hash);
2470        // Similar to above - testing that safety is bypassed
2471    }
2472
2473    #[test]
2474    fn test_get_modified_files() {
2475        let (_temp_dir, repo_path) = create_test_repo();
2476        let repo = GitRepository::open(&repo_path).unwrap();
2477
2478        // Initially should have no modified files
2479        let modified = repo.get_modified_files().unwrap();
2480        assert!(modified.is_empty());
2481
2482        // Modify a file
2483        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
2484
2485        // Should now detect the modified file
2486        let modified = repo.get_modified_files().unwrap();
2487        assert_eq!(modified.len(), 1);
2488        assert!(modified.contains(&"README.md".to_string()));
2489    }
2490
2491    #[test]
2492    fn test_get_staged_files() {
2493        let (_temp_dir, repo_path) = create_test_repo();
2494        let repo = GitRepository::open(&repo_path).unwrap();
2495
2496        // Initially should have no staged files
2497        let staged = repo.get_staged_files().unwrap();
2498        assert!(staged.is_empty());
2499
2500        // Create and stage a new file
2501        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
2502        Command::new("git")
2503            .args(["add", "staged.txt"])
2504            .current_dir(&repo_path)
2505            .output()
2506            .unwrap();
2507
2508        // Should now detect the staged file
2509        let staged = repo.get_staged_files().unwrap();
2510        assert_eq!(staged.len(), 1);
2511        assert!(staged.contains(&"staged.txt".to_string()));
2512    }
2513
2514    #[test]
2515    fn test_create_stash_fallback() {
2516        let (_temp_dir, repo_path) = create_test_repo();
2517        let repo = GitRepository::open(&repo_path).unwrap();
2518
2519        // Test that stash creation returns helpful error message
2520        let result = repo.create_stash("test stash");
2521        assert!(result.is_err());
2522        let error_msg = result.unwrap_err().to_string();
2523        assert!(error_msg.contains("git stash push"));
2524    }
2525
2526    #[test]
2527    fn test_delete_branch_unsafe() {
2528        let (_temp_dir, repo_path) = create_test_repo();
2529        let repo = GitRepository::open(&repo_path).unwrap();
2530
2531        // Create a test branch
2532        create_commit(&repo_path, "Second commit", "test.txt");
2533        Command::new("git")
2534            .args(["checkout", "-b", "test-branch"])
2535            .current_dir(&repo_path)
2536            .output()
2537            .unwrap();
2538
2539        // Add another commit to the test branch to make it different from master
2540        create_commit(&repo_path, "Branch-specific commit", "branch.txt");
2541
2542        // Go back to master
2543        Command::new("git")
2544            .args(["checkout", "master"])
2545            .current_dir(&repo_path)
2546            .output()
2547            .unwrap();
2548
2549        // Test unsafe delete bypasses safety checks
2550        // Note: This may still fail if the branch has unpushed commits, but it should bypass our safety confirmation
2551        let result = repo.delete_branch_unsafe("test-branch");
2552        // Even if it fails, the key is that it didn't prompt for user confirmation
2553        // So we just check that it attempted the operation without interactive prompts
2554        let _ = result; // Don't assert success since delete may fail for git reasons
2555    }
2556
2557    #[test]
2558    fn test_force_push_unsafe() {
2559        let (_temp_dir, repo_path) = create_test_repo();
2560        let repo = GitRepository::open(&repo_path).unwrap();
2561
2562        // Create a test branch
2563        create_commit(&repo_path, "Second commit", "test.txt");
2564        Command::new("git")
2565            .args(["checkout", "-b", "test-branch"])
2566            .current_dir(&repo_path)
2567            .output()
2568            .unwrap();
2569
2570        // Test unsafe force push bypasses safety checks
2571        // Note: This will likely fail due to no remote, but it tests the safety bypass
2572        let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
2573        // The key is that it doesn't trigger safety confirmation dialogs
2574    }
2575}