1use serde::{Deserialize, Serialize};
7
8use crate::{pr::PrData, types::State};
9
10#[derive(Debug, Clone)]
16#[allow(
17 clippy::struct_excessive_bools,
18 reason = "Configuration type with boolean flags"
19)]
20pub struct CleanupArgs {
21 pub numbers: Vec<u64>,
23 pub merged: bool,
25 pub closed: bool,
27 pub worktree: Option<String>,
29 pub remote: bool,
31 pub local: bool,
33 pub force: bool,
35 pub dry_run: bool,
37 pub yes: bool,
42}
43
44#[derive(Debug, Clone)]
54#[non_exhaustive]
55pub struct CleanupPlan {
56 pub targets: Vec<PrData>,
58 pub truncated: bool,
64 pub limit: u32,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
77#[serde(rename_all = "camelCase")]
78#[allow(
79 clippy::struct_excessive_bools,
80 reason = "Result type tracking multiple operation outcomes"
81)]
82pub struct CleanupResult {
83 pub pr_number: u64,
85 pub pr_title: String,
87 pub branch: String,
89 pub remote_deleted: bool,
91 pub local_deleted: bool,
93 pub worktree_exited: bool,
95 pub worktree_removed: bool,
97 pub dry_run: bool,
99 pub error: Option<String>,
101}
102
103#[must_use]
113pub fn select_merge_candidates(prs: &[PrData]) -> Vec<&PrData> {
114 if prs.iter().any(|pr| pr.merged_at.is_some()) {
115 prs.iter().filter(|pr| pr.merged_at.is_some()).collect()
116 } else {
117 prs.iter().filter(|pr| pr.state == State::Closed).collect()
118 }
119}
120
121#[must_use]
127pub fn is_protected_branch(branch: &str) -> bool {
128 matches!(branch, "main" | "master" | "develop") || branch.starts_with("release/")
129}
130
131pub fn check_safety(pr: &PrData, current_branch: &str, force: bool) -> crate::Result<()> {
142 if !force && pr.state != State::Closed {
144 return Err(crate::CoreError::App(format!(
145 "PR #{} 尚未合并或关闭。使用 --force 强制清理。",
146 pr.number
147 )));
148 }
149
150 if is_protected_branch(&pr.head_branch) {
152 return Err(crate::CoreError::App(format!(
153 "分支 '{}' 受保护,拒绝删除",
154 pr.head_branch
155 )));
156 }
157
158 if pr.head_branch == current_branch {
160 return Err(crate::CoreError::App(format!(
161 "无法删除当前检出的分支 '{}'",
162 pr.head_branch
163 )));
164 }
165
166 Ok(())
167}
168
169#[derive(Debug)]
173pub struct CleanupService;
174
175impl CleanupService {
176 pub async fn cleanup_single_pr(
185 provider: &dyn crate::pr::PrProvider,
186 pr_number: u64,
187 args: &CleanupArgs,
188 ) -> crate::Result<CleanupResult> {
189 let pr = provider.view(pr_number).await?;
191
192 let current_branch = get_current_branch().await?;
194
195 check_safety(&pr, ¤t_branch, args.force)?;
197
198 let mut remote_deleted = false;
200 if args.remote && !args.dry_run {
201 if let Err(e) = crate::git_ops::delete_remote_branch(&pr.head_branch).await {
202 tracing::warn!("Failed to delete remote branch: {}", e);
204 } else {
205 remote_deleted = true;
206 }
207 }
208
209 let mut local_deleted = false;
211 if args.local && !args.dry_run {
212 crate::git_ops::delete_local_branch(&pr.head_branch, args.force).await?;
213 local_deleted = true;
214 }
215
216 let mut worktree_exited = false;
218 let mut worktree_removed = false;
219
220 if crate::git_ops::is_in_worktree().await? && !args.dry_run {
221 crate::git_ops::exit_worktree().await?;
222 worktree_exited = true;
223
224 if let Some(ref worktree_path) = args.worktree {
225 crate::git_ops::remove_worktree(worktree_path).await?;
226 worktree_removed = true;
227 }
228 }
229
230 Ok(CleanupResult {
231 pr_number: pr.number,
232 pr_title: pr.title,
233 branch: pr.head_branch,
234 remote_deleted,
235 local_deleted,
236 worktree_exited,
237 worktree_removed,
238 dry_run: args.dry_run,
239 error: None,
240 })
241 }
242
243 pub async fn cleanup(
252 provider: &dyn crate::pr::PrProvider,
253 args: &CleanupArgs,
254 ) -> crate::Result<Vec<CleanupResult>> {
255 let mut results = Vec::new();
256
257 for &pr_number in &args.numbers {
258 match Self::cleanup_single_pr(provider, pr_number, args).await {
259 Ok(result) => results.push(result),
260 Err(e) => {
261 results.push(CleanupResult {
263 pr_number,
264 pr_title: String::new(),
265 branch: String::new(),
266 remote_deleted: false,
267 local_deleted: false,
268 worktree_exited: false,
269 worktree_removed: false,
270 dry_run: args.dry_run,
271 error: Some(e.to_string()),
272 });
273 }
274 }
275 }
276
277 Ok(results)
278 }
279
280 pub async fn plan_merged(provider: &dyn crate::pr::PrProvider) -> crate::Result<CleanupPlan> {
287 Self::plan_filtered(provider, true).await
288 }
289
290 pub async fn plan_closed(provider: &dyn crate::pr::PrProvider) -> crate::Result<CleanupPlan> {
297 Self::plan_filtered(provider, false).await
298 }
299
300 async fn plan_filtered(
307 provider: &dyn crate::pr::PrProvider,
308 require_merged: bool,
309 ) -> crate::Result<CleanupPlan> {
310 let paged = provider
311 .list(crate::pr::ListPrArgs {
312 state: Some(State::Closed),
313 limit: None,
314 })
315 .await?;
316
317 let targets: Vec<PrData> = if require_merged {
318 select_merge_candidates(&paged.items)
319 .into_iter()
320 .cloned()
321 .collect()
322 } else {
323 paged
324 .items
325 .iter()
326 .filter(|pr| pr.state == State::Closed)
327 .cloned()
328 .collect()
329 };
330
331 Ok(CleanupPlan {
332 targets,
333 truncated: paged.truncated,
334 limit: paged.limit,
335 })
336 }
337
338 pub async fn execute_plan(
345 provider: &dyn crate::pr::PrProvider,
346 args: &CleanupArgs,
347 plan: &CleanupPlan,
348 ) -> crate::Result<Vec<CleanupResult>> {
349 let mut results = Vec::new();
350 for pr in &plan.targets {
351 let mut pr_args = args.clone();
352 pr_args.numbers = vec![pr.number];
353
354 match Self::cleanup_single_pr(provider, pr.number, &pr_args).await {
355 Ok(result) => results.push(result),
356 Err(e) => {
357 results.push(CleanupResult {
358 pr_number: pr.number,
359 pr_title: pr.title.clone(),
360 branch: pr.head_branch.clone(),
361 remote_deleted: false,
362 local_deleted: false,
363 worktree_exited: false,
364 worktree_removed: false,
365 dry_run: args.dry_run,
366 error: Some(e.to_string()),
367 });
368 }
369 }
370 }
371
372 Ok(results)
373 }
374}
375
376async fn get_current_branch() -> crate::Result<String> {
382 let output = tokio::process::Command::new("git")
383 .args(["branch", "--show-current"])
384 .output()
385 .await
386 .map_err(|e| crate::CoreError::App(format!("Failed to get current branch: {e}")))?;
387
388 if !output.status.success() {
389 return Err(crate::CoreError::App(
390 "Failed to get current branch".to_string(),
391 ));
392 }
393
394 let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
395 if branch.is_empty() {
396 return Err(crate::CoreError::App("HEAD is detached".to_string()));
397 }
398
399 Ok(branch)
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405
406 #[test]
407 fn test_should_create_cleanup_args_with_defaults() {
408 let args = CleanupArgs {
409 numbers: vec![172],
410 merged: false,
411 closed: false,
412 worktree: None,
413 remote: true,
414 local: true,
415 force: false,
416 dry_run: false,
417 yes: false,
418 };
419 assert_eq!(args.numbers, vec![172]);
420 assert!(args.remote);
421 assert!(args.local);
422 assert!(!args.force);
423 }
424
425 #[test]
426 fn test_should_create_cleanup_args_for_batch() {
427 let args = CleanupArgs {
428 numbers: vec![172, 173, 174],
429 merged: false,
430 closed: false,
431 worktree: None,
432 remote: true,
433 local: true,
434 force: false,
435 dry_run: false,
436 yes: false,
437 };
438 assert_eq!(args.numbers.len(), 3);
439 }
440
441 #[test]
442 fn test_should_create_cleanup_args_for_merged() {
443 let args = CleanupArgs {
444 numbers: vec![],
445 merged: true,
446 closed: false,
447 worktree: None,
448 remote: true,
449 local: true,
450 force: false,
451 dry_run: false,
452 yes: false,
453 };
454 assert!(args.merged);
455 assert!(!args.closed);
456 }
457
458 #[test]
459 fn test_should_serialize_cleanup_result() {
460 let result = CleanupResult {
461 pr_number: 172,
462 pr_title: "Add feature".to_string(),
463 branch: "feature/x".to_string(),
464 remote_deleted: true,
465 local_deleted: true,
466 worktree_exited: false,
467 worktree_removed: false,
468 dry_run: false,
469 error: None,
470 };
471 let json = serde_json::to_string(&result).expect("serialize");
472 assert!(json.contains("\"prNumber\":172"));
473 assert!(json.contains("\"remoteDeleted\":true"));
474 }
475
476 #[test]
477 fn test_should_serialize_cleanup_result_with_error() {
478 let result = CleanupResult {
479 pr_number: 175,
480 pr_title: "Protected branch".to_string(),
481 branch: "main".to_string(),
482 remote_deleted: false,
483 local_deleted: false,
484 worktree_exited: false,
485 worktree_removed: false,
486 dry_run: false,
487 error: Some("Branch 'main' is protected".to_string()),
488 };
489 let json = serde_json::to_string(&result).expect("serialize");
490 assert!(json.contains("\"error\":"));
491 assert!(json.contains("protected"));
492 }
493
494 #[test]
495 fn test_should_identify_main_as_protected() {
496 assert!(is_protected_branch("main"));
497 }
498
499 #[test]
500 fn test_should_identify_master_as_protected() {
501 assert!(is_protected_branch("master"));
502 }
503
504 #[test]
505 fn test_should_identify_develop_as_protected() {
506 assert!(is_protected_branch("develop"));
507 }
508
509 #[test]
510 fn test_should_identify_release_branches_as_protected() {
511 assert!(is_protected_branch("release/1.0"));
512 assert!(is_protected_branch("release/v2.0.0"));
513 }
514
515 #[test]
516 fn test_should_not_identify_feature_branch_as_protected() {
517 assert!(!is_protected_branch("feature/x"));
518 assert!(!is_protected_branch("bugfix/123"));
519 }
520
521 #[test]
522 fn test_should_allow_cleanup_of_merged_pr() {
523 let pr = PrData {
524 number: 172,
525 title: "Add feature".to_string(),
526 body: None,
527 state: State::Closed,
528 draft: false,
529 author: crate::types::UserSummary {
530 login: "alice".to_string(),
531 id: "1".to_string(),
532 },
533 base_branch: "main".to_string(),
534 head_branch: "feature/x".to_string(),
535 created_at: Some(chrono::Utc::now()),
536 updated_at: Some(chrono::Utc::now()),
537 merged_at: Some(chrono::Utc::now()),
538 url: "https://github.com/test/repo/pull/172".to_string(),
539 milestone: None,
540 };
541 let result = check_safety(&pr, "main", false);
542 assert!(result.is_ok());
543 }
544
545 #[test]
546 fn test_should_refuse_to_delete_protected_branch() {
547 let pr = PrData {
548 number: 172,
549 title: "Update main".to_string(),
550 body: None,
551 state: State::Closed,
552 draft: false,
553 author: crate::types::UserSummary {
554 login: "alice".to_string(),
555 id: "1".to_string(),
556 },
557 base_branch: "main".to_string(),
558 head_branch: "main".to_string(),
559 created_at: Some(chrono::Utc::now()),
560 merged_at: None,
561 updated_at: Some(chrono::Utc::now()),
562 url: "https://github.com/test/repo/pull/172".to_string(),
563 milestone: None,
564 };
565 let result = check_safety(&pr, "develop", false);
566 assert!(result.is_err());
567 let err = result.unwrap_err().to_string();
568 assert!(err.contains("受保护"));
569 }
570
571 #[test]
572 fn test_should_refuse_to_delete_current_branch() {
573 let pr = PrData {
574 number: 172,
575 title: "Add feature".to_string(),
576 body: None,
577 state: State::Closed,
578 draft: false,
579 author: crate::types::UserSummary {
580 login: "alice".to_string(),
581 id: "1".to_string(),
582 },
583 base_branch: "main".to_string(),
584 head_branch: "feature/x".to_string(),
585 merged_at: None,
586 created_at: Some(chrono::Utc::now()),
587 updated_at: Some(chrono::Utc::now()),
588 url: "https://github.com/test/repo/pull/172".to_string(),
589 milestone: None,
590 };
591 let result = check_safety(&pr, "feature/x", false);
592 assert!(result.is_err());
593 let err = result.unwrap_err().to_string();
594 assert!(err.contains("当前检出"));
595 }
596
597 #[test]
598 fn test_should_require_merged_or_closed_state() {
599 let pr = PrData {
600 number: 172,
601 title: "Add feature".to_string(),
602 body: None,
603 state: State::Open,
604 draft: false,
605 author: crate::types::UserSummary {
606 login: "alice".to_string(),
607 id: "1".to_string(),
608 },
609 base_branch: "main".to_string(),
610 merged_at: None,
611 head_branch: "feature/x".to_string(),
612 created_at: Some(chrono::Utc::now()),
613 updated_at: Some(chrono::Utc::now()),
614 url: "https://github.com/test/repo/pull/172".to_string(),
615 milestone: None,
616 };
617 let result = check_safety(&pr, "main", false);
618 assert!(result.is_err());
619 let err = result.unwrap_err().to_string();
620 assert!(err.contains("尚未合并或关闭"));
621 }
622
623 #[test]
624 fn test_should_allow_unmerged_pr_with_force() {
625 let pr = PrData {
626 number: 172,
627 title: "Add feature".to_string(),
628 body: None,
629 state: State::Open,
630 draft: false,
631 author: crate::types::UserSummary {
632 login: "alice".to_string(),
633 id: "1".to_string(),
634 },
635 merged_at: None,
636 base_branch: "main".to_string(),
637 head_branch: "feature/x".to_string(),
638 created_at: Some(chrono::Utc::now()),
639 updated_at: Some(chrono::Utc::now()),
640 url: "https://github.com/test/repo/pull/172".to_string(),
641 milestone: None,
642 };
643 let result = check_safety(&pr, "main", true);
644 assert!(result.is_ok());
645 }
646
647 fn pr_fixture(number: u64, state: State, merged: bool) -> PrData {
648 PrData {
649 number,
650 title: format!("PR {number}"),
651 body: None,
652 state,
653 draft: false,
654 author: crate::types::UserSummary {
655 login: "alice".to_string(),
656 id: "1".to_string(),
657 },
658 base_branch: "main".to_string(),
659 head_branch: format!("feature/{number}"),
660 created_at: Some(chrono::Utc::now()),
661 updated_at: Some(chrono::Utc::now()),
662 merged_at: if merged {
663 Some(chrono::Utc::now())
664 } else {
665 None
666 },
667 url: format!("https://github.com/test/repo/pull/{number}"),
668 milestone: None,
669 }
670 }
671
672 fn picked(prs: &[&PrData]) -> Vec<u64> {
673 prs.iter().map(|pr| pr.number).collect()
674 }
675
676 #[test]
677 fn test_should_exclude_closed_but_unmerged_from_merged_cleanup() {
678 let prs = vec![
681 pr_fixture(200, State::Closed, true),
682 pr_fixture(201, State::Closed, false),
683 ];
684 assert_eq!(picked(&select_merge_candidates(&prs)), vec![200]);
685 }
686
687 #[test]
688 fn test_should_fall_back_to_closed_state_when_merged_at_never_reported() {
689 let prs = vec![
692 pr_fixture(300, State::Closed, false),
693 pr_fixture(301, State::Closed, false),
694 ];
695 assert_eq!(picked(&select_merge_candidates(&prs)), vec![300, 301]);
696 }
697
698 #[test]
699 fn test_should_keep_open_pr_out_of_merge_candidates() {
700 let prs = vec![
701 pr_fixture(400, State::Closed, true),
702 pr_fixture(401, State::Open, false),
703 ];
704 assert_eq!(picked(&select_merge_candidates(&prs)), vec![400]);
705 }
706
707 #[derive(Debug)]
711 struct RecordingProvider {
712 prs: Vec<PrData>,
713 truncated: bool,
714 calls: std::sync::Mutex<Vec<&'static str>>,
715 }
716
717 impl RecordingProvider {
718 fn new(prs: Vec<PrData>, truncated: bool) -> Self {
719 Self {
720 prs,
721 truncated,
722 calls: std::sync::Mutex::new(Vec::new()),
723 }
724 }
725
726 fn record(&self, name: &'static str) {
727 self.calls.lock().expect("lock calls").push(name);
728 }
729
730 fn call_count(&self, name: &str) -> usize {
731 self.calls
732 .lock()
733 .expect("lock calls")
734 .iter()
735 .filter(|call| **call == name)
736 .count()
737 }
738 }
739
740 fn unsupported<T>(op: &str) -> crate::Result<T> {
741 Err(crate::CoreError::App(format!(
742 "RecordingProvider does not support '{op}' in tests"
743 )))
744 }
745
746 #[async_trait::async_trait]
747 impl crate::pr::PrProvider for RecordingProvider {
748 async fn create(&self, _args: crate::pr::CreatePrArgs) -> crate::Result<PrData> {
749 self.record("create");
750 unsupported("create")
751 }
752
753 async fn list(
754 &self,
755 _args: crate::pr::ListPrArgs,
756 ) -> crate::Result<crate::paging::Paged<PrData>> {
757 self.record("list");
758 Ok(crate::paging::Paged {
759 items: self.prs.clone(),
760 truncated: self.truncated,
761 limit: crate::paging::DEFAULT_LIST_LIMIT,
762 })
763 }
764
765 async fn view(&self, number: u64) -> crate::Result<PrData> {
766 self.record("view");
767 self.prs
768 .iter()
769 .find(|pr| pr.number == number)
770 .cloned()
771 .ok_or_else(|| crate::CoreError::App(format!("pr #{number} not found")))
772 }
773
774 async fn close(&self, _number: u64) -> crate::Result<PrData> {
775 self.record("close");
776 unsupported("close")
777 }
778
779 async fn reopen(&self, _number: u64) -> crate::Result<PrData> {
780 self.record("reopen");
781 unsupported("reopen")
782 }
783
784 async fn comment(
785 &self,
786 _number: u64,
787 _body: &str,
788 ) -> crate::Result<crate::types::CommentData> {
789 self.record("comment");
790 unsupported("comment")
791 }
792
793 async fn merge(
794 &self,
795 _number: u64,
796 _strategy: Option<crate::types::MergeStrategy>,
797 _auto: bool,
798 ) -> crate::Result<crate::types::MergeResult> {
799 self.record("merge");
800 unsupported("merge")
801 }
802
803 async fn checkout(&self, _number: u64) -> crate::Result<()> {
804 self.record("checkout");
805 unsupported("checkout")
806 }
807
808 async fn mark_ready(&self, _number: u64) -> crate::Result<PrData> {
809 self.record("mark_ready");
810 unsupported("mark_ready")
811 }
812
813 async fn mark_wip(&self, _number: u64) -> crate::Result<PrData> {
814 self.record("mark_wip");
815 unsupported("mark_wip")
816 }
817
818 async fn sync_branch(&self, _number: u64) -> crate::Result<()> {
819 self.record("sync_branch");
820 unsupported("sync_branch")
821 }
822
823 async fn diff(&self, _number: u64) -> crate::Result<String> {
824 self.record("diff");
825 unsupported("diff")
826 }
827
828 async fn patch(&self, _number: u64) -> crate::Result<String> {
829 self.record("patch");
830 unsupported("patch")
831 }
832
833 async fn default_branch(&self) -> crate::Result<String> {
834 self.record("default_branch");
835 unsupported("default_branch")
836 }
837 }
838
839 #[tokio::test]
840 async fn test_should_carry_truncated_flag_into_cleanup_plan() {
841 let provider = RecordingProvider::new(
842 vec![pr_fixture(500, State::Closed, true)],
843 true, );
845
846 let plan = CleanupService::plan_merged(&provider)
847 .await
848 .expect("plan_merged should succeed");
849
850 assert!(plan.truncated);
851 }
852
853 #[tokio::test]
854 async fn test_should_not_delete_anything_while_planning() {
855 let provider = RecordingProvider::new(
858 vec![
859 pr_fixture(600, State::Closed, true),
860 pr_fixture(601, State::Closed, false),
861 ],
862 false,
863 );
864
865 let _plan = CleanupService::plan_merged(&provider)
866 .await
867 .expect("plan_merged should succeed");
868
869 assert_eq!(
873 provider.call_count("view"),
874 0,
875 "planning must not touch any per-PR cleanup path"
876 );
877 assert_eq!(provider.call_count("list"), 1);
878 }
879
880 #[tokio::test]
881 async fn test_should_select_only_merged_prs_in_merged_plan() {
882 let provider = RecordingProvider::new(
883 vec![
884 pr_fixture(700, State::Closed, true),
885 pr_fixture(701, State::Closed, false),
886 ],
887 false,
888 );
889
890 let plan = CleanupService::plan_merged(&provider)
891 .await
892 .expect("plan_merged should succeed");
893
894 let numbers: Vec<u64> = plan.targets.iter().map(|pr| pr.number).collect();
895 assert_eq!(numbers, vec![700]);
896 }
897}