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