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 indicatif::{ProgressBar, ProgressStyle};
9use 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: {}/{} approvals",
970 enhanced.review_status.current_approvals,
971 enhanced.review_status.required_approvals
972 );
973
974 if enhanced.review_status.needs_work_count > 0 {
975 println!(
976 " {} reviewers requested changes",
977 enhanced.review_status.needs_work_count
978 );
979 }
980
981 if let Some(build) = &enhanced.build_status {
983 let build_icon = match build.state {
984 crate::bitbucket::pull_request::BuildState::Successful => "✅",
985 crate::bitbucket::pull_request::BuildState::Failed => "❌",
986 crate::bitbucket::pull_request::BuildState::InProgress => "🔄",
987 _ => "⚪",
988 };
989 println!(" Build: {} {:?}", build_icon, build.state);
990 }
991
992 if let Some(url) = enhanced.pr.web_url() {
993 println!(" URL: {url}");
994 }
995 println!();
996 }
997 }
998
999 if ready_to_land > 0 {
1000 println!(
1001 "\n🎯 {} PR{} ready to land! Use 'ca land' to land them all.",
1002 ready_to_land,
1003 if ready_to_land == 1 { " is" } else { "s are" }
1004 );
1005 }
1006 }
1007 }
1008 Err(e) => {
1009 warn!("Failed to get enhanced stack status: {}", e);
1010 println!(" ⚠️ Could not fetch mergability status");
1011 println!(" Use 'ca stack show --verbose' for basic PR information");
1012 }
1013 }
1014 } else {
1015 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1017 let config_path = config_dir.join("config.json");
1018 let settings = crate::config::Settings::load_from_file(&config_path)?;
1019
1020 let cascade_config = crate::config::CascadeConfig {
1021 bitbucket: Some(settings.bitbucket.clone()),
1022 git: settings.git.clone(),
1023 auth: crate::config::AuthConfig::default(),
1024 cascade: settings.cascade.clone(),
1025 };
1026
1027 let integration =
1028 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1029
1030 match integration.check_stack_status(&stack_id).await {
1031 Ok(status) => {
1032 println!("\n📊 Pull Request Status:");
1033 println!(" Total entries: {}", status.total_entries);
1034 println!(" Submitted: {}", status.submitted_entries);
1035 println!(" Open PRs: {}", status.open_prs);
1036 println!(" Merged PRs: {}", status.merged_prs);
1037 println!(" Declined PRs: {}", status.declined_prs);
1038 println!(" Completion: {:.1}%", status.completion_percentage());
1039
1040 if !status.pull_requests.is_empty() {
1041 println!("\n📋 Pull Requests:");
1042 for pr in &status.pull_requests {
1043 let state_icon = match pr.state {
1044 crate::bitbucket::PullRequestState::Open => "🔄",
1045 crate::bitbucket::PullRequestState::Merged => "✅",
1046 crate::bitbucket::PullRequestState::Declined => "❌",
1047 };
1048 println!(
1049 " {} PR #{}: {} ({} -> {})",
1050 state_icon,
1051 pr.id,
1052 pr.title,
1053 pr.from_ref.display_id,
1054 pr.to_ref.display_id
1055 );
1056 if let Some(url) = pr.web_url() {
1057 println!(" URL: {url}");
1058 }
1059 }
1060 }
1061
1062 println!("\n💡 Use 'ca stack --mergeable' to see detailed status including build and review information");
1063 }
1064 Err(e) => {
1065 warn!("Failed to check stack status: {}", e);
1066 }
1067 }
1068 }
1069
1070 Ok(())
1071}
1072
1073#[allow(clippy::too_many_arguments)]
1074async fn push_to_stack(
1075 branch: Option<String>,
1076 message: Option<String>,
1077 commit: Option<String>,
1078 since: Option<String>,
1079 commits: Option<String>,
1080 squash: Option<usize>,
1081 squash_since: Option<String>,
1082 auto_branch: bool,
1083 allow_base_branch: bool,
1084 dry_run: bool,
1085) -> Result<()> {
1086 let current_dir = env::current_dir()
1087 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1088
1089 let repo_root = find_repository_root(¤t_dir)
1090 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1091
1092 let mut manager = StackManager::new(&repo_root)?;
1093 let repo = GitRepository::open(&repo_root)?;
1094
1095 if !manager.check_for_branch_change()? {
1097 return Ok(()); }
1099
1100 let active_stack = manager.get_active_stack().ok_or_else(|| {
1102 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1103 })?;
1104
1105 let current_branch = repo.get_current_branch()?;
1107 let base_branch = &active_stack.base_branch;
1108
1109 if current_branch == *base_branch {
1110 Output::error(format!(
1111 "You're currently on the base branch '{base_branch}'"
1112 ));
1113 Output::sub_item("Making commits directly on the base branch is not recommended.");
1114 Output::sub_item("This can pollute the base branch with work-in-progress commits.");
1115
1116 if allow_base_branch {
1118 Output::warning("Proceeding anyway due to --allow-base-branch flag");
1119 } else {
1120 let has_changes = repo.is_dirty()?;
1122
1123 if has_changes {
1124 if auto_branch {
1125 let feature_branch = format!("feature/{}-work", active_stack.name);
1127 Output::progress(format!(
1128 "Auto-creating feature branch '{feature_branch}'..."
1129 ));
1130
1131 repo.create_branch(&feature_branch, None)?;
1132 repo.checkout_branch(&feature_branch)?;
1133
1134 println!("✅ Created and switched to '{feature_branch}'");
1135 println!(" You can now commit and push your changes safely");
1136
1137 } else {
1139 println!("\n💡 You have uncommitted changes. Here are your options:");
1140 println!(" 1. Create a feature branch first:");
1141 println!(" git checkout -b feature/my-work");
1142 println!(" git commit -am \"your work\"");
1143 println!(" ca push");
1144 println!("\n 2. Auto-create a branch (recommended):");
1145 println!(" ca push --auto-branch");
1146 println!("\n 3. Force push to base branch (dangerous):");
1147 println!(" ca push --allow-base-branch");
1148
1149 return Err(CascadeError::config(
1150 "Refusing to push uncommitted changes from base branch. Use one of the options above."
1151 ));
1152 }
1153 } else {
1154 let commits_to_check = if let Some(commits_str) = &commits {
1156 commits_str
1157 .split(',')
1158 .map(|s| s.trim().to_string())
1159 .collect::<Vec<String>>()
1160 } else if let Some(since_ref) = &since {
1161 let since_commit = repo.resolve_reference(since_ref)?;
1162 let head_commit = repo.get_head_commit()?;
1163 let commits = repo.get_commits_between(
1164 &since_commit.id().to_string(),
1165 &head_commit.id().to_string(),
1166 )?;
1167 commits.into_iter().map(|c| c.id().to_string()).collect()
1168 } else if commit.is_none() {
1169 let mut unpushed = Vec::new();
1170 let head_commit = repo.get_head_commit()?;
1171 let mut current_commit = head_commit;
1172
1173 loop {
1174 let commit_hash = current_commit.id().to_string();
1175 let already_in_stack = active_stack
1176 .entries
1177 .iter()
1178 .any(|entry| entry.commit_hash == commit_hash);
1179
1180 if already_in_stack {
1181 break;
1182 }
1183
1184 unpushed.push(commit_hash);
1185
1186 if let Some(parent) = current_commit.parents().next() {
1187 current_commit = parent;
1188 } else {
1189 break;
1190 }
1191 }
1192
1193 unpushed.reverse();
1194 unpushed
1195 } else {
1196 vec![repo.get_head_commit()?.id().to_string()]
1197 };
1198
1199 if !commits_to_check.is_empty() {
1200 if auto_branch {
1201 let feature_branch = format!("feature/{}-work", active_stack.name);
1203 Output::progress(format!(
1204 "Auto-creating feature branch '{feature_branch}'..."
1205 ));
1206
1207 repo.create_branch(&feature_branch, Some(base_branch))?;
1208 repo.checkout_branch(&feature_branch)?;
1209
1210 println!(
1212 "🍒 Cherry-picking {} commit(s) to new branch...",
1213 commits_to_check.len()
1214 );
1215 for commit_hash in &commits_to_check {
1216 match repo.cherry_pick(commit_hash) {
1217 Ok(_) => println!(" ✅ Cherry-picked {}", &commit_hash[..8]),
1218 Err(e) => {
1219 println!(
1220 " ❌ Failed to cherry-pick {}: {}",
1221 &commit_hash[..8],
1222 e
1223 );
1224 println!(" 💡 You may need to resolve conflicts manually");
1225 return Err(CascadeError::branch(format!(
1226 "Failed to cherry-pick commit {commit_hash}: {e}"
1227 )));
1228 }
1229 }
1230 }
1231
1232 println!(
1233 "✅ Successfully moved {} commit(s) to '{feature_branch}'",
1234 commits_to_check.len()
1235 );
1236 println!(
1237 " You're now on the feature branch and can continue with 'ca push'"
1238 );
1239
1240 } else {
1242 println!(
1243 "\n💡 Found {} commit(s) to push from base branch '{base_branch}'",
1244 commits_to_check.len()
1245 );
1246 println!(" These commits are currently ON the base branch, which may not be intended.");
1247 println!("\n Options:");
1248 println!(" 1. Auto-create feature branch and cherry-pick commits:");
1249 println!(" ca push --auto-branch");
1250 println!("\n 2. Manually create branch and move commits:");
1251 println!(" git checkout -b feature/my-work");
1252 println!(" ca push");
1253 println!("\n 3. Force push from base branch (not recommended):");
1254 println!(" ca push --allow-base-branch");
1255
1256 return Err(CascadeError::config(
1257 "Refusing to push commits from base branch. Use --auto-branch or create a feature branch manually."
1258 ));
1259 }
1260 }
1261 }
1262 }
1263 }
1264
1265 if let Some(squash_count) = squash {
1267 if squash_count == 0 {
1268 let active_stack = manager.get_active_stack().ok_or_else(|| {
1270 CascadeError::config(
1271 "No active stack. Create a stack first with 'ca stacks create'",
1272 )
1273 })?;
1274
1275 let unpushed_count = get_unpushed_commits(&repo, active_stack)?.len();
1276
1277 if unpushed_count == 0 {
1278 println!("ℹ️ No unpushed commits to squash");
1279 } else if unpushed_count == 1 {
1280 println!("ℹ️ Only 1 unpushed commit, no squashing needed");
1281 } else {
1282 println!("🔄 Auto-detected {unpushed_count} unpushed commits, squashing...");
1283 squash_commits(&repo, unpushed_count, None).await?;
1284 println!("✅ Squashed {unpushed_count} unpushed commits into one");
1285 }
1286 } else {
1287 println!("🔄 Squashing last {squash_count} commits...");
1288 squash_commits(&repo, squash_count, None).await?;
1289 println!("✅ Squashed {squash_count} commits into one");
1290 }
1291 } else if let Some(since_ref) = squash_since {
1292 println!("🔄 Squashing commits since {since_ref}...");
1293 let since_commit = repo.resolve_reference(&since_ref)?;
1294 let commits_count = count_commits_since(&repo, &since_commit.id().to_string())?;
1295 squash_commits(&repo, commits_count, Some(since_ref.clone())).await?;
1296 println!("✅ Squashed {commits_count} commits since {since_ref} into one");
1297 }
1298
1299 let commits_to_push = if let Some(commits_str) = commits {
1301 commits_str
1303 .split(',')
1304 .map(|s| s.trim().to_string())
1305 .collect::<Vec<String>>()
1306 } else if let Some(since_ref) = since {
1307 let since_commit = repo.resolve_reference(&since_ref)?;
1309 let head_commit = repo.get_head_commit()?;
1310
1311 let commits = repo.get_commits_between(
1313 &since_commit.id().to_string(),
1314 &head_commit.id().to_string(),
1315 )?;
1316 commits.into_iter().map(|c| c.id().to_string()).collect()
1317 } else if let Some(hash) = commit {
1318 vec![hash]
1320 } else {
1321 let active_stack = manager.get_active_stack().ok_or_else(|| {
1323 CascadeError::config("No active stack. Create a stack first with 'ca stacks create'")
1324 })?;
1325
1326 let base_branch = &active_stack.base_branch;
1328 let current_branch = repo.get_current_branch()?;
1329
1330 if current_branch == *base_branch {
1332 let mut unpushed = Vec::new();
1333 let head_commit = repo.get_head_commit()?;
1334 let mut current_commit = head_commit;
1335
1336 loop {
1338 let commit_hash = current_commit.id().to_string();
1339 let already_in_stack = active_stack
1340 .entries
1341 .iter()
1342 .any(|entry| entry.commit_hash == commit_hash);
1343
1344 if already_in_stack {
1345 break;
1346 }
1347
1348 unpushed.push(commit_hash);
1349
1350 if let Some(parent) = current_commit.parents().next() {
1352 current_commit = parent;
1353 } else {
1354 break;
1355 }
1356 }
1357
1358 unpushed.reverse(); unpushed
1360 } else {
1361 match repo.get_commits_between(base_branch, ¤t_branch) {
1363 Ok(commits) => {
1364 let mut unpushed: Vec<String> =
1365 commits.into_iter().map(|c| c.id().to_string()).collect();
1366
1367 unpushed.retain(|commit_hash| {
1369 !active_stack
1370 .entries
1371 .iter()
1372 .any(|entry| entry.commit_hash == *commit_hash)
1373 });
1374
1375 unpushed.reverse(); unpushed
1377 }
1378 Err(e) => {
1379 return Err(CascadeError::branch(format!(
1380 "Failed to calculate commits between '{base_branch}' and '{current_branch}': {e}. \
1381 This usually means the branches have diverged or don't share common history."
1382 )));
1383 }
1384 }
1385 }
1386 };
1387
1388 if commits_to_push.is_empty() {
1389 println!("ℹ️ No commits to push to stack");
1390 return Ok(());
1391 }
1392
1393 analyze_commits_for_safeguards(&commits_to_push, &repo, dry_run).await?;
1395
1396 if dry_run {
1398 return Ok(());
1399 }
1400
1401 let mut pushed_count = 0;
1403 let mut source_branches = std::collections::HashSet::new();
1404
1405 for (i, commit_hash) in commits_to_push.iter().enumerate() {
1406 let commit_obj = repo.get_commit(commit_hash)?;
1407 let commit_msg = commit_obj.message().unwrap_or("").to_string();
1408
1409 let commit_source_branch = repo
1411 .find_branch_containing_commit(commit_hash)
1412 .unwrap_or_else(|_| current_branch.clone());
1413 source_branches.insert(commit_source_branch.clone());
1414
1415 let branch_name = if i == 0 && branch.is_some() {
1417 branch.clone().unwrap()
1418 } else {
1419 let temp_repo = GitRepository::open(&repo_root)?;
1421 let branch_mgr = crate::git::BranchManager::new(temp_repo);
1422 branch_mgr.generate_branch_name(&commit_msg)
1423 };
1424
1425 let final_message = if i == 0 && message.is_some() {
1427 message.clone().unwrap()
1428 } else {
1429 commit_msg.clone()
1430 };
1431
1432 let entry_id = manager.push_to_stack(
1433 branch_name.clone(),
1434 commit_hash.clone(),
1435 final_message.clone(),
1436 commit_source_branch.clone(),
1437 )?;
1438 pushed_count += 1;
1439
1440 Output::success(format!(
1441 "Pushed commit {}/{} to stack",
1442 i + 1,
1443 commits_to_push.len()
1444 ));
1445 Output::sub_item(format!(
1446 "Commit: {} ({})",
1447 &commit_hash[..8],
1448 commit_msg.split('\n').next().unwrap_or("")
1449 ));
1450 Output::sub_item(format!("Branch: {branch_name}"));
1451 Output::sub_item(format!("Source: {commit_source_branch}"));
1452 Output::sub_item(format!("Entry ID: {entry_id}"));
1453 println!();
1454 }
1455
1456 if source_branches.len() > 1 {
1458 Output::warning("Scattered Commit Detection");
1459 Output::sub_item(format!(
1460 "You've pushed commits from {} different Git branches:",
1461 source_branches.len()
1462 ));
1463 for branch in &source_branches {
1464 Output::bullet(branch.to_string());
1465 }
1466
1467 Output::section("This can lead to confusion because:");
1468 Output::bullet("Stack appears sequential but commits are scattered across branches");
1469 Output::bullet("Team members won't know which branch contains which work");
1470 Output::bullet("Branch cleanup becomes unclear after merge");
1471 Output::bullet("Rebase operations become more complex");
1472
1473 Output::tip("Consider consolidating work to a single feature branch:");
1474 Output::bullet("Create a new feature branch: git checkout -b feature/consolidated-work");
1475 Output::bullet("Cherry-pick commits in order: git cherry-pick <commit1> <commit2> ...");
1476 Output::bullet("Delete old scattered branches");
1477 Output::bullet("Push the consolidated branch to your stack");
1478 println!();
1479 }
1480
1481 Output::success(format!(
1482 "Successfully pushed {} commit{} to stack",
1483 pushed_count,
1484 if pushed_count == 1 { "" } else { "s" }
1485 ));
1486
1487 Ok(())
1488}
1489
1490async fn pop_from_stack(keep_branch: bool) -> Result<()> {
1491 let current_dir = env::current_dir()
1492 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1493
1494 let repo_root = find_repository_root(¤t_dir)
1495 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1496
1497 let mut manager = StackManager::new(&repo_root)?;
1498 let repo = GitRepository::open(&repo_root)?;
1499
1500 let entry = manager.pop_from_stack()?;
1501
1502 Output::success("Popped commit from stack");
1503 Output::sub_item(format!(
1504 "Commit: {} ({})",
1505 entry.short_hash(),
1506 entry.short_message(50)
1507 ));
1508 Output::sub_item(format!("Branch: {}", entry.branch));
1509
1510 if !keep_branch && entry.branch != repo.get_current_branch()? {
1512 match repo.delete_branch(&entry.branch) {
1513 Ok(_) => Output::sub_item(format!("Deleted branch: {}", entry.branch)),
1514 Err(e) => Output::warning(format!("Could not delete branch {}: {}", entry.branch, e)),
1515 }
1516 }
1517
1518 Ok(())
1519}
1520
1521async fn submit_entry(
1522 entry: Option<usize>,
1523 title: Option<String>,
1524 description: Option<String>,
1525 range: Option<String>,
1526 draft: bool,
1527) -> Result<()> {
1528 let current_dir = env::current_dir()
1529 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1530
1531 let repo_root = find_repository_root(¤t_dir)
1532 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1533
1534 let mut stack_manager = StackManager::new(&repo_root)?;
1535
1536 if !stack_manager.check_for_branch_change()? {
1538 return Ok(()); }
1540
1541 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1543 let config_path = config_dir.join("config.json");
1544 let settings = crate::config::Settings::load_from_file(&config_path)?;
1545
1546 let cascade_config = crate::config::CascadeConfig {
1548 bitbucket: Some(settings.bitbucket.clone()),
1549 git: settings.git.clone(),
1550 auth: crate::config::AuthConfig::default(),
1551 cascade: settings.cascade.clone(),
1552 };
1553
1554 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1556 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1557 })?;
1558 let stack_id = active_stack.id;
1559
1560 let entries_to_submit = if let Some(range_str) = range {
1562 let mut entries = Vec::new();
1564
1565 if range_str.contains('-') {
1566 let parts: Vec<&str> = range_str.split('-').collect();
1568 if parts.len() != 2 {
1569 return Err(CascadeError::config(
1570 "Invalid range format. Use 'start-end' (e.g., '1-3')",
1571 ));
1572 }
1573
1574 let start: usize = parts[0]
1575 .parse()
1576 .map_err(|_| CascadeError::config("Invalid start number in range"))?;
1577 let end: usize = parts[1]
1578 .parse()
1579 .map_err(|_| CascadeError::config("Invalid end number in range"))?;
1580
1581 if start == 0
1582 || end == 0
1583 || start > active_stack.entries.len()
1584 || end > active_stack.entries.len()
1585 {
1586 return Err(CascadeError::config(format!(
1587 "Range out of bounds. Stack has {} entries",
1588 active_stack.entries.len()
1589 )));
1590 }
1591
1592 for i in start..=end {
1593 entries.push((i, active_stack.entries[i - 1].clone()));
1594 }
1595 } else {
1596 for entry_str in range_str.split(',') {
1598 let entry_num: usize = entry_str.trim().parse().map_err(|_| {
1599 CascadeError::config(format!("Invalid entry number: {entry_str}"))
1600 })?;
1601
1602 if entry_num == 0 || entry_num > active_stack.entries.len() {
1603 return Err(CascadeError::config(format!(
1604 "Entry {} out of bounds. Stack has {} entries",
1605 entry_num,
1606 active_stack.entries.len()
1607 )));
1608 }
1609
1610 entries.push((entry_num, active_stack.entries[entry_num - 1].clone()));
1611 }
1612 }
1613
1614 entries
1615 } else if let Some(entry_num) = entry {
1616 if entry_num == 0 || entry_num > active_stack.entries.len() {
1618 return Err(CascadeError::config(format!(
1619 "Invalid entry number: {}. Stack has {} entries",
1620 entry_num,
1621 active_stack.entries.len()
1622 )));
1623 }
1624 vec![(entry_num, active_stack.entries[entry_num - 1].clone())]
1625 } else {
1626 active_stack
1628 .entries
1629 .iter()
1630 .enumerate()
1631 .filter(|(_, entry)| !entry.is_submitted)
1632 .map(|(i, entry)| (i + 1, entry.clone())) .collect::<Vec<(usize, _)>>()
1634 };
1635
1636 if entries_to_submit.is_empty() {
1637 Output::info("No entries to submit");
1638 return Ok(());
1639 }
1640
1641 let total_operations = entries_to_submit.len() + 2; let pb = ProgressBar::new(total_operations as u64);
1644 pb.set_style(
1645 ProgressStyle::default_bar()
1646 .template("📤 {msg} [{bar:40.cyan/blue}] {pos}/{len}")
1647 .map_err(|e| CascadeError::config(format!("Progress bar template error: {e}")))?,
1648 );
1649
1650 pb.set_message("Connecting to Bitbucket");
1651 pb.inc(1);
1652
1653 let integration_stack_manager = StackManager::new(&repo_root)?;
1655 let mut integration =
1656 BitbucketIntegration::new(integration_stack_manager, cascade_config.clone())?;
1657
1658 pb.set_message("Starting batch submission");
1659 pb.inc(1);
1660
1661 let mut submitted_count = 0;
1663 let mut failed_entries = Vec::new();
1664 let total_entries = entries_to_submit.len();
1665
1666 for (entry_num, entry_to_submit) in &entries_to_submit {
1667 pb.set_message(format!("Submitting entry {entry_num}..."));
1668
1669 let entry_title = if total_entries == 1 {
1671 title.clone()
1672 } else {
1673 None
1674 };
1675 let entry_description = if total_entries == 1 {
1676 description.clone()
1677 } else {
1678 None
1679 };
1680
1681 match integration
1682 .submit_entry(
1683 &stack_id,
1684 &entry_to_submit.id,
1685 entry_title,
1686 entry_description,
1687 draft,
1688 )
1689 .await
1690 {
1691 Ok(pr) => {
1692 submitted_count += 1;
1693 Output::success(format!("Entry {} - PR #{}: {}", entry_num, pr.id, pr.title));
1694 if let Some(url) = pr.web_url() {
1695 Output::sub_item(format!("URL: {url}"));
1696 }
1697 Output::sub_item(format!(
1698 "From: {} -> {}",
1699 pr.from_ref.display_id, pr.to_ref.display_id
1700 ));
1701 println!();
1702 }
1703 Err(e) => {
1704 failed_entries.push((*entry_num, e.to_string()));
1705 }
1707 }
1708
1709 pb.inc(1);
1710 }
1711
1712 let has_any_prs = active_stack
1714 .entries
1715 .iter()
1716 .any(|e| e.pull_request_id.is_some());
1717 if has_any_prs && submitted_count > 0 {
1718 pb.set_message("Updating PR descriptions...");
1719 match integration.update_all_pr_descriptions(&stack_id).await {
1720 Ok(updated_prs) => {
1721 if !updated_prs.is_empty() {
1722 Output::sub_item(format!(
1723 "Updated {} PR descriptions with current stack hierarchy",
1724 updated_prs.len()
1725 ));
1726 }
1727 }
1728 Err(e) => {
1729 Output::warning(format!("Failed to update some PR descriptions: {e}"));
1730 }
1731 }
1732 }
1733
1734 if failed_entries.is_empty() {
1735 pb.finish_with_message("✅ All pull requests created successfully");
1736 Output::success(format!(
1737 "Successfully submitted {} entr{}",
1738 submitted_count,
1739 if submitted_count == 1 { "y" } else { "ies" }
1740 ));
1741 } else {
1742 pb.abandon_with_message("⚠️ Some submissions failed");
1743 Output::section("Submission Summary");
1744 Output::bullet(format!("Successful: {submitted_count}"));
1745 Output::bullet(format!("Failed: {}", failed_entries.len()));
1746
1747 Output::section("Failed entries:");
1748 for (entry_num, error) in failed_entries {
1749 Output::bullet(format!("Entry {entry_num}: {error}"));
1750 }
1751
1752 Output::tip("You can retry failed entries individually:");
1753 Output::command_example("ca stack submit <ENTRY_NUMBER>");
1754 }
1755
1756 Ok(())
1757}
1758
1759async fn check_stack_status(name: Option<String>) -> Result<()> {
1760 let current_dir = env::current_dir()
1761 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1762
1763 let repo_root = find_repository_root(¤t_dir)
1764 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1765
1766 let stack_manager = StackManager::new(&repo_root)?;
1767
1768 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1770 let config_path = config_dir.join("config.json");
1771 let settings = crate::config::Settings::load_from_file(&config_path)?;
1772
1773 let cascade_config = crate::config::CascadeConfig {
1775 bitbucket: Some(settings.bitbucket.clone()),
1776 git: settings.git.clone(),
1777 auth: crate::config::AuthConfig::default(),
1778 cascade: settings.cascade.clone(),
1779 };
1780
1781 let stack = if let Some(name) = name {
1783 stack_manager
1784 .get_stack_by_name(&name)
1785 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?
1786 } else {
1787 stack_manager.get_active_stack().ok_or_else(|| {
1788 CascadeError::config("No active stack. Use 'ca stack list' to see available stacks")
1789 })?
1790 };
1791 let stack_id = stack.id;
1792
1793 Output::section(format!("Stack: {}", stack.name));
1794 Output::sub_item(format!("ID: {}", stack.id));
1795 Output::sub_item(format!("Base: {}", stack.base_branch));
1796
1797 if let Some(description) = &stack.description {
1798 Output::sub_item(format!("Description: {description}"));
1799 }
1800
1801 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1803
1804 match integration.check_stack_status(&stack_id).await {
1806 Ok(status) => {
1807 Output::section("Pull Request Status");
1808 Output::sub_item(format!("Total entries: {}", status.total_entries));
1809 Output::sub_item(format!("Submitted: {}", status.submitted_entries));
1810 Output::sub_item(format!("Open PRs: {}", status.open_prs));
1811 Output::sub_item(format!("Merged PRs: {}", status.merged_prs));
1812 Output::sub_item(format!("Declined PRs: {}", status.declined_prs));
1813 Output::sub_item(format!(
1814 "Completion: {:.1}%",
1815 status.completion_percentage()
1816 ));
1817
1818 if !status.pull_requests.is_empty() {
1819 Output::section("Pull Requests");
1820 for pr in &status.pull_requests {
1821 let state_icon = match pr.state {
1822 crate::bitbucket::PullRequestState::Open => "🔄",
1823 crate::bitbucket::PullRequestState::Merged => "✅",
1824 crate::bitbucket::PullRequestState::Declined => "❌",
1825 };
1826 Output::bullet(format!(
1827 "{} PR #{}: {} ({} -> {})",
1828 state_icon, pr.id, pr.title, pr.from_ref.display_id, pr.to_ref.display_id
1829 ));
1830 if let Some(url) = pr.web_url() {
1831 Output::sub_item(format!("URL: {url}"));
1832 }
1833 }
1834 }
1835 }
1836 Err(e) => {
1837 warn!("Failed to check stack status: {}", e);
1838 return Err(e);
1839 }
1840 }
1841
1842 Ok(())
1843}
1844
1845async fn list_pull_requests(state: Option<String>, verbose: bool) -> Result<()> {
1846 let current_dir = env::current_dir()
1847 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1848
1849 let repo_root = find_repository_root(¤t_dir)
1850 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1851
1852 let stack_manager = StackManager::new(&repo_root)?;
1853
1854 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1856 let config_path = config_dir.join("config.json");
1857 let settings = crate::config::Settings::load_from_file(&config_path)?;
1858
1859 let cascade_config = crate::config::CascadeConfig {
1861 bitbucket: Some(settings.bitbucket.clone()),
1862 git: settings.git.clone(),
1863 auth: crate::config::AuthConfig::default(),
1864 cascade: settings.cascade.clone(),
1865 };
1866
1867 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1869
1870 let pr_state = if let Some(state_str) = state {
1872 match state_str.to_lowercase().as_str() {
1873 "open" => Some(crate::bitbucket::PullRequestState::Open),
1874 "merged" => Some(crate::bitbucket::PullRequestState::Merged),
1875 "declined" => Some(crate::bitbucket::PullRequestState::Declined),
1876 _ => {
1877 return Err(CascadeError::config(format!(
1878 "Invalid state '{state_str}'. Use: open, merged, declined"
1879 )))
1880 }
1881 }
1882 } else {
1883 None
1884 };
1885
1886 match integration.list_pull_requests(pr_state).await {
1888 Ok(pr_page) => {
1889 if pr_page.values.is_empty() {
1890 Output::info("No pull requests found.");
1891 return Ok(());
1892 }
1893
1894 println!("📋 Pull Requests ({} total):", pr_page.values.len());
1895 for pr in &pr_page.values {
1896 let state_icon = match pr.state {
1897 crate::bitbucket::PullRequestState::Open => "🔄",
1898 crate::bitbucket::PullRequestState::Merged => "✅",
1899 crate::bitbucket::PullRequestState::Declined => "❌",
1900 };
1901 println!(" {} PR #{}: {}", state_icon, pr.id, pr.title);
1902 if verbose {
1903 println!(
1904 " From: {} -> {}",
1905 pr.from_ref.display_id, pr.to_ref.display_id
1906 );
1907 println!(
1908 " Author: {}",
1909 pr.author
1910 .user
1911 .display_name
1912 .as_deref()
1913 .unwrap_or(&pr.author.user.name)
1914 );
1915 if let Some(url) = pr.web_url() {
1916 println!(" URL: {url}");
1917 }
1918 if let Some(desc) = &pr.description {
1919 if !desc.is_empty() {
1920 println!(" Description: {desc}");
1921 }
1922 }
1923 println!();
1924 }
1925 }
1926
1927 if !verbose {
1928 println!("\nUse --verbose for more details");
1929 }
1930 }
1931 Err(e) => {
1932 warn!("Failed to list pull requests: {}", e);
1933 return Err(e);
1934 }
1935 }
1936
1937 Ok(())
1938}
1939
1940async fn check_stack(_force: bool) -> Result<()> {
1941 let current_dir = env::current_dir()
1942 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1943
1944 let repo_root = find_repository_root(¤t_dir)
1945 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1946
1947 let mut manager = StackManager::new(&repo_root)?;
1948
1949 let active_stack = manager
1950 .get_active_stack()
1951 .ok_or_else(|| CascadeError::config("No active stack"))?;
1952 let stack_id = active_stack.id;
1953
1954 manager.sync_stack(&stack_id)?;
1955
1956 Output::success("Stack check completed successfully");
1957
1958 Ok(())
1959}
1960
1961async fn sync_stack(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
1962 let current_dir = env::current_dir()
1963 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1964
1965 let repo_root = find_repository_root(¤t_dir)
1966 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1967
1968 let stack_manager = StackManager::new(&repo_root)?;
1969 let git_repo = GitRepository::open(&repo_root)?;
1970
1971 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1973 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1974 })?;
1975
1976 let base_branch = active_stack.base_branch.clone();
1977 let stack_name = active_stack.name.clone();
1978
1979 println!("Syncing stack '{stack_name}' with remote...");
1981
1982 match git_repo.checkout_branch(&base_branch) {
1984 Ok(_) => {
1985 match git_repo.pull(&base_branch) {
1986 Ok(_) => {
1987 }
1989 Err(e) => {
1990 if force {
1991 Output::warning(format!("Pull failed: {e} (continuing due to --force)"));
1992 } else {
1993 Output::error(format!("Failed to pull latest changes: {e}"));
1994 Output::tip("Use --force to skip pull and continue with rebase");
1995 return Err(CascadeError::branch(format!(
1996 "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
1997 )));
1998 }
1999 }
2000 }
2001 }
2002 Err(e) => {
2003 if force {
2004 Output::warning(format!(
2005 "Failed to checkout '{base_branch}': {e} (continuing due to --force)"
2006 ));
2007 } else {
2008 Output::error(format!(
2009 "Failed to checkout base branch '{base_branch}': {e}"
2010 ));
2011 Output::tip("Use --force to bypass checkout issues and continue anyway");
2012 return Err(CascadeError::branch(format!(
2013 "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
2014 )));
2015 }
2016 }
2017 }
2018
2019 let mut updated_stack_manager = StackManager::new(&repo_root)?;
2021 let stack_id = active_stack.id;
2022
2023 match updated_stack_manager.sync_stack(&stack_id) {
2024 Ok(_) => {
2025 if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
2027 match &updated_stack.status {
2028 crate::stack::StackStatus::NeedsSync => {
2029 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2031 let config_path = config_dir.join("config.json");
2032 let settings = crate::config::Settings::load_from_file(&config_path)?;
2033
2034 let cascade_config = crate::config::CascadeConfig {
2035 bitbucket: Some(settings.bitbucket.clone()),
2036 git: settings.git.clone(),
2037 auth: crate::config::AuthConfig::default(),
2038 cascade: settings.cascade.clone(),
2039 };
2040
2041 let options = crate::stack::RebaseOptions {
2044 strategy: crate::stack::RebaseStrategy::ForcePush,
2045 interactive,
2046 target_base: Some(base_branch.clone()),
2047 preserve_merges: true,
2048 auto_resolve: !interactive,
2049 max_retries: 3,
2050 skip_pull: Some(true), };
2052
2053 let mut rebase_manager = crate::stack::RebaseManager::new(
2054 updated_stack_manager,
2055 git_repo,
2056 options,
2057 );
2058
2059 match rebase_manager.rebase_stack(&stack_id) {
2060 Ok(result) => {
2061 if !result.branch_mapping.is_empty() {
2062 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2064 let integration_stack_manager =
2065 StackManager::new(&repo_root)?;
2066 let mut integration =
2067 crate::bitbucket::BitbucketIntegration::new(
2068 integration_stack_manager,
2069 cascade_config,
2070 )?;
2071
2072 match integration
2073 .update_prs_after_rebase(
2074 &stack_id,
2075 &result.branch_mapping,
2076 )
2077 .await
2078 {
2079 Ok(updated_prs) => {
2080 if !updated_prs.is_empty() {
2081 println!(
2082 "Updated {} pull requests",
2083 updated_prs.len()
2084 );
2085 }
2086 }
2087 Err(e) => {
2088 Output::warning(format!(
2089 "Failed to update pull requests: {e}"
2090 ));
2091 }
2092 }
2093 }
2094 }
2095 }
2096 Err(e) => {
2097 Output::error(format!("Rebase failed: {e}"));
2098 Output::tip("To resolve conflicts:");
2099 Output::bullet("Fix conflicts in the affected files");
2100 Output::bullet("Stage resolved files: git add <files>");
2101 Output::bullet("Continue: ca stack continue-rebase");
2102 return Err(e);
2103 }
2104 }
2105 }
2106 crate::stack::StackStatus::Clean => {
2107 }
2109 other => {
2110 Output::info(format!("Stack status: {other:?}"));
2112 }
2113 }
2114 }
2115 }
2116 Err(e) => {
2117 if force {
2118 Output::warning(format!(
2119 "Failed to check stack status: {e} (continuing due to --force)"
2120 ));
2121 } else {
2122 return Err(e);
2123 }
2124 }
2125 }
2126
2127 if !skip_cleanup {
2129 let git_repo_for_cleanup = GitRepository::open(&repo_root)?;
2130 match perform_simple_cleanup(&stack_manager, &git_repo_for_cleanup, false).await {
2131 Ok(result) => {
2132 if result.total_candidates > 0 {
2133 Output::section("Cleanup Summary");
2134 if !result.cleaned_branches.is_empty() {
2135 Output::success(format!(
2136 "Cleaned up {} merged branches",
2137 result.cleaned_branches.len()
2138 ));
2139 for branch in &result.cleaned_branches {
2140 Output::sub_item(format!("🗑️ Deleted: {branch}"));
2141 }
2142 }
2143 if !result.skipped_branches.is_empty() {
2144 Output::sub_item(format!(
2145 "Skipped {} branches",
2146 result.skipped_branches.len()
2147 ));
2148 }
2149 if !result.failed_branches.is_empty() {
2150 for (branch, error) in &result.failed_branches {
2151 Output::warning(format!("Failed to clean up {branch}: {error}"));
2152 }
2153 }
2154 }
2155 }
2156 Err(e) => {
2157 Output::warning(format!("Branch cleanup failed: {e}"));
2158 }
2159 }
2160 }
2161
2162 Output::success("Sync completed successfully!");
2163
2164 Ok(())
2165}
2166
2167async fn rebase_stack(
2168 interactive: bool,
2169 onto: Option<String>,
2170 strategy: Option<RebaseStrategyArg>,
2171) -> Result<()> {
2172 let current_dir = env::current_dir()
2173 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2174
2175 let repo_root = find_repository_root(¤t_dir)
2176 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2177
2178 let stack_manager = StackManager::new(&repo_root)?;
2179 let git_repo = GitRepository::open(&repo_root)?;
2180
2181 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2183 let config_path = config_dir.join("config.json");
2184 let settings = crate::config::Settings::load_from_file(&config_path)?;
2185
2186 let cascade_config = crate::config::CascadeConfig {
2188 bitbucket: Some(settings.bitbucket.clone()),
2189 git: settings.git.clone(),
2190 auth: crate::config::AuthConfig::default(),
2191 cascade: settings.cascade.clone(),
2192 };
2193
2194 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2196 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2197 })?;
2198 let stack_id = active_stack.id;
2199
2200 let active_stack = stack_manager
2201 .get_stack(&stack_id)
2202 .ok_or_else(|| CascadeError::config("Active stack not found"))?
2203 .clone();
2204
2205 if active_stack.entries.is_empty() {
2206 Output::info("Stack is empty. Nothing to rebase.");
2207 return Ok(());
2208 }
2209
2210 Output::progress(format!("Rebasing stack: {}", active_stack.name));
2211 Output::sub_item(format!("Base: {}", active_stack.base_branch));
2212
2213 let rebase_strategy = if let Some(cli_strategy) = strategy {
2215 match cli_strategy {
2216 RebaseStrategyArg::ForcePush => crate::stack::RebaseStrategy::ForcePush,
2217 RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
2218 }
2219 } else {
2220 crate::stack::RebaseStrategy::ForcePush
2222 };
2223
2224 let options = crate::stack::RebaseOptions {
2226 strategy: rebase_strategy.clone(),
2227 interactive,
2228 target_base: onto,
2229 preserve_merges: true,
2230 auto_resolve: !interactive, max_retries: 3,
2232 skip_pull: None, };
2234
2235 debug!(" Strategy: {:?}", rebase_strategy);
2236 debug!(" Interactive: {}", interactive);
2237 debug!(" Target base: {:?}", options.target_base);
2238 debug!(" Entries: {}", active_stack.entries.len());
2239
2240 let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2242
2243 if rebase_manager.is_rebase_in_progress() {
2244 Output::warning("Rebase already in progress!");
2245 Output::tip("Use 'git status' to check the current state");
2246 Output::next_steps(&[
2247 "Run 'ca stack continue-rebase' to continue",
2248 "Run 'ca stack abort-rebase' to abort",
2249 ]);
2250 return Ok(());
2251 }
2252
2253 match rebase_manager.rebase_stack(&stack_id) {
2255 Ok(result) => {
2256 Output::success("Rebase completed!");
2257 Output::sub_item(result.get_summary());
2258
2259 if result.has_conflicts() {
2260 Output::warning(format!(
2261 "{} conflicts were resolved",
2262 result.conflicts.len()
2263 ));
2264 for conflict in &result.conflicts {
2265 Output::bullet(&conflict[..8.min(conflict.len())]);
2266 }
2267 }
2268
2269 if !result.branch_mapping.is_empty() {
2270 Output::section("Branch mapping");
2271 for (old, new) in &result.branch_mapping {
2272 Output::bullet(format!("{old} -> {new}"));
2273 }
2274
2275 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2277 let integration_stack_manager = StackManager::new(&repo_root)?;
2279 let mut integration = BitbucketIntegration::new(
2280 integration_stack_manager,
2281 cascade_config.clone(),
2282 )?;
2283
2284 match integration
2285 .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2286 .await
2287 {
2288 Ok(updated_prs) => {
2289 if !updated_prs.is_empty() {
2290 println!(" 🔄 Preserved pull request history:");
2291 for pr_update in updated_prs {
2292 println!(" ✅ {pr_update}");
2293 }
2294 }
2295 }
2296 Err(e) => {
2297 eprintln!(" ⚠️ Failed to update pull requests: {e}");
2298 eprintln!(" You may need to manually update PRs in Bitbucket");
2299 }
2300 }
2301 }
2302 }
2303
2304 println!(
2305 " ✅ {} commits successfully rebased",
2306 result.success_count()
2307 );
2308
2309 if matches!(rebase_strategy, crate::stack::RebaseStrategy::ForcePush) {
2311 println!("\n📝 Next steps:");
2312 if !result.branch_mapping.is_empty() {
2313 println!(" 1. ✅ Branches have been rebased and force-pushed");
2314 println!(" 2. ✅ Pull requests updated automatically (history preserved)");
2315 println!(" 3. 🔍 Review the updated PRs in Bitbucket");
2316 println!(" 4. 🧪 Test your changes");
2317 } else {
2318 println!(" 1. Review the rebased stack");
2319 println!(" 2. Test your changes");
2320 println!(" 3. Submit new pull requests with 'ca stack submit'");
2321 }
2322 }
2323 }
2324 Err(e) => {
2325 warn!("❌ Rebase failed: {}", e);
2326 println!("💡 Tips for resolving rebase issues:");
2327 println!(" - Check for uncommitted changes with 'git status'");
2328 println!(" - Ensure base branch is up to date");
2329 println!(" - Try interactive mode: 'ca stack rebase --interactive'");
2330 return Err(e);
2331 }
2332 }
2333
2334 Ok(())
2335}
2336
2337async fn continue_rebase() -> Result<()> {
2338 let current_dir = env::current_dir()
2339 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2340
2341 let repo_root = find_repository_root(¤t_dir)
2342 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2343
2344 let stack_manager = StackManager::new(&repo_root)?;
2345 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2346 let options = crate::stack::RebaseOptions::default();
2347 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2348
2349 if !rebase_manager.is_rebase_in_progress() {
2350 println!("ℹ️ No rebase in progress");
2351 return Ok(());
2352 }
2353
2354 println!("🔄 Continuing rebase...");
2355 match rebase_manager.continue_rebase() {
2356 Ok(_) => {
2357 println!("✅ Rebase continued successfully");
2358 println!(" Check 'ca stack rebase-status' for current state");
2359 }
2360 Err(e) => {
2361 warn!("❌ Failed to continue rebase: {}", e);
2362 println!("💡 You may need to resolve conflicts first:");
2363 println!(" 1. Edit conflicted files");
2364 println!(" 2. Stage resolved files with 'git add'");
2365 println!(" 3. Run 'ca stack continue-rebase' again");
2366 }
2367 }
2368
2369 Ok(())
2370}
2371
2372async fn abort_rebase() -> Result<()> {
2373 let current_dir = env::current_dir()
2374 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2375
2376 let repo_root = find_repository_root(¤t_dir)
2377 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2378
2379 let stack_manager = StackManager::new(&repo_root)?;
2380 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2381 let options = crate::stack::RebaseOptions::default();
2382 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2383
2384 if !rebase_manager.is_rebase_in_progress() {
2385 println!("ℹ️ No rebase in progress");
2386 return Ok(());
2387 }
2388
2389 println!("⚠️ Aborting rebase...");
2390 match rebase_manager.abort_rebase() {
2391 Ok(_) => {
2392 println!("✅ Rebase aborted successfully");
2393 println!(" Repository restored to pre-rebase state");
2394 }
2395 Err(e) => {
2396 warn!("❌ Failed to abort rebase: {}", e);
2397 println!("⚠️ You may need to manually clean up the repository state");
2398 }
2399 }
2400
2401 Ok(())
2402}
2403
2404async fn rebase_status() -> Result<()> {
2405 let current_dir = env::current_dir()
2406 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2407
2408 let repo_root = find_repository_root(¤t_dir)
2409 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2410
2411 let stack_manager = StackManager::new(&repo_root)?;
2412 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2413
2414 println!("📊 Rebase Status");
2415
2416 let git_dir = current_dir.join(".git");
2418 let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
2419 || git_dir.join("rebase-merge").exists()
2420 || git_dir.join("rebase-apply").exists();
2421
2422 if rebase_in_progress {
2423 println!(" Status: 🔄 Rebase in progress");
2424 println!(
2425 "
2426📝 Actions available:"
2427 );
2428 println!(" - 'ca stack continue-rebase' to continue");
2429 println!(" - 'ca stack abort-rebase' to abort");
2430 println!(" - 'git status' to see conflicted files");
2431
2432 match git_repo.get_status() {
2434 Ok(statuses) => {
2435 let mut conflicts = Vec::new();
2436 for status in statuses.iter() {
2437 if status.status().contains(git2::Status::CONFLICTED) {
2438 if let Some(path) = status.path() {
2439 conflicts.push(path.to_string());
2440 }
2441 }
2442 }
2443
2444 if !conflicts.is_empty() {
2445 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
2446 for conflict in conflicts {
2447 println!(" - {conflict}");
2448 }
2449 println!(
2450 "
2451💡 To resolve conflicts:"
2452 );
2453 println!(" 1. Edit the conflicted files");
2454 println!(" 2. Stage resolved files: git add <file>");
2455 println!(" 3. Continue: ca stack continue-rebase");
2456 }
2457 }
2458 Err(e) => {
2459 warn!("Failed to get git status: {}", e);
2460 }
2461 }
2462 } else {
2463 println!(" Status: ✅ No rebase in progress");
2464
2465 if let Some(active_stack) = stack_manager.get_active_stack() {
2467 println!(" Active stack: {}", active_stack.name);
2468 println!(" Entries: {}", active_stack.entries.len());
2469 println!(" Base branch: {}", active_stack.base_branch);
2470 }
2471 }
2472
2473 Ok(())
2474}
2475
2476async fn delete_stack(name: String, force: bool) -> Result<()> {
2477 let current_dir = env::current_dir()
2478 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2479
2480 let repo_root = find_repository_root(¤t_dir)
2481 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2482
2483 let mut manager = StackManager::new(&repo_root)?;
2484
2485 let stack = manager
2486 .get_stack_by_name(&name)
2487 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2488 let stack_id = stack.id;
2489
2490 if !force && !stack.entries.is_empty() {
2491 return Err(CascadeError::config(format!(
2492 "Stack '{}' has {} entries. Use --force to delete anyway",
2493 name,
2494 stack.entries.len()
2495 )));
2496 }
2497
2498 let deleted = manager.delete_stack(&stack_id)?;
2499
2500 Output::success(format!("Deleted stack '{}'", deleted.name));
2501 if !deleted.entries.is_empty() {
2502 Output::warning(format!("{} entries were removed", deleted.entries.len()));
2503 }
2504
2505 Ok(())
2506}
2507
2508async fn validate_stack(name: Option<String>, fix_mode: Option<String>) -> Result<()> {
2509 let current_dir = env::current_dir()
2510 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2511
2512 let repo_root = find_repository_root(¤t_dir)
2513 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2514
2515 let mut manager = StackManager::new(&repo_root)?;
2516
2517 if let Some(name) = name {
2518 let stack = manager
2520 .get_stack_by_name(&name)
2521 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2522
2523 let stack_id = stack.id;
2524
2525 match stack.validate() {
2527 Ok(message) => {
2528 println!("✅ Stack '{name}' structure validation: {message}");
2529 }
2530 Err(e) => {
2531 println!("❌ Stack '{name}' structure validation failed: {e}");
2532 return Err(CascadeError::config(e));
2533 }
2534 }
2535
2536 manager.handle_branch_modifications(&stack_id, fix_mode)?;
2538
2539 println!("🎉 Stack '{name}' validation completed");
2540 Ok(())
2541 } else {
2542 println!("🔍 Validating all stacks...");
2544
2545 let all_stacks = manager.get_all_stacks();
2547 let stack_ids: Vec<uuid::Uuid> = all_stacks.iter().map(|s| s.id).collect();
2548
2549 if stack_ids.is_empty() {
2550 println!("📭 No stacks found");
2551 return Ok(());
2552 }
2553
2554 let mut all_valid = true;
2555 for stack_id in stack_ids {
2556 let stack = manager.get_stack(&stack_id).unwrap();
2557 let stack_name = &stack.name;
2558
2559 println!("\n📋 Checking stack '{stack_name}':");
2560
2561 match stack.validate() {
2563 Ok(message) => {
2564 println!(" ✅ Structure: {message}");
2565 }
2566 Err(e) => {
2567 println!(" ❌ Structure: {e}");
2568 all_valid = false;
2569 continue;
2570 }
2571 }
2572
2573 match manager.handle_branch_modifications(&stack_id, fix_mode.clone()) {
2575 Ok(_) => {
2576 println!(" ✅ Git integrity: OK");
2577 }
2578 Err(e) => {
2579 println!(" ❌ Git integrity: {e}");
2580 all_valid = false;
2581 }
2582 }
2583 }
2584
2585 if all_valid {
2586 println!("\n🎉 All stacks passed validation");
2587 } else {
2588 println!("\n⚠️ Some stacks have validation issues");
2589 return Err(CascadeError::config("Stack validation failed".to_string()));
2590 }
2591
2592 Ok(())
2593 }
2594}
2595
2596#[allow(dead_code)]
2598fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
2599 let mut unpushed = Vec::new();
2600 let head_commit = repo.get_head_commit()?;
2601 let mut current_commit = head_commit;
2602
2603 loop {
2605 let commit_hash = current_commit.id().to_string();
2606 let already_in_stack = stack
2607 .entries
2608 .iter()
2609 .any(|entry| entry.commit_hash == commit_hash);
2610
2611 if already_in_stack {
2612 break;
2613 }
2614
2615 unpushed.push(commit_hash);
2616
2617 if let Some(parent) = current_commit.parents().next() {
2619 current_commit = parent;
2620 } else {
2621 break;
2622 }
2623 }
2624
2625 unpushed.reverse(); Ok(unpushed)
2627}
2628
2629pub async fn squash_commits(
2631 repo: &GitRepository,
2632 count: usize,
2633 since_ref: Option<String>,
2634) -> Result<()> {
2635 if count <= 1 {
2636 return Ok(()); }
2638
2639 let _current_branch = repo.get_current_branch()?;
2641
2642 let rebase_range = if let Some(ref since) = since_ref {
2644 since.clone()
2645 } else {
2646 format!("HEAD~{count}")
2647 };
2648
2649 println!(" Analyzing {count} commits to create smart squash message...");
2650
2651 let head_commit = repo.get_head_commit()?;
2653 let mut commits_to_squash = Vec::new();
2654 let mut current = head_commit;
2655
2656 for _ in 0..count {
2658 commits_to_squash.push(current.clone());
2659 if current.parent_count() > 0 {
2660 current = current.parent(0).map_err(CascadeError::Git)?;
2661 } else {
2662 break;
2663 }
2664 }
2665
2666 let smart_message = generate_squash_message(&commits_to_squash)?;
2668 println!(
2669 " Smart message: {}",
2670 smart_message.lines().next().unwrap_or("")
2671 );
2672
2673 let reset_target = if since_ref.is_some() {
2675 format!("{rebase_range}~1")
2677 } else {
2678 format!("HEAD~{count}")
2680 };
2681
2682 repo.reset_soft(&reset_target)?;
2684
2685 repo.stage_all()?;
2687
2688 let new_commit_hash = repo.commit(&smart_message)?;
2690
2691 println!(
2692 " Created squashed commit: {} ({})",
2693 &new_commit_hash[..8],
2694 smart_message.lines().next().unwrap_or("")
2695 );
2696 println!(" 💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
2697
2698 Ok(())
2699}
2700
2701pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
2703 if commits.is_empty() {
2704 return Ok("Squashed commits".to_string());
2705 }
2706
2707 let messages: Vec<String> = commits
2709 .iter()
2710 .map(|c| c.message().unwrap_or("").trim().to_string())
2711 .filter(|m| !m.is_empty())
2712 .collect();
2713
2714 if messages.is_empty() {
2715 return Ok("Squashed commits".to_string());
2716 }
2717
2718 if let Some(last_msg) = messages.first() {
2720 if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
2722 return Ok(last_msg
2723 .trim_start_matches("Final:")
2724 .trim_start_matches("final:")
2725 .trim()
2726 .to_string());
2727 }
2728 }
2729
2730 let wip_count = messages
2732 .iter()
2733 .filter(|m| {
2734 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
2735 })
2736 .count();
2737
2738 if wip_count > messages.len() / 2 {
2739 let non_wip: Vec<&String> = messages
2741 .iter()
2742 .filter(|m| {
2743 !m.to_lowercase().starts_with("wip")
2744 && !m.to_lowercase().contains("work in progress")
2745 })
2746 .collect();
2747
2748 if let Some(best_msg) = non_wip.first() {
2749 return Ok(best_msg.to_string());
2750 }
2751
2752 let feature = extract_feature_from_wip(&messages);
2754 return Ok(feature);
2755 }
2756
2757 Ok(messages.first().unwrap().clone())
2759}
2760
2761pub fn extract_feature_from_wip(messages: &[String]) -> String {
2763 for msg in messages {
2765 if msg.to_lowercase().starts_with("wip:") {
2767 if let Some(rest) = msg
2768 .strip_prefix("WIP:")
2769 .or_else(|| msg.strip_prefix("wip:"))
2770 {
2771 let feature = rest.trim();
2772 if !feature.is_empty() && feature.len() > 3 {
2773 let mut chars: Vec<char> = feature.chars().collect();
2775 if let Some(first) = chars.first_mut() {
2776 *first = first.to_uppercase().next().unwrap_or(*first);
2777 }
2778 return chars.into_iter().collect();
2779 }
2780 }
2781 }
2782 }
2783
2784 if let Some(first) = messages.first() {
2786 let cleaned = first
2787 .trim_start_matches("WIP:")
2788 .trim_start_matches("wip:")
2789 .trim_start_matches("WIP")
2790 .trim_start_matches("wip")
2791 .trim();
2792
2793 if !cleaned.is_empty() {
2794 return format!("Implement {cleaned}");
2795 }
2796 }
2797
2798 format!("Squashed {} commits", messages.len())
2799}
2800
2801pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
2803 let head_commit = repo.get_head_commit()?;
2804 let since_commit = repo.get_commit(since_commit_hash)?;
2805
2806 let mut count = 0;
2807 let mut current = head_commit;
2808
2809 loop {
2811 if current.id() == since_commit.id() {
2812 break;
2813 }
2814
2815 count += 1;
2816
2817 if current.parent_count() == 0 {
2819 break; }
2821
2822 current = current.parent(0).map_err(CascadeError::Git)?;
2823 }
2824
2825 Ok(count)
2826}
2827
2828async fn land_stack(
2830 entry: Option<usize>,
2831 force: bool,
2832 dry_run: bool,
2833 auto: bool,
2834 wait_for_builds: bool,
2835 strategy: Option<MergeStrategyArg>,
2836 build_timeout: u64,
2837) -> Result<()> {
2838 let current_dir = env::current_dir()
2839 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2840
2841 let repo_root = find_repository_root(¤t_dir)
2842 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2843
2844 let stack_manager = StackManager::new(&repo_root)?;
2845
2846 let stack_id = stack_manager
2848 .get_active_stack()
2849 .map(|s| s.id)
2850 .ok_or_else(|| {
2851 CascadeError::config(
2852 "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
2853 .to_string(),
2854 )
2855 })?;
2856
2857 let active_stack = stack_manager
2858 .get_active_stack()
2859 .cloned()
2860 .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
2861
2862 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2864 let config_path = config_dir.join("config.json");
2865 let settings = crate::config::Settings::load_from_file(&config_path)?;
2866
2867 let cascade_config = crate::config::CascadeConfig {
2868 bitbucket: Some(settings.bitbucket.clone()),
2869 git: settings.git.clone(),
2870 auth: crate::config::AuthConfig::default(),
2871 cascade: settings.cascade.clone(),
2872 };
2873
2874 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
2875
2876 let status = integration.check_enhanced_stack_status(&stack_id).await?;
2878
2879 if status.enhanced_statuses.is_empty() {
2880 println!("❌ No pull requests found to land");
2881 return Ok(());
2882 }
2883
2884 let ready_prs: Vec<_> = status
2886 .enhanced_statuses
2887 .iter()
2888 .filter(|pr_status| {
2889 if let Some(entry_num) = entry {
2891 if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
2893 if pr_status.pr.from_ref.display_id != stack_entry.branch {
2895 return false;
2896 }
2897 } else {
2898 return false; }
2900 }
2901
2902 if force {
2903 pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
2905 } else {
2906 pr_status.is_ready_to_land()
2907 }
2908 })
2909 .collect();
2910
2911 if ready_prs.is_empty() {
2912 if let Some(entry_num) = entry {
2913 println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
2914 } else {
2915 println!("❌ No pull requests are ready to land");
2916 }
2917
2918 println!("\n🚫 Blocking Issues:");
2920 for pr_status in &status.enhanced_statuses {
2921 if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
2922 let blocking = pr_status.get_blocking_reasons();
2923 if !blocking.is_empty() {
2924 println!(" PR #{}: {}", pr_status.pr.id, blocking.join(", "));
2925 }
2926 }
2927 }
2928
2929 if !force {
2930 println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
2931 }
2932 return Ok(());
2933 }
2934
2935 if dry_run {
2936 if let Some(entry_num) = entry {
2937 println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
2938 } else {
2939 println!("🏃 Dry Run - PRs that would be landed:");
2940 }
2941 for pr_status in &ready_prs {
2942 println!(" ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
2943 if !pr_status.is_ready_to_land() && force {
2944 let blocking = pr_status.get_blocking_reasons();
2945 println!(
2946 " ⚠️ Would force land despite: {}",
2947 blocking.join(", ")
2948 );
2949 }
2950 }
2951 return Ok(());
2952 }
2953
2954 if entry.is_some() && ready_prs.len() > 1 {
2957 println!(
2958 "🎯 {} PRs are ready to land, but landing only entry #{}",
2959 ready_prs.len(),
2960 entry.unwrap()
2961 );
2962 }
2963
2964 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
2966 strategy.unwrap_or(MergeStrategyArg::Squash).into();
2967 let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
2968 merge_strategy: merge_strategy.clone(),
2969 wait_for_builds,
2970 build_timeout: std::time::Duration::from_secs(build_timeout),
2971 allowed_authors: None, };
2973
2974 println!(
2976 "🚀 Landing {} PR{}...",
2977 ready_prs.len(),
2978 if ready_prs.len() == 1 { "" } else { "s" }
2979 );
2980
2981 let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
2982 crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
2983 );
2984
2985 let mut landed_count = 0;
2987 let mut failed_count = 0;
2988 let total_ready_prs = ready_prs.len();
2989
2990 for pr_status in ready_prs {
2991 let pr_id = pr_status.pr.id;
2992
2993 print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
2994
2995 let land_result = if auto {
2996 pr_manager
2998 .auto_merge_if_ready(pr_id, &auto_merge_conditions)
2999 .await
3000 } else {
3001 pr_manager
3003 .merge_pull_request(pr_id, merge_strategy.clone())
3004 .await
3005 .map(
3006 |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
3007 pr: Box::new(pr),
3008 merge_strategy: merge_strategy.clone(),
3009 },
3010 )
3011 };
3012
3013 match land_result {
3014 Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
3015 println!(" ✅");
3016 landed_count += 1;
3017
3018 if landed_count < total_ready_prs {
3020 println!("🔄 Retargeting remaining PRs to latest base...");
3021
3022 let base_branch = active_stack.base_branch.clone();
3024 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3025
3026 println!(" 📥 Updating base branch: {base_branch}");
3027 match git_repo.pull(&base_branch) {
3028 Ok(_) => println!(" ✅ Base branch updated successfully"),
3029 Err(e) => {
3030 println!(" ⚠️ Warning: Failed to update base branch: {e}");
3031 println!(
3032 " 💡 You may want to manually run: git pull origin {base_branch}"
3033 );
3034 }
3035 }
3036
3037 let mut rebase_manager = crate::stack::RebaseManager::new(
3039 StackManager::new(&repo_root)?,
3040 git_repo,
3041 crate::stack::RebaseOptions {
3042 strategy: crate::stack::RebaseStrategy::ForcePush,
3043 target_base: Some(base_branch.clone()),
3044 ..Default::default()
3045 },
3046 );
3047
3048 match rebase_manager.rebase_stack(&stack_id) {
3049 Ok(rebase_result) => {
3050 if !rebase_result.branch_mapping.is_empty() {
3051 let retarget_config = crate::config::CascadeConfig {
3053 bitbucket: Some(settings.bitbucket.clone()),
3054 git: settings.git.clone(),
3055 auth: crate::config::AuthConfig::default(),
3056 cascade: settings.cascade.clone(),
3057 };
3058 let mut retarget_integration = BitbucketIntegration::new(
3059 StackManager::new(&repo_root)?,
3060 retarget_config,
3061 )?;
3062
3063 match retarget_integration
3064 .update_prs_after_rebase(
3065 &stack_id,
3066 &rebase_result.branch_mapping,
3067 )
3068 .await
3069 {
3070 Ok(updated_prs) => {
3071 if !updated_prs.is_empty() {
3072 println!(
3073 " ✅ Updated {} PRs with new targets",
3074 updated_prs.len()
3075 );
3076 }
3077 }
3078 Err(e) => {
3079 println!(" ⚠️ Failed to update remaining PRs: {e}");
3080 println!(
3081 " 💡 You may need to run: ca stack rebase --onto {base_branch}"
3082 );
3083 }
3084 }
3085 }
3086 }
3087 Err(e) => {
3088 println!(" ❌ Auto-retargeting conflicts detected!");
3090 println!(" 📝 To resolve conflicts and continue landing:");
3091 println!(" 1. Resolve conflicts in the affected files");
3092 println!(" 2. Stage resolved files: git add <files>");
3093 println!(" 3. Continue the process: ca stack continue-land");
3094 println!(" 4. Or abort the operation: ca stack abort-land");
3095 println!();
3096 println!(" 💡 Check current status: ca stack land-status");
3097 println!(" ⚠️ Error details: {e}");
3098
3099 break;
3101 }
3102 }
3103 }
3104 }
3105 Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
3106 println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
3107 failed_count += 1;
3108 if !force {
3109 break;
3110 }
3111 }
3112 Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
3113 println!(" ❌ Failed: {error}");
3114 failed_count += 1;
3115 if !force {
3116 break;
3117 }
3118 }
3119 Err(e) => {
3120 println!(" ❌");
3121 eprintln!("Failed to land PR #{pr_id}: {e}");
3122 failed_count += 1;
3123
3124 if !force {
3125 break;
3126 }
3127 }
3128 }
3129 }
3130
3131 println!("\n🎯 Landing Summary:");
3133 println!(" ✅ Successfully landed: {landed_count}");
3134 if failed_count > 0 {
3135 println!(" ❌ Failed to land: {failed_count}");
3136 }
3137
3138 if landed_count > 0 {
3139 println!("✅ Landing operation completed!");
3140 } else {
3141 println!("❌ No PRs were successfully landed");
3142 }
3143
3144 Ok(())
3145}
3146
3147async fn auto_land_stack(
3149 force: bool,
3150 dry_run: bool,
3151 wait_for_builds: bool,
3152 strategy: Option<MergeStrategyArg>,
3153 build_timeout: u64,
3154) -> Result<()> {
3155 land_stack(
3157 None,
3158 force,
3159 dry_run,
3160 true, wait_for_builds,
3162 strategy,
3163 build_timeout,
3164 )
3165 .await
3166}
3167
3168async fn continue_land() -> Result<()> {
3169 let current_dir = env::current_dir()
3170 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3171
3172 let repo_root = find_repository_root(¤t_dir)
3173 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3174
3175 let stack_manager = StackManager::new(&repo_root)?;
3176 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3177 let options = crate::stack::RebaseOptions::default();
3178 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3179
3180 if !rebase_manager.is_rebase_in_progress() {
3181 println!("ℹ️ No rebase in progress");
3182 return Ok(());
3183 }
3184
3185 println!("🔄 Continuing land operation...");
3186 match rebase_manager.continue_rebase() {
3187 Ok(_) => {
3188 println!("✅ Land operation continued successfully");
3189 println!(" Check 'ca stack land-status' for current state");
3190 }
3191 Err(e) => {
3192 warn!("❌ Failed to continue land operation: {}", e);
3193 println!("💡 You may need to resolve conflicts first:");
3194 println!(" 1. Edit conflicted files");
3195 println!(" 2. Stage resolved files with 'git add'");
3196 println!(" 3. Run 'ca stack continue-land' again");
3197 }
3198 }
3199
3200 Ok(())
3201}
3202
3203async fn abort_land() -> Result<()> {
3204 let current_dir = env::current_dir()
3205 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3206
3207 let repo_root = find_repository_root(¤t_dir)
3208 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3209
3210 let stack_manager = StackManager::new(&repo_root)?;
3211 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3212 let options = crate::stack::RebaseOptions::default();
3213 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3214
3215 if !rebase_manager.is_rebase_in_progress() {
3216 println!("ℹ️ No rebase in progress");
3217 return Ok(());
3218 }
3219
3220 println!("⚠️ Aborting land operation...");
3221 match rebase_manager.abort_rebase() {
3222 Ok(_) => {
3223 println!("✅ Land operation aborted successfully");
3224 println!(" Repository restored to pre-land state");
3225 }
3226 Err(e) => {
3227 warn!("❌ Failed to abort land operation: {}", e);
3228 println!("⚠️ You may need to manually clean up the repository state");
3229 }
3230 }
3231
3232 Ok(())
3233}
3234
3235async fn land_status() -> Result<()> {
3236 let current_dir = env::current_dir()
3237 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3238
3239 let repo_root = find_repository_root(¤t_dir)
3240 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3241
3242 let stack_manager = StackManager::new(&repo_root)?;
3243 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3244
3245 println!("📊 Land Status");
3246
3247 let git_dir = repo_root.join(".git");
3249 let land_in_progress = git_dir.join("REBASE_HEAD").exists()
3250 || git_dir.join("rebase-merge").exists()
3251 || git_dir.join("rebase-apply").exists();
3252
3253 if land_in_progress {
3254 println!(" Status: 🔄 Land operation in progress");
3255 println!(
3256 "
3257📝 Actions available:"
3258 );
3259 println!(" - 'ca stack continue-land' to continue");
3260 println!(" - 'ca stack abort-land' to abort");
3261 println!(" - 'git status' to see conflicted files");
3262
3263 match git_repo.get_status() {
3265 Ok(statuses) => {
3266 let mut conflicts = Vec::new();
3267 for status in statuses.iter() {
3268 if status.status().contains(git2::Status::CONFLICTED) {
3269 if let Some(path) = status.path() {
3270 conflicts.push(path.to_string());
3271 }
3272 }
3273 }
3274
3275 if !conflicts.is_empty() {
3276 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
3277 for conflict in conflicts {
3278 println!(" - {conflict}");
3279 }
3280 println!(
3281 "
3282💡 To resolve conflicts:"
3283 );
3284 println!(" 1. Edit the conflicted files");
3285 println!(" 2. Stage resolved files: git add <file>");
3286 println!(" 3. Continue: ca stack continue-land");
3287 }
3288 }
3289 Err(e) => {
3290 warn!("Failed to get git status: {}", e);
3291 }
3292 }
3293 } else {
3294 println!(" Status: ✅ No land operation in progress");
3295
3296 if let Some(active_stack) = stack_manager.get_active_stack() {
3298 println!(" Active stack: {}", active_stack.name);
3299 println!(" Entries: {}", active_stack.entries.len());
3300 println!(" Base branch: {}", active_stack.base_branch);
3301 }
3302 }
3303
3304 Ok(())
3305}
3306
3307async fn repair_stack_data() -> Result<()> {
3308 let current_dir = env::current_dir()
3309 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3310
3311 let repo_root = find_repository_root(¤t_dir)
3312 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3313
3314 let mut stack_manager = StackManager::new(&repo_root)?;
3315
3316 println!("🔧 Repairing stack data consistency...");
3317
3318 stack_manager.repair_all_stacks()?;
3319
3320 println!("✅ Stack data consistency repaired successfully!");
3321 println!("💡 Run 'ca stack --mergeable' to see updated status");
3322
3323 Ok(())
3324}
3325
3326async fn cleanup_branches(
3328 dry_run: bool,
3329 force: bool,
3330 include_stale: bool,
3331 stale_days: u32,
3332 cleanup_remote: bool,
3333 include_non_stack: bool,
3334 verbose: bool,
3335) -> Result<()> {
3336 let current_dir = env::current_dir()
3337 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3338
3339 let repo_root = find_repository_root(¤t_dir)
3340 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3341
3342 let stack_manager = StackManager::new(&repo_root)?;
3343 let git_repo = GitRepository::open(&repo_root)?;
3344
3345 let result = perform_cleanup(
3346 &stack_manager,
3347 &git_repo,
3348 dry_run,
3349 force,
3350 include_stale,
3351 stale_days,
3352 cleanup_remote,
3353 include_non_stack,
3354 verbose,
3355 )
3356 .await?;
3357
3358 if result.total_candidates == 0 {
3360 Output::success("No branches found that need cleanup");
3361 return Ok(());
3362 }
3363
3364 Output::section("Cleanup Results");
3365
3366 if dry_run {
3367 Output::sub_item(format!(
3368 "Found {} branches that would be cleaned up",
3369 result.total_candidates
3370 ));
3371 } else {
3372 if !result.cleaned_branches.is_empty() {
3373 Output::success(format!(
3374 "Successfully cleaned up {} branches",
3375 result.cleaned_branches.len()
3376 ));
3377 for branch in &result.cleaned_branches {
3378 Output::sub_item(format!("🗑️ Deleted: {branch}"));
3379 }
3380 }
3381
3382 if !result.skipped_branches.is_empty() {
3383 Output::sub_item(format!(
3384 "Skipped {} branches",
3385 result.skipped_branches.len()
3386 ));
3387 if verbose {
3388 for (branch, reason) in &result.skipped_branches {
3389 Output::sub_item(format!("⏭️ {branch}: {reason}"));
3390 }
3391 }
3392 }
3393
3394 if !result.failed_branches.is_empty() {
3395 Output::warning(format!(
3396 "Failed to clean up {} branches",
3397 result.failed_branches.len()
3398 ));
3399 for (branch, error) in &result.failed_branches {
3400 Output::sub_item(format!("❌ {branch}: {error}"));
3401 }
3402 }
3403 }
3404
3405 Ok(())
3406}
3407
3408#[allow(clippy::too_many_arguments)]
3410async fn perform_cleanup(
3411 stack_manager: &StackManager,
3412 git_repo: &GitRepository,
3413 dry_run: bool,
3414 force: bool,
3415 include_stale: bool,
3416 stale_days: u32,
3417 cleanup_remote: bool,
3418 include_non_stack: bool,
3419 verbose: bool,
3420) -> Result<CleanupResult> {
3421 let options = CleanupOptions {
3422 dry_run,
3423 force,
3424 include_stale,
3425 cleanup_remote,
3426 stale_threshold_days: stale_days,
3427 cleanup_non_stack: include_non_stack,
3428 };
3429
3430 let stack_manager_copy = StackManager::new(stack_manager.repo_path())?;
3431 let git_repo_copy = GitRepository::open(git_repo.path())?;
3432 let mut cleanup_manager = CleanupManager::new(stack_manager_copy, git_repo_copy, options);
3433
3434 let candidates = cleanup_manager.find_cleanup_candidates()?;
3436
3437 if candidates.is_empty() {
3438 return Ok(CleanupResult {
3439 cleaned_branches: Vec::new(),
3440 failed_branches: Vec::new(),
3441 skipped_branches: Vec::new(),
3442 total_candidates: 0,
3443 });
3444 }
3445
3446 if verbose || dry_run {
3448 Output::section("Cleanup Candidates");
3449 for candidate in &candidates {
3450 let reason_icon = match candidate.reason {
3451 crate::stack::CleanupReason::FullyMerged => "🔀",
3452 crate::stack::CleanupReason::StackEntryMerged => "✅",
3453 crate::stack::CleanupReason::Stale => "⏰",
3454 crate::stack::CleanupReason::Orphaned => "👻",
3455 };
3456
3457 Output::sub_item(format!(
3458 "{} {} - {} ({})",
3459 reason_icon,
3460 candidate.branch_name,
3461 candidate.reason_to_string(),
3462 candidate.safety_info
3463 ));
3464 }
3465 }
3466
3467 if !force && !dry_run && !candidates.is_empty() {
3469 Output::warning(format!("About to delete {} branches", candidates.len()));
3470
3471 let should_continue = Confirm::with_theme(&ColorfulTheme::default())
3473 .with_prompt("Continue with branch cleanup?")
3474 .default(false)
3475 .interact()
3476 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
3477
3478 if !should_continue {
3479 Output::sub_item("Cleanup cancelled");
3480 return Ok(CleanupResult {
3481 cleaned_branches: Vec::new(),
3482 failed_branches: Vec::new(),
3483 skipped_branches: Vec::new(),
3484 total_candidates: candidates.len(),
3485 });
3486 }
3487 }
3488
3489 cleanup_manager.perform_cleanup(&candidates)
3491}
3492
3493async fn perform_simple_cleanup(
3495 stack_manager: &StackManager,
3496 git_repo: &GitRepository,
3497 dry_run: bool,
3498) -> Result<CleanupResult> {
3499 perform_cleanup(
3500 stack_manager,
3501 git_repo,
3502 dry_run,
3503 false, false, 30, false, false, false, )
3510 .await
3511}
3512
3513async fn analyze_commits_for_safeguards(
3515 commits_to_push: &[String],
3516 repo: &GitRepository,
3517 dry_run: bool,
3518) -> Result<()> {
3519 const LARGE_COMMIT_THRESHOLD: usize = 10;
3520 const WEEK_IN_SECONDS: i64 = 7 * 24 * 3600;
3521
3522 if commits_to_push.len() > LARGE_COMMIT_THRESHOLD {
3524 println!(
3525 "⚠️ Warning: About to push {} commits to stack",
3526 commits_to_push.len()
3527 );
3528 println!(" This may indicate a merge commit issue or unexpected commit range.");
3529 println!(" Large commit counts often result from merging instead of rebasing.");
3530
3531 if !dry_run && !confirm_large_push(commits_to_push.len())? {
3532 return Err(CascadeError::config("Push cancelled by user"));
3533 }
3534 }
3535
3536 let commit_objects: Result<Vec<_>> = commits_to_push
3538 .iter()
3539 .map(|hash| repo.get_commit(hash))
3540 .collect();
3541 let commit_objects = commit_objects?;
3542
3543 let merge_commits: Vec<_> = commit_objects
3545 .iter()
3546 .filter(|c| c.parent_count() > 1)
3547 .collect();
3548
3549 if !merge_commits.is_empty() {
3550 println!(
3551 "⚠️ Warning: {} merge commits detected in push",
3552 merge_commits.len()
3553 );
3554 println!(" This often indicates you merged instead of rebased.");
3555 println!(" Consider using 'ca sync' to rebase on the base branch.");
3556 println!(" Merge commits in stacks can cause confusion and duplicate work.");
3557 }
3558
3559 if commit_objects.len() > 1 {
3561 let oldest_commit_time = commit_objects.first().unwrap().time().seconds();
3562 let newest_commit_time = commit_objects.last().unwrap().time().seconds();
3563 let time_span = newest_commit_time - oldest_commit_time;
3564
3565 if time_span > WEEK_IN_SECONDS {
3566 let days = time_span / (24 * 3600);
3567 println!("⚠️ Warning: Commits span {days} days");
3568 println!(" This may indicate merged history rather than new work.");
3569 println!(" Recent work should typically span hours or days, not weeks.");
3570 }
3571 }
3572
3573 if commits_to_push.len() > 5 {
3575 println!("💡 Tip: If you only want recent commits, use:");
3576 println!(
3577 " ca push --since HEAD~{} # pushes last {} commits",
3578 std::cmp::min(commits_to_push.len(), 5),
3579 std::cmp::min(commits_to_push.len(), 5)
3580 );
3581 println!(" ca push --commits <hash1>,<hash2> # pushes specific commits");
3582 println!(" ca push --dry-run # preview what would be pushed");
3583 }
3584
3585 if dry_run {
3587 println!("🔍 DRY RUN: Would push {} commits:", commits_to_push.len());
3588 for (i, (commit_hash, commit_obj)) in commits_to_push
3589 .iter()
3590 .zip(commit_objects.iter())
3591 .enumerate()
3592 {
3593 let summary = commit_obj.summary().unwrap_or("(no message)");
3594 let short_hash = &commit_hash[..std::cmp::min(commit_hash.len(), 7)];
3595 println!(" {}: {} ({})", i + 1, summary, short_hash);
3596 }
3597 println!("💡 Run without --dry-run to actually push these commits.");
3598 }
3599
3600 Ok(())
3601}
3602
3603fn confirm_large_push(count: usize) -> Result<bool> {
3605 let should_continue = Confirm::with_theme(&ColorfulTheme::default())
3607 .with_prompt(format!("Continue pushing {count} commits?"))
3608 .default(false)
3609 .interact()
3610 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
3611
3612 Ok(should_continue)
3613}
3614
3615#[cfg(test)]
3616mod tests {
3617 use super::*;
3618 use std::process::Command;
3619 use tempfile::TempDir;
3620
3621 fn create_test_repo() -> Result<(TempDir, std::path::PathBuf)> {
3622 let temp_dir = TempDir::new()
3623 .map_err(|e| CascadeError::config(format!("Failed to create temp directory: {e}")))?;
3624 let repo_path = temp_dir.path().to_path_buf();
3625
3626 let output = Command::new("git")
3628 .args(["init"])
3629 .current_dir(&repo_path)
3630 .output()
3631 .map_err(|e| CascadeError::config(format!("Failed to run git init: {e}")))?;
3632 if !output.status.success() {
3633 return Err(CascadeError::config("Git init failed".to_string()));
3634 }
3635
3636 let output = Command::new("git")
3637 .args(["config", "user.name", "Test User"])
3638 .current_dir(&repo_path)
3639 .output()
3640 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3641 if !output.status.success() {
3642 return Err(CascadeError::config(
3643 "Git config user.name failed".to_string(),
3644 ));
3645 }
3646
3647 let output = Command::new("git")
3648 .args(["config", "user.email", "test@example.com"])
3649 .current_dir(&repo_path)
3650 .output()
3651 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3652 if !output.status.success() {
3653 return Err(CascadeError::config(
3654 "Git config user.email failed".to_string(),
3655 ));
3656 }
3657
3658 std::fs::write(repo_path.join("README.md"), "# Test")
3660 .map_err(|e| CascadeError::config(format!("Failed to write file: {e}")))?;
3661 let output = Command::new("git")
3662 .args(["add", "."])
3663 .current_dir(&repo_path)
3664 .output()
3665 .map_err(|e| CascadeError::config(format!("Failed to run git add: {e}")))?;
3666 if !output.status.success() {
3667 return Err(CascadeError::config("Git add failed".to_string()));
3668 }
3669
3670 let output = Command::new("git")
3671 .args(["commit", "-m", "Initial commit"])
3672 .current_dir(&repo_path)
3673 .output()
3674 .map_err(|e| CascadeError::config(format!("Failed to run git commit: {e}")))?;
3675 if !output.status.success() {
3676 return Err(CascadeError::config("Git commit failed".to_string()));
3677 }
3678
3679 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))?;
3681
3682 Ok((temp_dir, repo_path))
3683 }
3684
3685 #[tokio::test]
3686 async fn test_create_stack() {
3687 let (temp_dir, repo_path) = match create_test_repo() {
3688 Ok(repo) => repo,
3689 Err(_) => {
3690 println!("Skipping test due to git environment setup failure");
3691 return;
3692 }
3693 };
3694 let _ = &temp_dir;
3696
3697 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3701 match env::set_current_dir(&repo_path) {
3702 Ok(_) => {
3703 let result = create_stack(
3704 "test-stack".to_string(),
3705 None, Some("Test description".to_string()),
3707 )
3708 .await;
3709
3710 if let Ok(orig) = original_dir {
3712 let _ = env::set_current_dir(orig);
3713 }
3714
3715 assert!(
3716 result.is_ok(),
3717 "Stack creation should succeed in initialized repository"
3718 );
3719 }
3720 Err(_) => {
3721 println!("Skipping test due to directory access restrictions");
3723 }
3724 }
3725 }
3726
3727 #[tokio::test]
3728 async fn test_list_empty_stacks() {
3729 let (temp_dir, repo_path) = match create_test_repo() {
3730 Ok(repo) => repo,
3731 Err(_) => {
3732 println!("Skipping test due to git environment setup failure");
3733 return;
3734 }
3735 };
3736 let _ = &temp_dir;
3738
3739 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3743 match env::set_current_dir(&repo_path) {
3744 Ok(_) => {
3745 let result = list_stacks(false, false, None).await;
3746
3747 if let Ok(orig) = original_dir {
3749 let _ = env::set_current_dir(orig);
3750 }
3751
3752 assert!(
3753 result.is_ok(),
3754 "Listing stacks should succeed in initialized repository"
3755 );
3756 }
3757 Err(_) => {
3758 println!("Skipping test due to directory access restrictions");
3760 }
3761 }
3762 }
3763
3764 #[test]
3767 fn test_extract_feature_from_wip_basic() {
3768 let messages = vec![
3769 "WIP: add authentication".to_string(),
3770 "WIP: implement login flow".to_string(),
3771 ];
3772
3773 let result = extract_feature_from_wip(&messages);
3774 assert_eq!(result, "Add authentication");
3775 }
3776
3777 #[test]
3778 fn test_extract_feature_from_wip_capitalize() {
3779 let messages = vec!["WIP: fix user validation bug".to_string()];
3780
3781 let result = extract_feature_from_wip(&messages);
3782 assert_eq!(result, "Fix user validation bug");
3783 }
3784
3785 #[test]
3786 fn test_extract_feature_from_wip_fallback() {
3787 let messages = vec![
3788 "WIP user interface changes".to_string(),
3789 "wip: css styling".to_string(),
3790 ];
3791
3792 let result = extract_feature_from_wip(&messages);
3793 assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
3795 }
3796
3797 #[test]
3798 fn test_extract_feature_from_wip_empty() {
3799 let messages = vec![];
3800
3801 let result = extract_feature_from_wip(&messages);
3802 assert_eq!(result, "Squashed 0 commits");
3803 }
3804
3805 #[test]
3806 fn test_extract_feature_from_wip_short_message() {
3807 let messages = vec!["WIP: x".to_string()]; let result = extract_feature_from_wip(&messages);
3810 assert!(result.starts_with("Implement") || result.contains("Squashed"));
3811 }
3812
3813 #[test]
3816 fn test_squash_message_final_strategy() {
3817 let messages = [
3821 "Final: implement user authentication system".to_string(),
3822 "WIP: add tests".to_string(),
3823 "WIP: fix validation".to_string(),
3824 ];
3825
3826 assert!(messages[0].starts_with("Final:"));
3828
3829 let extracted = messages[0].trim_start_matches("Final:").trim();
3831 assert_eq!(extracted, "implement user authentication system");
3832 }
3833
3834 #[test]
3835 fn test_squash_message_wip_detection() {
3836 let messages = [
3837 "WIP: start feature".to_string(),
3838 "WIP: continue work".to_string(),
3839 "WIP: almost done".to_string(),
3840 "Regular commit message".to_string(),
3841 ];
3842
3843 let wip_count = messages
3844 .iter()
3845 .filter(|m| {
3846 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
3847 })
3848 .count();
3849
3850 assert_eq!(wip_count, 3); assert!(wip_count > messages.len() / 2); let non_wip: Vec<&String> = messages
3855 .iter()
3856 .filter(|m| {
3857 !m.to_lowercase().starts_with("wip")
3858 && !m.to_lowercase().contains("work in progress")
3859 })
3860 .collect();
3861
3862 assert_eq!(non_wip.len(), 1);
3863 assert_eq!(non_wip[0], "Regular commit message");
3864 }
3865
3866 #[test]
3867 fn test_squash_message_all_wip() {
3868 let messages = vec![
3869 "WIP: add feature A".to_string(),
3870 "WIP: add feature B".to_string(),
3871 "WIP: finish implementation".to_string(),
3872 ];
3873
3874 let result = extract_feature_from_wip(&messages);
3875 assert_eq!(result, "Add feature A");
3877 }
3878
3879 #[test]
3880 fn test_squash_message_edge_cases() {
3881 let empty_messages: Vec<String> = vec![];
3883 let result = extract_feature_from_wip(&empty_messages);
3884 assert_eq!(result, "Squashed 0 commits");
3885
3886 let whitespace_messages = vec![" ".to_string(), "\t\n".to_string()];
3888 let result = extract_feature_from_wip(&whitespace_messages);
3889 assert!(result.contains("Squashed") || result.contains("Implement"));
3890
3891 let mixed_case = vec!["wip: Add Feature".to_string()];
3893 let result = extract_feature_from_wip(&mixed_case);
3894 assert_eq!(result, "Add Feature");
3895 }
3896
3897 #[tokio::test]
3900 async fn test_auto_land_wrapper() {
3901 let (temp_dir, repo_path) = match create_test_repo() {
3903 Ok(repo) => repo,
3904 Err(_) => {
3905 println!("Skipping test due to git environment setup failure");
3906 return;
3907 }
3908 };
3909 let _ = &temp_dir;
3911
3912 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
3914 .expect("Failed to initialize Cascade in test repo");
3915
3916 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3917 match env::set_current_dir(&repo_path) {
3918 Ok(_) => {
3919 let result = create_stack(
3921 "test-stack".to_string(),
3922 None,
3923 Some("Test stack for auto-land".to_string()),
3924 )
3925 .await;
3926
3927 if let Ok(orig) = original_dir {
3928 let _ = env::set_current_dir(orig);
3929 }
3930
3931 assert!(
3934 result.is_ok(),
3935 "Stack creation should succeed in initialized repository"
3936 );
3937 }
3938 Err(_) => {
3939 println!("Skipping test due to directory access restrictions");
3940 }
3941 }
3942 }
3943
3944 #[test]
3945 fn test_auto_land_action_enum() {
3946 use crate::cli::commands::stack::StackAction;
3948
3949 let _action = StackAction::AutoLand {
3951 force: false,
3952 dry_run: true,
3953 wait_for_builds: true,
3954 strategy: Some(MergeStrategyArg::Squash),
3955 build_timeout: 1800,
3956 };
3957
3958 }
3960
3961 #[test]
3962 fn test_merge_strategy_conversion() {
3963 let squash_strategy = MergeStrategyArg::Squash;
3965 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
3966
3967 match merge_strategy {
3968 crate::bitbucket::pull_request::MergeStrategy::Squash => {
3969 }
3971 _ => panic!("Expected Squash strategy"),
3972 }
3973
3974 let merge_strategy = MergeStrategyArg::Merge;
3975 let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
3976
3977 match converted {
3978 crate::bitbucket::pull_request::MergeStrategy::Merge => {
3979 }
3981 _ => panic!("Expected Merge strategy"),
3982 }
3983 }
3984
3985 #[test]
3986 fn test_auto_merge_conditions_structure() {
3987 use std::time::Duration;
3989
3990 let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3991 merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
3992 wait_for_builds: true,
3993 build_timeout: Duration::from_secs(1800),
3994 allowed_authors: None,
3995 };
3996
3997 assert!(conditions.wait_for_builds);
3999 assert_eq!(conditions.build_timeout.as_secs(), 1800);
4000 assert!(conditions.allowed_authors.is_none());
4001 assert!(matches!(
4002 conditions.merge_strategy,
4003 crate::bitbucket::pull_request::MergeStrategy::Squash
4004 ));
4005 }
4006
4007 #[test]
4008 fn test_polling_constants() {
4009 use std::time::Duration;
4011
4012 let expected_polling_interval = Duration::from_secs(30);
4014
4015 assert!(expected_polling_interval.as_secs() >= 10); assert!(expected_polling_interval.as_secs() <= 60); assert_eq!(expected_polling_interval.as_secs(), 30); }
4020
4021 #[test]
4022 fn test_build_timeout_defaults() {
4023 const DEFAULT_TIMEOUT: u64 = 1800; assert_eq!(DEFAULT_TIMEOUT, 1800);
4026 let timeout_value = 1800u64;
4028 assert!(timeout_value >= 300); assert!(timeout_value <= 3600); }
4031
4032 #[test]
4033 fn test_scattered_commit_detection() {
4034 use std::collections::HashSet;
4035
4036 let mut source_branches = HashSet::new();
4038 source_branches.insert("feature-branch-1".to_string());
4039 source_branches.insert("feature-branch-2".to_string());
4040 source_branches.insert("feature-branch-3".to_string());
4041
4042 let single_branch = HashSet::from(["main".to_string()]);
4044 assert_eq!(single_branch.len(), 1);
4045
4046 assert!(source_branches.len() > 1);
4048 assert_eq!(source_branches.len(), 3);
4049
4050 assert!(source_branches.contains("feature-branch-1"));
4052 assert!(source_branches.contains("feature-branch-2"));
4053 assert!(source_branches.contains("feature-branch-3"));
4054 }
4055
4056 #[test]
4057 fn test_source_branch_tracking() {
4058 let branch_a = "feature-work";
4062 let branch_b = "feature-work";
4063 assert_eq!(branch_a, branch_b);
4064
4065 let branch_1 = "feature-ui";
4067 let branch_2 = "feature-api";
4068 assert_ne!(branch_1, branch_2);
4069
4070 assert!(branch_1.starts_with("feature-"));
4072 assert!(branch_2.starts_with("feature-"));
4073 }
4074
4075 #[tokio::test]
4078 async fn test_push_default_behavior() {
4079 let (temp_dir, repo_path) = match create_test_repo() {
4081 Ok(repo) => repo,
4082 Err(_) => {
4083 println!("Skipping test due to git environment setup failure");
4084 return;
4085 }
4086 };
4087 let _ = &temp_dir;
4089
4090 if !repo_path.exists() {
4092 println!("Skipping test due to temporary directory creation issue");
4093 return;
4094 }
4095
4096 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4098
4099 match env::set_current_dir(&repo_path) {
4100 Ok(_) => {
4101 let result = push_to_stack(
4103 None, None, None, None, None, None, None, false, false, false, )
4114 .await;
4115
4116 if let Ok(orig) = original_dir {
4118 let _ = env::set_current_dir(orig);
4119 }
4120
4121 match &result {
4123 Err(e) => {
4124 let error_msg = e.to_string();
4125 assert!(
4127 error_msg.contains("No active stack")
4128 || error_msg.contains("config")
4129 || error_msg.contains("current directory")
4130 || error_msg.contains("Not a git repository")
4131 || error_msg.contains("could not find repository"),
4132 "Expected 'No active stack' or repository error, got: {error_msg}"
4133 );
4134 }
4135 Ok(_) => {
4136 println!(
4138 "Push succeeded unexpectedly - test environment may have active stack"
4139 );
4140 }
4141 }
4142 }
4143 Err(_) => {
4144 println!("Skipping test due to directory access restrictions");
4146 }
4147 }
4148
4149 let push_action = StackAction::Push {
4151 branch: None,
4152 message: None,
4153 commit: None,
4154 since: None,
4155 commits: None,
4156 squash: None,
4157 squash_since: None,
4158 auto_branch: false,
4159 allow_base_branch: false,
4160 dry_run: false,
4161 };
4162
4163 assert!(matches!(
4164 push_action,
4165 StackAction::Push {
4166 branch: None,
4167 message: None,
4168 commit: None,
4169 since: None,
4170 commits: None,
4171 squash: None,
4172 squash_since: None,
4173 auto_branch: false,
4174 allow_base_branch: false,
4175 dry_run: false
4176 }
4177 ));
4178 }
4179
4180 #[tokio::test]
4181 async fn test_submit_default_behavior() {
4182 let (temp_dir, repo_path) = match create_test_repo() {
4184 Ok(repo) => repo,
4185 Err(_) => {
4186 println!("Skipping test due to git environment setup failure");
4187 return;
4188 }
4189 };
4190 let _ = &temp_dir;
4192
4193 if !repo_path.exists() {
4195 println!("Skipping test due to temporary directory creation issue");
4196 return;
4197 }
4198
4199 let original_dir = match env::current_dir() {
4201 Ok(dir) => dir,
4202 Err(_) => {
4203 println!("Skipping test due to current directory access restrictions");
4204 return;
4205 }
4206 };
4207
4208 match env::set_current_dir(&repo_path) {
4209 Ok(_) => {
4210 let result = submit_entry(
4212 None, None, None, None, false, )
4218 .await;
4219
4220 let _ = env::set_current_dir(original_dir);
4222
4223 match &result {
4225 Err(e) => {
4226 let error_msg = e.to_string();
4227 assert!(
4229 error_msg.contains("No active stack")
4230 || error_msg.contains("config")
4231 || error_msg.contains("current directory")
4232 || error_msg.contains("Not a git repository")
4233 || error_msg.contains("could not find repository"),
4234 "Expected 'No active stack' or repository error, got: {error_msg}"
4235 );
4236 }
4237 Ok(_) => {
4238 println!("Submit succeeded unexpectedly - test environment may have active stack");
4240 }
4241 }
4242 }
4243 Err(_) => {
4244 println!("Skipping test due to directory access restrictions");
4246 }
4247 }
4248
4249 let submit_action = StackAction::Submit {
4251 entry: None,
4252 title: None,
4253 description: None,
4254 range: None,
4255 draft: false,
4256 };
4257
4258 assert!(matches!(
4259 submit_action,
4260 StackAction::Submit {
4261 entry: None,
4262 title: None,
4263 description: None,
4264 range: None,
4265 draft: false
4266 }
4267 ));
4268 }
4269
4270 #[test]
4271 fn test_targeting_options_still_work() {
4272 let commits = "abc123,def456,ghi789";
4276 let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
4277 assert_eq!(parsed.len(), 3);
4278 assert_eq!(parsed[0], "abc123");
4279 assert_eq!(parsed[1], "def456");
4280 assert_eq!(parsed[2], "ghi789");
4281
4282 let range = "1-3";
4284 assert!(range.contains('-'));
4285 let parts: Vec<&str> = range.split('-').collect();
4286 assert_eq!(parts.len(), 2);
4287
4288 let since_ref = "HEAD~3";
4290 assert!(since_ref.starts_with("HEAD"));
4291 assert!(since_ref.contains('~'));
4292 }
4293
4294 #[test]
4295 fn test_command_flow_logic() {
4296 assert!(matches!(
4298 StackAction::Push {
4299 branch: None,
4300 message: None,
4301 commit: None,
4302 since: None,
4303 commits: None,
4304 squash: None,
4305 squash_since: None,
4306 auto_branch: false,
4307 allow_base_branch: false,
4308 dry_run: false
4309 },
4310 StackAction::Push { .. }
4311 ));
4312
4313 assert!(matches!(
4314 StackAction::Submit {
4315 entry: None,
4316 title: None,
4317 description: None,
4318 range: None,
4319 draft: false
4320 },
4321 StackAction::Submit { .. }
4322 ));
4323 }
4324
4325 #[tokio::test]
4326 async fn test_deactivate_command_structure() {
4327 let deactivate_action = StackAction::Deactivate { force: false };
4329
4330 assert!(matches!(
4332 deactivate_action,
4333 StackAction::Deactivate { force: false }
4334 ));
4335
4336 let force_deactivate = StackAction::Deactivate { force: true };
4338 assert!(matches!(
4339 force_deactivate,
4340 StackAction::Deactivate { force: true }
4341 ));
4342 }
4343}