use serde::{Deserialize, Serialize};
use crate::{pr::PrData, types::State};
#[derive(Debug, Clone)]
#[allow(
clippy::struct_excessive_bools,
reason = "Configuration type with boolean flags"
)]
pub struct CleanupArgs {
pub numbers: Vec<u64>,
pub merged: bool,
pub closed: bool,
pub worktree: Option<String>,
pub remote: bool,
pub local: bool,
pub force: bool,
pub dry_run: bool,
pub yes: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(
clippy::struct_excessive_bools,
reason = "Result type tracking multiple operation outcomes"
)]
pub struct CleanupResult {
pub pr_number: u64,
pub pr_title: String,
pub branch: String,
pub remote_deleted: bool,
pub local_deleted: bool,
pub worktree_exited: bool,
pub worktree_removed: bool,
pub dry_run: bool,
pub error: Option<String>,
}
#[must_use]
pub fn is_protected_branch(branch: &str) -> bool {
matches!(branch, "main" | "master" | "develop") || branch.starts_with("release/")
}
pub fn check_safety(pr: &PrData, current_branch: &str, force: bool) -> crate::Result<()> {
if !force && pr.state != State::Closed {
return Err(crate::CoreError::App(format!(
"PR #{} 尚未合并或关闭。使用 --force 强制清理。",
pr.number
)));
}
if is_protected_branch(&pr.head_branch) {
return Err(crate::CoreError::App(format!(
"分支 '{}' 受保护,拒绝删除",
pr.head_branch
)));
}
if pr.head_branch == current_branch {
return Err(crate::CoreError::App(format!(
"无法删除当前检出的分支 '{}'",
pr.head_branch
)));
}
Ok(())
}
#[derive(Debug)]
pub struct CleanupService;
impl CleanupService {
pub async fn cleanup_single_pr(
provider: &dyn crate::pr::PrProvider,
pr_number: u64,
args: &CleanupArgs,
) -> crate::Result<CleanupResult> {
let pr = provider.view(pr_number).await?;
let current_branch = get_current_branch().await?;
check_safety(&pr, ¤t_branch, args.force)?;
let mut remote_deleted = false;
if args.remote && !args.dry_run {
if let Err(e) = crate::git_ops::delete_remote_branch(&pr.head_branch).await {
tracing::warn!("Failed to delete remote branch: {}", e);
} else {
remote_deleted = true;
}
}
let mut local_deleted = false;
if args.local && !args.dry_run {
crate::git_ops::delete_local_branch(&pr.head_branch, args.force).await?;
local_deleted = true;
}
let mut worktree_exited = false;
let mut worktree_removed = false;
if crate::git_ops::is_in_worktree().await? && !args.dry_run {
crate::git_ops::exit_worktree().await?;
worktree_exited = true;
if let Some(ref worktree_path) = args.worktree {
crate::git_ops::remove_worktree(worktree_path).await?;
worktree_removed = true;
}
}
Ok(CleanupResult {
pr_number: pr.number,
pr_title: pr.title,
branch: pr.head_branch,
remote_deleted,
local_deleted,
worktree_exited,
worktree_removed,
dry_run: args.dry_run,
error: None,
})
}
pub async fn cleanup(
provider: &dyn crate::pr::PrProvider,
args: &CleanupArgs,
) -> crate::Result<Vec<CleanupResult>> {
let mut results = Vec::new();
for &pr_number in &args.numbers {
match Self::cleanup_single_pr(provider, pr_number, args).await {
Ok(result) => results.push(result),
Err(e) => {
results.push(CleanupResult {
pr_number,
pr_title: String::new(),
branch: String::new(),
remote_deleted: false,
local_deleted: false,
worktree_exited: false,
worktree_removed: false,
dry_run: args.dry_run,
error: Some(e.to_string()),
});
}
}
}
Ok(results)
}
pub async fn cleanup_merged(
provider: &dyn crate::pr::PrProvider,
args: &CleanupArgs,
) -> crate::Result<Vec<CleanupResult>> {
let prs = provider
.list(crate::pr::ListPrArgs {
state: Some(State::Closed),
limit: None,
})
.await?;
let merged_prs: Vec<_> = prs
.into_iter()
.filter(|pr| pr.state == State::Closed)
.collect();
let mut results = Vec::new();
for pr in merged_prs {
let mut pr_args = args.clone();
pr_args.numbers = vec![pr.number];
match Self::cleanup_single_pr(provider, pr.number, &pr_args).await {
Ok(result) => results.push(result),
Err(e) => {
results.push(CleanupResult {
pr_number: pr.number,
pr_title: pr.title,
branch: pr.head_branch,
remote_deleted: false,
local_deleted: false,
worktree_exited: false,
worktree_removed: false,
dry_run: args.dry_run,
error: Some(e.to_string()),
});
}
}
}
Ok(results)
}
pub async fn cleanup_closed(
provider: &dyn crate::pr::PrProvider,
args: &CleanupArgs,
) -> crate::Result<Vec<CleanupResult>> {
Self::cleanup_merged(provider, args).await
}
}
async fn get_current_branch() -> crate::Result<String> {
let output = tokio::process::Command::new("git")
.args(["branch", "--show-current"])
.output()
.await
.map_err(|e| crate::CoreError::App(format!("Failed to get current branch: {e}")))?;
if !output.status.success() {
return Err(crate::CoreError::App(
"Failed to get current branch".to_string(),
));
}
let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
if branch.is_empty() {
return Err(crate::CoreError::App("HEAD is detached".to_string()));
}
Ok(branch)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_should_create_cleanup_args_with_defaults() {
let args = CleanupArgs {
numbers: vec![172],
merged: false,
closed: false,
worktree: None,
remote: true,
local: true,
force: false,
dry_run: false,
yes: false,
};
assert_eq!(args.numbers, vec![172]);
assert!(args.remote);
assert!(args.local);
assert!(!args.force);
}
#[test]
fn test_should_create_cleanup_args_for_batch() {
let args = CleanupArgs {
numbers: vec![172, 173, 174],
merged: false,
closed: false,
worktree: None,
remote: true,
local: true,
force: false,
dry_run: false,
yes: false,
};
assert_eq!(args.numbers.len(), 3);
}
#[test]
fn test_should_create_cleanup_args_for_merged() {
let args = CleanupArgs {
numbers: vec![],
merged: true,
closed: false,
worktree: None,
remote: true,
local: true,
force: false,
dry_run: false,
yes: false,
};
assert!(args.merged);
assert!(!args.closed);
}
#[test]
fn test_should_serialize_cleanup_result() {
let result = CleanupResult {
pr_number: 172,
pr_title: "Add feature".to_string(),
branch: "feature/x".to_string(),
remote_deleted: true,
local_deleted: true,
worktree_exited: false,
worktree_removed: false,
dry_run: false,
error: None,
};
let json = serde_json::to_string(&result).expect("serialize");
assert!(json.contains("\"prNumber\":172"));
assert!(json.contains("\"remoteDeleted\":true"));
}
#[test]
fn test_should_serialize_cleanup_result_with_error() {
let result = CleanupResult {
pr_number: 175,
pr_title: "Protected branch".to_string(),
branch: "main".to_string(),
remote_deleted: false,
local_deleted: false,
worktree_exited: false,
worktree_removed: false,
dry_run: false,
error: Some("Branch 'main' is protected".to_string()),
};
let json = serde_json::to_string(&result).expect("serialize");
assert!(json.contains("\"error\":"));
assert!(json.contains("protected"));
}
#[test]
fn test_should_identify_main_as_protected() {
assert!(is_protected_branch("main"));
}
#[test]
fn test_should_identify_master_as_protected() {
assert!(is_protected_branch("master"));
}
#[test]
fn test_should_identify_develop_as_protected() {
assert!(is_protected_branch("develop"));
}
#[test]
fn test_should_identify_release_branches_as_protected() {
assert!(is_protected_branch("release/1.0"));
assert!(is_protected_branch("release/v2.0.0"));
}
#[test]
fn test_should_not_identify_feature_branch_as_protected() {
assert!(!is_protected_branch("feature/x"));
assert!(!is_protected_branch("bugfix/123"));
}
#[test]
fn test_should_allow_cleanup_of_merged_pr() {
let pr = PrData {
number: 172,
title: "Add feature".to_string(),
body: None,
state: State::Closed,
draft: false,
author: crate::types::UserSummary {
login: "alice".to_string(),
id: "1".to_string(),
},
base_branch: "main".to_string(),
head_branch: "feature/x".to_string(),
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
url: "https://github.com/test/repo/pull/172".to_string(),
};
let result = check_safety(&pr, "main", false);
assert!(result.is_ok());
}
#[test]
fn test_should_refuse_to_delete_protected_branch() {
let pr = PrData {
number: 172,
title: "Update main".to_string(),
body: None,
state: State::Closed,
draft: false,
author: crate::types::UserSummary {
login: "alice".to_string(),
id: "1".to_string(),
},
base_branch: "main".to_string(),
head_branch: "main".to_string(),
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
url: "https://github.com/test/repo/pull/172".to_string(),
};
let result = check_safety(&pr, "develop", false);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(err.contains("受保护"));
}
#[test]
fn test_should_refuse_to_delete_current_branch() {
let pr = PrData {
number: 172,
title: "Add feature".to_string(),
body: None,
state: State::Closed,
draft: false,
author: crate::types::UserSummary {
login: "alice".to_string(),
id: "1".to_string(),
},
base_branch: "main".to_string(),
head_branch: "feature/x".to_string(),
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
url: "https://github.com/test/repo/pull/172".to_string(),
};
let result = check_safety(&pr, "feature/x", false);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(err.contains("当前检出"));
}
#[test]
fn test_should_require_merged_or_closed_state() {
let pr = PrData {
number: 172,
title: "Add feature".to_string(),
body: None,
state: State::Open,
draft: false,
author: crate::types::UserSummary {
login: "alice".to_string(),
id: "1".to_string(),
},
base_branch: "main".to_string(),
head_branch: "feature/x".to_string(),
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
url: "https://github.com/test/repo/pull/172".to_string(),
};
let result = check_safety(&pr, "main", false);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(err.contains("尚未合并或关闭"));
}
#[test]
fn test_should_allow_unmerged_pr_with_force() {
let pr = PrData {
number: 172,
title: "Add feature".to_string(),
body: None,
state: State::Open,
draft: false,
author: crate::types::UserSummary {
login: "alice".to_string(),
id: "1".to_string(),
},
base_branch: "main".to_string(),
head_branch: "feature/x".to_string(),
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
url: "https://github.com/test/repo/pull/172".to_string(),
};
let result = check_safety(&pr, "main", true);
assert!(result.is_ok());
}
}