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,
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46#[allow(
47 clippy::struct_excessive_bools,
48 reason = "Result type tracking multiple operation outcomes"
49)]
50pub struct CleanupResult {
51 pub pr_number: u64,
53 pub pr_title: String,
55 pub branch: String,
57 pub remote_deleted: bool,
59 pub local_deleted: bool,
61 pub worktree_exited: bool,
63 pub worktree_removed: bool,
65 pub dry_run: bool,
67 pub error: Option<String>,
69}
70
71#[must_use]
77pub fn is_protected_branch(branch: &str) -> bool {
78 matches!(branch, "main" | "master" | "develop") || branch.starts_with("release/")
79}
80
81pub fn check_safety(pr: &PrData, current_branch: &str, force: bool) -> crate::Result<()> {
92 if !force && pr.state != State::Closed {
94 return Err(crate::CoreError::App(format!(
95 "PR #{} 尚未合并或关闭。使用 --force 强制清理。",
96 pr.number
97 )));
98 }
99
100 if is_protected_branch(&pr.head_branch) {
102 return Err(crate::CoreError::App(format!(
103 "分支 '{}' 受保护,拒绝删除",
104 pr.head_branch
105 )));
106 }
107
108 if pr.head_branch == current_branch {
110 return Err(crate::CoreError::App(format!(
111 "无法删除当前检出的分支 '{}'",
112 pr.head_branch
113 )));
114 }
115
116 Ok(())
117}
118
119#[derive(Debug)]
123pub struct CleanupService;
124
125impl CleanupService {
126 pub async fn cleanup_single_pr(
135 provider: &dyn crate::pr::PrProvider,
136 pr_number: u64,
137 args: &CleanupArgs,
138 ) -> crate::Result<CleanupResult> {
139 let pr = provider.view(pr_number).await?;
141
142 let current_branch = get_current_branch().await?;
144
145 check_safety(&pr, ¤t_branch, args.force)?;
147
148 let mut remote_deleted = false;
150 if args.remote && !args.dry_run {
151 if let Err(e) = crate::git_ops::delete_remote_branch(&pr.head_branch).await {
152 tracing::warn!("Failed to delete remote branch: {}", e);
154 } else {
155 remote_deleted = true;
156 }
157 }
158
159 let mut local_deleted = false;
161 if args.local && !args.dry_run {
162 crate::git_ops::delete_local_branch(&pr.head_branch, args.force).await?;
163 local_deleted = true;
164 }
165
166 let mut worktree_exited = false;
168 let mut worktree_removed = false;
169
170 if crate::git_ops::is_in_worktree().await? && !args.dry_run {
171 crate::git_ops::exit_worktree().await?;
172 worktree_exited = true;
173
174 if let Some(ref worktree_path) = args.worktree {
175 crate::git_ops::remove_worktree(worktree_path).await?;
176 worktree_removed = true;
177 }
178 }
179
180 Ok(CleanupResult {
181 pr_number: pr.number,
182 pr_title: pr.title,
183 branch: pr.head_branch,
184 remote_deleted,
185 local_deleted,
186 worktree_exited,
187 worktree_removed,
188 dry_run: args.dry_run,
189 error: None,
190 })
191 }
192
193 pub async fn cleanup(
202 provider: &dyn crate::pr::PrProvider,
203 args: &CleanupArgs,
204 ) -> crate::Result<Vec<CleanupResult>> {
205 let mut results = Vec::new();
206
207 for &pr_number in &args.numbers {
208 match Self::cleanup_single_pr(provider, pr_number, args).await {
209 Ok(result) => results.push(result),
210 Err(e) => {
211 results.push(CleanupResult {
213 pr_number,
214 pr_title: String::new(),
215 branch: String::new(),
216 remote_deleted: false,
217 local_deleted: false,
218 worktree_exited: false,
219 worktree_removed: false,
220 dry_run: args.dry_run,
221 error: Some(e.to_string()),
222 });
223 }
224 }
225 }
226
227 Ok(results)
228 }
229
230 pub async fn cleanup_merged(
236 provider: &dyn crate::pr::PrProvider,
237 args: &CleanupArgs,
238 ) -> crate::Result<Vec<CleanupResult>> {
239 let prs = provider
240 .list(crate::pr::ListPrArgs {
241 state: Some(State::Closed),
242 limit: None,
243 })
244 .await?;
245
246 let merged_prs: Vec<_> = prs
248 .into_iter()
249 .filter(|pr| pr.state == State::Closed)
250 .collect();
251
252 let mut results = Vec::new();
253 for pr in merged_prs {
254 let mut pr_args = args.clone();
255 pr_args.numbers = vec![pr.number];
256
257 match Self::cleanup_single_pr(provider, pr.number, &pr_args).await {
258 Ok(result) => results.push(result),
259 Err(e) => {
260 results.push(CleanupResult {
261 pr_number: pr.number,
262 pr_title: pr.title,
263 branch: pr.head_branch,
264 remote_deleted: false,
265 local_deleted: false,
266 worktree_exited: false,
267 worktree_removed: false,
268 dry_run: args.dry_run,
269 error: Some(e.to_string()),
270 });
271 }
272 }
273 }
274
275 Ok(results)
276 }
277
278 pub async fn cleanup_closed(
284 provider: &dyn crate::pr::PrProvider,
285 args: &CleanupArgs,
286 ) -> crate::Result<Vec<CleanupResult>> {
287 Self::cleanup_merged(provider, args).await
289 }
290}
291
292async fn get_current_branch() -> crate::Result<String> {
298 let output = tokio::process::Command::new("git")
299 .args(["branch", "--show-current"])
300 .output()
301 .await
302 .map_err(|e| crate::CoreError::App(format!("Failed to get current branch: {e}")))?;
303
304 if !output.status.success() {
305 return Err(crate::CoreError::App(
306 "Failed to get current branch".to_string(),
307 ));
308 }
309
310 let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
311 if branch.is_empty() {
312 return Err(crate::CoreError::App("HEAD is detached".to_string()));
313 }
314
315 Ok(branch)
316}
317
318#[cfg(test)]
319mod tests {
320 use super::*;
321
322 #[test]
323 fn test_should_create_cleanup_args_with_defaults() {
324 let args = CleanupArgs {
325 numbers: vec![172],
326 merged: false,
327 closed: false,
328 worktree: None,
329 remote: true,
330 local: true,
331 force: false,
332 dry_run: false,
333 yes: false,
334 };
335 assert_eq!(args.numbers, vec![172]);
336 assert!(args.remote);
337 assert!(args.local);
338 assert!(!args.force);
339 }
340
341 #[test]
342 fn test_should_create_cleanup_args_for_batch() {
343 let args = CleanupArgs {
344 numbers: vec![172, 173, 174],
345 merged: false,
346 closed: false,
347 worktree: None,
348 remote: true,
349 local: true,
350 force: false,
351 dry_run: false,
352 yes: false,
353 };
354 assert_eq!(args.numbers.len(), 3);
355 }
356
357 #[test]
358 fn test_should_create_cleanup_args_for_merged() {
359 let args = CleanupArgs {
360 numbers: vec![],
361 merged: true,
362 closed: false,
363 worktree: None,
364 remote: true,
365 local: true,
366 force: false,
367 dry_run: false,
368 yes: false,
369 };
370 assert!(args.merged);
371 assert!(!args.closed);
372 }
373
374 #[test]
375 fn test_should_serialize_cleanup_result() {
376 let result = CleanupResult {
377 pr_number: 172,
378 pr_title: "Add feature".to_string(),
379 branch: "feature/x".to_string(),
380 remote_deleted: true,
381 local_deleted: true,
382 worktree_exited: false,
383 worktree_removed: false,
384 dry_run: false,
385 error: None,
386 };
387 let json = serde_json::to_string(&result).expect("serialize");
388 assert!(json.contains("\"prNumber\":172"));
389 assert!(json.contains("\"remoteDeleted\":true"));
390 }
391
392 #[test]
393 fn test_should_serialize_cleanup_result_with_error() {
394 let result = CleanupResult {
395 pr_number: 175,
396 pr_title: "Protected branch".to_string(),
397 branch: "main".to_string(),
398 remote_deleted: false,
399 local_deleted: false,
400 worktree_exited: false,
401 worktree_removed: false,
402 dry_run: false,
403 error: Some("Branch 'main' is protected".to_string()),
404 };
405 let json = serde_json::to_string(&result).expect("serialize");
406 assert!(json.contains("\"error\":"));
407 assert!(json.contains("protected"));
408 }
409
410 #[test]
411 fn test_should_identify_main_as_protected() {
412 assert!(is_protected_branch("main"));
413 }
414
415 #[test]
416 fn test_should_identify_master_as_protected() {
417 assert!(is_protected_branch("master"));
418 }
419
420 #[test]
421 fn test_should_identify_develop_as_protected() {
422 assert!(is_protected_branch("develop"));
423 }
424
425 #[test]
426 fn test_should_identify_release_branches_as_protected() {
427 assert!(is_protected_branch("release/1.0"));
428 assert!(is_protected_branch("release/v2.0.0"));
429 }
430
431 #[test]
432 fn test_should_not_identify_feature_branch_as_protected() {
433 assert!(!is_protected_branch("feature/x"));
434 assert!(!is_protected_branch("bugfix/123"));
435 }
436
437 #[test]
438 fn test_should_allow_cleanup_of_merged_pr() {
439 let pr = PrData {
440 number: 172,
441 title: "Add feature".to_string(),
442 body: None,
443 state: State::Closed,
444 draft: false,
445 author: crate::types::UserSummary {
446 login: "alice".to_string(),
447 id: "1".to_string(),
448 },
449 base_branch: "main".to_string(),
450 head_branch: "feature/x".to_string(),
451 created_at: chrono::Utc::now(),
452 updated_at: chrono::Utc::now(),
453 url: "https://github.com/test/repo/pull/172".to_string(),
454 };
455 let result = check_safety(&pr, "main", false);
456 assert!(result.is_ok());
457 }
458
459 #[test]
460 fn test_should_refuse_to_delete_protected_branch() {
461 let pr = PrData {
462 number: 172,
463 title: "Update main".to_string(),
464 body: None,
465 state: State::Closed,
466 draft: false,
467 author: crate::types::UserSummary {
468 login: "alice".to_string(),
469 id: "1".to_string(),
470 },
471 base_branch: "main".to_string(),
472 head_branch: "main".to_string(),
473 created_at: chrono::Utc::now(),
474 updated_at: chrono::Utc::now(),
475 url: "https://github.com/test/repo/pull/172".to_string(),
476 };
477 let result = check_safety(&pr, "develop", false);
478 assert!(result.is_err());
479 let err = result.unwrap_err().to_string();
480 assert!(err.contains("受保护"));
481 }
482
483 #[test]
484 fn test_should_refuse_to_delete_current_branch() {
485 let pr = PrData {
486 number: 172,
487 title: "Add feature".to_string(),
488 body: None,
489 state: State::Closed,
490 draft: false,
491 author: crate::types::UserSummary {
492 login: "alice".to_string(),
493 id: "1".to_string(),
494 },
495 base_branch: "main".to_string(),
496 head_branch: "feature/x".to_string(),
497 created_at: chrono::Utc::now(),
498 updated_at: chrono::Utc::now(),
499 url: "https://github.com/test/repo/pull/172".to_string(),
500 };
501 let result = check_safety(&pr, "feature/x", false);
502 assert!(result.is_err());
503 let err = result.unwrap_err().to_string();
504 assert!(err.contains("当前检出"));
505 }
506
507 #[test]
508 fn test_should_require_merged_or_closed_state() {
509 let pr = PrData {
510 number: 172,
511 title: "Add feature".to_string(),
512 body: None,
513 state: State::Open,
514 draft: false,
515 author: crate::types::UserSummary {
516 login: "alice".to_string(),
517 id: "1".to_string(),
518 },
519 base_branch: "main".to_string(),
520 head_branch: "feature/x".to_string(),
521 created_at: chrono::Utc::now(),
522 updated_at: chrono::Utc::now(),
523 url: "https://github.com/test/repo/pull/172".to_string(),
524 };
525 let result = check_safety(&pr, "main", false);
526 assert!(result.is_err());
527 let err = result.unwrap_err().to_string();
528 assert!(err.contains("尚未合并或关闭"));
529 }
530
531 #[test]
532 fn test_should_allow_unmerged_pr_with_force() {
533 let pr = PrData {
534 number: 172,
535 title: "Add feature".to_string(),
536 body: None,
537 state: State::Open,
538 draft: false,
539 author: crate::types::UserSummary {
540 login: "alice".to_string(),
541 id: "1".to_string(),
542 },
543 base_branch: "main".to_string(),
544 head_branch: "feature/x".to_string(),
545 created_at: chrono::Utc::now(),
546 updated_at: chrono::Utc::now(),
547 url: "https://github.com/test/repo/pull/172".to_string(),
548 };
549 let result = check_safety(&pr, "main", true);
550 assert!(result.is_ok());
551 }
552}