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