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