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