1use crate::bitbucket::BitbucketIntegration;
2use crate::cli::output::Output;
3use crate::errors::{CascadeError, Result};
4use crate::git::{find_repository_root, GitRepository};
5use crate::stack::{CleanupManager, CleanupOptions, CleanupResult, StackManager, StackStatus};
6use clap::{Subcommand, ValueEnum};
7use dialoguer::{theme::ColorfulTheme, Confirm};
8use std::env;
10use tracing::{debug, warn};
11
12#[derive(ValueEnum, Clone, Debug)]
14pub enum RebaseStrategyArg {
15 ForcePush,
17 Interactive,
19}
20
21#[derive(ValueEnum, Clone, Debug)]
22pub enum MergeStrategyArg {
23 Merge,
25 Squash,
27 FastForward,
29}
30
31impl From<MergeStrategyArg> for crate::bitbucket::pull_request::MergeStrategy {
32 fn from(arg: MergeStrategyArg) -> Self {
33 match arg {
34 MergeStrategyArg::Merge => Self::Merge,
35 MergeStrategyArg::Squash => Self::Squash,
36 MergeStrategyArg::FastForward => Self::FastForward,
37 }
38 }
39}
40
41#[derive(Debug, Subcommand)]
42pub enum StackAction {
43 Create {
45 name: String,
47 #[arg(long, short)]
49 base: Option<String>,
50 #[arg(long, short)]
52 description: Option<String>,
53 },
54
55 List {
57 #[arg(long, short)]
59 verbose: bool,
60 #[arg(long)]
62 active: bool,
63 #[arg(long)]
65 format: Option<String>,
66 },
67
68 Switch {
70 name: String,
72 },
73
74 Deactivate {
76 #[arg(long)]
78 force: bool,
79 },
80
81 Show {
83 #[arg(short, long)]
85 verbose: bool,
86 #[arg(short, long)]
88 mergeable: bool,
89 },
90
91 Push {
93 #[arg(long, short)]
95 branch: Option<String>,
96 #[arg(long, short)]
98 message: Option<String>,
99 #[arg(long)]
101 commit: Option<String>,
102 #[arg(long)]
104 since: Option<String>,
105 #[arg(long)]
107 commits: Option<String>,
108 #[arg(long, num_args = 0..=1, default_missing_value = "0")]
110 squash: Option<usize>,
111 #[arg(long)]
113 squash_since: Option<String>,
114 #[arg(long)]
116 auto_branch: bool,
117 #[arg(long)]
119 allow_base_branch: bool,
120 #[arg(long)]
122 dry_run: bool,
123 },
124
125 Pop {
127 #[arg(long)]
129 keep_branch: bool,
130 },
131
132 Submit {
134 entry: Option<usize>,
136 #[arg(long, short)]
138 title: Option<String>,
139 #[arg(long, short)]
141 description: Option<String>,
142 #[arg(long)]
144 range: Option<String>,
145 #[arg(long)]
147 draft: bool,
148 },
149
150 Status {
152 name: Option<String>,
154 },
155
156 Prs {
158 #[arg(long)]
160 state: Option<String>,
161 #[arg(long, short)]
163 verbose: bool,
164 },
165
166 Check {
168 #[arg(long)]
170 force: bool,
171 },
172
173 Sync {
175 #[arg(long)]
177 force: bool,
178 #[arg(long)]
180 skip_cleanup: bool,
181 #[arg(long, short)]
183 interactive: bool,
184 },
185
186 Rebase {
188 #[arg(long, short)]
190 interactive: bool,
191 #[arg(long)]
193 onto: Option<String>,
194 #[arg(long, value_enum)]
196 strategy: Option<RebaseStrategyArg>,
197 },
198
199 ContinueRebase,
201
202 AbortRebase,
204
205 RebaseStatus,
207
208 Delete {
210 name: String,
212 #[arg(long)]
214 force: bool,
215 },
216
217 Validate {
229 name: Option<String>,
231 #[arg(long)]
233 fix: Option<String>,
234 },
235
236 Land {
238 entry: Option<usize>,
240 #[arg(short, long)]
242 force: bool,
243 #[arg(short, long)]
245 dry_run: bool,
246 #[arg(long)]
248 auto: bool,
249 #[arg(long)]
251 wait_for_builds: bool,
252 #[arg(long, value_enum, default_value = "squash")]
254 strategy: Option<MergeStrategyArg>,
255 #[arg(long, default_value = "1800")]
257 build_timeout: u64,
258 },
259
260 AutoLand {
262 #[arg(short, long)]
264 force: bool,
265 #[arg(short, long)]
267 dry_run: bool,
268 #[arg(long)]
270 wait_for_builds: bool,
271 #[arg(long, value_enum, default_value = "squash")]
273 strategy: Option<MergeStrategyArg>,
274 #[arg(long, default_value = "1800")]
276 build_timeout: u64,
277 },
278
279 ListPrs {
281 #[arg(short, long)]
283 state: Option<String>,
284 #[arg(short, long)]
286 verbose: bool,
287 },
288
289 ContinueLand,
291
292 AbortLand,
294
295 LandStatus,
297
298 Cleanup {
300 #[arg(long)]
302 dry_run: bool,
303 #[arg(long)]
305 force: bool,
306 #[arg(long)]
308 include_stale: bool,
309 #[arg(long, default_value = "30")]
311 stale_days: u32,
312 #[arg(long)]
314 cleanup_remote: bool,
315 #[arg(long)]
317 include_non_stack: bool,
318 #[arg(long)]
320 verbose: bool,
321 },
322
323 Repair,
325}
326
327pub async fn run(action: StackAction) -> Result<()> {
328 match action {
329 StackAction::Create {
330 name,
331 base,
332 description,
333 } => create_stack(name, base, description).await,
334 StackAction::List {
335 verbose,
336 active,
337 format,
338 } => list_stacks(verbose, active, format).await,
339 StackAction::Switch { name } => switch_stack(name).await,
340 StackAction::Deactivate { force } => deactivate_stack(force).await,
341 StackAction::Show { verbose, mergeable } => show_stack(verbose, mergeable).await,
342 StackAction::Push {
343 branch,
344 message,
345 commit,
346 since,
347 commits,
348 squash,
349 squash_since,
350 auto_branch,
351 allow_base_branch,
352 dry_run,
353 } => {
354 push_to_stack(
355 branch,
356 message,
357 commit,
358 since,
359 commits,
360 squash,
361 squash_since,
362 auto_branch,
363 allow_base_branch,
364 dry_run,
365 )
366 .await
367 }
368 StackAction::Pop { keep_branch } => pop_from_stack(keep_branch).await,
369 StackAction::Submit {
370 entry,
371 title,
372 description,
373 range,
374 draft,
375 } => submit_entry(entry, title, description, range, draft).await,
376 StackAction::Status { name } => check_stack_status(name).await,
377 StackAction::Prs { state, verbose } => list_pull_requests(state, verbose).await,
378 StackAction::Check { force } => check_stack(force).await,
379 StackAction::Sync {
380 force,
381 skip_cleanup,
382 interactive,
383 } => sync_stack(force, skip_cleanup, interactive).await,
384 StackAction::Rebase {
385 interactive,
386 onto,
387 strategy,
388 } => rebase_stack(interactive, onto, strategy).await,
389 StackAction::ContinueRebase => continue_rebase().await,
390 StackAction::AbortRebase => abort_rebase().await,
391 StackAction::RebaseStatus => rebase_status().await,
392 StackAction::Delete { name, force } => delete_stack(name, force).await,
393 StackAction::Validate { name, fix } => validate_stack(name, fix).await,
394 StackAction::Land {
395 entry,
396 force,
397 dry_run,
398 auto,
399 wait_for_builds,
400 strategy,
401 build_timeout,
402 } => {
403 land_stack(
404 entry,
405 force,
406 dry_run,
407 auto,
408 wait_for_builds,
409 strategy,
410 build_timeout,
411 )
412 .await
413 }
414 StackAction::AutoLand {
415 force,
416 dry_run,
417 wait_for_builds,
418 strategy,
419 build_timeout,
420 } => auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await,
421 StackAction::ListPrs { state, verbose } => list_pull_requests(state, verbose).await,
422 StackAction::ContinueLand => continue_land().await,
423 StackAction::AbortLand => abort_land().await,
424 StackAction::LandStatus => land_status().await,
425 StackAction::Cleanup {
426 dry_run,
427 force,
428 include_stale,
429 stale_days,
430 cleanup_remote,
431 include_non_stack,
432 verbose,
433 } => {
434 cleanup_branches(
435 dry_run,
436 force,
437 include_stale,
438 stale_days,
439 cleanup_remote,
440 include_non_stack,
441 verbose,
442 )
443 .await
444 }
445 StackAction::Repair => repair_stack_data().await,
446 }
447}
448
449pub async fn show(verbose: bool, mergeable: bool) -> Result<()> {
451 show_stack(verbose, mergeable).await
452}
453
454#[allow(clippy::too_many_arguments)]
455pub async fn push(
456 branch: Option<String>,
457 message: Option<String>,
458 commit: Option<String>,
459 since: Option<String>,
460 commits: Option<String>,
461 squash: Option<usize>,
462 squash_since: Option<String>,
463 auto_branch: bool,
464 allow_base_branch: bool,
465 dry_run: bool,
466) -> Result<()> {
467 push_to_stack(
468 branch,
469 message,
470 commit,
471 since,
472 commits,
473 squash,
474 squash_since,
475 auto_branch,
476 allow_base_branch,
477 dry_run,
478 )
479 .await
480}
481
482pub async fn pop(keep_branch: bool) -> Result<()> {
483 pop_from_stack(keep_branch).await
484}
485
486pub async fn land(
487 entry: Option<usize>,
488 force: bool,
489 dry_run: bool,
490 auto: bool,
491 wait_for_builds: bool,
492 strategy: Option<MergeStrategyArg>,
493 build_timeout: u64,
494) -> Result<()> {
495 land_stack(
496 entry,
497 force,
498 dry_run,
499 auto,
500 wait_for_builds,
501 strategy,
502 build_timeout,
503 )
504 .await
505}
506
507pub async fn autoland(
508 force: bool,
509 dry_run: bool,
510 wait_for_builds: bool,
511 strategy: Option<MergeStrategyArg>,
512 build_timeout: u64,
513) -> Result<()> {
514 auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await
515}
516
517pub async fn sync(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
518 sync_stack(force, skip_cleanup, interactive).await
519}
520
521pub async fn rebase(
522 interactive: bool,
523 onto: Option<String>,
524 strategy: Option<RebaseStrategyArg>,
525) -> Result<()> {
526 rebase_stack(interactive, onto, strategy).await
527}
528
529pub async fn deactivate(force: bool) -> Result<()> {
530 deactivate_stack(force).await
531}
532
533pub async fn switch(name: String) -> Result<()> {
534 switch_stack(name).await
535}
536
537async fn create_stack(
538 name: String,
539 base: Option<String>,
540 description: Option<String>,
541) -> Result<()> {
542 let current_dir = env::current_dir()
543 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
544
545 let repo_root = find_repository_root(¤t_dir)
546 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
547
548 let mut manager = StackManager::new(&repo_root)?;
549 let stack_id = manager.create_stack(name.clone(), base.clone(), description.clone())?;
550
551 let stack = manager
553 .get_stack(&stack_id)
554 .ok_or_else(|| CascadeError::config("Failed to get created stack"))?;
555
556 Output::stack_info(
558 &name,
559 &stack_id.to_string(),
560 &stack.base_branch,
561 stack.working_branch.as_deref(),
562 true, );
564
565 if let Some(desc) = description {
566 Output::sub_item(format!("Description: {desc}"));
567 }
568
569 if stack.working_branch.is_none() {
571 Output::warning(format!(
572 "You're currently on the base branch '{}'",
573 stack.base_branch
574 ));
575 Output::next_steps(&[
576 &format!("Create a feature branch: git checkout -b {name}"),
577 "Make changes and commit them",
578 "Run 'ca push' to add commits to this stack",
579 ]);
580 } else {
581 Output::next_steps(&[
582 "Make changes and commit them",
583 "Run 'ca push' to add commits to this stack",
584 "Use 'ca submit' when ready to create pull requests",
585 ]);
586 }
587
588 Ok(())
589}
590
591async fn list_stacks(verbose: bool, _active: bool, _format: Option<String>) -> Result<()> {
592 let current_dir = env::current_dir()
593 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
594
595 let repo_root = find_repository_root(¤t_dir)
596 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
597
598 let manager = StackManager::new(&repo_root)?;
599 let stacks = manager.list_stacks();
600
601 if stacks.is_empty() {
602 Output::info("No stacks found. Create one with: ca stack create <name>");
603 return Ok(());
604 }
605
606 println!("📚 Stacks:");
607 for (stack_id, name, status, entry_count, active_marker) in stacks {
608 let status_icon = match status {
609 StackStatus::Clean => "✅",
610 StackStatus::Dirty => "🔄",
611 StackStatus::OutOfSync => "⚠️",
612 StackStatus::Conflicted => "❌",
613 StackStatus::Rebasing => "🔀",
614 StackStatus::NeedsSync => "🔄",
615 StackStatus::Corrupted => "💥",
616 };
617
618 let active_indicator = if active_marker.is_some() {
619 " (active)"
620 } else {
621 ""
622 };
623
624 let stack = manager.get_stack(&stack_id);
626
627 if verbose {
628 println!(" {status_icon} {name} [{entry_count}]{active_indicator}");
629 println!(" ID: {stack_id}");
630 if let Some(stack_meta) = manager.get_stack_metadata(&stack_id) {
631 println!(" Base: {}", stack_meta.base_branch);
632 if let Some(desc) = &stack_meta.description {
633 println!(" Description: {desc}");
634 }
635 println!(
636 " Commits: {} total, {} submitted",
637 stack_meta.total_commits, stack_meta.submitted_commits
638 );
639 if stack_meta.has_conflicts {
640 println!(" ⚠️ Has conflicts");
641 }
642 }
643
644 if let Some(stack_obj) = stack {
646 if !stack_obj.entries.is_empty() {
647 println!(" Branches:");
648 for (i, entry) in stack_obj.entries.iter().enumerate() {
649 let entry_num = i + 1;
650 let submitted_indicator = if entry.is_submitted { "📤" } else { "📝" };
651 let branch_name = &entry.branch;
652 let short_message = if entry.message.len() > 40 {
653 format!("{}...", &entry.message[..37])
654 } else {
655 entry.message.clone()
656 };
657 println!(" {entry_num}. {submitted_indicator} {branch_name} - {short_message}");
658 }
659 }
660 }
661 println!();
662 } else {
663 let branch_info = if let Some(stack_obj) = stack {
665 if stack_obj.entries.is_empty() {
666 String::new()
667 } else if stack_obj.entries.len() == 1 {
668 format!(" → {}", stack_obj.entries[0].branch)
669 } else {
670 let first_branch = &stack_obj.entries[0].branch;
671 let last_branch = &stack_obj.entries.last().unwrap().branch;
672 format!(" → {first_branch} … {last_branch}")
673 }
674 } else {
675 String::new()
676 };
677
678 println!(" {status_icon} {name} [{entry_count}]{branch_info}{active_indicator}");
679 }
680 }
681
682 if !verbose {
683 println!("\nUse --verbose for more details");
684 }
685
686 Ok(())
687}
688
689async fn switch_stack(name: String) -> Result<()> {
690 let current_dir = env::current_dir()
691 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
692
693 let repo_root = find_repository_root(¤t_dir)
694 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
695
696 let mut manager = StackManager::new(&repo_root)?;
697 let repo = GitRepository::open(&repo_root)?;
698
699 let stack = manager
701 .get_stack_by_name(&name)
702 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
703
704 if let Some(working_branch) = &stack.working_branch {
706 let current_branch = repo.get_current_branch().ok();
708
709 if current_branch.as_ref() != Some(working_branch) {
710 Output::progress(format!(
711 "Switching to stack working branch: {working_branch}"
712 ));
713
714 if repo.branch_exists(working_branch) {
716 match repo.checkout_branch(working_branch) {
717 Ok(_) => {
718 Output::success(format!("Checked out branch: {working_branch}"));
719 }
720 Err(e) => {
721 Output::warning(format!("Failed to checkout '{working_branch}': {e}"));
722 Output::sub_item("Stack activated but stayed on current branch");
723 Output::sub_item(format!(
724 "You can manually checkout with: git checkout {working_branch}"
725 ));
726 }
727 }
728 } else {
729 Output::warning(format!(
730 "Stack working branch '{working_branch}' doesn't exist locally"
731 ));
732 Output::sub_item("Stack activated but stayed on current branch");
733 Output::sub_item(format!(
734 "You may need to fetch from remote: git fetch origin {working_branch}"
735 ));
736 }
737 } else {
738 Output::success(format!("Already on stack working branch: {working_branch}"));
739 }
740 } else {
741 Output::warning(format!("Stack '{name}' has no working branch set"));
743 Output::sub_item(
744 "This typically happens when a stack was created while on the base branch",
745 );
746
747 Output::tip("To start working on this stack:");
748 Output::bullet(format!("Create a feature branch: git checkout -b {name}"));
749 Output::bullet("The stack will automatically track this as its working branch");
750 Output::bullet("Then use 'ca push' to add commits to the stack");
751
752 Output::sub_item(format!("Base branch: {}", stack.base_branch));
753 }
754
755 manager.set_active_stack_by_name(&name)?;
757 Output::success(format!("Switched to stack '{name}'"));
758
759 Ok(())
760}
761
762async fn deactivate_stack(force: bool) -> Result<()> {
763 let current_dir = env::current_dir()
764 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
765
766 let repo_root = find_repository_root(¤t_dir)
767 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
768
769 let mut manager = StackManager::new(&repo_root)?;
770
771 let active_stack = manager.get_active_stack();
772
773 if active_stack.is_none() {
774 Output::info("No active stack to deactivate");
775 return Ok(());
776 }
777
778 let stack_name = active_stack.unwrap().name.clone();
779
780 if !force {
781 Output::warning(format!(
782 "This will deactivate stack '{stack_name}' and return to normal Git workflow"
783 ));
784 Output::sub_item(format!(
785 "You can reactivate it later with 'ca stacks switch {stack_name}'"
786 ));
787 let should_deactivate = Confirm::with_theme(&ColorfulTheme::default())
789 .with_prompt("Continue with deactivation?")
790 .default(false)
791 .interact()
792 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
793
794 if !should_deactivate {
795 Output::info("Cancelled deactivation");
796 return Ok(());
797 }
798 }
799
800 manager.set_active_stack(None)?;
802
803 Output::success(format!("Deactivated stack '{stack_name}'"));
804 Output::sub_item("Stack management is now OFF - you can use normal Git workflow");
805 Output::sub_item(format!("To reactivate: ca stacks switch {stack_name}"));
806
807 Ok(())
808}
809
810async fn show_stack(verbose: bool, show_mergeable: bool) -> Result<()> {
811 let current_dir = env::current_dir()
812 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
813
814 let repo_root = find_repository_root(¤t_dir)
815 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
816
817 let stack_manager = StackManager::new(&repo_root)?;
818
819 let (stack_id, stack_name, stack_base, stack_working, stack_entries) = {
821 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
822 CascadeError::config(
823 "No active stack. Use 'ca stacks create' or 'ca stacks switch' to select a stack"
824 .to_string(),
825 )
826 })?;
827
828 (
829 active_stack.id,
830 active_stack.name.clone(),
831 active_stack.base_branch.clone(),
832 active_stack.working_branch.clone(),
833 active_stack.entries.clone(),
834 )
835 };
836
837 Output::stack_info(
839 &stack_name,
840 &stack_id.to_string(),
841 &stack_base,
842 stack_working.as_deref(),
843 true, );
845 Output::sub_item(format!("Total entries: {}", stack_entries.len()));
846
847 if stack_entries.is_empty() {
848 Output::info("No entries in this stack yet");
849 Output::tip("Use 'ca push' to add commits to this stack");
850 return Ok(());
851 }
852
853 Output::section("Stack Entries");
855 for (i, entry) in stack_entries.iter().enumerate() {
856 let entry_num = i + 1;
857 let short_hash = entry.short_hash();
858 let short_msg = entry.short_message(50);
859
860 let metadata = stack_manager.get_repository_metadata();
862 let source_branch_info = if let Some(commit_meta) = metadata.get_commit(&entry.commit_hash)
863 {
864 if commit_meta.source_branch != commit_meta.branch
865 && !commit_meta.source_branch.is_empty()
866 {
867 format!(" (from {})", commit_meta.source_branch)
868 } else {
869 String::new()
870 }
871 } else {
872 String::new()
873 };
874
875 let status_icon = if entry.is_submitted {
876 "[submitted]"
877 } else {
878 "[pending]"
879 };
880 Output::numbered_item(
881 entry_num,
882 format!("{short_hash} {status_icon} {short_msg}{source_branch_info}"),
883 );
884
885 if verbose {
886 Output::sub_item(format!("Branch: {}", entry.branch));
887 Output::sub_item(format!(
888 "Created: {}",
889 entry.created_at.format("%Y-%m-%d %H:%M")
890 ));
891 if let Some(pr_id) = &entry.pull_request_id {
892 Output::sub_item(format!("PR: #{pr_id}"));
893 }
894
895 Output::sub_item("Commit Message:");
897 let lines: Vec<&str> = entry.message.lines().collect();
898 for line in lines {
899 Output::sub_item(format!(" {line}"));
900 }
901 }
902 }
903
904 if show_mergeable {
906 Output::section("Mergability Status");
907
908 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
910 let config_path = config_dir.join("config.json");
911 let settings = crate::config::Settings::load_from_file(&config_path)?;
912
913 let cascade_config = crate::config::CascadeConfig {
914 bitbucket: Some(settings.bitbucket.clone()),
915 git: settings.git.clone(),
916 auth: crate::config::AuthConfig::default(),
917 cascade: settings.cascade.clone(),
918 };
919
920 let integration =
921 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
922
923 match integration.check_enhanced_stack_status(&stack_id).await {
924 Ok(status) => {
925 Output::bullet(format!("Total entries: {}", status.total_entries));
926 Output::bullet(format!("Submitted: {}", status.submitted_entries));
927 Output::bullet(format!("Open PRs: {}", status.open_prs));
928 Output::bullet(format!("Merged PRs: {}", status.merged_prs));
929 Output::bullet(format!("Declined PRs: {}", status.declined_prs));
930 Output::bullet(format!(
931 "Completion: {:.1}%",
932 status.completion_percentage()
933 ));
934
935 if !status.enhanced_statuses.is_empty() {
936 Output::section("Pull Request Status");
937 let mut ready_to_land = 0;
938
939 for enhanced in &status.enhanced_statuses {
940 let status_display = enhanced.get_display_status();
941 let ready_icon = if enhanced.is_ready_to_land() {
942 ready_to_land += 1;
943 "[READY]"
944 } else {
945 "[PENDING]"
946 };
947
948 Output::bullet(format!(
949 "{} PR #{}: {} ({})",
950 ready_icon, enhanced.pr.id, enhanced.pr.title, status_display
951 ));
952
953 if verbose {
954 println!(
955 " {} -> {}",
956 enhanced.pr.from_ref.display_id, enhanced.pr.to_ref.display_id
957 );
958
959 if !enhanced.is_ready_to_land() {
961 let blocking = enhanced.get_blocking_reasons();
962 if !blocking.is_empty() {
963 println!(" Blocking: {}", blocking.join(", "));
964 }
965 }
966
967 println!(
969 " Reviews: {} approval{}",
970 enhanced.review_status.current_approvals,
971 if enhanced.review_status.current_approvals == 1 {
972 ""
973 } else {
974 "s"
975 }
976 );
977
978 if enhanced.review_status.needs_work_count > 0 {
979 println!(
980 " {} reviewers requested changes",
981 enhanced.review_status.needs_work_count
982 );
983 }
984
985 if let Some(build) = &enhanced.build_status {
987 let build_icon = match build.state {
988 crate::bitbucket::pull_request::BuildState::Successful => "✅",
989 crate::bitbucket::pull_request::BuildState::Failed => "❌",
990 crate::bitbucket::pull_request::BuildState::InProgress => "🔄",
991 _ => "⚪",
992 };
993 println!(" Build: {} {:?}", build_icon, build.state);
994 }
995
996 if let Some(url) = enhanced.pr.web_url() {
997 println!(" URL: {url}");
998 }
999 println!();
1000 }
1001 }
1002
1003 if ready_to_land > 0 {
1004 println!(
1005 "\n🎯 {} PR{} ready to land! Use 'ca land' to land them all.",
1006 ready_to_land,
1007 if ready_to_land == 1 { " is" } else { "s are" }
1008 );
1009 }
1010 }
1011 }
1012 Err(e) => {
1013 warn!("Failed to get enhanced stack status: {}", e);
1014 println!(" ⚠️ Could not fetch mergability status");
1015 println!(" Use 'ca stack show --verbose' for basic PR information");
1016 }
1017 }
1018 } else {
1019 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1021 let config_path = config_dir.join("config.json");
1022 let settings = crate::config::Settings::load_from_file(&config_path)?;
1023
1024 let cascade_config = crate::config::CascadeConfig {
1025 bitbucket: Some(settings.bitbucket.clone()),
1026 git: settings.git.clone(),
1027 auth: crate::config::AuthConfig::default(),
1028 cascade: settings.cascade.clone(),
1029 };
1030
1031 let integration =
1032 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1033
1034 match integration.check_stack_status(&stack_id).await {
1035 Ok(status) => {
1036 println!("\n📊 Pull Request Status:");
1037 println!(" Total entries: {}", status.total_entries);
1038 println!(" Submitted: {}", status.submitted_entries);
1039 println!(" Open PRs: {}", status.open_prs);
1040 println!(" Merged PRs: {}", status.merged_prs);
1041 println!(" Declined PRs: {}", status.declined_prs);
1042 println!(" Completion: {:.1}%", status.completion_percentage());
1043
1044 if !status.pull_requests.is_empty() {
1045 println!("\n📋 Pull Requests:");
1046 for pr in &status.pull_requests {
1047 let state_icon = match pr.state {
1048 crate::bitbucket::PullRequestState::Open => "🔄",
1049 crate::bitbucket::PullRequestState::Merged => "✅",
1050 crate::bitbucket::PullRequestState::Declined => "❌",
1051 };
1052 println!(
1053 " {} PR #{}: {} ({} -> {})",
1054 state_icon,
1055 pr.id,
1056 pr.title,
1057 pr.from_ref.display_id,
1058 pr.to_ref.display_id
1059 );
1060 if let Some(url) = pr.web_url() {
1061 println!(" URL: {url}");
1062 }
1063 }
1064 }
1065
1066 println!("\n💡 Use 'ca stack --mergeable' to see detailed status including build and review information");
1067 }
1068 Err(e) => {
1069 warn!("Failed to check stack status: {}", e);
1070 }
1071 }
1072 }
1073
1074 Ok(())
1075}
1076
1077#[allow(clippy::too_many_arguments)]
1078async fn push_to_stack(
1079 branch: Option<String>,
1080 message: Option<String>,
1081 commit: Option<String>,
1082 since: Option<String>,
1083 commits: Option<String>,
1084 squash: Option<usize>,
1085 squash_since: Option<String>,
1086 auto_branch: bool,
1087 allow_base_branch: bool,
1088 dry_run: bool,
1089) -> Result<()> {
1090 let current_dir = env::current_dir()
1091 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1092
1093 let repo_root = find_repository_root(¤t_dir)
1094 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1095
1096 let mut manager = StackManager::new(&repo_root)?;
1097 let repo = GitRepository::open(&repo_root)?;
1098
1099 if !manager.check_for_branch_change()? {
1101 return Ok(()); }
1103
1104 let active_stack = manager.get_active_stack().ok_or_else(|| {
1106 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1107 })?;
1108
1109 let current_branch = repo.get_current_branch()?;
1111 let base_branch = &active_stack.base_branch;
1112
1113 if current_branch == *base_branch {
1114 Output::error(format!(
1115 "You're currently on the base branch '{base_branch}'"
1116 ));
1117 Output::sub_item("Making commits directly on the base branch is not recommended.");
1118 Output::sub_item("This can pollute the base branch with work-in-progress commits.");
1119
1120 if allow_base_branch {
1122 Output::warning("Proceeding anyway due to --allow-base-branch flag");
1123 } else {
1124 let has_changes = repo.is_dirty()?;
1126
1127 if has_changes {
1128 if auto_branch {
1129 let feature_branch = format!("feature/{}-work", active_stack.name);
1131 Output::progress(format!(
1132 "Auto-creating feature branch '{feature_branch}'..."
1133 ));
1134
1135 repo.create_branch(&feature_branch, None)?;
1136 repo.checkout_branch(&feature_branch)?;
1137
1138 println!("✅ Created and switched to '{feature_branch}'");
1139 println!(" You can now commit and push your changes safely");
1140
1141 } else {
1143 println!("\n💡 You have uncommitted changes. Here are your options:");
1144 println!(" 1. Create a feature branch first:");
1145 println!(" git checkout -b feature/my-work");
1146 println!(" git commit -am \"your work\"");
1147 println!(" ca push");
1148 println!("\n 2. Auto-create a branch (recommended):");
1149 println!(" ca push --auto-branch");
1150 println!("\n 3. Force push to base branch (dangerous):");
1151 println!(" ca push --allow-base-branch");
1152
1153 return Err(CascadeError::config(
1154 "Refusing to push uncommitted changes from base branch. Use one of the options above."
1155 ));
1156 }
1157 } else {
1158 let commits_to_check = if let Some(commits_str) = &commits {
1160 commits_str
1161 .split(',')
1162 .map(|s| s.trim().to_string())
1163 .collect::<Vec<String>>()
1164 } else if let Some(since_ref) = &since {
1165 let since_commit = repo.resolve_reference(since_ref)?;
1166 let head_commit = repo.get_head_commit()?;
1167 let commits = repo.get_commits_between(
1168 &since_commit.id().to_string(),
1169 &head_commit.id().to_string(),
1170 )?;
1171 commits.into_iter().map(|c| c.id().to_string()).collect()
1172 } else if commit.is_none() {
1173 let mut unpushed = Vec::new();
1174 let head_commit = repo.get_head_commit()?;
1175 let mut current_commit = head_commit;
1176
1177 loop {
1178 let commit_hash = current_commit.id().to_string();
1179 let already_in_stack = active_stack
1180 .entries
1181 .iter()
1182 .any(|entry| entry.commit_hash == commit_hash);
1183
1184 if already_in_stack {
1185 break;
1186 }
1187
1188 unpushed.push(commit_hash);
1189
1190 if let Some(parent) = current_commit.parents().next() {
1191 current_commit = parent;
1192 } else {
1193 break;
1194 }
1195 }
1196
1197 unpushed.reverse();
1198 unpushed
1199 } else {
1200 vec![repo.get_head_commit()?.id().to_string()]
1201 };
1202
1203 if !commits_to_check.is_empty() {
1204 if auto_branch {
1205 let feature_branch = format!("feature/{}-work", active_stack.name);
1207 Output::progress(format!(
1208 "Auto-creating feature branch '{feature_branch}'..."
1209 ));
1210
1211 repo.create_branch(&feature_branch, Some(base_branch))?;
1212 repo.checkout_branch(&feature_branch)?;
1213
1214 println!(
1216 "🍒 Cherry-picking {} commit(s) to new branch...",
1217 commits_to_check.len()
1218 );
1219 for commit_hash in &commits_to_check {
1220 match repo.cherry_pick(commit_hash) {
1221 Ok(_) => println!(" ✅ Cherry-picked {}", &commit_hash[..8]),
1222 Err(e) => {
1223 println!(
1224 " ❌ Failed to cherry-pick {}: {}",
1225 &commit_hash[..8],
1226 e
1227 );
1228 println!(" 💡 You may need to resolve conflicts manually");
1229 return Err(CascadeError::branch(format!(
1230 "Failed to cherry-pick commit {commit_hash}: {e}"
1231 )));
1232 }
1233 }
1234 }
1235
1236 println!(
1237 "✅ Successfully moved {} commit(s) to '{feature_branch}'",
1238 commits_to_check.len()
1239 );
1240 println!(
1241 " You're now on the feature branch and can continue with 'ca push'"
1242 );
1243
1244 } else {
1246 println!(
1247 "\n💡 Found {} commit(s) to push from base branch '{base_branch}'",
1248 commits_to_check.len()
1249 );
1250 println!(" These commits are currently ON the base branch, which may not be intended.");
1251 println!("\n Options:");
1252 println!(" 1. Auto-create feature branch and cherry-pick commits:");
1253 println!(" ca push --auto-branch");
1254 println!("\n 2. Manually create branch and move commits:");
1255 println!(" git checkout -b feature/my-work");
1256 println!(" ca push");
1257 println!("\n 3. Force push from base branch (not recommended):");
1258 println!(" ca push --allow-base-branch");
1259
1260 return Err(CascadeError::config(
1261 "Refusing to push commits from base branch. Use --auto-branch or create a feature branch manually."
1262 ));
1263 }
1264 }
1265 }
1266 }
1267 }
1268
1269 if let Some(squash_count) = squash {
1271 if squash_count == 0 {
1272 let active_stack = manager.get_active_stack().ok_or_else(|| {
1274 CascadeError::config(
1275 "No active stack. Create a stack first with 'ca stacks create'",
1276 )
1277 })?;
1278
1279 let unpushed_count = get_unpushed_commits(&repo, active_stack)?.len();
1280
1281 if unpushed_count == 0 {
1282 println!("ℹ️ No unpushed commits to squash");
1283 } else if unpushed_count == 1 {
1284 println!("ℹ️ Only 1 unpushed commit, no squashing needed");
1285 } else {
1286 println!("🔄 Auto-detected {unpushed_count} unpushed commits, squashing...");
1287 squash_commits(&repo, unpushed_count, None).await?;
1288 println!("✅ Squashed {unpushed_count} unpushed commits into one");
1289 }
1290 } else {
1291 println!("🔄 Squashing last {squash_count} commits...");
1292 squash_commits(&repo, squash_count, None).await?;
1293 println!("✅ Squashed {squash_count} commits into one");
1294 }
1295 } else if let Some(since_ref) = squash_since {
1296 println!("🔄 Squashing commits since {since_ref}...");
1297 let since_commit = repo.resolve_reference(&since_ref)?;
1298 let commits_count = count_commits_since(&repo, &since_commit.id().to_string())?;
1299 squash_commits(&repo, commits_count, Some(since_ref.clone())).await?;
1300 println!("✅ Squashed {commits_count} commits since {since_ref} into one");
1301 }
1302
1303 let commits_to_push = if let Some(commits_str) = commits {
1305 commits_str
1307 .split(',')
1308 .map(|s| s.trim().to_string())
1309 .collect::<Vec<String>>()
1310 } else if let Some(since_ref) = since {
1311 let since_commit = repo.resolve_reference(&since_ref)?;
1313 let head_commit = repo.get_head_commit()?;
1314
1315 let commits = repo.get_commits_between(
1317 &since_commit.id().to_string(),
1318 &head_commit.id().to_string(),
1319 )?;
1320 commits.into_iter().map(|c| c.id().to_string()).collect()
1321 } else if let Some(hash) = commit {
1322 vec![hash]
1324 } else {
1325 let active_stack = manager.get_active_stack().ok_or_else(|| {
1327 CascadeError::config("No active stack. Create a stack first with 'ca stacks create'")
1328 })?;
1329
1330 let base_branch = &active_stack.base_branch;
1332 let current_branch = repo.get_current_branch()?;
1333
1334 if current_branch == *base_branch {
1336 let mut unpushed = Vec::new();
1337 let head_commit = repo.get_head_commit()?;
1338 let mut current_commit = head_commit;
1339
1340 loop {
1342 let commit_hash = current_commit.id().to_string();
1343 let already_in_stack = active_stack
1344 .entries
1345 .iter()
1346 .any(|entry| entry.commit_hash == commit_hash);
1347
1348 if already_in_stack {
1349 break;
1350 }
1351
1352 unpushed.push(commit_hash);
1353
1354 if let Some(parent) = current_commit.parents().next() {
1356 current_commit = parent;
1357 } else {
1358 break;
1359 }
1360 }
1361
1362 unpushed.reverse(); unpushed
1364 } else {
1365 match repo.get_commits_between(base_branch, ¤t_branch) {
1367 Ok(commits) => {
1368 let mut unpushed: Vec<String> =
1369 commits.into_iter().map(|c| c.id().to_string()).collect();
1370
1371 unpushed.retain(|commit_hash| {
1373 !active_stack
1374 .entries
1375 .iter()
1376 .any(|entry| entry.commit_hash == *commit_hash)
1377 });
1378
1379 unpushed.reverse(); unpushed
1381 }
1382 Err(e) => {
1383 return Err(CascadeError::branch(format!(
1384 "Failed to calculate commits between '{base_branch}' and '{current_branch}': {e}. \
1385 This usually means the branches have diverged or don't share common history."
1386 )));
1387 }
1388 }
1389 }
1390 };
1391
1392 if commits_to_push.is_empty() {
1393 println!("ℹ️ No commits to push to stack");
1394 return Ok(());
1395 }
1396
1397 analyze_commits_for_safeguards(&commits_to_push, &repo, dry_run).await?;
1399
1400 if dry_run {
1402 return Ok(());
1403 }
1404
1405 let mut pushed_count = 0;
1407 let mut source_branches = std::collections::HashSet::new();
1408
1409 for (i, commit_hash) in commits_to_push.iter().enumerate() {
1410 let commit_obj = repo.get_commit(commit_hash)?;
1411 let commit_msg = commit_obj.message().unwrap_or("").to_string();
1412
1413 let commit_source_branch = repo
1415 .find_branch_containing_commit(commit_hash)
1416 .unwrap_or_else(|_| current_branch.clone());
1417 source_branches.insert(commit_source_branch.clone());
1418
1419 let branch_name = if i == 0 && branch.is_some() {
1421 branch.clone().unwrap()
1422 } else {
1423 let temp_repo = GitRepository::open(&repo_root)?;
1425 let branch_mgr = crate::git::BranchManager::new(temp_repo);
1426 branch_mgr.generate_branch_name(&commit_msg)
1427 };
1428
1429 let final_message = if i == 0 && message.is_some() {
1431 message.clone().unwrap()
1432 } else {
1433 commit_msg.clone()
1434 };
1435
1436 let entry_id = manager.push_to_stack(
1437 branch_name.clone(),
1438 commit_hash.clone(),
1439 final_message.clone(),
1440 commit_source_branch.clone(),
1441 )?;
1442 pushed_count += 1;
1443
1444 Output::success(format!(
1445 "Pushed commit {}/{} to stack",
1446 i + 1,
1447 commits_to_push.len()
1448 ));
1449 Output::sub_item(format!(
1450 "Commit: {} ({})",
1451 &commit_hash[..8],
1452 commit_msg.split('\n').next().unwrap_or("")
1453 ));
1454 Output::sub_item(format!("Branch: {branch_name}"));
1455 Output::sub_item(format!("Source: {commit_source_branch}"));
1456 Output::sub_item(format!("Entry ID: {entry_id}"));
1457 println!();
1458 }
1459
1460 if source_branches.len() > 1 {
1462 Output::warning("Scattered Commit Detection");
1463 Output::sub_item(format!(
1464 "You've pushed commits from {} different Git branches:",
1465 source_branches.len()
1466 ));
1467 for branch in &source_branches {
1468 Output::bullet(branch.to_string());
1469 }
1470
1471 Output::section("This can lead to confusion because:");
1472 Output::bullet("Stack appears sequential but commits are scattered across branches");
1473 Output::bullet("Team members won't know which branch contains which work");
1474 Output::bullet("Branch cleanup becomes unclear after merge");
1475 Output::bullet("Rebase operations become more complex");
1476
1477 Output::tip("Consider consolidating work to a single feature branch:");
1478 Output::bullet("Create a new feature branch: git checkout -b feature/consolidated-work");
1479 Output::bullet("Cherry-pick commits in order: git cherry-pick <commit1> <commit2> ...");
1480 Output::bullet("Delete old scattered branches");
1481 Output::bullet("Push the consolidated branch to your stack");
1482 println!();
1483 }
1484
1485 Output::success(format!(
1486 "Successfully pushed {} commit{} to stack",
1487 pushed_count,
1488 if pushed_count == 1 { "" } else { "s" }
1489 ));
1490
1491 Ok(())
1492}
1493
1494async fn pop_from_stack(keep_branch: bool) -> Result<()> {
1495 let current_dir = env::current_dir()
1496 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1497
1498 let repo_root = find_repository_root(¤t_dir)
1499 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1500
1501 let mut manager = StackManager::new(&repo_root)?;
1502 let repo = GitRepository::open(&repo_root)?;
1503
1504 let entry = manager.pop_from_stack()?;
1505
1506 Output::success("Popped commit from stack");
1507 Output::sub_item(format!(
1508 "Commit: {} ({})",
1509 entry.short_hash(),
1510 entry.short_message(50)
1511 ));
1512 Output::sub_item(format!("Branch: {}", entry.branch));
1513
1514 if !keep_branch && entry.branch != repo.get_current_branch()? {
1516 match repo.delete_branch(&entry.branch) {
1517 Ok(_) => Output::sub_item(format!("Deleted branch: {}", entry.branch)),
1518 Err(e) => Output::warning(format!("Could not delete branch {}: {}", entry.branch, e)),
1519 }
1520 }
1521
1522 Ok(())
1523}
1524
1525async fn submit_entry(
1526 entry: Option<usize>,
1527 title: Option<String>,
1528 description: Option<String>,
1529 range: Option<String>,
1530 draft: bool,
1531) -> Result<()> {
1532 let current_dir = env::current_dir()
1533 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1534
1535 let repo_root = find_repository_root(¤t_dir)
1536 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1537
1538 let mut stack_manager = StackManager::new(&repo_root)?;
1539
1540 if !stack_manager.check_for_branch_change()? {
1542 return Ok(()); }
1544
1545 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1547 let config_path = config_dir.join("config.json");
1548 let settings = crate::config::Settings::load_from_file(&config_path)?;
1549
1550 let cascade_config = crate::config::CascadeConfig {
1552 bitbucket: Some(settings.bitbucket.clone()),
1553 git: settings.git.clone(),
1554 auth: crate::config::AuthConfig::default(),
1555 cascade: settings.cascade.clone(),
1556 };
1557
1558 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1560 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1561 })?;
1562 let stack_id = active_stack.id;
1563
1564 let entries_to_submit = if let Some(range_str) = range {
1566 let mut entries = Vec::new();
1568
1569 if range_str.contains('-') {
1570 let parts: Vec<&str> = range_str.split('-').collect();
1572 if parts.len() != 2 {
1573 return Err(CascadeError::config(
1574 "Invalid range format. Use 'start-end' (e.g., '1-3')",
1575 ));
1576 }
1577
1578 let start: usize = parts[0]
1579 .parse()
1580 .map_err(|_| CascadeError::config("Invalid start number in range"))?;
1581 let end: usize = parts[1]
1582 .parse()
1583 .map_err(|_| CascadeError::config("Invalid end number in range"))?;
1584
1585 if start == 0
1586 || end == 0
1587 || start > active_stack.entries.len()
1588 || end > active_stack.entries.len()
1589 {
1590 return Err(CascadeError::config(format!(
1591 "Range out of bounds. Stack has {} entries",
1592 active_stack.entries.len()
1593 )));
1594 }
1595
1596 for i in start..=end {
1597 entries.push((i, active_stack.entries[i - 1].clone()));
1598 }
1599 } else {
1600 for entry_str in range_str.split(',') {
1602 let entry_num: usize = entry_str.trim().parse().map_err(|_| {
1603 CascadeError::config(format!("Invalid entry number: {entry_str}"))
1604 })?;
1605
1606 if entry_num == 0 || entry_num > active_stack.entries.len() {
1607 return Err(CascadeError::config(format!(
1608 "Entry {} out of bounds. Stack has {} entries",
1609 entry_num,
1610 active_stack.entries.len()
1611 )));
1612 }
1613
1614 entries.push((entry_num, active_stack.entries[entry_num - 1].clone()));
1615 }
1616 }
1617
1618 entries
1619 } else if let Some(entry_num) = entry {
1620 if entry_num == 0 || entry_num > active_stack.entries.len() {
1622 return Err(CascadeError::config(format!(
1623 "Invalid entry number: {}. Stack has {} entries",
1624 entry_num,
1625 active_stack.entries.len()
1626 )));
1627 }
1628 vec![(entry_num, active_stack.entries[entry_num - 1].clone())]
1629 } else {
1630 active_stack
1632 .entries
1633 .iter()
1634 .enumerate()
1635 .filter(|(_, entry)| !entry.is_submitted)
1636 .map(|(i, entry)| (i + 1, entry.clone())) .collect::<Vec<(usize, _)>>()
1638 };
1639
1640 if entries_to_submit.is_empty() {
1641 Output::info("No entries to submit");
1642 return Ok(());
1643 }
1644
1645 Output::section(format!(
1647 "Submitting {} {}",
1648 entries_to_submit.len(),
1649 if entries_to_submit.len() == 1 {
1650 "entry"
1651 } else {
1652 "entries"
1653 }
1654 ));
1655 println!();
1656
1657 let integration_stack_manager = StackManager::new(&repo_root)?;
1659 let mut integration =
1660 BitbucketIntegration::new(integration_stack_manager, cascade_config.clone())?;
1661
1662 let mut submitted_count = 0;
1664 let mut failed_entries = Vec::new();
1665 let total_entries = entries_to_submit.len();
1666
1667 for (entry_num, entry_to_submit) in &entries_to_submit {
1668 let tree_char = if entries_to_submit.len() == 1 {
1670 "→"
1671 } else if entry_num == &entries_to_submit.len() {
1672 "└─"
1673 } else {
1674 "├─"
1675 };
1676 print!(
1677 " {} Entry {}: {}... ",
1678 tree_char, entry_num, entry_to_submit.branch
1679 );
1680 std::io::Write::flush(&mut std::io::stdout()).ok();
1681
1682 let entry_title = if total_entries == 1 {
1684 title.clone()
1685 } else {
1686 None
1687 };
1688 let entry_description = if total_entries == 1 {
1689 description.clone()
1690 } else {
1691 None
1692 };
1693
1694 match integration
1695 .submit_entry(
1696 &stack_id,
1697 &entry_to_submit.id,
1698 entry_title,
1699 entry_description,
1700 draft,
1701 )
1702 .await
1703 {
1704 Ok(pr) => {
1705 submitted_count += 1;
1706 println!("✓ PR #{}", pr.id);
1707 if let Some(url) = pr.web_url() {
1708 Output::sub_item(format!(
1709 "{} → {}",
1710 pr.from_ref.display_id, pr.to_ref.display_id
1711 ));
1712 Output::sub_item(format!("URL: {url}"));
1713 }
1714 }
1715 Err(e) => {
1716 println!("✗ Failed");
1717 let clean_error = if e.to_string().contains("non-fast-forward") {
1719 "Branch has diverged (was rebased after initial submission). Update to v0.1.41+ to auto force-push.".to_string()
1720 } else if e.to_string().contains("authentication") {
1721 "Authentication failed. Check your Bitbucket credentials.".to_string()
1722 } else {
1723 e.to_string()
1725 .lines()
1726 .filter(|l| !l.trim().starts_with("hint:") && !l.trim().is_empty())
1727 .take(1)
1728 .collect::<Vec<_>>()
1729 .join(" ")
1730 .trim()
1731 .to_string()
1732 };
1733 Output::sub_item(format!("Error: {}", clean_error));
1734 failed_entries.push((*entry_num, clean_error));
1735 }
1736 }
1737 }
1738
1739 println!();
1740
1741 let has_any_prs = active_stack
1743 .entries
1744 .iter()
1745 .any(|e| e.pull_request_id.is_some());
1746 if has_any_prs && submitted_count > 0 {
1747 match integration.update_all_pr_descriptions(&stack_id).await {
1748 Ok(updated_prs) => {
1749 if !updated_prs.is_empty() {
1750 Output::sub_item(format!(
1751 "Updated {} PR description{} with stack hierarchy",
1752 updated_prs.len(),
1753 if updated_prs.len() == 1 { "" } else { "s" }
1754 ));
1755 }
1756 }
1757 Err(e) => {
1758 Output::warning(format!("Failed to update some PR descriptions: {e}"));
1759 }
1760 }
1761 }
1762
1763 if failed_entries.is_empty() {
1765 Output::success(format!(
1766 "All {} {} submitted successfully!",
1767 submitted_count,
1768 if submitted_count == 1 {
1769 "entry"
1770 } else {
1771 "entries"
1772 }
1773 ));
1774 } else {
1775 println!();
1776 Output::section("Submission Summary");
1777 println!(" ✓ Successful: {submitted_count}");
1778 println!(" ✗ Failed: {}", failed_entries.len());
1779
1780 if !failed_entries.is_empty() {
1781 println!();
1782 Output::tip("Retry failed entries:");
1783 for (entry_num, _) in &failed_entries {
1784 Output::bullet(format!("ca stack submit {entry_num}"));
1785 }
1786 }
1787 }
1788
1789 Ok(())
1790}
1791
1792async fn check_stack_status(name: Option<String>) -> Result<()> {
1793 let current_dir = env::current_dir()
1794 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1795
1796 let repo_root = find_repository_root(¤t_dir)
1797 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1798
1799 let stack_manager = StackManager::new(&repo_root)?;
1800
1801 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1803 let config_path = config_dir.join("config.json");
1804 let settings = crate::config::Settings::load_from_file(&config_path)?;
1805
1806 let cascade_config = crate::config::CascadeConfig {
1808 bitbucket: Some(settings.bitbucket.clone()),
1809 git: settings.git.clone(),
1810 auth: crate::config::AuthConfig::default(),
1811 cascade: settings.cascade.clone(),
1812 };
1813
1814 let stack = if let Some(name) = name {
1816 stack_manager
1817 .get_stack_by_name(&name)
1818 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?
1819 } else {
1820 stack_manager.get_active_stack().ok_or_else(|| {
1821 CascadeError::config("No active stack. Use 'ca stack list' to see available stacks")
1822 })?
1823 };
1824 let stack_id = stack.id;
1825
1826 Output::section(format!("Stack: {}", stack.name));
1827 Output::sub_item(format!("ID: {}", stack.id));
1828 Output::sub_item(format!("Base: {}", stack.base_branch));
1829
1830 if let Some(description) = &stack.description {
1831 Output::sub_item(format!("Description: {description}"));
1832 }
1833
1834 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1836
1837 match integration.check_stack_status(&stack_id).await {
1839 Ok(status) => {
1840 Output::section("Pull Request Status");
1841 Output::sub_item(format!("Total entries: {}", status.total_entries));
1842 Output::sub_item(format!("Submitted: {}", status.submitted_entries));
1843 Output::sub_item(format!("Open PRs: {}", status.open_prs));
1844 Output::sub_item(format!("Merged PRs: {}", status.merged_prs));
1845 Output::sub_item(format!("Declined PRs: {}", status.declined_prs));
1846 Output::sub_item(format!(
1847 "Completion: {:.1}%",
1848 status.completion_percentage()
1849 ));
1850
1851 if !status.pull_requests.is_empty() {
1852 Output::section("Pull Requests");
1853 for pr in &status.pull_requests {
1854 let state_icon = match pr.state {
1855 crate::bitbucket::PullRequestState::Open => "🔄",
1856 crate::bitbucket::PullRequestState::Merged => "✅",
1857 crate::bitbucket::PullRequestState::Declined => "❌",
1858 };
1859 Output::bullet(format!(
1860 "{} PR #{}: {} ({} -> {})",
1861 state_icon, pr.id, pr.title, pr.from_ref.display_id, pr.to_ref.display_id
1862 ));
1863 if let Some(url) = pr.web_url() {
1864 Output::sub_item(format!("URL: {url}"));
1865 }
1866 }
1867 }
1868 }
1869 Err(e) => {
1870 warn!("Failed to check stack status: {}", e);
1871 return Err(e);
1872 }
1873 }
1874
1875 Ok(())
1876}
1877
1878async fn list_pull_requests(state: Option<String>, verbose: bool) -> Result<()> {
1879 let current_dir = env::current_dir()
1880 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1881
1882 let repo_root = find_repository_root(¤t_dir)
1883 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1884
1885 let stack_manager = StackManager::new(&repo_root)?;
1886
1887 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1889 let config_path = config_dir.join("config.json");
1890 let settings = crate::config::Settings::load_from_file(&config_path)?;
1891
1892 let cascade_config = crate::config::CascadeConfig {
1894 bitbucket: Some(settings.bitbucket.clone()),
1895 git: settings.git.clone(),
1896 auth: crate::config::AuthConfig::default(),
1897 cascade: settings.cascade.clone(),
1898 };
1899
1900 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1902
1903 let pr_state = if let Some(state_str) = state {
1905 match state_str.to_lowercase().as_str() {
1906 "open" => Some(crate::bitbucket::PullRequestState::Open),
1907 "merged" => Some(crate::bitbucket::PullRequestState::Merged),
1908 "declined" => Some(crate::bitbucket::PullRequestState::Declined),
1909 _ => {
1910 return Err(CascadeError::config(format!(
1911 "Invalid state '{state_str}'. Use: open, merged, declined"
1912 )))
1913 }
1914 }
1915 } else {
1916 None
1917 };
1918
1919 match integration.list_pull_requests(pr_state).await {
1921 Ok(pr_page) => {
1922 if pr_page.values.is_empty() {
1923 Output::info("No pull requests found.");
1924 return Ok(());
1925 }
1926
1927 println!("📋 Pull Requests ({} total):", pr_page.values.len());
1928 for pr in &pr_page.values {
1929 let state_icon = match pr.state {
1930 crate::bitbucket::PullRequestState::Open => "🔄",
1931 crate::bitbucket::PullRequestState::Merged => "✅",
1932 crate::bitbucket::PullRequestState::Declined => "❌",
1933 };
1934 println!(" {} PR #{}: {}", state_icon, pr.id, pr.title);
1935 if verbose {
1936 println!(
1937 " From: {} -> {}",
1938 pr.from_ref.display_id, pr.to_ref.display_id
1939 );
1940 println!(
1941 " Author: {}",
1942 pr.author
1943 .user
1944 .display_name
1945 .as_deref()
1946 .unwrap_or(&pr.author.user.name)
1947 );
1948 if let Some(url) = pr.web_url() {
1949 println!(" URL: {url}");
1950 }
1951 if let Some(desc) = &pr.description {
1952 if !desc.is_empty() {
1953 println!(" Description: {desc}");
1954 }
1955 }
1956 println!();
1957 }
1958 }
1959
1960 if !verbose {
1961 println!("\nUse --verbose for more details");
1962 }
1963 }
1964 Err(e) => {
1965 warn!("Failed to list pull requests: {}", e);
1966 return Err(e);
1967 }
1968 }
1969
1970 Ok(())
1971}
1972
1973async fn check_stack(_force: bool) -> Result<()> {
1974 let current_dir = env::current_dir()
1975 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1976
1977 let repo_root = find_repository_root(¤t_dir)
1978 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1979
1980 let mut manager = StackManager::new(&repo_root)?;
1981
1982 let active_stack = manager
1983 .get_active_stack()
1984 .ok_or_else(|| CascadeError::config("No active stack"))?;
1985 let stack_id = active_stack.id;
1986
1987 manager.sync_stack(&stack_id)?;
1988
1989 Output::success("Stack check completed successfully");
1990
1991 Ok(())
1992}
1993
1994async fn sync_stack(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
1995 let current_dir = env::current_dir()
1996 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1997
1998 let repo_root = find_repository_root(¤t_dir)
1999 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2000
2001 let mut stack_manager = StackManager::new(&repo_root)?;
2002
2003 if stack_manager.is_in_edit_mode() {
2006 debug!("Exiting edit mode before sync (commit SHAs will change)");
2007 stack_manager.exit_edit_mode()?;
2008 }
2009
2010 let git_repo = GitRepository::open(&repo_root)?;
2011
2012 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2014 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2015 })?;
2016
2017 let base_branch = active_stack.base_branch.clone();
2018 let stack_name = active_stack.name.clone();
2019
2020 let original_branch = git_repo.get_current_branch().ok();
2022
2023 println!("Syncing stack '{stack_name}' with remote...");
2025
2026 match git_repo.checkout_branch(&base_branch) {
2028 Ok(_) => {
2029 match git_repo.pull(&base_branch) {
2030 Ok(_) => {
2031 }
2033 Err(e) => {
2034 if force {
2035 Output::warning(format!("Pull failed: {e} (continuing due to --force)"));
2036 } else {
2037 Output::error(format!("Failed to pull latest changes: {e}"));
2038 Output::tip("Use --force to skip pull and continue with rebase");
2039 return Err(CascadeError::branch(format!(
2040 "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
2041 )));
2042 }
2043 }
2044 }
2045 }
2046 Err(e) => {
2047 if force {
2048 Output::warning(format!(
2049 "Failed to checkout '{base_branch}': {e} (continuing due to --force)"
2050 ));
2051 } else {
2052 Output::error(format!(
2053 "Failed to checkout base branch '{base_branch}': {e}"
2054 ));
2055 Output::tip("Use --force to bypass checkout issues and continue anyway");
2056 return Err(CascadeError::branch(format!(
2057 "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
2058 )));
2059 }
2060 }
2061 }
2062
2063 let mut updated_stack_manager = StackManager::new(&repo_root)?;
2066 let stack_id = active_stack.id;
2067
2068 if let Some(stack) = updated_stack_manager.get_stack_mut(&stack_id) {
2071 for entry in &mut stack.entries {
2072 if let Ok(current_commit) = git_repo.get_branch_head(&entry.branch) {
2073 if entry.commit_hash != current_commit {
2074 debug!(
2075 "Reconciling entry '{}': updating hash from {} to {} (current branch HEAD)",
2076 entry.branch,
2077 &entry.commit_hash[..8],
2078 ¤t_commit[..8]
2079 );
2080 entry.commit_hash = current_commit;
2081 }
2082 }
2083 }
2084 updated_stack_manager.save_to_disk()?;
2086 }
2087
2088 match updated_stack_manager.sync_stack(&stack_id) {
2089 Ok(_) => {
2090 if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
2092 match &updated_stack.status {
2093 crate::stack::StackStatus::NeedsSync => {
2094 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2096 let config_path = config_dir.join("config.json");
2097 let settings = crate::config::Settings::load_from_file(&config_path)?;
2098
2099 let cascade_config = crate::config::CascadeConfig {
2100 bitbucket: Some(settings.bitbucket.clone()),
2101 git: settings.git.clone(),
2102 auth: crate::config::AuthConfig::default(),
2103 cascade: settings.cascade.clone(),
2104 };
2105
2106 let options = crate::stack::RebaseOptions {
2109 strategy: crate::stack::RebaseStrategy::ForcePush,
2110 interactive,
2111 target_base: Some(base_branch.clone()),
2112 preserve_merges: true,
2113 auto_resolve: !interactive,
2114 max_retries: 3,
2115 skip_pull: Some(true), };
2117
2118 let mut rebase_manager = crate::stack::RebaseManager::new(
2119 updated_stack_manager,
2120 git_repo,
2121 options,
2122 );
2123
2124 match rebase_manager.rebase_stack(&stack_id) {
2125 Ok(result) => {
2126 if !result.branch_mapping.is_empty() {
2127 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2129 let integration_stack_manager =
2130 StackManager::new(&repo_root)?;
2131 let mut integration =
2132 crate::bitbucket::BitbucketIntegration::new(
2133 integration_stack_manager,
2134 cascade_config,
2135 )?;
2136
2137 match integration
2138 .update_prs_after_rebase(
2139 &stack_id,
2140 &result.branch_mapping,
2141 )
2142 .await
2143 {
2144 Ok(updated_prs) => {
2145 if !updated_prs.is_empty() {
2146 println!(
2147 "Updated {} pull requests",
2148 updated_prs.len()
2149 );
2150 }
2151 }
2152 Err(e) => {
2153 Output::warning(format!(
2154 "Failed to update pull requests: {e}"
2155 ));
2156 }
2157 }
2158 }
2159 }
2160 }
2161 Err(e) => {
2162 Output::error(format!("Rebase failed: {e}"));
2163 Output::tip("To resolve conflicts:");
2164 Output::bullet("Fix conflicts in the affected files");
2165 Output::bullet("Stage resolved files: git add <files>");
2166 Output::bullet("Continue: ca stack continue-rebase");
2167 return Err(e);
2168 }
2169 }
2170 }
2171 crate::stack::StackStatus::Clean => {
2172 }
2174 other => {
2175 Output::info(format!("Stack status: {other:?}"));
2177 }
2178 }
2179 }
2180 }
2181 Err(e) => {
2182 if force {
2183 Output::warning(format!(
2184 "Failed to check stack status: {e} (continuing due to --force)"
2185 ));
2186 } else {
2187 return Err(e);
2188 }
2189 }
2190 }
2191
2192 if !skip_cleanup {
2194 let git_repo_for_cleanup = GitRepository::open(&repo_root)?;
2195 match perform_simple_cleanup(&stack_manager, &git_repo_for_cleanup, false).await {
2196 Ok(result) => {
2197 if result.total_candidates > 0 {
2198 Output::section("Cleanup Summary");
2199 if !result.cleaned_branches.is_empty() {
2200 Output::success(format!(
2201 "Cleaned up {} merged branches",
2202 result.cleaned_branches.len()
2203 ));
2204 for branch in &result.cleaned_branches {
2205 Output::sub_item(format!("🗑️ Deleted: {branch}"));
2206 }
2207 }
2208 if !result.skipped_branches.is_empty() {
2209 Output::sub_item(format!(
2210 "Skipped {} branches",
2211 result.skipped_branches.len()
2212 ));
2213 }
2214 if !result.failed_branches.is_empty() {
2215 for (branch, error) in &result.failed_branches {
2216 Output::warning(format!("Failed to clean up {branch}: {error}"));
2217 }
2218 }
2219 }
2220 }
2221 Err(e) => {
2222 Output::warning(format!("Branch cleanup failed: {e}"));
2223 }
2224 }
2225 }
2226
2227 if let Some(orig_branch) = original_branch {
2229 if orig_branch != base_branch {
2230 if let Ok(git_repo) = GitRepository::open(&repo_root) {
2232 if let Err(e) = git_repo.checkout_branch(&orig_branch) {
2233 Output::warning(format!(
2234 "Could not return to original branch '{}': {}",
2235 orig_branch, e
2236 ));
2237 }
2238 }
2239 }
2240 }
2241
2242 Output::success("Sync completed successfully!");
2243
2244 Ok(())
2245}
2246
2247async fn rebase_stack(
2248 interactive: bool,
2249 onto: Option<String>,
2250 strategy: Option<RebaseStrategyArg>,
2251) -> Result<()> {
2252 let current_dir = env::current_dir()
2253 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2254
2255 let repo_root = find_repository_root(¤t_dir)
2256 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2257
2258 let stack_manager = StackManager::new(&repo_root)?;
2259 let git_repo = GitRepository::open(&repo_root)?;
2260
2261 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2263 let config_path = config_dir.join("config.json");
2264 let settings = crate::config::Settings::load_from_file(&config_path)?;
2265
2266 let cascade_config = crate::config::CascadeConfig {
2268 bitbucket: Some(settings.bitbucket.clone()),
2269 git: settings.git.clone(),
2270 auth: crate::config::AuthConfig::default(),
2271 cascade: settings.cascade.clone(),
2272 };
2273
2274 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2276 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2277 })?;
2278 let stack_id = active_stack.id;
2279
2280 let active_stack = stack_manager
2281 .get_stack(&stack_id)
2282 .ok_or_else(|| CascadeError::config("Active stack not found"))?
2283 .clone();
2284
2285 if active_stack.entries.is_empty() {
2286 Output::info("Stack is empty. Nothing to rebase.");
2287 return Ok(());
2288 }
2289
2290 Output::progress(format!("Rebasing stack: {}", active_stack.name));
2291 Output::sub_item(format!("Base: {}", active_stack.base_branch));
2292
2293 let rebase_strategy = if let Some(cli_strategy) = strategy {
2295 match cli_strategy {
2296 RebaseStrategyArg::ForcePush => crate::stack::RebaseStrategy::ForcePush,
2297 RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
2298 }
2299 } else {
2300 crate::stack::RebaseStrategy::ForcePush
2302 };
2303
2304 let options = crate::stack::RebaseOptions {
2306 strategy: rebase_strategy.clone(),
2307 interactive,
2308 target_base: onto,
2309 preserve_merges: true,
2310 auto_resolve: !interactive, max_retries: 3,
2312 skip_pull: None, };
2314
2315 debug!(" Strategy: {:?}", rebase_strategy);
2316 debug!(" Interactive: {}", interactive);
2317 debug!(" Target base: {:?}", options.target_base);
2318 debug!(" Entries: {}", active_stack.entries.len());
2319
2320 let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2322
2323 if rebase_manager.is_rebase_in_progress() {
2324 Output::warning("Rebase already in progress!");
2325 Output::tip("Use 'git status' to check the current state");
2326 Output::next_steps(&[
2327 "Run 'ca stack continue-rebase' to continue",
2328 "Run 'ca stack abort-rebase' to abort",
2329 ]);
2330 return Ok(());
2331 }
2332
2333 match rebase_manager.rebase_stack(&stack_id) {
2335 Ok(result) => {
2336 Output::success("Rebase completed!");
2337 Output::sub_item(result.get_summary());
2338
2339 if result.has_conflicts() {
2340 Output::warning(format!(
2341 "{} conflicts were resolved",
2342 result.conflicts.len()
2343 ));
2344 for conflict in &result.conflicts {
2345 Output::bullet(&conflict[..8.min(conflict.len())]);
2346 }
2347 }
2348
2349 if !result.branch_mapping.is_empty() {
2350 Output::section("Branch mapping");
2351 for (old, new) in &result.branch_mapping {
2352 Output::bullet(format!("{old} -> {new}"));
2353 }
2354
2355 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2357 let integration_stack_manager = StackManager::new(&repo_root)?;
2359 let mut integration = BitbucketIntegration::new(
2360 integration_stack_manager,
2361 cascade_config.clone(),
2362 )?;
2363
2364 match integration
2365 .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2366 .await
2367 {
2368 Ok(updated_prs) => {
2369 if !updated_prs.is_empty() {
2370 println!(" 🔄 Preserved pull request history:");
2371 for pr_update in updated_prs {
2372 println!(" ✅ {pr_update}");
2373 }
2374 }
2375 }
2376 Err(e) => {
2377 eprintln!(" ⚠️ Failed to update pull requests: {e}");
2378 eprintln!(" You may need to manually update PRs in Bitbucket");
2379 }
2380 }
2381 }
2382 }
2383
2384 println!(
2385 " ✅ {} commits successfully rebased",
2386 result.success_count()
2387 );
2388
2389 if matches!(rebase_strategy, crate::stack::RebaseStrategy::ForcePush) {
2391 println!("\n📝 Next steps:");
2392 if !result.branch_mapping.is_empty() {
2393 println!(" 1. ✅ Branches have been rebased and force-pushed");
2394 println!(" 2. ✅ Pull requests updated automatically (history preserved)");
2395 println!(" 3. 🔍 Review the updated PRs in Bitbucket");
2396 println!(" 4. 🧪 Test your changes");
2397 } else {
2398 println!(" 1. Review the rebased stack");
2399 println!(" 2. Test your changes");
2400 println!(" 3. Submit new pull requests with 'ca stack submit'");
2401 }
2402 }
2403 }
2404 Err(e) => {
2405 warn!("❌ Rebase failed: {}", e);
2406 println!("💡 Tips for resolving rebase issues:");
2407 println!(" - Check for uncommitted changes with 'git status'");
2408 println!(" - Ensure base branch is up to date");
2409 println!(" - Try interactive mode: 'ca stack rebase --interactive'");
2410 return Err(e);
2411 }
2412 }
2413
2414 Ok(())
2415}
2416
2417async fn continue_rebase() -> Result<()> {
2418 let current_dir = env::current_dir()
2419 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2420
2421 let repo_root = find_repository_root(¤t_dir)
2422 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2423
2424 let stack_manager = StackManager::new(&repo_root)?;
2425 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2426 let options = crate::stack::RebaseOptions::default();
2427 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2428
2429 if !rebase_manager.is_rebase_in_progress() {
2430 println!("ℹ️ No rebase in progress");
2431 return Ok(());
2432 }
2433
2434 println!("🔄 Continuing rebase...");
2435 match rebase_manager.continue_rebase() {
2436 Ok(_) => {
2437 println!("✅ Rebase continued successfully");
2438 println!(" Check 'ca stack rebase-status' for current state");
2439 }
2440 Err(e) => {
2441 warn!("❌ Failed to continue rebase: {}", e);
2442 println!("💡 You may need to resolve conflicts first:");
2443 println!(" 1. Edit conflicted files");
2444 println!(" 2. Stage resolved files with 'git add'");
2445 println!(" 3. Run 'ca stack continue-rebase' again");
2446 }
2447 }
2448
2449 Ok(())
2450}
2451
2452async fn abort_rebase() -> Result<()> {
2453 let current_dir = env::current_dir()
2454 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2455
2456 let repo_root = find_repository_root(¤t_dir)
2457 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2458
2459 let stack_manager = StackManager::new(&repo_root)?;
2460 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2461 let options = crate::stack::RebaseOptions::default();
2462 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2463
2464 if !rebase_manager.is_rebase_in_progress() {
2465 println!("ℹ️ No rebase in progress");
2466 return Ok(());
2467 }
2468
2469 println!("⚠️ Aborting rebase...");
2470 match rebase_manager.abort_rebase() {
2471 Ok(_) => {
2472 println!("✅ Rebase aborted successfully");
2473 println!(" Repository restored to pre-rebase state");
2474 }
2475 Err(e) => {
2476 warn!("❌ Failed to abort rebase: {}", e);
2477 println!("⚠️ You may need to manually clean up the repository state");
2478 }
2479 }
2480
2481 Ok(())
2482}
2483
2484async fn rebase_status() -> Result<()> {
2485 let current_dir = env::current_dir()
2486 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2487
2488 let repo_root = find_repository_root(¤t_dir)
2489 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2490
2491 let stack_manager = StackManager::new(&repo_root)?;
2492 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2493
2494 println!("📊 Rebase Status");
2495
2496 let git_dir = current_dir.join(".git");
2498 let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
2499 || git_dir.join("rebase-merge").exists()
2500 || git_dir.join("rebase-apply").exists();
2501
2502 if rebase_in_progress {
2503 println!(" Status: 🔄 Rebase in progress");
2504 println!(
2505 "
2506📝 Actions available:"
2507 );
2508 println!(" - 'ca stack continue-rebase' to continue");
2509 println!(" - 'ca stack abort-rebase' to abort");
2510 println!(" - 'git status' to see conflicted files");
2511
2512 match git_repo.get_status() {
2514 Ok(statuses) => {
2515 let mut conflicts = Vec::new();
2516 for status in statuses.iter() {
2517 if status.status().contains(git2::Status::CONFLICTED) {
2518 if let Some(path) = status.path() {
2519 conflicts.push(path.to_string());
2520 }
2521 }
2522 }
2523
2524 if !conflicts.is_empty() {
2525 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
2526 for conflict in conflicts {
2527 println!(" - {conflict}");
2528 }
2529 println!(
2530 "
2531💡 To resolve conflicts:"
2532 );
2533 println!(" 1. Edit the conflicted files");
2534 println!(" 2. Stage resolved files: git add <file>");
2535 println!(" 3. Continue: ca stack continue-rebase");
2536 }
2537 }
2538 Err(e) => {
2539 warn!("Failed to get git status: {}", e);
2540 }
2541 }
2542 } else {
2543 println!(" Status: ✅ No rebase in progress");
2544
2545 if let Some(active_stack) = stack_manager.get_active_stack() {
2547 println!(" Active stack: {}", active_stack.name);
2548 println!(" Entries: {}", active_stack.entries.len());
2549 println!(" Base branch: {}", active_stack.base_branch);
2550 }
2551 }
2552
2553 Ok(())
2554}
2555
2556async fn delete_stack(name: String, force: bool) -> Result<()> {
2557 let current_dir = env::current_dir()
2558 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2559
2560 let repo_root = find_repository_root(¤t_dir)
2561 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2562
2563 let mut manager = StackManager::new(&repo_root)?;
2564
2565 let stack = manager
2566 .get_stack_by_name(&name)
2567 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2568 let stack_id = stack.id;
2569
2570 if !force && !stack.entries.is_empty() {
2571 return Err(CascadeError::config(format!(
2572 "Stack '{}' has {} entries. Use --force to delete anyway",
2573 name,
2574 stack.entries.len()
2575 )));
2576 }
2577
2578 let deleted = manager.delete_stack(&stack_id)?;
2579
2580 Output::success(format!("Deleted stack '{}'", deleted.name));
2581 if !deleted.entries.is_empty() {
2582 Output::warning(format!("{} entries were removed", deleted.entries.len()));
2583 }
2584
2585 Ok(())
2586}
2587
2588async fn validate_stack(name: Option<String>, fix_mode: Option<String>) -> Result<()> {
2589 let current_dir = env::current_dir()
2590 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2591
2592 let repo_root = find_repository_root(¤t_dir)
2593 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2594
2595 let mut manager = StackManager::new(&repo_root)?;
2596
2597 if let Some(name) = name {
2598 let stack = manager
2600 .get_stack_by_name(&name)
2601 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2602
2603 let stack_id = stack.id;
2604
2605 match stack.validate() {
2607 Ok(message) => {
2608 println!("✅ Stack '{name}' structure validation: {message}");
2609 }
2610 Err(e) => {
2611 println!("❌ Stack '{name}' structure validation failed: {e}");
2612 return Err(CascadeError::config(e));
2613 }
2614 }
2615
2616 manager.handle_branch_modifications(&stack_id, fix_mode)?;
2618
2619 println!("🎉 Stack '{name}' validation completed");
2620 Ok(())
2621 } else {
2622 println!("🔍 Validating all stacks...");
2624
2625 let all_stacks = manager.get_all_stacks();
2627 let stack_ids: Vec<uuid::Uuid> = all_stacks.iter().map(|s| s.id).collect();
2628
2629 if stack_ids.is_empty() {
2630 println!("📭 No stacks found");
2631 return Ok(());
2632 }
2633
2634 let mut all_valid = true;
2635 for stack_id in stack_ids {
2636 let stack = manager.get_stack(&stack_id).unwrap();
2637 let stack_name = &stack.name;
2638
2639 println!("\n📋 Checking stack '{stack_name}':");
2640
2641 match stack.validate() {
2643 Ok(message) => {
2644 println!(" ✅ Structure: {message}");
2645 }
2646 Err(e) => {
2647 println!(" ❌ Structure: {e}");
2648 all_valid = false;
2649 continue;
2650 }
2651 }
2652
2653 match manager.handle_branch_modifications(&stack_id, fix_mode.clone()) {
2655 Ok(_) => {
2656 println!(" ✅ Git integrity: OK");
2657 }
2658 Err(e) => {
2659 println!(" ❌ Git integrity: {e}");
2660 all_valid = false;
2661 }
2662 }
2663 }
2664
2665 if all_valid {
2666 println!("\n🎉 All stacks passed validation");
2667 } else {
2668 println!("\n⚠️ Some stacks have validation issues");
2669 return Err(CascadeError::config("Stack validation failed".to_string()));
2670 }
2671
2672 Ok(())
2673 }
2674}
2675
2676#[allow(dead_code)]
2678fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
2679 let mut unpushed = Vec::new();
2680 let head_commit = repo.get_head_commit()?;
2681 let mut current_commit = head_commit;
2682
2683 loop {
2685 let commit_hash = current_commit.id().to_string();
2686 let already_in_stack = stack
2687 .entries
2688 .iter()
2689 .any(|entry| entry.commit_hash == commit_hash);
2690
2691 if already_in_stack {
2692 break;
2693 }
2694
2695 unpushed.push(commit_hash);
2696
2697 if let Some(parent) = current_commit.parents().next() {
2699 current_commit = parent;
2700 } else {
2701 break;
2702 }
2703 }
2704
2705 unpushed.reverse(); Ok(unpushed)
2707}
2708
2709pub async fn squash_commits(
2711 repo: &GitRepository,
2712 count: usize,
2713 since_ref: Option<String>,
2714) -> Result<()> {
2715 if count <= 1 {
2716 return Ok(()); }
2718
2719 let _current_branch = repo.get_current_branch()?;
2721
2722 let rebase_range = if let Some(ref since) = since_ref {
2724 since.clone()
2725 } else {
2726 format!("HEAD~{count}")
2727 };
2728
2729 println!(" Analyzing {count} commits to create smart squash message...");
2730
2731 let head_commit = repo.get_head_commit()?;
2733 let mut commits_to_squash = Vec::new();
2734 let mut current = head_commit;
2735
2736 for _ in 0..count {
2738 commits_to_squash.push(current.clone());
2739 if current.parent_count() > 0 {
2740 current = current.parent(0).map_err(CascadeError::Git)?;
2741 } else {
2742 break;
2743 }
2744 }
2745
2746 let smart_message = generate_squash_message(&commits_to_squash)?;
2748 println!(
2749 " Smart message: {}",
2750 smart_message.lines().next().unwrap_or("")
2751 );
2752
2753 let reset_target = if since_ref.is_some() {
2755 format!("{rebase_range}~1")
2757 } else {
2758 format!("HEAD~{count}")
2760 };
2761
2762 repo.reset_soft(&reset_target)?;
2764
2765 repo.stage_all()?;
2767
2768 let new_commit_hash = repo.commit(&smart_message)?;
2770
2771 println!(
2772 " Created squashed commit: {} ({})",
2773 &new_commit_hash[..8],
2774 smart_message.lines().next().unwrap_or("")
2775 );
2776 println!(" 💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
2777
2778 Ok(())
2779}
2780
2781pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
2783 if commits.is_empty() {
2784 return Ok("Squashed commits".to_string());
2785 }
2786
2787 let messages: Vec<String> = commits
2789 .iter()
2790 .map(|c| c.message().unwrap_or("").trim().to_string())
2791 .filter(|m| !m.is_empty())
2792 .collect();
2793
2794 if messages.is_empty() {
2795 return Ok("Squashed commits".to_string());
2796 }
2797
2798 if let Some(last_msg) = messages.first() {
2800 if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
2802 return Ok(last_msg
2803 .trim_start_matches("Final:")
2804 .trim_start_matches("final:")
2805 .trim()
2806 .to_string());
2807 }
2808 }
2809
2810 let wip_count = messages
2812 .iter()
2813 .filter(|m| {
2814 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
2815 })
2816 .count();
2817
2818 if wip_count > messages.len() / 2 {
2819 let non_wip: Vec<&String> = messages
2821 .iter()
2822 .filter(|m| {
2823 !m.to_lowercase().starts_with("wip")
2824 && !m.to_lowercase().contains("work in progress")
2825 })
2826 .collect();
2827
2828 if let Some(best_msg) = non_wip.first() {
2829 return Ok(best_msg.to_string());
2830 }
2831
2832 let feature = extract_feature_from_wip(&messages);
2834 return Ok(feature);
2835 }
2836
2837 Ok(messages.first().unwrap().clone())
2839}
2840
2841pub fn extract_feature_from_wip(messages: &[String]) -> String {
2843 for msg in messages {
2845 if msg.to_lowercase().starts_with("wip:") {
2847 if let Some(rest) = msg
2848 .strip_prefix("WIP:")
2849 .or_else(|| msg.strip_prefix("wip:"))
2850 {
2851 let feature = rest.trim();
2852 if !feature.is_empty() && feature.len() > 3 {
2853 let mut chars: Vec<char> = feature.chars().collect();
2855 if let Some(first) = chars.first_mut() {
2856 *first = first.to_uppercase().next().unwrap_or(*first);
2857 }
2858 return chars.into_iter().collect();
2859 }
2860 }
2861 }
2862 }
2863
2864 if let Some(first) = messages.first() {
2866 let cleaned = first
2867 .trim_start_matches("WIP:")
2868 .trim_start_matches("wip:")
2869 .trim_start_matches("WIP")
2870 .trim_start_matches("wip")
2871 .trim();
2872
2873 if !cleaned.is_empty() {
2874 return format!("Implement {cleaned}");
2875 }
2876 }
2877
2878 format!("Squashed {} commits", messages.len())
2879}
2880
2881pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
2883 let head_commit = repo.get_head_commit()?;
2884 let since_commit = repo.get_commit(since_commit_hash)?;
2885
2886 let mut count = 0;
2887 let mut current = head_commit;
2888
2889 loop {
2891 if current.id() == since_commit.id() {
2892 break;
2893 }
2894
2895 count += 1;
2896
2897 if current.parent_count() == 0 {
2899 break; }
2901
2902 current = current.parent(0).map_err(CascadeError::Git)?;
2903 }
2904
2905 Ok(count)
2906}
2907
2908async fn land_stack(
2910 entry: Option<usize>,
2911 force: bool,
2912 dry_run: bool,
2913 auto: bool,
2914 wait_for_builds: bool,
2915 strategy: Option<MergeStrategyArg>,
2916 build_timeout: u64,
2917) -> Result<()> {
2918 let current_dir = env::current_dir()
2919 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2920
2921 let repo_root = find_repository_root(¤t_dir)
2922 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2923
2924 let stack_manager = StackManager::new(&repo_root)?;
2925
2926 let stack_id = stack_manager
2928 .get_active_stack()
2929 .map(|s| s.id)
2930 .ok_or_else(|| {
2931 CascadeError::config(
2932 "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
2933 .to_string(),
2934 )
2935 })?;
2936
2937 let active_stack = stack_manager
2938 .get_active_stack()
2939 .cloned()
2940 .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
2941
2942 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2944 let config_path = config_dir.join("config.json");
2945 let settings = crate::config::Settings::load_from_file(&config_path)?;
2946
2947 let cascade_config = crate::config::CascadeConfig {
2948 bitbucket: Some(settings.bitbucket.clone()),
2949 git: settings.git.clone(),
2950 auth: crate::config::AuthConfig::default(),
2951 cascade: settings.cascade.clone(),
2952 };
2953
2954 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
2955
2956 let status = integration.check_enhanced_stack_status(&stack_id).await?;
2958
2959 if status.enhanced_statuses.is_empty() {
2960 println!("❌ No pull requests found to land");
2961 return Ok(());
2962 }
2963
2964 let ready_prs: Vec<_> = status
2966 .enhanced_statuses
2967 .iter()
2968 .filter(|pr_status| {
2969 if let Some(entry_num) = entry {
2971 if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
2973 if pr_status.pr.from_ref.display_id != stack_entry.branch {
2975 return false;
2976 }
2977 } else {
2978 return false; }
2980 }
2981
2982 if force {
2983 pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
2985 } else {
2986 pr_status.is_ready_to_land()
2987 }
2988 })
2989 .collect();
2990
2991 if ready_prs.is_empty() {
2992 if let Some(entry_num) = entry {
2993 println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
2994 } else {
2995 println!("❌ No pull requests are ready to land");
2996 }
2997
2998 println!("\n🚫 Blocking Issues:");
3000 for pr_status in &status.enhanced_statuses {
3001 if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
3002 let blocking = pr_status.get_blocking_reasons();
3003 if !blocking.is_empty() {
3004 println!(" PR #{}: {}", pr_status.pr.id, blocking.join(", "));
3005 }
3006 }
3007 }
3008
3009 if !force {
3010 println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
3011 }
3012 return Ok(());
3013 }
3014
3015 if dry_run {
3016 if let Some(entry_num) = entry {
3017 println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
3018 } else {
3019 println!("🏃 Dry Run - PRs that would be landed:");
3020 }
3021 for pr_status in &ready_prs {
3022 println!(" ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
3023 if !pr_status.is_ready_to_land() && force {
3024 let blocking = pr_status.get_blocking_reasons();
3025 println!(
3026 " ⚠️ Would force land despite: {}",
3027 blocking.join(", ")
3028 );
3029 }
3030 }
3031 return Ok(());
3032 }
3033
3034 if entry.is_some() && ready_prs.len() > 1 {
3037 println!(
3038 "🎯 {} PRs are ready to land, but landing only entry #{}",
3039 ready_prs.len(),
3040 entry.unwrap()
3041 );
3042 }
3043
3044 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
3046 strategy.unwrap_or(MergeStrategyArg::Squash).into();
3047 let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3048 merge_strategy: merge_strategy.clone(),
3049 wait_for_builds,
3050 build_timeout: std::time::Duration::from_secs(build_timeout),
3051 allowed_authors: None, };
3053
3054 println!(
3056 "🚀 Landing {} PR{}...",
3057 ready_prs.len(),
3058 if ready_prs.len() == 1 { "" } else { "s" }
3059 );
3060
3061 let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
3062 crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
3063 );
3064
3065 let mut landed_count = 0;
3067 let mut failed_count = 0;
3068 let total_ready_prs = ready_prs.len();
3069
3070 for pr_status in ready_prs {
3071 let pr_id = pr_status.pr.id;
3072
3073 print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
3074
3075 let land_result = if auto {
3076 pr_manager
3078 .auto_merge_if_ready(pr_id, &auto_merge_conditions)
3079 .await
3080 } else {
3081 pr_manager
3083 .merge_pull_request(pr_id, merge_strategy.clone())
3084 .await
3085 .map(
3086 |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
3087 pr: Box::new(pr),
3088 merge_strategy: merge_strategy.clone(),
3089 },
3090 )
3091 };
3092
3093 match land_result {
3094 Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
3095 println!(" ✅");
3096 landed_count += 1;
3097
3098 if landed_count < total_ready_prs {
3100 println!("🔄 Retargeting remaining PRs to latest base...");
3101
3102 let base_branch = active_stack.base_branch.clone();
3104 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3105
3106 println!(" 📥 Updating base branch: {base_branch}");
3107 match git_repo.pull(&base_branch) {
3108 Ok(_) => println!(" ✅ Base branch updated successfully"),
3109 Err(e) => {
3110 println!(" ⚠️ Warning: Failed to update base branch: {e}");
3111 println!(
3112 " 💡 You may want to manually run: git pull origin {base_branch}"
3113 );
3114 }
3115 }
3116
3117 let mut rebase_manager = crate::stack::RebaseManager::new(
3119 StackManager::new(&repo_root)?,
3120 git_repo,
3121 crate::stack::RebaseOptions {
3122 strategy: crate::stack::RebaseStrategy::ForcePush,
3123 target_base: Some(base_branch.clone()),
3124 ..Default::default()
3125 },
3126 );
3127
3128 match rebase_manager.rebase_stack(&stack_id) {
3129 Ok(rebase_result) => {
3130 if !rebase_result.branch_mapping.is_empty() {
3131 let retarget_config = crate::config::CascadeConfig {
3133 bitbucket: Some(settings.bitbucket.clone()),
3134 git: settings.git.clone(),
3135 auth: crate::config::AuthConfig::default(),
3136 cascade: settings.cascade.clone(),
3137 };
3138 let mut retarget_integration = BitbucketIntegration::new(
3139 StackManager::new(&repo_root)?,
3140 retarget_config,
3141 )?;
3142
3143 match retarget_integration
3144 .update_prs_after_rebase(
3145 &stack_id,
3146 &rebase_result.branch_mapping,
3147 )
3148 .await
3149 {
3150 Ok(updated_prs) => {
3151 if !updated_prs.is_empty() {
3152 println!(
3153 " ✅ Updated {} PRs with new targets",
3154 updated_prs.len()
3155 );
3156 }
3157 }
3158 Err(e) => {
3159 println!(" ⚠️ Failed to update remaining PRs: {e}");
3160 println!(
3161 " 💡 You may need to run: ca stack rebase --onto {base_branch}"
3162 );
3163 }
3164 }
3165 }
3166 }
3167 Err(e) => {
3168 println!(" ❌ Auto-retargeting conflicts detected!");
3170 println!(" 📝 To resolve conflicts and continue landing:");
3171 println!(" 1. Resolve conflicts in the affected files");
3172 println!(" 2. Stage resolved files: git add <files>");
3173 println!(" 3. Continue the process: ca stack continue-land");
3174 println!(" 4. Or abort the operation: ca stack abort-land");
3175 println!();
3176 println!(" 💡 Check current status: ca stack land-status");
3177 println!(" ⚠️ Error details: {e}");
3178
3179 break;
3181 }
3182 }
3183 }
3184 }
3185 Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
3186 println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
3187 failed_count += 1;
3188 if !force {
3189 break;
3190 }
3191 }
3192 Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
3193 println!(" ❌ Failed: {error}");
3194 failed_count += 1;
3195 if !force {
3196 break;
3197 }
3198 }
3199 Err(e) => {
3200 println!(" ❌");
3201 eprintln!("Failed to land PR #{pr_id}: {e}");
3202 failed_count += 1;
3203
3204 if !force {
3205 break;
3206 }
3207 }
3208 }
3209 }
3210
3211 println!("\n🎯 Landing Summary:");
3213 println!(" ✅ Successfully landed: {landed_count}");
3214 if failed_count > 0 {
3215 println!(" ❌ Failed to land: {failed_count}");
3216 }
3217
3218 if landed_count > 0 {
3219 println!("✅ Landing operation completed!");
3220 } else {
3221 println!("❌ No PRs were successfully landed");
3222 }
3223
3224 Ok(())
3225}
3226
3227async fn auto_land_stack(
3229 force: bool,
3230 dry_run: bool,
3231 wait_for_builds: bool,
3232 strategy: Option<MergeStrategyArg>,
3233 build_timeout: u64,
3234) -> Result<()> {
3235 land_stack(
3237 None,
3238 force,
3239 dry_run,
3240 true, wait_for_builds,
3242 strategy,
3243 build_timeout,
3244 )
3245 .await
3246}
3247
3248async fn continue_land() -> Result<()> {
3249 let current_dir = env::current_dir()
3250 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3251
3252 let repo_root = find_repository_root(¤t_dir)
3253 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3254
3255 let stack_manager = StackManager::new(&repo_root)?;
3256 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3257 let options = crate::stack::RebaseOptions::default();
3258 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3259
3260 if !rebase_manager.is_rebase_in_progress() {
3261 println!("ℹ️ No rebase in progress");
3262 return Ok(());
3263 }
3264
3265 println!("🔄 Continuing land operation...");
3266 match rebase_manager.continue_rebase() {
3267 Ok(_) => {
3268 println!("✅ Land operation continued successfully");
3269 println!(" Check 'ca stack land-status' for current state");
3270 }
3271 Err(e) => {
3272 warn!("❌ Failed to continue land operation: {}", e);
3273 println!("💡 You may need to resolve conflicts first:");
3274 println!(" 1. Edit conflicted files");
3275 println!(" 2. Stage resolved files with 'git add'");
3276 println!(" 3. Run 'ca stack continue-land' again");
3277 }
3278 }
3279
3280 Ok(())
3281}
3282
3283async fn abort_land() -> Result<()> {
3284 let current_dir = env::current_dir()
3285 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3286
3287 let repo_root = find_repository_root(¤t_dir)
3288 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3289
3290 let stack_manager = StackManager::new(&repo_root)?;
3291 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3292 let options = crate::stack::RebaseOptions::default();
3293 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3294
3295 if !rebase_manager.is_rebase_in_progress() {
3296 println!("ℹ️ No rebase in progress");
3297 return Ok(());
3298 }
3299
3300 println!("⚠️ Aborting land operation...");
3301 match rebase_manager.abort_rebase() {
3302 Ok(_) => {
3303 println!("✅ Land operation aborted successfully");
3304 println!(" Repository restored to pre-land state");
3305 }
3306 Err(e) => {
3307 warn!("❌ Failed to abort land operation: {}", e);
3308 println!("⚠️ You may need to manually clean up the repository state");
3309 }
3310 }
3311
3312 Ok(())
3313}
3314
3315async fn land_status() -> Result<()> {
3316 let current_dir = env::current_dir()
3317 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3318
3319 let repo_root = find_repository_root(¤t_dir)
3320 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3321
3322 let stack_manager = StackManager::new(&repo_root)?;
3323 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3324
3325 println!("📊 Land Status");
3326
3327 let git_dir = repo_root.join(".git");
3329 let land_in_progress = git_dir.join("REBASE_HEAD").exists()
3330 || git_dir.join("rebase-merge").exists()
3331 || git_dir.join("rebase-apply").exists();
3332
3333 if land_in_progress {
3334 println!(" Status: 🔄 Land operation in progress");
3335 println!(
3336 "
3337📝 Actions available:"
3338 );
3339 println!(" - 'ca stack continue-land' to continue");
3340 println!(" - 'ca stack abort-land' to abort");
3341 println!(" - 'git status' to see conflicted files");
3342
3343 match git_repo.get_status() {
3345 Ok(statuses) => {
3346 let mut conflicts = Vec::new();
3347 for status in statuses.iter() {
3348 if status.status().contains(git2::Status::CONFLICTED) {
3349 if let Some(path) = status.path() {
3350 conflicts.push(path.to_string());
3351 }
3352 }
3353 }
3354
3355 if !conflicts.is_empty() {
3356 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
3357 for conflict in conflicts {
3358 println!(" - {conflict}");
3359 }
3360 println!(
3361 "
3362💡 To resolve conflicts:"
3363 );
3364 println!(" 1. Edit the conflicted files");
3365 println!(" 2. Stage resolved files: git add <file>");
3366 println!(" 3. Continue: ca stack continue-land");
3367 }
3368 }
3369 Err(e) => {
3370 warn!("Failed to get git status: {}", e);
3371 }
3372 }
3373 } else {
3374 println!(" Status: ✅ No land operation in progress");
3375
3376 if let Some(active_stack) = stack_manager.get_active_stack() {
3378 println!(" Active stack: {}", active_stack.name);
3379 println!(" Entries: {}", active_stack.entries.len());
3380 println!(" Base branch: {}", active_stack.base_branch);
3381 }
3382 }
3383
3384 Ok(())
3385}
3386
3387async fn repair_stack_data() -> Result<()> {
3388 let current_dir = env::current_dir()
3389 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3390
3391 let repo_root = find_repository_root(¤t_dir)
3392 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3393
3394 let mut stack_manager = StackManager::new(&repo_root)?;
3395
3396 println!("🔧 Repairing stack data consistency...");
3397
3398 stack_manager.repair_all_stacks()?;
3399
3400 println!("✅ Stack data consistency repaired successfully!");
3401 println!("💡 Run 'ca stack --mergeable' to see updated status");
3402
3403 Ok(())
3404}
3405
3406async fn cleanup_branches(
3408 dry_run: bool,
3409 force: bool,
3410 include_stale: bool,
3411 stale_days: u32,
3412 cleanup_remote: bool,
3413 include_non_stack: bool,
3414 verbose: bool,
3415) -> Result<()> {
3416 let current_dir = env::current_dir()
3417 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3418
3419 let repo_root = find_repository_root(¤t_dir)
3420 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3421
3422 let stack_manager = StackManager::new(&repo_root)?;
3423 let git_repo = GitRepository::open(&repo_root)?;
3424
3425 let result = perform_cleanup(
3426 &stack_manager,
3427 &git_repo,
3428 dry_run,
3429 force,
3430 include_stale,
3431 stale_days,
3432 cleanup_remote,
3433 include_non_stack,
3434 verbose,
3435 )
3436 .await?;
3437
3438 if result.total_candidates == 0 {
3440 Output::success("No branches found that need cleanup");
3441 return Ok(());
3442 }
3443
3444 Output::section("Cleanup Results");
3445
3446 if dry_run {
3447 Output::sub_item(format!(
3448 "Found {} branches that would be cleaned up",
3449 result.total_candidates
3450 ));
3451 } else {
3452 if !result.cleaned_branches.is_empty() {
3453 Output::success(format!(
3454 "Successfully cleaned up {} branches",
3455 result.cleaned_branches.len()
3456 ));
3457 for branch in &result.cleaned_branches {
3458 Output::sub_item(format!("🗑️ Deleted: {branch}"));
3459 }
3460 }
3461
3462 if !result.skipped_branches.is_empty() {
3463 Output::sub_item(format!(
3464 "Skipped {} branches",
3465 result.skipped_branches.len()
3466 ));
3467 if verbose {
3468 for (branch, reason) in &result.skipped_branches {
3469 Output::sub_item(format!("⏭️ {branch}: {reason}"));
3470 }
3471 }
3472 }
3473
3474 if !result.failed_branches.is_empty() {
3475 Output::warning(format!(
3476 "Failed to clean up {} branches",
3477 result.failed_branches.len()
3478 ));
3479 for (branch, error) in &result.failed_branches {
3480 Output::sub_item(format!("❌ {branch}: {error}"));
3481 }
3482 }
3483 }
3484
3485 Ok(())
3486}
3487
3488#[allow(clippy::too_many_arguments)]
3490async fn perform_cleanup(
3491 stack_manager: &StackManager,
3492 git_repo: &GitRepository,
3493 dry_run: bool,
3494 force: bool,
3495 include_stale: bool,
3496 stale_days: u32,
3497 cleanup_remote: bool,
3498 include_non_stack: bool,
3499 verbose: bool,
3500) -> Result<CleanupResult> {
3501 let options = CleanupOptions {
3502 dry_run,
3503 force,
3504 include_stale,
3505 cleanup_remote,
3506 stale_threshold_days: stale_days,
3507 cleanup_non_stack: include_non_stack,
3508 };
3509
3510 let stack_manager_copy = StackManager::new(stack_manager.repo_path())?;
3511 let git_repo_copy = GitRepository::open(git_repo.path())?;
3512 let mut cleanup_manager = CleanupManager::new(stack_manager_copy, git_repo_copy, options);
3513
3514 let candidates = cleanup_manager.find_cleanup_candidates()?;
3516
3517 if candidates.is_empty() {
3518 return Ok(CleanupResult {
3519 cleaned_branches: Vec::new(),
3520 failed_branches: Vec::new(),
3521 skipped_branches: Vec::new(),
3522 total_candidates: 0,
3523 });
3524 }
3525
3526 if verbose || dry_run {
3528 Output::section("Cleanup Candidates");
3529 for candidate in &candidates {
3530 let reason_icon = match candidate.reason {
3531 crate::stack::CleanupReason::FullyMerged => "🔀",
3532 crate::stack::CleanupReason::StackEntryMerged => "✅",
3533 crate::stack::CleanupReason::Stale => "⏰",
3534 crate::stack::CleanupReason::Orphaned => "👻",
3535 };
3536
3537 Output::sub_item(format!(
3538 "{} {} - {} ({})",
3539 reason_icon,
3540 candidate.branch_name,
3541 candidate.reason_to_string(),
3542 candidate.safety_info
3543 ));
3544 }
3545 }
3546
3547 if !force && !dry_run && !candidates.is_empty() {
3549 Output::warning(format!("About to delete {} branches", candidates.len()));
3550
3551 let preview_count = 5.min(candidates.len());
3553 for candidate in candidates.iter().take(preview_count) {
3554 println!(" • {}", candidate.branch_name);
3555 }
3556 if candidates.len() > preview_count {
3557 println!(" ... and {} more", candidates.len() - preview_count);
3558 }
3559 println!(); let should_continue = Confirm::with_theme(&ColorfulTheme::default())
3563 .with_prompt("Continue with branch cleanup?")
3564 .default(false)
3565 .interact()
3566 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
3567
3568 if !should_continue {
3569 Output::sub_item("Cleanup cancelled");
3570 return Ok(CleanupResult {
3571 cleaned_branches: Vec::new(),
3572 failed_branches: Vec::new(),
3573 skipped_branches: Vec::new(),
3574 total_candidates: candidates.len(),
3575 });
3576 }
3577 }
3578
3579 cleanup_manager.perform_cleanup(&candidates)
3581}
3582
3583async fn perform_simple_cleanup(
3585 stack_manager: &StackManager,
3586 git_repo: &GitRepository,
3587 dry_run: bool,
3588) -> Result<CleanupResult> {
3589 perform_cleanup(
3590 stack_manager,
3591 git_repo,
3592 dry_run,
3593 false, false, 30, false, false, false, )
3600 .await
3601}
3602
3603async fn analyze_commits_for_safeguards(
3605 commits_to_push: &[String],
3606 repo: &GitRepository,
3607 dry_run: bool,
3608) -> Result<()> {
3609 const LARGE_COMMIT_THRESHOLD: usize = 10;
3610 const WEEK_IN_SECONDS: i64 = 7 * 24 * 3600;
3611
3612 if commits_to_push.len() > LARGE_COMMIT_THRESHOLD {
3614 println!(
3615 "⚠️ Warning: About to push {} commits to stack",
3616 commits_to_push.len()
3617 );
3618 println!(" This may indicate a merge commit issue or unexpected commit range.");
3619 println!(" Large commit counts often result from merging instead of rebasing.");
3620
3621 if !dry_run && !confirm_large_push(commits_to_push.len())? {
3622 return Err(CascadeError::config("Push cancelled by user"));
3623 }
3624 }
3625
3626 let commit_objects: Result<Vec<_>> = commits_to_push
3628 .iter()
3629 .map(|hash| repo.get_commit(hash))
3630 .collect();
3631 let commit_objects = commit_objects?;
3632
3633 let merge_commits: Vec<_> = commit_objects
3635 .iter()
3636 .filter(|c| c.parent_count() > 1)
3637 .collect();
3638
3639 if !merge_commits.is_empty() {
3640 println!(
3641 "⚠️ Warning: {} merge commits detected in push",
3642 merge_commits.len()
3643 );
3644 println!(" This often indicates you merged instead of rebased.");
3645 println!(" Consider using 'ca sync' to rebase on the base branch.");
3646 println!(" Merge commits in stacks can cause confusion and duplicate work.");
3647 }
3648
3649 if commit_objects.len() > 1 {
3651 let oldest_commit_time = commit_objects.first().unwrap().time().seconds();
3652 let newest_commit_time = commit_objects.last().unwrap().time().seconds();
3653 let time_span = newest_commit_time - oldest_commit_time;
3654
3655 if time_span > WEEK_IN_SECONDS {
3656 let days = time_span / (24 * 3600);
3657 println!("⚠️ Warning: Commits span {days} days");
3658 println!(" This may indicate merged history rather than new work.");
3659 println!(" Recent work should typically span hours or days, not weeks.");
3660 }
3661 }
3662
3663 if commits_to_push.len() > 5 {
3665 println!("💡 Tip: If you only want recent commits, use:");
3666 println!(
3667 " ca push --since HEAD~{} # pushes last {} commits",
3668 std::cmp::min(commits_to_push.len(), 5),
3669 std::cmp::min(commits_to_push.len(), 5)
3670 );
3671 println!(" ca push --commits <hash1>,<hash2> # pushes specific commits");
3672 println!(" ca push --dry-run # preview what would be pushed");
3673 }
3674
3675 if dry_run {
3677 println!("🔍 DRY RUN: Would push {} commits:", commits_to_push.len());
3678 for (i, (commit_hash, commit_obj)) in commits_to_push
3679 .iter()
3680 .zip(commit_objects.iter())
3681 .enumerate()
3682 {
3683 let summary = commit_obj.summary().unwrap_or("(no message)");
3684 let short_hash = &commit_hash[..std::cmp::min(commit_hash.len(), 7)];
3685 println!(" {}: {} ({})", i + 1, summary, short_hash);
3686 }
3687 println!("💡 Run without --dry-run to actually push these commits.");
3688 }
3689
3690 Ok(())
3691}
3692
3693fn confirm_large_push(count: usize) -> Result<bool> {
3695 let should_continue = Confirm::with_theme(&ColorfulTheme::default())
3697 .with_prompt(format!("Continue pushing {count} commits?"))
3698 .default(false)
3699 .interact()
3700 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
3701
3702 Ok(should_continue)
3703}
3704
3705#[cfg(test)]
3706mod tests {
3707 use super::*;
3708 use std::process::Command;
3709 use tempfile::TempDir;
3710
3711 fn create_test_repo() -> Result<(TempDir, std::path::PathBuf)> {
3712 let temp_dir = TempDir::new()
3713 .map_err(|e| CascadeError::config(format!("Failed to create temp directory: {e}")))?;
3714 let repo_path = temp_dir.path().to_path_buf();
3715
3716 let output = Command::new("git")
3718 .args(["init"])
3719 .current_dir(&repo_path)
3720 .output()
3721 .map_err(|e| CascadeError::config(format!("Failed to run git init: {e}")))?;
3722 if !output.status.success() {
3723 return Err(CascadeError::config("Git init failed".to_string()));
3724 }
3725
3726 let output = Command::new("git")
3727 .args(["config", "user.name", "Test User"])
3728 .current_dir(&repo_path)
3729 .output()
3730 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3731 if !output.status.success() {
3732 return Err(CascadeError::config(
3733 "Git config user.name failed".to_string(),
3734 ));
3735 }
3736
3737 let output = Command::new("git")
3738 .args(["config", "user.email", "test@example.com"])
3739 .current_dir(&repo_path)
3740 .output()
3741 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3742 if !output.status.success() {
3743 return Err(CascadeError::config(
3744 "Git config user.email failed".to_string(),
3745 ));
3746 }
3747
3748 std::fs::write(repo_path.join("README.md"), "# Test")
3750 .map_err(|e| CascadeError::config(format!("Failed to write file: {e}")))?;
3751 let output = Command::new("git")
3752 .args(["add", "."])
3753 .current_dir(&repo_path)
3754 .output()
3755 .map_err(|e| CascadeError::config(format!("Failed to run git add: {e}")))?;
3756 if !output.status.success() {
3757 return Err(CascadeError::config("Git add failed".to_string()));
3758 }
3759
3760 let output = Command::new("git")
3761 .args(["commit", "-m", "Initial commit"])
3762 .current_dir(&repo_path)
3763 .output()
3764 .map_err(|e| CascadeError::config(format!("Failed to run git commit: {e}")))?;
3765 if !output.status.success() {
3766 return Err(CascadeError::config("Git commit failed".to_string()));
3767 }
3768
3769 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))?;
3771
3772 Ok((temp_dir, repo_path))
3773 }
3774
3775 #[tokio::test]
3776 async fn test_create_stack() {
3777 let (temp_dir, repo_path) = match create_test_repo() {
3778 Ok(repo) => repo,
3779 Err(_) => {
3780 println!("Skipping test due to git environment setup failure");
3781 return;
3782 }
3783 };
3784 let _ = &temp_dir;
3786
3787 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3791 match env::set_current_dir(&repo_path) {
3792 Ok(_) => {
3793 let result = create_stack(
3794 "test-stack".to_string(),
3795 None, Some("Test description".to_string()),
3797 )
3798 .await;
3799
3800 if let Ok(orig) = original_dir {
3802 let _ = env::set_current_dir(orig);
3803 }
3804
3805 assert!(
3806 result.is_ok(),
3807 "Stack creation should succeed in initialized repository"
3808 );
3809 }
3810 Err(_) => {
3811 println!("Skipping test due to directory access restrictions");
3813 }
3814 }
3815 }
3816
3817 #[tokio::test]
3818 async fn test_list_empty_stacks() {
3819 let (temp_dir, repo_path) = match create_test_repo() {
3820 Ok(repo) => repo,
3821 Err(_) => {
3822 println!("Skipping test due to git environment setup failure");
3823 return;
3824 }
3825 };
3826 let _ = &temp_dir;
3828
3829 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3833 match env::set_current_dir(&repo_path) {
3834 Ok(_) => {
3835 let result = list_stacks(false, false, None).await;
3836
3837 if let Ok(orig) = original_dir {
3839 let _ = env::set_current_dir(orig);
3840 }
3841
3842 assert!(
3843 result.is_ok(),
3844 "Listing stacks should succeed in initialized repository"
3845 );
3846 }
3847 Err(_) => {
3848 println!("Skipping test due to directory access restrictions");
3850 }
3851 }
3852 }
3853
3854 #[test]
3857 fn test_extract_feature_from_wip_basic() {
3858 let messages = vec![
3859 "WIP: add authentication".to_string(),
3860 "WIP: implement login flow".to_string(),
3861 ];
3862
3863 let result = extract_feature_from_wip(&messages);
3864 assert_eq!(result, "Add authentication");
3865 }
3866
3867 #[test]
3868 fn test_extract_feature_from_wip_capitalize() {
3869 let messages = vec!["WIP: fix user validation bug".to_string()];
3870
3871 let result = extract_feature_from_wip(&messages);
3872 assert_eq!(result, "Fix user validation bug");
3873 }
3874
3875 #[test]
3876 fn test_extract_feature_from_wip_fallback() {
3877 let messages = vec![
3878 "WIP user interface changes".to_string(),
3879 "wip: css styling".to_string(),
3880 ];
3881
3882 let result = extract_feature_from_wip(&messages);
3883 assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
3885 }
3886
3887 #[test]
3888 fn test_extract_feature_from_wip_empty() {
3889 let messages = vec![];
3890
3891 let result = extract_feature_from_wip(&messages);
3892 assert_eq!(result, "Squashed 0 commits");
3893 }
3894
3895 #[test]
3896 fn test_extract_feature_from_wip_short_message() {
3897 let messages = vec!["WIP: x".to_string()]; let result = extract_feature_from_wip(&messages);
3900 assert!(result.starts_with("Implement") || result.contains("Squashed"));
3901 }
3902
3903 #[test]
3906 fn test_squash_message_final_strategy() {
3907 let messages = [
3911 "Final: implement user authentication system".to_string(),
3912 "WIP: add tests".to_string(),
3913 "WIP: fix validation".to_string(),
3914 ];
3915
3916 assert!(messages[0].starts_with("Final:"));
3918
3919 let extracted = messages[0].trim_start_matches("Final:").trim();
3921 assert_eq!(extracted, "implement user authentication system");
3922 }
3923
3924 #[test]
3925 fn test_squash_message_wip_detection() {
3926 let messages = [
3927 "WIP: start feature".to_string(),
3928 "WIP: continue work".to_string(),
3929 "WIP: almost done".to_string(),
3930 "Regular commit message".to_string(),
3931 ];
3932
3933 let wip_count = messages
3934 .iter()
3935 .filter(|m| {
3936 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
3937 })
3938 .count();
3939
3940 assert_eq!(wip_count, 3); assert!(wip_count > messages.len() / 2); let non_wip: Vec<&String> = messages
3945 .iter()
3946 .filter(|m| {
3947 !m.to_lowercase().starts_with("wip")
3948 && !m.to_lowercase().contains("work in progress")
3949 })
3950 .collect();
3951
3952 assert_eq!(non_wip.len(), 1);
3953 assert_eq!(non_wip[0], "Regular commit message");
3954 }
3955
3956 #[test]
3957 fn test_squash_message_all_wip() {
3958 let messages = vec![
3959 "WIP: add feature A".to_string(),
3960 "WIP: add feature B".to_string(),
3961 "WIP: finish implementation".to_string(),
3962 ];
3963
3964 let result = extract_feature_from_wip(&messages);
3965 assert_eq!(result, "Add feature A");
3967 }
3968
3969 #[test]
3970 fn test_squash_message_edge_cases() {
3971 let empty_messages: Vec<String> = vec![];
3973 let result = extract_feature_from_wip(&empty_messages);
3974 assert_eq!(result, "Squashed 0 commits");
3975
3976 let whitespace_messages = vec![" ".to_string(), "\t\n".to_string()];
3978 let result = extract_feature_from_wip(&whitespace_messages);
3979 assert!(result.contains("Squashed") || result.contains("Implement"));
3980
3981 let mixed_case = vec!["wip: Add Feature".to_string()];
3983 let result = extract_feature_from_wip(&mixed_case);
3984 assert_eq!(result, "Add Feature");
3985 }
3986
3987 #[tokio::test]
3990 async fn test_auto_land_wrapper() {
3991 let (temp_dir, repo_path) = match create_test_repo() {
3993 Ok(repo) => repo,
3994 Err(_) => {
3995 println!("Skipping test due to git environment setup failure");
3996 return;
3997 }
3998 };
3999 let _ = &temp_dir;
4001
4002 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
4004 .expect("Failed to initialize Cascade in test repo");
4005
4006 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4007 match env::set_current_dir(&repo_path) {
4008 Ok(_) => {
4009 let result = create_stack(
4011 "test-stack".to_string(),
4012 None,
4013 Some("Test stack for auto-land".to_string()),
4014 )
4015 .await;
4016
4017 if let Ok(orig) = original_dir {
4018 let _ = env::set_current_dir(orig);
4019 }
4020
4021 assert!(
4024 result.is_ok(),
4025 "Stack creation should succeed in initialized repository"
4026 );
4027 }
4028 Err(_) => {
4029 println!("Skipping test due to directory access restrictions");
4030 }
4031 }
4032 }
4033
4034 #[test]
4035 fn test_auto_land_action_enum() {
4036 use crate::cli::commands::stack::StackAction;
4038
4039 let _action = StackAction::AutoLand {
4041 force: false,
4042 dry_run: true,
4043 wait_for_builds: true,
4044 strategy: Some(MergeStrategyArg::Squash),
4045 build_timeout: 1800,
4046 };
4047
4048 }
4050
4051 #[test]
4052 fn test_merge_strategy_conversion() {
4053 let squash_strategy = MergeStrategyArg::Squash;
4055 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
4056
4057 match merge_strategy {
4058 crate::bitbucket::pull_request::MergeStrategy::Squash => {
4059 }
4061 _ => unreachable!("SquashStrategyArg only has Squash variant"),
4062 }
4063
4064 let merge_strategy = MergeStrategyArg::Merge;
4065 let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
4066
4067 match converted {
4068 crate::bitbucket::pull_request::MergeStrategy::Merge => {
4069 }
4071 _ => unreachable!("MergeStrategyArg::Merge maps to MergeStrategy::Merge"),
4072 }
4073 }
4074
4075 #[test]
4076 fn test_auto_merge_conditions_structure() {
4077 use std::time::Duration;
4079
4080 let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
4081 merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
4082 wait_for_builds: true,
4083 build_timeout: Duration::from_secs(1800),
4084 allowed_authors: None,
4085 };
4086
4087 assert!(conditions.wait_for_builds);
4089 assert_eq!(conditions.build_timeout.as_secs(), 1800);
4090 assert!(conditions.allowed_authors.is_none());
4091 assert!(matches!(
4092 conditions.merge_strategy,
4093 crate::bitbucket::pull_request::MergeStrategy::Squash
4094 ));
4095 }
4096
4097 #[test]
4098 fn test_polling_constants() {
4099 use std::time::Duration;
4101
4102 let expected_polling_interval = Duration::from_secs(30);
4104
4105 assert!(expected_polling_interval.as_secs() >= 10); assert!(expected_polling_interval.as_secs() <= 60); assert_eq!(expected_polling_interval.as_secs(), 30); }
4110
4111 #[test]
4112 fn test_build_timeout_defaults() {
4113 const DEFAULT_TIMEOUT: u64 = 1800; assert_eq!(DEFAULT_TIMEOUT, 1800);
4116 let timeout_value = 1800u64;
4118 assert!(timeout_value >= 300); assert!(timeout_value <= 3600); }
4121
4122 #[test]
4123 fn test_scattered_commit_detection() {
4124 use std::collections::HashSet;
4125
4126 let mut source_branches = HashSet::new();
4128 source_branches.insert("feature-branch-1".to_string());
4129 source_branches.insert("feature-branch-2".to_string());
4130 source_branches.insert("feature-branch-3".to_string());
4131
4132 let single_branch = HashSet::from(["main".to_string()]);
4134 assert_eq!(single_branch.len(), 1);
4135
4136 assert!(source_branches.len() > 1);
4138 assert_eq!(source_branches.len(), 3);
4139
4140 assert!(source_branches.contains("feature-branch-1"));
4142 assert!(source_branches.contains("feature-branch-2"));
4143 assert!(source_branches.contains("feature-branch-3"));
4144 }
4145
4146 #[test]
4147 fn test_source_branch_tracking() {
4148 let branch_a = "feature-work";
4152 let branch_b = "feature-work";
4153 assert_eq!(branch_a, branch_b);
4154
4155 let branch_1 = "feature-ui";
4157 let branch_2 = "feature-api";
4158 assert_ne!(branch_1, branch_2);
4159
4160 assert!(branch_1.starts_with("feature-"));
4162 assert!(branch_2.starts_with("feature-"));
4163 }
4164
4165 #[tokio::test]
4168 async fn test_push_default_behavior() {
4169 let (temp_dir, repo_path) = match create_test_repo() {
4171 Ok(repo) => repo,
4172 Err(_) => {
4173 println!("Skipping test due to git environment setup failure");
4174 return;
4175 }
4176 };
4177 let _ = &temp_dir;
4179
4180 if !repo_path.exists() {
4182 println!("Skipping test due to temporary directory creation issue");
4183 return;
4184 }
4185
4186 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4188
4189 match env::set_current_dir(&repo_path) {
4190 Ok(_) => {
4191 let result = push_to_stack(
4193 None, None, None, None, None, None, None, false, false, false, )
4204 .await;
4205
4206 if let Ok(orig) = original_dir {
4208 let _ = env::set_current_dir(orig);
4209 }
4210
4211 match &result {
4213 Err(e) => {
4214 let error_msg = e.to_string();
4215 assert!(
4217 error_msg.contains("No active stack")
4218 || error_msg.contains("config")
4219 || error_msg.contains("current directory")
4220 || error_msg.contains("Not a git repository")
4221 || error_msg.contains("could not find repository"),
4222 "Expected 'No active stack' or repository error, got: {error_msg}"
4223 );
4224 }
4225 Ok(_) => {
4226 println!(
4228 "Push succeeded unexpectedly - test environment may have active stack"
4229 );
4230 }
4231 }
4232 }
4233 Err(_) => {
4234 println!("Skipping test due to directory access restrictions");
4236 }
4237 }
4238
4239 let push_action = StackAction::Push {
4241 branch: None,
4242 message: None,
4243 commit: None,
4244 since: None,
4245 commits: None,
4246 squash: None,
4247 squash_since: None,
4248 auto_branch: false,
4249 allow_base_branch: false,
4250 dry_run: false,
4251 };
4252
4253 assert!(matches!(
4254 push_action,
4255 StackAction::Push {
4256 branch: None,
4257 message: None,
4258 commit: None,
4259 since: None,
4260 commits: None,
4261 squash: None,
4262 squash_since: None,
4263 auto_branch: false,
4264 allow_base_branch: false,
4265 dry_run: false
4266 }
4267 ));
4268 }
4269
4270 #[tokio::test]
4271 async fn test_submit_default_behavior() {
4272 let (temp_dir, repo_path) = match create_test_repo() {
4274 Ok(repo) => repo,
4275 Err(_) => {
4276 println!("Skipping test due to git environment setup failure");
4277 return;
4278 }
4279 };
4280 let _ = &temp_dir;
4282
4283 if !repo_path.exists() {
4285 println!("Skipping test due to temporary directory creation issue");
4286 return;
4287 }
4288
4289 let original_dir = match env::current_dir() {
4291 Ok(dir) => dir,
4292 Err(_) => {
4293 println!("Skipping test due to current directory access restrictions");
4294 return;
4295 }
4296 };
4297
4298 match env::set_current_dir(&repo_path) {
4299 Ok(_) => {
4300 let result = submit_entry(
4302 None, None, None, None, false, )
4308 .await;
4309
4310 let _ = env::set_current_dir(original_dir);
4312
4313 match &result {
4315 Err(e) => {
4316 let error_msg = e.to_string();
4317 assert!(
4319 error_msg.contains("No active stack")
4320 || error_msg.contains("config")
4321 || error_msg.contains("current directory")
4322 || error_msg.contains("Not a git repository")
4323 || error_msg.contains("could not find repository"),
4324 "Expected 'No active stack' or repository error, got: {error_msg}"
4325 );
4326 }
4327 Ok(_) => {
4328 println!("Submit succeeded unexpectedly - test environment may have active stack");
4330 }
4331 }
4332 }
4333 Err(_) => {
4334 println!("Skipping test due to directory access restrictions");
4336 }
4337 }
4338
4339 let submit_action = StackAction::Submit {
4341 entry: None,
4342 title: None,
4343 description: None,
4344 range: None,
4345 draft: false,
4346 };
4347
4348 assert!(matches!(
4349 submit_action,
4350 StackAction::Submit {
4351 entry: None,
4352 title: None,
4353 description: None,
4354 range: None,
4355 draft: false
4356 }
4357 ));
4358 }
4359
4360 #[test]
4361 fn test_targeting_options_still_work() {
4362 let commits = "abc123,def456,ghi789";
4366 let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
4367 assert_eq!(parsed.len(), 3);
4368 assert_eq!(parsed[0], "abc123");
4369 assert_eq!(parsed[1], "def456");
4370 assert_eq!(parsed[2], "ghi789");
4371
4372 let range = "1-3";
4374 assert!(range.contains('-'));
4375 let parts: Vec<&str> = range.split('-').collect();
4376 assert_eq!(parts.len(), 2);
4377
4378 let since_ref = "HEAD~3";
4380 assert!(since_ref.starts_with("HEAD"));
4381 assert!(since_ref.contains('~'));
4382 }
4383
4384 #[test]
4385 fn test_command_flow_logic() {
4386 assert!(matches!(
4388 StackAction::Push {
4389 branch: None,
4390 message: None,
4391 commit: None,
4392 since: None,
4393 commits: None,
4394 squash: None,
4395 squash_since: None,
4396 auto_branch: false,
4397 allow_base_branch: false,
4398 dry_run: false
4399 },
4400 StackAction::Push { .. }
4401 ));
4402
4403 assert!(matches!(
4404 StackAction::Submit {
4405 entry: None,
4406 title: None,
4407 description: None,
4408 range: None,
4409 draft: false
4410 },
4411 StackAction::Submit { .. }
4412 ));
4413 }
4414
4415 #[tokio::test]
4416 async fn test_deactivate_command_structure() {
4417 let deactivate_action = StackAction::Deactivate { force: false };
4419
4420 assert!(matches!(
4422 deactivate_action,
4423 StackAction::Deactivate { force: false }
4424 ));
4425
4426 let force_deactivate = StackAction::Deactivate { force: true };
4428 assert!(matches!(
4429 force_deactivate,
4430 StackAction::Deactivate { force: true }
4431 ));
4432 }
4433}