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};
11use uuid::Uuid;
12
13#[derive(ValueEnum, Clone, Debug)]
15pub enum RebaseStrategyArg {
16 ForcePush,
18 Interactive,
20}
21
22#[derive(ValueEnum, Clone, Debug)]
23pub enum MergeStrategyArg {
24 Merge,
26 Squash,
28 FastForward,
30}
31
32impl From<MergeStrategyArg> for crate::bitbucket::pull_request::MergeStrategy {
33 fn from(arg: MergeStrategyArg) -> Self {
34 match arg {
35 MergeStrategyArg::Merge => Self::Merge,
36 MergeStrategyArg::Squash => Self::Squash,
37 MergeStrategyArg::FastForward => Self::FastForward,
38 }
39 }
40}
41
42#[derive(Debug, Subcommand)]
43pub enum StackAction {
44 Create {
46 name: String,
48 #[arg(long, short)]
50 base: Option<String>,
51 #[arg(long, short)]
53 description: Option<String>,
54 },
55
56 List {
58 #[arg(long, short)]
60 verbose: bool,
61 #[arg(long)]
63 active: bool,
64 #[arg(long)]
66 format: Option<String>,
67 },
68
69 Switch {
71 name: String,
73 },
74
75 Deactivate {
77 #[arg(long)]
79 force: bool,
80 },
81
82 Show {
84 #[arg(short, long)]
86 verbose: bool,
87 #[arg(short, long)]
89 mergeable: bool,
90 },
91
92 Push {
94 #[arg(long, short)]
96 branch: Option<String>,
97 #[arg(long, short)]
99 message: Option<String>,
100 #[arg(long)]
102 commit: Option<String>,
103 #[arg(long)]
105 since: Option<String>,
106 #[arg(long)]
108 commits: Option<String>,
109 #[arg(long, num_args = 0..=1, default_missing_value = "0")]
111 squash: Option<usize>,
112 #[arg(long)]
114 squash_since: Option<String>,
115 #[arg(long)]
117 auto_branch: bool,
118 #[arg(long)]
120 allow_base_branch: bool,
121 #[arg(long)]
123 dry_run: bool,
124 },
125
126 Pop {
128 #[arg(long)]
130 keep_branch: bool,
131 },
132
133 Submit {
135 entry: Option<usize>,
137 #[arg(long, short)]
139 title: Option<String>,
140 #[arg(long, short)]
142 description: Option<String>,
143 #[arg(long)]
145 range: Option<String>,
146 #[arg(long, default_value_t = true)]
148 draft: bool,
149 #[arg(long, default_value_t = true)]
151 open: bool,
152 },
153
154 Status {
156 name: Option<String>,
158 },
159
160 Prs {
162 #[arg(long)]
164 state: Option<String>,
165 #[arg(long, short)]
167 verbose: bool,
168 },
169
170 Check {
172 #[arg(long)]
174 force: bool,
175 },
176
177 Sync {
179 #[arg(long)]
181 force: bool,
182 #[arg(long)]
184 cleanup: bool,
185 #[arg(long, short)]
187 interactive: bool,
188 },
189
190 Rebase {
192 #[arg(long, short)]
194 interactive: bool,
195 #[arg(long)]
197 onto: Option<String>,
198 #[arg(long, value_enum)]
200 strategy: Option<RebaseStrategyArg>,
201 },
202
203 ContinueRebase,
205
206 AbortRebase,
208
209 RebaseStatus,
211
212 Delete {
214 name: String,
216 #[arg(long)]
218 force: bool,
219 },
220
221 Validate {
233 name: Option<String>,
235 #[arg(long)]
237 fix: Option<String>,
238 },
239
240 Land {
242 entry: Option<usize>,
244 #[arg(short, long)]
246 force: bool,
247 #[arg(short, long)]
249 dry_run: bool,
250 #[arg(long)]
252 auto: bool,
253 #[arg(long)]
255 wait_for_builds: bool,
256 #[arg(long, value_enum, default_value = "squash")]
258 strategy: Option<MergeStrategyArg>,
259 #[arg(long, default_value = "1800")]
261 build_timeout: u64,
262 },
263
264 AutoLand {
266 #[arg(short, long)]
268 force: bool,
269 #[arg(short, long)]
271 dry_run: bool,
272 #[arg(long)]
274 wait_for_builds: bool,
275 #[arg(long, value_enum, default_value = "squash")]
277 strategy: Option<MergeStrategyArg>,
278 #[arg(long, default_value = "1800")]
280 build_timeout: u64,
281 },
282
283 ListPrs {
285 #[arg(short, long)]
287 state: Option<String>,
288 #[arg(short, long)]
290 verbose: bool,
291 },
292
293 ContinueLand,
295
296 AbortLand,
298
299 LandStatus,
301
302 Cleanup {
304 #[arg(long)]
306 dry_run: bool,
307 #[arg(long)]
309 force: bool,
310 #[arg(long)]
312 include_stale: bool,
313 #[arg(long, default_value = "30")]
315 stale_days: u32,
316 #[arg(long)]
318 cleanup_remote: bool,
319 #[arg(long)]
321 include_non_stack: bool,
322 #[arg(long)]
324 verbose: bool,
325 },
326
327 Repair,
329}
330
331pub async fn run(action: StackAction) -> Result<()> {
332 match action {
333 StackAction::Create {
334 name,
335 base,
336 description,
337 } => create_stack(name, base, description).await,
338 StackAction::List {
339 verbose,
340 active,
341 format,
342 } => list_stacks(verbose, active, format).await,
343 StackAction::Switch { name } => switch_stack(name).await,
344 StackAction::Deactivate { force } => deactivate_stack(force).await,
345 StackAction::Show { verbose, mergeable } => show_stack(verbose, mergeable).await,
346 StackAction::Push {
347 branch,
348 message,
349 commit,
350 since,
351 commits,
352 squash,
353 squash_since,
354 auto_branch,
355 allow_base_branch,
356 dry_run,
357 } => {
358 push_to_stack(
359 branch,
360 message,
361 commit,
362 since,
363 commits,
364 squash,
365 squash_since,
366 auto_branch,
367 allow_base_branch,
368 dry_run,
369 )
370 .await
371 }
372 StackAction::Pop { keep_branch } => pop_from_stack(keep_branch).await,
373 StackAction::Submit {
374 entry,
375 title,
376 description,
377 range,
378 draft,
379 open,
380 } => submit_entry(entry, title, description, range, draft, open).await,
381 StackAction::Status { name } => check_stack_status(name).await,
382 StackAction::Prs { state, verbose } => list_pull_requests(state, verbose).await,
383 StackAction::Check { force } => check_stack(force).await,
384 StackAction::Sync {
385 force,
386 cleanup,
387 interactive,
388 } => sync_stack(force, cleanup, interactive).await,
389 StackAction::Rebase {
390 interactive,
391 onto,
392 strategy,
393 } => rebase_stack(interactive, onto, strategy).await,
394 StackAction::ContinueRebase => continue_rebase().await,
395 StackAction::AbortRebase => abort_rebase().await,
396 StackAction::RebaseStatus => rebase_status().await,
397 StackAction::Delete { name, force } => delete_stack(name, force).await,
398 StackAction::Validate { name, fix } => validate_stack(name, fix).await,
399 StackAction::Land {
400 entry,
401 force,
402 dry_run,
403 auto,
404 wait_for_builds,
405 strategy,
406 build_timeout,
407 } => {
408 land_stack(
409 entry,
410 force,
411 dry_run,
412 auto,
413 wait_for_builds,
414 strategy,
415 build_timeout,
416 )
417 .await
418 }
419 StackAction::AutoLand {
420 force,
421 dry_run,
422 wait_for_builds,
423 strategy,
424 build_timeout,
425 } => auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await,
426 StackAction::ListPrs { state, verbose } => list_pull_requests(state, verbose).await,
427 StackAction::ContinueLand => continue_land().await,
428 StackAction::AbortLand => abort_land().await,
429 StackAction::LandStatus => land_status().await,
430 StackAction::Cleanup {
431 dry_run,
432 force,
433 include_stale,
434 stale_days,
435 cleanup_remote,
436 include_non_stack,
437 verbose,
438 } => {
439 cleanup_branches(
440 dry_run,
441 force,
442 include_stale,
443 stale_days,
444 cleanup_remote,
445 include_non_stack,
446 verbose,
447 )
448 .await
449 }
450 StackAction::Repair => repair_stack_data().await,
451 }
452}
453
454pub async fn show(verbose: bool, mergeable: bool) -> Result<()> {
456 show_stack(verbose, mergeable).await
457}
458
459#[allow(clippy::too_many_arguments)]
460pub async fn push(
461 branch: Option<String>,
462 message: Option<String>,
463 commit: Option<String>,
464 since: Option<String>,
465 commits: Option<String>,
466 squash: Option<usize>,
467 squash_since: Option<String>,
468 auto_branch: bool,
469 allow_base_branch: bool,
470 dry_run: bool,
471) -> Result<()> {
472 push_to_stack(
473 branch,
474 message,
475 commit,
476 since,
477 commits,
478 squash,
479 squash_since,
480 auto_branch,
481 allow_base_branch,
482 dry_run,
483 )
484 .await
485}
486
487pub async fn pop(keep_branch: bool) -> Result<()> {
488 pop_from_stack(keep_branch).await
489}
490
491pub async fn land(
492 entry: Option<usize>,
493 force: bool,
494 dry_run: bool,
495 auto: bool,
496 wait_for_builds: bool,
497 strategy: Option<MergeStrategyArg>,
498 build_timeout: u64,
499) -> Result<()> {
500 land_stack(
501 entry,
502 force,
503 dry_run,
504 auto,
505 wait_for_builds,
506 strategy,
507 build_timeout,
508 )
509 .await
510}
511
512pub async fn autoland(
513 force: bool,
514 dry_run: bool,
515 wait_for_builds: bool,
516 strategy: Option<MergeStrategyArg>,
517 build_timeout: u64,
518) -> Result<()> {
519 auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await
520}
521
522pub async fn sync(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
523 sync_stack(force, skip_cleanup, interactive).await
524}
525
526pub async fn rebase(
527 interactive: bool,
528 onto: Option<String>,
529 strategy: Option<RebaseStrategyArg>,
530) -> Result<()> {
531 rebase_stack(interactive, onto, strategy).await
532}
533
534pub async fn deactivate(force: bool) -> Result<()> {
535 deactivate_stack(force).await
536}
537
538pub async fn switch(name: String) -> Result<()> {
539 switch_stack(name).await
540}
541
542async fn create_stack(
543 name: String,
544 base: Option<String>,
545 description: Option<String>,
546) -> Result<()> {
547 let current_dir = env::current_dir()
548 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
549
550 let repo_root = find_repository_root(¤t_dir)
551 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
552
553 let mut manager = StackManager::new(&repo_root)?;
554 let stack_id = manager.create_stack(name.clone(), base.clone(), description.clone())?;
555
556 let stack = manager
558 .get_stack(&stack_id)
559 .ok_or_else(|| CascadeError::config("Failed to get created stack"))?;
560
561 Output::stack_info(
563 &name,
564 &stack_id.to_string(),
565 &stack.base_branch,
566 stack.working_branch.as_deref(),
567 true, );
569
570 if let Some(desc) = description {
571 Output::sub_item(format!("Description: {desc}"));
572 }
573
574 if stack.working_branch.is_none() {
576 Output::warning(format!(
577 "You're currently on the base branch '{}'",
578 stack.base_branch
579 ));
580 Output::next_steps(&[
581 &format!("Create a feature branch: git checkout -b {name}"),
582 "Make changes and commit them",
583 "Run 'ca push' to add commits to this stack",
584 ]);
585 } else {
586 Output::next_steps(&[
587 "Make changes and commit them",
588 "Run 'ca push' to add commits to this stack",
589 "Use 'ca submit' when ready to create pull requests",
590 ]);
591 }
592
593 Ok(())
594}
595
596async fn list_stacks(verbose: bool, active_only: bool, format: Option<String>) -> Result<()> {
597 let current_dir = env::current_dir()
598 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
599
600 let repo_root = find_repository_root(¤t_dir)
601 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
602
603 let manager = StackManager::new(&repo_root)?;
604 let mut stacks = manager.list_stacks();
605
606 if active_only {
607 stacks.retain(|(_, _, _, _, active_marker)| active_marker.is_some());
608 }
609
610 if let Some(ref format) = format {
611 match format.as_str() {
612 "json" => {
613 let mut json_stacks = Vec::new();
614
615 for (stack_id, name, status, entry_count, active_marker) in &stacks {
616 let (entries_json, working_branch, base_branch) =
617 if let Some(stack_obj) = manager.get_stack(stack_id) {
618 let entries_json = stack_obj
619 .entries
620 .iter()
621 .enumerate()
622 .map(|(idx, entry)| {
623 serde_json::json!({
624 "position": idx + 1,
625 "entry_id": entry.id.to_string(),
626 "branch_name": entry.branch.clone(),
627 "commit_hash": entry.commit_hash.clone(),
628 "short_hash": entry.short_hash(),
629 "is_submitted": entry.is_submitted,
630 "is_merged": entry.is_merged,
631 "pull_request_id": entry.pull_request_id.clone(),
632 })
633 })
634 .collect::<Vec<_>>();
635
636 (
637 entries_json,
638 stack_obj.working_branch.clone(),
639 Some(stack_obj.base_branch.clone()),
640 )
641 } else {
642 (Vec::new(), None, None)
643 };
644
645 let status_label = format!("{status:?}");
646
647 json_stacks.push(serde_json::json!({
648 "id": stack_id.to_string(),
649 "name": name,
650 "status": status_label,
651 "entry_count": entry_count,
652 "is_active": active_marker.is_some(),
653 "base_branch": base_branch,
654 "working_branch": working_branch,
655 "entries": entries_json,
656 }));
657 }
658
659 let json_output = serde_json::json!({ "stacks": json_stacks });
660 let serialized = serde_json::to_string_pretty(&json_output)?;
661 println!("{serialized}");
662 return Ok(());
663 }
664 "name" => {
665 for (_, name, _, _, _) in &stacks {
666 println!("{name}");
667 }
668 return Ok(());
669 }
670 "id" => {
671 for (stack_id, _, _, _, _) in &stacks {
672 println!("{}", stack_id);
673 }
674 return Ok(());
675 }
676 "status" => {
677 for (_, name, status, _, active_marker) in &stacks {
678 let status_label = format!("{status:?}");
679 let marker = if active_marker.is_some() {
680 " (active)"
681 } else {
682 ""
683 };
684 println!("{name}: {status_label}{marker}");
685 }
686 return Ok(());
687 }
688 other => {
689 return Err(CascadeError::config(format!(
690 "Unsupported format '{}'. Supported formats: name, id, status, json",
691 other
692 )));
693 }
694 }
695 }
696
697 if stacks.is_empty() {
698 if active_only {
699 Output::info("No active stack. Activate one with 'ca stack switch <name>'");
700 } else {
701 Output::info("No stacks found. Create one with: ca stack create <name>");
702 }
703 return Ok(());
704 }
705
706 println!("Stacks:");
707 for (stack_id, name, status, entry_count, active_marker) in stacks {
708 let status_icon = match status {
709 StackStatus::Clean => "✓",
710 StackStatus::Dirty => "~",
711 StackStatus::OutOfSync => "!",
712 StackStatus::Conflicted => "✗",
713 StackStatus::Rebasing => "↔",
714 StackStatus::NeedsSync => "~",
715 StackStatus::Corrupted => "✗",
716 };
717
718 let active_indicator = if active_marker.is_some() {
719 " (active)"
720 } else {
721 ""
722 };
723
724 let stack = manager.get_stack(&stack_id);
726
727 if verbose {
728 println!(" {status_icon} {name} [{entry_count}]{active_indicator}");
729 println!(" ID: {stack_id}");
730 if let Some(stack_meta) = manager.get_stack_metadata(&stack_id) {
731 println!(" Base: {}", stack_meta.base_branch);
732 if let Some(desc) = &stack_meta.description {
733 println!(" Description: {desc}");
734 }
735 println!(
736 " Commits: {} total, {} submitted",
737 stack_meta.total_commits, stack_meta.submitted_commits
738 );
739 if stack_meta.has_conflicts {
740 Output::warning(" Has conflicts");
741 }
742 }
743
744 if let Some(stack_obj) = stack {
746 if !stack_obj.entries.is_empty() {
747 println!(" Branches:");
748 for (i, entry) in stack_obj.entries.iter().enumerate() {
749 let entry_num = i + 1;
750 let submitted_indicator = if entry.is_submitted {
751 "[submitted]"
752 } else {
753 ""
754 };
755 let branch_name = &entry.branch;
756 let short_message = if entry.message.len() > 40 {
757 format!("{}...", &entry.message[..37])
758 } else {
759 entry.message.clone()
760 };
761 println!(" {entry_num}. {submitted_indicator} {branch_name} - {short_message}");
762 }
763 }
764 }
765 println!();
766 } else {
767 let branch_info = if let Some(stack_obj) = stack {
769 if stack_obj.entries.is_empty() {
770 String::new()
771 } else if stack_obj.entries.len() == 1 {
772 format!(" → {}", stack_obj.entries[0].branch)
773 } else {
774 let first_branch = &stack_obj.entries[0].branch;
775 let last_branch = &stack_obj.entries.last().unwrap().branch;
776 format!(" → {first_branch} … {last_branch}")
777 }
778 } else {
779 String::new()
780 };
781
782 println!(" {status_icon} {name} [{entry_count}]{branch_info}{active_indicator}");
783 }
784 }
785
786 if !verbose {
787 println!("\nUse --verbose for more details");
788 }
789
790 Ok(())
791}
792
793async fn switch_stack(name: String) -> Result<()> {
794 let current_dir = env::current_dir()
795 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
796
797 let repo_root = find_repository_root(¤t_dir)
798 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
799
800 let mut manager = StackManager::new(&repo_root)?;
801 let repo = GitRepository::open(&repo_root)?;
802
803 let stack = manager
805 .get_stack_by_name(&name)
806 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
807
808 if let Some(working_branch) = &stack.working_branch {
810 let current_branch = repo.get_current_branch().ok();
812
813 if current_branch.as_ref() != Some(working_branch) {
814 Output::progress(format!(
815 "Switching to stack working branch: {working_branch}"
816 ));
817
818 if repo.branch_exists(working_branch) {
820 match repo.checkout_branch(working_branch) {
821 Ok(_) => {
822 Output::success(format!("Checked out branch: {working_branch}"));
823 }
824 Err(e) => {
825 Output::warning(format!("Failed to checkout '{working_branch}': {e}"));
826 Output::sub_item("Stack activated but stayed on current branch");
827 Output::sub_item(format!(
828 "You can manually checkout with: git checkout {working_branch}"
829 ));
830 }
831 }
832 } else {
833 Output::warning(format!(
834 "Stack working branch '{working_branch}' doesn't exist locally"
835 ));
836 Output::sub_item("Stack activated but stayed on current branch");
837 Output::sub_item(format!(
838 "You may need to fetch from remote: git fetch origin {working_branch}"
839 ));
840 }
841 } else {
842 Output::success(format!("Already on stack working branch: {working_branch}"));
843 }
844 } else {
845 Output::warning(format!("Stack '{name}' has no working branch set"));
847 Output::sub_item(
848 "This typically happens when a stack was created while on the base branch",
849 );
850
851 Output::tip("To start working on this stack:");
852 Output::bullet(format!("Create a feature branch: git checkout -b {name}"));
853 Output::bullet("The stack will automatically track this as its working branch");
854 Output::bullet("Then use 'ca push' to add commits to the stack");
855
856 Output::sub_item(format!("Base branch: {}", stack.base_branch));
857 }
858
859 manager.set_active_stack_by_name(&name)?;
861 Output::success(format!("Switched to stack '{name}'"));
862
863 Ok(())
864}
865
866async fn deactivate_stack(force: bool) -> Result<()> {
867 let current_dir = env::current_dir()
868 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
869
870 let repo_root = find_repository_root(¤t_dir)
871 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
872
873 let mut manager = StackManager::new(&repo_root)?;
874
875 let active_stack = manager.get_active_stack();
876
877 if active_stack.is_none() {
878 Output::info("No active stack to deactivate");
879 return Ok(());
880 }
881
882 let stack_name = active_stack.unwrap().name.clone();
883
884 if !force {
885 Output::warning(format!(
886 "This will deactivate stack '{stack_name}' and return to normal Git workflow"
887 ));
888 Output::sub_item(format!(
889 "You can reactivate it later with 'ca stacks switch {stack_name}'"
890 ));
891 let should_deactivate = Confirm::with_theme(&ColorfulTheme::default())
893 .with_prompt("Continue with deactivation?")
894 .default(false)
895 .interact()
896 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
897
898 if !should_deactivate {
899 Output::info("Cancelled deactivation");
900 return Ok(());
901 }
902 }
903
904 manager.set_active_stack(None)?;
906
907 Output::success(format!("Deactivated stack '{stack_name}'"));
908 Output::sub_item("Stack management is now OFF - you can use normal Git workflow");
909 Output::sub_item(format!("To reactivate: ca stacks switch {stack_name}"));
910
911 Ok(())
912}
913
914async fn show_stack(verbose: bool, show_mergeable: bool) -> Result<()> {
915 let current_dir = env::current_dir()
916 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
917
918 let repo_root = find_repository_root(¤t_dir)
919 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
920
921 let stack_manager = StackManager::new(&repo_root)?;
922
923 let (stack_id, stack_name, stack_base, stack_working, stack_entries) = {
925 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
926 CascadeError::config(
927 "No active stack. Use 'ca stacks create' or 'ca stacks switch' to select a stack"
928 .to_string(),
929 )
930 })?;
931
932 (
933 active_stack.id,
934 active_stack.name.clone(),
935 active_stack.base_branch.clone(),
936 active_stack.working_branch.clone(),
937 active_stack.entries.clone(),
938 )
939 };
940
941 Output::stack_info(
943 &stack_name,
944 &stack_id.to_string(),
945 &stack_base,
946 stack_working.as_deref(),
947 true, );
949 Output::sub_item(format!("Total entries: {}", stack_entries.len()));
950
951 if stack_entries.is_empty() {
952 Output::info("No entries in this stack yet");
953 Output::tip("Use 'ca push' to add commits to this stack");
954 return Ok(());
955 }
956
957 Output::section("Stack Entries");
959 for (i, entry) in stack_entries.iter().enumerate() {
960 let entry_num = i + 1;
961 let short_hash = entry.short_hash();
962 let short_msg = entry.short_message(50);
963
964 let metadata = stack_manager.get_repository_metadata();
967 let source_branch_info = if !entry.is_submitted {
968 if let Some(commit_meta) = metadata.get_commit(&entry.commit_hash) {
969 if commit_meta.source_branch != commit_meta.branch
970 && !commit_meta.source_branch.is_empty()
971 {
972 format!(" (from {})", commit_meta.source_branch)
973 } else {
974 String::new()
975 }
976 } else {
977 String::new()
978 }
979 } else {
980 String::new()
981 };
982
983 let status_colored = Output::entry_status(entry.is_submitted, entry.is_merged);
985
986 Output::numbered_item(
987 entry_num,
988 format!("{short_hash} {status_colored} {short_msg}{source_branch_info}"),
989 );
990
991 if verbose {
992 Output::sub_item(format!("Branch: {}", entry.branch));
993 Output::sub_item(format!(
994 "Created: {}",
995 entry.created_at.format("%Y-%m-%d %H:%M")
996 ));
997 if let Some(pr_id) = &entry.pull_request_id {
998 Output::sub_item(format!("PR: #{pr_id}"));
999 }
1000
1001 Output::sub_item("Commit Message:");
1003 let lines: Vec<&str> = entry.message.lines().collect();
1004 for line in lines {
1005 Output::sub_item(format!(" {line}"));
1006 }
1007 }
1008 }
1009
1010 if show_mergeable {
1012 Output::section("Mergeability Status");
1013
1014 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1016 let config_path = config_dir.join("config.json");
1017 let settings = crate::config::Settings::load_from_file(&config_path)?;
1018
1019 let cascade_config = crate::config::CascadeConfig {
1020 bitbucket: Some(settings.bitbucket.clone()),
1021 git: settings.git.clone(),
1022 auth: crate::config::AuthConfig::default(),
1023 cascade: settings.cascade.clone(),
1024 };
1025
1026 let mut integration =
1027 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1028
1029 match integration.check_enhanced_stack_status(&stack_id).await {
1030 Ok(status) => {
1031 Output::bullet(format!("Total entries: {}", status.total_entries));
1032 Output::bullet(format!("Submitted: {}", status.submitted_entries));
1033 Output::bullet(format!("Open PRs: {}", status.open_prs));
1034 Output::bullet(format!("Merged PRs: {}", status.merged_prs));
1035 Output::bullet(format!("Declined PRs: {}", status.declined_prs));
1036 Output::bullet(format!(
1037 "Completion: {:.1}%",
1038 status.completion_percentage()
1039 ));
1040
1041 if !status.enhanced_statuses.is_empty() {
1042 Output::section("Pull Request Status");
1043 let mut ready_to_land = 0;
1044
1045 for enhanced in &status.enhanced_statuses {
1046 let (ready_icon, show_details) = match enhanced.pr.state {
1047 crate::bitbucket::pull_request::PullRequestState::Merged => {
1048 ("[MERGED]", false) }
1050 crate::bitbucket::pull_request::PullRequestState::Declined => {
1051 ("[DECLINED]", false) }
1053 crate::bitbucket::pull_request::PullRequestState::Open => {
1054 if enhanced.is_ready_to_land() {
1055 ready_to_land += 1;
1056 ("[READY]", true) } else {
1058 ("[PENDING]", true) }
1060 }
1061 };
1062
1063 let output = if show_details {
1064 let status_display = enhanced.get_display_status();
1065 format!(
1066 "{} PR #{}: {} ({})",
1067 ready_icon, enhanced.pr.id, enhanced.pr.title, status_display
1068 )
1069 } else {
1070 format!(
1071 "{} PR #{}: {}",
1072 ready_icon, enhanced.pr.id, enhanced.pr.title
1073 )
1074 };
1075
1076 Output::bullet(output);
1077
1078 if verbose {
1079 println!(
1080 " {} -> {}",
1081 enhanced.pr.from_ref.display_id, enhanced.pr.to_ref.display_id
1082 );
1083
1084 if !enhanced.is_ready_to_land() {
1086 let blocking = enhanced.get_blocking_reasons();
1087 if !blocking.is_empty() {
1088 println!(" Blocking: {}", blocking.join(", "));
1089 }
1090 }
1091
1092 println!(
1094 " Reviews: {} approval{}",
1095 enhanced.review_status.current_approvals,
1096 if enhanced.review_status.current_approvals == 1 {
1097 ""
1098 } else {
1099 "s"
1100 }
1101 );
1102
1103 if enhanced.review_status.needs_work_count > 0 {
1104 println!(
1105 " {} reviewers requested changes",
1106 enhanced.review_status.needs_work_count
1107 );
1108 }
1109
1110 if let Some(build) = &enhanced.build_status {
1112 let build_icon = match build.state {
1113 crate::bitbucket::pull_request::BuildState::Successful => "✓",
1114 crate::bitbucket::pull_request::BuildState::Failed => "✗",
1115 crate::bitbucket::pull_request::BuildState::InProgress => "~",
1116 _ => "○",
1117 };
1118 println!(" Build: {} {:?}", build_icon, build.state);
1119 }
1120
1121 if let Some(url) = enhanced.pr.web_url() {
1122 println!(" URL: {url}");
1123 }
1124 println!();
1125 }
1126 }
1127
1128 if ready_to_land > 0 {
1129 println!(
1130 "\n🎯 {} PR{} ready to land! Use 'ca land' to land them all.",
1131 ready_to_land,
1132 if ready_to_land == 1 { " is" } else { "s are" }
1133 );
1134 }
1135 }
1136 }
1137 Err(e) => {
1138 tracing::debug!("Failed to get enhanced stack status: {}", e);
1139 Output::warning("Could not fetch mergability status");
1140 Output::sub_item("Use 'ca stack show --verbose' for basic PR information");
1141 }
1142 }
1143 } else {
1144 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1146 let config_path = config_dir.join("config.json");
1147 let settings = crate::config::Settings::load_from_file(&config_path)?;
1148
1149 let cascade_config = crate::config::CascadeConfig {
1150 bitbucket: Some(settings.bitbucket.clone()),
1151 git: settings.git.clone(),
1152 auth: crate::config::AuthConfig::default(),
1153 cascade: settings.cascade.clone(),
1154 };
1155
1156 let integration =
1157 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1158
1159 match integration.check_stack_status(&stack_id).await {
1160 Ok(status) => {
1161 println!("\nPull Request Status:");
1162 println!(" Total entries: {}", status.total_entries);
1163 println!(" Submitted: {}", status.submitted_entries);
1164 println!(" Open PRs: {}", status.open_prs);
1165 println!(" Merged PRs: {}", status.merged_prs);
1166 println!(" Declined PRs: {}", status.declined_prs);
1167 println!(" Completion: {:.1}%", status.completion_percentage());
1168
1169 if !status.pull_requests.is_empty() {
1170 println!("\nPull Requests:");
1171 for pr in &status.pull_requests {
1172 let state_icon = match pr.state {
1173 crate::bitbucket::PullRequestState::Open => "→",
1174 crate::bitbucket::PullRequestState::Merged => "✓",
1175 crate::bitbucket::PullRequestState::Declined => "✗",
1176 };
1177 println!(
1178 " {} PR #{}: {} ({} -> {})",
1179 state_icon,
1180 pr.id,
1181 pr.title,
1182 pr.from_ref.display_id,
1183 pr.to_ref.display_id
1184 );
1185 if let Some(url) = pr.web_url() {
1186 println!(" URL: {url}");
1187 }
1188 }
1189 }
1190
1191 println!();
1192 Output::tip("Use 'ca stack --mergeable' to see detailed status including build and review information");
1193 }
1194 Err(e) => {
1195 tracing::debug!("Failed to check stack status: {}", e);
1196 }
1197 }
1198 }
1199
1200 Ok(())
1201}
1202
1203#[allow(clippy::too_many_arguments)]
1204async fn push_to_stack(
1205 branch: Option<String>,
1206 message: Option<String>,
1207 commit: Option<String>,
1208 since: Option<String>,
1209 commits: Option<String>,
1210 squash: Option<usize>,
1211 squash_since: Option<String>,
1212 auto_branch: bool,
1213 allow_base_branch: bool,
1214 dry_run: bool,
1215) -> Result<()> {
1216 let current_dir = env::current_dir()
1217 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1218
1219 let repo_root = find_repository_root(¤t_dir)
1220 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1221
1222 let mut manager = StackManager::new(&repo_root)?;
1223 let repo = GitRepository::open(&repo_root)?;
1224
1225 if !manager.check_for_branch_change()? {
1227 return Ok(()); }
1229
1230 let active_stack = manager.get_active_stack().ok_or_else(|| {
1232 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1233 })?;
1234
1235 let current_branch = repo.get_current_branch()?;
1237 let base_branch = &active_stack.base_branch;
1238
1239 if current_branch == *base_branch {
1240 Output::error(format!(
1241 "You're currently on the base branch '{base_branch}'"
1242 ));
1243 Output::sub_item("Making commits directly on the base branch is not recommended.");
1244 Output::sub_item("This can pollute the base branch with work-in-progress commits.");
1245
1246 if allow_base_branch {
1248 Output::warning("Proceeding anyway due to --allow-base-branch flag");
1249 } else {
1250 let has_changes = repo.is_dirty()?;
1252
1253 if has_changes {
1254 if auto_branch {
1255 let feature_branch = format!("feature/{}-work", active_stack.name);
1257 Output::progress(format!(
1258 "Auto-creating feature branch '{feature_branch}'..."
1259 ));
1260
1261 repo.create_branch(&feature_branch, None)?;
1262 repo.checkout_branch(&feature_branch)?;
1263
1264 Output::success(format!("Created and switched to '{feature_branch}'"));
1265 println!(" You can now commit and push your changes safely");
1266
1267 } else {
1269 println!("\nYou have uncommitted changes. Here are your options:");
1270 println!(" 1. Create a feature branch first:");
1271 println!(" git checkout -b feature/my-work");
1272 println!(" git commit -am \"your work\"");
1273 println!(" ca push");
1274 println!("\n 2. Auto-create a branch (recommended):");
1275 println!(" ca push --auto-branch");
1276 println!("\n 3. Force push to base branch (dangerous):");
1277 println!(" ca push --allow-base-branch");
1278
1279 return Err(CascadeError::config(
1280 "Refusing to push uncommitted changes from base branch. Use one of the options above."
1281 ));
1282 }
1283 } else {
1284 let commits_to_check = if let Some(commits_str) = &commits {
1286 commits_str
1287 .split(',')
1288 .map(|s| s.trim().to_string())
1289 .collect::<Vec<String>>()
1290 } else if let Some(since_ref) = &since {
1291 let since_commit = repo.resolve_reference(since_ref)?;
1292 let head_commit = repo.get_head_commit()?;
1293 let commits = repo.get_commits_between(
1294 &since_commit.id().to_string(),
1295 &head_commit.id().to_string(),
1296 )?;
1297 commits.into_iter().map(|c| c.id().to_string()).collect()
1298 } else if commit.is_none() {
1299 let mut unpushed = Vec::new();
1300 let head_commit = repo.get_head_commit()?;
1301 let mut current_commit = head_commit;
1302
1303 loop {
1304 let commit_hash = current_commit.id().to_string();
1305 let already_in_stack = active_stack
1306 .entries
1307 .iter()
1308 .any(|entry| entry.commit_hash == commit_hash);
1309
1310 if already_in_stack {
1311 break;
1312 }
1313
1314 unpushed.push(commit_hash);
1315
1316 if let Some(parent) = current_commit.parents().next() {
1317 current_commit = parent;
1318 } else {
1319 break;
1320 }
1321 }
1322
1323 unpushed.reverse();
1324 unpushed
1325 } else {
1326 vec![repo.get_head_commit()?.id().to_string()]
1327 };
1328
1329 if !commits_to_check.is_empty() {
1330 if auto_branch {
1331 let feature_branch = format!("feature/{}-work", active_stack.name);
1333 Output::progress(format!(
1334 "Auto-creating feature branch '{feature_branch}'..."
1335 ));
1336
1337 repo.create_branch(&feature_branch, Some(base_branch))?;
1338 repo.checkout_branch(&feature_branch)?;
1339
1340 println!(
1342 "🍒 Cherry-picking {} commit(s) to new branch...",
1343 commits_to_check.len()
1344 );
1345 for commit_hash in &commits_to_check {
1346 match repo.cherry_pick(commit_hash) {
1347 Ok(_) => println!(" ✅ Cherry-picked {}", &commit_hash[..8]),
1348 Err(e) => {
1349 Output::error(format!(
1350 "Failed to cherry-pick {}: {}",
1351 &commit_hash[..8],
1352 e
1353 ));
1354 Output::tip("You may need to resolve conflicts manually");
1355 return Err(CascadeError::branch(format!(
1356 "Failed to cherry-pick commit {commit_hash}: {e}"
1357 )));
1358 }
1359 }
1360 }
1361
1362 println!(
1363 "✅ Successfully moved {} commit(s) to '{feature_branch}'",
1364 commits_to_check.len()
1365 );
1366 println!(
1367 " You're now on the feature branch and can continue with 'ca push'"
1368 );
1369
1370 } else {
1372 println!(
1373 "\n💡 Found {} commit(s) to push from base branch '{base_branch}'",
1374 commits_to_check.len()
1375 );
1376 println!(" These commits are currently ON the base branch, which may not be intended.");
1377 println!("\n Options:");
1378 println!(" 1. Auto-create feature branch and cherry-pick commits:");
1379 println!(" ca push --auto-branch");
1380 println!("\n 2. Manually create branch and move commits:");
1381 println!(" git checkout -b feature/my-work");
1382 println!(" ca push");
1383 println!("\n 3. Force push from base branch (not recommended):");
1384 println!(" ca push --allow-base-branch");
1385
1386 return Err(CascadeError::config(
1387 "Refusing to push commits from base branch. Use --auto-branch or create a feature branch manually."
1388 ));
1389 }
1390 }
1391 }
1392 }
1393 }
1394
1395 if let Some(squash_count) = squash {
1397 if squash_count == 0 {
1398 let active_stack = manager.get_active_stack().ok_or_else(|| {
1400 CascadeError::config(
1401 "No active stack. Create a stack first with 'ca stacks create'",
1402 )
1403 })?;
1404
1405 let unpushed_count = get_unpushed_commits(&repo, active_stack)?.len();
1406
1407 if unpushed_count == 0 {
1408 Output::info(" No unpushed commits to squash");
1409 } else if unpushed_count == 1 {
1410 Output::info(" Only 1 unpushed commit, no squashing needed");
1411 } else {
1412 println!(" Auto-detected {unpushed_count} unpushed commits, squashing...");
1413 squash_commits(&repo, unpushed_count, None).await?;
1414 Output::success(" Squashed {unpushed_count} unpushed commits into one");
1415 }
1416 } else {
1417 println!(" Squashing last {squash_count} commits...");
1418 squash_commits(&repo, squash_count, None).await?;
1419 Output::success(" Squashed {squash_count} commits into one");
1420 }
1421 } else if let Some(since_ref) = squash_since {
1422 println!(" Squashing commits since {since_ref}...");
1423 let since_commit = repo.resolve_reference(&since_ref)?;
1424 let commits_count = count_commits_since(&repo, &since_commit.id().to_string())?;
1425 squash_commits(&repo, commits_count, Some(since_ref.clone())).await?;
1426 Output::success(" Squashed {commits_count} commits since {since_ref} into one");
1427 }
1428
1429 let commits_to_push = if let Some(commits_str) = commits {
1431 commits_str
1433 .split(',')
1434 .map(|s| s.trim().to_string())
1435 .collect::<Vec<String>>()
1436 } else if let Some(since_ref) = since {
1437 let since_commit = repo.resolve_reference(&since_ref)?;
1439 let head_commit = repo.get_head_commit()?;
1440
1441 let commits = repo.get_commits_between(
1443 &since_commit.id().to_string(),
1444 &head_commit.id().to_string(),
1445 )?;
1446 commits.into_iter().map(|c| c.id().to_string()).collect()
1447 } else if let Some(hash) = commit {
1448 vec![hash]
1450 } else {
1451 let active_stack = manager.get_active_stack().ok_or_else(|| {
1453 CascadeError::config("No active stack. Create a stack first with 'ca stacks create'")
1454 })?;
1455
1456 let base_branch = &active_stack.base_branch;
1458 let current_branch = repo.get_current_branch()?;
1459
1460 if current_branch == *base_branch {
1462 let mut unpushed = Vec::new();
1463 let head_commit = repo.get_head_commit()?;
1464 let mut current_commit = head_commit;
1465
1466 loop {
1468 let commit_hash = current_commit.id().to_string();
1469 let already_in_stack = active_stack
1470 .entries
1471 .iter()
1472 .any(|entry| entry.commit_hash == commit_hash);
1473
1474 if already_in_stack {
1475 break;
1476 }
1477
1478 unpushed.push(commit_hash);
1479
1480 if let Some(parent) = current_commit.parents().next() {
1482 current_commit = parent;
1483 } else {
1484 break;
1485 }
1486 }
1487
1488 unpushed.reverse(); unpushed
1490 } else {
1491 match repo.get_commits_between(base_branch, ¤t_branch) {
1493 Ok(commits) => {
1494 let mut unpushed: Vec<String> =
1495 commits.into_iter().map(|c| c.id().to_string()).collect();
1496
1497 unpushed.retain(|commit_hash| {
1499 !active_stack
1500 .entries
1501 .iter()
1502 .any(|entry| entry.commit_hash == *commit_hash)
1503 });
1504
1505 unpushed.reverse(); unpushed
1507 }
1508 Err(e) => {
1509 return Err(CascadeError::branch(format!(
1510 "Failed to calculate commits between '{base_branch}' and '{current_branch}': {e}. \
1511 This usually means the branches have diverged or don't share common history."
1512 )));
1513 }
1514 }
1515 }
1516 };
1517
1518 if commits_to_push.is_empty() {
1519 Output::info(" No commits to push to stack");
1520 return Ok(());
1521 }
1522
1523 analyze_commits_for_safeguards(&commits_to_push, &repo, dry_run).await?;
1525
1526 if dry_run {
1528 return Ok(());
1529 }
1530
1531 let mut pushed_count = 0;
1533 let mut source_branches = std::collections::HashSet::new();
1534
1535 for (i, commit_hash) in commits_to_push.iter().enumerate() {
1536 let commit_obj = repo.get_commit(commit_hash)?;
1537 let commit_msg = commit_obj.message().unwrap_or("").to_string();
1538
1539 let commit_source_branch = repo
1541 .find_branch_containing_commit(commit_hash)
1542 .unwrap_or_else(|_| current_branch.clone());
1543 source_branches.insert(commit_source_branch.clone());
1544
1545 let branch_name = if i == 0 && branch.is_some() {
1547 branch.clone().unwrap()
1548 } else {
1549 let temp_repo = GitRepository::open(&repo_root)?;
1551 let branch_mgr = crate::git::BranchManager::new(temp_repo);
1552 branch_mgr.generate_branch_name(&commit_msg)
1553 };
1554
1555 let final_message = if i == 0 && message.is_some() {
1557 message.clone().unwrap()
1558 } else {
1559 commit_msg.clone()
1560 };
1561
1562 let entry_id = manager.push_to_stack(
1563 branch_name.clone(),
1564 commit_hash.clone(),
1565 final_message.clone(),
1566 commit_source_branch.clone(),
1567 )?;
1568 pushed_count += 1;
1569
1570 Output::success(format!(
1571 "Pushed commit {}/{} to stack",
1572 i + 1,
1573 commits_to_push.len()
1574 ));
1575 Output::sub_item(format!(
1576 "Commit: {} ({})",
1577 &commit_hash[..8],
1578 commit_msg.split('\n').next().unwrap_or("")
1579 ));
1580 Output::sub_item(format!("Branch: {branch_name}"));
1581 Output::sub_item(format!("Source: {commit_source_branch}"));
1582 Output::sub_item(format!("Entry ID: {entry_id}"));
1583 println!();
1584 }
1585
1586 if source_branches.len() > 1 {
1588 Output::warning("Scattered Commit Detection");
1589 Output::sub_item(format!(
1590 "You've pushed commits from {} different Git branches:",
1591 source_branches.len()
1592 ));
1593 for branch in &source_branches {
1594 Output::bullet(branch.to_string());
1595 }
1596
1597 Output::section("This can lead to confusion because:");
1598 Output::bullet("Stack appears sequential but commits are scattered across branches");
1599 Output::bullet("Team members won't know which branch contains which work");
1600 Output::bullet("Branch cleanup becomes unclear after merge");
1601 Output::bullet("Rebase operations become more complex");
1602
1603 Output::tip("Consider consolidating work to a single feature branch:");
1604 Output::bullet("Create a new feature branch: git checkout -b feature/consolidated-work");
1605 Output::bullet("Cherry-pick commits in order: git cherry-pick <commit1> <commit2> ...");
1606 Output::bullet("Delete old scattered branches");
1607 Output::bullet("Push the consolidated branch to your stack");
1608 println!();
1609 }
1610
1611 Output::success(format!(
1612 "Successfully pushed {} commit{} to stack",
1613 pushed_count,
1614 if pushed_count == 1 { "" } else { "s" }
1615 ));
1616
1617 Ok(())
1618}
1619
1620async fn pop_from_stack(keep_branch: bool) -> Result<()> {
1621 let current_dir = env::current_dir()
1622 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1623
1624 let repo_root = find_repository_root(¤t_dir)
1625 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1626
1627 let mut manager = StackManager::new(&repo_root)?;
1628 let repo = GitRepository::open(&repo_root)?;
1629
1630 let entry = manager.pop_from_stack()?;
1631
1632 Output::success("Popped commit from stack");
1633 Output::sub_item(format!(
1634 "Commit: {} ({})",
1635 entry.short_hash(),
1636 entry.short_message(50)
1637 ));
1638 Output::sub_item(format!("Branch: {}", entry.branch));
1639
1640 if !keep_branch && entry.branch != repo.get_current_branch()? {
1642 match repo.delete_branch(&entry.branch) {
1643 Ok(_) => Output::sub_item(format!("Deleted branch: {}", entry.branch)),
1644 Err(e) => Output::warning(format!("Could not delete branch {}: {}", entry.branch, e)),
1645 }
1646 }
1647
1648 Ok(())
1649}
1650
1651async fn submit_entry(
1652 entry: Option<usize>,
1653 title: Option<String>,
1654 description: Option<String>,
1655 range: Option<String>,
1656 draft: bool,
1657 open: bool,
1658) -> Result<()> {
1659 let current_dir = env::current_dir()
1660 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1661
1662 let repo_root = find_repository_root(¤t_dir)
1663 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1664
1665 let mut stack_manager = StackManager::new(&repo_root)?;
1666
1667 if !stack_manager.check_for_branch_change()? {
1669 return Ok(()); }
1671
1672 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1674 let config_path = config_dir.join("config.json");
1675 let settings = crate::config::Settings::load_from_file(&config_path)?;
1676
1677 let cascade_config = crate::config::CascadeConfig {
1679 bitbucket: Some(settings.bitbucket.clone()),
1680 git: settings.git.clone(),
1681 auth: crate::config::AuthConfig::default(),
1682 cascade: settings.cascade.clone(),
1683 };
1684
1685 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1687 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1688 })?;
1689 let stack_id = active_stack.id;
1690
1691 let entries_to_submit = if let Some(range_str) = range {
1693 let mut entries = Vec::new();
1695
1696 if range_str.contains('-') {
1697 let parts: Vec<&str> = range_str.split('-').collect();
1699 if parts.len() != 2 {
1700 return Err(CascadeError::config(
1701 "Invalid range format. Use 'start-end' (e.g., '1-3')",
1702 ));
1703 }
1704
1705 let start: usize = parts[0]
1706 .parse()
1707 .map_err(|_| CascadeError::config("Invalid start number in range"))?;
1708 let end: usize = parts[1]
1709 .parse()
1710 .map_err(|_| CascadeError::config("Invalid end number in range"))?;
1711
1712 if start == 0
1713 || end == 0
1714 || start > active_stack.entries.len()
1715 || end > active_stack.entries.len()
1716 {
1717 return Err(CascadeError::config(format!(
1718 "Range out of bounds. Stack has {} entries",
1719 active_stack.entries.len()
1720 )));
1721 }
1722
1723 for i in start..=end {
1724 entries.push((i, active_stack.entries[i - 1].clone()));
1725 }
1726 } else {
1727 for entry_str in range_str.split(',') {
1729 let entry_num: usize = entry_str.trim().parse().map_err(|_| {
1730 CascadeError::config(format!("Invalid entry number: {entry_str}"))
1731 })?;
1732
1733 if entry_num == 0 || entry_num > active_stack.entries.len() {
1734 return Err(CascadeError::config(format!(
1735 "Entry {} out of bounds. Stack has {} entries",
1736 entry_num,
1737 active_stack.entries.len()
1738 )));
1739 }
1740
1741 entries.push((entry_num, active_stack.entries[entry_num - 1].clone()));
1742 }
1743 }
1744
1745 entries
1746 } else if let Some(entry_num) = entry {
1747 if entry_num == 0 || entry_num > active_stack.entries.len() {
1749 return Err(CascadeError::config(format!(
1750 "Invalid entry number: {}. Stack has {} entries",
1751 entry_num,
1752 active_stack.entries.len()
1753 )));
1754 }
1755 vec![(entry_num, active_stack.entries[entry_num - 1].clone())]
1756 } else {
1757 active_stack
1759 .entries
1760 .iter()
1761 .enumerate()
1762 .filter(|(_, entry)| !entry.is_submitted)
1763 .map(|(i, entry)| (i + 1, entry.clone())) .collect::<Vec<(usize, _)>>()
1765 };
1766
1767 if entries_to_submit.is_empty() {
1768 Output::info("No entries to submit");
1769 return Ok(());
1770 }
1771
1772 Output::section(format!(
1774 "Submitting {} {}",
1775 entries_to_submit.len(),
1776 if entries_to_submit.len() == 1 {
1777 "entry"
1778 } else {
1779 "entries"
1780 }
1781 ));
1782 println!();
1783
1784 let integration_stack_manager = StackManager::new(&repo_root)?;
1786 let mut integration =
1787 BitbucketIntegration::new(integration_stack_manager, cascade_config.clone())?;
1788
1789 let mut submitted_count = 0;
1791 let mut failed_entries = Vec::new();
1792 let mut pr_urls = Vec::new(); let total_entries = entries_to_submit.len();
1794
1795 for (entry_num, entry_to_submit) in &entries_to_submit {
1796 let tree_char = if entries_to_submit.len() == 1 {
1798 "→"
1799 } else if entry_num == &entries_to_submit.len() {
1800 "└─"
1801 } else {
1802 "├─"
1803 };
1804 print!(
1805 " {} Entry {}: {}... ",
1806 tree_char, entry_num, entry_to_submit.branch
1807 );
1808 std::io::Write::flush(&mut std::io::stdout()).ok();
1809
1810 let entry_title = if total_entries == 1 {
1812 title.clone()
1813 } else {
1814 None
1815 };
1816 let entry_description = if total_entries == 1 {
1817 description.clone()
1818 } else {
1819 None
1820 };
1821
1822 match integration
1823 .submit_entry(
1824 &stack_id,
1825 &entry_to_submit.id,
1826 entry_title,
1827 entry_description,
1828 draft,
1829 )
1830 .await
1831 {
1832 Ok(pr) => {
1833 submitted_count += 1;
1834 Output::success(format!("PR #{}", pr.id));
1835 if let Some(url) = pr.web_url() {
1836 Output::sub_item(format!(
1837 "{} → {}",
1838 pr.from_ref.display_id, pr.to_ref.display_id
1839 ));
1840 Output::sub_item(format!("URL: {url}"));
1841 pr_urls.push(url); }
1843 }
1844 Err(e) => {
1845 Output::error("Failed");
1846 let clean_error = if e.to_string().contains("non-fast-forward") {
1848 "Branch has diverged (was rebased after initial submission). Update to v0.1.41+ to auto force-push.".to_string()
1849 } else if e.to_string().contains("authentication") {
1850 "Authentication failed. Check your Bitbucket credentials.".to_string()
1851 } else {
1852 e.to_string()
1854 .lines()
1855 .filter(|l| !l.trim().starts_with("hint:") && !l.trim().is_empty())
1856 .take(1)
1857 .collect::<Vec<_>>()
1858 .join(" ")
1859 .trim()
1860 .to_string()
1861 };
1862 Output::sub_item(format!("Error: {}", clean_error));
1863 failed_entries.push((*entry_num, clean_error));
1864 }
1865 }
1866 }
1867
1868 println!();
1869
1870 let has_any_prs = active_stack
1872 .entries
1873 .iter()
1874 .any(|e| e.pull_request_id.is_some());
1875 if has_any_prs && submitted_count > 0 {
1876 match integration.update_all_pr_descriptions(&stack_id).await {
1877 Ok(updated_prs) => {
1878 if !updated_prs.is_empty() {
1879 Output::sub_item(format!(
1880 "Updated {} PR description{} with stack hierarchy",
1881 updated_prs.len(),
1882 if updated_prs.len() == 1 { "" } else { "s" }
1883 ));
1884 }
1885 }
1886 Err(e) => {
1887 let error_msg = e.to_string();
1890 if !error_msg.contains("409") && !error_msg.contains("out-of-date") {
1891 let clean_error = error_msg.lines().next().unwrap_or("Unknown error").trim();
1893 Output::warning(format!(
1894 "Could not update some PR descriptions: {}",
1895 clean_error
1896 ));
1897 Output::sub_item(
1898 "PRs were created successfully - descriptions can be updated manually",
1899 );
1900 }
1901 }
1902 }
1903 }
1904
1905 if failed_entries.is_empty() {
1907 Output::success(format!(
1908 "{} {} submitted successfully!",
1909 submitted_count,
1910 if submitted_count == 1 {
1911 "entry"
1912 } else {
1913 "entries"
1914 }
1915 ));
1916 } else {
1917 println!();
1918 Output::section("Submission Summary");
1919 Output::success(format!("Successful: {submitted_count}"));
1920 Output::error(format!("Failed: {}", failed_entries.len()));
1921
1922 if !failed_entries.is_empty() {
1923 println!();
1924 Output::tip("Retry failed entries:");
1925 for (entry_num, _) in &failed_entries {
1926 Output::bullet(format!("ca stack submit {entry_num}"));
1927 }
1928 }
1929 }
1930
1931 if open && !pr_urls.is_empty() {
1933 println!();
1934 for url in &pr_urls {
1935 if let Err(e) = open::that(url) {
1936 Output::warning(format!("Could not open browser: {}", e));
1937 Output::tip(format!("Open manually: {}", url));
1938 }
1939 }
1940 }
1941
1942 Ok(())
1943}
1944
1945async fn check_stack_status(name: Option<String>) -> Result<()> {
1946 let current_dir = env::current_dir()
1947 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1948
1949 let repo_root = find_repository_root(¤t_dir)
1950 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1951
1952 let stack_manager = StackManager::new(&repo_root)?;
1953
1954 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1956 let config_path = config_dir.join("config.json");
1957 let settings = crate::config::Settings::load_from_file(&config_path)?;
1958
1959 let cascade_config = crate::config::CascadeConfig {
1961 bitbucket: Some(settings.bitbucket.clone()),
1962 git: settings.git.clone(),
1963 auth: crate::config::AuthConfig::default(),
1964 cascade: settings.cascade.clone(),
1965 };
1966
1967 let stack = if let Some(name) = name {
1969 stack_manager
1970 .get_stack_by_name(&name)
1971 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?
1972 } else {
1973 stack_manager.get_active_stack().ok_or_else(|| {
1974 CascadeError::config("No active stack. Use 'ca stack list' to see available stacks")
1975 })?
1976 };
1977 let stack_id = stack.id;
1978
1979 Output::section(format!("Stack: {}", stack.name));
1980 Output::sub_item(format!("ID: {}", stack.id));
1981 Output::sub_item(format!("Base: {}", stack.base_branch));
1982
1983 if let Some(description) = &stack.description {
1984 Output::sub_item(format!("Description: {description}"));
1985 }
1986
1987 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1989
1990 match integration.check_stack_status(&stack_id).await {
1992 Ok(status) => {
1993 Output::section("Pull Request Status");
1994 Output::sub_item(format!("Total entries: {}", status.total_entries));
1995 Output::sub_item(format!("Submitted: {}", status.submitted_entries));
1996 Output::sub_item(format!("Open PRs: {}", status.open_prs));
1997 Output::sub_item(format!("Merged PRs: {}", status.merged_prs));
1998 Output::sub_item(format!("Declined PRs: {}", status.declined_prs));
1999 Output::sub_item(format!(
2000 "Completion: {:.1}%",
2001 status.completion_percentage()
2002 ));
2003
2004 if !status.pull_requests.is_empty() {
2005 Output::section("Pull Requests");
2006 for pr in &status.pull_requests {
2007 let state_icon = match pr.state {
2008 crate::bitbucket::PullRequestState::Open => "🔄",
2009 crate::bitbucket::PullRequestState::Merged => "✅",
2010 crate::bitbucket::PullRequestState::Declined => "❌",
2011 };
2012 Output::bullet(format!(
2013 "{} PR #{}: {} ({} -> {})",
2014 state_icon, pr.id, pr.title, pr.from_ref.display_id, pr.to_ref.display_id
2015 ));
2016 if let Some(url) = pr.web_url() {
2017 Output::sub_item(format!("URL: {url}"));
2018 }
2019 }
2020 }
2021 }
2022 Err(e) => {
2023 tracing::debug!("Failed to check stack status: {}", e);
2024 return Err(e);
2025 }
2026 }
2027
2028 Ok(())
2029}
2030
2031async fn list_pull_requests(state: Option<String>, verbose: bool) -> Result<()> {
2032 let current_dir = env::current_dir()
2033 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2034
2035 let repo_root = find_repository_root(¤t_dir)
2036 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2037
2038 let stack_manager = StackManager::new(&repo_root)?;
2039
2040 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2042 let config_path = config_dir.join("config.json");
2043 let settings = crate::config::Settings::load_from_file(&config_path)?;
2044
2045 let cascade_config = crate::config::CascadeConfig {
2047 bitbucket: Some(settings.bitbucket.clone()),
2048 git: settings.git.clone(),
2049 auth: crate::config::AuthConfig::default(),
2050 cascade: settings.cascade.clone(),
2051 };
2052
2053 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
2055
2056 let pr_state = if let Some(state_str) = state {
2058 match state_str.to_lowercase().as_str() {
2059 "open" => Some(crate::bitbucket::PullRequestState::Open),
2060 "merged" => Some(crate::bitbucket::PullRequestState::Merged),
2061 "declined" => Some(crate::bitbucket::PullRequestState::Declined),
2062 _ => {
2063 return Err(CascadeError::config(format!(
2064 "Invalid state '{state_str}'. Use: open, merged, declined"
2065 )))
2066 }
2067 }
2068 } else {
2069 None
2070 };
2071
2072 match integration.list_pull_requests(pr_state).await {
2074 Ok(pr_page) => {
2075 if pr_page.values.is_empty() {
2076 Output::info("No pull requests found.");
2077 return Ok(());
2078 }
2079
2080 println!("Pull Requests ({} total):", pr_page.values.len());
2081 for pr in &pr_page.values {
2082 let state_icon = match pr.state {
2083 crate::bitbucket::PullRequestState::Open => "○",
2084 crate::bitbucket::PullRequestState::Merged => "✓",
2085 crate::bitbucket::PullRequestState::Declined => "✗",
2086 };
2087 println!(" {} PR #{}: {}", state_icon, pr.id, pr.title);
2088 if verbose {
2089 println!(
2090 " From: {} -> {}",
2091 pr.from_ref.display_id, pr.to_ref.display_id
2092 );
2093 println!(
2094 " Author: {}",
2095 pr.author
2096 .user
2097 .display_name
2098 .as_deref()
2099 .unwrap_or(&pr.author.user.name)
2100 );
2101 if let Some(url) = pr.web_url() {
2102 println!(" URL: {url}");
2103 }
2104 if let Some(desc) = &pr.description {
2105 if !desc.is_empty() {
2106 println!(" Description: {desc}");
2107 }
2108 }
2109 println!();
2110 }
2111 }
2112
2113 if !verbose {
2114 println!("\nUse --verbose for more details");
2115 }
2116 }
2117 Err(e) => {
2118 warn!("Failed to list pull requests: {}", e);
2119 return Err(e);
2120 }
2121 }
2122
2123 Ok(())
2124}
2125
2126async fn check_stack(_force: bool) -> Result<()> {
2127 let current_dir = env::current_dir()
2128 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2129
2130 let repo_root = find_repository_root(¤t_dir)
2131 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2132
2133 let mut manager = StackManager::new(&repo_root)?;
2134
2135 let active_stack = manager
2136 .get_active_stack()
2137 .ok_or_else(|| CascadeError::config("No active stack"))?;
2138 let stack_id = active_stack.id;
2139
2140 manager.sync_stack(&stack_id)?;
2141
2142 Output::success("Stack check completed successfully");
2143
2144 Ok(())
2145}
2146
2147pub async fn continue_sync() -> Result<()> {
2148 let current_dir = env::current_dir()
2149 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2150
2151 let repo_root = find_repository_root(¤t_dir)?;
2152
2153 Output::section("Continuing sync from where it left off");
2154 println!();
2155
2156 let cherry_pick_head = repo_root.join(".git").join("CHERRY_PICK_HEAD");
2158 if !cherry_pick_head.exists() {
2159 return Err(CascadeError::config(
2160 "No in-progress cherry-pick found. Nothing to continue.\n\n\
2161 Use 'ca sync' to start a new sync."
2162 .to_string(),
2163 ));
2164 }
2165
2166 Output::info("Staging all resolved files");
2167
2168 std::process::Command::new("git")
2170 .args(["add", "-A"])
2171 .current_dir(&repo_root)
2172 .output()
2173 .map_err(CascadeError::Io)?;
2174
2175 let sync_state = crate::stack::SyncState::load(&repo_root).ok();
2176
2177 Output::info("Continuing cherry-pick");
2178
2179 let continue_output = std::process::Command::new("git")
2181 .args(["cherry-pick", "--continue"])
2182 .current_dir(&repo_root)
2183 .output()
2184 .map_err(CascadeError::Io)?;
2185
2186 if !continue_output.status.success() {
2187 let stderr = String::from_utf8_lossy(&continue_output.stderr);
2188 return Err(CascadeError::Branch(format!(
2189 "Failed to continue cherry-pick: {}\n\n\
2190 Make sure all conflicts are resolved.",
2191 stderr
2192 )));
2193 }
2194
2195 Output::success("Cherry-pick continued successfully");
2196 println!();
2197
2198 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2205 let current_branch = git_repo.get_current_branch()?;
2206
2207 let stack_branch = if let Some(state) = &sync_state {
2208 if !state.current_entry_branch.is_empty() {
2209 if !state.current_temp_branch.is_empty() && current_branch != state.current_temp_branch
2210 {
2211 tracing::warn!(
2212 "Sync state temp branch '{}' differs from current branch '{}'",
2213 state.current_temp_branch,
2214 current_branch
2215 );
2216 }
2217 state.current_entry_branch.clone()
2218 } else if let Some(idx) = current_branch.rfind("-temp-") {
2219 current_branch[..idx].to_string()
2220 } else {
2221 return Err(CascadeError::config(format!(
2222 "Current branch '{}' doesn't appear to be a temp branch created by cascade.\n\
2223 Expected format: <branch>-temp-<timestamp>",
2224 current_branch
2225 )));
2226 }
2227 } else if let Some(idx) = current_branch.rfind("-temp-") {
2228 current_branch[..idx].to_string()
2229 } else {
2230 return Err(CascadeError::config(format!(
2231 "Current branch '{}' doesn't appear to be a temp branch created by cascade.\n\
2232 Expected format: <branch>-temp-<timestamp>",
2233 current_branch
2234 )));
2235 };
2236
2237 Output::info(format!("Updating stack branch: {}", stack_branch));
2238
2239 let output = std::process::Command::new("git")
2241 .args(["branch", "-f", &stack_branch])
2242 .current_dir(&repo_root)
2243 .output()
2244 .map_err(CascadeError::Io)?;
2245
2246 if !output.status.success() {
2247 let stderr = String::from_utf8_lossy(&output.stderr);
2248 return Err(CascadeError::validation(format!(
2249 "Failed to update branch '{}': {}\n\n\
2250 This could be due to:\n\
2251 • Git lock file (.git/index.lock or .git/refs/heads/{}.lock)\n\
2252 • Insufficient permissions\n\
2253 • Branch is checked out in another worktree\n\n\
2254 Recovery:\n\
2255 1. Check for lock files: find .git -name '*.lock'\n\
2256 2. Remove stale lock files if safe\n\
2257 3. Run 'ca sync' to retry",
2258 stack_branch,
2259 stderr.trim(),
2260 stack_branch
2261 )));
2262 }
2263
2264 let mut manager = crate::stack::StackManager::new(&repo_root)?;
2266
2267 let new_commit_hash = git_repo.get_branch_head(&stack_branch)?;
2270
2271 let (stack_id, entry_id_opt, working_branch) = if let Some(state) = &sync_state {
2272 let stack_uuid = Uuid::parse_str(&state.stack_id)
2273 .map_err(|e| CascadeError::config(format!("Invalid stack ID in sync state: {e}")))?;
2274
2275 let stack_snapshot = manager
2276 .get_stack(&stack_uuid)
2277 .cloned()
2278 .ok_or_else(|| CascadeError::config("Stack not found in sync state".to_string()))?;
2279
2280 let working_branch = stack_snapshot
2281 .working_branch
2282 .clone()
2283 .ok_or_else(|| CascadeError::config("Stack has no working branch".to_string()))?;
2284
2285 let entry_id = if !state.current_entry_id.is_empty() {
2286 Uuid::parse_str(&state.current_entry_id).ok()
2287 } else {
2288 stack_snapshot
2289 .entries
2290 .iter()
2291 .find(|e| e.branch == stack_branch)
2292 .map(|e| e.id)
2293 };
2294
2295 (stack_uuid, entry_id, working_branch)
2296 } else {
2297 let active_stack = manager
2298 .get_active_stack()
2299 .ok_or_else(|| CascadeError::config("No active stack found"))?;
2300
2301 let entry_id = active_stack
2302 .entries
2303 .iter()
2304 .find(|e| e.branch == stack_branch)
2305 .map(|e| e.id);
2306
2307 let working_branch = active_stack
2308 .working_branch
2309 .as_ref()
2310 .ok_or_else(|| CascadeError::config("Active stack has no working branch"))?
2311 .clone();
2312
2313 (active_stack.id, entry_id, working_branch)
2314 };
2315
2316 let entry_id = entry_id_opt.ok_or_else(|| {
2318 CascadeError::config(format!(
2319 "Could not find stack entry for branch '{}'",
2320 stack_branch
2321 ))
2322 })?;
2323
2324 let stack = manager
2325 .get_stack_mut(&stack_id)
2326 .ok_or_else(|| CascadeError::config("Could not get mutable stack reference"))?;
2327
2328 stack
2329 .update_entry_commit_hash(&entry_id, new_commit_hash.clone())
2330 .map_err(CascadeError::config)?;
2331
2332 manager.save_to_disk()?;
2333
2334 let top_commit = {
2336 let active_stack = manager
2337 .get_active_stack()
2338 .ok_or_else(|| CascadeError::config("No active stack found"))?;
2339
2340 if let Some(last_entry) = active_stack.entries.last() {
2341 git_repo.get_branch_head(&last_entry.branch)?
2342 } else {
2343 new_commit_hash.clone()
2344 }
2345 };
2346
2347 Output::info(format!(
2348 "Checking out to working branch: {}",
2349 working_branch
2350 ));
2351
2352 git_repo.checkout_branch_unsafe(&working_branch)?;
2354
2355 if let Ok(working_head) = git_repo.get_branch_head(&working_branch) {
2364 if working_head != top_commit {
2365 git_repo.update_branch_to_commit(&working_branch, &top_commit)?;
2366
2367 git_repo.reset_to_head()?;
2369 }
2370 }
2371
2372 if sync_state.is_some() {
2373 crate::stack::SyncState::delete(&repo_root)?;
2374 }
2375
2376 println!();
2377 Output::info("Resuming sync to complete the rebase...");
2378 println!();
2379
2380 sync_stack(false, false, false).await
2382}
2383
2384pub async fn abort_sync() -> Result<()> {
2385 let current_dir = env::current_dir()
2386 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2387
2388 let repo_root = find_repository_root(¤t_dir)?;
2389
2390 Output::section("Aborting sync");
2391 println!();
2392
2393 let cherry_pick_head = repo_root.join(".git").join("CHERRY_PICK_HEAD");
2395 if !cherry_pick_head.exists() {
2396 return Err(CascadeError::config(
2397 "No in-progress cherry-pick found. Nothing to abort.\n\n\
2398 The sync may have already completed or been aborted."
2399 .to_string(),
2400 ));
2401 }
2402
2403 Output::info("Aborting cherry-pick");
2404
2405 let abort_output = std::process::Command::new("git")
2407 .args(["cherry-pick", "--abort"])
2408 .env("CASCADE_SKIP_HOOKS", "1")
2409 .current_dir(&repo_root)
2410 .output()
2411 .map_err(CascadeError::Io)?;
2412
2413 if !abort_output.status.success() {
2414 let stderr = String::from_utf8_lossy(&abort_output.stderr);
2415 return Err(CascadeError::Branch(format!(
2416 "Failed to abort cherry-pick: {}",
2417 stderr
2418 )));
2419 }
2420
2421 Output::success("Cherry-pick aborted");
2422
2423 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2425
2426 if let Ok(state) = crate::stack::SyncState::load(&repo_root) {
2427 println!();
2428 Output::info("Cleaning up temporary branches");
2429
2430 for temp_branch in &state.temp_branches {
2432 if let Err(e) = git_repo.delete_branch_unsafe(temp_branch) {
2433 tracing::warn!("Could not delete temp branch '{}': {}", temp_branch, e);
2434 }
2435 }
2436
2437 Output::info(format!(
2439 "Returning to original branch: {}",
2440 state.original_branch
2441 ));
2442 if let Err(e) = git_repo.checkout_branch_unsafe(&state.original_branch) {
2443 tracing::warn!("Could not checkout original branch: {}", e);
2445 if let Err(e2) = git_repo.checkout_branch_unsafe(&state.target_base) {
2446 tracing::warn!("Could not checkout base branch: {}", e2);
2447 }
2448 }
2449
2450 crate::stack::SyncState::delete(&repo_root)?;
2452 } else {
2453 let current_branch = git_repo.get_current_branch()?;
2455
2456 if let Some(idx) = current_branch.rfind("-temp-") {
2458 let original_branch = ¤t_branch[..idx];
2459 Output::info(format!("Returning to branch: {}", original_branch));
2460
2461 if let Err(e) = git_repo.checkout_branch_unsafe(original_branch) {
2462 tracing::warn!("Could not checkout original branch: {}", e);
2463 }
2464
2465 if let Err(e) = git_repo.delete_branch_unsafe(¤t_branch) {
2467 tracing::warn!("Could not delete temp branch: {}", e);
2468 }
2469 }
2470 }
2471
2472 println!();
2473 Output::success("Sync aborted");
2474 println!();
2475 Output::tip("You can start a fresh sync with: ca sync");
2476
2477 Ok(())
2478}
2479
2480async fn sync_stack(force: bool, cleanup: bool, interactive: bool) -> Result<()> {
2481 let current_dir = env::current_dir()
2482 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2483
2484 let repo_root = find_repository_root(¤t_dir)
2485 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2486
2487 let mut stack_manager = StackManager::new(&repo_root)?;
2488
2489 if stack_manager.is_in_edit_mode() {
2492 debug!("Exiting edit mode before sync (commit SHAs will change)");
2493 stack_manager.exit_edit_mode()?;
2494 }
2495
2496 let git_repo = GitRepository::open(&repo_root)?;
2497
2498 if git_repo.is_dirty()? {
2499 return Err(CascadeError::branch(
2500 "Working tree has uncommitted changes. Commit or stash them before running 'ca sync'."
2501 .to_string(),
2502 ));
2503 }
2504
2505 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2507 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2508 })?;
2509
2510 let base_branch = active_stack.base_branch.clone();
2511 let _stack_name = active_stack.name.clone();
2512
2513 let original_branch = git_repo.get_current_branch().ok();
2515
2516 match git_repo.checkout_branch_silent(&base_branch) {
2520 Ok(_) => {
2521 match git_repo.pull(&base_branch) {
2522 Ok(_) => {
2523 }
2525 Err(e) => {
2526 if force {
2527 Output::warning(format!("Pull failed: {e} (continuing due to --force)"));
2528 } else {
2529 Output::error(format!("Failed to pull latest changes: {e}"));
2530 Output::tip("Use --force to skip pull and continue with rebase");
2531 return Err(CascadeError::branch(format!(
2532 "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
2533 )));
2534 }
2535 }
2536 }
2537 }
2538 Err(e) => {
2539 if force {
2540 Output::warning(format!(
2541 "Failed to checkout '{base_branch}': {e} (continuing due to --force)"
2542 ));
2543 } else {
2544 Output::error(format!(
2545 "Failed to checkout base branch '{base_branch}': {e}"
2546 ));
2547 Output::tip("Use --force to bypass checkout issues and continue anyway");
2548 return Err(CascadeError::branch(format!(
2549 "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
2550 )));
2551 }
2552 }
2553 }
2554
2555 let mut updated_stack_manager = StackManager::new(&repo_root)?;
2558 let stack_id = active_stack.id;
2559
2560 if let Some(stack) = updated_stack_manager.get_stack_mut(&stack_id) {
2563 let mut updates = Vec::new();
2564 for entry in &stack.entries {
2565 if let Ok(current_commit) = git_repo.get_branch_head(&entry.branch) {
2566 if entry.commit_hash != current_commit {
2567 let is_safe_descendant = match git_repo.commit_exists(&entry.commit_hash) {
2568 Ok(true) => {
2569 match git_repo.is_descendant_of(¤t_commit, &entry.commit_hash) {
2570 Ok(result) => result,
2571 Err(e) => {
2572 warn!(
2573 "Cannot verify ancestry for '{}': {} - treating as unsafe to prevent potential data loss",
2574 entry.branch, e
2575 );
2576 false
2577 }
2578 }
2579 }
2580 Ok(false) => {
2581 debug!(
2582 "Recorded commit {} for '{}' no longer exists in repository",
2583 &entry.commit_hash[..8],
2584 entry.branch
2585 );
2586 false
2587 }
2588 Err(e) => {
2589 warn!(
2590 "Cannot verify commit existence for '{}': {} - treating as unsafe to prevent potential data loss",
2591 entry.branch, e
2592 );
2593 false
2594 }
2595 };
2596
2597 if is_safe_descendant {
2598 debug!(
2599 "Reconciling entry '{}': updating hash from {} to {} (current branch HEAD)",
2600 entry.branch,
2601 &entry.commit_hash[..8],
2602 ¤t_commit[..8]
2603 );
2604 updates.push((entry.id, current_commit));
2605 } else {
2606 warn!(
2607 "Skipped automatic reconciliation for entry '{}' because local HEAD ({}) does not descend from recorded commit ({})",
2608 entry.branch,
2609 ¤t_commit[..8],
2610 &entry.commit_hash[..8]
2611 );
2612 }
2615 }
2616 }
2617 }
2618
2619 for (entry_id, new_hash) in updates {
2621 stack
2622 .update_entry_commit_hash(&entry_id, new_hash)
2623 .map_err(CascadeError::config)?;
2624 }
2625
2626 updated_stack_manager.save_to_disk()?;
2628 }
2629
2630 match updated_stack_manager.sync_stack(&stack_id) {
2631 Ok(_) => {
2632 if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
2634 if updated_stack.entries.is_empty() {
2636 println!(); Output::info("Stack has no entries yet");
2638 Output::tip("Use 'ca push' to add commits to this stack");
2639 return Ok(());
2640 }
2641
2642 match &updated_stack.status {
2643 crate::stack::StackStatus::NeedsSync => {
2644 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2646 let config_path = config_dir.join("config.json");
2647 let settings = crate::config::Settings::load_from_file(&config_path)?;
2648
2649 let cascade_config = crate::config::CascadeConfig {
2650 bitbucket: Some(settings.bitbucket.clone()),
2651 git: settings.git.clone(),
2652 auth: crate::config::AuthConfig::default(),
2653 cascade: settings.cascade.clone(),
2654 };
2655
2656 println!(); let options = crate::stack::RebaseOptions {
2661 strategy: crate::stack::RebaseStrategy::ForcePush,
2662 interactive,
2663 target_base: Some(base_branch.clone()),
2664 preserve_merges: true,
2665 auto_resolve: !interactive, max_retries: 3,
2667 skip_pull: Some(true), original_working_branch: original_branch.clone(), };
2670
2671 let mut rebase_manager = crate::stack::RebaseManager::new(
2672 updated_stack_manager,
2673 git_repo,
2674 options,
2675 );
2676
2677 let rebase_result = rebase_manager.rebase_stack(&stack_id);
2679
2680 match rebase_result {
2681 Ok(result) => {
2682 if !result.branch_mapping.is_empty() {
2683 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2685 let integration_stack_manager =
2687 StackManager::new(&repo_root)?;
2688 let mut integration =
2689 crate::bitbucket::BitbucketIntegration::new(
2690 integration_stack_manager,
2691 cascade_config,
2692 )?;
2693
2694 let pr_result = integration
2696 .update_prs_after_rebase(
2697 &stack_id,
2698 &result.branch_mapping,
2699 )
2700 .await;
2701
2702 match pr_result {
2703 Ok(updated_prs) => {
2704 if !updated_prs.is_empty() {
2705 Output::success(format!(
2706 "Updated {} pull request{}",
2707 updated_prs.len(),
2708 if updated_prs.len() == 1 {
2709 ""
2710 } else {
2711 "s"
2712 }
2713 ));
2714 }
2715 }
2716 Err(e) => {
2717 Output::warning(format!(
2718 "Failed to update pull requests: {e}"
2719 ));
2720 }
2721 }
2722 }
2723 }
2724 }
2725 Err(e) => {
2726 return Err(e);
2728 }
2729 }
2730 }
2731 crate::stack::StackStatus::Clean => {
2732 }
2734 other => {
2735 Output::info(format!("Stack status: {other:?}"));
2737 }
2738 }
2739 }
2740 }
2741 Err(e) => {
2742 if force {
2743 Output::warning(format!(
2744 "Failed to check stack status: {e} (continuing due to --force)"
2745 ));
2746 } else {
2747 return Err(e);
2748 }
2749 }
2750 }
2751
2752 if cleanup {
2754 let git_repo_for_cleanup = GitRepository::open(&repo_root)?;
2755 match perform_simple_cleanup(&stack_manager, &git_repo_for_cleanup, false).await {
2756 Ok(result) => {
2757 if result.total_candidates > 0 {
2758 Output::section("Cleanup Summary");
2759 if !result.cleaned_branches.is_empty() {
2760 Output::success(format!(
2761 "Cleaned up {} merged branches",
2762 result.cleaned_branches.len()
2763 ));
2764 for branch in &result.cleaned_branches {
2765 Output::sub_item(format!("🗑️ Deleted: {branch}"));
2766 }
2767 }
2768 if !result.skipped_branches.is_empty() {
2769 Output::sub_item(format!(
2770 "Skipped {} branches",
2771 result.skipped_branches.len()
2772 ));
2773 }
2774 if !result.failed_branches.is_empty() {
2775 for (branch, error) in &result.failed_branches {
2776 Output::warning(format!("Failed to clean up {branch}: {error}"));
2777 }
2778 }
2779 }
2780 }
2781 Err(e) => {
2782 Output::warning(format!("Branch cleanup failed: {e}"));
2783 }
2784 }
2785 }
2786
2787 Output::success("Sync completed successfully!");
2795
2796 Ok(())
2797}
2798
2799async fn rebase_stack(
2800 interactive: bool,
2801 onto: Option<String>,
2802 strategy: Option<RebaseStrategyArg>,
2803) -> Result<()> {
2804 let current_dir = env::current_dir()
2805 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2806
2807 let repo_root = find_repository_root(¤t_dir)
2808 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2809
2810 let stack_manager = StackManager::new(&repo_root)?;
2811 let git_repo = GitRepository::open(&repo_root)?;
2812
2813 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2815 let config_path = config_dir.join("config.json");
2816 let settings = crate::config::Settings::load_from_file(&config_path)?;
2817
2818 let cascade_config = crate::config::CascadeConfig {
2820 bitbucket: Some(settings.bitbucket.clone()),
2821 git: settings.git.clone(),
2822 auth: crate::config::AuthConfig::default(),
2823 cascade: settings.cascade.clone(),
2824 };
2825
2826 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2828 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2829 })?;
2830 let stack_id = active_stack.id;
2831
2832 let active_stack = stack_manager
2833 .get_stack(&stack_id)
2834 .ok_or_else(|| CascadeError::config("Active stack not found"))?
2835 .clone();
2836
2837 if active_stack.entries.is_empty() {
2838 Output::info("Stack is empty. Nothing to rebase.");
2839 return Ok(());
2840 }
2841
2842 let rebase_strategy = if let Some(cli_strategy) = strategy {
2844 match cli_strategy {
2845 RebaseStrategyArg::ForcePush => crate::stack::RebaseStrategy::ForcePush,
2846 RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
2847 }
2848 } else {
2849 crate::stack::RebaseStrategy::ForcePush
2851 };
2852
2853 let original_branch = git_repo.get_current_branch().ok();
2855
2856 debug!(" Strategy: {:?}", rebase_strategy);
2857 debug!(" Interactive: {}", interactive);
2858 debug!(" Target base: {:?}", onto);
2859 debug!(" Entries: {}", active_stack.entries.len());
2860
2861 println!(); let rebase_spinner = crate::utils::spinner::Spinner::new_with_output_below(format!(
2865 "Rebasing stack: {}",
2866 active_stack.name
2867 ));
2868
2869 let options = crate::stack::RebaseOptions {
2871 strategy: rebase_strategy.clone(),
2872 interactive,
2873 target_base: onto,
2874 preserve_merges: true,
2875 auto_resolve: !interactive, max_retries: 3,
2877 skip_pull: None, original_working_branch: original_branch,
2879 };
2880
2881 let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2883
2884 if rebase_manager.is_rebase_in_progress() {
2885 Output::warning("Rebase already in progress!");
2886 Output::tip("Use 'git status' to check the current state");
2887 Output::next_steps(&[
2888 "Run 'ca stack continue-rebase' to continue",
2889 "Run 'ca stack abort-rebase' to abort",
2890 ]);
2891 rebase_spinner.stop();
2892 return Ok(());
2893 }
2894
2895 let rebase_result = rebase_manager.rebase_stack(&stack_id);
2897
2898 rebase_spinner.stop();
2900 println!(); match rebase_result {
2903 Ok(result) => {
2904 Output::success("Rebase completed!");
2905 Output::sub_item(result.get_summary());
2906
2907 if result.has_conflicts() {
2908 Output::warning(format!(
2909 "{} conflicts were resolved",
2910 result.conflicts.len()
2911 ));
2912 for conflict in &result.conflicts {
2913 Output::bullet(&conflict[..8.min(conflict.len())]);
2914 }
2915 }
2916
2917 if !result.branch_mapping.is_empty() {
2918 Output::section("Branch mapping");
2919 for (old, new) in &result.branch_mapping {
2920 Output::bullet(format!("{old} -> {new}"));
2921 }
2922
2923 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2925 let integration_stack_manager = StackManager::new(&repo_root)?;
2927 let mut integration = BitbucketIntegration::new(
2928 integration_stack_manager,
2929 cascade_config.clone(),
2930 )?;
2931
2932 match integration
2933 .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2934 .await
2935 {
2936 Ok(updated_prs) => {
2937 if !updated_prs.is_empty() {
2938 println!(" 🔄 Preserved pull request history:");
2939 for pr_update in updated_prs {
2940 println!(" ✅ {pr_update}");
2941 }
2942 }
2943 }
2944 Err(e) => {
2945 Output::warning(format!("Failed to update pull requests: {e}"));
2946 Output::sub_item("You may need to manually update PRs in Bitbucket");
2947 }
2948 }
2949 }
2950 }
2951
2952 Output::success(format!(
2953 "{} commits successfully rebased",
2954 result.success_count()
2955 ));
2956
2957 if matches!(rebase_strategy, crate::stack::RebaseStrategy::ForcePush) {
2959 println!();
2960 Output::section("Next steps");
2961 if !result.branch_mapping.is_empty() {
2962 Output::numbered_item(1, "Branches have been rebased and force-pushed");
2963 Output::numbered_item(
2964 2,
2965 "Pull requests updated automatically (history preserved)",
2966 );
2967 Output::numbered_item(3, "Review the updated PRs in Bitbucket");
2968 Output::numbered_item(4, "Test your changes");
2969 } else {
2970 println!(" 1. Review the rebased stack");
2971 println!(" 2. Test your changes");
2972 println!(" 3. Submit new pull requests with 'ca stack submit'");
2973 }
2974 }
2975 }
2976 Err(e) => {
2977 warn!("❌ Rebase failed: {}", e);
2978 Output::tip(" Tips for resolving rebase issues:");
2979 println!(" - Check for uncommitted changes with 'git status'");
2980 println!(" - Ensure base branch is up to date");
2981 println!(" - Try interactive mode: 'ca stack rebase --interactive'");
2982 return Err(e);
2983 }
2984 }
2985
2986 Ok(())
2987}
2988
2989pub async fn continue_rebase() -> Result<()> {
2990 let current_dir = env::current_dir()
2991 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2992
2993 let repo_root = find_repository_root(¤t_dir)
2994 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2995
2996 let stack_manager = StackManager::new(&repo_root)?;
2997 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2998 let options = crate::stack::RebaseOptions::default();
2999 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3000
3001 if !rebase_manager.is_rebase_in_progress() {
3002 Output::info(" No rebase in progress");
3003 return Ok(());
3004 }
3005
3006 println!(" Continuing rebase...");
3007 match rebase_manager.continue_rebase() {
3008 Ok(_) => {
3009 Output::success(" Rebase continued successfully");
3010 println!(" Check 'ca stack rebase-status' for current state");
3011 }
3012 Err(e) => {
3013 warn!("❌ Failed to continue rebase: {}", e);
3014 Output::tip(" You may need to resolve conflicts first:");
3015 println!(" 1. Edit conflicted files");
3016 println!(" 2. Stage resolved files with 'git add'");
3017 println!(" 3. Run 'ca stack continue-rebase' again");
3018 }
3019 }
3020
3021 Ok(())
3022}
3023
3024pub async fn abort_rebase() -> Result<()> {
3025 let current_dir = env::current_dir()
3026 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3027
3028 let repo_root = find_repository_root(¤t_dir)
3029 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3030
3031 let stack_manager = StackManager::new(&repo_root)?;
3032 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3033 let options = crate::stack::RebaseOptions::default();
3034 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3035
3036 if !rebase_manager.is_rebase_in_progress() {
3037 Output::info(" No rebase in progress");
3038 return Ok(());
3039 }
3040
3041 Output::warning("Aborting rebase...");
3042 match rebase_manager.abort_rebase() {
3043 Ok(_) => {
3044 Output::success(" Rebase aborted successfully");
3045 println!(" Repository restored to pre-rebase state");
3046 }
3047 Err(e) => {
3048 warn!("❌ Failed to abort rebase: {}", e);
3049 println!("⚠️ You may need to manually clean up the repository state");
3050 }
3051 }
3052
3053 Ok(())
3054}
3055
3056async fn rebase_status() -> Result<()> {
3057 let current_dir = env::current_dir()
3058 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3059
3060 let repo_root = find_repository_root(¤t_dir)
3061 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3062
3063 let stack_manager = StackManager::new(&repo_root)?;
3064 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3065
3066 println!("Rebase Status");
3067
3068 let git_dir = current_dir.join(".git");
3070 let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
3071 || git_dir.join("rebase-merge").exists()
3072 || git_dir.join("rebase-apply").exists();
3073
3074 if rebase_in_progress {
3075 println!(" Status: 🔄 Rebase in progress");
3076 println!(
3077 "
3078📝 Actions available:"
3079 );
3080 println!(" - 'ca stack continue-rebase' to continue");
3081 println!(" - 'ca stack abort-rebase' to abort");
3082 println!(" - 'git status' to see conflicted files");
3083
3084 match git_repo.get_status() {
3086 Ok(statuses) => {
3087 let mut conflicts = Vec::new();
3088 for status in statuses.iter() {
3089 if status.status().contains(git2::Status::CONFLICTED) {
3090 if let Some(path) = status.path() {
3091 conflicts.push(path.to_string());
3092 }
3093 }
3094 }
3095
3096 if !conflicts.is_empty() {
3097 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
3098 for conflict in conflicts {
3099 println!(" - {conflict}");
3100 }
3101 println!(
3102 "
3103💡 To resolve conflicts:"
3104 );
3105 println!(" 1. Edit the conflicted files");
3106 println!(" 2. Stage resolved files: git add <file>");
3107 println!(" 3. Continue: ca stack continue-rebase");
3108 }
3109 }
3110 Err(e) => {
3111 warn!("Failed to get git status: {}", e);
3112 }
3113 }
3114 } else {
3115 println!(" Status: ✅ No rebase in progress");
3116
3117 if let Some(active_stack) = stack_manager.get_active_stack() {
3119 println!(" Active stack: {}", active_stack.name);
3120 println!(" Entries: {}", active_stack.entries.len());
3121 println!(" Base branch: {}", active_stack.base_branch);
3122 }
3123 }
3124
3125 Ok(())
3126}
3127
3128async fn delete_stack(name: String, force: bool) -> Result<()> {
3129 let current_dir = env::current_dir()
3130 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3131
3132 let repo_root = find_repository_root(¤t_dir)
3133 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3134
3135 let mut manager = StackManager::new(&repo_root)?;
3136
3137 let stack = manager
3138 .get_stack_by_name(&name)
3139 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
3140 let stack_id = stack.id;
3141
3142 if !force && !stack.entries.is_empty() {
3143 return Err(CascadeError::config(format!(
3144 "Stack '{}' has {} entries. Use --force to delete anyway",
3145 name,
3146 stack.entries.len()
3147 )));
3148 }
3149
3150 let deleted = manager.delete_stack(&stack_id)?;
3151
3152 Output::success(format!("Deleted stack '{}'", deleted.name));
3153 if !deleted.entries.is_empty() {
3154 Output::warning(format!("{} entries were removed", deleted.entries.len()));
3155 }
3156
3157 Ok(())
3158}
3159
3160async fn validate_stack(name: Option<String>, fix_mode: Option<String>) -> Result<()> {
3161 let current_dir = env::current_dir()
3162 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3163
3164 let repo_root = find_repository_root(¤t_dir)
3165 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3166
3167 let mut manager = StackManager::new(&repo_root)?;
3168
3169 if let Some(name) = name {
3170 let stack = manager
3172 .get_stack_by_name(&name)
3173 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
3174
3175 let stack_id = stack.id;
3176
3177 match stack.validate() {
3179 Ok(_message) => {
3180 Output::success(format!("Stack '{}' structure validation passed", name));
3181 }
3182 Err(e) => {
3183 Output::error(format!(
3184 "Stack '{}' structure validation failed: {}",
3185 name, e
3186 ));
3187 return Err(CascadeError::config(e));
3188 }
3189 }
3190
3191 manager.handle_branch_modifications(&stack_id, fix_mode)?;
3193
3194 println!();
3195 Output::success(format!("Stack '{name}' validation completed"));
3196 Ok(())
3197 } else {
3198 Output::section("Validating all stacks");
3200 println!();
3201
3202 let all_stacks = manager.get_all_stacks();
3204 let stack_ids: Vec<uuid::Uuid> = all_stacks.iter().map(|s| s.id).collect();
3205
3206 if stack_ids.is_empty() {
3207 Output::info("No stacks found");
3208 return Ok(());
3209 }
3210
3211 let mut all_valid = true;
3212 for stack_id in stack_ids {
3213 let stack = manager.get_stack(&stack_id).unwrap();
3214 let stack_name = &stack.name;
3215
3216 println!("Checking stack '{stack_name}':");
3217
3218 match stack.validate() {
3220 Ok(message) => {
3221 Output::sub_item(format!("Structure: {message}"));
3222 }
3223 Err(e) => {
3224 Output::sub_item(format!("Structure: {e}"));
3225 all_valid = false;
3226 continue;
3227 }
3228 }
3229
3230 match manager.handle_branch_modifications(&stack_id, fix_mode.clone()) {
3232 Ok(_) => {
3233 Output::sub_item("Git integrity: OK");
3234 }
3235 Err(e) => {
3236 Output::sub_item(format!("Git integrity: {e}"));
3237 all_valid = false;
3238 }
3239 }
3240 println!();
3241 }
3242
3243 if all_valid {
3244 Output::success("All stacks passed validation");
3245 } else {
3246 Output::warning("Some stacks have validation issues");
3247 return Err(CascadeError::config("Stack validation failed".to_string()));
3248 }
3249
3250 Ok(())
3251 }
3252}
3253
3254#[allow(dead_code)]
3256fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
3257 let mut unpushed = Vec::new();
3258 let head_commit = repo.get_head_commit()?;
3259 let mut current_commit = head_commit;
3260
3261 loop {
3263 let commit_hash = current_commit.id().to_string();
3264 let already_in_stack = stack
3265 .entries
3266 .iter()
3267 .any(|entry| entry.commit_hash == commit_hash);
3268
3269 if already_in_stack {
3270 break;
3271 }
3272
3273 unpushed.push(commit_hash);
3274
3275 if let Some(parent) = current_commit.parents().next() {
3277 current_commit = parent;
3278 } else {
3279 break;
3280 }
3281 }
3282
3283 unpushed.reverse(); Ok(unpushed)
3285}
3286
3287pub async fn squash_commits(
3289 repo: &GitRepository,
3290 count: usize,
3291 since_ref: Option<String>,
3292) -> Result<()> {
3293 if count <= 1 {
3294 return Ok(()); }
3296
3297 let _current_branch = repo.get_current_branch()?;
3299
3300 let rebase_range = if let Some(ref since) = since_ref {
3302 since.clone()
3303 } else {
3304 format!("HEAD~{count}")
3305 };
3306
3307 println!(" Analyzing {count} commits to create smart squash message...");
3308
3309 let head_commit = repo.get_head_commit()?;
3311 let mut commits_to_squash = Vec::new();
3312 let mut current = head_commit;
3313
3314 for _ in 0..count {
3316 commits_to_squash.push(current.clone());
3317 if current.parent_count() > 0 {
3318 current = current.parent(0).map_err(CascadeError::Git)?;
3319 } else {
3320 break;
3321 }
3322 }
3323
3324 let smart_message = generate_squash_message(&commits_to_squash)?;
3326 println!(
3327 " Smart message: {}",
3328 smart_message.lines().next().unwrap_or("")
3329 );
3330
3331 let reset_target = if since_ref.is_some() {
3333 format!("{rebase_range}~1")
3335 } else {
3336 format!("HEAD~{count}")
3338 };
3339
3340 repo.reset_soft(&reset_target)?;
3342
3343 repo.stage_all()?;
3345
3346 let new_commit_hash = repo.commit(&smart_message)?;
3348
3349 println!(
3350 " Created squashed commit: {} ({})",
3351 &new_commit_hash[..8],
3352 smart_message.lines().next().unwrap_or("")
3353 );
3354 println!(" 💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
3355
3356 Ok(())
3357}
3358
3359pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
3361 if commits.is_empty() {
3362 return Ok("Squashed commits".to_string());
3363 }
3364
3365 let messages: Vec<String> = commits
3367 .iter()
3368 .map(|c| c.message().unwrap_or("").trim().to_string())
3369 .filter(|m| !m.is_empty())
3370 .collect();
3371
3372 if messages.is_empty() {
3373 return Ok("Squashed commits".to_string());
3374 }
3375
3376 if let Some(last_msg) = messages.first() {
3378 if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
3380 return Ok(last_msg
3381 .trim_start_matches("Final:")
3382 .trim_start_matches("final:")
3383 .trim()
3384 .to_string());
3385 }
3386 }
3387
3388 let wip_count = messages
3390 .iter()
3391 .filter(|m| {
3392 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
3393 })
3394 .count();
3395
3396 if wip_count > messages.len() / 2 {
3397 let non_wip: Vec<&String> = messages
3399 .iter()
3400 .filter(|m| {
3401 !m.to_lowercase().starts_with("wip")
3402 && !m.to_lowercase().contains("work in progress")
3403 })
3404 .collect();
3405
3406 if let Some(best_msg) = non_wip.first() {
3407 return Ok(best_msg.to_string());
3408 }
3409
3410 let feature = extract_feature_from_wip(&messages);
3412 return Ok(feature);
3413 }
3414
3415 Ok(messages.first().unwrap().clone())
3417}
3418
3419pub fn extract_feature_from_wip(messages: &[String]) -> String {
3421 for msg in messages {
3423 if msg.to_lowercase().starts_with("wip:") {
3425 if let Some(rest) = msg
3426 .strip_prefix("WIP:")
3427 .or_else(|| msg.strip_prefix("wip:"))
3428 {
3429 let feature = rest.trim();
3430 if !feature.is_empty() && feature.len() > 3 {
3431 let mut chars: Vec<char> = feature.chars().collect();
3433 if let Some(first) = chars.first_mut() {
3434 *first = first.to_uppercase().next().unwrap_or(*first);
3435 }
3436 return chars.into_iter().collect();
3437 }
3438 }
3439 }
3440 }
3441
3442 if let Some(first) = messages.first() {
3444 let cleaned = first
3445 .trim_start_matches("WIP:")
3446 .trim_start_matches("wip:")
3447 .trim_start_matches("WIP")
3448 .trim_start_matches("wip")
3449 .trim();
3450
3451 if !cleaned.is_empty() {
3452 return format!("Implement {cleaned}");
3453 }
3454 }
3455
3456 format!("Squashed {} commits", messages.len())
3457}
3458
3459pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
3461 let head_commit = repo.get_head_commit()?;
3462 let since_commit = repo.get_commit(since_commit_hash)?;
3463
3464 let mut count = 0;
3465 let mut current = head_commit;
3466
3467 loop {
3469 if current.id() == since_commit.id() {
3470 break;
3471 }
3472
3473 count += 1;
3474
3475 if current.parent_count() == 0 {
3477 break; }
3479
3480 current = current.parent(0).map_err(CascadeError::Git)?;
3481 }
3482
3483 Ok(count)
3484}
3485
3486async fn land_stack(
3488 entry: Option<usize>,
3489 force: bool,
3490 dry_run: bool,
3491 auto: bool,
3492 wait_for_builds: bool,
3493 strategy: Option<MergeStrategyArg>,
3494 build_timeout: u64,
3495) -> Result<()> {
3496 let current_dir = env::current_dir()
3497 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3498
3499 let repo_root = find_repository_root(¤t_dir)
3500 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3501
3502 let stack_manager = StackManager::new(&repo_root)?;
3503
3504 let stack_id = stack_manager
3506 .get_active_stack()
3507 .map(|s| s.id)
3508 .ok_or_else(|| {
3509 CascadeError::config(
3510 "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
3511 .to_string(),
3512 )
3513 })?;
3514
3515 let active_stack = stack_manager
3516 .get_active_stack()
3517 .cloned()
3518 .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
3519
3520 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
3522 let config_path = config_dir.join("config.json");
3523 let settings = crate::config::Settings::load_from_file(&config_path)?;
3524
3525 let cascade_config = crate::config::CascadeConfig {
3526 bitbucket: Some(settings.bitbucket.clone()),
3527 git: settings.git.clone(),
3528 auth: crate::config::AuthConfig::default(),
3529 cascade: settings.cascade.clone(),
3530 };
3531
3532 let mut integration =
3533 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
3534
3535 let status = integration.check_enhanced_stack_status(&stack_id).await?;
3537
3538 if status.enhanced_statuses.is_empty() {
3539 println!("❌ No pull requests found to land");
3540 return Ok(());
3541 }
3542
3543 let ready_prs: Vec<_> = status
3545 .enhanced_statuses
3546 .iter()
3547 .filter(|pr_status| {
3548 if let Some(entry_num) = entry {
3550 if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
3552 if pr_status.pr.from_ref.display_id != stack_entry.branch {
3554 return false;
3555 }
3556 } else {
3557 return false; }
3559 }
3560
3561 if force {
3562 pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
3564 } else {
3565 pr_status.is_ready_to_land()
3566 }
3567 })
3568 .collect();
3569
3570 if ready_prs.is_empty() {
3571 if let Some(entry_num) = entry {
3572 println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
3573 } else {
3574 println!("❌ No pull requests are ready to land");
3575 }
3576
3577 println!("\n🚫 Blocking Issues:");
3579 for pr_status in &status.enhanced_statuses {
3580 if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
3581 let blocking = pr_status.get_blocking_reasons();
3582 if !blocking.is_empty() {
3583 println!(" PR #{}: {}", pr_status.pr.id, blocking.join(", "));
3584 }
3585 }
3586 }
3587
3588 if !force {
3589 println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
3590 }
3591 return Ok(());
3592 }
3593
3594 if dry_run {
3595 if let Some(entry_num) = entry {
3596 println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
3597 } else {
3598 println!("🏃 Dry Run - PRs that would be landed:");
3599 }
3600 for pr_status in &ready_prs {
3601 println!(" ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
3602 if !pr_status.is_ready_to_land() && force {
3603 let blocking = pr_status.get_blocking_reasons();
3604 println!(
3605 " ⚠️ Would force land despite: {}",
3606 blocking.join(", ")
3607 );
3608 }
3609 }
3610 return Ok(());
3611 }
3612
3613 if entry.is_some() && ready_prs.len() > 1 {
3616 println!(
3617 "🎯 {} PRs are ready to land, but landing only entry #{}",
3618 ready_prs.len(),
3619 entry.unwrap()
3620 );
3621 }
3622
3623 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
3625 strategy.unwrap_or(MergeStrategyArg::Squash).into();
3626 let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3627 merge_strategy: merge_strategy.clone(),
3628 wait_for_builds,
3629 build_timeout: std::time::Duration::from_secs(build_timeout),
3630 allowed_authors: None, };
3632
3633 println!(
3635 "🚀 Landing {} PR{}...",
3636 ready_prs.len(),
3637 if ready_prs.len() == 1 { "" } else { "s" }
3638 );
3639
3640 let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
3641 crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
3642 );
3643
3644 let mut landed_count = 0;
3646 let mut failed_count = 0;
3647 let total_ready_prs = ready_prs.len();
3648
3649 for pr_status in ready_prs {
3650 let pr_id = pr_status.pr.id;
3651
3652 print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
3653
3654 let land_result = if auto {
3655 pr_manager
3657 .auto_merge_if_ready(pr_id, &auto_merge_conditions)
3658 .await
3659 } else {
3660 pr_manager
3662 .merge_pull_request(pr_id, merge_strategy.clone())
3663 .await
3664 .map(
3665 |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
3666 pr: Box::new(pr),
3667 merge_strategy: merge_strategy.clone(),
3668 },
3669 )
3670 };
3671
3672 match land_result {
3673 Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
3674 println!(" ✅");
3675 landed_count += 1;
3676
3677 if landed_count < total_ready_prs {
3679 println!(" Retargeting remaining PRs to latest base...");
3680
3681 let base_branch = active_stack.base_branch.clone();
3683 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3684
3685 println!(" 📥 Updating base branch: {base_branch}");
3686 match git_repo.pull(&base_branch) {
3687 Ok(_) => println!(" ✅ Base branch updated successfully"),
3688 Err(e) => {
3689 println!(" ⚠️ Warning: Failed to update base branch: {e}");
3690 println!(
3691 " 💡 You may want to manually run: git pull origin {base_branch}"
3692 );
3693 }
3694 }
3695
3696 let temp_manager = StackManager::new(&repo_root)?;
3698 let stack_for_count = temp_manager
3699 .get_stack(&stack_id)
3700 .ok_or_else(|| CascadeError::config("Stack not found"))?;
3701 let entry_count = stack_for_count.entries.len();
3702 let plural = if entry_count == 1 { "entry" } else { "entries" };
3703
3704 println!(); let rebase_spinner = crate::utils::spinner::Spinner::new(format!(
3706 "Retargeting {} {}",
3707 entry_count, plural
3708 ));
3709
3710 let mut rebase_manager = crate::stack::RebaseManager::new(
3711 StackManager::new(&repo_root)?,
3712 git_repo,
3713 crate::stack::RebaseOptions {
3714 strategy: crate::stack::RebaseStrategy::ForcePush,
3715 target_base: Some(base_branch.clone()),
3716 ..Default::default()
3717 },
3718 );
3719
3720 let rebase_result = rebase_manager.rebase_stack(&stack_id);
3721
3722 rebase_spinner.stop();
3723 println!(); match rebase_result {
3726 Ok(rebase_result) => {
3727 if !rebase_result.branch_mapping.is_empty() {
3728 let retarget_config = crate::config::CascadeConfig {
3730 bitbucket: Some(settings.bitbucket.clone()),
3731 git: settings.git.clone(),
3732 auth: crate::config::AuthConfig::default(),
3733 cascade: settings.cascade.clone(),
3734 };
3735 let mut retarget_integration = BitbucketIntegration::new(
3736 StackManager::new(&repo_root)?,
3737 retarget_config,
3738 )?;
3739
3740 match retarget_integration
3741 .update_prs_after_rebase(
3742 &stack_id,
3743 &rebase_result.branch_mapping,
3744 )
3745 .await
3746 {
3747 Ok(updated_prs) => {
3748 if !updated_prs.is_empty() {
3749 println!(
3750 " ✅ Updated {} PRs with new targets",
3751 updated_prs.len()
3752 );
3753 }
3754 }
3755 Err(e) => {
3756 println!(" ⚠️ Failed to update remaining PRs: {e}");
3757 println!(
3758 " 💡 You may need to run: ca stack rebase --onto {base_branch}"
3759 );
3760 }
3761 }
3762 }
3763 }
3764 Err(e) => {
3765 println!(" ❌ Auto-retargeting conflicts detected!");
3767 println!(" 📝 To resolve conflicts and continue landing:");
3768 println!(" 1. Resolve conflicts in the affected files");
3769 println!(" 2. Stage resolved files: git add <files>");
3770 println!(" 3. Continue the process: ca stack continue-land");
3771 println!(" 4. Or abort the operation: ca stack abort-land");
3772 println!();
3773 println!(" 💡 Check current status: ca stack land-status");
3774 println!(" ⚠️ Error details: {e}");
3775
3776 break;
3778 }
3779 }
3780 }
3781 }
3782 Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
3783 println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
3784 failed_count += 1;
3785 if !force {
3786 break;
3787 }
3788 }
3789 Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
3790 println!(" ❌ Failed: {error}");
3791 failed_count += 1;
3792 if !force {
3793 break;
3794 }
3795 }
3796 Err(e) => {
3797 println!(" ❌");
3798 eprintln!("Failed to land PR #{pr_id}: {e}");
3799 failed_count += 1;
3800
3801 if !force {
3802 break;
3803 }
3804 }
3805 }
3806 }
3807
3808 println!("\n🎯 Landing Summary:");
3810 println!(" ✅ Successfully landed: {landed_count}");
3811 if failed_count > 0 {
3812 println!(" ❌ Failed to land: {failed_count}");
3813 }
3814
3815 if landed_count > 0 {
3816 Output::success(" Landing operation completed!");
3817 } else {
3818 println!("❌ No PRs were successfully landed");
3819 }
3820
3821 Ok(())
3822}
3823
3824async fn auto_land_stack(
3826 force: bool,
3827 dry_run: bool,
3828 wait_for_builds: bool,
3829 strategy: Option<MergeStrategyArg>,
3830 build_timeout: u64,
3831) -> Result<()> {
3832 land_stack(
3834 None,
3835 force,
3836 dry_run,
3837 true, wait_for_builds,
3839 strategy,
3840 build_timeout,
3841 )
3842 .await
3843}
3844
3845async fn continue_land() -> Result<()> {
3846 let current_dir = env::current_dir()
3847 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3848
3849 let repo_root = find_repository_root(¤t_dir)
3850 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3851
3852 let stack_manager = StackManager::new(&repo_root)?;
3853 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3854 let options = crate::stack::RebaseOptions::default();
3855 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3856
3857 if !rebase_manager.is_rebase_in_progress() {
3858 Output::info(" No rebase in progress");
3859 return Ok(());
3860 }
3861
3862 println!(" Continuing land operation...");
3863 match rebase_manager.continue_rebase() {
3864 Ok(_) => {
3865 Output::success(" Land operation continued successfully");
3866 println!(" Check 'ca stack land-status' for current state");
3867 }
3868 Err(e) => {
3869 warn!("❌ Failed to continue land operation: {}", e);
3870 Output::tip(" You may need to resolve conflicts first:");
3871 println!(" 1. Edit conflicted files");
3872 println!(" 2. Stage resolved files with 'git add'");
3873 println!(" 3. Run 'ca stack continue-land' again");
3874 }
3875 }
3876
3877 Ok(())
3878}
3879
3880async fn abort_land() -> Result<()> {
3881 let current_dir = env::current_dir()
3882 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3883
3884 let repo_root = find_repository_root(¤t_dir)
3885 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3886
3887 let stack_manager = StackManager::new(&repo_root)?;
3888 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3889 let options = crate::stack::RebaseOptions::default();
3890 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3891
3892 if !rebase_manager.is_rebase_in_progress() {
3893 Output::info(" No rebase in progress");
3894 return Ok(());
3895 }
3896
3897 println!("⚠️ Aborting land operation...");
3898 match rebase_manager.abort_rebase() {
3899 Ok(_) => {
3900 Output::success(" Land operation aborted successfully");
3901 println!(" Repository restored to pre-land state");
3902 }
3903 Err(e) => {
3904 warn!("❌ Failed to abort land operation: {}", e);
3905 println!("⚠️ You may need to manually clean up the repository state");
3906 }
3907 }
3908
3909 Ok(())
3910}
3911
3912async fn land_status() -> Result<()> {
3913 let current_dir = env::current_dir()
3914 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3915
3916 let repo_root = find_repository_root(¤t_dir)
3917 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3918
3919 let stack_manager = StackManager::new(&repo_root)?;
3920 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3921
3922 println!("Land Status");
3923
3924 let git_dir = repo_root.join(".git");
3926 let land_in_progress = git_dir.join("REBASE_HEAD").exists()
3927 || git_dir.join("rebase-merge").exists()
3928 || git_dir.join("rebase-apply").exists();
3929
3930 if land_in_progress {
3931 println!(" Status: 🔄 Land operation in progress");
3932 println!(
3933 "
3934📝 Actions available:"
3935 );
3936 println!(" - 'ca stack continue-land' to continue");
3937 println!(" - 'ca stack abort-land' to abort");
3938 println!(" - 'git status' to see conflicted files");
3939
3940 match git_repo.get_status() {
3942 Ok(statuses) => {
3943 let mut conflicts = Vec::new();
3944 for status in statuses.iter() {
3945 if status.status().contains(git2::Status::CONFLICTED) {
3946 if let Some(path) = status.path() {
3947 conflicts.push(path.to_string());
3948 }
3949 }
3950 }
3951
3952 if !conflicts.is_empty() {
3953 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
3954 for conflict in conflicts {
3955 println!(" - {conflict}");
3956 }
3957 println!(
3958 "
3959💡 To resolve conflicts:"
3960 );
3961 println!(" 1. Edit the conflicted files");
3962 println!(" 2. Stage resolved files: git add <file>");
3963 println!(" 3. Continue: ca stack continue-land");
3964 }
3965 }
3966 Err(e) => {
3967 warn!("Failed to get git status: {}", e);
3968 }
3969 }
3970 } else {
3971 println!(" Status: ✅ No land operation in progress");
3972
3973 if let Some(active_stack) = stack_manager.get_active_stack() {
3975 println!(" Active stack: {}", active_stack.name);
3976 println!(" Entries: {}", active_stack.entries.len());
3977 println!(" Base branch: {}", active_stack.base_branch);
3978 }
3979 }
3980
3981 Ok(())
3982}
3983
3984async fn repair_stack_data() -> Result<()> {
3985 let current_dir = env::current_dir()
3986 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3987
3988 let repo_root = find_repository_root(¤t_dir)
3989 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3990
3991 let mut stack_manager = StackManager::new(&repo_root)?;
3992
3993 println!("🔧 Repairing stack data consistency...");
3994
3995 stack_manager.repair_all_stacks()?;
3996
3997 Output::success(" Stack data consistency repaired successfully!");
3998 Output::tip(" Run 'ca stack --mergeable' to see updated status");
3999
4000 Ok(())
4001}
4002
4003async fn cleanup_branches(
4005 dry_run: bool,
4006 force: bool,
4007 include_stale: bool,
4008 stale_days: u32,
4009 cleanup_remote: bool,
4010 include_non_stack: bool,
4011 verbose: bool,
4012) -> Result<()> {
4013 let current_dir = env::current_dir()
4014 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
4015
4016 let repo_root = find_repository_root(¤t_dir)
4017 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
4018
4019 let stack_manager = StackManager::new(&repo_root)?;
4020 let git_repo = GitRepository::open(&repo_root)?;
4021
4022 let result = perform_cleanup(
4023 &stack_manager,
4024 &git_repo,
4025 dry_run,
4026 force,
4027 include_stale,
4028 stale_days,
4029 cleanup_remote,
4030 include_non_stack,
4031 verbose,
4032 )
4033 .await?;
4034
4035 if result.total_candidates == 0 {
4037 Output::success("No branches found that need cleanup");
4038 return Ok(());
4039 }
4040
4041 Output::section("Cleanup Results");
4042
4043 if dry_run {
4044 Output::sub_item(format!(
4045 "Found {} branches that would be cleaned up",
4046 result.total_candidates
4047 ));
4048 } else {
4049 if !result.cleaned_branches.is_empty() {
4050 Output::success(format!(
4051 "Successfully cleaned up {} branches",
4052 result.cleaned_branches.len()
4053 ));
4054 for branch in &result.cleaned_branches {
4055 Output::sub_item(format!("🗑️ Deleted: {branch}"));
4056 }
4057 }
4058
4059 if !result.skipped_branches.is_empty() {
4060 Output::sub_item(format!(
4061 "Skipped {} branches",
4062 result.skipped_branches.len()
4063 ));
4064 if verbose {
4065 for (branch, reason) in &result.skipped_branches {
4066 Output::sub_item(format!("⏭️ {branch}: {reason}"));
4067 }
4068 }
4069 }
4070
4071 if !result.failed_branches.is_empty() {
4072 Output::warning(format!(
4073 "Failed to clean up {} branches",
4074 result.failed_branches.len()
4075 ));
4076 for (branch, error) in &result.failed_branches {
4077 Output::sub_item(format!("❌ {branch}: {error}"));
4078 }
4079 }
4080 }
4081
4082 Ok(())
4083}
4084
4085#[allow(clippy::too_many_arguments)]
4087async fn perform_cleanup(
4088 stack_manager: &StackManager,
4089 git_repo: &GitRepository,
4090 dry_run: bool,
4091 force: bool,
4092 include_stale: bool,
4093 stale_days: u32,
4094 cleanup_remote: bool,
4095 include_non_stack: bool,
4096 verbose: bool,
4097) -> Result<CleanupResult> {
4098 let options = CleanupOptions {
4099 dry_run,
4100 force,
4101 include_stale,
4102 cleanup_remote,
4103 stale_threshold_days: stale_days,
4104 cleanup_non_stack: include_non_stack,
4105 };
4106
4107 let stack_manager_copy = StackManager::new(stack_manager.repo_path())?;
4108 let git_repo_copy = GitRepository::open(git_repo.path())?;
4109 let mut cleanup_manager = CleanupManager::new(stack_manager_copy, git_repo_copy, options);
4110
4111 let candidates = cleanup_manager.find_cleanup_candidates()?;
4113
4114 if candidates.is_empty() {
4115 return Ok(CleanupResult {
4116 cleaned_branches: Vec::new(),
4117 failed_branches: Vec::new(),
4118 skipped_branches: Vec::new(),
4119 total_candidates: 0,
4120 });
4121 }
4122
4123 if verbose || dry_run {
4125 Output::section("Cleanup Candidates");
4126 for candidate in &candidates {
4127 let reason_icon = match candidate.reason {
4128 crate::stack::CleanupReason::FullyMerged => "🔀",
4129 crate::stack::CleanupReason::StackEntryMerged => "✅",
4130 crate::stack::CleanupReason::Stale => "⏰",
4131 crate::stack::CleanupReason::Orphaned => "👻",
4132 };
4133
4134 Output::sub_item(format!(
4135 "{} {} - {} ({})",
4136 reason_icon,
4137 candidate.branch_name,
4138 candidate.reason_to_string(),
4139 candidate.safety_info
4140 ));
4141 }
4142 }
4143
4144 if !force && !dry_run && !candidates.is_empty() {
4146 Output::warning(format!("About to delete {} branches", candidates.len()));
4147
4148 let preview_count = 5.min(candidates.len());
4150 for candidate in candidates.iter().take(preview_count) {
4151 println!(" • {}", candidate.branch_name);
4152 }
4153 if candidates.len() > preview_count {
4154 println!(" ... and {} more", candidates.len() - preview_count);
4155 }
4156 println!(); let should_continue = Confirm::with_theme(&ColorfulTheme::default())
4160 .with_prompt("Continue with branch cleanup?")
4161 .default(false)
4162 .interact()
4163 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
4164
4165 if !should_continue {
4166 Output::sub_item("Cleanup cancelled");
4167 return Ok(CleanupResult {
4168 cleaned_branches: Vec::new(),
4169 failed_branches: Vec::new(),
4170 skipped_branches: Vec::new(),
4171 total_candidates: candidates.len(),
4172 });
4173 }
4174 }
4175
4176 cleanup_manager.perform_cleanup(&candidates)
4178}
4179
4180async fn perform_simple_cleanup(
4182 stack_manager: &StackManager,
4183 git_repo: &GitRepository,
4184 dry_run: bool,
4185) -> Result<CleanupResult> {
4186 perform_cleanup(
4187 stack_manager,
4188 git_repo,
4189 dry_run,
4190 false, false, 30, false, false, false, )
4197 .await
4198}
4199
4200async fn analyze_commits_for_safeguards(
4202 commits_to_push: &[String],
4203 repo: &GitRepository,
4204 dry_run: bool,
4205) -> Result<()> {
4206 const LARGE_COMMIT_THRESHOLD: usize = 10;
4207 const WEEK_IN_SECONDS: i64 = 7 * 24 * 3600;
4208
4209 if commits_to_push.len() > LARGE_COMMIT_THRESHOLD {
4211 println!(
4212 "⚠️ Warning: About to push {} commits to stack",
4213 commits_to_push.len()
4214 );
4215 println!(" This may indicate a merge commit issue or unexpected commit range.");
4216 println!(" Large commit counts often result from merging instead of rebasing.");
4217
4218 if !dry_run && !confirm_large_push(commits_to_push.len())? {
4219 return Err(CascadeError::config("Push cancelled by user"));
4220 }
4221 }
4222
4223 let commit_objects: Result<Vec<_>> = commits_to_push
4225 .iter()
4226 .map(|hash| repo.get_commit(hash))
4227 .collect();
4228 let commit_objects = commit_objects?;
4229
4230 let merge_commits: Vec<_> = commit_objects
4232 .iter()
4233 .filter(|c| c.parent_count() > 1)
4234 .collect();
4235
4236 if !merge_commits.is_empty() {
4237 println!(
4238 "⚠️ Warning: {} merge commits detected in push",
4239 merge_commits.len()
4240 );
4241 println!(" This often indicates you merged instead of rebased.");
4242 println!(" Consider using 'ca sync' to rebase on the base branch.");
4243 println!(" Merge commits in stacks can cause confusion and duplicate work.");
4244 }
4245
4246 if commit_objects.len() > 1 {
4248 let oldest_commit_time = commit_objects.first().unwrap().time().seconds();
4249 let newest_commit_time = commit_objects.last().unwrap().time().seconds();
4250 let time_span = newest_commit_time - oldest_commit_time;
4251
4252 if time_span > WEEK_IN_SECONDS {
4253 let days = time_span / (24 * 3600);
4254 println!("⚠️ Warning: Commits span {days} days");
4255 println!(" This may indicate merged history rather than new work.");
4256 println!(" Recent work should typically span hours or days, not weeks.");
4257 }
4258 }
4259
4260 if commits_to_push.len() > 5 {
4262 Output::tip(" Tip: If you only want recent commits, use:");
4263 println!(
4264 " ca push --since HEAD~{} # pushes last {} commits",
4265 std::cmp::min(commits_to_push.len(), 5),
4266 std::cmp::min(commits_to_push.len(), 5)
4267 );
4268 println!(" ca push --commits <hash1>,<hash2> # pushes specific commits");
4269 println!(" ca push --dry-run # preview what would be pushed");
4270 }
4271
4272 if dry_run {
4274 println!("🔍 DRY RUN: Would push {} commits:", commits_to_push.len());
4275 for (i, (commit_hash, commit_obj)) in commits_to_push
4276 .iter()
4277 .zip(commit_objects.iter())
4278 .enumerate()
4279 {
4280 let summary = commit_obj.summary().unwrap_or("(no message)");
4281 let short_hash = &commit_hash[..std::cmp::min(commit_hash.len(), 7)];
4282 println!(" {}: {} ({})", i + 1, summary, short_hash);
4283 }
4284 Output::tip(" Run without --dry-run to actually push these commits.");
4285 }
4286
4287 Ok(())
4288}
4289
4290fn confirm_large_push(count: usize) -> Result<bool> {
4292 let should_continue = Confirm::with_theme(&ColorfulTheme::default())
4294 .with_prompt(format!("Continue pushing {count} commits?"))
4295 .default(false)
4296 .interact()
4297 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
4298
4299 Ok(should_continue)
4300}
4301
4302#[cfg(test)]
4303mod tests {
4304 use super::*;
4305 use std::process::Command;
4306 use tempfile::TempDir;
4307
4308 fn create_test_repo() -> Result<(TempDir, std::path::PathBuf)> {
4309 let temp_dir = TempDir::new()
4310 .map_err(|e| CascadeError::config(format!("Failed to create temp directory: {e}")))?;
4311 let repo_path = temp_dir.path().to_path_buf();
4312
4313 let output = Command::new("git")
4315 .args(["init"])
4316 .current_dir(&repo_path)
4317 .output()
4318 .map_err(|e| CascadeError::config(format!("Failed to run git init: {e}")))?;
4319 if !output.status.success() {
4320 return Err(CascadeError::config("Git init failed".to_string()));
4321 }
4322
4323 let output = Command::new("git")
4324 .args(["config", "user.name", "Test User"])
4325 .current_dir(&repo_path)
4326 .output()
4327 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
4328 if !output.status.success() {
4329 return Err(CascadeError::config(
4330 "Git config user.name failed".to_string(),
4331 ));
4332 }
4333
4334 let output = Command::new("git")
4335 .args(["config", "user.email", "test@example.com"])
4336 .current_dir(&repo_path)
4337 .output()
4338 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
4339 if !output.status.success() {
4340 return Err(CascadeError::config(
4341 "Git config user.email failed".to_string(),
4342 ));
4343 }
4344
4345 std::fs::write(repo_path.join("README.md"), "# Test")
4347 .map_err(|e| CascadeError::config(format!("Failed to write file: {e}")))?;
4348 let output = Command::new("git")
4349 .args(["add", "."])
4350 .current_dir(&repo_path)
4351 .output()
4352 .map_err(|e| CascadeError::config(format!("Failed to run git add: {e}")))?;
4353 if !output.status.success() {
4354 return Err(CascadeError::config("Git add failed".to_string()));
4355 }
4356
4357 let output = Command::new("git")
4358 .args(["commit", "-m", "Initial commit"])
4359 .current_dir(&repo_path)
4360 .output()
4361 .map_err(|e| CascadeError::config(format!("Failed to run git commit: {e}")))?;
4362 if !output.status.success() {
4363 return Err(CascadeError::config("Git commit failed".to_string()));
4364 }
4365
4366 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))?;
4368
4369 Ok((temp_dir, repo_path))
4370 }
4371
4372 #[tokio::test]
4373 async fn test_create_stack() {
4374 let (temp_dir, repo_path) = match create_test_repo() {
4375 Ok(repo) => repo,
4376 Err(_) => {
4377 println!("Skipping test due to git environment setup failure");
4378 return;
4379 }
4380 };
4381 let _ = &temp_dir;
4383
4384 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4388 match env::set_current_dir(&repo_path) {
4389 Ok(_) => {
4390 let result = create_stack(
4391 "test-stack".to_string(),
4392 None, Some("Test description".to_string()),
4394 )
4395 .await;
4396
4397 if let Ok(orig) = original_dir {
4399 let _ = env::set_current_dir(orig);
4400 }
4401
4402 assert!(
4403 result.is_ok(),
4404 "Stack creation should succeed in initialized repository"
4405 );
4406 }
4407 Err(_) => {
4408 println!("Skipping test due to directory access restrictions");
4410 }
4411 }
4412 }
4413
4414 #[tokio::test]
4415 async fn test_list_empty_stacks() {
4416 let (temp_dir, repo_path) = match create_test_repo() {
4417 Ok(repo) => repo,
4418 Err(_) => {
4419 println!("Skipping test due to git environment setup failure");
4420 return;
4421 }
4422 };
4423 let _ = &temp_dir;
4425
4426 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4430 match env::set_current_dir(&repo_path) {
4431 Ok(_) => {
4432 let result = list_stacks(false, false, None).await;
4433
4434 if let Ok(orig) = original_dir {
4436 let _ = env::set_current_dir(orig);
4437 }
4438
4439 assert!(
4440 result.is_ok(),
4441 "Listing stacks should succeed in initialized repository"
4442 );
4443 }
4444 Err(_) => {
4445 println!("Skipping test due to directory access restrictions");
4447 }
4448 }
4449 }
4450
4451 #[test]
4454 fn test_extract_feature_from_wip_basic() {
4455 let messages = vec![
4456 "WIP: add authentication".to_string(),
4457 "WIP: implement login flow".to_string(),
4458 ];
4459
4460 let result = extract_feature_from_wip(&messages);
4461 assert_eq!(result, "Add authentication");
4462 }
4463
4464 #[test]
4465 fn test_extract_feature_from_wip_capitalize() {
4466 let messages = vec!["WIP: fix user validation bug".to_string()];
4467
4468 let result = extract_feature_from_wip(&messages);
4469 assert_eq!(result, "Fix user validation bug");
4470 }
4471
4472 #[test]
4473 fn test_extract_feature_from_wip_fallback() {
4474 let messages = vec![
4475 "WIP user interface changes".to_string(),
4476 "wip: css styling".to_string(),
4477 ];
4478
4479 let result = extract_feature_from_wip(&messages);
4480 assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
4482 }
4483
4484 #[test]
4485 fn test_extract_feature_from_wip_empty() {
4486 let messages = vec![];
4487
4488 let result = extract_feature_from_wip(&messages);
4489 assert_eq!(result, "Squashed 0 commits");
4490 }
4491
4492 #[test]
4493 fn test_extract_feature_from_wip_short_message() {
4494 let messages = vec!["WIP: x".to_string()]; let result = extract_feature_from_wip(&messages);
4497 assert!(result.starts_with("Implement") || result.contains("Squashed"));
4498 }
4499
4500 #[test]
4503 fn test_squash_message_final_strategy() {
4504 let messages = [
4508 "Final: implement user authentication system".to_string(),
4509 "WIP: add tests".to_string(),
4510 "WIP: fix validation".to_string(),
4511 ];
4512
4513 assert!(messages[0].starts_with("Final:"));
4515
4516 let extracted = messages[0].trim_start_matches("Final:").trim();
4518 assert_eq!(extracted, "implement user authentication system");
4519 }
4520
4521 #[test]
4522 fn test_squash_message_wip_detection() {
4523 let messages = [
4524 "WIP: start feature".to_string(),
4525 "WIP: continue work".to_string(),
4526 "WIP: almost done".to_string(),
4527 "Regular commit message".to_string(),
4528 ];
4529
4530 let wip_count = messages
4531 .iter()
4532 .filter(|m| {
4533 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
4534 })
4535 .count();
4536
4537 assert_eq!(wip_count, 3); assert!(wip_count > messages.len() / 2); let non_wip: Vec<&String> = messages
4542 .iter()
4543 .filter(|m| {
4544 !m.to_lowercase().starts_with("wip")
4545 && !m.to_lowercase().contains("work in progress")
4546 })
4547 .collect();
4548
4549 assert_eq!(non_wip.len(), 1);
4550 assert_eq!(non_wip[0], "Regular commit message");
4551 }
4552
4553 #[test]
4554 fn test_squash_message_all_wip() {
4555 let messages = vec![
4556 "WIP: add feature A".to_string(),
4557 "WIP: add feature B".to_string(),
4558 "WIP: finish implementation".to_string(),
4559 ];
4560
4561 let result = extract_feature_from_wip(&messages);
4562 assert_eq!(result, "Add feature A");
4564 }
4565
4566 #[test]
4567 fn test_squash_message_edge_cases() {
4568 let empty_messages: Vec<String> = vec![];
4570 let result = extract_feature_from_wip(&empty_messages);
4571 assert_eq!(result, "Squashed 0 commits");
4572
4573 let whitespace_messages = vec![" ".to_string(), "\t\n".to_string()];
4575 let result = extract_feature_from_wip(&whitespace_messages);
4576 assert!(result.contains("Squashed") || result.contains("Implement"));
4577
4578 let mixed_case = vec!["wip: Add Feature".to_string()];
4580 let result = extract_feature_from_wip(&mixed_case);
4581 assert_eq!(result, "Add Feature");
4582 }
4583
4584 #[tokio::test]
4587 async fn test_auto_land_wrapper() {
4588 let (temp_dir, repo_path) = match create_test_repo() {
4590 Ok(repo) => repo,
4591 Err(_) => {
4592 println!("Skipping test due to git environment setup failure");
4593 return;
4594 }
4595 };
4596 let _ = &temp_dir;
4598
4599 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
4601 .expect("Failed to initialize Cascade in test repo");
4602
4603 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4604 match env::set_current_dir(&repo_path) {
4605 Ok(_) => {
4606 let result = create_stack(
4608 "test-stack".to_string(),
4609 None,
4610 Some("Test stack for auto-land".to_string()),
4611 )
4612 .await;
4613
4614 if let Ok(orig) = original_dir {
4615 let _ = env::set_current_dir(orig);
4616 }
4617
4618 assert!(
4621 result.is_ok(),
4622 "Stack creation should succeed in initialized repository"
4623 );
4624 }
4625 Err(_) => {
4626 println!("Skipping test due to directory access restrictions");
4627 }
4628 }
4629 }
4630
4631 #[test]
4632 fn test_auto_land_action_enum() {
4633 use crate::cli::commands::stack::StackAction;
4635
4636 let _action = StackAction::AutoLand {
4638 force: false,
4639 dry_run: true,
4640 wait_for_builds: true,
4641 strategy: Some(MergeStrategyArg::Squash),
4642 build_timeout: 1800,
4643 };
4644
4645 }
4647
4648 #[test]
4649 fn test_merge_strategy_conversion() {
4650 let squash_strategy = MergeStrategyArg::Squash;
4652 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
4653
4654 match merge_strategy {
4655 crate::bitbucket::pull_request::MergeStrategy::Squash => {
4656 }
4658 _ => unreachable!("SquashStrategyArg only has Squash variant"),
4659 }
4660
4661 let merge_strategy = MergeStrategyArg::Merge;
4662 let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
4663
4664 match converted {
4665 crate::bitbucket::pull_request::MergeStrategy::Merge => {
4666 }
4668 _ => unreachable!("MergeStrategyArg::Merge maps to MergeStrategy::Merge"),
4669 }
4670 }
4671
4672 #[test]
4673 fn test_auto_merge_conditions_structure() {
4674 use std::time::Duration;
4676
4677 let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
4678 merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
4679 wait_for_builds: true,
4680 build_timeout: Duration::from_secs(1800),
4681 allowed_authors: None,
4682 };
4683
4684 assert!(conditions.wait_for_builds);
4686 assert_eq!(conditions.build_timeout.as_secs(), 1800);
4687 assert!(conditions.allowed_authors.is_none());
4688 assert!(matches!(
4689 conditions.merge_strategy,
4690 crate::bitbucket::pull_request::MergeStrategy::Squash
4691 ));
4692 }
4693
4694 #[test]
4695 fn test_polling_constants() {
4696 use std::time::Duration;
4698
4699 let expected_polling_interval = Duration::from_secs(30);
4701
4702 assert!(expected_polling_interval.as_secs() >= 10); assert!(expected_polling_interval.as_secs() <= 60); assert_eq!(expected_polling_interval.as_secs(), 30); }
4707
4708 #[test]
4709 fn test_build_timeout_defaults() {
4710 const DEFAULT_TIMEOUT: u64 = 1800; assert_eq!(DEFAULT_TIMEOUT, 1800);
4713 let timeout_value = 1800u64;
4715 assert!(timeout_value >= 300); assert!(timeout_value <= 3600); }
4718
4719 #[test]
4720 fn test_scattered_commit_detection() {
4721 use std::collections::HashSet;
4722
4723 let mut source_branches = HashSet::new();
4725 source_branches.insert("feature-branch-1".to_string());
4726 source_branches.insert("feature-branch-2".to_string());
4727 source_branches.insert("feature-branch-3".to_string());
4728
4729 let single_branch = HashSet::from(["main".to_string()]);
4731 assert_eq!(single_branch.len(), 1);
4732
4733 assert!(source_branches.len() > 1);
4735 assert_eq!(source_branches.len(), 3);
4736
4737 assert!(source_branches.contains("feature-branch-1"));
4739 assert!(source_branches.contains("feature-branch-2"));
4740 assert!(source_branches.contains("feature-branch-3"));
4741 }
4742
4743 #[test]
4744 fn test_source_branch_tracking() {
4745 let branch_a = "feature-work";
4749 let branch_b = "feature-work";
4750 assert_eq!(branch_a, branch_b);
4751
4752 let branch_1 = "feature-ui";
4754 let branch_2 = "feature-api";
4755 assert_ne!(branch_1, branch_2);
4756
4757 assert!(branch_1.starts_with("feature-"));
4759 assert!(branch_2.starts_with("feature-"));
4760 }
4761
4762 #[tokio::test]
4765 async fn test_push_default_behavior() {
4766 let (temp_dir, repo_path) = match create_test_repo() {
4768 Ok(repo) => repo,
4769 Err(_) => {
4770 println!("Skipping test due to git environment setup failure");
4771 return;
4772 }
4773 };
4774 let _ = &temp_dir;
4776
4777 if !repo_path.exists() {
4779 println!("Skipping test due to temporary directory creation issue");
4780 return;
4781 }
4782
4783 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4785
4786 match env::set_current_dir(&repo_path) {
4787 Ok(_) => {
4788 let result = push_to_stack(
4790 None, None, None, None, None, None, None, false, false, false, )
4801 .await;
4802
4803 if let Ok(orig) = original_dir {
4805 let _ = env::set_current_dir(orig);
4806 }
4807
4808 match &result {
4810 Err(e) => {
4811 let error_msg = e.to_string();
4812 assert!(
4814 error_msg.contains("No active stack")
4815 || error_msg.contains("config")
4816 || error_msg.contains("current directory")
4817 || error_msg.contains("Not a git repository")
4818 || error_msg.contains("could not find repository"),
4819 "Expected 'No active stack' or repository error, got: {error_msg}"
4820 );
4821 }
4822 Ok(_) => {
4823 println!(
4825 "Push succeeded unexpectedly - test environment may have active stack"
4826 );
4827 }
4828 }
4829 }
4830 Err(_) => {
4831 println!("Skipping test due to directory access restrictions");
4833 }
4834 }
4835
4836 let push_action = StackAction::Push {
4838 branch: None,
4839 message: None,
4840 commit: None,
4841 since: None,
4842 commits: None,
4843 squash: None,
4844 squash_since: None,
4845 auto_branch: false,
4846 allow_base_branch: false,
4847 dry_run: false,
4848 };
4849
4850 assert!(matches!(
4851 push_action,
4852 StackAction::Push {
4853 branch: None,
4854 message: None,
4855 commit: None,
4856 since: None,
4857 commits: None,
4858 squash: None,
4859 squash_since: None,
4860 auto_branch: false,
4861 allow_base_branch: false,
4862 dry_run: false
4863 }
4864 ));
4865 }
4866
4867 #[tokio::test]
4868 async fn test_submit_default_behavior() {
4869 let (temp_dir, repo_path) = match create_test_repo() {
4871 Ok(repo) => repo,
4872 Err(_) => {
4873 println!("Skipping test due to git environment setup failure");
4874 return;
4875 }
4876 };
4877 let _ = &temp_dir;
4879
4880 if !repo_path.exists() {
4882 println!("Skipping test due to temporary directory creation issue");
4883 return;
4884 }
4885
4886 let original_dir = match env::current_dir() {
4888 Ok(dir) => dir,
4889 Err(_) => {
4890 println!("Skipping test due to current directory access restrictions");
4891 return;
4892 }
4893 };
4894
4895 match env::set_current_dir(&repo_path) {
4896 Ok(_) => {
4897 let result = submit_entry(
4899 None, None, None, None, false, true, )
4906 .await;
4907
4908 let _ = env::set_current_dir(original_dir);
4910
4911 match &result {
4913 Err(e) => {
4914 let error_msg = e.to_string();
4915 assert!(
4917 error_msg.contains("No active stack")
4918 || error_msg.contains("config")
4919 || error_msg.contains("current directory")
4920 || error_msg.contains("Not a git repository")
4921 || error_msg.contains("could not find repository"),
4922 "Expected 'No active stack' or repository error, got: {error_msg}"
4923 );
4924 }
4925 Ok(_) => {
4926 println!("Submit succeeded unexpectedly - test environment may have active stack");
4928 }
4929 }
4930 }
4931 Err(_) => {
4932 println!("Skipping test due to directory access restrictions");
4934 }
4935 }
4936
4937 let submit_action = StackAction::Submit {
4939 entry: None,
4940 title: None,
4941 description: None,
4942 range: None,
4943 draft: true, open: true,
4945 };
4946
4947 assert!(matches!(
4948 submit_action,
4949 StackAction::Submit {
4950 entry: None,
4951 title: None,
4952 description: None,
4953 range: None,
4954 draft: true, open: true
4956 }
4957 ));
4958 }
4959
4960 #[test]
4961 fn test_targeting_options_still_work() {
4962 let commits = "abc123,def456,ghi789";
4966 let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
4967 assert_eq!(parsed.len(), 3);
4968 assert_eq!(parsed[0], "abc123");
4969 assert_eq!(parsed[1], "def456");
4970 assert_eq!(parsed[2], "ghi789");
4971
4972 let range = "1-3";
4974 assert!(range.contains('-'));
4975 let parts: Vec<&str> = range.split('-').collect();
4976 assert_eq!(parts.len(), 2);
4977
4978 let since_ref = "HEAD~3";
4980 assert!(since_ref.starts_with("HEAD"));
4981 assert!(since_ref.contains('~'));
4982 }
4983
4984 #[test]
4985 fn test_command_flow_logic() {
4986 assert!(matches!(
4988 StackAction::Push {
4989 branch: None,
4990 message: None,
4991 commit: None,
4992 since: None,
4993 commits: None,
4994 squash: None,
4995 squash_since: None,
4996 auto_branch: false,
4997 allow_base_branch: false,
4998 dry_run: false
4999 },
5000 StackAction::Push { .. }
5001 ));
5002
5003 assert!(matches!(
5004 StackAction::Submit {
5005 entry: None,
5006 title: None,
5007 description: None,
5008 range: None,
5009 draft: false,
5010 open: true
5011 },
5012 StackAction::Submit { .. }
5013 ));
5014 }
5015
5016 #[tokio::test]
5017 async fn test_deactivate_command_structure() {
5018 let deactivate_action = StackAction::Deactivate { force: false };
5020
5021 assert!(matches!(
5023 deactivate_action,
5024 StackAction::Deactivate { force: false }
5025 ));
5026
5027 let force_deactivate = StackAction::Deactivate { force: true };
5029 assert!(matches!(
5030 force_deactivate,
5031 StackAction::Deactivate { force: true }
5032 ));
5033 }
5034}