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> {
226 let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
227
228 for status in statuses.iter() {
229 let flags = status.status();
230
231 if flags.intersects(
233 git2::Status::INDEX_MODIFIED
234 | git2::Status::INDEX_NEW
235 | git2::Status::INDEX_DELETED
236 | git2::Status::WT_MODIFIED
237 | git2::Status::WT_NEW
238 | git2::Status::WT_DELETED,
239 ) {
240 return Ok(true);
241 }
242 }
243
244 Ok(false)
245 }
246
247 pub fn get_untracked_files(&self) -> Result<Vec<String>> {
249 let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
250
251 let mut untracked = Vec::new();
252 for status in statuses.iter() {
253 if status.status().contains(git2::Status::WT_NEW) {
254 if let Some(path) = status.path() {
255 untracked.push(path.to_string());
256 }
257 }
258 }
259
260 Ok(untracked)
261 }
262
263 pub fn create_branch(&self, name: &str, target: Option<&str>) -> Result<()> {
265 let target_commit = if let Some(target) = target {
266 let target_obj = self.repo.revparse_single(target).map_err(|e| {
268 CascadeError::branch(format!("Could not find target '{target}': {e}"))
269 })?;
270 target_obj.peel_to_commit().map_err(|e| {
271 CascadeError::branch(format!("Target '{target}' is not a commit: {e}"))
272 })?
273 } else {
274 let head = self
276 .repo
277 .head()
278 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
279 head.peel_to_commit()
280 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?
281 };
282
283 self.repo
284 .branch(name, &target_commit, false)
285 .map_err(|e| CascadeError::branch(format!("Could not create branch '{name}': {e}")))?;
286
287 Ok(())
289 }
290
291 pub fn update_branch_to_commit(&self, branch_name: &str, commit_id: &str) -> Result<()> {
294 let commit_oid = Oid::from_str(commit_id).map_err(|e| {
295 CascadeError::branch(format!("Invalid commit ID '{}': {}", commit_id, e))
296 })?;
297
298 let commit = self.repo.find_commit(commit_oid).map_err(|e| {
299 CascadeError::branch(format!("Commit '{}' not found: {}", commit_id, e))
300 })?;
301
302 if self
304 .repo
305 .find_branch(branch_name, git2::BranchType::Local)
306 .is_ok()
307 {
308 let refname = format!("refs/heads/{}", branch_name);
310 self.repo
311 .reference(
312 &refname,
313 commit_oid,
314 true,
315 "update branch to rebased commit",
316 )
317 .map_err(|e| {
318 CascadeError::branch(format!(
319 "Failed to update branch '{}': {}",
320 branch_name, e
321 ))
322 })?;
323 } else {
324 self.repo.branch(branch_name, &commit, false).map_err(|e| {
326 CascadeError::branch(format!("Failed to create branch '{}': {}", branch_name, e))
327 })?;
328 }
329
330 Ok(())
331 }
332
333 pub fn force_push_single_branch(&self, branch_name: &str) -> Result<()> {
335 self.force_push_single_branch_with_options(branch_name, false)
336 }
337
338 pub fn force_push_single_branch_auto(&self, branch_name: &str) -> Result<()> {
340 self.force_push_single_branch_with_options(branch_name, true)
341 }
342
343 fn force_push_single_branch_with_options(
344 &self,
345 branch_name: &str,
346 auto_confirm: bool,
347 ) -> Result<()> {
348 if self.get_branch_commit_hash(branch_name).is_err() {
351 return Err(CascadeError::branch(format!(
352 "Cannot push '{}': branch does not exist locally",
353 branch_name
354 )));
355 }
356
357 if let Err(e) = self.fetch() {
359 tracing::warn!("Could not fetch before force push: {}", e);
360 }
361
362 let safety_result = if auto_confirm {
364 self.check_force_push_safety_auto(branch_name)?
365 } else {
366 self.check_force_push_safety_enhanced(branch_name)?
367 };
368
369 if let Some(backup_info) = safety_result {
370 self.create_backup_branch(branch_name, &backup_info.remote_commit_id)?;
371 }
372
373 self.ensure_index_closed()?;
375
376 let output = std::process::Command::new("git")
379 .args(["push", "--force", "origin", branch_name])
380 .env("CASCADE_INTERNAL_PUSH", "1")
381 .current_dir(&self.path)
382 .output()
383 .map_err(|e| CascadeError::branch(format!("Failed to execute git push: {}", e)))?;
384
385 if !output.status.success() {
386 let stderr = String::from_utf8_lossy(&output.stderr);
387 let stdout = String::from_utf8_lossy(&output.stdout);
388
389 let full_error = if !stdout.is_empty() {
391 format!("{}\n{}", stderr.trim(), stdout.trim())
392 } else {
393 stderr.trim().to_string()
394 };
395
396 return Err(CascadeError::branch(format!(
397 "Force push failed for '{}':\n{}",
398 branch_name, full_error
399 )));
400 }
401
402 Ok(())
403 }
404
405 pub fn checkout_branch(&self, name: &str) -> Result<()> {
407 self.checkout_branch_with_options(name, false, true)
408 }
409
410 pub fn checkout_branch_silent(&self, name: &str) -> Result<()> {
412 self.checkout_branch_with_options(name, false, false)
413 }
414
415 pub fn checkout_branch_unsafe(&self, name: &str) -> Result<()> {
417 self.checkout_branch_with_options(name, true, false)
418 }
419
420 fn checkout_branch_with_options(
422 &self,
423 name: &str,
424 force_unsafe: bool,
425 show_output: bool,
426 ) -> Result<()> {
427 debug!("Attempting to checkout branch: {}", name);
428
429 if !force_unsafe {
431 let safety_result = self.check_checkout_safety(name)?;
432 if let Some(safety_info) = safety_result {
433 self.handle_checkout_confirmation(name, &safety_info)?;
435 }
436 }
437
438 let branch = self
440 .repo
441 .find_branch(name, git2::BranchType::Local)
442 .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
443
444 let branch_ref = branch.get();
445 let tree = branch_ref.peel_to_tree().map_err(|e| {
446 CascadeError::branch(format!("Could not get tree for branch '{name}': {e}"))
447 })?;
448
449 self.repo
451 .checkout_tree(tree.as_object(), None)
452 .map_err(|e| {
453 CascadeError::branch(format!("Could not checkout branch '{name}': {e}"))
454 })?;
455
456 self.repo
458 .set_head(&format!("refs/heads/{name}"))
459 .map_err(|e| CascadeError::branch(format!("Could not update HEAD to '{name}': {e}")))?;
460
461 if show_output {
462 Output::success(format!("Switched to branch '{name}'"));
463 }
464 Ok(())
465 }
466
467 pub fn checkout_commit(&self, commit_hash: &str) -> Result<()> {
469 self.checkout_commit_with_options(commit_hash, false)
470 }
471
472 pub fn checkout_commit_unsafe(&self, commit_hash: &str) -> Result<()> {
474 self.checkout_commit_with_options(commit_hash, true)
475 }
476
477 fn checkout_commit_with_options(&self, commit_hash: &str, force_unsafe: bool) -> Result<()> {
479 debug!("Attempting to checkout commit: {}", commit_hash);
480
481 if !force_unsafe {
483 let safety_result = self.check_checkout_safety(&format!("commit:{commit_hash}"))?;
484 if let Some(safety_info) = safety_result {
485 self.handle_checkout_confirmation(&format!("commit {commit_hash}"), &safety_info)?;
487 }
488 }
489
490 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
491
492 let commit = self.repo.find_commit(oid).map_err(|e| {
493 CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
494 })?;
495
496 let tree = commit.tree().map_err(|e| {
497 CascadeError::branch(format!(
498 "Could not get tree for commit '{commit_hash}': {e}"
499 ))
500 })?;
501
502 self.repo
504 .checkout_tree(tree.as_object(), None)
505 .map_err(|e| {
506 CascadeError::branch(format!("Could not checkout commit '{commit_hash}': {e}"))
507 })?;
508
509 self.repo.set_head_detached(oid).map_err(|e| {
511 CascadeError::branch(format!(
512 "Could not update HEAD to commit '{commit_hash}': {e}"
513 ))
514 })?;
515
516 Output::success(format!(
517 "Checked out commit '{commit_hash}' (detached HEAD)"
518 ));
519 Ok(())
520 }
521
522 pub fn branch_exists(&self, name: &str) -> bool {
524 self.repo.find_branch(name, git2::BranchType::Local).is_ok()
525 }
526
527 pub fn branch_exists_or_fetch(&self, name: &str) -> Result<bool> {
529 if self.repo.find_branch(name, git2::BranchType::Local).is_ok() {
531 return Ok(true);
532 }
533
534 crate::cli::output::Output::info(format!(
536 "Branch '{name}' not found locally, trying to fetch from remote..."
537 ));
538
539 use std::process::Command;
540
541 let fetch_result = Command::new("git")
543 .args(["fetch", "origin", &format!("{name}:{name}")])
544 .current_dir(&self.path)
545 .output();
546
547 match fetch_result {
548 Ok(output) => {
549 if output.status.success() {
550 println!("✅ Successfully fetched '{name}' from origin");
551 return Ok(self.repo.find_branch(name, git2::BranchType::Local).is_ok());
553 } else {
554 let stderr = String::from_utf8_lossy(&output.stderr);
555 tracing::debug!("Failed to fetch branch '{name}': {stderr}");
556 }
557 }
558 Err(e) => {
559 tracing::debug!("Git fetch command failed: {e}");
560 }
561 }
562
563 if name.contains('/') {
565 crate::cli::output::Output::info("Trying alternative fetch patterns...");
566
567 let fetch_all_result = Command::new("git")
569 .args(["fetch", "origin"])
570 .current_dir(&self.path)
571 .output();
572
573 if let Ok(output) = fetch_all_result {
574 if output.status.success() {
575 let checkout_result = Command::new("git")
577 .args(["checkout", "-b", name, &format!("origin/{name}")])
578 .current_dir(&self.path)
579 .output();
580
581 if let Ok(checkout_output) = checkout_result {
582 if checkout_output.status.success() {
583 println!(
584 "✅ Successfully created local branch '{name}' from origin/{name}"
585 );
586 return Ok(true);
587 }
588 }
589 }
590 }
591 }
592
593 Ok(false)
595 }
596
597 pub fn get_branch_commit_hash(&self, branch_name: &str) -> Result<String> {
599 let branch = self
600 .repo
601 .find_branch(branch_name, git2::BranchType::Local)
602 .map_err(|e| {
603 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
604 })?;
605
606 let commit = branch.get().peel_to_commit().map_err(|e| {
607 CascadeError::branch(format!(
608 "Could not get commit for branch '{branch_name}': {e}"
609 ))
610 })?;
611
612 Ok(commit.id().to_string())
613 }
614
615 pub fn list_branches(&self) -> Result<Vec<String>> {
617 let branches = self
618 .repo
619 .branches(Some(git2::BranchType::Local))
620 .map_err(CascadeError::Git)?;
621
622 let mut branch_names = Vec::new();
623 for branch in branches {
624 let (branch, _) = branch.map_err(CascadeError::Git)?;
625 if let Some(name) = branch.name().map_err(CascadeError::Git)? {
626 branch_names.push(name.to_string());
627 }
628 }
629
630 Ok(branch_names)
631 }
632
633 pub fn get_upstream_branch(&self, branch_name: &str) -> Result<Option<String>> {
635 let config = self.repo.config().map_err(CascadeError::Git)?;
637
638 let remote_key = format!("branch.{branch_name}.remote");
640 let merge_key = format!("branch.{branch_name}.merge");
641
642 if let (Ok(remote), Ok(merge_ref)) = (
643 config.get_string(&remote_key),
644 config.get_string(&merge_key),
645 ) {
646 if let Some(branch_part) = merge_ref.strip_prefix("refs/heads/") {
648 return Ok(Some(format!("{remote}/{branch_part}")));
649 }
650 }
651
652 let potential_upstream = format!("origin/{branch_name}");
654 if self
655 .repo
656 .find_reference(&format!("refs/remotes/{potential_upstream}"))
657 .is_ok()
658 {
659 return Ok(Some(potential_upstream));
660 }
661
662 Ok(None)
663 }
664
665 pub fn get_ahead_behind_counts(
667 &self,
668 local_branch: &str,
669 upstream_branch: &str,
670 ) -> Result<(usize, usize)> {
671 let local_ref = self
673 .repo
674 .find_reference(&format!("refs/heads/{local_branch}"))
675 .map_err(|_| {
676 CascadeError::config(format!("Local branch '{local_branch}' not found"))
677 })?;
678 let local_commit = local_ref.peel_to_commit().map_err(CascadeError::Git)?;
679
680 let upstream_ref = self
681 .repo
682 .find_reference(&format!("refs/remotes/{upstream_branch}"))
683 .map_err(|_| {
684 CascadeError::config(format!("Upstream branch '{upstream_branch}' not found"))
685 })?;
686 let upstream_commit = upstream_ref.peel_to_commit().map_err(CascadeError::Git)?;
687
688 let (ahead, behind) = self
690 .repo
691 .graph_ahead_behind(local_commit.id(), upstream_commit.id())
692 .map_err(CascadeError::Git)?;
693
694 Ok((ahead, behind))
695 }
696
697 pub fn set_upstream(&self, branch_name: &str, remote: &str, remote_branch: &str) -> Result<()> {
699 let mut config = self.repo.config().map_err(CascadeError::Git)?;
700
701 let remote_key = format!("branch.{branch_name}.remote");
703 config
704 .set_str(&remote_key, remote)
705 .map_err(CascadeError::Git)?;
706
707 let merge_key = format!("branch.{branch_name}.merge");
709 let merge_value = format!("refs/heads/{remote_branch}");
710 config
711 .set_str(&merge_key, &merge_value)
712 .map_err(CascadeError::Git)?;
713
714 Ok(())
715 }
716
717 pub fn commit(&self, message: &str) -> Result<String> {
719 self.validate_git_user_config()?;
721
722 let signature = self.get_signature()?;
723 let tree_id = self.get_index_tree()?;
724 let tree = self.repo.find_tree(tree_id).map_err(CascadeError::Git)?;
725
726 let head = self.repo.head().map_err(CascadeError::Git)?;
728 let parent_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
729
730 let commit_id = self
731 .repo
732 .commit(
733 Some("HEAD"),
734 &signature,
735 &signature,
736 message,
737 &tree,
738 &[&parent_commit],
739 )
740 .map_err(CascadeError::Git)?;
741
742 Output::success(format!("Created commit: {commit_id} - {message}"));
743 Ok(commit_id.to_string())
744 }
745
746 pub fn commit_staged_changes(&self, default_message: &str) -> Result<Option<String>> {
748 let staged_files = self.get_staged_files()?;
750 if staged_files.is_empty() {
751 tracing::debug!("No staged changes to commit");
752 return Ok(None);
753 }
754
755 tracing::debug!("Committing {} staged files", staged_files.len());
756 let commit_hash = self.commit(default_message)?;
757 Ok(Some(commit_hash))
758 }
759
760 pub fn stage_all(&self) -> Result<()> {
762 let mut index = self.repo.index().map_err(CascadeError::Git)?;
763
764 index
765 .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
766 .map_err(CascadeError::Git)?;
767
768 index.write().map_err(CascadeError::Git)?;
769
770 tracing::debug!("Staged all changes");
771 Ok(())
772 }
773
774 fn ensure_index_closed(&self) -> Result<()> {
777 let mut index = self.repo.index().map_err(CascadeError::Git)?;
780 index.write().map_err(CascadeError::Git)?;
781 drop(index); std::thread::sleep(std::time::Duration::from_millis(10));
787
788 Ok(())
789 }
790
791 pub fn stage_files(&self, file_paths: &[&str]) -> Result<()> {
793 if file_paths.is_empty() {
794 tracing::debug!("No files to stage");
795 return Ok(());
796 }
797
798 let mut index = self.repo.index().map_err(CascadeError::Git)?;
799
800 for file_path in file_paths {
801 index
802 .add_path(std::path::Path::new(file_path))
803 .map_err(CascadeError::Git)?;
804 }
805
806 index.write().map_err(CascadeError::Git)?;
807
808 tracing::debug!(
809 "Staged {} specific files: {:?}",
810 file_paths.len(),
811 file_paths
812 );
813 Ok(())
814 }
815
816 pub fn stage_conflict_resolved_files(&self) -> Result<()> {
818 let conflicted_files = self.get_conflicted_files()?;
819 if conflicted_files.is_empty() {
820 tracing::debug!("No conflicted files to stage");
821 return Ok(());
822 }
823
824 let file_paths: Vec<&str> = conflicted_files.iter().map(|s| s.as_str()).collect();
825 self.stage_files(&file_paths)?;
826
827 tracing::debug!("Staged {} conflict-resolved files", conflicted_files.len());
828 Ok(())
829 }
830
831 pub fn path(&self) -> &Path {
833 &self.path
834 }
835
836 pub fn commit_exists(&self, commit_hash: &str) -> Result<bool> {
838 match Oid::from_str(commit_hash) {
839 Ok(oid) => match self.repo.find_commit(oid) {
840 Ok(_) => Ok(true),
841 Err(_) => Ok(false),
842 },
843 Err(_) => Ok(false),
844 }
845 }
846
847 pub fn is_commit_based_on(&self, commit_hash: &str, expected_base: &str) -> Result<bool> {
850 let commit_oid = Oid::from_str(commit_hash).map_err(|e| {
851 CascadeError::branch(format!("Invalid commit hash '{}': {}", commit_hash, e))
852 })?;
853
854 let commit = self.repo.find_commit(commit_oid).map_err(|e| {
855 CascadeError::branch(format!("Commit '{}' not found: {}", commit_hash, e))
856 })?;
857
858 if commit.parent_count() == 0 {
860 return Ok(false);
862 }
863
864 let parent = commit.parent(0).map_err(|e| {
865 CascadeError::branch(format!(
866 "Could not get parent of commit '{}': {}",
867 commit_hash, e
868 ))
869 })?;
870 let parent_hash = parent.id().to_string();
871
872 let expected_base_oid = if let Ok(oid) = Oid::from_str(expected_base) {
874 oid
875 } else {
876 let branch_ref = format!("refs/heads/{}", expected_base);
878 let reference = self.repo.find_reference(&branch_ref).map_err(|e| {
879 CascadeError::branch(format!("Could not find base '{}': {}", expected_base, e))
880 })?;
881 reference.target().ok_or_else(|| {
882 CascadeError::branch(format!("Base '{}' has no target commit", expected_base))
883 })?
884 };
885
886 let expected_base_hash = expected_base_oid.to_string();
887
888 tracing::debug!(
889 "Checking if commit {} is based on {}: parent={}, expected={}",
890 &commit_hash[..8],
891 expected_base,
892 &parent_hash[..8],
893 &expected_base_hash[..8]
894 );
895
896 Ok(parent_hash == expected_base_hash)
897 }
898
899 pub fn get_head_commit(&self) -> Result<git2::Commit<'_>> {
901 let head = self
902 .repo
903 .head()
904 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
905 head.peel_to_commit()
906 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))
907 }
908
909 pub fn get_commit(&self, commit_hash: &str) -> Result<git2::Commit<'_>> {
911 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
912
913 self.repo.find_commit(oid).map_err(CascadeError::Git)
914 }
915
916 pub fn get_branch_head(&self, branch_name: &str) -> Result<String> {
918 let branch = self
919 .repo
920 .find_branch(branch_name, git2::BranchType::Local)
921 .map_err(|e| {
922 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
923 })?;
924
925 let commit = branch.get().peel_to_commit().map_err(|e| {
926 CascadeError::branch(format!(
927 "Could not get commit for branch '{branch_name}': {e}"
928 ))
929 })?;
930
931 Ok(commit.id().to_string())
932 }
933
934 pub fn validate_git_user_config(&self) -> Result<()> {
936 if let Ok(config) = self.repo.config() {
937 let name_result = config.get_string("user.name");
938 let email_result = config.get_string("user.email");
939
940 if let (Ok(name), Ok(email)) = (name_result, email_result) {
941 if !name.trim().is_empty() && !email.trim().is_empty() {
942 tracing::debug!("Git user config validated: {} <{}>", name, email);
943 return Ok(());
944 }
945 }
946 }
947
948 let is_ci = std::env::var("CI").is_ok();
950
951 if is_ci {
952 tracing::debug!("CI environment - skipping git user config validation");
953 return Ok(());
954 }
955
956 Output::warning("Git user configuration missing or incomplete");
957 Output::info("This can cause cherry-pick and commit operations to fail");
958 Output::info("Please configure git user information:");
959 Output::bullet("git config user.name \"Your Name\"".to_string());
960 Output::bullet("git config user.email \"your.email@example.com\"".to_string());
961 Output::info("Or set globally with the --global flag");
962
963 Ok(())
966 }
967
968 fn get_signature(&self) -> Result<Signature<'_>> {
970 if let Ok(config) = self.repo.config() {
972 let name_result = config.get_string("user.name");
974 let email_result = config.get_string("user.email");
975
976 if let (Ok(name), Ok(email)) = (name_result, email_result) {
977 if !name.trim().is_empty() && !email.trim().is_empty() {
978 tracing::debug!("Using git config: {} <{}>", name, email);
979 return Signature::now(&name, &email).map_err(CascadeError::Git);
980 }
981 } else {
982 tracing::debug!("Git user config incomplete or missing");
983 }
984 }
985
986 let is_ci = std::env::var("CI").is_ok();
988
989 if is_ci {
990 tracing::debug!("CI environment detected, using fallback signature");
991 return Signature::now("Cascade CLI", "cascade@example.com").map_err(CascadeError::Git);
992 }
993
994 tracing::warn!("Git user configuration missing - this can cause commit operations to fail");
996
997 match Signature::now("Cascade CLI", "cascade@example.com") {
999 Ok(sig) => {
1000 Output::warning("Git user not configured - using fallback signature");
1001 Output::info("For better git history, run:");
1002 Output::bullet("git config user.name \"Your Name\"".to_string());
1003 Output::bullet("git config user.email \"your.email@example.com\"".to_string());
1004 Output::info("Or set it globally with --global flag");
1005 Ok(sig)
1006 }
1007 Err(e) => {
1008 Err(CascadeError::branch(format!(
1009 "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\""
1010 )))
1011 }
1012 }
1013 }
1014
1015 fn configure_remote_callbacks(&self) -> Result<git2::RemoteCallbacks<'_>> {
1018 self.configure_remote_callbacks_with_fallback(false)
1019 }
1020
1021 fn should_retry_with_default_credentials(&self, error: &git2::Error) -> bool {
1023 match error.class() {
1024 git2::ErrorClass::Http => {
1026 match error.code() {
1028 git2::ErrorCode::Auth => true,
1029 _ => {
1030 let error_string = error.to_string();
1032 error_string.contains("too many redirects")
1033 || error_string.contains("authentication replays")
1034 || error_string.contains("authentication required")
1035 }
1036 }
1037 }
1038 git2::ErrorClass::Net => {
1039 let error_string = error.to_string();
1041 error_string.contains("authentication")
1042 || error_string.contains("unauthorized")
1043 || error_string.contains("forbidden")
1044 }
1045 _ => false,
1046 }
1047 }
1048
1049 fn should_fallback_to_git_cli(&self, error: &git2::Error) -> bool {
1051 match error.class() {
1052 git2::ErrorClass::Ssl => true,
1054
1055 git2::ErrorClass::Http if error.code() == git2::ErrorCode::Certificate => true,
1057
1058 git2::ErrorClass::Ssh => {
1060 let error_string = error.to_string();
1061 error_string.contains("no callback set")
1062 || error_string.contains("authentication required")
1063 }
1064
1065 git2::ErrorClass::Net => {
1067 let error_string = error.to_string();
1068 error_string.contains("TLS stream")
1069 || error_string.contains("SSL")
1070 || error_string.contains("proxy")
1071 || error_string.contains("firewall")
1072 }
1073
1074 git2::ErrorClass::Http => {
1076 let error_string = error.to_string();
1077 error_string.contains("TLS stream")
1078 || error_string.contains("SSL")
1079 || error_string.contains("proxy")
1080 }
1081
1082 _ => false,
1083 }
1084 }
1085
1086 fn configure_remote_callbacks_with_fallback(
1087 &self,
1088 use_default_first: bool,
1089 ) -> Result<git2::RemoteCallbacks<'_>> {
1090 let mut callbacks = git2::RemoteCallbacks::new();
1091
1092 let bitbucket_credentials = self.bitbucket_credentials.clone();
1094 callbacks.credentials(move |url, username_from_url, allowed_types| {
1095 tracing::debug!(
1096 "Authentication requested for URL: {}, username: {:?}, allowed_types: {:?}",
1097 url,
1098 username_from_url,
1099 allowed_types
1100 );
1101
1102 if allowed_types.contains(git2::CredentialType::SSH_KEY) {
1104 if let Some(username) = username_from_url {
1105 tracing::debug!("Trying SSH key authentication for user: {}", username);
1106 return git2::Cred::ssh_key_from_agent(username);
1107 }
1108 }
1109
1110 if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
1112 if use_default_first {
1114 tracing::debug!("Corporate network mode: trying DefaultCredentials first");
1115 return git2::Cred::default();
1116 }
1117
1118 if url.contains("bitbucket") {
1119 if let Some(creds) = &bitbucket_credentials {
1120 if let (Some(username), Some(token)) = (&creds.username, &creds.token) {
1122 tracing::debug!("Trying Bitbucket username + token authentication");
1123 return git2::Cred::userpass_plaintext(username, token);
1124 }
1125
1126 if let Some(token) = &creds.token {
1128 tracing::debug!("Trying Bitbucket token-as-username authentication");
1129 return git2::Cred::userpass_plaintext(token, "");
1130 }
1131
1132 if let Some(username) = &creds.username {
1134 tracing::debug!("Trying Bitbucket username authentication (will use credential helper)");
1135 return git2::Cred::username(username);
1136 }
1137 }
1138 }
1139
1140 tracing::debug!("Trying default credential helper for HTTPS authentication");
1142 return git2::Cred::default();
1143 }
1144
1145 tracing::debug!("Using default credential fallback");
1147 git2::Cred::default()
1148 });
1149
1150 let mut ssl_configured = false;
1155
1156 if let Some(ssl_config) = &self.ssl_config {
1158 if ssl_config.accept_invalid_certs {
1159 Output::warning(
1160 "SSL certificate verification DISABLED via Cascade config - this is insecure!",
1161 );
1162 callbacks.certificate_check(|_cert, _host| {
1163 tracing::debug!("⚠️ Accepting invalid certificate for host: {}", _host);
1164 Ok(git2::CertificateCheckStatus::CertificateOk)
1165 });
1166 ssl_configured = true;
1167 } else if let Some(ca_path) = &ssl_config.ca_bundle_path {
1168 Output::info(format!(
1169 "Using custom CA bundle from Cascade config: {ca_path}"
1170 ));
1171 callbacks.certificate_check(|_cert, host| {
1172 tracing::debug!("Using custom CA bundle for host: {}", host);
1173 Ok(git2::CertificateCheckStatus::CertificateOk)
1174 });
1175 ssl_configured = true;
1176 }
1177 }
1178
1179 if !ssl_configured {
1181 if let Ok(config) = self.repo.config() {
1182 let ssl_verify = config.get_bool("http.sslVerify").unwrap_or(true);
1183
1184 if !ssl_verify {
1185 Output::warning(
1186 "SSL certificate verification DISABLED via git config - this is insecure!",
1187 );
1188 callbacks.certificate_check(|_cert, host| {
1189 tracing::debug!("⚠️ Bypassing SSL verification for host: {}", host);
1190 Ok(git2::CertificateCheckStatus::CertificateOk)
1191 });
1192 ssl_configured = true;
1193 } else if let Ok(ca_path) = config.get_string("http.sslCAInfo") {
1194 Output::info(format!("Using custom CA bundle from git config: {ca_path}"));
1195 callbacks.certificate_check(|_cert, host| {
1196 tracing::debug!("Using git config CA bundle for host: {}", host);
1197 Ok(git2::CertificateCheckStatus::CertificateOk)
1198 });
1199 ssl_configured = true;
1200 }
1201 }
1202 }
1203
1204 if !ssl_configured {
1207 tracing::debug!(
1208 "Using system certificate store for SSL verification (default behavior)"
1209 );
1210
1211 if cfg!(target_os = "macos") {
1213 tracing::debug!("macOS detected - using default certificate validation");
1214 } else {
1217 callbacks.certificate_check(|_cert, host| {
1219 tracing::debug!("System certificate validation for host: {}", host);
1220 Ok(git2::CertificateCheckStatus::CertificatePassthrough)
1221 });
1222 }
1223 }
1224
1225 Ok(callbacks)
1226 }
1227
1228 fn get_index_tree(&self) -> Result<Oid> {
1230 let mut index = self.repo.index().map_err(CascadeError::Git)?;
1231
1232 index.write_tree().map_err(CascadeError::Git)
1233 }
1234
1235 pub fn get_status(&self) -> Result<git2::Statuses<'_>> {
1237 self.repo.statuses(None).map_err(CascadeError::Git)
1238 }
1239
1240 pub fn get_status_summary(&self) -> Result<GitStatusSummary> {
1242 let statuses = self.get_status()?;
1243
1244 let mut staged_files = 0;
1245 let mut unstaged_files = 0;
1246 let mut untracked_files = 0;
1247
1248 for status in statuses.iter() {
1249 let flags = status.status();
1250
1251 if flags.intersects(
1252 git2::Status::INDEX_MODIFIED
1253 | git2::Status::INDEX_NEW
1254 | git2::Status::INDEX_DELETED
1255 | git2::Status::INDEX_RENAMED
1256 | git2::Status::INDEX_TYPECHANGE,
1257 ) {
1258 staged_files += 1;
1259 }
1260
1261 if flags.intersects(
1262 git2::Status::WT_MODIFIED
1263 | git2::Status::WT_DELETED
1264 | git2::Status::WT_TYPECHANGE
1265 | git2::Status::WT_RENAMED,
1266 ) {
1267 unstaged_files += 1;
1268 }
1269
1270 if flags.intersects(git2::Status::WT_NEW) {
1271 untracked_files += 1;
1272 }
1273 }
1274
1275 Ok(GitStatusSummary {
1276 staged_files,
1277 unstaged_files,
1278 untracked_files,
1279 })
1280 }
1281
1282 pub fn get_current_commit_hash(&self) -> Result<String> {
1284 self.get_head_commit_hash()
1285 }
1286
1287 pub fn get_commit_count_between(&self, from_commit: &str, to_commit: &str) -> Result<usize> {
1289 let from_oid = git2::Oid::from_str(from_commit).map_err(CascadeError::Git)?;
1290 let to_oid = git2::Oid::from_str(to_commit).map_err(CascadeError::Git)?;
1291
1292 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1293 revwalk.push(to_oid).map_err(CascadeError::Git)?;
1294 revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1295
1296 Ok(revwalk.count())
1297 }
1298
1299 pub fn get_remote_url(&self, name: &str) -> Result<String> {
1301 let remote = self.repo.find_remote(name).map_err(CascadeError::Git)?;
1302 Ok(remote.url().unwrap_or("unknown").to_string())
1303 }
1304
1305 pub fn cherry_pick(&self, commit_hash: &str) -> Result<String> {
1307 tracing::debug!("Cherry-picking commit {}", commit_hash);
1308
1309 self.validate_git_user_config()?;
1311
1312 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1313 let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1314
1315 let commit_tree = commit.tree().map_err(CascadeError::Git)?;
1317
1318 let parent_commit = if commit.parent_count() > 0 {
1320 commit.parent(0).map_err(CascadeError::Git)?
1321 } else {
1322 let empty_tree_oid = self.repo.treebuilder(None)?.write()?;
1324 let empty_tree = self.repo.find_tree(empty_tree_oid)?;
1325 let sig = self.get_signature()?;
1326 return self
1327 .repo
1328 .commit(
1329 Some("HEAD"),
1330 &sig,
1331 &sig,
1332 commit.message().unwrap_or("Cherry-picked commit"),
1333 &empty_tree,
1334 &[],
1335 )
1336 .map(|oid| oid.to_string())
1337 .map_err(CascadeError::Git);
1338 };
1339
1340 let parent_tree = parent_commit.tree().map_err(CascadeError::Git)?;
1341
1342 let head_commit = self.get_head_commit()?;
1344 let head_tree = head_commit.tree().map_err(CascadeError::Git)?;
1345
1346 let mut index = self
1348 .repo
1349 .merge_trees(&parent_tree, &head_tree, &commit_tree, None)
1350 .map_err(CascadeError::Git)?;
1351
1352 if index.has_conflicts() {
1354 debug!("Cherry-pick has conflicts - writing conflicted state to disk for resolution");
1357
1358 let mut repo_index = self.repo.index().map_err(CascadeError::Git)?;
1364
1365 repo_index.clear().map_err(CascadeError::Git)?;
1367 repo_index
1368 .read_tree(&head_tree)
1369 .map_err(CascadeError::Git)?;
1370
1371 repo_index
1373 .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
1374 .map_err(CascadeError::Git)?;
1375
1376 drop(repo_index);
1381 self.ensure_index_closed()?;
1382
1383 let cherry_pick_output = std::process::Command::new("git")
1384 .args(["cherry-pick", commit_hash])
1385 .current_dir(self.path())
1386 .output()
1387 .map_err(CascadeError::Io)?;
1388
1389 if !cherry_pick_output.status.success() {
1390 debug!("Git CLI cherry-pick failed as expected (has conflicts)");
1391 }
1394
1395 self.repo
1398 .index()
1399 .and_then(|mut idx| idx.read(true).map(|_| ()))
1400 .map_err(CascadeError::Git)?;
1401
1402 debug!("Conflicted state written and index reloaded - auto-resolve can now process conflicts");
1403
1404 return Err(CascadeError::branch(format!(
1405 "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
1406 )));
1407 }
1408
1409 let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
1411 let merged_tree = self
1412 .repo
1413 .find_tree(merged_tree_oid)
1414 .map_err(CascadeError::Git)?;
1415
1416 let signature = self.get_signature()?;
1418 let message = commit.message().unwrap_or("Cherry-picked commit");
1419
1420 let new_commit_oid = self
1421 .repo
1422 .commit(
1423 Some("HEAD"),
1424 &signature,
1425 &signature,
1426 message,
1427 &merged_tree,
1428 &[&head_commit],
1429 )
1430 .map_err(CascadeError::Git)?;
1431
1432 let new_commit = self
1434 .repo
1435 .find_commit(new_commit_oid)
1436 .map_err(CascadeError::Git)?;
1437 let new_tree = new_commit.tree().map_err(CascadeError::Git)?;
1438
1439 self.repo
1440 .checkout_tree(
1441 new_tree.as_object(),
1442 Some(git2::build::CheckoutBuilder::new().force()),
1443 )
1444 .map_err(CascadeError::Git)?;
1445
1446 tracing::debug!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
1447 Ok(new_commit_oid.to_string())
1448 }
1449
1450 pub fn has_conflicts(&self) -> Result<bool> {
1452 let index = self.repo.index().map_err(CascadeError::Git)?;
1453 Ok(index.has_conflicts())
1454 }
1455
1456 pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
1458 let index = self.repo.index().map_err(CascadeError::Git)?;
1459
1460 let mut conflicts = Vec::new();
1461
1462 let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;
1464
1465 for conflict in conflict_iter {
1466 let conflict = conflict.map_err(CascadeError::Git)?;
1467 if let Some(our) = conflict.our {
1468 if let Ok(path) = std::str::from_utf8(&our.path) {
1469 conflicts.push(path.to_string());
1470 }
1471 } else if let Some(their) = conflict.their {
1472 if let Ok(path) = std::str::from_utf8(&their.path) {
1473 conflicts.push(path.to_string());
1474 }
1475 }
1476 }
1477
1478 Ok(conflicts)
1479 }
1480
1481 pub fn fetch(&self) -> Result<()> {
1483 tracing::debug!("Fetching from origin");
1484
1485 let mut remote = self
1486 .repo
1487 .find_remote("origin")
1488 .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1489
1490 let callbacks = self.configure_remote_callbacks()?;
1492
1493 let mut fetch_options = git2::FetchOptions::new();
1495 fetch_options.remote_callbacks(callbacks);
1496
1497 match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1499 Ok(_) => {
1500 tracing::debug!("Fetch completed successfully");
1501 Ok(())
1502 }
1503 Err(e) => {
1504 if self.should_retry_with_default_credentials(&e) {
1505 tracing::debug!(
1506 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1507 e.class(), e.code(), e
1508 );
1509
1510 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1512 let mut fetch_options = git2::FetchOptions::new();
1513 fetch_options.remote_callbacks(callbacks);
1514
1515 match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1516 Ok(_) => {
1517 tracing::debug!("Fetch succeeded with DefaultCredentials");
1518 return Ok(());
1519 }
1520 Err(retry_error) => {
1521 tracing::debug!(
1522 "DefaultCredentials retry failed: {}, falling back to git CLI",
1523 retry_error
1524 );
1525 return self.fetch_with_git_cli();
1526 }
1527 }
1528 }
1529
1530 if self.should_fallback_to_git_cli(&e) {
1531 tracing::debug!(
1532 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for fetch operation",
1533 e.class(), e.code(), e
1534 );
1535 return self.fetch_with_git_cli();
1536 }
1537 Err(CascadeError::Git(e))
1538 }
1539 }
1540 }
1541
1542 pub fn pull(&self, branch: &str) -> Result<()> {
1544 tracing::debug!("Pulling branch: {}", branch);
1545
1546 match self.fetch() {
1548 Ok(_) => {}
1549 Err(e) => {
1550 let error_string = e.to_string();
1552 if error_string.contains("TLS stream") || error_string.contains("SSL") {
1553 tracing::warn!(
1554 "git2 error detected: {}, falling back to git CLI for pull operation",
1555 e
1556 );
1557 return self.pull_with_git_cli(branch);
1558 }
1559 return Err(e);
1560 }
1561 }
1562
1563 let remote_branch_name = format!("origin/{branch}");
1565 let remote_oid = self
1566 .repo
1567 .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
1568 .map_err(|e| {
1569 CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
1570 })?;
1571
1572 let remote_commit = self
1573 .repo
1574 .find_commit(remote_oid)
1575 .map_err(CascadeError::Git)?;
1576
1577 let head_commit = self.get_head_commit()?;
1579
1580 if head_commit.id() == remote_commit.id() {
1582 tracing::debug!("Already up to date");
1583 return Ok(());
1584 }
1585
1586 let merge_base_oid = self
1588 .repo
1589 .merge_base(head_commit.id(), remote_commit.id())
1590 .map_err(CascadeError::Git)?;
1591
1592 if merge_base_oid == head_commit.id() {
1593 tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());
1595
1596 let refname = format!("refs/heads/{}", branch);
1598 self.repo
1599 .reference(&refname, remote_oid, true, "pull: Fast-forward")
1600 .map_err(CascadeError::Git)?;
1601
1602 self.repo.set_head(&refname).map_err(CascadeError::Git)?;
1604
1605 self.repo
1607 .checkout_head(Some(
1608 git2::build::CheckoutBuilder::new()
1609 .force()
1610 .remove_untracked(false),
1611 ))
1612 .map_err(CascadeError::Git)?;
1613
1614 tracing::debug!("Fast-forwarded to {}", remote_commit.id());
1615 return Ok(());
1616 }
1617
1618 Err(CascadeError::branch(format!(
1621 "Branch '{}' has diverged from remote. Local has commits not in remote. \
1622 Protected branches should not have local commits. \
1623 Try: git reset --hard origin/{}",
1624 branch, branch
1625 )))
1626 }
1627
1628 pub fn push(&self, branch: &str) -> Result<()> {
1630 let mut remote = self
1633 .repo
1634 .find_remote("origin")
1635 .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1636
1637 let remote_url = remote.url().unwrap_or("unknown").to_string();
1638 tracing::debug!("Remote URL: {}", remote_url);
1639
1640 let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1641 tracing::debug!("Push refspec: {}", refspec);
1642
1643 let mut callbacks = self.configure_remote_callbacks()?;
1645
1646 callbacks.push_update_reference(|refname, status| {
1648 if let Some(msg) = status {
1649 tracing::error!("Push failed for ref {}: {}", refname, msg);
1650 return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1651 }
1652 tracing::debug!("Push succeeded for ref: {}", refname);
1653 Ok(())
1654 });
1655
1656 let mut push_options = git2::PushOptions::new();
1658 push_options.remote_callbacks(callbacks);
1659
1660 match remote.push(&[&refspec], Some(&mut push_options)) {
1662 Ok(_) => {
1663 tracing::debug!("Push completed successfully for branch: {}", branch);
1664 Ok(())
1665 }
1666 Err(e) => {
1667 tracing::debug!(
1668 "git2 push error: {} (class: {:?}, code: {:?})",
1669 e,
1670 e.class(),
1671 e.code()
1672 );
1673
1674 if self.should_retry_with_default_credentials(&e) {
1675 tracing::debug!(
1676 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1677 e.class(), e.code(), e
1678 );
1679
1680 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1682 let mut push_options = git2::PushOptions::new();
1683 push_options.remote_callbacks(callbacks);
1684
1685 match remote.push(&[&refspec], Some(&mut push_options)) {
1686 Ok(_) => {
1687 tracing::debug!("Push succeeded with DefaultCredentials");
1688 return Ok(());
1689 }
1690 Err(retry_error) => {
1691 tracing::debug!(
1692 "DefaultCredentials retry failed: {}, falling back to git CLI",
1693 retry_error
1694 );
1695 return self.push_with_git_cli(branch);
1696 }
1697 }
1698 }
1699
1700 if self.should_fallback_to_git_cli(&e) {
1701 tracing::debug!(
1702 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
1703 e.class(), e.code(), e
1704 );
1705 return self.push_with_git_cli(branch);
1706 }
1707
1708 let error_msg = if e.to_string().contains("authentication") {
1710 format!(
1711 "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1712 )
1713 } else {
1714 format!("Failed to push branch '{branch}': {e}")
1715 };
1716
1717 tracing::error!("{}", error_msg);
1718 Err(CascadeError::branch(error_msg))
1719 }
1720 }
1721 }
1722
1723 fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1726 self.ensure_index_closed()?;
1728
1729 let output = std::process::Command::new("git")
1730 .args(["push", "origin", branch])
1731 .current_dir(&self.path)
1732 .output()
1733 .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1734
1735 if output.status.success() {
1736 Ok(())
1738 } else {
1739 let stderr = String::from_utf8_lossy(&output.stderr);
1740 let _stdout = String::from_utf8_lossy(&output.stdout);
1741 let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
1743 "Network error: Unable to connect to repository (VPN may be required)".to_string()
1744 } else if stderr.contains("repository") && stderr.contains("not found") {
1745 "Repository not found - check your Bitbucket configuration".to_string()
1746 } else if stderr.contains("authentication") || stderr.contains("403") {
1747 "Authentication failed - check your credentials".to_string()
1748 } else {
1749 stderr.trim().to_string()
1751 };
1752 tracing::error!("{}", error_msg);
1753 Err(CascadeError::branch(error_msg))
1754 }
1755 }
1756
1757 fn fetch_with_git_cli(&self) -> Result<()> {
1760 tracing::debug!("Using git CLI fallback for fetch operation");
1761
1762 self.ensure_index_closed()?;
1764
1765 let output = std::process::Command::new("git")
1766 .args(["fetch", "origin"])
1767 .current_dir(&self.path)
1768 .output()
1769 .map_err(|e| {
1770 CascadeError::Git(git2::Error::from_str(&format!(
1771 "Failed to execute git command: {e}"
1772 )))
1773 })?;
1774
1775 if output.status.success() {
1776 tracing::debug!("Git CLI fetch succeeded");
1777 Ok(())
1778 } else {
1779 let stderr = String::from_utf8_lossy(&output.stderr);
1780 let stdout = String::from_utf8_lossy(&output.stdout);
1781 let error_msg = format!(
1782 "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
1783 output.status, stdout, stderr
1784 );
1785 tracing::error!("{}", error_msg);
1786 Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1787 }
1788 }
1789
1790 fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
1793 tracing::debug!("Using git CLI fallback for pull operation: {}", branch);
1794
1795 self.ensure_index_closed()?;
1797
1798 let output = std::process::Command::new("git")
1799 .args(["pull", "origin", branch])
1800 .current_dir(&self.path)
1801 .output()
1802 .map_err(|e| {
1803 CascadeError::Git(git2::Error::from_str(&format!(
1804 "Failed to execute git command: {e}"
1805 )))
1806 })?;
1807
1808 if output.status.success() {
1809 tracing::debug!("Git CLI pull succeeded for branch: {}", branch);
1810 Ok(())
1811 } else {
1812 let stderr = String::from_utf8_lossy(&output.stderr);
1813 let stdout = String::from_utf8_lossy(&output.stdout);
1814 let error_msg = format!(
1815 "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1816 branch, output.status, stdout, stderr
1817 );
1818 tracing::error!("{}", error_msg);
1819 Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1820 }
1821 }
1822
1823 fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
1826 tracing::debug!(
1827 "Using git CLI fallback for force push operation: {}",
1828 branch
1829 );
1830
1831 let output = std::process::Command::new("git")
1832 .args(["push", "--force", "origin", branch])
1833 .current_dir(&self.path)
1834 .output()
1835 .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1836
1837 if output.status.success() {
1838 tracing::debug!("Git CLI force push succeeded for branch: {}", branch);
1839 Ok(())
1840 } else {
1841 let stderr = String::from_utf8_lossy(&output.stderr);
1842 let stdout = String::from_utf8_lossy(&output.stdout);
1843 let error_msg = format!(
1844 "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1845 branch, output.status, stdout, stderr
1846 );
1847 tracing::error!("{}", error_msg);
1848 Err(CascadeError::branch(error_msg))
1849 }
1850 }
1851
1852 pub fn delete_branch(&self, name: &str) -> Result<()> {
1854 self.delete_branch_with_options(name, false)
1855 }
1856
1857 pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
1859 self.delete_branch_with_options(name, true)
1860 }
1861
1862 fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
1864 debug!("Attempting to delete branch: {}", name);
1865
1866 if !force_unsafe {
1868 let safety_result = self.check_branch_deletion_safety(name)?;
1869 if let Some(safety_info) = safety_result {
1870 self.handle_branch_deletion_confirmation(name, &safety_info)?;
1872 }
1873 }
1874
1875 let mut branch = self
1876 .repo
1877 .find_branch(name, git2::BranchType::Local)
1878 .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
1879
1880 branch
1881 .delete()
1882 .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
1883
1884 debug!("Successfully deleted branch '{}'", name);
1885 Ok(())
1886 }
1887
1888 pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
1890 let from_oid = self
1891 .repo
1892 .refname_to_id(&format!("refs/heads/{from}"))
1893 .or_else(|_| Oid::from_str(from))
1894 .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
1895
1896 let to_oid = self
1897 .repo
1898 .refname_to_id(&format!("refs/heads/{to}"))
1899 .or_else(|_| Oid::from_str(to))
1900 .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
1901
1902 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1903
1904 revwalk.push(to_oid).map_err(CascadeError::Git)?;
1905 revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1906
1907 let mut commits = Vec::new();
1908 for oid in revwalk {
1909 let oid = oid.map_err(CascadeError::Git)?;
1910 let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1911 commits.push(commit);
1912 }
1913
1914 Ok(commits)
1915 }
1916
1917 pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1920 self.force_push_branch_with_options(target_branch, source_branch, false)
1921 }
1922
1923 pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1925 self.force_push_branch_with_options(target_branch, source_branch, true)
1926 }
1927
1928 fn force_push_branch_with_options(
1930 &self,
1931 target_branch: &str,
1932 source_branch: &str,
1933 force_unsafe: bool,
1934 ) -> Result<()> {
1935 debug!(
1936 "Force pushing {} content to {} to preserve PR history",
1937 source_branch, target_branch
1938 );
1939
1940 if !force_unsafe {
1942 let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
1943 if let Some(backup_info) = safety_result {
1944 self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
1946 debug!("Created backup branch: {}", backup_info.backup_branch_name);
1947 }
1948 }
1949
1950 let source_ref = self
1952 .repo
1953 .find_reference(&format!("refs/heads/{source_branch}"))
1954 .map_err(|e| {
1955 CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
1956 })?;
1957 let _source_commit = source_ref.peel_to_commit().map_err(|e| {
1958 CascadeError::config(format!(
1959 "Failed to get commit for source branch {source_branch}: {e}"
1960 ))
1961 })?;
1962
1963 let mut remote = self
1965 .repo
1966 .find_remote("origin")
1967 .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
1968
1969 let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");
1971
1972 let callbacks = self.configure_remote_callbacks()?;
1974
1975 let mut push_options = git2::PushOptions::new();
1977 push_options.remote_callbacks(callbacks);
1978
1979 match remote.push(&[&refspec], Some(&mut push_options)) {
1980 Ok(_) => {}
1981 Err(e) => {
1982 if self.should_retry_with_default_credentials(&e) {
1983 tracing::debug!(
1984 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1985 e.class(), e.code(), e
1986 );
1987
1988 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1990 let mut push_options = git2::PushOptions::new();
1991 push_options.remote_callbacks(callbacks);
1992
1993 match remote.push(&[&refspec], Some(&mut push_options)) {
1994 Ok(_) => {
1995 tracing::debug!("Force push succeeded with DefaultCredentials");
1996 }
1998 Err(retry_error) => {
1999 tracing::debug!(
2000 "DefaultCredentials retry failed: {}, falling back to git CLI",
2001 retry_error
2002 );
2003 return self.force_push_with_git_cli(target_branch);
2004 }
2005 }
2006 } else if self.should_fallback_to_git_cli(&e) {
2007 tracing::debug!(
2008 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
2009 e.class(), e.code(), e
2010 );
2011 return self.force_push_with_git_cli(target_branch);
2012 } else {
2013 return Err(CascadeError::config(format!(
2014 "Failed to force push {target_branch}: {e}"
2015 )));
2016 }
2017 }
2018 }
2019
2020 tracing::debug!(
2021 "Successfully force pushed {} to preserve PR history",
2022 target_branch
2023 );
2024 Ok(())
2025 }
2026
2027 fn check_force_push_safety_enhanced(
2030 &self,
2031 target_branch: &str,
2032 ) -> Result<Option<ForceBackupInfo>> {
2033 match self.fetch() {
2035 Ok(_) => {}
2036 Err(e) => {
2037 warn!("Could not fetch latest changes for safety check: {}", e);
2039 }
2040 }
2041
2042 let remote_ref = format!("refs/remotes/origin/{target_branch}");
2044 let local_ref = format!("refs/heads/{target_branch}");
2045
2046 let local_commit = match self.repo.find_reference(&local_ref) {
2048 Ok(reference) => reference.peel_to_commit().ok(),
2049 Err(_) => None,
2050 };
2051
2052 let remote_commit = match self.repo.find_reference(&remote_ref) {
2053 Ok(reference) => reference.peel_to_commit().ok(),
2054 Err(_) => None,
2055 };
2056
2057 if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2059 if local.id() != remote.id() {
2060 let merge_base_oid = self
2062 .repo
2063 .merge_base(local.id(), remote.id())
2064 .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2065
2066 if merge_base_oid != remote.id() {
2068 let commits_to_lose = self.count_commits_between(
2069 &merge_base_oid.to_string(),
2070 &remote.id().to_string(),
2071 )?;
2072
2073 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2075 let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2076
2077 debug!(
2078 "Force push to '{}' would overwrite {} commits on remote",
2079 target_branch, commits_to_lose
2080 );
2081
2082 if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
2084 {
2085 info!(
2086 "Non-interactive environment detected, proceeding with backup creation"
2087 );
2088 return Ok(Some(ForceBackupInfo {
2089 backup_branch_name,
2090 remote_commit_id: remote.id().to_string(),
2091 commits_that_would_be_lost: commits_to_lose,
2092 }));
2093 }
2094
2095 println!();
2097 Output::warning("FORCE PUSH WARNING");
2098 println!("Force push to '{target_branch}' would overwrite {commits_to_lose} commits on remote:");
2099
2100 match self
2102 .get_commits_between(&merge_base_oid.to_string(), &remote.id().to_string())
2103 {
2104 Ok(commits) => {
2105 println!();
2106 println!("Commits that would be lost:");
2107 for (i, commit) in commits.iter().take(5).enumerate() {
2108 let short_hash = &commit.id().to_string()[..8];
2109 let summary = commit.summary().unwrap_or("<no message>");
2110 println!(" {}. {} - {}", i + 1, short_hash, summary);
2111 }
2112 if commits.len() > 5 {
2113 println!(" ... and {} more commits", commits.len() - 5);
2114 }
2115 }
2116 Err(_) => {
2117 println!(" (Unable to retrieve commit details)");
2118 }
2119 }
2120
2121 println!();
2122 Output::info(format!(
2123 "A backup branch '{backup_branch_name}' will be created before proceeding."
2124 ));
2125
2126 let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2127 .with_prompt("Do you want to proceed with the force push?")
2128 .default(false)
2129 .interact()
2130 .map_err(|e| {
2131 CascadeError::config(format!("Failed to get user confirmation: {e}"))
2132 })?;
2133
2134 if !confirmed {
2135 return Err(CascadeError::config(
2136 "Force push cancelled by user. Use --force to bypass this check."
2137 .to_string(),
2138 ));
2139 }
2140
2141 return Ok(Some(ForceBackupInfo {
2142 backup_branch_name,
2143 remote_commit_id: remote.id().to_string(),
2144 commits_that_would_be_lost: commits_to_lose,
2145 }));
2146 }
2147 }
2148 }
2149
2150 Ok(None)
2151 }
2152
2153 fn is_likely_rebase_scenario(&self, local_oid: &str, remote_oid: &str) -> bool {
2156 let local_oid_parsed = match git2::Oid::from_str(local_oid) {
2158 Ok(oid) => oid,
2159 Err(_) => return false,
2160 };
2161
2162 let remote_oid_parsed = match git2::Oid::from_str(remote_oid) {
2163 Ok(oid) => oid,
2164 Err(_) => return false,
2165 };
2166
2167 let local_commit = match self.repo.find_commit(local_oid_parsed) {
2168 Ok(c) => c,
2169 Err(_) => return false,
2170 };
2171
2172 let remote_commit = match self.repo.find_commit(remote_oid_parsed) {
2173 Ok(c) => c,
2174 Err(_) => return false,
2175 };
2176
2177 let local_msg = local_commit.message().unwrap_or("");
2179 let remote_msg = remote_commit.message().unwrap_or("");
2180
2181 if local_msg == remote_msg {
2183 return true;
2184 }
2185
2186 let local_count = local_commit.parent_count();
2189 let remote_count = remote_commit.parent_count();
2190
2191 if local_count == remote_count && local_count > 0 {
2192 let mut local_walker = match self.repo.revwalk() {
2194 Ok(w) => w,
2195 Err(_) => return false,
2196 };
2197 let mut remote_walker = match self.repo.revwalk() {
2198 Ok(w) => w,
2199 Err(_) => return false,
2200 };
2201
2202 if local_walker.push(local_commit.id()).is_err() {
2203 return false;
2204 }
2205 if remote_walker.push(remote_commit.id()).is_err() {
2206 return false;
2207 }
2208
2209 let local_messages: Vec<String> = local_walker
2210 .take(5) .filter_map(|oid| {
2212 self.repo
2213 .find_commit(oid.ok()?)
2214 .ok()?
2215 .message()
2216 .map(|s| s.to_string())
2217 })
2218 .collect();
2219
2220 let remote_messages: Vec<String> = remote_walker
2221 .take(5)
2222 .filter_map(|oid| {
2223 self.repo
2224 .find_commit(oid.ok()?)
2225 .ok()?
2226 .message()
2227 .map(|s| s.to_string())
2228 })
2229 .collect();
2230
2231 let matches = local_messages
2233 .iter()
2234 .zip(remote_messages.iter())
2235 .filter(|(l, r)| l == r)
2236 .count();
2237
2238 return matches >= local_messages.len() / 2;
2239 }
2240
2241 false
2242 }
2243
2244 fn check_force_push_safety_auto(&self, target_branch: &str) -> Result<Option<ForceBackupInfo>> {
2247 match self.fetch() {
2249 Ok(_) => {}
2250 Err(e) => {
2251 warn!("Could not fetch latest changes for safety check: {}", e);
2252 }
2253 }
2254
2255 let remote_ref = format!("refs/remotes/origin/{target_branch}");
2257 let local_ref = format!("refs/heads/{target_branch}");
2258
2259 let local_commit = match self.repo.find_reference(&local_ref) {
2261 Ok(reference) => reference.peel_to_commit().ok(),
2262 Err(_) => None,
2263 };
2264
2265 let remote_commit = match self.repo.find_reference(&remote_ref) {
2266 Ok(reference) => reference.peel_to_commit().ok(),
2267 Err(_) => None,
2268 };
2269
2270 if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2272 if local.id() != remote.id() {
2273 let merge_base_oid = self
2275 .repo
2276 .merge_base(local.id(), remote.id())
2277 .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2278
2279 if merge_base_oid != remote.id() {
2281 let is_likely_rebase = self.is_likely_rebase_scenario(
2284 &local.id().to_string(),
2285 &remote.id().to_string(),
2286 );
2287
2288 if is_likely_rebase {
2289 debug!(
2290 "Detected rebase scenario for '{}' - skipping backup (commit content preserved)",
2291 target_branch
2292 );
2293 return Ok(None);
2295 }
2296
2297 let commits_to_lose = self.count_commits_between(
2298 &merge_base_oid.to_string(),
2299 &remote.id().to_string(),
2300 )?;
2301
2302 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2304 let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2305
2306 debug!(
2307 "Auto-creating backup for force push to '{}' (would overwrite {} commits)",
2308 target_branch, commits_to_lose
2309 );
2310
2311 return Ok(Some(ForceBackupInfo {
2313 backup_branch_name,
2314 remote_commit_id: remote.id().to_string(),
2315 commits_that_would_be_lost: commits_to_lose,
2316 }));
2317 }
2318 }
2319 }
2320
2321 Ok(None)
2322 }
2323
2324 fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
2326 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2327 let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
2328
2329 let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
2331 CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
2332 })?;
2333
2334 let commit = self.repo.find_commit(commit_oid).map_err(|e| {
2336 CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
2337 })?;
2338
2339 self.repo
2341 .branch(&backup_branch_name, &commit, false)
2342 .map_err(|e| {
2343 CascadeError::config(format!(
2344 "Failed to create backup branch {backup_branch_name}: {e}"
2345 ))
2346 })?;
2347
2348 debug!(
2349 "Created backup branch '{}' pointing to {}",
2350 backup_branch_name,
2351 &remote_commit_id[..8]
2352 );
2353 Ok(())
2354 }
2355
2356 fn check_branch_deletion_safety(
2359 &self,
2360 branch_name: &str,
2361 ) -> Result<Option<BranchDeletionSafety>> {
2362 match self.fetch() {
2364 Ok(_) => {}
2365 Err(e) => {
2366 warn!(
2367 "Could not fetch latest changes for branch deletion safety check: {}",
2368 e
2369 );
2370 }
2371 }
2372
2373 let branch = self
2375 .repo
2376 .find_branch(branch_name, git2::BranchType::Local)
2377 .map_err(|e| {
2378 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2379 })?;
2380
2381 let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
2382 CascadeError::branch(format!(
2383 "Could not get commit for branch '{branch_name}': {e}"
2384 ))
2385 })?;
2386
2387 let main_branch_name = self.detect_main_branch()?;
2389
2390 let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
2392
2393 let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
2395
2396 let mut unpushed_commits = Vec::new();
2397
2398 if let Some(ref remote_branch) = remote_tracking_branch {
2400 match self.get_commits_between(remote_branch, branch_name) {
2401 Ok(commits) => {
2402 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2403 }
2404 Err(_) => {
2405 if !is_merged_to_main {
2407 if let Ok(commits) =
2408 self.get_commits_between(&main_branch_name, branch_name)
2409 {
2410 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2411 }
2412 }
2413 }
2414 }
2415 } else if !is_merged_to_main {
2416 if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
2418 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2419 }
2420 }
2421
2422 if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
2424 {
2425 Ok(Some(BranchDeletionSafety {
2426 unpushed_commits,
2427 remote_tracking_branch,
2428 is_merged_to_main,
2429 main_branch_name,
2430 }))
2431 } else {
2432 Ok(None)
2433 }
2434 }
2435
2436 fn handle_branch_deletion_confirmation(
2438 &self,
2439 branch_name: &str,
2440 safety_info: &BranchDeletionSafety,
2441 ) -> Result<()> {
2442 if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
2444 return Err(CascadeError::branch(
2445 format!(
2446 "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
2447 safety_info.unpushed_commits.len()
2448 )
2449 ));
2450 }
2451
2452 println!();
2454 Output::warning("BRANCH DELETION WARNING");
2455 println!("Branch '{branch_name}' has potential issues:");
2456
2457 if !safety_info.unpushed_commits.is_empty() {
2458 println!(
2459 "\n🔍 Unpushed commits ({} total):",
2460 safety_info.unpushed_commits.len()
2461 );
2462
2463 for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
2465 if let Ok(oid) = Oid::from_str(commit_id) {
2466 if let Ok(commit) = self.repo.find_commit(oid) {
2467 let short_hash = &commit_id[..8];
2468 let summary = commit.summary().unwrap_or("<no message>");
2469 println!(" {}. {} - {}", i + 1, short_hash, summary);
2470 }
2471 }
2472 }
2473
2474 if safety_info.unpushed_commits.len() > 5 {
2475 println!(
2476 " ... and {} more commits",
2477 safety_info.unpushed_commits.len() - 5
2478 );
2479 }
2480 }
2481
2482 if !safety_info.is_merged_to_main {
2483 println!();
2484 crate::cli::output::Output::section("Branch status");
2485 crate::cli::output::Output::bullet(format!(
2486 "Not merged to '{}'",
2487 safety_info.main_branch_name
2488 ));
2489 if let Some(ref remote) = safety_info.remote_tracking_branch {
2490 crate::cli::output::Output::bullet(format!("Remote tracking branch: {remote}"));
2491 } else {
2492 crate::cli::output::Output::bullet("No remote tracking branch");
2493 }
2494 }
2495
2496 println!();
2497 crate::cli::output::Output::section("Safer alternatives");
2498 if !safety_info.unpushed_commits.is_empty() {
2499 if let Some(ref _remote) = safety_info.remote_tracking_branch {
2500 println!(" • Push commits first: git push origin {branch_name}");
2501 } else {
2502 println!(" • Create and push to remote: git push -u origin {branch_name}");
2503 }
2504 }
2505 if !safety_info.is_merged_to_main {
2506 println!(
2507 " • Merge to {} first: git checkout {} && git merge {branch_name}",
2508 safety_info.main_branch_name, safety_info.main_branch_name
2509 );
2510 }
2511
2512 let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2513 .with_prompt("Do you want to proceed with deleting this branch?")
2514 .default(false)
2515 .interact()
2516 .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
2517
2518 if !confirmed {
2519 return Err(CascadeError::branch(
2520 "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
2521 ));
2522 }
2523
2524 Ok(())
2525 }
2526
2527 pub fn detect_main_branch(&self) -> Result<String> {
2529 let main_candidates = ["main", "master", "develop", "trunk"];
2530
2531 for candidate in &main_candidates {
2532 if self
2533 .repo
2534 .find_branch(candidate, git2::BranchType::Local)
2535 .is_ok()
2536 {
2537 return Ok(candidate.to_string());
2538 }
2539 }
2540
2541 if let Ok(head) = self.repo.head() {
2543 if let Some(name) = head.shorthand() {
2544 return Ok(name.to_string());
2545 }
2546 }
2547
2548 Ok("main".to_string())
2550 }
2551
2552 fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
2554 match self.get_commits_between(main_branch, branch_name) {
2556 Ok(commits) => Ok(commits.is_empty()),
2557 Err(_) => {
2558 Ok(false)
2560 }
2561 }
2562 }
2563
2564 fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
2566 let remote_candidates = [
2568 format!("origin/{branch_name}"),
2569 format!("remotes/origin/{branch_name}"),
2570 ];
2571
2572 for candidate in &remote_candidates {
2573 if self
2574 .repo
2575 .find_reference(&format!(
2576 "refs/remotes/{}",
2577 candidate.replace("remotes/", "")
2578 ))
2579 .is_ok()
2580 {
2581 return Some(candidate.clone());
2582 }
2583 }
2584
2585 None
2586 }
2587
2588 fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
2590 let is_dirty = self.is_dirty()?;
2592 if !is_dirty {
2593 return Ok(None);
2595 }
2596
2597 let current_branch = self.get_current_branch().ok();
2599
2600 let modified_files = self.get_modified_files()?;
2602 let staged_files = self.get_staged_files()?;
2603 let untracked_files = self.get_untracked_files()?;
2604
2605 let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
2606
2607 if has_uncommitted_changes || !untracked_files.is_empty() {
2608 return Ok(Some(CheckoutSafety {
2609 has_uncommitted_changes,
2610 modified_files,
2611 staged_files,
2612 untracked_files,
2613 stash_created: None,
2614 current_branch,
2615 }));
2616 }
2617
2618 Ok(None)
2619 }
2620
2621 fn handle_checkout_confirmation(
2623 &self,
2624 target: &str,
2625 safety_info: &CheckoutSafety,
2626 ) -> Result<()> {
2627 let is_ci = std::env::var("CI").is_ok();
2629 let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
2630 let is_non_interactive = is_ci || no_confirm;
2631
2632 if is_non_interactive {
2633 return Err(CascadeError::branch(
2634 format!(
2635 "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
2636 )
2637 ));
2638 }
2639
2640 println!("\nCHECKOUT WARNING");
2642 println!("Attempting to checkout: {}", target);
2643 println!("You have uncommitted changes that could be lost:");
2644
2645 if !safety_info.modified_files.is_empty() {
2646 println!("\nModified files ({}):", safety_info.modified_files.len());
2647 for file in safety_info.modified_files.iter().take(10) {
2648 println!(" - {file}");
2649 }
2650 if safety_info.modified_files.len() > 10 {
2651 println!(" ... and {} more", safety_info.modified_files.len() - 10);
2652 }
2653 }
2654
2655 if !safety_info.staged_files.is_empty() {
2656 println!("\nStaged files ({}):", safety_info.staged_files.len());
2657 for file in safety_info.staged_files.iter().take(10) {
2658 println!(" - {file}");
2659 }
2660 if safety_info.staged_files.len() > 10 {
2661 println!(" ... and {} more", safety_info.staged_files.len() - 10);
2662 }
2663 }
2664
2665 if !safety_info.untracked_files.is_empty() {
2666 println!("\nUntracked files ({}):", safety_info.untracked_files.len());
2667 for file in safety_info.untracked_files.iter().take(5) {
2668 println!(" - {file}");
2669 }
2670 if safety_info.untracked_files.len() > 5 {
2671 println!(" ... and {} more", safety_info.untracked_files.len() - 5);
2672 }
2673 }
2674
2675 println!("\nOptions:");
2676 println!("1. Stash changes and checkout (recommended)");
2677 println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
2678 println!("3. Cancel checkout");
2679
2680 let selection = Select::with_theme(&ColorfulTheme::default())
2682 .with_prompt("Choose an action")
2683 .items(&[
2684 "Stash changes and checkout (recommended)",
2685 "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
2686 "Cancel checkout",
2687 ])
2688 .default(0)
2689 .interact()
2690 .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;
2691
2692 match selection {
2693 0 => {
2694 let stash_message = format!(
2696 "Auto-stash before checkout to {} at {}",
2697 target,
2698 chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
2699 );
2700
2701 match self.create_stash(&stash_message) {
2702 Ok(stash_id) => {
2703 crate::cli::output::Output::success(format!(
2704 "Created stash: {stash_message} ({stash_id})"
2705 ));
2706 crate::cli::output::Output::tip("You can restore with: git stash pop");
2707 }
2708 Err(e) => {
2709 crate::cli::output::Output::error(format!("Failed to create stash: {e}"));
2710
2711 use dialoguer::Select;
2713 let stash_failed_options = vec![
2714 "Commit staged changes and proceed",
2715 "Force checkout (WILL LOSE CHANGES)",
2716 "Cancel and handle manually",
2717 ];
2718
2719 let stash_selection = Select::with_theme(&ColorfulTheme::default())
2720 .with_prompt("Stash failed. What would you like to do?")
2721 .items(&stash_failed_options)
2722 .default(0)
2723 .interact()
2724 .map_err(|e| {
2725 CascadeError::branch(format!("Could not get user selection: {e}"))
2726 })?;
2727
2728 match stash_selection {
2729 0 => {
2730 let staged_files = self.get_staged_files()?;
2732 if !staged_files.is_empty() {
2733 println!(
2734 "📝 Committing {} staged files...",
2735 staged_files.len()
2736 );
2737 match self
2738 .commit_staged_changes("WIP: Auto-commit before checkout")
2739 {
2740 Ok(Some(commit_hash)) => {
2741 crate::cli::output::Output::success(format!(
2742 "Committed staged changes as {}",
2743 &commit_hash[..8]
2744 ));
2745 crate::cli::output::Output::tip(
2746 "You can undo with: git reset HEAD~1",
2747 );
2748 }
2749 Ok(None) => {
2750 crate::cli::output::Output::info(
2751 "No staged changes found to commit",
2752 );
2753 }
2754 Err(commit_err) => {
2755 println!(
2756 "❌ Failed to commit staged changes: {commit_err}"
2757 );
2758 return Err(CascadeError::branch(
2759 "Could not commit staged changes".to_string(),
2760 ));
2761 }
2762 }
2763 } else {
2764 println!("No staged changes to commit");
2765 }
2766 }
2767 1 => {
2768 Output::warning("Proceeding with force checkout - uncommitted changes will be lost!");
2770 }
2771 2 => {
2772 return Err(CascadeError::branch(
2774 "Checkout cancelled. Please handle changes manually and try again.".to_string(),
2775 ));
2776 }
2777 _ => unreachable!(),
2778 }
2779 }
2780 }
2781 }
2782 1 => {
2783 Output::warning(
2785 "Proceeding with force checkout - uncommitted changes will be lost!",
2786 );
2787 }
2788 2 => {
2789 return Err(CascadeError::branch(
2791 "Checkout cancelled by user".to_string(),
2792 ));
2793 }
2794 _ => unreachable!(),
2795 }
2796
2797 Ok(())
2798 }
2799
2800 fn create_stash(&self, message: &str) -> Result<String> {
2802 tracing::info!("Creating stash: {}", message);
2803
2804 let output = std::process::Command::new("git")
2806 .args(["stash", "push", "-m", message])
2807 .current_dir(&self.path)
2808 .output()
2809 .map_err(|e| {
2810 CascadeError::branch(format!("Failed to execute git stash command: {e}"))
2811 })?;
2812
2813 if output.status.success() {
2814 let stdout = String::from_utf8_lossy(&output.stdout);
2815
2816 let stash_id = if stdout.contains("Saved working directory") {
2818 let stash_list_output = std::process::Command::new("git")
2820 .args(["stash", "list", "-n", "1", "--format=%H"])
2821 .current_dir(&self.path)
2822 .output()
2823 .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;
2824
2825 if stash_list_output.status.success() {
2826 String::from_utf8_lossy(&stash_list_output.stdout)
2827 .trim()
2828 .to_string()
2829 } else {
2830 "stash@{0}".to_string() }
2832 } else {
2833 "stash@{0}".to_string() };
2835
2836 tracing::info!("✅ Created stash: {} ({})", message, stash_id);
2837 Ok(stash_id)
2838 } else {
2839 let stderr = String::from_utf8_lossy(&output.stderr);
2840 let stdout = String::from_utf8_lossy(&output.stdout);
2841
2842 if stderr.contains("No local changes to save")
2844 || stdout.contains("No local changes to save")
2845 {
2846 return Err(CascadeError::branch("No local changes to save".to_string()));
2847 }
2848
2849 Err(CascadeError::branch(format!(
2850 "Failed to create stash: {}\nStderr: {}\nStdout: {}",
2851 output.status, stderr, stdout
2852 )))
2853 }
2854 }
2855
2856 fn get_modified_files(&self) -> Result<Vec<String>> {
2858 let mut opts = git2::StatusOptions::new();
2859 opts.include_untracked(false).include_ignored(false);
2860
2861 let statuses = self
2862 .repo
2863 .statuses(Some(&mut opts))
2864 .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2865
2866 let mut modified_files = Vec::new();
2867 for status in statuses.iter() {
2868 let flags = status.status();
2869 if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
2870 {
2871 if let Some(path) = status.path() {
2872 modified_files.push(path.to_string());
2873 }
2874 }
2875 }
2876
2877 Ok(modified_files)
2878 }
2879
2880 pub fn get_staged_files(&self) -> Result<Vec<String>> {
2882 let mut opts = git2::StatusOptions::new();
2883 opts.include_untracked(false).include_ignored(false);
2884
2885 let statuses = self
2886 .repo
2887 .statuses(Some(&mut opts))
2888 .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2889
2890 let mut staged_files = Vec::new();
2891 for status in statuses.iter() {
2892 let flags = status.status();
2893 if flags.contains(git2::Status::INDEX_MODIFIED)
2894 || flags.contains(git2::Status::INDEX_NEW)
2895 || flags.contains(git2::Status::INDEX_DELETED)
2896 {
2897 if let Some(path) = status.path() {
2898 staged_files.push(path.to_string());
2899 }
2900 }
2901 }
2902
2903 Ok(staged_files)
2904 }
2905
2906 fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
2908 let commits = self.get_commits_between(from, to)?;
2909 Ok(commits.len())
2910 }
2911
2912 pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
2914 if let Ok(oid) = Oid::from_str(reference) {
2916 if let Ok(commit) = self.repo.find_commit(oid) {
2917 return Ok(commit);
2918 }
2919 }
2920
2921 let obj = self.repo.revparse_single(reference).map_err(|e| {
2923 CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
2924 })?;
2925
2926 obj.peel_to_commit().map_err(|e| {
2927 CascadeError::branch(format!(
2928 "Reference '{reference}' does not point to a commit: {e}"
2929 ))
2930 })
2931 }
2932
2933 pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
2935 let target_commit = self.resolve_reference(target_ref)?;
2936
2937 self.repo
2938 .reset(target_commit.as_object(), git2::ResetType::Soft, None)
2939 .map_err(CascadeError::Git)?;
2940
2941 Ok(())
2942 }
2943
2944 pub fn reset_to_head(&self) -> Result<()> {
2947 tracing::debug!("Resetting working directory and index to HEAD");
2948
2949 let head = self.repo.head().map_err(CascadeError::Git)?;
2950 let head_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
2951
2952 let mut checkout_builder = git2::build::CheckoutBuilder::new();
2954 checkout_builder.force(); checkout_builder.remove_untracked(false); self.repo
2958 .reset(
2959 head_commit.as_object(),
2960 git2::ResetType::Hard,
2961 Some(&mut checkout_builder),
2962 )
2963 .map_err(CascadeError::Git)?;
2964
2965 tracing::debug!("Successfully reset working directory to HEAD");
2966 Ok(())
2967 }
2968
2969 pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
2971 let oid = Oid::from_str(commit_hash).map_err(|e| {
2972 CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2973 })?;
2974
2975 let branches = self
2977 .repo
2978 .branches(Some(git2::BranchType::Local))
2979 .map_err(CascadeError::Git)?;
2980
2981 for branch_result in branches {
2982 let (branch, _) = branch_result.map_err(CascadeError::Git)?;
2983
2984 if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
2985 if let Ok(branch_head) = branch.get().peel_to_commit() {
2987 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2989 revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
2990
2991 for commit_oid in revwalk {
2992 let commit_oid = commit_oid.map_err(CascadeError::Git)?;
2993 if commit_oid == oid {
2994 return Ok(branch_name.to_string());
2995 }
2996 }
2997 }
2998 }
2999 }
3000
3001 Err(CascadeError::branch(format!(
3003 "Commit {commit_hash} not found in any local branch"
3004 )))
3005 }
3006
3007 pub async fn fetch_async(&self) -> Result<()> {
3011 let repo_path = self.path.clone();
3012 crate::utils::async_ops::run_git_operation(move || {
3013 let repo = GitRepository::open(&repo_path)?;
3014 repo.fetch()
3015 })
3016 .await
3017 }
3018
3019 pub async fn pull_async(&self, branch: &str) -> Result<()> {
3021 let repo_path = self.path.clone();
3022 let branch_name = branch.to_string();
3023 crate::utils::async_ops::run_git_operation(move || {
3024 let repo = GitRepository::open(&repo_path)?;
3025 repo.pull(&branch_name)
3026 })
3027 .await
3028 }
3029
3030 pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
3032 let repo_path = self.path.clone();
3033 let branch = branch_name.to_string();
3034 crate::utils::async_ops::run_git_operation(move || {
3035 let repo = GitRepository::open(&repo_path)?;
3036 repo.push(&branch)
3037 })
3038 .await
3039 }
3040
3041 pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
3043 let repo_path = self.path.clone();
3044 let hash = commit_hash.to_string();
3045 crate::utils::async_ops::run_git_operation(move || {
3046 let repo = GitRepository::open(&repo_path)?;
3047 repo.cherry_pick(&hash)
3048 })
3049 .await
3050 }
3051
3052 pub async fn get_commit_hashes_between_async(
3054 &self,
3055 from: &str,
3056 to: &str,
3057 ) -> Result<Vec<String>> {
3058 let repo_path = self.path.clone();
3059 let from_str = from.to_string();
3060 let to_str = to.to_string();
3061 crate::utils::async_ops::run_git_operation(move || {
3062 let repo = GitRepository::open(&repo_path)?;
3063 let commits = repo.get_commits_between(&from_str, &to_str)?;
3064 Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
3065 })
3066 .await
3067 }
3068
3069 pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
3071 info!(
3072 "Resetting branch '{}' to commit {}",
3073 branch_name,
3074 &commit_hash[..8]
3075 );
3076
3077 let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
3079 CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
3080 })?;
3081
3082 let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
3083 CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
3084 })?;
3085
3086 let _branch = self
3088 .repo
3089 .find_branch(branch_name, git2::BranchType::Local)
3090 .map_err(|e| {
3091 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
3092 })?;
3093
3094 let branch_ref_name = format!("refs/heads/{branch_name}");
3096 self.repo
3097 .reference(
3098 &branch_ref_name,
3099 target_oid,
3100 true,
3101 &format!("Reset {branch_name} to {commit_hash}"),
3102 )
3103 .map_err(|e| {
3104 CascadeError::branch(format!(
3105 "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
3106 ))
3107 })?;
3108
3109 tracing::info!(
3110 "Successfully reset branch '{}' to commit {}",
3111 branch_name,
3112 &commit_hash[..8]
3113 );
3114 Ok(())
3115 }
3116
3117 pub fn detect_parent_branch(&self) -> Result<Option<String>> {
3119 let current_branch = self.get_current_branch()?;
3120
3121 if let Ok(Some(upstream)) = self.get_upstream_branch(¤t_branch) {
3123 if let Some(branch_name) = upstream.split('/').nth(1) {
3125 if self.branch_exists(branch_name) {
3126 tracing::debug!(
3127 "Detected parent branch '{}' from upstream tracking",
3128 branch_name
3129 );
3130 return Ok(Some(branch_name.to_string()));
3131 }
3132 }
3133 }
3134
3135 if let Ok(default_branch) = self.detect_main_branch() {
3137 if current_branch != default_branch {
3139 tracing::debug!(
3140 "Detected parent branch '{}' as repository default",
3141 default_branch
3142 );
3143 return Ok(Some(default_branch));
3144 }
3145 }
3146
3147 if let Ok(branches) = self.list_branches() {
3150 let current_commit = self.get_head_commit()?;
3151 let current_commit_hash = current_commit.id().to_string();
3152 let current_oid = current_commit.id();
3153
3154 let mut best_candidate = None;
3155 let mut best_distance = usize::MAX;
3156
3157 for branch in branches {
3158 if branch == current_branch
3160 || branch.contains("-v")
3161 || branch.ends_with("-v2")
3162 || branch.ends_with("-v3")
3163 {
3164 continue;
3165 }
3166
3167 if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
3168 if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
3169 if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
3171 if let Ok(distance) = self.count_commits_between(
3173 &merge_base_oid.to_string(),
3174 ¤t_commit_hash,
3175 ) {
3176 let is_likely_base = self.is_likely_base_branch(&branch);
3179 let adjusted_distance = if is_likely_base {
3180 distance
3181 } else {
3182 distance + 1000
3183 };
3184
3185 if adjusted_distance < best_distance {
3186 best_distance = adjusted_distance;
3187 best_candidate = Some(branch.clone());
3188 }
3189 }
3190 }
3191 }
3192 }
3193 }
3194
3195 if let Some(ref candidate) = best_candidate {
3196 tracing::debug!(
3197 "Detected parent branch '{}' with distance {}",
3198 candidate,
3199 best_distance
3200 );
3201 }
3202
3203 return Ok(best_candidate);
3204 }
3205
3206 tracing::debug!("Could not detect parent branch for '{}'", current_branch);
3207 Ok(None)
3208 }
3209
3210 fn is_likely_base_branch(&self, branch_name: &str) -> bool {
3212 let base_patterns = [
3213 "main",
3214 "master",
3215 "develop",
3216 "dev",
3217 "development",
3218 "staging",
3219 "stage",
3220 "release",
3221 "production",
3222 "prod",
3223 ];
3224
3225 base_patterns.contains(&branch_name)
3226 }
3227}
3228
3229#[cfg(test)]
3230mod tests {
3231 use super::*;
3232 use std::process::Command;
3233 use tempfile::TempDir;
3234
3235 fn create_test_repo() -> (TempDir, PathBuf) {
3236 let temp_dir = TempDir::new().unwrap();
3237 let repo_path = temp_dir.path().to_path_buf();
3238
3239 Command::new("git")
3241 .args(["init"])
3242 .current_dir(&repo_path)
3243 .output()
3244 .unwrap();
3245 Command::new("git")
3246 .args(["config", "user.name", "Test"])
3247 .current_dir(&repo_path)
3248 .output()
3249 .unwrap();
3250 Command::new("git")
3251 .args(["config", "user.email", "test@test.com"])
3252 .current_dir(&repo_path)
3253 .output()
3254 .unwrap();
3255
3256 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
3258 Command::new("git")
3259 .args(["add", "."])
3260 .current_dir(&repo_path)
3261 .output()
3262 .unwrap();
3263 Command::new("git")
3264 .args(["commit", "-m", "Initial commit"])
3265 .current_dir(&repo_path)
3266 .output()
3267 .unwrap();
3268
3269 (temp_dir, repo_path)
3270 }
3271
3272 fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
3273 let file_path = repo_path.join(filename);
3274 std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
3275
3276 Command::new("git")
3277 .args(["add", filename])
3278 .current_dir(repo_path)
3279 .output()
3280 .unwrap();
3281 Command::new("git")
3282 .args(["commit", "-m", message])
3283 .current_dir(repo_path)
3284 .output()
3285 .unwrap();
3286 }
3287
3288 #[test]
3289 fn test_repository_info() {
3290 let (_temp_dir, repo_path) = create_test_repo();
3291 let repo = GitRepository::open(&repo_path).unwrap();
3292
3293 let info = repo.get_info().unwrap();
3294 assert!(!info.is_dirty); assert!(
3296 info.head_branch == Some("master".to_string())
3297 || info.head_branch == Some("main".to_string()),
3298 "Expected default branch to be 'master' or 'main', got {:?}",
3299 info.head_branch
3300 );
3301 assert!(info.head_commit.is_some()); assert!(info.untracked_files.is_empty()); }
3304
3305 #[test]
3306 fn test_force_push_branch_basic() {
3307 let (_temp_dir, repo_path) = create_test_repo();
3308 let repo = GitRepository::open(&repo_path).unwrap();
3309
3310 let default_branch = repo.get_current_branch().unwrap();
3312
3313 create_commit(&repo_path, "Feature commit 1", "feature1.rs");
3315 Command::new("git")
3316 .args(["checkout", "-b", "source-branch"])
3317 .current_dir(&repo_path)
3318 .output()
3319 .unwrap();
3320 create_commit(&repo_path, "Feature commit 2", "feature2.rs");
3321
3322 Command::new("git")
3324 .args(["checkout", &default_branch])
3325 .current_dir(&repo_path)
3326 .output()
3327 .unwrap();
3328 Command::new("git")
3329 .args(["checkout", "-b", "target-branch"])
3330 .current_dir(&repo_path)
3331 .output()
3332 .unwrap();
3333 create_commit(&repo_path, "Target commit", "target.rs");
3334
3335 let result = repo.force_push_branch("target-branch", "source-branch");
3337
3338 assert!(result.is_ok() || result.is_err()); }
3342
3343 #[test]
3344 fn test_force_push_branch_nonexistent_branches() {
3345 let (_temp_dir, repo_path) = create_test_repo();
3346 let repo = GitRepository::open(&repo_path).unwrap();
3347
3348 let default_branch = repo.get_current_branch().unwrap();
3350
3351 let result = repo.force_push_branch("target", "nonexistent-source");
3353 assert!(result.is_err());
3354
3355 let result = repo.force_push_branch("nonexistent-target", &default_branch);
3357 assert!(result.is_err());
3358 }
3359
3360 #[test]
3361 fn test_force_push_workflow_simulation() {
3362 let (_temp_dir, repo_path) = create_test_repo();
3363 let repo = GitRepository::open(&repo_path).unwrap();
3364
3365 Command::new("git")
3368 .args(["checkout", "-b", "feature-auth"])
3369 .current_dir(&repo_path)
3370 .output()
3371 .unwrap();
3372 create_commit(&repo_path, "Add authentication", "auth.rs");
3373
3374 Command::new("git")
3376 .args(["checkout", "-b", "feature-auth-v2"])
3377 .current_dir(&repo_path)
3378 .output()
3379 .unwrap();
3380 create_commit(&repo_path, "Fix auth validation", "auth.rs");
3381
3382 let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
3384
3385 match result {
3387 Ok(_) => {
3388 Command::new("git")
3390 .args(["checkout", "feature-auth"])
3391 .current_dir(&repo_path)
3392 .output()
3393 .unwrap();
3394 let log_output = Command::new("git")
3395 .args(["log", "--oneline", "-2"])
3396 .current_dir(&repo_path)
3397 .output()
3398 .unwrap();
3399 let log_str = String::from_utf8_lossy(&log_output.stdout);
3400 assert!(
3401 log_str.contains("Fix auth validation")
3402 || log_str.contains("Add authentication")
3403 );
3404 }
3405 Err(_) => {
3406 }
3409 }
3410 }
3411
3412 #[test]
3413 fn test_branch_operations() {
3414 let (_temp_dir, repo_path) = create_test_repo();
3415 let repo = GitRepository::open(&repo_path).unwrap();
3416
3417 let current = repo.get_current_branch().unwrap();
3419 assert!(
3420 current == "master" || current == "main",
3421 "Expected default branch to be 'master' or 'main', got '{current}'"
3422 );
3423
3424 Command::new("git")
3426 .args(["checkout", "-b", "test-branch"])
3427 .current_dir(&repo_path)
3428 .output()
3429 .unwrap();
3430 let current = repo.get_current_branch().unwrap();
3431 assert_eq!(current, "test-branch");
3432 }
3433
3434 #[test]
3435 fn test_commit_operations() {
3436 let (_temp_dir, repo_path) = create_test_repo();
3437 let repo = GitRepository::open(&repo_path).unwrap();
3438
3439 let head = repo.get_head_commit().unwrap();
3441 assert_eq!(head.message().unwrap().trim(), "Initial commit");
3442
3443 let hash = head.id().to_string();
3445 let same_commit = repo.get_commit(&hash).unwrap();
3446 assert_eq!(head.id(), same_commit.id());
3447 }
3448
3449 #[test]
3450 fn test_checkout_safety_clean_repo() {
3451 let (_temp_dir, repo_path) = create_test_repo();
3452 let repo = GitRepository::open(&repo_path).unwrap();
3453
3454 create_commit(&repo_path, "Second commit", "test.txt");
3456 Command::new("git")
3457 .args(["checkout", "-b", "test-branch"])
3458 .current_dir(&repo_path)
3459 .output()
3460 .unwrap();
3461
3462 let safety_result = repo.check_checkout_safety("main");
3464 assert!(safety_result.is_ok());
3465 assert!(safety_result.unwrap().is_none()); }
3467
3468 #[test]
3469 fn test_checkout_safety_with_modified_files() {
3470 let (_temp_dir, repo_path) = create_test_repo();
3471 let repo = GitRepository::open(&repo_path).unwrap();
3472
3473 Command::new("git")
3475 .args(["checkout", "-b", "test-branch"])
3476 .current_dir(&repo_path)
3477 .output()
3478 .unwrap();
3479
3480 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3482
3483 let safety_result = repo.check_checkout_safety("main");
3485 assert!(safety_result.is_ok());
3486 let safety_info = safety_result.unwrap();
3487 assert!(safety_info.is_some());
3488
3489 let info = safety_info.unwrap();
3490 assert!(!info.modified_files.is_empty());
3491 assert!(info.modified_files.contains(&"README.md".to_string()));
3492 }
3493
3494 #[test]
3495 fn test_unsafe_checkout_methods() {
3496 let (_temp_dir, repo_path) = create_test_repo();
3497 let repo = GitRepository::open(&repo_path).unwrap();
3498
3499 create_commit(&repo_path, "Second commit", "test.txt");
3501 Command::new("git")
3502 .args(["checkout", "-b", "test-branch"])
3503 .current_dir(&repo_path)
3504 .output()
3505 .unwrap();
3506
3507 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3509
3510 let _result = repo.checkout_branch_unsafe("main");
3512 let head_commit = repo.get_head_commit().unwrap();
3517 let commit_hash = head_commit.id().to_string();
3518 let _result = repo.checkout_commit_unsafe(&commit_hash);
3519 }
3521
3522 #[test]
3523 fn test_get_modified_files() {
3524 let (_temp_dir, repo_path) = create_test_repo();
3525 let repo = GitRepository::open(&repo_path).unwrap();
3526
3527 let modified = repo.get_modified_files().unwrap();
3529 assert!(modified.is_empty());
3530
3531 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3533
3534 let modified = repo.get_modified_files().unwrap();
3536 assert_eq!(modified.len(), 1);
3537 assert!(modified.contains(&"README.md".to_string()));
3538 }
3539
3540 #[test]
3541 fn test_get_staged_files() {
3542 let (_temp_dir, repo_path) = create_test_repo();
3543 let repo = GitRepository::open(&repo_path).unwrap();
3544
3545 let staged = repo.get_staged_files().unwrap();
3547 assert!(staged.is_empty());
3548
3549 std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3551 Command::new("git")
3552 .args(["add", "staged.txt"])
3553 .current_dir(&repo_path)
3554 .output()
3555 .unwrap();
3556
3557 let staged = repo.get_staged_files().unwrap();
3559 assert_eq!(staged.len(), 1);
3560 assert!(staged.contains(&"staged.txt".to_string()));
3561 }
3562
3563 #[test]
3564 fn test_create_stash_fallback() {
3565 let (_temp_dir, repo_path) = create_test_repo();
3566 let repo = GitRepository::open(&repo_path).unwrap();
3567
3568 let result = repo.create_stash("test stash");
3570
3571 match result {
3573 Ok(stash_id) => {
3574 assert!(!stash_id.is_empty());
3576 assert!(stash_id.contains("stash") || stash_id.len() >= 7); }
3578 Err(error) => {
3579 let error_msg = error.to_string();
3581 assert!(
3582 error_msg.contains("No local changes to save")
3583 || error_msg.contains("git stash push")
3584 );
3585 }
3586 }
3587 }
3588
3589 #[test]
3590 fn test_delete_branch_unsafe() {
3591 let (_temp_dir, repo_path) = create_test_repo();
3592 let repo = GitRepository::open(&repo_path).unwrap();
3593
3594 create_commit(&repo_path, "Second commit", "test.txt");
3596 Command::new("git")
3597 .args(["checkout", "-b", "test-branch"])
3598 .current_dir(&repo_path)
3599 .output()
3600 .unwrap();
3601
3602 create_commit(&repo_path, "Branch-specific commit", "branch.txt");
3604
3605 Command::new("git")
3607 .args(["checkout", "main"])
3608 .current_dir(&repo_path)
3609 .output()
3610 .unwrap();
3611
3612 let result = repo.delete_branch_unsafe("test-branch");
3615 let _ = result; }
3619
3620 #[test]
3621 fn test_force_push_unsafe() {
3622 let (_temp_dir, repo_path) = create_test_repo();
3623 let repo = GitRepository::open(&repo_path).unwrap();
3624
3625 create_commit(&repo_path, "Second commit", "test.txt");
3627 Command::new("git")
3628 .args(["checkout", "-b", "test-branch"])
3629 .current_dir(&repo_path)
3630 .output()
3631 .unwrap();
3632
3633 let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
3636 }
3638
3639 #[test]
3640 fn test_cherry_pick_basic() {
3641 let (_temp_dir, repo_path) = create_test_repo();
3642 let repo = GitRepository::open(&repo_path).unwrap();
3643
3644 repo.create_branch("source", None).unwrap();
3646 repo.checkout_branch("source").unwrap();
3647
3648 std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
3649 Command::new("git")
3650 .args(["add", "."])
3651 .current_dir(&repo_path)
3652 .output()
3653 .unwrap();
3654
3655 Command::new("git")
3656 .args(["commit", "-m", "Cherry commit"])
3657 .current_dir(&repo_path)
3658 .output()
3659 .unwrap();
3660
3661 let cherry_commit = repo.get_head_commit_hash().unwrap();
3662
3663 Command::new("git")
3666 .args(["checkout", "-"])
3667 .current_dir(&repo_path)
3668 .output()
3669 .unwrap();
3670
3671 repo.create_branch("target", None).unwrap();
3672 repo.checkout_branch("target").unwrap();
3673
3674 let new_commit = repo.cherry_pick(&cherry_commit).unwrap();
3676
3677 repo.repo
3679 .find_commit(git2::Oid::from_str(&new_commit).unwrap())
3680 .unwrap();
3681
3682 assert!(
3684 repo_path.join("cherry.txt").exists(),
3685 "Cherry-picked file should exist"
3686 );
3687
3688 repo.checkout_branch("source").unwrap();
3690 let source_head = repo.get_head_commit_hash().unwrap();
3691 assert_eq!(
3692 source_head, cherry_commit,
3693 "Source branch should be unchanged"
3694 );
3695 }
3696
3697 #[test]
3698 fn test_cherry_pick_preserves_commit_message() {
3699 let (_temp_dir, repo_path) = create_test_repo();
3700 let repo = GitRepository::open(&repo_path).unwrap();
3701
3702 repo.create_branch("msg-test", None).unwrap();
3704 repo.checkout_branch("msg-test").unwrap();
3705
3706 std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
3707 Command::new("git")
3708 .args(["add", "."])
3709 .current_dir(&repo_path)
3710 .output()
3711 .unwrap();
3712
3713 let commit_msg = "Test: Special commit message\n\nWith body";
3714 Command::new("git")
3715 .args(["commit", "-m", commit_msg])
3716 .current_dir(&repo_path)
3717 .output()
3718 .unwrap();
3719
3720 let original_commit = repo.get_head_commit_hash().unwrap();
3721
3722 Command::new("git")
3724 .args(["checkout", "-"])
3725 .current_dir(&repo_path)
3726 .output()
3727 .unwrap();
3728 let new_commit = repo.cherry_pick(&original_commit).unwrap();
3729
3730 let output = Command::new("git")
3732 .args(["log", "-1", "--format=%B", &new_commit])
3733 .current_dir(&repo_path)
3734 .output()
3735 .unwrap();
3736
3737 let new_msg = String::from_utf8_lossy(&output.stdout);
3738 assert!(
3739 new_msg.contains("Special commit message"),
3740 "Should preserve commit message"
3741 );
3742 }
3743
3744 #[test]
3745 fn test_cherry_pick_handles_conflicts() {
3746 let (_temp_dir, repo_path) = create_test_repo();
3747 let repo = GitRepository::open(&repo_path).unwrap();
3748
3749 std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
3751 Command::new("git")
3752 .args(["add", "."])
3753 .current_dir(&repo_path)
3754 .output()
3755 .unwrap();
3756
3757 Command::new("git")
3758 .args(["commit", "-m", "Add conflict file"])
3759 .current_dir(&repo_path)
3760 .output()
3761 .unwrap();
3762
3763 repo.create_branch("conflict-branch", None).unwrap();
3765 repo.checkout_branch("conflict-branch").unwrap();
3766
3767 std::fs::write(repo_path.join("conflict.txt"), "Modified").unwrap();
3768 Command::new("git")
3769 .args(["add", "."])
3770 .current_dir(&repo_path)
3771 .output()
3772 .unwrap();
3773
3774 Command::new("git")
3775 .args(["commit", "-m", "Modify conflict file"])
3776 .current_dir(&repo_path)
3777 .output()
3778 .unwrap();
3779
3780 let conflict_commit = repo.get_head_commit_hash().unwrap();
3781
3782 Command::new("git")
3785 .args(["checkout", "-"])
3786 .current_dir(&repo_path)
3787 .output()
3788 .unwrap();
3789 std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
3790 Command::new("git")
3791 .args(["add", "."])
3792 .current_dir(&repo_path)
3793 .output()
3794 .unwrap();
3795
3796 Command::new("git")
3797 .args(["commit", "-m", "Different change"])
3798 .current_dir(&repo_path)
3799 .output()
3800 .unwrap();
3801
3802 let result = repo.cherry_pick(&conflict_commit);
3804 assert!(result.is_err(), "Cherry-pick with conflict should fail");
3805 }
3806
3807 #[test]
3808 fn test_reset_to_head_clears_staged_files() {
3809 let (_temp_dir, repo_path) = create_test_repo();
3810 let repo = GitRepository::open(&repo_path).unwrap();
3811
3812 std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
3814 std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();
3815
3816 Command::new("git")
3817 .args(["add", "staged1.txt", "staged2.txt"])
3818 .current_dir(&repo_path)
3819 .output()
3820 .unwrap();
3821
3822 let staged_before = repo.get_staged_files().unwrap();
3824 assert_eq!(staged_before.len(), 2, "Should have 2 staged files");
3825
3826 repo.reset_to_head().unwrap();
3828
3829 let staged_after = repo.get_staged_files().unwrap();
3831 assert_eq!(
3832 staged_after.len(),
3833 0,
3834 "Should have no staged files after reset"
3835 );
3836 }
3837
3838 #[test]
3839 fn test_reset_to_head_clears_modified_files() {
3840 let (_temp_dir, repo_path) = create_test_repo();
3841 let repo = GitRepository::open(&repo_path).unwrap();
3842
3843 std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();
3845
3846 Command::new("git")
3848 .args(["add", "README.md"])
3849 .current_dir(&repo_path)
3850 .output()
3851 .unwrap();
3852
3853 assert!(repo.is_dirty().unwrap(), "Repo should be dirty");
3855
3856 repo.reset_to_head().unwrap();
3858
3859 assert!(
3861 !repo.is_dirty().unwrap(),
3862 "Repo should be clean after reset"
3863 );
3864
3865 let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
3867 assert_eq!(
3868 content, "# Test",
3869 "File should be restored to original content"
3870 );
3871 }
3872
3873 #[test]
3874 fn test_reset_to_head_preserves_untracked_files() {
3875 let (_temp_dir, repo_path) = create_test_repo();
3876 let repo = GitRepository::open(&repo_path).unwrap();
3877
3878 std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();
3880
3881 std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3883 Command::new("git")
3884 .args(["add", "staged.txt"])
3885 .current_dir(&repo_path)
3886 .output()
3887 .unwrap();
3888
3889 repo.reset_to_head().unwrap();
3891
3892 assert!(
3894 repo_path.join("untracked.txt").exists(),
3895 "Untracked file should be preserved"
3896 );
3897
3898 assert!(
3900 !repo_path.join("staged.txt").exists(),
3901 "Staged but uncommitted file should be removed"
3902 );
3903 }
3904
3905 #[test]
3906 fn test_cherry_pick_does_not_modify_source() {
3907 let (_temp_dir, repo_path) = create_test_repo();
3908 let repo = GitRepository::open(&repo_path).unwrap();
3909
3910 repo.create_branch("feature", None).unwrap();
3912 repo.checkout_branch("feature").unwrap();
3913
3914 for i in 1..=3 {
3916 std::fs::write(
3917 repo_path.join(format!("file{i}.txt")),
3918 format!("Content {i}"),
3919 )
3920 .unwrap();
3921 Command::new("git")
3922 .args(["add", "."])
3923 .current_dir(&repo_path)
3924 .output()
3925 .unwrap();
3926
3927 Command::new("git")
3928 .args(["commit", "-m", &format!("Commit {i}")])
3929 .current_dir(&repo_path)
3930 .output()
3931 .unwrap();
3932 }
3933
3934 let source_commits = Command::new("git")
3936 .args(["log", "--format=%H", "feature"])
3937 .current_dir(&repo_path)
3938 .output()
3939 .unwrap();
3940 let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();
3941
3942 let commits: Vec<&str> = source_state.lines().collect();
3944 let middle_commit = commits[1];
3945
3946 Command::new("git")
3948 .args(["checkout", "-"])
3949 .current_dir(&repo_path)
3950 .output()
3951 .unwrap();
3952 repo.create_branch("target", None).unwrap();
3953 repo.checkout_branch("target").unwrap();
3954
3955 repo.cherry_pick(middle_commit).unwrap();
3956
3957 let after_commits = Command::new("git")
3959 .args(["log", "--format=%H", "feature"])
3960 .current_dir(&repo_path)
3961 .output()
3962 .unwrap();
3963 let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();
3964
3965 assert_eq!(
3966 source_state, after_state,
3967 "Source branch should be completely unchanged after cherry-pick"
3968 );
3969 }
3970
3971 #[test]
3972 fn test_detect_parent_branch() {
3973 let (_temp_dir, repo_path) = create_test_repo();
3974 let repo = GitRepository::open(&repo_path).unwrap();
3975
3976 repo.create_branch("dev123", None).unwrap();
3978 repo.checkout_branch("dev123").unwrap();
3979 create_commit(&repo_path, "Base commit on dev123", "base.txt");
3980
3981 repo.create_branch("feature-branch", None).unwrap();
3983 repo.checkout_branch("feature-branch").unwrap();
3984 create_commit(&repo_path, "Feature commit", "feature.txt");
3985
3986 let detected_parent = repo.detect_parent_branch().unwrap();
3988
3989 assert!(detected_parent.is_some(), "Should detect a parent branch");
3992
3993 let parent = detected_parent.unwrap();
3996 assert!(
3997 parent == "dev123" || parent == "main" || parent == "master",
3998 "Parent should be dev123, main, or master, got: {parent}"
3999 );
4000 }
4001}