1use crate::bitbucket::BitbucketIntegration;
2use crate::errors::{CascadeError, Result};
3use crate::git::{find_repository_root, GitRepository};
4use crate::stack::{StackManager, StackStatus};
5use clap::{Subcommand, ValueEnum};
6use indicatif::{ProgressBar, ProgressStyle};
7use std::env;
8use tracing::{info, warn};
9
10#[derive(ValueEnum, Clone, Debug)]
12pub enum RebaseStrategyArg {
13 BranchVersioning,
15 CherryPick,
17 ThreeWayMerge,
19 Interactive,
21}
22
23#[derive(ValueEnum, Clone, Debug)]
24pub enum MergeStrategyArg {
25 Merge,
27 Squash,
29 FastForward,
31}
32
33impl From<MergeStrategyArg> for crate::bitbucket::pull_request::MergeStrategy {
34 fn from(arg: MergeStrategyArg) -> Self {
35 match arg {
36 MergeStrategyArg::Merge => Self::Merge,
37 MergeStrategyArg::Squash => Self::Squash,
38 MergeStrategyArg::FastForward => Self::FastForward,
39 }
40 }
41}
42
43#[derive(Subcommand)]
44pub enum StackAction {
45 Create {
47 name: String,
49 #[arg(long, short)]
51 base: Option<String>,
52 #[arg(long, short)]
54 description: Option<String>,
55 },
56
57 List {
59 #[arg(long, short)]
61 verbose: bool,
62 #[arg(long)]
64 active: bool,
65 #[arg(long)]
67 format: Option<String>,
68 },
69
70 Switch {
72 name: String,
74 },
75
76 Deactivate {
78 #[arg(long)]
80 force: bool,
81 },
82
83 Show {
85 #[arg(short, long)]
87 verbose: bool,
88 #[arg(short, long)]
90 mergeable: bool,
91 },
92
93 Push {
95 #[arg(long, short)]
97 branch: Option<String>,
98 #[arg(long, short)]
100 message: Option<String>,
101 #[arg(long)]
103 commit: Option<String>,
104 #[arg(long)]
106 since: Option<String>,
107 #[arg(long)]
109 commits: Option<String>,
110 #[arg(long, num_args = 0..=1, default_missing_value = "0")]
112 squash: Option<usize>,
113 #[arg(long)]
115 squash_since: Option<String>,
116 #[arg(long)]
118 auto_branch: bool,
119 #[arg(long)]
121 allow_base_branch: bool,
122 },
123
124 Pop {
126 #[arg(long)]
128 keep_branch: bool,
129 },
130
131 Submit {
133 entry: Option<usize>,
135 #[arg(long, short)]
137 title: Option<String>,
138 #[arg(long, short)]
140 description: Option<String>,
141 #[arg(long)]
143 range: Option<String>,
144 #[arg(long)]
146 draft: bool,
147 },
148
149 Status {
151 name: Option<String>,
153 },
154
155 Prs {
157 #[arg(long)]
159 state: Option<String>,
160 #[arg(long, short)]
162 verbose: bool,
163 },
164
165 Check {
167 #[arg(long)]
169 force: bool,
170 },
171
172 Sync {
174 #[arg(long)]
176 force: bool,
177 #[arg(long)]
179 skip_cleanup: bool,
180 #[arg(long, short)]
182 interactive: bool,
183 },
184
185 Rebase {
187 #[arg(long, short)]
189 interactive: bool,
190 #[arg(long)]
192 onto: Option<String>,
193 #[arg(long, value_enum)]
195 strategy: Option<RebaseStrategyArg>,
196 },
197
198 ContinueRebase,
200
201 AbortRebase,
203
204 RebaseStatus,
206
207 Delete {
209 name: String,
211 #[arg(long)]
213 force: bool,
214 },
215
216 Validate {
218 name: Option<String>,
220 },
221
222 Land {
224 entry: Option<usize>,
226 #[arg(short, long)]
228 force: bool,
229 #[arg(short, long)]
231 dry_run: bool,
232 #[arg(long)]
234 auto: bool,
235 #[arg(long)]
237 wait_for_builds: bool,
238 #[arg(long, value_enum, default_value = "squash")]
240 strategy: Option<MergeStrategyArg>,
241 #[arg(long, default_value = "1800")]
243 build_timeout: u64,
244 },
245
246 AutoLand {
248 #[arg(short, long)]
250 force: bool,
251 #[arg(short, long)]
253 dry_run: bool,
254 #[arg(long)]
256 wait_for_builds: bool,
257 #[arg(long, value_enum, default_value = "squash")]
259 strategy: Option<MergeStrategyArg>,
260 #[arg(long, default_value = "1800")]
262 build_timeout: u64,
263 },
264
265 ListPrs {
267 #[arg(short, long)]
269 state: Option<String>,
270 #[arg(short, long)]
272 verbose: bool,
273 },
274
275 ContinueLand,
277
278 AbortLand,
280
281 LandStatus,
283}
284
285pub async fn run(action: StackAction) -> Result<()> {
286 match action {
287 StackAction::Create {
288 name,
289 base,
290 description,
291 } => create_stack(name, base, description).await,
292 StackAction::List {
293 verbose,
294 active,
295 format,
296 } => list_stacks(verbose, active, format).await,
297 StackAction::Switch { name } => switch_stack(name).await,
298 StackAction::Deactivate { force } => deactivate_stack(force).await,
299 StackAction::Show { verbose, mergeable } => show_stack(verbose, mergeable).await,
300 StackAction::Push {
301 branch,
302 message,
303 commit,
304 since,
305 commits,
306 squash,
307 squash_since,
308 auto_branch,
309 allow_base_branch,
310 } => {
311 push_to_stack(
312 branch,
313 message,
314 commit,
315 since,
316 commits,
317 squash,
318 squash_since,
319 auto_branch,
320 allow_base_branch,
321 )
322 .await
323 }
324 StackAction::Pop { keep_branch } => pop_from_stack(keep_branch).await,
325 StackAction::Submit {
326 entry,
327 title,
328 description,
329 range,
330 draft,
331 } => submit_entry(entry, title, description, range, draft).await,
332 StackAction::Status { name } => check_stack_status(name).await,
333 StackAction::Prs { state, verbose } => list_pull_requests(state, verbose).await,
334 StackAction::Check { force } => check_stack(force).await,
335 StackAction::Sync {
336 force,
337 skip_cleanup,
338 interactive,
339 } => sync_stack(force, skip_cleanup, interactive).await,
340 StackAction::Rebase {
341 interactive,
342 onto,
343 strategy,
344 } => rebase_stack(interactive, onto, strategy).await,
345 StackAction::ContinueRebase => continue_rebase().await,
346 StackAction::AbortRebase => abort_rebase().await,
347 StackAction::RebaseStatus => rebase_status().await,
348 StackAction::Delete { name, force } => delete_stack(name, force).await,
349 StackAction::Validate { name } => validate_stack(name).await,
350 StackAction::Land {
351 entry,
352 force,
353 dry_run,
354 auto,
355 wait_for_builds,
356 strategy,
357 build_timeout,
358 } => {
359 land_stack(
360 entry,
361 force,
362 dry_run,
363 auto,
364 wait_for_builds,
365 strategy,
366 build_timeout,
367 )
368 .await
369 }
370 StackAction::AutoLand {
371 force,
372 dry_run,
373 wait_for_builds,
374 strategy,
375 build_timeout,
376 } => auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await,
377 StackAction::ListPrs { state, verbose } => list_pull_requests(state, verbose).await,
378 StackAction::ContinueLand => continue_land().await,
379 StackAction::AbortLand => abort_land().await,
380 StackAction::LandStatus => land_status().await,
381 }
382}
383
384pub async fn show(verbose: bool, mergeable: bool) -> Result<()> {
386 show_stack(verbose, mergeable).await
387}
388
389#[allow(clippy::too_many_arguments)]
390pub async fn push(
391 branch: Option<String>,
392 message: Option<String>,
393 commit: Option<String>,
394 since: Option<String>,
395 commits: Option<String>,
396 squash: Option<usize>,
397 squash_since: Option<String>,
398 auto_branch: bool,
399 allow_base_branch: bool,
400) -> Result<()> {
401 push_to_stack(
402 branch,
403 message,
404 commit,
405 since,
406 commits,
407 squash,
408 squash_since,
409 auto_branch,
410 allow_base_branch,
411 )
412 .await
413}
414
415pub async fn pop(keep_branch: bool) -> Result<()> {
416 pop_from_stack(keep_branch).await
417}
418
419pub async fn land(
420 entry: Option<usize>,
421 force: bool,
422 dry_run: bool,
423 auto: bool,
424 wait_for_builds: bool,
425 strategy: Option<MergeStrategyArg>,
426 build_timeout: u64,
427) -> Result<()> {
428 land_stack(
429 entry,
430 force,
431 dry_run,
432 auto,
433 wait_for_builds,
434 strategy,
435 build_timeout,
436 )
437 .await
438}
439
440pub async fn autoland(
441 force: bool,
442 dry_run: bool,
443 wait_for_builds: bool,
444 strategy: Option<MergeStrategyArg>,
445 build_timeout: u64,
446) -> Result<()> {
447 auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await
448}
449
450pub async fn sync(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
451 sync_stack(force, skip_cleanup, interactive).await
452}
453
454pub async fn rebase(
455 interactive: bool,
456 onto: Option<String>,
457 strategy: Option<RebaseStrategyArg>,
458) -> Result<()> {
459 rebase_stack(interactive, onto, strategy).await
460}
461
462pub async fn deactivate(force: bool) -> Result<()> {
463 deactivate_stack(force).await
464}
465
466pub async fn switch(name: String) -> Result<()> {
467 switch_stack(name).await
468}
469
470async fn create_stack(
471 name: String,
472 base: Option<String>,
473 description: Option<String>,
474) -> Result<()> {
475 let current_dir = env::current_dir()
476 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
477
478 let repo_root = find_repository_root(¤t_dir)
479 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
480
481 let mut manager = StackManager::new(&repo_root)?;
482 let stack_id = manager.create_stack(name.clone(), base.clone(), description.clone())?;
483
484 info!("✅ Created stack '{}'", name);
485 if let Some(base_branch) = base {
486 info!(" Base branch: {}", base_branch);
487 }
488 if let Some(desc) = description {
489 info!(" Description: {}", desc);
490 }
491 info!(" Stack ID: {}", stack_id);
492 info!(" Stack is now active");
493
494 Ok(())
495}
496
497async fn list_stacks(verbose: bool, _active: bool, _format: Option<String>) -> Result<()> {
498 let current_dir = env::current_dir()
499 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
500
501 let repo_root = find_repository_root(¤t_dir)
502 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
503
504 let manager = StackManager::new(&repo_root)?;
505 let stacks = manager.list_stacks();
506
507 if stacks.is_empty() {
508 info!("No stacks found. Create one with: ca stack create <name>");
509 return Ok(());
510 }
511
512 println!("📚 Stacks:");
513 for (stack_id, name, status, entry_count, active_marker) in stacks {
514 let status_icon = match status {
515 StackStatus::Clean => "✅",
516 StackStatus::Dirty => "🔄",
517 StackStatus::OutOfSync => "⚠️",
518 StackStatus::Conflicted => "❌",
519 StackStatus::Rebasing => "🔀",
520 StackStatus::NeedsSync => "🔄",
521 StackStatus::Corrupted => "💥",
522 };
523
524 let active_indicator = if active_marker.is_some() {
525 " (active)"
526 } else {
527 ""
528 };
529
530 if verbose {
531 println!(" {status_icon} {name} [{entry_count}]{active_indicator}");
532 println!(" ID: {stack_id}");
533 if let Some(stack_meta) = manager.get_stack_metadata(&stack_id) {
534 println!(" Base: {}", stack_meta.base_branch);
535 if let Some(desc) = &stack_meta.description {
536 println!(" Description: {desc}");
537 }
538 println!(
539 " Commits: {} total, {} submitted",
540 stack_meta.total_commits, stack_meta.submitted_commits
541 );
542 if stack_meta.has_conflicts {
543 println!(" ⚠️ Has conflicts");
544 }
545 }
546 println!();
547 } else {
548 println!(" {status_icon} {name} [{entry_count}]{active_indicator}");
549 }
550 }
551
552 if !verbose {
553 println!("\nUse --verbose for more details");
554 }
555
556 Ok(())
557}
558
559async fn switch_stack(name: String) -> Result<()> {
560 let current_dir = env::current_dir()
561 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
562
563 let repo_root = find_repository_root(¤t_dir)
564 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
565
566 let mut manager = StackManager::new(&repo_root)?;
567
568 if manager.get_stack_by_name(&name).is_none() {
570 return Err(CascadeError::config(format!("Stack '{name}' not found")));
571 }
572
573 manager.set_active_stack_by_name(&name)?;
574 info!("✅ Switched to stack '{}'", name);
575
576 Ok(())
577}
578
579async fn deactivate_stack(force: bool) -> Result<()> {
580 let current_dir = env::current_dir()
581 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
582
583 let repo_root = find_repository_root(¤t_dir)
584 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
585
586 let mut manager = StackManager::new(&repo_root)?;
587
588 let active_stack = manager.get_active_stack();
589
590 if active_stack.is_none() {
591 println!("ℹ️ No active stack to deactivate");
592 return Ok(());
593 }
594
595 let stack_name = active_stack.unwrap().name.clone();
596
597 if !force {
598 println!("⚠️ This will deactivate stack '{stack_name}' and return to normal Git workflow");
599 println!(" You can reactivate it later with 'ca stacks switch {stack_name}'");
600 print!(" Continue? (y/N): ");
601
602 use std::io::{self, Write};
603 io::stdout().flush().unwrap();
604
605 let mut input = String::new();
606 io::stdin().read_line(&mut input).unwrap();
607
608 if !input.trim().to_lowercase().starts_with('y') {
609 println!("Cancelled deactivation");
610 return Ok(());
611 }
612 }
613
614 manager.set_active_stack(None)?;
616
617 println!("✅ Deactivated stack '{stack_name}'");
618 println!(" Stack management is now OFF - you can use normal Git workflow");
619 println!(" To reactivate: ca stacks switch {stack_name}");
620
621 Ok(())
622}
623
624async fn show_stack(verbose: bool, show_mergeable: bool) -> Result<()> {
625 let current_dir = env::current_dir()
626 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
627
628 let repo_root = find_repository_root(¤t_dir)
629 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
630
631 let stack_manager = StackManager::new(&repo_root)?;
632
633 let (stack_id, stack_name, stack_base, stack_entries) = {
635 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
636 CascadeError::config(
637 "No active stack. Use 'ca stacks create' or 'ca stacks switch' to select a stack"
638 .to_string(),
639 )
640 })?;
641
642 (
643 active_stack.id,
644 active_stack.name.clone(),
645 active_stack.base_branch.clone(),
646 active_stack.entries.clone(),
647 )
648 };
649
650 println!("📊 Stack: {stack_name}");
651 println!(" Base branch: {stack_base}");
652 println!(" Total entries: {}", stack_entries.len());
653
654 if stack_entries.is_empty() {
655 println!(" No entries in this stack yet");
656 println!(" Use 'ca push' to add commits to this stack");
657 return Ok(());
658 }
659
660 println!("\n📚 Stack Entries:");
662 for (i, entry) in stack_entries.iter().enumerate() {
663 let entry_num = i + 1;
664 let short_hash = entry.short_hash();
665 let short_msg = entry.short_message(50);
666
667 let metadata = stack_manager.get_repository_metadata();
669 let source_branch_info = if let Some(commit_meta) = metadata.get_commit(&entry.commit_hash)
670 {
671 if commit_meta.source_branch != commit_meta.branch
672 && !commit_meta.source_branch.is_empty()
673 {
674 format!(" (from {})", commit_meta.source_branch)
675 } else {
676 String::new()
677 }
678 } else {
679 String::new()
680 };
681
682 println!(
683 " {entry_num}. {} {} {}{}",
684 short_hash,
685 if entry.is_submitted { "📤" } else { "📝" },
686 short_msg,
687 source_branch_info
688 );
689
690 if verbose {
691 println!(" Branch: {}", entry.branch);
692 println!(
693 " Created: {}",
694 entry.created_at.format("%Y-%m-%d %H:%M")
695 );
696 if let Some(pr_id) = &entry.pull_request_id {
697 println!(" PR: #{pr_id}");
698 }
699 }
700 }
701
702 if show_mergeable {
704 println!("\n🔍 Mergability Status:");
705
706 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
708 let config_path = config_dir.join("config.json");
709 let settings = crate::config::Settings::load_from_file(&config_path)?;
710
711 let cascade_config = crate::config::CascadeConfig {
712 bitbucket: Some(settings.bitbucket.clone()),
713 git: settings.git.clone(),
714 auth: crate::config::AuthConfig::default(),
715 };
716
717 let integration =
718 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
719
720 match integration.check_enhanced_stack_status(&stack_id).await {
721 Ok(status) => {
722 println!(" Total entries: {}", status.total_entries);
723 println!(" Submitted: {}", status.submitted_entries);
724 println!(" Open PRs: {}", status.open_prs);
725 println!(" Merged PRs: {}", status.merged_prs);
726 println!(" Declined PRs: {}", status.declined_prs);
727 println!(" Completion: {:.1}%", status.completion_percentage());
728
729 if !status.enhanced_statuses.is_empty() {
730 println!("\n📋 Pull Request Status:");
731 let mut ready_to_land = 0;
732
733 for enhanced in &status.enhanced_statuses {
734 let status_display = enhanced.get_display_status();
735 let ready_icon = if enhanced.is_ready_to_land() {
736 ready_to_land += 1;
737 "🚀"
738 } else {
739 "⏳"
740 };
741
742 println!(
743 " {} PR #{}: {} ({})",
744 ready_icon, enhanced.pr.id, enhanced.pr.title, status_display
745 );
746
747 if verbose {
748 println!(
749 " {} -> {}",
750 enhanced.pr.from_ref.display_id, enhanced.pr.to_ref.display_id
751 );
752
753 if !enhanced.is_ready_to_land() {
755 let blocking = enhanced.get_blocking_reasons();
756 if !blocking.is_empty() {
757 println!(" Blocking: {}", blocking.join(", "));
758 }
759 }
760
761 println!(
763 " Reviews: {}/{} approvals",
764 enhanced.review_status.current_approvals,
765 enhanced.review_status.required_approvals
766 );
767
768 if enhanced.review_status.needs_work_count > 0 {
769 println!(
770 " {} reviewers requested changes",
771 enhanced.review_status.needs_work_count
772 );
773 }
774
775 if let Some(build) = &enhanced.build_status {
777 let build_icon = match build.state {
778 crate::bitbucket::pull_request::BuildState::Successful => "✅",
779 crate::bitbucket::pull_request::BuildState::Failed => "❌",
780 crate::bitbucket::pull_request::BuildState::InProgress => "🔄",
781 _ => "⚪",
782 };
783 println!(" Build: {} {:?}", build_icon, build.state);
784 }
785
786 if let Some(url) = enhanced.pr.web_url() {
787 println!(" URL: {url}");
788 }
789 println!();
790 }
791 }
792
793 if ready_to_land > 0 {
794 println!(
795 "\n🎯 {} PR{} ready to land! Use 'ca land' to land them all.",
796 ready_to_land,
797 if ready_to_land == 1 { " is" } else { "s are" }
798 );
799 }
800 }
801 }
802 Err(e) => {
803 warn!("Failed to get enhanced stack status: {}", e);
804 println!(" ⚠️ Could not fetch mergability status");
805 println!(" Use 'ca stack show --verbose' for basic PR information");
806 }
807 }
808 } else {
809 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
811 let config_path = config_dir.join("config.json");
812 let settings = crate::config::Settings::load_from_file(&config_path)?;
813
814 let cascade_config = crate::config::CascadeConfig {
815 bitbucket: Some(settings.bitbucket.clone()),
816 git: settings.git.clone(),
817 auth: crate::config::AuthConfig::default(),
818 };
819
820 let integration =
821 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
822
823 match integration.check_stack_status(&stack_id).await {
824 Ok(status) => {
825 println!("\n📊 Pull Request Status:");
826 println!(" Total entries: {}", status.total_entries);
827 println!(" Submitted: {}", status.submitted_entries);
828 println!(" Open PRs: {}", status.open_prs);
829 println!(" Merged PRs: {}", status.merged_prs);
830 println!(" Declined PRs: {}", status.declined_prs);
831 println!(" Completion: {:.1}%", status.completion_percentage());
832
833 if !status.pull_requests.is_empty() {
834 println!("\n📋 Pull Requests:");
835 for pr in &status.pull_requests {
836 let state_icon = match pr.state {
837 crate::bitbucket::PullRequestState::Open => "🔄",
838 crate::bitbucket::PullRequestState::Merged => "✅",
839 crate::bitbucket::PullRequestState::Declined => "❌",
840 };
841 println!(
842 " {} PR #{}: {} ({} -> {})",
843 state_icon,
844 pr.id,
845 pr.title,
846 pr.from_ref.display_id,
847 pr.to_ref.display_id
848 );
849 if let Some(url) = pr.web_url() {
850 println!(" URL: {url}");
851 }
852 }
853 }
854
855 println!("\n💡 Use 'ca stack show --mergeable' to see detailed status including build and review information");
856 }
857 Err(e) => {
858 warn!("Failed to check stack status: {}", e);
859 }
860 }
861 }
862
863 Ok(())
864}
865
866#[allow(clippy::too_many_arguments)]
867async fn push_to_stack(
868 branch: Option<String>,
869 message: Option<String>,
870 commit: Option<String>,
871 since: Option<String>,
872 commits: Option<String>,
873 squash: Option<usize>,
874 squash_since: Option<String>,
875 auto_branch: bool,
876 allow_base_branch: bool,
877) -> Result<()> {
878 let current_dir = env::current_dir()
879 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
880
881 let repo_root = find_repository_root(¤t_dir)
882 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
883
884 let mut manager = StackManager::new(&repo_root)?;
885 let repo = GitRepository::open(&repo_root)?;
886
887 if !manager.check_for_branch_change()? {
889 return Ok(()); }
891
892 let active_stack = manager.get_active_stack().ok_or_else(|| {
894 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
895 })?;
896
897 let current_branch = repo.get_current_branch()?;
899 let base_branch = &active_stack.base_branch;
900
901 if current_branch == *base_branch {
902 println!("🚨 WARNING: You're currently on the base branch '{base_branch}'");
903 println!(" Making commits directly on the base branch is not recommended.");
904 println!(" This can pollute the base branch with work-in-progress commits.");
905
906 if allow_base_branch {
908 println!(" ⚠️ Proceeding anyway due to --allow-base-branch flag");
909 } else {
910 let has_changes = repo.is_dirty()?;
912
913 if has_changes {
914 if auto_branch {
915 let feature_branch = format!("feature/{}-work", active_stack.name);
917 println!("🚀 Auto-creating feature branch '{feature_branch}'...");
918
919 repo.create_branch(&feature_branch, None)?;
920 repo.checkout_branch(&feature_branch)?;
921
922 println!("✅ Created and switched to '{feature_branch}'");
923 println!(" You can now commit and push your changes safely");
924
925 } else {
927 println!("\n💡 You have uncommitted changes. Here are your options:");
928 println!(" 1. Create a feature branch first:");
929 println!(" git checkout -b feature/my-work");
930 println!(" git commit -am \"your work\"");
931 println!(" ca push");
932 println!("\n 2. Auto-create a branch (recommended):");
933 println!(" ca push --auto-branch");
934 println!("\n 3. Force push to base branch (dangerous):");
935 println!(" ca push --allow-base-branch");
936
937 return Err(CascadeError::config(
938 "Refusing to push uncommitted changes from base branch. Use one of the options above."
939 ));
940 }
941 } else {
942 let commits_to_check = if let Some(commits_str) = &commits {
944 commits_str
945 .split(',')
946 .map(|s| s.trim().to_string())
947 .collect::<Vec<String>>()
948 } else if let Some(since_ref) = &since {
949 let since_commit = repo.resolve_reference(since_ref)?;
950 let head_commit = repo.get_head_commit()?;
951 let commits = repo.get_commits_between(
952 &since_commit.id().to_string(),
953 &head_commit.id().to_string(),
954 )?;
955 commits.into_iter().map(|c| c.id().to_string()).collect()
956 } else if commit.is_none() {
957 let mut unpushed = Vec::new();
958 let head_commit = repo.get_head_commit()?;
959 let mut current_commit = head_commit;
960
961 loop {
962 let commit_hash = current_commit.id().to_string();
963 let already_in_stack = active_stack
964 .entries
965 .iter()
966 .any(|entry| entry.commit_hash == commit_hash);
967
968 if already_in_stack {
969 break;
970 }
971
972 unpushed.push(commit_hash);
973
974 if let Some(parent) = current_commit.parents().next() {
975 current_commit = parent;
976 } else {
977 break;
978 }
979 }
980
981 unpushed.reverse();
982 unpushed
983 } else {
984 vec![repo.get_head_commit()?.id().to_string()]
985 };
986
987 if !commits_to_check.is_empty() {
988 if auto_branch {
989 let feature_branch = format!("feature/{}-work", active_stack.name);
991 println!("🚀 Auto-creating feature branch '{feature_branch}'...");
992
993 repo.create_branch(&feature_branch, Some(base_branch))?;
994 repo.checkout_branch(&feature_branch)?;
995
996 println!(
998 "🍒 Cherry-picking {} commit(s) to new branch...",
999 commits_to_check.len()
1000 );
1001 for commit_hash in &commits_to_check {
1002 match repo.cherry_pick(commit_hash) {
1003 Ok(_) => println!(" ✅ Cherry-picked {}", &commit_hash[..8]),
1004 Err(e) => {
1005 println!(
1006 " ❌ Failed to cherry-pick {}: {}",
1007 &commit_hash[..8],
1008 e
1009 );
1010 println!(" 💡 You may need to resolve conflicts manually");
1011 return Err(CascadeError::branch(format!(
1012 "Failed to cherry-pick commit {commit_hash}: {e}"
1013 )));
1014 }
1015 }
1016 }
1017
1018 println!(
1019 "✅ Successfully moved {} commit(s) to '{feature_branch}'",
1020 commits_to_check.len()
1021 );
1022 println!(
1023 " You're now on the feature branch and can continue with 'ca push'"
1024 );
1025
1026 } else {
1028 println!(
1029 "\n💡 Found {} commit(s) to push from base branch '{base_branch}'",
1030 commits_to_check.len()
1031 );
1032 println!(" These commits are currently ON the base branch, which may not be intended.");
1033 println!("\n Options:");
1034 println!(" 1. Auto-create feature branch and cherry-pick commits:");
1035 println!(" ca push --auto-branch");
1036 println!("\n 2. Manually create branch and move commits:");
1037 println!(" git checkout -b feature/my-work");
1038 println!(" ca push");
1039 println!("\n 3. Force push from base branch (not recommended):");
1040 println!(" ca push --allow-base-branch");
1041
1042 return Err(CascadeError::config(
1043 "Refusing to push commits from base branch. Use --auto-branch or create a feature branch manually."
1044 ));
1045 }
1046 }
1047 }
1048 }
1049 }
1050
1051 if let Some(squash_count) = squash {
1053 if squash_count == 0 {
1054 let active_stack = manager.get_active_stack().ok_or_else(|| {
1056 CascadeError::config(
1057 "No active stack. Create a stack first with 'ca stacks create'",
1058 )
1059 })?;
1060
1061 let unpushed_count = get_unpushed_commits(&repo, active_stack)?.len();
1062
1063 if unpushed_count == 0 {
1064 println!("ℹ️ No unpushed commits to squash");
1065 } else if unpushed_count == 1 {
1066 println!("ℹ️ Only 1 unpushed commit, no squashing needed");
1067 } else {
1068 println!("🔄 Auto-detected {unpushed_count} unpushed commits, squashing...");
1069 squash_commits(&repo, unpushed_count, None).await?;
1070 println!("✅ Squashed {unpushed_count} unpushed commits into one");
1071 }
1072 } else {
1073 println!("🔄 Squashing last {squash_count} commits...");
1074 squash_commits(&repo, squash_count, None).await?;
1075 println!("✅ Squashed {squash_count} commits into one");
1076 }
1077 } else if let Some(since_ref) = squash_since {
1078 println!("🔄 Squashing commits since {since_ref}...");
1079 let since_commit = repo.resolve_reference(&since_ref)?;
1080 let commits_count = count_commits_since(&repo, &since_commit.id().to_string())?;
1081 squash_commits(&repo, commits_count, Some(since_ref.clone())).await?;
1082 println!("✅ Squashed {commits_count} commits since {since_ref} into one");
1083 }
1084
1085 let commits_to_push = if let Some(commits_str) = commits {
1087 commits_str
1089 .split(',')
1090 .map(|s| s.trim().to_string())
1091 .collect::<Vec<String>>()
1092 } else if let Some(since_ref) = since {
1093 let since_commit = repo.resolve_reference(&since_ref)?;
1095 let head_commit = repo.get_head_commit()?;
1096
1097 let commits = repo.get_commits_between(
1099 &since_commit.id().to_string(),
1100 &head_commit.id().to_string(),
1101 )?;
1102 commits.into_iter().map(|c| c.id().to_string()).collect()
1103 } else if let Some(hash) = commit {
1104 vec![hash]
1106 } else {
1107 let active_stack = manager.get_active_stack().ok_or_else(|| {
1109 CascadeError::config("No active stack. Create a stack first with 'ca stacks create'")
1110 })?;
1111
1112 let base_branch = &active_stack.base_branch;
1114 let current_branch = repo.get_current_branch()?;
1115
1116 if current_branch == *base_branch {
1118 let mut unpushed = Vec::new();
1119 let head_commit = repo.get_head_commit()?;
1120 let mut current_commit = head_commit;
1121
1122 loop {
1124 let commit_hash = current_commit.id().to_string();
1125 let already_in_stack = active_stack
1126 .entries
1127 .iter()
1128 .any(|entry| entry.commit_hash == commit_hash);
1129
1130 if already_in_stack {
1131 break;
1132 }
1133
1134 unpushed.push(commit_hash);
1135
1136 if let Some(parent) = current_commit.parents().next() {
1138 current_commit = parent;
1139 } else {
1140 break;
1141 }
1142 }
1143
1144 unpushed.reverse(); unpushed
1146 } else {
1147 match repo.get_commits_between(base_branch, ¤t_branch) {
1149 Ok(commits) => {
1150 let mut unpushed: Vec<String> =
1151 commits.into_iter().map(|c| c.id().to_string()).collect();
1152
1153 unpushed.retain(|commit_hash| {
1155 !active_stack
1156 .entries
1157 .iter()
1158 .any(|entry| entry.commit_hash == *commit_hash)
1159 });
1160
1161 unpushed.reverse(); unpushed
1163 }
1164 Err(e) => {
1165 return Err(CascadeError::branch(format!(
1166 "Failed to calculate commits between '{base_branch}' and '{current_branch}': {e}. \
1167 This usually means the branches have diverged or don't share common history."
1168 )));
1169 }
1170 }
1171 }
1172 };
1173
1174 if commits_to_push.is_empty() {
1175 println!("ℹ️ No commits to push to stack");
1176 return Ok(());
1177 }
1178
1179 let mut pushed_count = 0;
1181 let mut source_branches = std::collections::HashSet::new();
1182
1183 for (i, commit_hash) in commits_to_push.iter().enumerate() {
1184 let commit_obj = repo.get_commit(commit_hash)?;
1185 let commit_msg = commit_obj.message().unwrap_or("").to_string();
1186
1187 let commit_source_branch = repo
1189 .find_branch_containing_commit(commit_hash)
1190 .unwrap_or_else(|_| current_branch.clone());
1191 source_branches.insert(commit_source_branch.clone());
1192
1193 let branch_name = if i == 0 && branch.is_some() {
1195 branch.clone().unwrap()
1196 } else {
1197 let temp_repo = GitRepository::open(&repo_root)?;
1199 let branch_mgr = crate::git::BranchManager::new(temp_repo);
1200 branch_mgr.generate_branch_name(&commit_msg)
1201 };
1202
1203 let final_message = if i == 0 && message.is_some() {
1205 message.clone().unwrap()
1206 } else {
1207 commit_msg.clone()
1208 };
1209
1210 let entry_id = manager.push_to_stack(
1211 branch_name.clone(),
1212 commit_hash.clone(),
1213 final_message.clone(),
1214 commit_source_branch.clone(),
1215 )?;
1216 pushed_count += 1;
1217
1218 println!(
1219 "✅ Pushed commit {}/{} to stack",
1220 i + 1,
1221 commits_to_push.len()
1222 );
1223 println!(
1224 " Commit: {} ({})",
1225 &commit_hash[..8],
1226 commit_msg.split('\n').next().unwrap_or("")
1227 );
1228 println!(" Branch: {branch_name}");
1229 println!(" Source: {commit_source_branch}");
1230 println!(" Entry ID: {entry_id}");
1231 println!();
1232 }
1233
1234 if source_branches.len() > 1 {
1236 println!("⚠️ WARNING: Scattered Commit Detection");
1237 println!(
1238 " You've pushed commits from {} different Git branches:",
1239 source_branches.len()
1240 );
1241 for branch in &source_branches {
1242 println!(" • {branch}");
1243 }
1244 println!();
1245 println!(" This can lead to confusion because:");
1246 println!(" • Stack appears sequential but commits are scattered across branches");
1247 println!(" • Team members won't know which branch contains which work");
1248 println!(" • Branch cleanup becomes unclear after merge");
1249 println!(" • Rebase operations become more complex");
1250 println!();
1251 println!(" 💡 Consider consolidating work to a single feature branch:");
1252 println!(" 1. Create a new feature branch: git checkout -b feature/consolidated-work");
1253 println!(" 2. Cherry-pick commits in order: git cherry-pick <commit1> <commit2> ...");
1254 println!(" 3. Delete old scattered branches");
1255 println!(" 4. Push the consolidated branch to your stack");
1256 println!();
1257 }
1258
1259 println!(
1260 "🎉 Successfully pushed {} commit{} to stack",
1261 pushed_count,
1262 if pushed_count == 1 { "" } else { "s" }
1263 );
1264
1265 Ok(())
1266}
1267
1268async fn pop_from_stack(keep_branch: bool) -> Result<()> {
1269 let current_dir = env::current_dir()
1270 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1271
1272 let repo_root = find_repository_root(¤t_dir)
1273 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1274
1275 let mut manager = StackManager::new(&repo_root)?;
1276 let repo = GitRepository::open(&repo_root)?;
1277
1278 let entry = manager.pop_from_stack()?;
1279
1280 info!("✅ Popped commit from stack");
1281 info!(
1282 " Commit: {} ({})",
1283 entry.short_hash(),
1284 entry.short_message(50)
1285 );
1286 info!(" Branch: {}", entry.branch);
1287
1288 if !keep_branch && entry.branch != repo.get_current_branch()? {
1290 match repo.delete_branch(&entry.branch) {
1291 Ok(_) => info!(" Deleted branch: {}", entry.branch),
1292 Err(e) => warn!(" Could not delete branch {}: {}", entry.branch, e),
1293 }
1294 }
1295
1296 Ok(())
1297}
1298
1299async fn submit_entry(
1300 entry: Option<usize>,
1301 title: Option<String>,
1302 description: Option<String>,
1303 range: Option<String>,
1304 draft: bool,
1305) -> Result<()> {
1306 let current_dir = env::current_dir()
1307 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1308
1309 let repo_root = find_repository_root(¤t_dir)
1310 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1311
1312 let mut stack_manager = StackManager::new(&repo_root)?;
1313
1314 if !stack_manager.check_for_branch_change()? {
1316 return Ok(()); }
1318
1319 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1321 let config_path = config_dir.join("config.json");
1322 let settings = crate::config::Settings::load_from_file(&config_path)?;
1323
1324 let cascade_config = crate::config::CascadeConfig {
1326 bitbucket: Some(settings.bitbucket.clone()),
1327 git: settings.git.clone(),
1328 auth: crate::config::AuthConfig::default(),
1329 };
1330
1331 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1333 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1334 })?;
1335 let stack_id = active_stack.id;
1336
1337 let entries_to_submit = if let Some(range_str) = range {
1339 let mut entries = Vec::new();
1341
1342 if range_str.contains('-') {
1343 let parts: Vec<&str> = range_str.split('-').collect();
1345 if parts.len() != 2 {
1346 return Err(CascadeError::config(
1347 "Invalid range format. Use 'start-end' (e.g., '1-3')",
1348 ));
1349 }
1350
1351 let start: usize = parts[0]
1352 .parse()
1353 .map_err(|_| CascadeError::config("Invalid start number in range"))?;
1354 let end: usize = parts[1]
1355 .parse()
1356 .map_err(|_| CascadeError::config("Invalid end number in range"))?;
1357
1358 if start == 0
1359 || end == 0
1360 || start > active_stack.entries.len()
1361 || end > active_stack.entries.len()
1362 {
1363 return Err(CascadeError::config(format!(
1364 "Range out of bounds. Stack has {} entries",
1365 active_stack.entries.len()
1366 )));
1367 }
1368
1369 for i in start..=end {
1370 entries.push((i, active_stack.entries[i - 1].clone()));
1371 }
1372 } else {
1373 for entry_str in range_str.split(',') {
1375 let entry_num: usize = entry_str.trim().parse().map_err(|_| {
1376 CascadeError::config(format!("Invalid entry number: {entry_str}"))
1377 })?;
1378
1379 if entry_num == 0 || entry_num > active_stack.entries.len() {
1380 return Err(CascadeError::config(format!(
1381 "Entry {} out of bounds. Stack has {} entries",
1382 entry_num,
1383 active_stack.entries.len()
1384 )));
1385 }
1386
1387 entries.push((entry_num, active_stack.entries[entry_num - 1].clone()));
1388 }
1389 }
1390
1391 entries
1392 } else if let Some(entry_num) = entry {
1393 if entry_num == 0 || entry_num > active_stack.entries.len() {
1395 return Err(CascadeError::config(format!(
1396 "Invalid entry number: {}. Stack has {} entries",
1397 entry_num,
1398 active_stack.entries.len()
1399 )));
1400 }
1401 vec![(entry_num, active_stack.entries[entry_num - 1].clone())]
1402 } else {
1403 active_stack
1405 .entries
1406 .iter()
1407 .enumerate()
1408 .filter(|(_, entry)| !entry.is_submitted)
1409 .map(|(i, entry)| (i + 1, entry.clone())) .collect::<Vec<(usize, _)>>()
1411 };
1412
1413 if entries_to_submit.is_empty() {
1414 println!("ℹ️ No entries to submit");
1415 return Ok(());
1416 }
1417
1418 let total_operations = entries_to_submit.len() + 2; let pb = ProgressBar::new(total_operations as u64);
1421 pb.set_style(
1422 ProgressStyle::default_bar()
1423 .template("📤 {msg} [{bar:40.cyan/blue}] {pos}/{len}")
1424 .map_err(|e| CascadeError::config(format!("Progress bar template error: {e}")))?,
1425 );
1426
1427 pb.set_message("Connecting to Bitbucket");
1428 pb.inc(1);
1429
1430 let integration_stack_manager = StackManager::new(&repo_root)?;
1432 let mut integration =
1433 BitbucketIntegration::new(integration_stack_manager, cascade_config.clone())?;
1434
1435 pb.set_message("Starting batch submission");
1436 pb.inc(1);
1437
1438 let mut submitted_count = 0;
1440 let mut failed_entries = Vec::new();
1441 let total_entries = entries_to_submit.len();
1442
1443 for (entry_num, entry_to_submit) in &entries_to_submit {
1444 pb.set_message("Submitting entries...");
1445
1446 let entry_title = if total_entries == 1 {
1448 title.clone()
1449 } else {
1450 None
1451 };
1452 let entry_description = if total_entries == 1 {
1453 description.clone()
1454 } else {
1455 None
1456 };
1457
1458 match integration
1459 .submit_entry(
1460 &stack_id,
1461 &entry_to_submit.id,
1462 entry_title,
1463 entry_description,
1464 draft,
1465 )
1466 .await
1467 {
1468 Ok(pr) => {
1469 submitted_count += 1;
1470 println!("✅ Entry {} - PR #{}: {}", entry_num, pr.id, pr.title);
1471 if let Some(url) = pr.web_url() {
1472 println!(" URL: {url}");
1473 }
1474 println!(
1475 " From: {} -> {}",
1476 pr.from_ref.display_id, pr.to_ref.display_id
1477 );
1478 println!();
1479 }
1480 Err(e) => {
1481 failed_entries.push((*entry_num, e.to_string()));
1482 println!("❌ Entry {entry_num} failed: {e}");
1483 }
1484 }
1485
1486 pb.inc(1);
1487 }
1488
1489 if failed_entries.is_empty() {
1490 pb.finish_with_message("✅ All pull requests created successfully");
1491 println!(
1492 "🎉 Successfully submitted {} entr{}",
1493 submitted_count,
1494 if submitted_count == 1 { "y" } else { "ies" }
1495 );
1496 } else {
1497 pb.abandon_with_message("⚠️ Some submissions failed");
1498 println!("📊 Submission Summary:");
1499 println!(" ✅ Successful: {submitted_count}");
1500 println!(" ❌ Failed: {}", failed_entries.len());
1501 println!();
1502 println!("💡 Failed entries:");
1503 for (entry_num, error) in failed_entries {
1504 println!(" - Entry {entry_num}: {error}");
1505 }
1506 println!();
1507 println!("💡 You can retry failed entries individually:");
1508 println!(" ca stack submit <ENTRY_NUMBER>");
1509 }
1510
1511 Ok(())
1512}
1513
1514async fn check_stack_status(name: Option<String>) -> Result<()> {
1515 let current_dir = env::current_dir()
1516 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1517
1518 let repo_root = find_repository_root(¤t_dir)
1519 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1520
1521 let stack_manager = StackManager::new(&repo_root)?;
1522
1523 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1525 let config_path = config_dir.join("config.json");
1526 let settings = crate::config::Settings::load_from_file(&config_path)?;
1527
1528 let cascade_config = crate::config::CascadeConfig {
1530 bitbucket: Some(settings.bitbucket.clone()),
1531 git: settings.git.clone(),
1532 auth: crate::config::AuthConfig::default(),
1533 };
1534
1535 let stack = if let Some(name) = name {
1537 stack_manager
1538 .get_stack_by_name(&name)
1539 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?
1540 } else {
1541 stack_manager.get_active_stack().ok_or_else(|| {
1542 CascadeError::config("No active stack. Use 'ca stack list' to see available stacks")
1543 })?
1544 };
1545 let stack_id = stack.id;
1546
1547 println!("📋 Stack: {}", stack.name);
1548 println!(" ID: {}", stack.id);
1549 println!(" Base: {}", stack.base_branch);
1550
1551 if let Some(description) = &stack.description {
1552 println!(" Description: {description}");
1553 }
1554
1555 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1557
1558 match integration.check_stack_status(&stack_id).await {
1560 Ok(status) => {
1561 println!("\n📊 Pull Request Status:");
1562 println!(" Total entries: {}", status.total_entries);
1563 println!(" Submitted: {}", status.submitted_entries);
1564 println!(" Open PRs: {}", status.open_prs);
1565 println!(" Merged PRs: {}", status.merged_prs);
1566 println!(" Declined PRs: {}", status.declined_prs);
1567 println!(" Completion: {:.1}%", status.completion_percentage());
1568
1569 if !status.pull_requests.is_empty() {
1570 println!("\n📋 Pull Requests:");
1571 for pr in &status.pull_requests {
1572 let state_icon = match pr.state {
1573 crate::bitbucket::PullRequestState::Open => "🔄",
1574 crate::bitbucket::PullRequestState::Merged => "✅",
1575 crate::bitbucket::PullRequestState::Declined => "❌",
1576 };
1577 println!(
1578 " {} PR #{}: {} ({} -> {})",
1579 state_icon, pr.id, pr.title, pr.from_ref.display_id, pr.to_ref.display_id
1580 );
1581 if let Some(url) = pr.web_url() {
1582 println!(" URL: {url}");
1583 }
1584 }
1585 }
1586 }
1587 Err(e) => {
1588 warn!("Failed to check stack status: {}", e);
1589 return Err(e);
1590 }
1591 }
1592
1593 Ok(())
1594}
1595
1596async fn list_pull_requests(state: Option<String>, verbose: bool) -> Result<()> {
1597 let current_dir = env::current_dir()
1598 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1599
1600 let repo_root = find_repository_root(¤t_dir)
1601 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1602
1603 let stack_manager = StackManager::new(&repo_root)?;
1604
1605 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1607 let config_path = config_dir.join("config.json");
1608 let settings = crate::config::Settings::load_from_file(&config_path)?;
1609
1610 let cascade_config = crate::config::CascadeConfig {
1612 bitbucket: Some(settings.bitbucket.clone()),
1613 git: settings.git.clone(),
1614 auth: crate::config::AuthConfig::default(),
1615 };
1616
1617 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1619
1620 let pr_state = if let Some(state_str) = state {
1622 match state_str.to_lowercase().as_str() {
1623 "open" => Some(crate::bitbucket::PullRequestState::Open),
1624 "merged" => Some(crate::bitbucket::PullRequestState::Merged),
1625 "declined" => Some(crate::bitbucket::PullRequestState::Declined),
1626 _ => {
1627 return Err(CascadeError::config(format!(
1628 "Invalid state '{state_str}'. Use: open, merged, declined"
1629 )))
1630 }
1631 }
1632 } else {
1633 None
1634 };
1635
1636 match integration.list_pull_requests(pr_state).await {
1638 Ok(pr_page) => {
1639 if pr_page.values.is_empty() {
1640 info!("No pull requests found.");
1641 return Ok(());
1642 }
1643
1644 println!("📋 Pull Requests ({} total):", pr_page.values.len());
1645 for pr in &pr_page.values {
1646 let state_icon = match pr.state {
1647 crate::bitbucket::PullRequestState::Open => "🔄",
1648 crate::bitbucket::PullRequestState::Merged => "✅",
1649 crate::bitbucket::PullRequestState::Declined => "❌",
1650 };
1651 println!(" {} PR #{}: {}", state_icon, pr.id, pr.title);
1652 if verbose {
1653 println!(
1654 " From: {} -> {}",
1655 pr.from_ref.display_id, pr.to_ref.display_id
1656 );
1657 println!(" Author: {}", pr.author.user.display_name);
1658 if let Some(url) = pr.web_url() {
1659 println!(" URL: {url}");
1660 }
1661 if let Some(desc) = &pr.description {
1662 if !desc.is_empty() {
1663 println!(" Description: {desc}");
1664 }
1665 }
1666 println!();
1667 }
1668 }
1669
1670 if !verbose {
1671 println!("\nUse --verbose for more details");
1672 }
1673 }
1674 Err(e) => {
1675 warn!("Failed to list pull requests: {}", e);
1676 return Err(e);
1677 }
1678 }
1679
1680 Ok(())
1681}
1682
1683async fn check_stack(_force: bool) -> Result<()> {
1684 let current_dir = env::current_dir()
1685 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1686
1687 let repo_root = find_repository_root(¤t_dir)
1688 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1689
1690 let mut manager = StackManager::new(&repo_root)?;
1691
1692 let active_stack = manager
1693 .get_active_stack()
1694 .ok_or_else(|| CascadeError::config("No active stack"))?;
1695 let stack_id = active_stack.id;
1696
1697 manager.sync_stack(&stack_id)?;
1698
1699 info!("✅ Stack check completed successfully");
1700
1701 Ok(())
1702}
1703
1704async fn sync_stack(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
1705 let current_dir = env::current_dir()
1706 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1707
1708 let repo_root = find_repository_root(¤t_dir)
1709 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1710
1711 let stack_manager = StackManager::new(&repo_root)?;
1712 let git_repo = GitRepository::open(&repo_root)?;
1713
1714 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1716 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1717 })?;
1718
1719 let base_branch = active_stack.base_branch.clone();
1720 let stack_name = active_stack.name.clone();
1721
1722 println!("🔄 Syncing stack '{stack_name}' with remote...");
1723
1724 println!("📥 Pulling latest changes from '{base_branch}'...");
1726
1727 match git_repo.checkout_branch(&base_branch) {
1729 Ok(_) => {
1730 println!(" ✅ Switched to '{base_branch}'");
1731
1732 match git_repo.pull(&base_branch) {
1734 Ok(_) => {
1735 println!(" ✅ Successfully pulled latest changes");
1736 }
1737 Err(e) => {
1738 if force {
1739 println!(" ⚠️ Failed to pull: {e} (continuing due to --force)");
1740 } else {
1741 return Err(CascadeError::branch(format!(
1742 "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
1743 )));
1744 }
1745 }
1746 }
1747 }
1748 Err(e) => {
1749 if force {
1750 println!(
1751 " ⚠️ Failed to checkout '{base_branch}': {e} (continuing due to --force)"
1752 );
1753 } else {
1754 return Err(CascadeError::branch(format!(
1755 "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
1756 )));
1757 }
1758 }
1759 }
1760
1761 println!("🔍 Checking if stack needs rebase...");
1763
1764 let mut updated_stack_manager = StackManager::new(&repo_root)?;
1765 let stack_id = active_stack.id;
1766
1767 match updated_stack_manager.sync_stack(&stack_id) {
1768 Ok(_) => {
1769 if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
1771 match &updated_stack.status {
1772 crate::stack::StackStatus::NeedsSync => {
1773 println!(" 🔄 Stack needs rebase due to new commits on '{base_branch}'");
1774
1775 println!("🔀 Rebasing stack onto updated '{base_branch}'...");
1777
1778 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1780 let config_path = config_dir.join("config.json");
1781 let settings = crate::config::Settings::load_from_file(&config_path)?;
1782
1783 let cascade_config = crate::config::CascadeConfig {
1784 bitbucket: Some(settings.bitbucket.clone()),
1785 git: settings.git.clone(),
1786 auth: crate::config::AuthConfig::default(),
1787 };
1788
1789 let options = crate::stack::RebaseOptions {
1791 strategy: crate::stack::RebaseStrategy::BranchVersioning,
1792 interactive,
1793 target_base: Some(base_branch.clone()),
1794 preserve_merges: true,
1795 auto_resolve: !interactive,
1796 max_retries: 3,
1797 };
1798
1799 let mut rebase_manager = crate::stack::RebaseManager::new(
1800 updated_stack_manager,
1801 git_repo,
1802 options,
1803 );
1804
1805 match rebase_manager.rebase_stack(&stack_id) {
1806 Ok(result) => {
1807 println!(" ✅ Rebase completed successfully!");
1808
1809 if !result.branch_mapping.is_empty() {
1810 println!(" 📋 Updated branches:");
1811 for (old, new) in &result.branch_mapping {
1812 println!(" {old} → {new}");
1813 }
1814
1815 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
1817 println!(" 🔄 Updating pull requests...");
1818
1819 let integration_stack_manager =
1820 StackManager::new(&repo_root)?;
1821 let mut integration =
1822 crate::bitbucket::BitbucketIntegration::new(
1823 integration_stack_manager,
1824 cascade_config,
1825 )?;
1826
1827 match integration
1828 .update_prs_after_rebase(
1829 &stack_id,
1830 &result.branch_mapping,
1831 )
1832 .await
1833 {
1834 Ok(updated_prs) => {
1835 if !updated_prs.is_empty() {
1836 println!(
1837 " ✅ Updated {} pull requests",
1838 updated_prs.len()
1839 );
1840 }
1841 }
1842 Err(e) => {
1843 println!(
1844 " ⚠️ Failed to update pull requests: {e}"
1845 );
1846 }
1847 }
1848 }
1849 }
1850 }
1851 Err(e) => {
1852 println!(" ❌ Rebase failed: {e}");
1853 println!(" 💡 To resolve conflicts:");
1854 println!(" 1. Fix conflicts in the affected files");
1855 println!(" 2. Stage resolved files: git add <files>");
1856 println!(" 3. Continue: ca stack continue-rebase");
1857 return Err(e);
1858 }
1859 }
1860 }
1861 crate::stack::StackStatus::Clean => {
1862 println!(" ✅ Stack is already up to date");
1863 }
1864 other => {
1865 println!(" ℹ️ Stack status: {other:?}");
1866 }
1867 }
1868 }
1869 }
1870 Err(e) => {
1871 if force {
1872 println!(" ⚠️ Failed to check stack status: {e} (continuing due to --force)");
1873 } else {
1874 return Err(e);
1875 }
1876 }
1877 }
1878
1879 if !skip_cleanup {
1881 println!("🧹 Checking for merged branches to clean up...");
1882 println!(" ℹ️ Branch cleanup not yet implemented");
1888 } else {
1889 println!("⏭️ Skipping branch cleanup");
1890 }
1891
1892 println!("🎉 Sync completed successfully!");
1893 println!(" Base branch: {base_branch}");
1894 println!(" 💡 Next steps:");
1895 println!(" • Review your updated stack: ca stack show");
1896 println!(" • Check PR status: ca stack status");
1897
1898 Ok(())
1899}
1900
1901async fn rebase_stack(
1902 interactive: bool,
1903 onto: Option<String>,
1904 strategy: Option<RebaseStrategyArg>,
1905) -> Result<()> {
1906 let current_dir = env::current_dir()
1907 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1908
1909 let repo_root = find_repository_root(¤t_dir)
1910 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1911
1912 let stack_manager = StackManager::new(&repo_root)?;
1913 let git_repo = GitRepository::open(&repo_root)?;
1914
1915 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1917 let config_path = config_dir.join("config.json");
1918 let settings = crate::config::Settings::load_from_file(&config_path)?;
1919
1920 let cascade_config = crate::config::CascadeConfig {
1922 bitbucket: Some(settings.bitbucket.clone()),
1923 git: settings.git.clone(),
1924 auth: crate::config::AuthConfig::default(),
1925 };
1926
1927 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1929 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1930 })?;
1931 let stack_id = active_stack.id;
1932
1933 let active_stack = stack_manager
1934 .get_stack(&stack_id)
1935 .ok_or_else(|| CascadeError::config("Active stack not found"))?
1936 .clone();
1937
1938 if active_stack.entries.is_empty() {
1939 println!("ℹ️ Stack is empty. Nothing to rebase.");
1940 return Ok(());
1941 }
1942
1943 println!("🔄 Rebasing stack: {}", active_stack.name);
1944 println!(" Base: {}", active_stack.base_branch);
1945
1946 let rebase_strategy = if let Some(cli_strategy) = strategy {
1948 match cli_strategy {
1949 RebaseStrategyArg::BranchVersioning => crate::stack::RebaseStrategy::BranchVersioning,
1950 RebaseStrategyArg::CherryPick => crate::stack::RebaseStrategy::CherryPick,
1951 RebaseStrategyArg::ThreeWayMerge => crate::stack::RebaseStrategy::ThreeWayMerge,
1952 RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
1953 }
1954 } else {
1955 match settings.cascade.default_sync_strategy.as_str() {
1957 "branch-versioning" => crate::stack::RebaseStrategy::BranchVersioning,
1958 "cherry-pick" => crate::stack::RebaseStrategy::CherryPick,
1959 "three-way-merge" => crate::stack::RebaseStrategy::ThreeWayMerge,
1960 "rebase" => crate::stack::RebaseStrategy::Interactive,
1961 _ => crate::stack::RebaseStrategy::BranchVersioning, }
1963 };
1964
1965 let options = crate::stack::RebaseOptions {
1967 strategy: rebase_strategy.clone(),
1968 interactive,
1969 target_base: onto,
1970 preserve_merges: true,
1971 auto_resolve: !interactive, max_retries: 3,
1973 };
1974
1975 info!(" Strategy: {:?}", rebase_strategy);
1976 info!(" Interactive: {}", interactive);
1977 info!(" Target base: {:?}", options.target_base);
1978 info!(" Entries: {}", active_stack.entries.len());
1979
1980 let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
1982
1983 if rebase_manager.is_rebase_in_progress() {
1984 println!("⚠️ Rebase already in progress!");
1985 println!(" Use 'git status' to check the current state");
1986 println!(" Use 'ca stack continue-rebase' to continue");
1987 println!(" Use 'ca stack abort-rebase' to abort");
1988 return Ok(());
1989 }
1990
1991 match rebase_manager.rebase_stack(&stack_id) {
1993 Ok(result) => {
1994 println!("🎉 Rebase completed!");
1995 println!(" {}", result.get_summary());
1996
1997 if result.has_conflicts() {
1998 println!(" ⚠️ {} conflicts were resolved", result.conflicts.len());
1999 for conflict in &result.conflicts {
2000 println!(" - {}", &conflict[..8.min(conflict.len())]);
2001 }
2002 }
2003
2004 if !result.branch_mapping.is_empty() {
2005 println!(" 📋 Branch mapping:");
2006 for (old, new) in &result.branch_mapping {
2007 println!(" {old} -> {new}");
2008 }
2009
2010 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2012 let integration_stack_manager = StackManager::new(&repo_root)?;
2014 let mut integration = BitbucketIntegration::new(
2015 integration_stack_manager,
2016 cascade_config.clone(),
2017 )?;
2018
2019 match integration
2020 .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2021 .await
2022 {
2023 Ok(updated_prs) => {
2024 if !updated_prs.is_empty() {
2025 println!(" 🔄 Preserved pull request history:");
2026 for pr_update in updated_prs {
2027 println!(" ✅ {pr_update}");
2028 }
2029 }
2030 }
2031 Err(e) => {
2032 eprintln!(" ⚠️ Failed to update pull requests: {e}");
2033 eprintln!(" You may need to manually update PRs in Bitbucket");
2034 }
2035 }
2036 }
2037 }
2038
2039 println!(
2040 " ✅ {} commits successfully rebased",
2041 result.success_count()
2042 );
2043
2044 if matches!(
2046 rebase_strategy,
2047 crate::stack::RebaseStrategy::BranchVersioning
2048 ) {
2049 println!("\n📝 Next steps:");
2050 if !result.branch_mapping.is_empty() {
2051 println!(" 1. ✅ New versioned branches have been created");
2052 println!(" 2. ✅ Pull requests have been updated automatically");
2053 println!(" 3. 🔍 Review the updated PRs in Bitbucket");
2054 println!(" 4. 🧪 Test your changes on the new branches");
2055 println!(
2056 " 5. 🗑️ Old branches are preserved for safety (can be deleted later)"
2057 );
2058 } else {
2059 println!(" 1. Review the rebased stack");
2060 println!(" 2. Test your changes");
2061 println!(" 3. Submit new pull requests with 'ca stack submit'");
2062 }
2063 }
2064 }
2065 Err(e) => {
2066 warn!("❌ Rebase failed: {}", e);
2067 println!("💡 Tips for resolving rebase issues:");
2068 println!(" - Check for uncommitted changes with 'git status'");
2069 println!(" - Ensure base branch is up to date");
2070 println!(" - Try interactive mode: 'ca stack rebase --interactive'");
2071 return Err(e);
2072 }
2073 }
2074
2075 Ok(())
2076}
2077
2078async fn continue_rebase() -> Result<()> {
2079 let current_dir = env::current_dir()
2080 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2081
2082 let repo_root = find_repository_root(¤t_dir)
2083 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2084
2085 let stack_manager = StackManager::new(&repo_root)?;
2086 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2087 let options = crate::stack::RebaseOptions::default();
2088 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2089
2090 if !rebase_manager.is_rebase_in_progress() {
2091 println!("ℹ️ No rebase in progress");
2092 return Ok(());
2093 }
2094
2095 println!("🔄 Continuing rebase...");
2096 match rebase_manager.continue_rebase() {
2097 Ok(_) => {
2098 println!("✅ Rebase continued successfully");
2099 println!(" Check 'ca stack rebase-status' for current state");
2100 }
2101 Err(e) => {
2102 warn!("❌ Failed to continue rebase: {}", e);
2103 println!("💡 You may need to resolve conflicts first:");
2104 println!(" 1. Edit conflicted files");
2105 println!(" 2. Stage resolved files with 'git add'");
2106 println!(" 3. Run 'ca stack continue-rebase' again");
2107 }
2108 }
2109
2110 Ok(())
2111}
2112
2113async fn abort_rebase() -> Result<()> {
2114 let current_dir = env::current_dir()
2115 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2116
2117 let repo_root = find_repository_root(¤t_dir)
2118 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2119
2120 let stack_manager = StackManager::new(&repo_root)?;
2121 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2122 let options = crate::stack::RebaseOptions::default();
2123 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2124
2125 if !rebase_manager.is_rebase_in_progress() {
2126 println!("ℹ️ No rebase in progress");
2127 return Ok(());
2128 }
2129
2130 println!("⚠️ Aborting rebase...");
2131 match rebase_manager.abort_rebase() {
2132 Ok(_) => {
2133 println!("✅ Rebase aborted successfully");
2134 println!(" Repository restored to pre-rebase state");
2135 }
2136 Err(e) => {
2137 warn!("❌ Failed to abort rebase: {}", e);
2138 println!("⚠️ You may need to manually clean up the repository state");
2139 }
2140 }
2141
2142 Ok(())
2143}
2144
2145async fn rebase_status() -> Result<()> {
2146 let current_dir = env::current_dir()
2147 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2148
2149 let repo_root = find_repository_root(¤t_dir)
2150 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2151
2152 let stack_manager = StackManager::new(&repo_root)?;
2153 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2154
2155 println!("📊 Rebase Status");
2156
2157 let git_dir = current_dir.join(".git");
2159 let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
2160 || git_dir.join("rebase-merge").exists()
2161 || git_dir.join("rebase-apply").exists();
2162
2163 if rebase_in_progress {
2164 println!(" Status: 🔄 Rebase in progress");
2165 println!(
2166 "
2167📝 Actions available:"
2168 );
2169 println!(" - 'ca stack continue-rebase' to continue");
2170 println!(" - 'ca stack abort-rebase' to abort");
2171 println!(" - 'git status' to see conflicted files");
2172
2173 match git_repo.get_status() {
2175 Ok(statuses) => {
2176 let mut conflicts = Vec::new();
2177 for status in statuses.iter() {
2178 if status.status().contains(git2::Status::CONFLICTED) {
2179 if let Some(path) = status.path() {
2180 conflicts.push(path.to_string());
2181 }
2182 }
2183 }
2184
2185 if !conflicts.is_empty() {
2186 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
2187 for conflict in conflicts {
2188 println!(" - {conflict}");
2189 }
2190 println!(
2191 "
2192💡 To resolve conflicts:"
2193 );
2194 println!(" 1. Edit the conflicted files");
2195 println!(" 2. Stage resolved files: git add <file>");
2196 println!(" 3. Continue: ca stack continue-rebase");
2197 }
2198 }
2199 Err(e) => {
2200 warn!("Failed to get git status: {}", e);
2201 }
2202 }
2203 } else {
2204 println!(" Status: ✅ No rebase in progress");
2205
2206 if let Some(active_stack) = stack_manager.get_active_stack() {
2208 println!(" Active stack: {}", active_stack.name);
2209 println!(" Entries: {}", active_stack.entries.len());
2210 println!(" Base branch: {}", active_stack.base_branch);
2211 }
2212 }
2213
2214 Ok(())
2215}
2216
2217async fn delete_stack(name: String, force: bool) -> Result<()> {
2218 let current_dir = env::current_dir()
2219 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2220
2221 let repo_root = find_repository_root(¤t_dir)
2222 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2223
2224 let mut manager = StackManager::new(&repo_root)?;
2225
2226 let stack = manager
2227 .get_stack_by_name(&name)
2228 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2229 let stack_id = stack.id;
2230
2231 if !force && !stack.entries.is_empty() {
2232 return Err(CascadeError::config(format!(
2233 "Stack '{}' has {} entries. Use --force to delete anyway",
2234 name,
2235 stack.entries.len()
2236 )));
2237 }
2238
2239 let deleted = manager.delete_stack(&stack_id)?;
2240
2241 info!("✅ Deleted stack '{}'", deleted.name);
2242 if !deleted.entries.is_empty() {
2243 warn!(" {} entries were removed", deleted.entries.len());
2244 }
2245
2246 Ok(())
2247}
2248
2249async fn validate_stack(name: Option<String>) -> Result<()> {
2250 let current_dir = env::current_dir()
2251 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2252
2253 let repo_root = find_repository_root(¤t_dir)
2254 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2255
2256 let manager = StackManager::new(&repo_root)?;
2257
2258 if let Some(name) = name {
2259 let stack = manager
2261 .get_stack_by_name(&name)
2262 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2263
2264 match stack.validate() {
2265 Ok(_) => {
2266 println!("✅ Stack '{name}' validation passed");
2267 Ok(())
2268 }
2269 Err(e) => {
2270 println!("❌ Stack '{name}' validation failed: {e}");
2271 Err(CascadeError::config(e))
2272 }
2273 }
2274 } else {
2275 match manager.validate_all() {
2277 Ok(_) => {
2278 println!("✅ All stacks validation passed");
2279 Ok(())
2280 }
2281 Err(e) => {
2282 println!("❌ Stack validation failed: {e}");
2283 Err(e)
2284 }
2285 }
2286 }
2287}
2288
2289#[allow(dead_code)]
2291fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
2292 let mut unpushed = Vec::new();
2293 let head_commit = repo.get_head_commit()?;
2294 let mut current_commit = head_commit;
2295
2296 loop {
2298 let commit_hash = current_commit.id().to_string();
2299 let already_in_stack = stack
2300 .entries
2301 .iter()
2302 .any(|entry| entry.commit_hash == commit_hash);
2303
2304 if already_in_stack {
2305 break;
2306 }
2307
2308 unpushed.push(commit_hash);
2309
2310 if let Some(parent) = current_commit.parents().next() {
2312 current_commit = parent;
2313 } else {
2314 break;
2315 }
2316 }
2317
2318 unpushed.reverse(); Ok(unpushed)
2320}
2321
2322pub async fn squash_commits(
2324 repo: &GitRepository,
2325 count: usize,
2326 since_ref: Option<String>,
2327) -> Result<()> {
2328 if count <= 1 {
2329 return Ok(()); }
2331
2332 let _current_branch = repo.get_current_branch()?;
2334
2335 let rebase_range = if let Some(ref since) = since_ref {
2337 since.clone()
2338 } else {
2339 format!("HEAD~{count}")
2340 };
2341
2342 println!(" Analyzing {count} commits to create smart squash message...");
2343
2344 let head_commit = repo.get_head_commit()?;
2346 let mut commits_to_squash = Vec::new();
2347 let mut current = head_commit;
2348
2349 for _ in 0..count {
2351 commits_to_squash.push(current.clone());
2352 if current.parent_count() > 0 {
2353 current = current.parent(0).map_err(CascadeError::Git)?;
2354 } else {
2355 break;
2356 }
2357 }
2358
2359 let smart_message = generate_squash_message(&commits_to_squash)?;
2361 println!(
2362 " Smart message: {}",
2363 smart_message.lines().next().unwrap_or("")
2364 );
2365
2366 let reset_target = if since_ref.is_some() {
2368 format!("{rebase_range}~1")
2370 } else {
2371 format!("HEAD~{count}")
2373 };
2374
2375 repo.reset_soft(&reset_target)?;
2377
2378 repo.stage_all()?;
2380
2381 let new_commit_hash = repo.commit(&smart_message)?;
2383
2384 println!(
2385 " Created squashed commit: {} ({})",
2386 &new_commit_hash[..8],
2387 smart_message.lines().next().unwrap_or("")
2388 );
2389 println!(" 💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
2390
2391 Ok(())
2392}
2393
2394pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
2396 if commits.is_empty() {
2397 return Ok("Squashed commits".to_string());
2398 }
2399
2400 let messages: Vec<String> = commits
2402 .iter()
2403 .map(|c| c.message().unwrap_or("").trim().to_string())
2404 .filter(|m| !m.is_empty())
2405 .collect();
2406
2407 if messages.is_empty() {
2408 return Ok("Squashed commits".to_string());
2409 }
2410
2411 if let Some(last_msg) = messages.first() {
2413 if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
2415 return Ok(last_msg
2416 .trim_start_matches("Final:")
2417 .trim_start_matches("final:")
2418 .trim()
2419 .to_string());
2420 }
2421 }
2422
2423 let wip_count = messages
2425 .iter()
2426 .filter(|m| {
2427 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
2428 })
2429 .count();
2430
2431 if wip_count > messages.len() / 2 {
2432 let non_wip: Vec<&String> = messages
2434 .iter()
2435 .filter(|m| {
2436 !m.to_lowercase().starts_with("wip")
2437 && !m.to_lowercase().contains("work in progress")
2438 })
2439 .collect();
2440
2441 if let Some(best_msg) = non_wip.first() {
2442 return Ok(best_msg.to_string());
2443 }
2444
2445 let feature = extract_feature_from_wip(&messages);
2447 return Ok(feature);
2448 }
2449
2450 Ok(messages.first().unwrap().clone())
2452}
2453
2454pub fn extract_feature_from_wip(messages: &[String]) -> String {
2456 for msg in messages {
2458 if msg.to_lowercase().starts_with("wip:") {
2460 if let Some(rest) = msg
2461 .strip_prefix("WIP:")
2462 .or_else(|| msg.strip_prefix("wip:"))
2463 {
2464 let feature = rest.trim();
2465 if !feature.is_empty() && feature.len() > 3 {
2466 let mut chars: Vec<char> = feature.chars().collect();
2468 if let Some(first) = chars.first_mut() {
2469 *first = first.to_uppercase().next().unwrap_or(*first);
2470 }
2471 return chars.into_iter().collect();
2472 }
2473 }
2474 }
2475 }
2476
2477 if let Some(first) = messages.first() {
2479 let cleaned = first
2480 .trim_start_matches("WIP:")
2481 .trim_start_matches("wip:")
2482 .trim_start_matches("WIP")
2483 .trim_start_matches("wip")
2484 .trim();
2485
2486 if !cleaned.is_empty() {
2487 return format!("Implement {cleaned}");
2488 }
2489 }
2490
2491 format!("Squashed {} commits", messages.len())
2492}
2493
2494pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
2496 let head_commit = repo.get_head_commit()?;
2497 let since_commit = repo.get_commit(since_commit_hash)?;
2498
2499 let mut count = 0;
2500 let mut current = head_commit;
2501
2502 loop {
2504 if current.id() == since_commit.id() {
2505 break;
2506 }
2507
2508 count += 1;
2509
2510 if current.parent_count() == 0 {
2512 break; }
2514
2515 current = current.parent(0).map_err(CascadeError::Git)?;
2516 }
2517
2518 Ok(count)
2519}
2520
2521async fn land_stack(
2523 entry: Option<usize>,
2524 force: bool,
2525 dry_run: bool,
2526 auto: bool,
2527 wait_for_builds: bool,
2528 strategy: Option<MergeStrategyArg>,
2529 build_timeout: u64,
2530) -> Result<()> {
2531 let current_dir = env::current_dir()
2532 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2533
2534 let repo_root = find_repository_root(¤t_dir)
2535 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2536
2537 let stack_manager = StackManager::new(&repo_root)?;
2538
2539 let stack_id = stack_manager
2541 .get_active_stack()
2542 .map(|s| s.id)
2543 .ok_or_else(|| {
2544 CascadeError::config(
2545 "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
2546 .to_string(),
2547 )
2548 })?;
2549
2550 let active_stack = stack_manager
2551 .get_active_stack()
2552 .cloned()
2553 .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
2554
2555 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2557 let config_path = config_dir.join("config.json");
2558 let settings = crate::config::Settings::load_from_file(&config_path)?;
2559
2560 let cascade_config = crate::config::CascadeConfig {
2561 bitbucket: Some(settings.bitbucket.clone()),
2562 git: settings.git.clone(),
2563 auth: crate::config::AuthConfig::default(),
2564 };
2565
2566 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
2567
2568 let status = integration.check_enhanced_stack_status(&stack_id).await?;
2570
2571 if status.enhanced_statuses.is_empty() {
2572 println!("❌ No pull requests found to land");
2573 return Ok(());
2574 }
2575
2576 let ready_prs: Vec<_> = status
2578 .enhanced_statuses
2579 .iter()
2580 .filter(|pr_status| {
2581 if let Some(entry_num) = entry {
2583 if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
2585 if pr_status.pr.from_ref.display_id != stack_entry.branch {
2587 return false;
2588 }
2589 } else {
2590 return false; }
2592 }
2593
2594 if force {
2595 pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
2597 } else {
2598 pr_status.is_ready_to_land()
2599 }
2600 })
2601 .collect();
2602
2603 if ready_prs.is_empty() {
2604 if let Some(entry_num) = entry {
2605 println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
2606 } else {
2607 println!("❌ No pull requests are ready to land");
2608 }
2609
2610 println!("\n🚫 Blocking Issues:");
2612 for pr_status in &status.enhanced_statuses {
2613 if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
2614 let blocking = pr_status.get_blocking_reasons();
2615 if !blocking.is_empty() {
2616 println!(" PR #{}: {}", pr_status.pr.id, blocking.join(", "));
2617 }
2618 }
2619 }
2620
2621 if !force {
2622 println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
2623 }
2624 return Ok(());
2625 }
2626
2627 if dry_run {
2628 if let Some(entry_num) = entry {
2629 println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
2630 } else {
2631 println!("🏃 Dry Run - PRs that would be landed:");
2632 }
2633 for pr_status in &ready_prs {
2634 println!(" ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
2635 if !pr_status.is_ready_to_land() && force {
2636 let blocking = pr_status.get_blocking_reasons();
2637 println!(
2638 " ⚠️ Would force land despite: {}",
2639 blocking.join(", ")
2640 );
2641 }
2642 }
2643 return Ok(());
2644 }
2645
2646 if entry.is_some() && ready_prs.len() > 1 {
2649 println!(
2650 "🎯 {} PRs are ready to land, but landing only entry #{}",
2651 ready_prs.len(),
2652 entry.unwrap()
2653 );
2654 }
2655
2656 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
2658 strategy.unwrap_or(MergeStrategyArg::Squash).into();
2659 let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
2660 merge_strategy: merge_strategy.clone(),
2661 wait_for_builds,
2662 build_timeout: std::time::Duration::from_secs(build_timeout),
2663 allowed_authors: None, };
2665
2666 println!(
2668 "🚀 Landing {} PR{}...",
2669 ready_prs.len(),
2670 if ready_prs.len() == 1 { "" } else { "s" }
2671 );
2672
2673 let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
2674 crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
2675 );
2676
2677 let mut landed_count = 0;
2679 let mut failed_count = 0;
2680 let total_ready_prs = ready_prs.len();
2681
2682 for pr_status in ready_prs {
2683 let pr_id = pr_status.pr.id;
2684
2685 print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
2686
2687 let land_result = if auto {
2688 pr_manager
2690 .auto_merge_if_ready(pr_id, &auto_merge_conditions)
2691 .await
2692 } else {
2693 pr_manager
2695 .merge_pull_request(pr_id, merge_strategy.clone())
2696 .await
2697 .map(
2698 |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
2699 pr: Box::new(pr),
2700 merge_strategy: merge_strategy.clone(),
2701 },
2702 )
2703 };
2704
2705 match land_result {
2706 Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
2707 println!(" ✅");
2708 landed_count += 1;
2709
2710 if landed_count < total_ready_prs {
2712 println!("🔄 Retargeting remaining PRs to latest base...");
2713
2714 let base_branch = active_stack.base_branch.clone();
2716 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2717
2718 println!(" 📥 Updating base branch: {base_branch}");
2719 match git_repo.pull(&base_branch) {
2720 Ok(_) => println!(" ✅ Base branch updated successfully"),
2721 Err(e) => {
2722 println!(" ⚠️ Warning: Failed to update base branch: {e}");
2723 println!(
2724 " 💡 You may want to manually run: git pull origin {base_branch}"
2725 );
2726 }
2727 }
2728
2729 let mut rebase_manager = crate::stack::RebaseManager::new(
2731 StackManager::new(&repo_root)?,
2732 git_repo,
2733 crate::stack::RebaseOptions {
2734 strategy: crate::stack::RebaseStrategy::BranchVersioning,
2735 target_base: Some(base_branch.clone()),
2736 ..Default::default()
2737 },
2738 );
2739
2740 match rebase_manager.rebase_stack(&stack_id) {
2741 Ok(rebase_result) => {
2742 if !rebase_result.branch_mapping.is_empty() {
2743 let retarget_config = crate::config::CascadeConfig {
2745 bitbucket: Some(settings.bitbucket.clone()),
2746 git: settings.git.clone(),
2747 auth: crate::config::AuthConfig::default(),
2748 };
2749 let mut retarget_integration = BitbucketIntegration::new(
2750 StackManager::new(&repo_root)?,
2751 retarget_config,
2752 )?;
2753
2754 match retarget_integration
2755 .update_prs_after_rebase(
2756 &stack_id,
2757 &rebase_result.branch_mapping,
2758 )
2759 .await
2760 {
2761 Ok(updated_prs) => {
2762 if !updated_prs.is_empty() {
2763 println!(
2764 " ✅ Updated {} PRs with new targets",
2765 updated_prs.len()
2766 );
2767 }
2768 }
2769 Err(e) => {
2770 println!(" ⚠️ Failed to update remaining PRs: {e}");
2771 println!(
2772 " 💡 You may need to run: ca stack rebase --onto {base_branch}"
2773 );
2774 }
2775 }
2776 }
2777 }
2778 Err(e) => {
2779 println!(" ❌ Auto-retargeting conflicts detected!");
2781 println!(" 📝 To resolve conflicts and continue landing:");
2782 println!(" 1. Resolve conflicts in the affected files");
2783 println!(" 2. Stage resolved files: git add <files>");
2784 println!(" 3. Continue the process: ca stack continue-land");
2785 println!(" 4. Or abort the operation: ca stack abort-land");
2786 println!();
2787 println!(" 💡 Check current status: ca stack land-status");
2788 println!(" ⚠️ Error details: {e}");
2789
2790 break;
2792 }
2793 }
2794 }
2795 }
2796 Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
2797 println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
2798 failed_count += 1;
2799 if !force {
2800 break;
2801 }
2802 }
2803 Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
2804 println!(" ❌ Failed: {error}");
2805 failed_count += 1;
2806 if !force {
2807 break;
2808 }
2809 }
2810 Err(e) => {
2811 println!(" ❌");
2812 eprintln!("Failed to land PR #{pr_id}: {e}");
2813 failed_count += 1;
2814
2815 if !force {
2816 break;
2817 }
2818 }
2819 }
2820 }
2821
2822 println!("\n🎯 Landing Summary:");
2824 println!(" ✅ Successfully landed: {landed_count}");
2825 if failed_count > 0 {
2826 println!(" ❌ Failed to land: {failed_count}");
2827 }
2828
2829 if landed_count > 0 {
2830 println!("✅ Landing operation completed!");
2831 } else {
2832 println!("❌ No PRs were successfully landed");
2833 }
2834
2835 Ok(())
2836}
2837
2838async fn auto_land_stack(
2840 force: bool,
2841 dry_run: bool,
2842 wait_for_builds: bool,
2843 strategy: Option<MergeStrategyArg>,
2844 build_timeout: u64,
2845) -> Result<()> {
2846 land_stack(
2848 None,
2849 force,
2850 dry_run,
2851 true, wait_for_builds,
2853 strategy,
2854 build_timeout,
2855 )
2856 .await
2857}
2858
2859async fn continue_land() -> Result<()> {
2860 let current_dir = env::current_dir()
2861 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2862
2863 let repo_root = find_repository_root(¤t_dir)
2864 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2865
2866 let stack_manager = StackManager::new(&repo_root)?;
2867 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2868 let options = crate::stack::RebaseOptions::default();
2869 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2870
2871 if !rebase_manager.is_rebase_in_progress() {
2872 println!("ℹ️ No rebase in progress");
2873 return Ok(());
2874 }
2875
2876 println!("🔄 Continuing land operation...");
2877 match rebase_manager.continue_rebase() {
2878 Ok(_) => {
2879 println!("✅ Land operation continued successfully");
2880 println!(" Check 'ca stack land-status' for current state");
2881 }
2882 Err(e) => {
2883 warn!("❌ Failed to continue land operation: {}", e);
2884 println!("💡 You may need to resolve conflicts first:");
2885 println!(" 1. Edit conflicted files");
2886 println!(" 2. Stage resolved files with 'git add'");
2887 println!(" 3. Run 'ca stack continue-land' again");
2888 }
2889 }
2890
2891 Ok(())
2892}
2893
2894async fn abort_land() -> Result<()> {
2895 let current_dir = env::current_dir()
2896 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2897
2898 let repo_root = find_repository_root(¤t_dir)
2899 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2900
2901 let stack_manager = StackManager::new(&repo_root)?;
2902 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2903 let options = crate::stack::RebaseOptions::default();
2904 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2905
2906 if !rebase_manager.is_rebase_in_progress() {
2907 println!("ℹ️ No rebase in progress");
2908 return Ok(());
2909 }
2910
2911 println!("⚠️ Aborting land operation...");
2912 match rebase_manager.abort_rebase() {
2913 Ok(_) => {
2914 println!("✅ Land operation aborted successfully");
2915 println!(" Repository restored to pre-land state");
2916 }
2917 Err(e) => {
2918 warn!("❌ Failed to abort land operation: {}", e);
2919 println!("⚠️ You may need to manually clean up the repository state");
2920 }
2921 }
2922
2923 Ok(())
2924}
2925
2926async fn land_status() -> Result<()> {
2927 let current_dir = env::current_dir()
2928 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2929
2930 let repo_root = find_repository_root(¤t_dir)
2931 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2932
2933 let stack_manager = StackManager::new(&repo_root)?;
2934 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2935
2936 println!("📊 Land Status");
2937
2938 let git_dir = repo_root.join(".git");
2940 let land_in_progress = git_dir.join("REBASE_HEAD").exists()
2941 || git_dir.join("rebase-merge").exists()
2942 || git_dir.join("rebase-apply").exists();
2943
2944 if land_in_progress {
2945 println!(" Status: 🔄 Land operation in progress");
2946 println!(
2947 "
2948📝 Actions available:"
2949 );
2950 println!(" - 'ca stack continue-land' to continue");
2951 println!(" - 'ca stack abort-land' to abort");
2952 println!(" - 'git status' to see conflicted files");
2953
2954 match git_repo.get_status() {
2956 Ok(statuses) => {
2957 let mut conflicts = Vec::new();
2958 for status in statuses.iter() {
2959 if status.status().contains(git2::Status::CONFLICTED) {
2960 if let Some(path) = status.path() {
2961 conflicts.push(path.to_string());
2962 }
2963 }
2964 }
2965
2966 if !conflicts.is_empty() {
2967 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
2968 for conflict in conflicts {
2969 println!(" - {conflict}");
2970 }
2971 println!(
2972 "
2973💡 To resolve conflicts:"
2974 );
2975 println!(" 1. Edit the conflicted files");
2976 println!(" 2. Stage resolved files: git add <file>");
2977 println!(" 3. Continue: ca stack continue-land");
2978 }
2979 }
2980 Err(e) => {
2981 warn!("Failed to get git status: {}", e);
2982 }
2983 }
2984 } else {
2985 println!(" Status: ✅ No land operation in progress");
2986
2987 if let Some(active_stack) = stack_manager.get_active_stack() {
2989 println!(" Active stack: {}", active_stack.name);
2990 println!(" Entries: {}", active_stack.entries.len());
2991 println!(" Base branch: {}", active_stack.base_branch);
2992 }
2993 }
2994
2995 Ok(())
2996}
2997
2998#[cfg(test)]
2999mod tests {
3000 use super::*;
3001 use std::process::Command;
3002 use tempfile::TempDir;
3003
3004 async fn create_test_repo() -> (TempDir, std::path::PathBuf) {
3005 let temp_dir = TempDir::new().unwrap();
3006 let repo_path = temp_dir.path().to_path_buf();
3007
3008 Command::new("git")
3010 .args(["init"])
3011 .current_dir(&repo_path)
3012 .output()
3013 .unwrap();
3014
3015 Command::new("git")
3016 .args(["config", "user.name", "Test User"])
3017 .current_dir(&repo_path)
3018 .output()
3019 .unwrap();
3020
3021 Command::new("git")
3022 .args(["config", "user.email", "test@example.com"])
3023 .current_dir(&repo_path)
3024 .output()
3025 .unwrap();
3026
3027 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
3029 Command::new("git")
3030 .args(["add", "."])
3031 .current_dir(&repo_path)
3032 .output()
3033 .unwrap();
3034
3035 Command::new("git")
3036 .args(["commit", "-m", "Initial commit"])
3037 .current_dir(&repo_path)
3038 .output()
3039 .unwrap();
3040
3041 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
3043 .unwrap();
3044
3045 (temp_dir, repo_path)
3046 }
3047
3048 #[tokio::test]
3049 async fn test_create_stack() {
3050 let (temp_dir, repo_path) = create_test_repo().await;
3051 let _ = &temp_dir;
3053
3054 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3058 match env::set_current_dir(&repo_path) {
3059 Ok(_) => {
3060 let result = create_stack(
3061 "test-stack".to_string(),
3062 None, Some("Test description".to_string()),
3064 )
3065 .await;
3066
3067 if let Ok(orig) = original_dir {
3069 let _ = env::set_current_dir(orig);
3070 }
3071
3072 assert!(
3073 result.is_ok(),
3074 "Stack creation should succeed in initialized repository"
3075 );
3076 }
3077 Err(_) => {
3078 println!("Skipping test due to directory access restrictions");
3080 }
3081 }
3082 }
3083
3084 #[tokio::test]
3085 async fn test_list_empty_stacks() {
3086 let (temp_dir, repo_path) = create_test_repo().await;
3087 let _ = &temp_dir;
3089
3090 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3094 match env::set_current_dir(&repo_path) {
3095 Ok(_) => {
3096 let result = list_stacks(false, false, None).await;
3097
3098 if let Ok(orig) = original_dir {
3100 let _ = env::set_current_dir(orig);
3101 }
3102
3103 assert!(
3104 result.is_ok(),
3105 "Listing stacks should succeed in initialized repository"
3106 );
3107 }
3108 Err(_) => {
3109 println!("Skipping test due to directory access restrictions");
3111 }
3112 }
3113 }
3114
3115 #[test]
3118 fn test_extract_feature_from_wip_basic() {
3119 let messages = vec![
3120 "WIP: add authentication".to_string(),
3121 "WIP: implement login flow".to_string(),
3122 ];
3123
3124 let result = extract_feature_from_wip(&messages);
3125 assert_eq!(result, "Add authentication");
3126 }
3127
3128 #[test]
3129 fn test_extract_feature_from_wip_capitalize() {
3130 let messages = vec!["WIP: fix user validation bug".to_string()];
3131
3132 let result = extract_feature_from_wip(&messages);
3133 assert_eq!(result, "Fix user validation bug");
3134 }
3135
3136 #[test]
3137 fn test_extract_feature_from_wip_fallback() {
3138 let messages = vec![
3139 "WIP user interface changes".to_string(),
3140 "wip: css styling".to_string(),
3141 ];
3142
3143 let result = extract_feature_from_wip(&messages);
3144 assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
3146 }
3147
3148 #[test]
3149 fn test_extract_feature_from_wip_empty() {
3150 let messages = vec![];
3151
3152 let result = extract_feature_from_wip(&messages);
3153 assert_eq!(result, "Squashed 0 commits");
3154 }
3155
3156 #[test]
3157 fn test_extract_feature_from_wip_short_message() {
3158 let messages = vec!["WIP: x".to_string()]; let result = extract_feature_from_wip(&messages);
3161 assert!(result.starts_with("Implement") || result.contains("Squashed"));
3162 }
3163
3164 #[test]
3167 fn test_squash_message_final_strategy() {
3168 let messages = [
3172 "Final: implement user authentication system".to_string(),
3173 "WIP: add tests".to_string(),
3174 "WIP: fix validation".to_string(),
3175 ];
3176
3177 assert!(messages[0].starts_with("Final:"));
3179
3180 let extracted = messages[0].trim_start_matches("Final:").trim();
3182 assert_eq!(extracted, "implement user authentication system");
3183 }
3184
3185 #[test]
3186 fn test_squash_message_wip_detection() {
3187 let messages = [
3188 "WIP: start feature".to_string(),
3189 "WIP: continue work".to_string(),
3190 "WIP: almost done".to_string(),
3191 "Regular commit message".to_string(),
3192 ];
3193
3194 let wip_count = messages
3195 .iter()
3196 .filter(|m| {
3197 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
3198 })
3199 .count();
3200
3201 assert_eq!(wip_count, 3); assert!(wip_count > messages.len() / 2); let non_wip: Vec<&String> = messages
3206 .iter()
3207 .filter(|m| {
3208 !m.to_lowercase().starts_with("wip")
3209 && !m.to_lowercase().contains("work in progress")
3210 })
3211 .collect();
3212
3213 assert_eq!(non_wip.len(), 1);
3214 assert_eq!(non_wip[0], "Regular commit message");
3215 }
3216
3217 #[test]
3218 fn test_squash_message_all_wip() {
3219 let messages = vec![
3220 "WIP: add feature A".to_string(),
3221 "WIP: add feature B".to_string(),
3222 "WIP: finish implementation".to_string(),
3223 ];
3224
3225 let result = extract_feature_from_wip(&messages);
3226 assert_eq!(result, "Add feature A");
3228 }
3229
3230 #[test]
3231 fn test_squash_message_edge_cases() {
3232 let empty_messages: Vec<String> = vec![];
3234 let result = extract_feature_from_wip(&empty_messages);
3235 assert_eq!(result, "Squashed 0 commits");
3236
3237 let whitespace_messages = vec![" ".to_string(), "\t\n".to_string()];
3239 let result = extract_feature_from_wip(&whitespace_messages);
3240 assert!(result.contains("Squashed") || result.contains("Implement"));
3241
3242 let mixed_case = vec!["wip: Add Feature".to_string()];
3244 let result = extract_feature_from_wip(&mixed_case);
3245 assert_eq!(result, "Add Feature");
3246 }
3247
3248 #[tokio::test]
3251 async fn test_auto_land_wrapper() {
3252 let (temp_dir, repo_path) = create_test_repo().await;
3254 let _ = &temp_dir;
3256
3257 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
3259 .expect("Failed to initialize Cascade in test repo");
3260
3261 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3262 match env::set_current_dir(&repo_path) {
3263 Ok(_) => {
3264 let result = create_stack(
3266 "test-stack".to_string(),
3267 None,
3268 Some("Test stack for auto-land".to_string()),
3269 )
3270 .await;
3271
3272 if let Ok(orig) = original_dir {
3273 let _ = env::set_current_dir(orig);
3274 }
3275
3276 assert!(
3279 result.is_ok(),
3280 "Stack creation should succeed in initialized repository"
3281 );
3282 }
3283 Err(_) => {
3284 println!("Skipping test due to directory access restrictions");
3285 }
3286 }
3287 }
3288
3289 #[test]
3290 fn test_auto_land_action_enum() {
3291 use crate::cli::commands::stack::StackAction;
3293
3294 let _action = StackAction::AutoLand {
3296 force: false,
3297 dry_run: true,
3298 wait_for_builds: true,
3299 strategy: Some(MergeStrategyArg::Squash),
3300 build_timeout: 1800,
3301 };
3302
3303 }
3305
3306 #[test]
3307 fn test_merge_strategy_conversion() {
3308 let squash_strategy = MergeStrategyArg::Squash;
3310 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
3311
3312 match merge_strategy {
3313 crate::bitbucket::pull_request::MergeStrategy::Squash => {
3314 }
3316 _ => panic!("Expected Squash strategy"),
3317 }
3318
3319 let merge_strategy = MergeStrategyArg::Merge;
3320 let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
3321
3322 match converted {
3323 crate::bitbucket::pull_request::MergeStrategy::Merge => {
3324 }
3326 _ => panic!("Expected Merge strategy"),
3327 }
3328 }
3329
3330 #[test]
3331 fn test_auto_merge_conditions_structure() {
3332 use std::time::Duration;
3334
3335 let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3336 merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
3337 wait_for_builds: true,
3338 build_timeout: Duration::from_secs(1800),
3339 allowed_authors: None,
3340 };
3341
3342 assert!(conditions.wait_for_builds);
3344 assert_eq!(conditions.build_timeout.as_secs(), 1800);
3345 assert!(conditions.allowed_authors.is_none());
3346 assert!(matches!(
3347 conditions.merge_strategy,
3348 crate::bitbucket::pull_request::MergeStrategy::Squash
3349 ));
3350 }
3351
3352 #[test]
3353 fn test_polling_constants() {
3354 use std::time::Duration;
3356
3357 let expected_polling_interval = Duration::from_secs(30);
3359
3360 assert!(expected_polling_interval.as_secs() >= 10); assert!(expected_polling_interval.as_secs() <= 60); assert_eq!(expected_polling_interval.as_secs(), 30); }
3365
3366 #[test]
3367 fn test_build_timeout_defaults() {
3368 const DEFAULT_TIMEOUT: u64 = 1800; assert_eq!(DEFAULT_TIMEOUT, 1800);
3371 let timeout_value = 1800u64;
3373 assert!(timeout_value >= 300); assert!(timeout_value <= 3600); }
3376
3377 #[test]
3378 fn test_scattered_commit_detection() {
3379 use std::collections::HashSet;
3380
3381 let mut source_branches = HashSet::new();
3383 source_branches.insert("feature-branch-1".to_string());
3384 source_branches.insert("feature-branch-2".to_string());
3385 source_branches.insert("feature-branch-3".to_string());
3386
3387 let single_branch = HashSet::from(["main".to_string()]);
3389 assert_eq!(single_branch.len(), 1);
3390
3391 assert!(source_branches.len() > 1);
3393 assert_eq!(source_branches.len(), 3);
3394
3395 assert!(source_branches.contains("feature-branch-1"));
3397 assert!(source_branches.contains("feature-branch-2"));
3398 assert!(source_branches.contains("feature-branch-3"));
3399 }
3400
3401 #[test]
3402 fn test_source_branch_tracking() {
3403 let branch_a = "feature-work";
3407 let branch_b = "feature-work";
3408 assert_eq!(branch_a, branch_b);
3409
3410 let branch_1 = "feature-ui";
3412 let branch_2 = "feature-api";
3413 assert_ne!(branch_1, branch_2);
3414
3415 assert!(branch_1.starts_with("feature-"));
3417 assert!(branch_2.starts_with("feature-"));
3418 }
3419
3420 #[tokio::test]
3423 async fn test_push_default_behavior() {
3424 let (temp_dir, repo_path) = create_test_repo().await;
3426 let _ = &temp_dir;
3428
3429 if !repo_path.exists() {
3431 println!("Skipping test due to temporary directory creation issue");
3432 return;
3433 }
3434
3435 let original_dir = env::current_dir().unwrap();
3437
3438 match env::set_current_dir(&repo_path) {
3439 Ok(_) => {
3440 let result = push_to_stack(
3442 None, None, None, None, None, None, None, false, false, )
3452 .await;
3453
3454 let _ = env::set_current_dir(original_dir);
3456
3457 match &result {
3459 Err(e) => {
3460 let error_msg = e.to_string();
3461 assert!(
3463 error_msg.contains("No active stack")
3464 || error_msg.contains("config")
3465 || error_msg.contains("current directory")
3466 || error_msg.contains("Not a git repository")
3467 || error_msg.contains("could not find repository"),
3468 "Expected 'No active stack' or repository error, got: {error_msg}"
3469 );
3470 }
3471 Ok(_) => {
3472 println!(
3474 "Push succeeded unexpectedly - test environment may have active stack"
3475 );
3476 }
3477 }
3478 }
3479 Err(_) => {
3480 println!("Skipping test due to directory access restrictions");
3482 }
3483 }
3484
3485 let push_action = StackAction::Push {
3487 branch: None,
3488 message: None,
3489 commit: None,
3490 since: None,
3491 commits: None,
3492 squash: None,
3493 squash_since: None,
3494 auto_branch: false,
3495 allow_base_branch: false,
3496 };
3497
3498 assert!(matches!(
3499 push_action,
3500 StackAction::Push {
3501 branch: None,
3502 message: None,
3503 commit: None,
3504 since: None,
3505 commits: None,
3506 squash: None,
3507 squash_since: None,
3508 auto_branch: false,
3509 allow_base_branch: false
3510 }
3511 ));
3512 }
3513
3514 #[tokio::test]
3515 async fn test_submit_default_behavior() {
3516 let (temp_dir, repo_path) = create_test_repo().await;
3518 let _ = &temp_dir;
3520
3521 if !repo_path.exists() {
3523 println!("Skipping test due to temporary directory creation issue");
3524 return;
3525 }
3526
3527 let original_dir = match env::current_dir() {
3529 Ok(dir) => dir,
3530 Err(_) => {
3531 println!("Skipping test due to current directory access restrictions");
3532 return;
3533 }
3534 };
3535
3536 match env::set_current_dir(&repo_path) {
3537 Ok(_) => {
3538 let result = submit_entry(
3540 None, None, None, None, false, )
3546 .await;
3547
3548 let _ = env::set_current_dir(original_dir);
3550
3551 match &result {
3553 Err(e) => {
3554 let error_msg = e.to_string();
3555 assert!(
3557 error_msg.contains("No active stack")
3558 || error_msg.contains("config")
3559 || error_msg.contains("current directory")
3560 || error_msg.contains("Not a git repository")
3561 || error_msg.contains("could not find repository"),
3562 "Expected 'No active stack' or repository error, got: {error_msg}"
3563 );
3564 }
3565 Ok(_) => {
3566 println!("Submit succeeded unexpectedly - test environment may have active stack");
3568 }
3569 }
3570 }
3571 Err(_) => {
3572 println!("Skipping test due to directory access restrictions");
3574 }
3575 }
3576
3577 let submit_action = StackAction::Submit {
3579 entry: None,
3580 title: None,
3581 description: None,
3582 range: None,
3583 draft: false,
3584 };
3585
3586 assert!(matches!(
3587 submit_action,
3588 StackAction::Submit {
3589 entry: None,
3590 title: None,
3591 description: None,
3592 range: None,
3593 draft: false
3594 }
3595 ));
3596 }
3597
3598 #[test]
3599 fn test_targeting_options_still_work() {
3600 let commits = "abc123,def456,ghi789";
3604 let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
3605 assert_eq!(parsed.len(), 3);
3606 assert_eq!(parsed[0], "abc123");
3607 assert_eq!(parsed[1], "def456");
3608 assert_eq!(parsed[2], "ghi789");
3609
3610 let range = "1-3";
3612 assert!(range.contains('-'));
3613 let parts: Vec<&str> = range.split('-').collect();
3614 assert_eq!(parts.len(), 2);
3615
3616 let since_ref = "HEAD~3";
3618 assert!(since_ref.starts_with("HEAD"));
3619 assert!(since_ref.contains('~'));
3620 }
3621
3622 #[test]
3623 fn test_command_flow_logic() {
3624 assert!(matches!(
3626 StackAction::Push {
3627 branch: None,
3628 message: None,
3629 commit: None,
3630 since: None,
3631 commits: None,
3632 squash: None,
3633 squash_since: None,
3634 auto_branch: false,
3635 allow_base_branch: false
3636 },
3637 StackAction::Push { .. }
3638 ));
3639
3640 assert!(matches!(
3641 StackAction::Submit {
3642 entry: None,
3643 title: None,
3644 description: None,
3645 range: None,
3646 draft: false
3647 },
3648 StackAction::Submit { .. }
3649 ));
3650 }
3651
3652 #[tokio::test]
3653 async fn test_deactivate_command_structure() {
3654 let deactivate_action = StackAction::Deactivate { force: false };
3656
3657 assert!(matches!(
3659 deactivate_action,
3660 StackAction::Deactivate { force: false }
3661 ));
3662
3663 let force_deactivate = StackAction::Deactivate { force: true };
3665 assert!(matches!(
3666 force_deactivate,
3667 StackAction::Deactivate { force: true }
3668 ));
3669 }
3670}