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 let Err(e) = self.fetch() {
350 tracing::warn!("Could not fetch before force push: {}", e);
351 }
352
353 let safety_result = if auto_confirm {
355 self.check_force_push_safety_auto(branch_name)?
356 } else {
357 self.check_force_push_safety_enhanced(branch_name)?
358 };
359
360 if let Some(backup_info) = safety_result {
361 self.create_backup_branch(branch_name, &backup_info.remote_commit_id)?;
362 }
363
364 let output = std::process::Command::new("git")
366 .args(["push", "--force", "origin", branch_name])
367 .current_dir(&self.path)
368 .output()
369 .map_err(|e| CascadeError::branch(format!("Failed to execute git push: {}", e)))?;
370
371 if !output.status.success() {
372 let stderr = String::from_utf8_lossy(&output.stderr);
373 return Err(CascadeError::branch(format!(
374 "Force push failed for '{}': {}",
375 branch_name, stderr
376 )));
377 }
378
379 Ok(())
380 }
381
382 pub fn checkout_branch(&self, name: &str) -> Result<()> {
384 self.checkout_branch_with_options(name, false, true)
385 }
386
387 pub fn checkout_branch_silent(&self, name: &str) -> Result<()> {
389 self.checkout_branch_with_options(name, false, false)
390 }
391
392 pub fn checkout_branch_unsafe(&self, name: &str) -> Result<()> {
394 self.checkout_branch_with_options(name, true, true)
395 }
396
397 fn checkout_branch_with_options(
399 &self,
400 name: &str,
401 force_unsafe: bool,
402 show_output: bool,
403 ) -> Result<()> {
404 debug!("Attempting to checkout branch: {}", name);
405
406 if !force_unsafe {
408 let safety_result = self.check_checkout_safety(name)?;
409 if let Some(safety_info) = safety_result {
410 self.handle_checkout_confirmation(name, &safety_info)?;
412 }
413 }
414
415 let branch = self
417 .repo
418 .find_branch(name, git2::BranchType::Local)
419 .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
420
421 let branch_ref = branch.get();
422 let tree = branch_ref.peel_to_tree().map_err(|e| {
423 CascadeError::branch(format!("Could not get tree for branch '{name}': {e}"))
424 })?;
425
426 self.repo
428 .checkout_tree(tree.as_object(), None)
429 .map_err(|e| {
430 CascadeError::branch(format!("Could not checkout branch '{name}': {e}"))
431 })?;
432
433 self.repo
435 .set_head(&format!("refs/heads/{name}"))
436 .map_err(|e| CascadeError::branch(format!("Could not update HEAD to '{name}': {e}")))?;
437
438 if show_output {
439 Output::success(format!("Switched to branch '{name}'"));
440 }
441 Ok(())
442 }
443
444 pub fn checkout_commit(&self, commit_hash: &str) -> Result<()> {
446 self.checkout_commit_with_options(commit_hash, false)
447 }
448
449 pub fn checkout_commit_unsafe(&self, commit_hash: &str) -> Result<()> {
451 self.checkout_commit_with_options(commit_hash, true)
452 }
453
454 fn checkout_commit_with_options(&self, commit_hash: &str, force_unsafe: bool) -> Result<()> {
456 debug!("Attempting to checkout commit: {}", commit_hash);
457
458 if !force_unsafe {
460 let safety_result = self.check_checkout_safety(&format!("commit:{commit_hash}"))?;
461 if let Some(safety_info) = safety_result {
462 self.handle_checkout_confirmation(&format!("commit {commit_hash}"), &safety_info)?;
464 }
465 }
466
467 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
468
469 let commit = self.repo.find_commit(oid).map_err(|e| {
470 CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
471 })?;
472
473 let tree = commit.tree().map_err(|e| {
474 CascadeError::branch(format!(
475 "Could not get tree for commit '{commit_hash}': {e}"
476 ))
477 })?;
478
479 self.repo
481 .checkout_tree(tree.as_object(), None)
482 .map_err(|e| {
483 CascadeError::branch(format!("Could not checkout commit '{commit_hash}': {e}"))
484 })?;
485
486 self.repo.set_head_detached(oid).map_err(|e| {
488 CascadeError::branch(format!(
489 "Could not update HEAD to commit '{commit_hash}': {e}"
490 ))
491 })?;
492
493 Output::success(format!(
494 "Checked out commit '{commit_hash}' (detached HEAD)"
495 ));
496 Ok(())
497 }
498
499 pub fn branch_exists(&self, name: &str) -> bool {
501 self.repo.find_branch(name, git2::BranchType::Local).is_ok()
502 }
503
504 pub fn branch_exists_or_fetch(&self, name: &str) -> Result<bool> {
506 if self.repo.find_branch(name, git2::BranchType::Local).is_ok() {
508 return Ok(true);
509 }
510
511 println!("🔍 Branch '{name}' not found locally, trying to fetch from remote...");
513
514 use std::process::Command;
515
516 let fetch_result = Command::new("git")
518 .args(["fetch", "origin", &format!("{name}:{name}")])
519 .current_dir(&self.path)
520 .output();
521
522 match fetch_result {
523 Ok(output) => {
524 if output.status.success() {
525 println!("✅ Successfully fetched '{name}' from origin");
526 return Ok(self.repo.find_branch(name, git2::BranchType::Local).is_ok());
528 } else {
529 let stderr = String::from_utf8_lossy(&output.stderr);
530 tracing::debug!("Failed to fetch branch '{name}': {stderr}");
531 }
532 }
533 Err(e) => {
534 tracing::debug!("Git fetch command failed: {e}");
535 }
536 }
537
538 if name.contains('/') {
540 println!("🔍 Trying alternative fetch patterns...");
541
542 let fetch_all_result = Command::new("git")
544 .args(["fetch", "origin"])
545 .current_dir(&self.path)
546 .output();
547
548 if let Ok(output) = fetch_all_result {
549 if output.status.success() {
550 let checkout_result = Command::new("git")
552 .args(["checkout", "-b", name, &format!("origin/{name}")])
553 .current_dir(&self.path)
554 .output();
555
556 if let Ok(checkout_output) = checkout_result {
557 if checkout_output.status.success() {
558 println!(
559 "✅ Successfully created local branch '{name}' from origin/{name}"
560 );
561 return Ok(true);
562 }
563 }
564 }
565 }
566 }
567
568 Ok(false)
570 }
571
572 pub fn get_branch_commit_hash(&self, branch_name: &str) -> Result<String> {
574 let branch = self
575 .repo
576 .find_branch(branch_name, git2::BranchType::Local)
577 .map_err(|e| {
578 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
579 })?;
580
581 let commit = branch.get().peel_to_commit().map_err(|e| {
582 CascadeError::branch(format!(
583 "Could not get commit for branch '{branch_name}': {e}"
584 ))
585 })?;
586
587 Ok(commit.id().to_string())
588 }
589
590 pub fn list_branches(&self) -> Result<Vec<String>> {
592 let branches = self
593 .repo
594 .branches(Some(git2::BranchType::Local))
595 .map_err(CascadeError::Git)?;
596
597 let mut branch_names = Vec::new();
598 for branch in branches {
599 let (branch, _) = branch.map_err(CascadeError::Git)?;
600 if let Some(name) = branch.name().map_err(CascadeError::Git)? {
601 branch_names.push(name.to_string());
602 }
603 }
604
605 Ok(branch_names)
606 }
607
608 pub fn get_upstream_branch(&self, branch_name: &str) -> Result<Option<String>> {
610 let config = self.repo.config().map_err(CascadeError::Git)?;
612
613 let remote_key = format!("branch.{branch_name}.remote");
615 let merge_key = format!("branch.{branch_name}.merge");
616
617 if let (Ok(remote), Ok(merge_ref)) = (
618 config.get_string(&remote_key),
619 config.get_string(&merge_key),
620 ) {
621 if let Some(branch_part) = merge_ref.strip_prefix("refs/heads/") {
623 return Ok(Some(format!("{remote}/{branch_part}")));
624 }
625 }
626
627 let potential_upstream = format!("origin/{branch_name}");
629 if self
630 .repo
631 .find_reference(&format!("refs/remotes/{potential_upstream}"))
632 .is_ok()
633 {
634 return Ok(Some(potential_upstream));
635 }
636
637 Ok(None)
638 }
639
640 pub fn get_ahead_behind_counts(
642 &self,
643 local_branch: &str,
644 upstream_branch: &str,
645 ) -> Result<(usize, usize)> {
646 let local_ref = self
648 .repo
649 .find_reference(&format!("refs/heads/{local_branch}"))
650 .map_err(|_| {
651 CascadeError::config(format!("Local branch '{local_branch}' not found"))
652 })?;
653 let local_commit = local_ref.peel_to_commit().map_err(CascadeError::Git)?;
654
655 let upstream_ref = self
656 .repo
657 .find_reference(&format!("refs/remotes/{upstream_branch}"))
658 .map_err(|_| {
659 CascadeError::config(format!("Upstream branch '{upstream_branch}' not found"))
660 })?;
661 let upstream_commit = upstream_ref.peel_to_commit().map_err(CascadeError::Git)?;
662
663 let (ahead, behind) = self
665 .repo
666 .graph_ahead_behind(local_commit.id(), upstream_commit.id())
667 .map_err(CascadeError::Git)?;
668
669 Ok((ahead, behind))
670 }
671
672 pub fn set_upstream(&self, branch_name: &str, remote: &str, remote_branch: &str) -> Result<()> {
674 let mut config = self.repo.config().map_err(CascadeError::Git)?;
675
676 let remote_key = format!("branch.{branch_name}.remote");
678 config
679 .set_str(&remote_key, remote)
680 .map_err(CascadeError::Git)?;
681
682 let merge_key = format!("branch.{branch_name}.merge");
684 let merge_value = format!("refs/heads/{remote_branch}");
685 config
686 .set_str(&merge_key, &merge_value)
687 .map_err(CascadeError::Git)?;
688
689 Ok(())
690 }
691
692 pub fn commit(&self, message: &str) -> Result<String> {
694 self.validate_git_user_config()?;
696
697 let signature = self.get_signature()?;
698 let tree_id = self.get_index_tree()?;
699 let tree = self.repo.find_tree(tree_id).map_err(CascadeError::Git)?;
700
701 let head = self.repo.head().map_err(CascadeError::Git)?;
703 let parent_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
704
705 let commit_id = self
706 .repo
707 .commit(
708 Some("HEAD"),
709 &signature,
710 &signature,
711 message,
712 &tree,
713 &[&parent_commit],
714 )
715 .map_err(CascadeError::Git)?;
716
717 Output::success(format!("Created commit: {commit_id} - {message}"));
718 Ok(commit_id.to_string())
719 }
720
721 pub fn commit_staged_changes(&self, default_message: &str) -> Result<Option<String>> {
723 let staged_files = self.get_staged_files()?;
725 if staged_files.is_empty() {
726 tracing::debug!("No staged changes to commit");
727 return Ok(None);
728 }
729
730 tracing::info!("Committing {} staged files", staged_files.len());
731 let commit_hash = self.commit(default_message)?;
732 Ok(Some(commit_hash))
733 }
734
735 pub fn stage_all(&self) -> Result<()> {
737 let mut index = self.repo.index().map_err(CascadeError::Git)?;
738
739 index
740 .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
741 .map_err(CascadeError::Git)?;
742
743 index.write().map_err(CascadeError::Git)?;
744
745 tracing::debug!("Staged all changes");
746 Ok(())
747 }
748
749 pub fn stage_files(&self, file_paths: &[&str]) -> Result<()> {
751 if file_paths.is_empty() {
752 tracing::debug!("No files to stage");
753 return Ok(());
754 }
755
756 let mut index = self.repo.index().map_err(CascadeError::Git)?;
757
758 for file_path in file_paths {
759 index
760 .add_path(std::path::Path::new(file_path))
761 .map_err(CascadeError::Git)?;
762 }
763
764 index.write().map_err(CascadeError::Git)?;
765
766 tracing::debug!(
767 "Staged {} specific files: {:?}",
768 file_paths.len(),
769 file_paths
770 );
771 Ok(())
772 }
773
774 pub fn stage_conflict_resolved_files(&self) -> Result<()> {
776 let conflicted_files = self.get_conflicted_files()?;
777 if conflicted_files.is_empty() {
778 tracing::debug!("No conflicted files to stage");
779 return Ok(());
780 }
781
782 let file_paths: Vec<&str> = conflicted_files.iter().map(|s| s.as_str()).collect();
783 self.stage_files(&file_paths)?;
784
785 tracing::debug!("Staged {} conflict-resolved files", conflicted_files.len());
786 Ok(())
787 }
788
789 pub fn path(&self) -> &Path {
791 &self.path
792 }
793
794 pub fn commit_exists(&self, commit_hash: &str) -> Result<bool> {
796 match Oid::from_str(commit_hash) {
797 Ok(oid) => match self.repo.find_commit(oid) {
798 Ok(_) => Ok(true),
799 Err(_) => Ok(false),
800 },
801 Err(_) => Ok(false),
802 }
803 }
804
805 pub fn get_head_commit(&self) -> Result<git2::Commit<'_>> {
807 let head = self
808 .repo
809 .head()
810 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
811 head.peel_to_commit()
812 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))
813 }
814
815 pub fn get_commit(&self, commit_hash: &str) -> Result<git2::Commit<'_>> {
817 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
818
819 self.repo.find_commit(oid).map_err(CascadeError::Git)
820 }
821
822 pub fn get_branch_head(&self, branch_name: &str) -> Result<String> {
824 let branch = self
825 .repo
826 .find_branch(branch_name, git2::BranchType::Local)
827 .map_err(|e| {
828 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
829 })?;
830
831 let commit = branch.get().peel_to_commit().map_err(|e| {
832 CascadeError::branch(format!(
833 "Could not get commit for branch '{branch_name}': {e}"
834 ))
835 })?;
836
837 Ok(commit.id().to_string())
838 }
839
840 pub fn validate_git_user_config(&self) -> Result<()> {
842 if let Ok(config) = self.repo.config() {
843 let name_result = config.get_string("user.name");
844 let email_result = config.get_string("user.email");
845
846 if let (Ok(name), Ok(email)) = (name_result, email_result) {
847 if !name.trim().is_empty() && !email.trim().is_empty() {
848 tracing::debug!("Git user config validated: {} <{}>", name, email);
849 return Ok(());
850 }
851 }
852 }
853
854 let is_ci = std::env::var("CI").is_ok();
856
857 if is_ci {
858 tracing::debug!("CI environment - skipping git user config validation");
859 return Ok(());
860 }
861
862 Output::warning("Git user configuration missing or incomplete");
863 Output::info("This can cause cherry-pick and commit operations to fail");
864 Output::info("Please configure git user information:");
865 Output::bullet("git config user.name \"Your Name\"".to_string());
866 Output::bullet("git config user.email \"your.email@example.com\"".to_string());
867 Output::info("Or set globally with the --global flag");
868
869 Ok(())
872 }
873
874 fn get_signature(&self) -> Result<Signature<'_>> {
876 if let Ok(config) = self.repo.config() {
878 let name_result = config.get_string("user.name");
880 let email_result = config.get_string("user.email");
881
882 if let (Ok(name), Ok(email)) = (name_result, email_result) {
883 if !name.trim().is_empty() && !email.trim().is_empty() {
884 tracing::debug!("Using git config: {} <{}>", name, email);
885 return Signature::now(&name, &email).map_err(CascadeError::Git);
886 }
887 } else {
888 tracing::debug!("Git user config incomplete or missing");
889 }
890 }
891
892 let is_ci = std::env::var("CI").is_ok();
894
895 if is_ci {
896 tracing::debug!("CI environment detected, using fallback signature");
897 return Signature::now("Cascade CLI", "cascade@example.com").map_err(CascadeError::Git);
898 }
899
900 tracing::warn!("Git user configuration missing - this can cause commit operations to fail");
902
903 match Signature::now("Cascade CLI", "cascade@example.com") {
905 Ok(sig) => {
906 Output::warning("Git user not configured - using fallback signature");
907 Output::info("For better git history, run:");
908 Output::bullet("git config user.name \"Your Name\"".to_string());
909 Output::bullet("git config user.email \"your.email@example.com\"".to_string());
910 Output::info("Or set it globally with --global flag");
911 Ok(sig)
912 }
913 Err(e) => {
914 Err(CascadeError::branch(format!(
915 "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\""
916 )))
917 }
918 }
919 }
920
921 fn configure_remote_callbacks(&self) -> Result<git2::RemoteCallbacks<'_>> {
924 self.configure_remote_callbacks_with_fallback(false)
925 }
926
927 fn should_retry_with_default_credentials(&self, error: &git2::Error) -> bool {
929 match error.class() {
930 git2::ErrorClass::Http => {
932 match error.code() {
934 git2::ErrorCode::Auth => true,
935 _ => {
936 let error_string = error.to_string();
938 error_string.contains("too many redirects")
939 || error_string.contains("authentication replays")
940 || error_string.contains("authentication required")
941 }
942 }
943 }
944 git2::ErrorClass::Net => {
945 let error_string = error.to_string();
947 error_string.contains("authentication")
948 || error_string.contains("unauthorized")
949 || error_string.contains("forbidden")
950 }
951 _ => false,
952 }
953 }
954
955 fn should_fallback_to_git_cli(&self, error: &git2::Error) -> bool {
957 match error.class() {
958 git2::ErrorClass::Ssl => true,
960
961 git2::ErrorClass::Http if error.code() == git2::ErrorCode::Certificate => true,
963
964 git2::ErrorClass::Ssh => {
966 let error_string = error.to_string();
967 error_string.contains("no callback set")
968 || error_string.contains("authentication required")
969 }
970
971 git2::ErrorClass::Net => {
973 let error_string = error.to_string();
974 error_string.contains("TLS stream")
975 || error_string.contains("SSL")
976 || error_string.contains("proxy")
977 || error_string.contains("firewall")
978 }
979
980 git2::ErrorClass::Http => {
982 let error_string = error.to_string();
983 error_string.contains("TLS stream")
984 || error_string.contains("SSL")
985 || error_string.contains("proxy")
986 }
987
988 _ => false,
989 }
990 }
991
992 fn configure_remote_callbacks_with_fallback(
993 &self,
994 use_default_first: bool,
995 ) -> Result<git2::RemoteCallbacks<'_>> {
996 let mut callbacks = git2::RemoteCallbacks::new();
997
998 let bitbucket_credentials = self.bitbucket_credentials.clone();
1000 callbacks.credentials(move |url, username_from_url, allowed_types| {
1001 tracing::debug!(
1002 "Authentication requested for URL: {}, username: {:?}, allowed_types: {:?}",
1003 url,
1004 username_from_url,
1005 allowed_types
1006 );
1007
1008 if allowed_types.contains(git2::CredentialType::SSH_KEY) {
1010 if let Some(username) = username_from_url {
1011 tracing::debug!("Trying SSH key authentication for user: {}", username);
1012 return git2::Cred::ssh_key_from_agent(username);
1013 }
1014 }
1015
1016 if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
1018 if use_default_first {
1020 tracing::debug!("Corporate network mode: trying DefaultCredentials first");
1021 return git2::Cred::default();
1022 }
1023
1024 if url.contains("bitbucket") {
1025 if let Some(creds) = &bitbucket_credentials {
1026 if let (Some(username), Some(token)) = (&creds.username, &creds.token) {
1028 tracing::debug!("Trying Bitbucket username + token authentication");
1029 return git2::Cred::userpass_plaintext(username, token);
1030 }
1031
1032 if let Some(token) = &creds.token {
1034 tracing::debug!("Trying Bitbucket token-as-username authentication");
1035 return git2::Cred::userpass_plaintext(token, "");
1036 }
1037
1038 if let Some(username) = &creds.username {
1040 tracing::debug!("Trying Bitbucket username authentication (will use credential helper)");
1041 return git2::Cred::username(username);
1042 }
1043 }
1044 }
1045
1046 tracing::debug!("Trying default credential helper for HTTPS authentication");
1048 return git2::Cred::default();
1049 }
1050
1051 tracing::debug!("Using default credential fallback");
1053 git2::Cred::default()
1054 });
1055
1056 let mut ssl_configured = false;
1061
1062 if let Some(ssl_config) = &self.ssl_config {
1064 if ssl_config.accept_invalid_certs {
1065 Output::warning(
1066 "SSL certificate verification DISABLED via Cascade config - this is insecure!",
1067 );
1068 callbacks.certificate_check(|_cert, _host| {
1069 tracing::debug!("⚠️ Accepting invalid certificate for host: {}", _host);
1070 Ok(git2::CertificateCheckStatus::CertificateOk)
1071 });
1072 ssl_configured = true;
1073 } else if let Some(ca_path) = &ssl_config.ca_bundle_path {
1074 Output::info(format!(
1075 "Using custom CA bundle from Cascade config: {ca_path}"
1076 ));
1077 callbacks.certificate_check(|_cert, host| {
1078 tracing::debug!("Using custom CA bundle for host: {}", host);
1079 Ok(git2::CertificateCheckStatus::CertificateOk)
1080 });
1081 ssl_configured = true;
1082 }
1083 }
1084
1085 if !ssl_configured {
1087 if let Ok(config) = self.repo.config() {
1088 let ssl_verify = config.get_bool("http.sslVerify").unwrap_or(true);
1089
1090 if !ssl_verify {
1091 Output::warning(
1092 "SSL certificate verification DISABLED via git config - this is insecure!",
1093 );
1094 callbacks.certificate_check(|_cert, host| {
1095 tracing::debug!("⚠️ Bypassing SSL verification for host: {}", host);
1096 Ok(git2::CertificateCheckStatus::CertificateOk)
1097 });
1098 ssl_configured = true;
1099 } else if let Ok(ca_path) = config.get_string("http.sslCAInfo") {
1100 Output::info(format!("Using custom CA bundle from git config: {ca_path}"));
1101 callbacks.certificate_check(|_cert, host| {
1102 tracing::debug!("Using git config CA bundle for host: {}", host);
1103 Ok(git2::CertificateCheckStatus::CertificateOk)
1104 });
1105 ssl_configured = true;
1106 }
1107 }
1108 }
1109
1110 if !ssl_configured {
1113 tracing::debug!(
1114 "Using system certificate store for SSL verification (default behavior)"
1115 );
1116
1117 if cfg!(target_os = "macos") {
1119 tracing::debug!("macOS detected - using default certificate validation");
1120 } else {
1123 callbacks.certificate_check(|_cert, host| {
1125 tracing::debug!("System certificate validation for host: {}", host);
1126 Ok(git2::CertificateCheckStatus::CertificatePassthrough)
1127 });
1128 }
1129 }
1130
1131 Ok(callbacks)
1132 }
1133
1134 fn get_index_tree(&self) -> Result<Oid> {
1136 let mut index = self.repo.index().map_err(CascadeError::Git)?;
1137
1138 index.write_tree().map_err(CascadeError::Git)
1139 }
1140
1141 pub fn get_status(&self) -> Result<git2::Statuses<'_>> {
1143 self.repo.statuses(None).map_err(CascadeError::Git)
1144 }
1145
1146 pub fn get_status_summary(&self) -> Result<GitStatusSummary> {
1148 let statuses = self.get_status()?;
1149
1150 let mut staged_files = 0;
1151 let mut unstaged_files = 0;
1152 let mut untracked_files = 0;
1153
1154 for status in statuses.iter() {
1155 let flags = status.status();
1156
1157 if flags.intersects(
1158 git2::Status::INDEX_MODIFIED
1159 | git2::Status::INDEX_NEW
1160 | git2::Status::INDEX_DELETED
1161 | git2::Status::INDEX_RENAMED
1162 | git2::Status::INDEX_TYPECHANGE,
1163 ) {
1164 staged_files += 1;
1165 }
1166
1167 if flags.intersects(
1168 git2::Status::WT_MODIFIED
1169 | git2::Status::WT_DELETED
1170 | git2::Status::WT_TYPECHANGE
1171 | git2::Status::WT_RENAMED,
1172 ) {
1173 unstaged_files += 1;
1174 }
1175
1176 if flags.intersects(git2::Status::WT_NEW) {
1177 untracked_files += 1;
1178 }
1179 }
1180
1181 Ok(GitStatusSummary {
1182 staged_files,
1183 unstaged_files,
1184 untracked_files,
1185 })
1186 }
1187
1188 pub fn get_current_commit_hash(&self) -> Result<String> {
1190 self.get_head_commit_hash()
1191 }
1192
1193 pub fn get_commit_count_between(&self, from_commit: &str, to_commit: &str) -> Result<usize> {
1195 let from_oid = git2::Oid::from_str(from_commit).map_err(CascadeError::Git)?;
1196 let to_oid = git2::Oid::from_str(to_commit).map_err(CascadeError::Git)?;
1197
1198 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1199 revwalk.push(to_oid).map_err(CascadeError::Git)?;
1200 revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1201
1202 Ok(revwalk.count())
1203 }
1204
1205 pub fn get_remote_url(&self, name: &str) -> Result<String> {
1207 let remote = self.repo.find_remote(name).map_err(CascadeError::Git)?;
1208 Ok(remote.url().unwrap_or("unknown").to_string())
1209 }
1210
1211 pub fn cherry_pick(&self, commit_hash: &str) -> Result<String> {
1213 tracing::debug!("Cherry-picking commit {}", commit_hash);
1214
1215 self.validate_git_user_config()?;
1217
1218 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1219 let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1220
1221 let commit_tree = commit.tree().map_err(CascadeError::Git)?;
1223
1224 let parent_commit = if commit.parent_count() > 0 {
1226 commit.parent(0).map_err(CascadeError::Git)?
1227 } else {
1228 let empty_tree_oid = self.repo.treebuilder(None)?.write()?;
1230 let empty_tree = self.repo.find_tree(empty_tree_oid)?;
1231 let sig = self.get_signature()?;
1232 return self
1233 .repo
1234 .commit(
1235 Some("HEAD"),
1236 &sig,
1237 &sig,
1238 commit.message().unwrap_or("Cherry-picked commit"),
1239 &empty_tree,
1240 &[],
1241 )
1242 .map(|oid| oid.to_string())
1243 .map_err(CascadeError::Git);
1244 };
1245
1246 let parent_tree = parent_commit.tree().map_err(CascadeError::Git)?;
1247
1248 let head_commit = self.get_head_commit()?;
1250 let head_tree = head_commit.tree().map_err(CascadeError::Git)?;
1251
1252 let mut index = self
1254 .repo
1255 .merge_trees(&parent_tree, &head_tree, &commit_tree, None)
1256 .map_err(CascadeError::Git)?;
1257
1258 if index.has_conflicts() {
1260 return Err(CascadeError::branch(format!(
1261 "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
1262 )));
1263 }
1264
1265 let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
1267 let merged_tree = self
1268 .repo
1269 .find_tree(merged_tree_oid)
1270 .map_err(CascadeError::Git)?;
1271
1272 let signature = self.get_signature()?;
1274 let message = commit.message().unwrap_or("Cherry-picked commit");
1275
1276 let new_commit_oid = self
1277 .repo
1278 .commit(
1279 Some("HEAD"),
1280 &signature,
1281 &signature,
1282 message,
1283 &merged_tree,
1284 &[&head_commit],
1285 )
1286 .map_err(CascadeError::Git)?;
1287
1288 let new_commit = self
1290 .repo
1291 .find_commit(new_commit_oid)
1292 .map_err(CascadeError::Git)?;
1293 let new_tree = new_commit.tree().map_err(CascadeError::Git)?;
1294
1295 self.repo
1296 .checkout_tree(
1297 new_tree.as_object(),
1298 Some(git2::build::CheckoutBuilder::new().force()),
1299 )
1300 .map_err(CascadeError::Git)?;
1301
1302 tracing::debug!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
1303 Ok(new_commit_oid.to_string())
1304 }
1305
1306 pub fn has_conflicts(&self) -> Result<bool> {
1308 let index = self.repo.index().map_err(CascadeError::Git)?;
1309 Ok(index.has_conflicts())
1310 }
1311
1312 pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
1314 let index = self.repo.index().map_err(CascadeError::Git)?;
1315
1316 let mut conflicts = Vec::new();
1317
1318 let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;
1320
1321 for conflict in conflict_iter {
1322 let conflict = conflict.map_err(CascadeError::Git)?;
1323 if let Some(our) = conflict.our {
1324 if let Ok(path) = std::str::from_utf8(&our.path) {
1325 conflicts.push(path.to_string());
1326 }
1327 } else if let Some(their) = conflict.their {
1328 if let Ok(path) = std::str::from_utf8(&their.path) {
1329 conflicts.push(path.to_string());
1330 }
1331 }
1332 }
1333
1334 Ok(conflicts)
1335 }
1336
1337 pub fn fetch(&self) -> Result<()> {
1339 tracing::debug!("Fetching from origin");
1340
1341 let mut remote = self
1342 .repo
1343 .find_remote("origin")
1344 .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1345
1346 let callbacks = self.configure_remote_callbacks()?;
1348
1349 let mut fetch_options = git2::FetchOptions::new();
1351 fetch_options.remote_callbacks(callbacks);
1352
1353 match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1355 Ok(_) => {
1356 tracing::debug!("Fetch completed successfully");
1357 Ok(())
1358 }
1359 Err(e) => {
1360 if self.should_retry_with_default_credentials(&e) {
1361 tracing::debug!(
1362 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1363 e.class(), e.code(), e
1364 );
1365
1366 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1368 let mut fetch_options = git2::FetchOptions::new();
1369 fetch_options.remote_callbacks(callbacks);
1370
1371 match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1372 Ok(_) => {
1373 tracing::debug!("Fetch succeeded with DefaultCredentials");
1374 return Ok(());
1375 }
1376 Err(retry_error) => {
1377 tracing::debug!(
1378 "DefaultCredentials retry failed: {}, falling back to git CLI",
1379 retry_error
1380 );
1381 return self.fetch_with_git_cli();
1382 }
1383 }
1384 }
1385
1386 if self.should_fallback_to_git_cli(&e) {
1387 tracing::debug!(
1388 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for fetch operation",
1389 e.class(), e.code(), e
1390 );
1391 return self.fetch_with_git_cli();
1392 }
1393 Err(CascadeError::Git(e))
1394 }
1395 }
1396 }
1397
1398 pub fn pull(&self, branch: &str) -> Result<()> {
1400 tracing::debug!("Pulling branch: {}", branch);
1401
1402 match self.fetch() {
1404 Ok(_) => {}
1405 Err(e) => {
1406 let error_string = e.to_string();
1408 if error_string.contains("TLS stream") || error_string.contains("SSL") {
1409 tracing::warn!(
1410 "git2 error detected: {}, falling back to git CLI for pull operation",
1411 e
1412 );
1413 return self.pull_with_git_cli(branch);
1414 }
1415 return Err(e);
1416 }
1417 }
1418
1419 let remote_branch_name = format!("origin/{branch}");
1421 let remote_oid = self
1422 .repo
1423 .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
1424 .map_err(|e| {
1425 CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
1426 })?;
1427
1428 let remote_commit = self
1429 .repo
1430 .find_commit(remote_oid)
1431 .map_err(CascadeError::Git)?;
1432
1433 let head_commit = self.get_head_commit()?;
1435
1436 if head_commit.id() == remote_commit.id() {
1438 tracing::debug!("Already up to date");
1439 return Ok(());
1440 }
1441
1442 let merge_base_oid = self
1444 .repo
1445 .merge_base(head_commit.id(), remote_commit.id())
1446 .map_err(CascadeError::Git)?;
1447
1448 if merge_base_oid == head_commit.id() {
1449 tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());
1451
1452 let refname = format!("refs/heads/{}", branch);
1454 self.repo
1455 .reference(&refname, remote_oid, true, "pull: Fast-forward")
1456 .map_err(CascadeError::Git)?;
1457
1458 self.repo.set_head(&refname).map_err(CascadeError::Git)?;
1460
1461 self.repo
1463 .checkout_head(Some(
1464 git2::build::CheckoutBuilder::new()
1465 .force()
1466 .remove_untracked(false),
1467 ))
1468 .map_err(CascadeError::Git)?;
1469
1470 tracing::debug!("Fast-forwarded to {}", remote_commit.id());
1471 return Ok(());
1472 }
1473
1474 Err(CascadeError::branch(format!(
1477 "Branch '{}' has diverged from remote. Local has commits not in remote. \
1478 Protected branches should not have local commits. \
1479 Try: git reset --hard origin/{}",
1480 branch, branch
1481 )))
1482 }
1483
1484 pub fn push(&self, branch: &str) -> Result<()> {
1486 let mut remote = self
1489 .repo
1490 .find_remote("origin")
1491 .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1492
1493 let remote_url = remote.url().unwrap_or("unknown").to_string();
1494 tracing::debug!("Remote URL: {}", remote_url);
1495
1496 let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1497 tracing::debug!("Push refspec: {}", refspec);
1498
1499 let mut callbacks = self.configure_remote_callbacks()?;
1501
1502 callbacks.push_update_reference(|refname, status| {
1504 if let Some(msg) = status {
1505 tracing::error!("Push failed for ref {}: {}", refname, msg);
1506 return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1507 }
1508 tracing::debug!("Push succeeded for ref: {}", refname);
1509 Ok(())
1510 });
1511
1512 let mut push_options = git2::PushOptions::new();
1514 push_options.remote_callbacks(callbacks);
1515
1516 match remote.push(&[&refspec], Some(&mut push_options)) {
1518 Ok(_) => {
1519 tracing::info!("Push completed successfully for branch: {}", branch);
1520 Ok(())
1521 }
1522 Err(e) => {
1523 tracing::debug!(
1524 "git2 push error: {} (class: {:?}, code: {:?})",
1525 e,
1526 e.class(),
1527 e.code()
1528 );
1529
1530 if self.should_retry_with_default_credentials(&e) {
1531 tracing::debug!(
1532 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1533 e.class(), e.code(), e
1534 );
1535
1536 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1538 let mut push_options = git2::PushOptions::new();
1539 push_options.remote_callbacks(callbacks);
1540
1541 match remote.push(&[&refspec], Some(&mut push_options)) {
1542 Ok(_) => {
1543 tracing::debug!("Push succeeded with DefaultCredentials");
1544 return Ok(());
1545 }
1546 Err(retry_error) => {
1547 tracing::debug!(
1548 "DefaultCredentials retry failed: {}, falling back to git CLI",
1549 retry_error
1550 );
1551 return self.push_with_git_cli(branch);
1552 }
1553 }
1554 }
1555
1556 if self.should_fallback_to_git_cli(&e) {
1557 tracing::debug!(
1558 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
1559 e.class(), e.code(), e
1560 );
1561 return self.push_with_git_cli(branch);
1562 }
1563
1564 let error_msg = if e.to_string().contains("authentication") {
1566 format!(
1567 "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1568 )
1569 } else {
1570 format!("Failed to push branch '{branch}': {e}")
1571 };
1572
1573 tracing::error!("{}", error_msg);
1574 Err(CascadeError::branch(error_msg))
1575 }
1576 }
1577 }
1578
1579 fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1582 let output = std::process::Command::new("git")
1583 .args(["push", "origin", branch])
1584 .current_dir(&self.path)
1585 .output()
1586 .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1587
1588 if output.status.success() {
1589 Ok(())
1591 } else {
1592 let stderr = String::from_utf8_lossy(&output.stderr);
1593 let _stdout = String::from_utf8_lossy(&output.stdout);
1594 let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
1596 "Network error: Unable to connect to repository (VPN may be required)".to_string()
1597 } else if stderr.contains("repository") && stderr.contains("not found") {
1598 "Repository not found - check your Bitbucket configuration".to_string()
1599 } else if stderr.contains("authentication") || stderr.contains("403") {
1600 "Authentication failed - check your credentials".to_string()
1601 } else {
1602 stderr.trim().to_string()
1604 };
1605 tracing::error!("{}", error_msg);
1606 Err(CascadeError::branch(error_msg))
1607 }
1608 }
1609
1610 fn fetch_with_git_cli(&self) -> Result<()> {
1613 tracing::debug!("Using git CLI fallback for fetch operation");
1614
1615 let output = std::process::Command::new("git")
1616 .args(["fetch", "origin"])
1617 .current_dir(&self.path)
1618 .output()
1619 .map_err(|e| {
1620 CascadeError::Git(git2::Error::from_str(&format!(
1621 "Failed to execute git command: {e}"
1622 )))
1623 })?;
1624
1625 if output.status.success() {
1626 tracing::debug!("Git CLI fetch succeeded");
1627 Ok(())
1628 } else {
1629 let stderr = String::from_utf8_lossy(&output.stderr);
1630 let stdout = String::from_utf8_lossy(&output.stdout);
1631 let error_msg = format!(
1632 "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
1633 output.status, stdout, stderr
1634 );
1635 tracing::error!("{}", error_msg);
1636 Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1637 }
1638 }
1639
1640 fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
1643 tracing::debug!("Using git CLI fallback for pull operation: {}", branch);
1644
1645 let output = std::process::Command::new("git")
1646 .args(["pull", "origin", branch])
1647 .current_dir(&self.path)
1648 .output()
1649 .map_err(|e| {
1650 CascadeError::Git(git2::Error::from_str(&format!(
1651 "Failed to execute git command: {e}"
1652 )))
1653 })?;
1654
1655 if output.status.success() {
1656 tracing::info!("✅ Git CLI pull succeeded for branch: {}", branch);
1657 Ok(())
1658 } else {
1659 let stderr = String::from_utf8_lossy(&output.stderr);
1660 let stdout = String::from_utf8_lossy(&output.stdout);
1661 let error_msg = format!(
1662 "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1663 branch, output.status, stdout, stderr
1664 );
1665 tracing::error!("{}", error_msg);
1666 Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1667 }
1668 }
1669
1670 fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
1673 tracing::debug!(
1674 "Using git CLI fallback for force push operation: {}",
1675 branch
1676 );
1677
1678 let output = std::process::Command::new("git")
1679 .args(["push", "--force", "origin", branch])
1680 .current_dir(&self.path)
1681 .output()
1682 .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1683
1684 if output.status.success() {
1685 tracing::debug!("Git CLI force push succeeded for branch: {}", branch);
1686 Ok(())
1687 } else {
1688 let stderr = String::from_utf8_lossy(&output.stderr);
1689 let stdout = String::from_utf8_lossy(&output.stdout);
1690 let error_msg = format!(
1691 "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1692 branch, output.status, stdout, stderr
1693 );
1694 tracing::error!("{}", error_msg);
1695 Err(CascadeError::branch(error_msg))
1696 }
1697 }
1698
1699 pub fn delete_branch(&self, name: &str) -> Result<()> {
1701 self.delete_branch_with_options(name, false)
1702 }
1703
1704 pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
1706 self.delete_branch_with_options(name, true)
1707 }
1708
1709 fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
1711 debug!("Attempting to delete branch: {}", name);
1712
1713 if !force_unsafe {
1715 let safety_result = self.check_branch_deletion_safety(name)?;
1716 if let Some(safety_info) = safety_result {
1717 self.handle_branch_deletion_confirmation(name, &safety_info)?;
1719 }
1720 }
1721
1722 let mut branch = self
1723 .repo
1724 .find_branch(name, git2::BranchType::Local)
1725 .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
1726
1727 branch
1728 .delete()
1729 .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
1730
1731 debug!("Successfully deleted branch '{}'", name);
1732 Ok(())
1733 }
1734
1735 pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
1737 let from_oid = self
1738 .repo
1739 .refname_to_id(&format!("refs/heads/{from}"))
1740 .or_else(|_| Oid::from_str(from))
1741 .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
1742
1743 let to_oid = self
1744 .repo
1745 .refname_to_id(&format!("refs/heads/{to}"))
1746 .or_else(|_| Oid::from_str(to))
1747 .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
1748
1749 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1750
1751 revwalk.push(to_oid).map_err(CascadeError::Git)?;
1752 revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1753
1754 let mut commits = Vec::new();
1755 for oid in revwalk {
1756 let oid = oid.map_err(CascadeError::Git)?;
1757 let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1758 commits.push(commit);
1759 }
1760
1761 Ok(commits)
1762 }
1763
1764 pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1767 self.force_push_branch_with_options(target_branch, source_branch, false)
1768 }
1769
1770 pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1772 self.force_push_branch_with_options(target_branch, source_branch, true)
1773 }
1774
1775 fn force_push_branch_with_options(
1777 &self,
1778 target_branch: &str,
1779 source_branch: &str,
1780 force_unsafe: bool,
1781 ) -> Result<()> {
1782 debug!(
1783 "Force pushing {} content to {} to preserve PR history",
1784 source_branch, target_branch
1785 );
1786
1787 if !force_unsafe {
1789 let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
1790 if let Some(backup_info) = safety_result {
1791 self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
1793 debug!("Created backup branch: {}", backup_info.backup_branch_name);
1794 }
1795 }
1796
1797 let source_ref = self
1799 .repo
1800 .find_reference(&format!("refs/heads/{source_branch}"))
1801 .map_err(|e| {
1802 CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
1803 })?;
1804 let _source_commit = source_ref.peel_to_commit().map_err(|e| {
1805 CascadeError::config(format!(
1806 "Failed to get commit for source branch {source_branch}: {e}"
1807 ))
1808 })?;
1809
1810 let mut remote = self
1812 .repo
1813 .find_remote("origin")
1814 .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
1815
1816 let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");
1818
1819 let callbacks = self.configure_remote_callbacks()?;
1821
1822 let mut push_options = git2::PushOptions::new();
1824 push_options.remote_callbacks(callbacks);
1825
1826 match remote.push(&[&refspec], Some(&mut push_options)) {
1827 Ok(_) => {}
1828 Err(e) => {
1829 if self.should_retry_with_default_credentials(&e) {
1830 tracing::debug!(
1831 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1832 e.class(), e.code(), e
1833 );
1834
1835 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1837 let mut push_options = git2::PushOptions::new();
1838 push_options.remote_callbacks(callbacks);
1839
1840 match remote.push(&[&refspec], Some(&mut push_options)) {
1841 Ok(_) => {
1842 tracing::debug!("Force push succeeded with DefaultCredentials");
1843 }
1845 Err(retry_error) => {
1846 tracing::debug!(
1847 "DefaultCredentials retry failed: {}, falling back to git CLI",
1848 retry_error
1849 );
1850 return self.force_push_with_git_cli(target_branch);
1851 }
1852 }
1853 } else if self.should_fallback_to_git_cli(&e) {
1854 tracing::debug!(
1855 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
1856 e.class(), e.code(), e
1857 );
1858 return self.force_push_with_git_cli(target_branch);
1859 } else {
1860 return Err(CascadeError::config(format!(
1861 "Failed to force push {target_branch}: {e}"
1862 )));
1863 }
1864 }
1865 }
1866
1867 info!(
1868 "✅ Successfully force pushed {} to preserve PR history",
1869 target_branch
1870 );
1871 Ok(())
1872 }
1873
1874 fn check_force_push_safety_enhanced(
1877 &self,
1878 target_branch: &str,
1879 ) -> Result<Option<ForceBackupInfo>> {
1880 match self.fetch() {
1882 Ok(_) => {}
1883 Err(e) => {
1884 warn!("Could not fetch latest changes for safety check: {}", e);
1886 }
1887 }
1888
1889 let remote_ref = format!("refs/remotes/origin/{target_branch}");
1891 let local_ref = format!("refs/heads/{target_branch}");
1892
1893 let local_commit = match self.repo.find_reference(&local_ref) {
1895 Ok(reference) => reference.peel_to_commit().ok(),
1896 Err(_) => None,
1897 };
1898
1899 let remote_commit = match self.repo.find_reference(&remote_ref) {
1900 Ok(reference) => reference.peel_to_commit().ok(),
1901 Err(_) => None,
1902 };
1903
1904 if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
1906 if local.id() != remote.id() {
1907 let merge_base_oid = self
1909 .repo
1910 .merge_base(local.id(), remote.id())
1911 .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
1912
1913 if merge_base_oid != remote.id() {
1915 let commits_to_lose = self.count_commits_between(
1916 &merge_base_oid.to_string(),
1917 &remote.id().to_string(),
1918 )?;
1919
1920 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
1922 let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
1923
1924 debug!(
1925 "Force push to '{}' would overwrite {} commits on remote",
1926 target_branch, commits_to_lose
1927 );
1928
1929 if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
1931 {
1932 info!(
1933 "Non-interactive environment detected, proceeding with backup creation"
1934 );
1935 return Ok(Some(ForceBackupInfo {
1936 backup_branch_name,
1937 remote_commit_id: remote.id().to_string(),
1938 commits_that_would_be_lost: commits_to_lose,
1939 }));
1940 }
1941
1942 println!("\n⚠️ FORCE PUSH WARNING ⚠️");
1944 println!("Force push to '{target_branch}' would overwrite {commits_to_lose} commits on remote:");
1945
1946 match self
1948 .get_commits_between(&merge_base_oid.to_string(), &remote.id().to_string())
1949 {
1950 Ok(commits) => {
1951 println!("\nCommits that would be lost:");
1952 for (i, commit) in commits.iter().take(5).enumerate() {
1953 let short_hash = &commit.id().to_string()[..8];
1954 let summary = commit.summary().unwrap_or("<no message>");
1955 println!(" {}. {} - {}", i + 1, short_hash, summary);
1956 }
1957 if commits.len() > 5 {
1958 println!(" ... and {} more commits", commits.len() - 5);
1959 }
1960 }
1961 Err(_) => {
1962 println!(" (Unable to retrieve commit details)");
1963 }
1964 }
1965
1966 println!("\nA backup branch '{backup_branch_name}' will be created before proceeding.");
1967
1968 let confirmed = Confirm::with_theme(&ColorfulTheme::default())
1969 .with_prompt("Do you want to proceed with the force push?")
1970 .default(false)
1971 .interact()
1972 .map_err(|e| {
1973 CascadeError::config(format!("Failed to get user confirmation: {e}"))
1974 })?;
1975
1976 if !confirmed {
1977 return Err(CascadeError::config(
1978 "Force push cancelled by user. Use --force to bypass this check."
1979 .to_string(),
1980 ));
1981 }
1982
1983 return Ok(Some(ForceBackupInfo {
1984 backup_branch_name,
1985 remote_commit_id: remote.id().to_string(),
1986 commits_that_would_be_lost: commits_to_lose,
1987 }));
1988 }
1989 }
1990 }
1991
1992 Ok(None)
1993 }
1994
1995 fn check_force_push_safety_auto(&self, target_branch: &str) -> Result<Option<ForceBackupInfo>> {
1998 match self.fetch() {
2000 Ok(_) => {}
2001 Err(e) => {
2002 warn!("Could not fetch latest changes for safety check: {}", e);
2003 }
2004 }
2005
2006 let remote_ref = format!("refs/remotes/origin/{target_branch}");
2008 let local_ref = format!("refs/heads/{target_branch}");
2009
2010 let local_commit = match self.repo.find_reference(&local_ref) {
2012 Ok(reference) => reference.peel_to_commit().ok(),
2013 Err(_) => None,
2014 };
2015
2016 let remote_commit = match self.repo.find_reference(&remote_ref) {
2017 Ok(reference) => reference.peel_to_commit().ok(),
2018 Err(_) => None,
2019 };
2020
2021 if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2023 if local.id() != remote.id() {
2024 let merge_base_oid = self
2026 .repo
2027 .merge_base(local.id(), remote.id())
2028 .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2029
2030 if merge_base_oid != remote.id() {
2032 let commits_to_lose = self.count_commits_between(
2033 &merge_base_oid.to_string(),
2034 &remote.id().to_string(),
2035 )?;
2036
2037 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2039 let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2040
2041 debug!(
2042 "Auto-creating backup for force push to '{}' (would overwrite {} commits)",
2043 target_branch, commits_to_lose
2044 );
2045
2046 return Ok(Some(ForceBackupInfo {
2048 backup_branch_name,
2049 remote_commit_id: remote.id().to_string(),
2050 commits_that_would_be_lost: commits_to_lose,
2051 }));
2052 }
2053 }
2054 }
2055
2056 Ok(None)
2057 }
2058
2059 fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
2061 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2062 let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
2063
2064 let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
2066 CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
2067 })?;
2068
2069 let commit = self.repo.find_commit(commit_oid).map_err(|e| {
2071 CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
2072 })?;
2073
2074 self.repo
2076 .branch(&backup_branch_name, &commit, false)
2077 .map_err(|e| {
2078 CascadeError::config(format!(
2079 "Failed to create backup branch {backup_branch_name}: {e}"
2080 ))
2081 })?;
2082
2083 debug!(
2084 "Created backup branch '{}' pointing to {}",
2085 backup_branch_name,
2086 &remote_commit_id[..8]
2087 );
2088 Ok(())
2089 }
2090
2091 fn check_branch_deletion_safety(
2094 &self,
2095 branch_name: &str,
2096 ) -> Result<Option<BranchDeletionSafety>> {
2097 match self.fetch() {
2099 Ok(_) => {}
2100 Err(e) => {
2101 warn!(
2102 "Could not fetch latest changes for branch deletion safety check: {}",
2103 e
2104 );
2105 }
2106 }
2107
2108 let branch = self
2110 .repo
2111 .find_branch(branch_name, git2::BranchType::Local)
2112 .map_err(|e| {
2113 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2114 })?;
2115
2116 let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
2117 CascadeError::branch(format!(
2118 "Could not get commit for branch '{branch_name}': {e}"
2119 ))
2120 })?;
2121
2122 let main_branch_name = self.detect_main_branch()?;
2124
2125 let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
2127
2128 let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
2130
2131 let mut unpushed_commits = Vec::new();
2132
2133 if let Some(ref remote_branch) = remote_tracking_branch {
2135 match self.get_commits_between(remote_branch, branch_name) {
2136 Ok(commits) => {
2137 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2138 }
2139 Err(_) => {
2140 if !is_merged_to_main {
2142 if let Ok(commits) =
2143 self.get_commits_between(&main_branch_name, branch_name)
2144 {
2145 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2146 }
2147 }
2148 }
2149 }
2150 } else if !is_merged_to_main {
2151 if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
2153 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2154 }
2155 }
2156
2157 if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
2159 {
2160 Ok(Some(BranchDeletionSafety {
2161 unpushed_commits,
2162 remote_tracking_branch,
2163 is_merged_to_main,
2164 main_branch_name,
2165 }))
2166 } else {
2167 Ok(None)
2168 }
2169 }
2170
2171 fn handle_branch_deletion_confirmation(
2173 &self,
2174 branch_name: &str,
2175 safety_info: &BranchDeletionSafety,
2176 ) -> Result<()> {
2177 if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
2179 return Err(CascadeError::branch(
2180 format!(
2181 "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
2182 safety_info.unpushed_commits.len()
2183 )
2184 ));
2185 }
2186
2187 println!("\n⚠️ BRANCH DELETION WARNING ⚠️");
2189 println!("Branch '{branch_name}' has potential issues:");
2190
2191 if !safety_info.unpushed_commits.is_empty() {
2192 println!(
2193 "\n🔍 Unpushed commits ({} total):",
2194 safety_info.unpushed_commits.len()
2195 );
2196
2197 for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
2199 if let Ok(oid) = Oid::from_str(commit_id) {
2200 if let Ok(commit) = self.repo.find_commit(oid) {
2201 let short_hash = &commit_id[..8];
2202 let summary = commit.summary().unwrap_or("<no message>");
2203 println!(" {}. {} - {}", i + 1, short_hash, summary);
2204 }
2205 }
2206 }
2207
2208 if safety_info.unpushed_commits.len() > 5 {
2209 println!(
2210 " ... and {} more commits",
2211 safety_info.unpushed_commits.len() - 5
2212 );
2213 }
2214 }
2215
2216 if !safety_info.is_merged_to_main {
2217 println!("\n📋 Branch status:");
2218 println!(" • Not merged to '{}'", safety_info.main_branch_name);
2219 if let Some(ref remote) = safety_info.remote_tracking_branch {
2220 println!(" • Remote tracking branch: {remote}");
2221 } else {
2222 println!(" • No remote tracking branch");
2223 }
2224 }
2225
2226 println!("\n💡 Safer alternatives:");
2227 if !safety_info.unpushed_commits.is_empty() {
2228 if let Some(ref _remote) = safety_info.remote_tracking_branch {
2229 println!(" • Push commits first: git push origin {branch_name}");
2230 } else {
2231 println!(" • Create and push to remote: git push -u origin {branch_name}");
2232 }
2233 }
2234 if !safety_info.is_merged_to_main {
2235 println!(
2236 " • Merge to {} first: git checkout {} && git merge {branch_name}",
2237 safety_info.main_branch_name, safety_info.main_branch_name
2238 );
2239 }
2240
2241 let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2242 .with_prompt("Do you want to proceed with deleting this branch?")
2243 .default(false)
2244 .interact()
2245 .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
2246
2247 if !confirmed {
2248 return Err(CascadeError::branch(
2249 "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
2250 ));
2251 }
2252
2253 Ok(())
2254 }
2255
2256 pub fn detect_main_branch(&self) -> Result<String> {
2258 let main_candidates = ["main", "master", "develop", "trunk"];
2259
2260 for candidate in &main_candidates {
2261 if self
2262 .repo
2263 .find_branch(candidate, git2::BranchType::Local)
2264 .is_ok()
2265 {
2266 return Ok(candidate.to_string());
2267 }
2268 }
2269
2270 if let Ok(head) = self.repo.head() {
2272 if let Some(name) = head.shorthand() {
2273 return Ok(name.to_string());
2274 }
2275 }
2276
2277 Ok("main".to_string())
2279 }
2280
2281 fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
2283 match self.get_commits_between(main_branch, branch_name) {
2285 Ok(commits) => Ok(commits.is_empty()),
2286 Err(_) => {
2287 Ok(false)
2289 }
2290 }
2291 }
2292
2293 fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
2295 let remote_candidates = [
2297 format!("origin/{branch_name}"),
2298 format!("remotes/origin/{branch_name}"),
2299 ];
2300
2301 for candidate in &remote_candidates {
2302 if self
2303 .repo
2304 .find_reference(&format!(
2305 "refs/remotes/{}",
2306 candidate.replace("remotes/", "")
2307 ))
2308 .is_ok()
2309 {
2310 return Some(candidate.clone());
2311 }
2312 }
2313
2314 None
2315 }
2316
2317 fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
2319 let is_dirty = self.is_dirty()?;
2321 if !is_dirty {
2322 return Ok(None);
2324 }
2325
2326 let current_branch = self.get_current_branch().ok();
2328
2329 let modified_files = self.get_modified_files()?;
2331 let staged_files = self.get_staged_files()?;
2332 let untracked_files = self.get_untracked_files()?;
2333
2334 let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
2335
2336 if has_uncommitted_changes || !untracked_files.is_empty() {
2337 return Ok(Some(CheckoutSafety {
2338 has_uncommitted_changes,
2339 modified_files,
2340 staged_files,
2341 untracked_files,
2342 stash_created: None,
2343 current_branch,
2344 }));
2345 }
2346
2347 Ok(None)
2348 }
2349
2350 fn handle_checkout_confirmation(
2352 &self,
2353 target: &str,
2354 safety_info: &CheckoutSafety,
2355 ) -> Result<()> {
2356 let is_ci = std::env::var("CI").is_ok();
2358 let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
2359 let is_non_interactive = is_ci || no_confirm;
2360
2361 if is_non_interactive {
2362 return Err(CascadeError::branch(
2363 format!(
2364 "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
2365 )
2366 ));
2367 }
2368
2369 println!("\n⚠️ CHECKOUT WARNING ⚠️");
2371 println!("You have uncommitted changes that could be lost:");
2372
2373 if !safety_info.modified_files.is_empty() {
2374 println!(
2375 "\n📝 Modified files ({}):",
2376 safety_info.modified_files.len()
2377 );
2378 for file in safety_info.modified_files.iter().take(10) {
2379 println!(" - {file}");
2380 }
2381 if safety_info.modified_files.len() > 10 {
2382 println!(" ... and {} more", safety_info.modified_files.len() - 10);
2383 }
2384 }
2385
2386 if !safety_info.staged_files.is_empty() {
2387 println!("\n📁 Staged files ({}):", safety_info.staged_files.len());
2388 for file in safety_info.staged_files.iter().take(10) {
2389 println!(" - {file}");
2390 }
2391 if safety_info.staged_files.len() > 10 {
2392 println!(" ... and {} more", safety_info.staged_files.len() - 10);
2393 }
2394 }
2395
2396 if !safety_info.untracked_files.is_empty() {
2397 println!(
2398 "\n❓ Untracked files ({}):",
2399 safety_info.untracked_files.len()
2400 );
2401 for file in safety_info.untracked_files.iter().take(5) {
2402 println!(" - {file}");
2403 }
2404 if safety_info.untracked_files.len() > 5 {
2405 println!(" ... and {} more", safety_info.untracked_files.len() - 5);
2406 }
2407 }
2408
2409 println!("\n🔄 Options:");
2410 println!("1. Stash changes and checkout (recommended)");
2411 println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
2412 println!("3. Cancel checkout");
2413
2414 let selection = Select::with_theme(&ColorfulTheme::default())
2416 .with_prompt("Choose an action")
2417 .items(&[
2418 "Stash changes and checkout (recommended)",
2419 "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
2420 "Cancel checkout",
2421 ])
2422 .default(0)
2423 .interact()
2424 .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;
2425
2426 match selection {
2427 0 => {
2428 let stash_message = format!(
2430 "Auto-stash before checkout to {} at {}",
2431 target,
2432 chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
2433 );
2434
2435 match self.create_stash(&stash_message) {
2436 Ok(stash_id) => {
2437 println!("✅ Created stash: {stash_message} ({stash_id})");
2438 println!("💡 You can restore with: git stash pop");
2439 }
2440 Err(e) => {
2441 println!("❌ Failed to create stash: {e}");
2442
2443 use dialoguer::Select;
2445 let stash_failed_options = vec![
2446 "Commit staged changes and proceed",
2447 "Force checkout (WILL LOSE CHANGES)",
2448 "Cancel and handle manually",
2449 ];
2450
2451 let stash_selection = Select::with_theme(&ColorfulTheme::default())
2452 .with_prompt("Stash failed. What would you like to do?")
2453 .items(&stash_failed_options)
2454 .default(0)
2455 .interact()
2456 .map_err(|e| {
2457 CascadeError::branch(format!("Could not get user selection: {e}"))
2458 })?;
2459
2460 match stash_selection {
2461 0 => {
2462 let staged_files = self.get_staged_files()?;
2464 if !staged_files.is_empty() {
2465 println!(
2466 "📝 Committing {} staged files...",
2467 staged_files.len()
2468 );
2469 match self
2470 .commit_staged_changes("WIP: Auto-commit before checkout")
2471 {
2472 Ok(Some(commit_hash)) => {
2473 println!(
2474 "✅ Committed staged changes as {}",
2475 &commit_hash[..8]
2476 );
2477 println!("💡 You can undo with: git reset HEAD~1");
2478 }
2479 Ok(None) => {
2480 println!("ℹ️ No staged changes found to commit");
2481 }
2482 Err(commit_err) => {
2483 println!(
2484 "❌ Failed to commit staged changes: {commit_err}"
2485 );
2486 return Err(CascadeError::branch(
2487 "Could not commit staged changes".to_string(),
2488 ));
2489 }
2490 }
2491 } else {
2492 println!("ℹ️ No staged changes to commit");
2493 }
2494 }
2495 1 => {
2496 println!("⚠️ Proceeding with force checkout - uncommitted changes will be lost!");
2498 }
2499 2 => {
2500 return Err(CascadeError::branch(
2502 "Checkout cancelled. Please handle changes manually and try again.".to_string(),
2503 ));
2504 }
2505 _ => unreachable!(),
2506 }
2507 }
2508 }
2509 }
2510 1 => {
2511 println!("⚠️ Proceeding with force checkout - uncommitted changes will be lost!");
2513 }
2514 2 => {
2515 return Err(CascadeError::branch(
2517 "Checkout cancelled by user".to_string(),
2518 ));
2519 }
2520 _ => unreachable!(),
2521 }
2522
2523 Ok(())
2524 }
2525
2526 fn create_stash(&self, message: &str) -> Result<String> {
2528 tracing::info!("Creating stash: {}", message);
2529
2530 let output = std::process::Command::new("git")
2532 .args(["stash", "push", "-m", message])
2533 .current_dir(&self.path)
2534 .output()
2535 .map_err(|e| {
2536 CascadeError::branch(format!("Failed to execute git stash command: {e}"))
2537 })?;
2538
2539 if output.status.success() {
2540 let stdout = String::from_utf8_lossy(&output.stdout);
2541
2542 let stash_id = if stdout.contains("Saved working directory") {
2544 let stash_list_output = std::process::Command::new("git")
2546 .args(["stash", "list", "-n", "1", "--format=%H"])
2547 .current_dir(&self.path)
2548 .output()
2549 .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;
2550
2551 if stash_list_output.status.success() {
2552 String::from_utf8_lossy(&stash_list_output.stdout)
2553 .trim()
2554 .to_string()
2555 } else {
2556 "stash@{0}".to_string() }
2558 } else {
2559 "stash@{0}".to_string() };
2561
2562 tracing::info!("✅ Created stash: {} ({})", message, stash_id);
2563 Ok(stash_id)
2564 } else {
2565 let stderr = String::from_utf8_lossy(&output.stderr);
2566 let stdout = String::from_utf8_lossy(&output.stdout);
2567
2568 if stderr.contains("No local changes to save")
2570 || stdout.contains("No local changes to save")
2571 {
2572 return Err(CascadeError::branch("No local changes to save".to_string()));
2573 }
2574
2575 Err(CascadeError::branch(format!(
2576 "Failed to create stash: {}\nStderr: {}\nStdout: {}",
2577 output.status, stderr, stdout
2578 )))
2579 }
2580 }
2581
2582 fn get_modified_files(&self) -> Result<Vec<String>> {
2584 let mut opts = git2::StatusOptions::new();
2585 opts.include_untracked(false).include_ignored(false);
2586
2587 let statuses = self
2588 .repo
2589 .statuses(Some(&mut opts))
2590 .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2591
2592 let mut modified_files = Vec::new();
2593 for status in statuses.iter() {
2594 let flags = status.status();
2595 if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
2596 {
2597 if let Some(path) = status.path() {
2598 modified_files.push(path.to_string());
2599 }
2600 }
2601 }
2602
2603 Ok(modified_files)
2604 }
2605
2606 pub fn get_staged_files(&self) -> Result<Vec<String>> {
2608 let mut opts = git2::StatusOptions::new();
2609 opts.include_untracked(false).include_ignored(false);
2610
2611 let statuses = self
2612 .repo
2613 .statuses(Some(&mut opts))
2614 .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2615
2616 let mut staged_files = Vec::new();
2617 for status in statuses.iter() {
2618 let flags = status.status();
2619 if flags.contains(git2::Status::INDEX_MODIFIED)
2620 || flags.contains(git2::Status::INDEX_NEW)
2621 || flags.contains(git2::Status::INDEX_DELETED)
2622 {
2623 if let Some(path) = status.path() {
2624 staged_files.push(path.to_string());
2625 }
2626 }
2627 }
2628
2629 Ok(staged_files)
2630 }
2631
2632 fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
2634 let commits = self.get_commits_between(from, to)?;
2635 Ok(commits.len())
2636 }
2637
2638 pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
2640 if let Ok(oid) = Oid::from_str(reference) {
2642 if let Ok(commit) = self.repo.find_commit(oid) {
2643 return Ok(commit);
2644 }
2645 }
2646
2647 let obj = self.repo.revparse_single(reference).map_err(|e| {
2649 CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
2650 })?;
2651
2652 obj.peel_to_commit().map_err(|e| {
2653 CascadeError::branch(format!(
2654 "Reference '{reference}' does not point to a commit: {e}"
2655 ))
2656 })
2657 }
2658
2659 pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
2661 let target_commit = self.resolve_reference(target_ref)?;
2662
2663 self.repo
2664 .reset(target_commit.as_object(), git2::ResetType::Soft, None)
2665 .map_err(CascadeError::Git)?;
2666
2667 Ok(())
2668 }
2669
2670 pub fn reset_to_head(&self) -> Result<()> {
2673 tracing::debug!("Resetting working directory and index to HEAD");
2674
2675 let head = self.repo.head().map_err(CascadeError::Git)?;
2676 let head_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
2677
2678 let mut checkout_builder = git2::build::CheckoutBuilder::new();
2680 checkout_builder.force(); checkout_builder.remove_untracked(false); self.repo
2684 .reset(
2685 head_commit.as_object(),
2686 git2::ResetType::Hard,
2687 Some(&mut checkout_builder),
2688 )
2689 .map_err(CascadeError::Git)?;
2690
2691 tracing::debug!("Successfully reset working directory to HEAD");
2692 Ok(())
2693 }
2694
2695 pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
2697 let oid = Oid::from_str(commit_hash).map_err(|e| {
2698 CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2699 })?;
2700
2701 let branches = self
2703 .repo
2704 .branches(Some(git2::BranchType::Local))
2705 .map_err(CascadeError::Git)?;
2706
2707 for branch_result in branches {
2708 let (branch, _) = branch_result.map_err(CascadeError::Git)?;
2709
2710 if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
2711 if let Ok(branch_head) = branch.get().peel_to_commit() {
2713 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2715 revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
2716
2717 for commit_oid in revwalk {
2718 let commit_oid = commit_oid.map_err(CascadeError::Git)?;
2719 if commit_oid == oid {
2720 return Ok(branch_name.to_string());
2721 }
2722 }
2723 }
2724 }
2725 }
2726
2727 Err(CascadeError::branch(format!(
2729 "Commit {commit_hash} not found in any local branch"
2730 )))
2731 }
2732
2733 pub async fn fetch_async(&self) -> Result<()> {
2737 let repo_path = self.path.clone();
2738 crate::utils::async_ops::run_git_operation(move || {
2739 let repo = GitRepository::open(&repo_path)?;
2740 repo.fetch()
2741 })
2742 .await
2743 }
2744
2745 pub async fn pull_async(&self, branch: &str) -> Result<()> {
2747 let repo_path = self.path.clone();
2748 let branch_name = branch.to_string();
2749 crate::utils::async_ops::run_git_operation(move || {
2750 let repo = GitRepository::open(&repo_path)?;
2751 repo.pull(&branch_name)
2752 })
2753 .await
2754 }
2755
2756 pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
2758 let repo_path = self.path.clone();
2759 let branch = branch_name.to_string();
2760 crate::utils::async_ops::run_git_operation(move || {
2761 let repo = GitRepository::open(&repo_path)?;
2762 repo.push(&branch)
2763 })
2764 .await
2765 }
2766
2767 pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
2769 let repo_path = self.path.clone();
2770 let hash = commit_hash.to_string();
2771 crate::utils::async_ops::run_git_operation(move || {
2772 let repo = GitRepository::open(&repo_path)?;
2773 repo.cherry_pick(&hash)
2774 })
2775 .await
2776 }
2777
2778 pub async fn get_commit_hashes_between_async(
2780 &self,
2781 from: &str,
2782 to: &str,
2783 ) -> Result<Vec<String>> {
2784 let repo_path = self.path.clone();
2785 let from_str = from.to_string();
2786 let to_str = to.to_string();
2787 crate::utils::async_ops::run_git_operation(move || {
2788 let repo = GitRepository::open(&repo_path)?;
2789 let commits = repo.get_commits_between(&from_str, &to_str)?;
2790 Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
2791 })
2792 .await
2793 }
2794
2795 pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
2797 info!(
2798 "Resetting branch '{}' to commit {}",
2799 branch_name,
2800 &commit_hash[..8]
2801 );
2802
2803 let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
2805 CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2806 })?;
2807
2808 let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
2809 CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
2810 })?;
2811
2812 let _branch = self
2814 .repo
2815 .find_branch(branch_name, git2::BranchType::Local)
2816 .map_err(|e| {
2817 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2818 })?;
2819
2820 let branch_ref_name = format!("refs/heads/{branch_name}");
2822 self.repo
2823 .reference(
2824 &branch_ref_name,
2825 target_oid,
2826 true,
2827 &format!("Reset {branch_name} to {commit_hash}"),
2828 )
2829 .map_err(|e| {
2830 CascadeError::branch(format!(
2831 "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
2832 ))
2833 })?;
2834
2835 tracing::info!(
2836 "Successfully reset branch '{}' to commit {}",
2837 branch_name,
2838 &commit_hash[..8]
2839 );
2840 Ok(())
2841 }
2842
2843 pub fn detect_parent_branch(&self) -> Result<Option<String>> {
2845 let current_branch = self.get_current_branch()?;
2846
2847 if let Ok(Some(upstream)) = self.get_upstream_branch(¤t_branch) {
2849 if let Some(branch_name) = upstream.split('/').nth(1) {
2851 if self.branch_exists(branch_name) {
2852 tracing::debug!(
2853 "Detected parent branch '{}' from upstream tracking",
2854 branch_name
2855 );
2856 return Ok(Some(branch_name.to_string()));
2857 }
2858 }
2859 }
2860
2861 if let Ok(default_branch) = self.detect_main_branch() {
2863 if current_branch != default_branch {
2865 tracing::debug!(
2866 "Detected parent branch '{}' as repository default",
2867 default_branch
2868 );
2869 return Ok(Some(default_branch));
2870 }
2871 }
2872
2873 if let Ok(branches) = self.list_branches() {
2876 let current_commit = self.get_head_commit()?;
2877 let current_commit_hash = current_commit.id().to_string();
2878 let current_oid = current_commit.id();
2879
2880 let mut best_candidate = None;
2881 let mut best_distance = usize::MAX;
2882
2883 for branch in branches {
2884 if branch == current_branch
2886 || branch.contains("-v")
2887 || branch.ends_with("-v2")
2888 || branch.ends_with("-v3")
2889 {
2890 continue;
2891 }
2892
2893 if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
2894 if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
2895 if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
2897 if let Ok(distance) = self.count_commits_between(
2899 &merge_base_oid.to_string(),
2900 ¤t_commit_hash,
2901 ) {
2902 let is_likely_base = self.is_likely_base_branch(&branch);
2905 let adjusted_distance = if is_likely_base {
2906 distance
2907 } else {
2908 distance + 1000
2909 };
2910
2911 if adjusted_distance < best_distance {
2912 best_distance = adjusted_distance;
2913 best_candidate = Some(branch.clone());
2914 }
2915 }
2916 }
2917 }
2918 }
2919 }
2920
2921 if let Some(ref candidate) = best_candidate {
2922 tracing::debug!(
2923 "Detected parent branch '{}' with distance {}",
2924 candidate,
2925 best_distance
2926 );
2927 }
2928
2929 return Ok(best_candidate);
2930 }
2931
2932 tracing::debug!("Could not detect parent branch for '{}'", current_branch);
2933 Ok(None)
2934 }
2935
2936 fn is_likely_base_branch(&self, branch_name: &str) -> bool {
2938 let base_patterns = [
2939 "main",
2940 "master",
2941 "develop",
2942 "dev",
2943 "development",
2944 "staging",
2945 "stage",
2946 "release",
2947 "production",
2948 "prod",
2949 ];
2950
2951 base_patterns.contains(&branch_name)
2952 }
2953}
2954
2955#[cfg(test)]
2956mod tests {
2957 use super::*;
2958 use std::process::Command;
2959 use tempfile::TempDir;
2960
2961 fn create_test_repo() -> (TempDir, PathBuf) {
2962 let temp_dir = TempDir::new().unwrap();
2963 let repo_path = temp_dir.path().to_path_buf();
2964
2965 Command::new("git")
2967 .args(["init"])
2968 .current_dir(&repo_path)
2969 .output()
2970 .unwrap();
2971 Command::new("git")
2972 .args(["config", "user.name", "Test"])
2973 .current_dir(&repo_path)
2974 .output()
2975 .unwrap();
2976 Command::new("git")
2977 .args(["config", "user.email", "test@test.com"])
2978 .current_dir(&repo_path)
2979 .output()
2980 .unwrap();
2981
2982 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
2984 Command::new("git")
2985 .args(["add", "."])
2986 .current_dir(&repo_path)
2987 .output()
2988 .unwrap();
2989 Command::new("git")
2990 .args(["commit", "-m", "Initial commit"])
2991 .current_dir(&repo_path)
2992 .output()
2993 .unwrap();
2994
2995 (temp_dir, repo_path)
2996 }
2997
2998 fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
2999 let file_path = repo_path.join(filename);
3000 std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
3001
3002 Command::new("git")
3003 .args(["add", filename])
3004 .current_dir(repo_path)
3005 .output()
3006 .unwrap();
3007 Command::new("git")
3008 .args(["commit", "-m", message])
3009 .current_dir(repo_path)
3010 .output()
3011 .unwrap();
3012 }
3013
3014 #[test]
3015 fn test_repository_info() {
3016 let (_temp_dir, repo_path) = create_test_repo();
3017 let repo = GitRepository::open(&repo_path).unwrap();
3018
3019 let info = repo.get_info().unwrap();
3020 assert!(!info.is_dirty); assert!(
3022 info.head_branch == Some("master".to_string())
3023 || info.head_branch == Some("main".to_string()),
3024 "Expected default branch to be 'master' or 'main', got {:?}",
3025 info.head_branch
3026 );
3027 assert!(info.head_commit.is_some()); assert!(info.untracked_files.is_empty()); }
3030
3031 #[test]
3032 fn test_force_push_branch_basic() {
3033 let (_temp_dir, repo_path) = create_test_repo();
3034 let repo = GitRepository::open(&repo_path).unwrap();
3035
3036 let default_branch = repo.get_current_branch().unwrap();
3038
3039 create_commit(&repo_path, "Feature commit 1", "feature1.rs");
3041 Command::new("git")
3042 .args(["checkout", "-b", "source-branch"])
3043 .current_dir(&repo_path)
3044 .output()
3045 .unwrap();
3046 create_commit(&repo_path, "Feature commit 2", "feature2.rs");
3047
3048 Command::new("git")
3050 .args(["checkout", &default_branch])
3051 .current_dir(&repo_path)
3052 .output()
3053 .unwrap();
3054 Command::new("git")
3055 .args(["checkout", "-b", "target-branch"])
3056 .current_dir(&repo_path)
3057 .output()
3058 .unwrap();
3059 create_commit(&repo_path, "Target commit", "target.rs");
3060
3061 let result = repo.force_push_branch("target-branch", "source-branch");
3063
3064 assert!(result.is_ok() || result.is_err()); }
3068
3069 #[test]
3070 fn test_force_push_branch_nonexistent_branches() {
3071 let (_temp_dir, repo_path) = create_test_repo();
3072 let repo = GitRepository::open(&repo_path).unwrap();
3073
3074 let default_branch = repo.get_current_branch().unwrap();
3076
3077 let result = repo.force_push_branch("target", "nonexistent-source");
3079 assert!(result.is_err());
3080
3081 let result = repo.force_push_branch("nonexistent-target", &default_branch);
3083 assert!(result.is_err());
3084 }
3085
3086 #[test]
3087 fn test_force_push_workflow_simulation() {
3088 let (_temp_dir, repo_path) = create_test_repo();
3089 let repo = GitRepository::open(&repo_path).unwrap();
3090
3091 Command::new("git")
3094 .args(["checkout", "-b", "feature-auth"])
3095 .current_dir(&repo_path)
3096 .output()
3097 .unwrap();
3098 create_commit(&repo_path, "Add authentication", "auth.rs");
3099
3100 Command::new("git")
3102 .args(["checkout", "-b", "feature-auth-v2"])
3103 .current_dir(&repo_path)
3104 .output()
3105 .unwrap();
3106 create_commit(&repo_path, "Fix auth validation", "auth.rs");
3107
3108 let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
3110
3111 match result {
3113 Ok(_) => {
3114 Command::new("git")
3116 .args(["checkout", "feature-auth"])
3117 .current_dir(&repo_path)
3118 .output()
3119 .unwrap();
3120 let log_output = Command::new("git")
3121 .args(["log", "--oneline", "-2"])
3122 .current_dir(&repo_path)
3123 .output()
3124 .unwrap();
3125 let log_str = String::from_utf8_lossy(&log_output.stdout);
3126 assert!(
3127 log_str.contains("Fix auth validation")
3128 || log_str.contains("Add authentication")
3129 );
3130 }
3131 Err(_) => {
3132 }
3135 }
3136 }
3137
3138 #[test]
3139 fn test_branch_operations() {
3140 let (_temp_dir, repo_path) = create_test_repo();
3141 let repo = GitRepository::open(&repo_path).unwrap();
3142
3143 let current = repo.get_current_branch().unwrap();
3145 assert!(
3146 current == "master" || current == "main",
3147 "Expected default branch to be 'master' or 'main', got '{current}'"
3148 );
3149
3150 Command::new("git")
3152 .args(["checkout", "-b", "test-branch"])
3153 .current_dir(&repo_path)
3154 .output()
3155 .unwrap();
3156 let current = repo.get_current_branch().unwrap();
3157 assert_eq!(current, "test-branch");
3158 }
3159
3160 #[test]
3161 fn test_commit_operations() {
3162 let (_temp_dir, repo_path) = create_test_repo();
3163 let repo = GitRepository::open(&repo_path).unwrap();
3164
3165 let head = repo.get_head_commit().unwrap();
3167 assert_eq!(head.message().unwrap().trim(), "Initial commit");
3168
3169 let hash = head.id().to_string();
3171 let same_commit = repo.get_commit(&hash).unwrap();
3172 assert_eq!(head.id(), same_commit.id());
3173 }
3174
3175 #[test]
3176 fn test_checkout_safety_clean_repo() {
3177 let (_temp_dir, repo_path) = create_test_repo();
3178 let repo = GitRepository::open(&repo_path).unwrap();
3179
3180 create_commit(&repo_path, "Second commit", "test.txt");
3182 Command::new("git")
3183 .args(["checkout", "-b", "test-branch"])
3184 .current_dir(&repo_path)
3185 .output()
3186 .unwrap();
3187
3188 let safety_result = repo.check_checkout_safety("main");
3190 assert!(safety_result.is_ok());
3191 assert!(safety_result.unwrap().is_none()); }
3193
3194 #[test]
3195 fn test_checkout_safety_with_modified_files() {
3196 let (_temp_dir, repo_path) = create_test_repo();
3197 let repo = GitRepository::open(&repo_path).unwrap();
3198
3199 Command::new("git")
3201 .args(["checkout", "-b", "test-branch"])
3202 .current_dir(&repo_path)
3203 .output()
3204 .unwrap();
3205
3206 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3208
3209 let safety_result = repo.check_checkout_safety("main");
3211 assert!(safety_result.is_ok());
3212 let safety_info = safety_result.unwrap();
3213 assert!(safety_info.is_some());
3214
3215 let info = safety_info.unwrap();
3216 assert!(!info.modified_files.is_empty());
3217 assert!(info.modified_files.contains(&"README.md".to_string()));
3218 }
3219
3220 #[test]
3221 fn test_unsafe_checkout_methods() {
3222 let (_temp_dir, repo_path) = create_test_repo();
3223 let repo = GitRepository::open(&repo_path).unwrap();
3224
3225 create_commit(&repo_path, "Second commit", "test.txt");
3227 Command::new("git")
3228 .args(["checkout", "-b", "test-branch"])
3229 .current_dir(&repo_path)
3230 .output()
3231 .unwrap();
3232
3233 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3235
3236 let _result = repo.checkout_branch_unsafe("main");
3238 let head_commit = repo.get_head_commit().unwrap();
3243 let commit_hash = head_commit.id().to_string();
3244 let _result = repo.checkout_commit_unsafe(&commit_hash);
3245 }
3247
3248 #[test]
3249 fn test_get_modified_files() {
3250 let (_temp_dir, repo_path) = create_test_repo();
3251 let repo = GitRepository::open(&repo_path).unwrap();
3252
3253 let modified = repo.get_modified_files().unwrap();
3255 assert!(modified.is_empty());
3256
3257 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3259
3260 let modified = repo.get_modified_files().unwrap();
3262 assert_eq!(modified.len(), 1);
3263 assert!(modified.contains(&"README.md".to_string()));
3264 }
3265
3266 #[test]
3267 fn test_get_staged_files() {
3268 let (_temp_dir, repo_path) = create_test_repo();
3269 let repo = GitRepository::open(&repo_path).unwrap();
3270
3271 let staged = repo.get_staged_files().unwrap();
3273 assert!(staged.is_empty());
3274
3275 std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3277 Command::new("git")
3278 .args(["add", "staged.txt"])
3279 .current_dir(&repo_path)
3280 .output()
3281 .unwrap();
3282
3283 let staged = repo.get_staged_files().unwrap();
3285 assert_eq!(staged.len(), 1);
3286 assert!(staged.contains(&"staged.txt".to_string()));
3287 }
3288
3289 #[test]
3290 fn test_create_stash_fallback() {
3291 let (_temp_dir, repo_path) = create_test_repo();
3292 let repo = GitRepository::open(&repo_path).unwrap();
3293
3294 let result = repo.create_stash("test stash");
3296
3297 match result {
3299 Ok(stash_id) => {
3300 assert!(!stash_id.is_empty());
3302 assert!(stash_id.contains("stash") || stash_id.len() >= 7); }
3304 Err(error) => {
3305 let error_msg = error.to_string();
3307 assert!(
3308 error_msg.contains("No local changes to save")
3309 || error_msg.contains("git stash push")
3310 );
3311 }
3312 }
3313 }
3314
3315 #[test]
3316 fn test_delete_branch_unsafe() {
3317 let (_temp_dir, repo_path) = create_test_repo();
3318 let repo = GitRepository::open(&repo_path).unwrap();
3319
3320 create_commit(&repo_path, "Second commit", "test.txt");
3322 Command::new("git")
3323 .args(["checkout", "-b", "test-branch"])
3324 .current_dir(&repo_path)
3325 .output()
3326 .unwrap();
3327
3328 create_commit(&repo_path, "Branch-specific commit", "branch.txt");
3330
3331 Command::new("git")
3333 .args(["checkout", "main"])
3334 .current_dir(&repo_path)
3335 .output()
3336 .unwrap();
3337
3338 let result = repo.delete_branch_unsafe("test-branch");
3341 let _ = result; }
3345
3346 #[test]
3347 fn test_force_push_unsafe() {
3348 let (_temp_dir, repo_path) = create_test_repo();
3349 let repo = GitRepository::open(&repo_path).unwrap();
3350
3351 create_commit(&repo_path, "Second commit", "test.txt");
3353 Command::new("git")
3354 .args(["checkout", "-b", "test-branch"])
3355 .current_dir(&repo_path)
3356 .output()
3357 .unwrap();
3358
3359 let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
3362 }
3364
3365 #[test]
3366 fn test_cherry_pick_basic() {
3367 let (_temp_dir, repo_path) = create_test_repo();
3368 let repo = GitRepository::open(&repo_path).unwrap();
3369
3370 repo.create_branch("source", None).unwrap();
3372 repo.checkout_branch("source").unwrap();
3373
3374 std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
3375 Command::new("git")
3376 .args(["add", "."])
3377 .current_dir(&repo_path)
3378 .output()
3379 .unwrap();
3380
3381 Command::new("git")
3382 .args(["commit", "-m", "Cherry commit"])
3383 .current_dir(&repo_path)
3384 .output()
3385 .unwrap();
3386
3387 let cherry_commit = repo.get_head_commit_hash().unwrap();
3388
3389 Command::new("git")
3392 .args(["checkout", "-"])
3393 .current_dir(&repo_path)
3394 .output()
3395 .unwrap();
3396
3397 repo.create_branch("target", None).unwrap();
3398 repo.checkout_branch("target").unwrap();
3399
3400 let new_commit = repo.cherry_pick(&cherry_commit).unwrap();
3402
3403 repo.repo
3405 .find_commit(git2::Oid::from_str(&new_commit).unwrap())
3406 .unwrap();
3407
3408 assert!(
3410 repo_path.join("cherry.txt").exists(),
3411 "Cherry-picked file should exist"
3412 );
3413
3414 repo.checkout_branch("source").unwrap();
3416 let source_head = repo.get_head_commit_hash().unwrap();
3417 assert_eq!(
3418 source_head, cherry_commit,
3419 "Source branch should be unchanged"
3420 );
3421 }
3422
3423 #[test]
3424 fn test_cherry_pick_preserves_commit_message() {
3425 let (_temp_dir, repo_path) = create_test_repo();
3426 let repo = GitRepository::open(&repo_path).unwrap();
3427
3428 repo.create_branch("msg-test", None).unwrap();
3430 repo.checkout_branch("msg-test").unwrap();
3431
3432 std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
3433 Command::new("git")
3434 .args(["add", "."])
3435 .current_dir(&repo_path)
3436 .output()
3437 .unwrap();
3438
3439 let commit_msg = "Test: Special commit message\n\nWith body";
3440 Command::new("git")
3441 .args(["commit", "-m", commit_msg])
3442 .current_dir(&repo_path)
3443 .output()
3444 .unwrap();
3445
3446 let original_commit = repo.get_head_commit_hash().unwrap();
3447
3448 Command::new("git")
3450 .args(["checkout", "-"])
3451 .current_dir(&repo_path)
3452 .output()
3453 .unwrap();
3454 let new_commit = repo.cherry_pick(&original_commit).unwrap();
3455
3456 let output = Command::new("git")
3458 .args(["log", "-1", "--format=%B", &new_commit])
3459 .current_dir(&repo_path)
3460 .output()
3461 .unwrap();
3462
3463 let new_msg = String::from_utf8_lossy(&output.stdout);
3464 assert!(
3465 new_msg.contains("Special commit message"),
3466 "Should preserve commit message"
3467 );
3468 }
3469
3470 #[test]
3471 fn test_cherry_pick_handles_conflicts() {
3472 let (_temp_dir, repo_path) = create_test_repo();
3473 let repo = GitRepository::open(&repo_path).unwrap();
3474
3475 std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
3477 Command::new("git")
3478 .args(["add", "."])
3479 .current_dir(&repo_path)
3480 .output()
3481 .unwrap();
3482
3483 Command::new("git")
3484 .args(["commit", "-m", "Add conflict file"])
3485 .current_dir(&repo_path)
3486 .output()
3487 .unwrap();
3488
3489 repo.create_branch("conflict-branch", None).unwrap();
3491 repo.checkout_branch("conflict-branch").unwrap();
3492
3493 std::fs::write(repo_path.join("conflict.txt"), "Modified").unwrap();
3494 Command::new("git")
3495 .args(["add", "."])
3496 .current_dir(&repo_path)
3497 .output()
3498 .unwrap();
3499
3500 Command::new("git")
3501 .args(["commit", "-m", "Modify conflict file"])
3502 .current_dir(&repo_path)
3503 .output()
3504 .unwrap();
3505
3506 let conflict_commit = repo.get_head_commit_hash().unwrap();
3507
3508 Command::new("git")
3511 .args(["checkout", "-"])
3512 .current_dir(&repo_path)
3513 .output()
3514 .unwrap();
3515 std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
3516 Command::new("git")
3517 .args(["add", "."])
3518 .current_dir(&repo_path)
3519 .output()
3520 .unwrap();
3521
3522 Command::new("git")
3523 .args(["commit", "-m", "Different change"])
3524 .current_dir(&repo_path)
3525 .output()
3526 .unwrap();
3527
3528 let result = repo.cherry_pick(&conflict_commit);
3530 assert!(result.is_err(), "Cherry-pick with conflict should fail");
3531 }
3532
3533 #[test]
3534 fn test_reset_to_head_clears_staged_files() {
3535 let (_temp_dir, repo_path) = create_test_repo();
3536 let repo = GitRepository::open(&repo_path).unwrap();
3537
3538 std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
3540 std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();
3541
3542 Command::new("git")
3543 .args(["add", "staged1.txt", "staged2.txt"])
3544 .current_dir(&repo_path)
3545 .output()
3546 .unwrap();
3547
3548 let staged_before = repo.get_staged_files().unwrap();
3550 assert_eq!(staged_before.len(), 2, "Should have 2 staged files");
3551
3552 repo.reset_to_head().unwrap();
3554
3555 let staged_after = repo.get_staged_files().unwrap();
3557 assert_eq!(
3558 staged_after.len(),
3559 0,
3560 "Should have no staged files after reset"
3561 );
3562 }
3563
3564 #[test]
3565 fn test_reset_to_head_clears_modified_files() {
3566 let (_temp_dir, repo_path) = create_test_repo();
3567 let repo = GitRepository::open(&repo_path).unwrap();
3568
3569 std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();
3571
3572 Command::new("git")
3574 .args(["add", "README.md"])
3575 .current_dir(&repo_path)
3576 .output()
3577 .unwrap();
3578
3579 assert!(repo.is_dirty().unwrap(), "Repo should be dirty");
3581
3582 repo.reset_to_head().unwrap();
3584
3585 assert!(
3587 !repo.is_dirty().unwrap(),
3588 "Repo should be clean after reset"
3589 );
3590
3591 let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
3593 assert_eq!(
3594 content, "# Test",
3595 "File should be restored to original content"
3596 );
3597 }
3598
3599 #[test]
3600 fn test_reset_to_head_preserves_untracked_files() {
3601 let (_temp_dir, repo_path) = create_test_repo();
3602 let repo = GitRepository::open(&repo_path).unwrap();
3603
3604 std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();
3606
3607 std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3609 Command::new("git")
3610 .args(["add", "staged.txt"])
3611 .current_dir(&repo_path)
3612 .output()
3613 .unwrap();
3614
3615 repo.reset_to_head().unwrap();
3617
3618 assert!(
3620 repo_path.join("untracked.txt").exists(),
3621 "Untracked file should be preserved"
3622 );
3623
3624 assert!(
3626 !repo_path.join("staged.txt").exists(),
3627 "Staged but uncommitted file should be removed"
3628 );
3629 }
3630
3631 #[test]
3632 fn test_cherry_pick_does_not_modify_source() {
3633 let (_temp_dir, repo_path) = create_test_repo();
3634 let repo = GitRepository::open(&repo_path).unwrap();
3635
3636 repo.create_branch("feature", None).unwrap();
3638 repo.checkout_branch("feature").unwrap();
3639
3640 for i in 1..=3 {
3642 std::fs::write(
3643 repo_path.join(format!("file{i}.txt")),
3644 format!("Content {i}"),
3645 )
3646 .unwrap();
3647 Command::new("git")
3648 .args(["add", "."])
3649 .current_dir(&repo_path)
3650 .output()
3651 .unwrap();
3652
3653 Command::new("git")
3654 .args(["commit", "-m", &format!("Commit {i}")])
3655 .current_dir(&repo_path)
3656 .output()
3657 .unwrap();
3658 }
3659
3660 let source_commits = Command::new("git")
3662 .args(["log", "--format=%H", "feature"])
3663 .current_dir(&repo_path)
3664 .output()
3665 .unwrap();
3666 let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();
3667
3668 let commits: Vec<&str> = source_state.lines().collect();
3670 let middle_commit = commits[1];
3671
3672 Command::new("git")
3674 .args(["checkout", "-"])
3675 .current_dir(&repo_path)
3676 .output()
3677 .unwrap();
3678 repo.create_branch("target", None).unwrap();
3679 repo.checkout_branch("target").unwrap();
3680
3681 repo.cherry_pick(middle_commit).unwrap();
3682
3683 let after_commits = Command::new("git")
3685 .args(["log", "--format=%H", "feature"])
3686 .current_dir(&repo_path)
3687 .output()
3688 .unwrap();
3689 let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();
3690
3691 assert_eq!(
3692 source_state, after_state,
3693 "Source branch should be completely unchanged after cherry-pick"
3694 );
3695 }
3696
3697 #[test]
3698 fn test_detect_parent_branch() {
3699 let (_temp_dir, repo_path) = create_test_repo();
3700 let repo = GitRepository::open(&repo_path).unwrap();
3701
3702 repo.create_branch("dev123", None).unwrap();
3704 repo.checkout_branch("dev123").unwrap();
3705 create_commit(&repo_path, "Base commit on dev123", "base.txt");
3706
3707 repo.create_branch("feature-branch", None).unwrap();
3709 repo.checkout_branch("feature-branch").unwrap();
3710 create_commit(&repo_path, "Feature commit", "feature.txt");
3711
3712 let detected_parent = repo.detect_parent_branch().unwrap();
3714
3715 assert!(detected_parent.is_some(), "Should detect a parent branch");
3718
3719 let parent = detected_parent.unwrap();
3722 assert!(
3723 parent == "dev123" || parent == "main" || parent == "master",
3724 "Parent should be dev123, main, or master, got: {parent}"
3725 );
3726 }
3727}