use clap::Subcommand;
use gitflow_core::{
CliOutput,
pr::{CreatePrArgs, ListPrArgs, PrProvider},
types::{MergeStrategy, State},
};
use gitflow_gitcode::GitCodePrProvider;
use gitflow_github::GitHubPrProvider;
use gitflow_gitlab::GitLabMrProvider;
use is_terminal::IsTerminal;
use crate::{
OutputFormat,
commands::{list_args::validate_limit, output::print_list_output},
};
#[derive(Debug, Subcommand)]
pub enum PrCommand {
Search(super::query_search::SearchArgs),
Create {
#[arg(long)]
title: String,
#[arg(long)]
head: Option<String>,
#[arg(long)]
base: Option<String>,
#[arg(long)]
body: Option<String>,
#[arg(long = "body-file")]
body_file: Option<String>,
#[arg(long)]
draft: bool,
#[arg(long)]
repo: Option<String>,
#[arg(long = "closes", alias = "fixes")]
closes: Vec<u64>,
#[arg(long)]
milestone: Option<String>,
},
List {
#[arg(long)]
state: Option<String>,
#[arg(long)]
limit: Option<u32>,
},
View {
number: u64,
},
Precheck {
#[arg(long)]
input: String,
#[arg(long, conflicts_with = "live")]
response: Option<String>,
#[arg(long)]
live: bool,
#[arg(long, requires = "live")]
allow_private: bool,
},
Close {
number: u64,
},
Reopen {
number: u64,
},
Comment {
number: u64,
#[arg(long)]
body: Option<String>,
#[arg(long = "body-file")]
body_file: Option<String>,
},
Merge {
number: u64,
#[arg(long)]
strategy: Option<String>,
#[arg(long, default_value_t = false)]
auto: bool,
},
Checkout {
number: u64,
},
Ready {
number: u64,
},
Wip {
number: u64,
},
Sync {
number: u64,
},
Diff {
number: u64,
},
Patch {
number: u64,
},
Cleanup {
#[arg(required = false)]
numbers: Vec<u64>,
#[arg(long)]
worktree: Option<String>,
#[arg(long, default_value = "true")]
remote: bool,
#[arg(long, default_value = "true")]
local: bool,
#[arg(long)]
force: bool,
#[arg(long)]
dry_run: bool,
#[arg(long, short = 'y')]
yes: bool,
#[arg(long, conflicts_with = "numbers")]
merged: bool,
#[arg(long, conflicts_with = "numbers")]
closed: bool,
},
}
#[allow(
clippy::too_many_lines,
reason = "Command dispatch: each match arm maps to one operation"
)]
pub async fn handle(
command: PrCommand,
platform: &str,
repo: &str,
remote_url: &str,
output_format: OutputFormat,
) -> miette::Result<()> {
if let PrCommand::Search(args) = &command {
return super::query_search::handle(
gitflow_core::query_filter::Target::Pr,
args.clone(),
platform,
repo,
remote_url,
)
.await;
}
if let PrCommand::Precheck {
input,
response,
live,
allow_private,
} = &command
{
let report =
super::pr_precheck::handle(input.clone(), response.clone(), *live, *allow_private)
.await?;
let output = CliOutput::success(report, "local", "pr precheck");
return print_output(&output, &output_format);
}
let provider: Box<dyn PrProvider> = match platform {
"github" => Box::new(GitHubPrProvider::new(repo)),
"gitlab" => {
if remote_url.is_empty() {
Box::new(GitLabMrProvider::new(repo))
} else {
Box::new(GitLabMrProvider::with_remote_url(repo, remote_url))
}
}
"gitcode" => Box::new(GitCodePrProvider::new(repo)),
other => {
return Err(miette::miette!(
"Platform '{other}' not yet supported for pr commands"
));
}
};
match command {
PrCommand::Search(_) => return Err(miette::miette!("invalid search dispatch")),
PrCommand::Precheck { .. } => return Err(miette::miette!("invalid precheck dispatch")),
PrCommand::Create {
title,
head,
base,
body,
body_file,
draft,
repo: target_repo,
closes,
milestone,
} => {
let resolved_body = resolve_body(body, body_file)?;
let resolved_head = resolve_head(head)?;
let resolved_base = match base {
Some(b) => b,
None => resolve_default_branch(provider.default_branch().await),
};
let args = CreatePrArgs {
title,
body: resolved_body,
head: resolved_head,
base: resolved_base,
draft,
repo: target_repo,
closes_issues: closes,
milestone,
};
let pr = provider
.create(args)
.await
.map_err(|e| miette::miette!("Failed to create pr: {e}"))?;
let output = CliOutput::success(pr, platform, "pr create");
print_output(&output, &output_format)?;
}
PrCommand::List { state, limit } => {
let parsed_state = state
.as_deref()
.map(|s| match s {
"open" => Ok(State::Open),
"closed" => Ok(State::Closed),
"all" => Ok(State::All),
other => Err(crate::errors::UserInputError::new(format!(
"Invalid state '{other}'. Expected 'open', 'closed', or 'all'."
))),
})
.transpose()?;
let limit = validate_limit(limit)?;
let args = ListPrArgs {
state: parsed_state,
limit,
};
let paged = provider
.list(args)
.await
.map_err(|e| miette::miette!("Failed to list prs: {e}"))?;
let (items, meta) = paged.into_parts();
print_list_output(items, meta, platform, "pr list", &output_format)?;
}
PrCommand::View { number } => {
let pr = provider
.view(number)
.await
.map_err(|e| miette::miette!("Failed to view pr #{number}: {e}"))?;
let output = CliOutput::success(pr, platform, "pr view");
print_output(&output, &output_format)?;
}
PrCommand::Close { number } => {
let pr = provider
.close(number)
.await
.map_err(|e| miette::miette!("Failed to close pr #{number}: {e}"))?;
let output = CliOutput::success(pr, platform, "pr close");
print_output(&output, &output_format)?;
}
PrCommand::Reopen { number } => {
let pr = provider
.reopen(number)
.await
.map_err(|e| miette::miette!("Failed to reopen pr #{number}: {e}"))?;
let output = CliOutput::success(pr, platform, "pr reopen");
print_output(&output, &output_format)?;
}
PrCommand::Comment {
number,
body,
body_file,
} => {
let resolved_body = resolve_comment_body(body, body_file)?;
let comment = provider
.comment(number, &resolved_body)
.await
.map_err(|e| miette::miette!("Failed to comment on pr #{number}: {e}"))?;
let output = CliOutput::success(comment, platform, "pr comment");
print_output(&output, &output_format)?;
}
PrCommand::Merge {
number,
strategy,
auto,
} => {
let parsed_strategy = match strategy.as_deref() {
Some("merge") => Some(MergeStrategy::Merge),
Some("squash") => Some(MergeStrategy::Squash),
Some("rebase") => Some(MergeStrategy::Rebase),
None => None,
Some(other) => {
return Err(miette::miette!(
"Invalid merge strategy '{other}'. Expected 'merge', 'squash', or \
'rebase'."
));
}
};
let result = provider
.merge(number, parsed_strategy, auto)
.await
.map_err(|e| miette::miette!("Failed to merge pr #{number}: {e}"))?;
let output = CliOutput::success(result, platform, "pr merge");
print_output(&output, &output_format)?;
}
PrCommand::Checkout { number } => {
provider
.checkout(number)
.await
.map_err(|e| miette::miette!("Failed to checkout pr #{number}: {e}"))?;
let result = serde_json::json!({
"number": number,
"checked_out": true,
});
let output = CliOutput::success(result, platform, "pr checkout");
print_output(&output, &output_format)?;
}
PrCommand::Ready { number } => {
let pr = provider
.mark_ready(number)
.await
.map_err(|e| miette::miette!("Failed to mark pr #{number} as ready: {e}"))?;
let output = CliOutput::success(pr, platform, "pr ready");
print_output(&output, &output_format)?;
}
PrCommand::Wip { number } => {
let pr = provider
.mark_wip(number)
.await
.map_err(|e| miette::miette!("Failed to mark pr #{number} as draft: {e}"))?;
let output = CliOutput::success(pr, platform, "pr wip");
print_output(&output, &output_format)?;
}
PrCommand::Sync { number } => {
provider
.sync_branch(number)
.await
.map_err(|e| miette::miette!("Failed to sync pr #{number} branch: {e}"))?;
let result = serde_json::json!({
"number": number,
"synced": true,
});
let output = CliOutput::success(result, platform, "pr sync");
print_output(&output, &output_format)?;
}
PrCommand::Diff { number } => {
let diff = provider
.diff(number)
.await
.map_err(|e| miette::miette!("Failed to get diff for pr #{number}: {e}"))?;
let output = CliOutput::success(
serde_json::json!({ "number": number, "diff": diff }),
platform,
"pr diff",
);
print_output(&output, &output_format)?;
}
PrCommand::Patch { number } => {
let patch = provider
.patch(number)
.await
.map_err(|e| miette::miette!("Failed to get patch for pr #{number}: {e}"))?;
let output = CliOutput::success(
serde_json::json!({ "number": number, "patch": patch }),
platform,
"pr patch",
);
print_output(&output, &output_format)?;
}
PrCommand::Cleanup {
numbers,
worktree,
remote,
local,
force,
dry_run,
yes,
merged,
closed,
} => {
let args = gitflow_core::cleanup::CleanupArgs {
numbers,
merged,
closed,
worktree,
remote,
local,
force,
dry_run,
yes,
};
if args.merged || args.closed {
let plan = if args.merged {
gitflow_core::cleanup::CleanupService::plan_merged(&*provider)
.await
.map_err(|e| miette::miette!("Failed to plan merged PR cleanup: {e}"))?
} else {
gitflow_core::cleanup::CleanupService::plan_closed(&*provider)
.await
.map_err(|e| miette::miette!("Failed to plan closed PR cleanup: {e}"))?
};
if plan.truncated {
eprintln!(
"警告:仓库中还有更多符合条件的 PR 未被纳入本次计划(已达到分页上限)。"
);
}
if !args.yes
&& !args.dry_run
&& !confirm_cleanup(plan.targets.len(), plan.truncated)?
{
eprintln!("已取消,未删除任何内容。");
return Ok(());
}
let truncated = plan.truncated;
let limit = plan.limit;
let results =
gitflow_core::cleanup::CleanupService::execute_plan(&*provider, &args, &plan)
.await
.map_err(|e| miette::miette!("Failed to execute PR cleanup plan: {e}"))?;
let meta = cleanup_pagination_meta(truncated, limit, results.len());
let output =
gitflow_core::CliOutput::success_paged(results, meta, platform, "pr cleanup");
print_output(&output, &output_format)?;
} else {
let results = gitflow_core::cleanup::CleanupService::cleanup(&*provider, &args)
.await
.map_err(|e| miette::miette!("Failed to cleanup PRs: {e}"))?;
let output = CliOutput::success(results, platform, "pr cleanup");
print_output(&output, &output_format)?;
}
}
}
Ok(())
}
#[must_use]
pub fn cleanup_pagination_meta(
truncated: bool,
limit: u32,
returned: usize,
) -> gitflow_core::PaginationMeta {
gitflow_core::PaginationMeta {
truncated,
returned,
limit,
}
}
#[must_use]
pub fn cleanup_confirmation_prompt(count: usize, truncated: bool) -> String {
let mut prompt = format!("即将清理 {count} 个 PR 的远程分支、本地分支与 worktree,是否继续?");
if truncated {
prompt.push_str(" 注意:仓库中还有更多符合条件的 PR 未被纳入本次计划(已达到分页上限)。");
}
prompt
}
fn confirm_cleanup(count: usize, truncated: bool) -> miette::Result<bool> {
if !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal() {
return Err(miette::miette!(
"Refusing to prompt for confirmation in a non-interactive session; re-run with --yes \
to skip confirmation."
));
}
let prompt = cleanup_confirmation_prompt(count, truncated);
eprint!("{prompt} [y/N] ");
let _ = std::io::Write::flush(&mut std::io::stderr());
let stdin = std::io::stdin();
let mut reader = stdin.lock();
confirm_cleanup_with_reader(&mut reader)
}
fn confirm_cleanup_with_reader(reader: &mut impl std::io::BufRead) -> miette::Result<bool> {
let mut line = String::new();
reader
.read_line(&mut line)
.map_err(|e| miette::miette!("Failed to read confirmation: {e}"))?;
Ok(cleanup_confirm_answer(&line))
}
#[must_use]
fn cleanup_confirm_answer(line: &str) -> bool {
matches!(line.trim().to_lowercase().as_str(), "y" | "yes")
}
#[allow(
clippy::disallowed_methods,
reason = "Sync file read; called from async handler but file body input is small and local"
)]
fn resolve_body(body: Option<String>, body_file: Option<String>) -> miette::Result<Option<String>> {
if body.is_some() && body_file.is_some() {
return Err(miette::miette!(
"Cannot specify both --body and --body-file"
));
}
if let Some(path) = body_file {
let content = std::fs::read_to_string(&path)
.map_err(|e| miette::miette!("Failed to read body file '{path}': {e}"))?;
return Ok(Some(content));
}
Ok(body)
}
fn resolve_comment_body(body: Option<String>, body_file: Option<String>) -> miette::Result<String> {
let resolved = resolve_body(body, body_file)?;
resolved.ok_or_else(|| miette::miette!("Comment body is required. Use --body or --body-file."))
}
#[allow(
clippy::disallowed_types,
reason = "Quick sync `git` call; converting to async adds overhead disproportionate to the \
work"
)]
fn resolve_head(head: Option<String>) -> miette::Result<String> {
if let Some(branch) = head {
return Ok(branch);
}
let output = std::process::Command::new("git")
.args(["branch", "--show-current"])
.output()
.map_err(|e| miette::miette!("Failed to detect current git branch: {e}"))?;
if !output.status.success() {
return Err(miette::miette!(
"Could not detect current branch. Use --head to specify explicitly."
));
}
let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
if branch.is_empty() {
return Err(miette::miette!(
"Current git HEAD is detached. Use --head to specify the source branch explicitly."
));
}
Ok(branch)
}
fn resolve_default_branch(detected: gitflow_core::Result<String>) -> String {
detected.unwrap_or_else(|e| {
tracing::debug!(error = %e, "default_branch query failed, falling back to \"main\"");
"main".to_string()
})
}
fn print_output<T: serde::Serialize>(value: &T, format: &OutputFormat) -> miette::Result<()> {
crate::commands::output::print_output(value, format)
}
#[cfg(test)]
#[allow(
clippy::panic,
reason = "Test code: panic is acceptable for assertion failures"
)]
mod tests {
use clap::Parser;
use super::*;
#[test]
fn test_should_resolve_body_with_body_only() {
let result = resolve_body(Some("hello".into()), None);
assert!(result.is_ok());
assert_eq!(result.expect("already checked"), Some("hello".into()));
}
#[test]
fn test_should_resolve_body_with_none() {
let result = resolve_body(None, None);
assert!(result.is_ok());
assert_eq!(result.expect("already checked"), None);
}
#[test]
fn test_should_resolve_body_from_file() {
let file = tempfile::NamedTempFile::new().expect("create temp file");
std::fs::write(file.path(), "pr body from file").expect("write temp file");
let result = resolve_body(None, Some(file.path().to_string_lossy().into_owned()));
assert!(result.is_ok());
assert_eq!(
result.expect("already checked"),
Some("pr body from file".into())
);
}
#[test]
fn test_should_error_on_missing_body_file() {
let result = resolve_body(None, Some("/nonexistent/path/body.md".into()));
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(err.contains("Failed to read body file"));
}
#[test]
fn test_should_reject_both_body_and_body_file() {
let result = resolve_body(Some("hello".into()), Some("/tmp/body.md".into()));
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(err.contains("Cannot specify both"));
}
#[test]
fn test_should_require_comment_body() {
let result = resolve_comment_body(None, None);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(err.contains("Comment body is required"));
}
#[test]
fn test_should_resolve_comment_body_with_body() {
let result = resolve_comment_body(Some("LGTM".into()), None);
assert!(result.is_ok());
assert_eq!(result.expect("already checked"), "LGTM");
}
#[test]
fn test_should_resolve_head_with_explicit_value() {
let result = resolve_head(Some("feature/my-branch".into()));
assert!(result.is_ok());
assert_eq!(result.expect("already checked"), "feature/my-branch");
}
#[test]
fn test_should_use_detected_branch_on_success() {
let result = resolve_default_branch(Ok("dev".to_string()));
assert_eq!(result, "dev");
}
#[test]
fn test_should_fallback_to_main_on_detection_failure() {
let result = resolve_default_branch(Err(gitflow_core::CoreError::Platform(
"unsupported".to_string(),
)));
assert_eq!(result, "main");
}
#[test]
fn test_should_print_json_output() {
let value = serde_json::json!({"number": 1, "title": "test"});
let result = print_output(&value, &OutputFormat::Json);
assert!(result.is_ok());
}
#[test]
fn test_should_accept_text_output() {
let value = serde_json::json!({"number": 1});
let result = print_output(&value, &OutputFormat::Text);
assert!(result.is_ok());
}
#[test]
fn test_should_parse_read_only_pr_precheck() {
let cli = crate::Cli::try_parse_from([
"gf",
"pr",
"precheck",
"--input",
"/tmp/pr.json",
"--live",
"--allow-private",
])
.expect("parse");
assert!(matches!(
cli.command,
crate::Commands::Pr(PrCommand::Precheck {
live: true,
allow_private: true,
..
})
));
}
#[test]
fn test_should_parse_pr_close() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "close", "42"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Close { number }) => {
assert_eq!(number, 42);
}
_ => panic!("Expected PrCommand::Close"),
}
}
#[test]
fn test_should_parse_pr_reopen() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "reopen", "7"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Reopen { number }) => {
assert_eq!(number, 7);
}
_ => panic!("Expected PrCommand::Reopen"),
}
}
#[test]
fn test_should_parse_pr_comment_with_body() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "comment", "10", "--body", "LGTM"])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Comment {
number,
body,
body_file,
}) => {
assert_eq!(number, 10);
assert_eq!(body, Some("LGTM".into()));
assert!(body_file.is_none());
}
_ => panic!("Expected PrCommand::Comment"),
}
}
#[test]
fn test_should_parse_pr_merge_with_strategy() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "pr", "merge", "5", "--strategy", "squash"])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Merge {
number,
strategy,
auto,
}) => {
assert_eq!(number, 5);
assert_eq!(strategy, Some("squash".into()));
assert!(!auto, "auto must default to false");
}
_ => panic!("Expected PrCommand::Merge"),
}
}
#[test]
fn test_should_parse_pr_merge_without_strategy() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "merge", "3"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Merge {
number,
strategy,
auto,
}) => {
assert_eq!(number, 3);
assert!(strategy.is_none());
assert!(!auto, "auto must default to false");
}
_ => panic!("Expected PrCommand::Merge"),
}
}
#[test]
fn test_should_parse_pr_merge_with_auto() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "pr", "merge", "7", "--auto"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Merge { auto, number, .. }) => {
assert_eq!(number, 7);
assert!(auto, "--auto must set auto to true");
}
_ => panic!("Expected PrCommand::Merge"),
}
}
#[test]
fn test_should_parse_pr_checkout() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "checkout", "15"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Checkout { number }) => {
assert_eq!(number, 15);
}
_ => panic!("Expected PrCommand::Checkout"),
}
}
#[test]
fn test_should_parse_pr_ready() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "ready", "8"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Ready { number }) => {
assert_eq!(number, 8);
}
_ => panic!("Expected PrCommand::Ready"),
}
}
#[test]
fn test_should_parse_pr_wip() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "wip", "12"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Wip { number }) => {
assert_eq!(number, 12);
}
_ => panic!("Expected PrCommand::Wip"),
}
}
#[test]
fn test_should_parse_pr_sync() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "sync", "20"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Sync { number }) => {
assert_eq!(number, 20);
}
_ => panic!("Expected PrCommand::Sync"),
}
}
#[test]
fn test_should_parse_pr_diff() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "diff", "42"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Diff { number }) => {
assert_eq!(number, 42);
}
_ => panic!("Expected PrCommand::Diff"),
}
}
#[test]
fn test_should_parse_pr_patch() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "patch", "17"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Patch { number }) => {
assert_eq!(number, 17);
}
_ => panic!("Expected PrCommand::Patch"),
}
}
#[test]
fn test_should_parse_pr_view() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "view", "42"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::View { number }) => {
assert_eq!(number, 42);
}
_ => panic!("Expected PrCommand::View"),
}
}
#[test]
fn test_should_parse_pr_list_with_state() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow", "pr", "list", "--state", "open", "--limit", "20",
])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::List { state, limit }) => {
assert_eq!(state, Some("open".into()));
assert_eq!(limit, Some(20));
}
_ => panic!("Expected PrCommand::List"),
}
}
#[test]
fn test_should_parse_pr_create_with_repo_and_head() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"pr",
"create",
"--title",
"Feature PR",
"--head",
"feature/my-branch",
"--base",
"develop",
"--repo",
"org/repo",
"--draft",
])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Create {
title,
head,
base,
repo,
draft,
..
}) => {
assert_eq!(title, "Feature PR");
assert_eq!(head, Some("feature/my-branch".into()));
assert_eq!(base, Some("develop".into()));
assert_eq!(repo, Some("org/repo".into()));
assert!(draft);
}
_ => panic!("Expected PrCommand::Create"),
}
}
#[test]
fn test_should_parse_pr_create_minimal() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "create", "--title", "Minimal PR"])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Create {
title,
head,
base,
draft,
repo,
..
}) => {
assert_eq!(title, "Minimal PR");
assert!(head.is_none());
assert!(base.is_none());
assert!(!draft);
assert!(repo.is_none());
}
_ => panic!("Expected PrCommand::Create"),
}
}
#[test]
fn test_should_parse_pr_create_with_milestone() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"pr",
"create",
"--title",
"Feature PR",
"--milestone",
"v1.0",
])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Create { milestone, .. }) => {
assert_eq!(milestone, Some("v1.0".to_string()));
}
_ => panic!("Expected PrCommand::Create"),
}
}
#[test]
fn test_should_parse_pr_create_without_milestone() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "create", "--title", "Feature PR"])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Create { milestone, .. }) => {
assert!(milestone.is_none());
}
_ => panic!("Expected PrCommand::Create"),
}
}
#[test]
fn test_should_parse_pr_list_without_args() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "list"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::List { state, limit }) => {
assert!(state.is_none());
assert!(limit.is_none());
}
_ => panic!("Expected PrCommand::List"),
}
}
#[test]
fn test_should_accept_state_all_for_pr_list() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gf", "pr", "list", "--state", "all"]);
assert!(cli.is_ok());
}
#[test]
fn test_should_print_toon_output() {
let value = serde_json::json!({"number": 1, "title": "test"});
let result = print_output(&value, &OutputFormat::Toon);
assert!(result.is_ok());
}
#[test]
fn test_should_print_auto_output() {
let value = serde_json::json!({"number": 1, "title": "test"});
let result = print_output(&value, &OutputFormat::Auto);
assert!(result.is_ok());
}
#[test]
fn test_should_parse_pr_cleanup_single() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "cleanup", "172"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Cleanup { numbers, .. }) => {
assert_eq!(numbers, vec![172]);
}
_ => panic!("Expected PrCommand::Cleanup"),
}
}
#[test]
fn test_should_parse_pr_cleanup_multiple() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "cleanup", "172", "173", "174"])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Cleanup { numbers, .. }) => {
assert_eq!(numbers, vec![172, 173, 174]);
}
_ => panic!("Expected PrCommand::Cleanup"),
}
}
#[test]
fn test_should_parse_pr_cleanup_with_worktree() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"pr",
"cleanup",
"172",
"--worktree",
".claude/worktrees/feat-172",
])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Cleanup {
numbers, worktree, ..
}) => {
assert_eq!(numbers, vec![172]);
assert_eq!(worktree, Some(".claude/worktrees/feat-172".to_string()));
}
_ => panic!("Expected PrCommand::Cleanup"),
}
}
#[test]
fn test_should_parse_pr_cleanup_merged() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "pr", "cleanup", "--merged"]).expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Cleanup { merged, .. }) => {
assert!(merged);
}
_ => panic!("Expected PrCommand::Cleanup"),
}
}
#[test]
fn test_should_parse_pr_create_with_single_closes() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow", "pr", "create", "--title", "Feature", "--closes", "24",
])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Create { closes, .. }) => {
assert_eq!(closes, vec![24]);
}
_ => panic!("Expected PrCommand::Create"),
}
}
#[test]
fn test_should_parse_pr_create_with_multiple_closes() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow", "pr", "create", "--title", "Feature", "--closes", "24", "--closes", "23",
])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Create { closes, .. }) => {
assert_eq!(closes, vec![24, 23]);
}
_ => panic!("Expected PrCommand::Create"),
}
}
#[test]
fn test_should_parse_pr_create_with_fixes_alias() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow", "pr", "create", "--title", "Feature", "--fixes", "42",
])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Create { closes, .. }) => {
assert_eq!(closes, vec![42]);
}
_ => panic!("Expected PrCommand::Create"),
}
}
#[test]
fn test_should_parse_pr_create_without_closes() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "pr", "create", "--title", "Feature"])
.expect("parse");
match cli.command {
crate::Commands::Pr(PrCommand::Create { closes, .. }) => {
assert!(closes.is_empty());
}
_ => panic!("Expected PrCommand::Create"),
}
}
#[test]
fn test_should_mention_count_in_cleanup_confirmation_prompt() {
let prompt = cleanup_confirmation_prompt(7, false);
assert!(prompt.contains('7'));
}
#[test]
fn test_should_warn_about_more_prs_when_plan_truncated() {
let truncated_prompt = cleanup_confirmation_prompt(1000, true);
assert!(truncated_prompt.contains("更多"));
let complete_prompt = cleanup_confirmation_prompt(3, false);
assert!(!complete_prompt.contains("更多"));
}
#[test]
fn test_should_surface_truncated_flag_in_cleanup_pagination_meta() {
let meta = cleanup_pagination_meta(true, 1000, 3);
assert!(meta.truncated);
assert_eq!(meta.limit, 1000);
assert_eq!(meta.returned, 3);
}
#[test]
fn test_should_not_report_truncated_when_plan_was_not_truncated() {
let meta = cleanup_pagination_meta(false, 1000, 3);
assert!(!meta.truncated);
}
#[test]
fn test_should_emit_pagination_truncated_in_cleanup_json_output_when_plan_truncated() {
let meta = cleanup_pagination_meta(true, 1000, 3);
let results: Vec<gitflow_core::cleanup::CleanupResult> = Vec::new();
let output = gitflow_core::CliOutput::success_paged(results, meta, "github", "pr cleanup");
let json = serde_json::to_value(&output).expect("serialize cleanup output");
assert_eq!(json["pagination"]["truncated"], serde_json::json!(true));
assert_eq!(json["success"], serde_json::json!(true));
}
#[test]
fn test_should_accept_lowercase_y_as_yes() {
assert!(cleanup_confirm_answer("y\n"));
}
#[test]
fn test_should_accept_uppercase_y_as_yes() {
assert!(cleanup_confirm_answer("Y\n"));
}
#[test]
fn test_should_accept_lowercase_yes_as_yes() {
assert!(cleanup_confirm_answer("yes\n"));
}
#[test]
fn test_should_accept_uppercase_yes_as_yes() {
assert!(cleanup_confirm_answer("YES\n"));
}
#[test]
fn test_should_accept_y_with_surrounding_whitespace_as_yes() {
assert!(cleanup_confirm_answer(" y \n"));
}
#[test]
fn test_should_treat_n_as_no() {
assert!(!cleanup_confirm_answer("n\n"));
}
#[test]
fn test_should_treat_empty_line_as_no() {
assert!(!cleanup_confirm_answer("\n"));
}
#[test]
fn test_should_treat_eof_as_no() {
assert!(!cleanup_confirm_answer(""));
}
#[test]
fn test_should_treat_eof_as_no_through_reader() {
let mut reader: &[u8] = b"";
let answer = confirm_cleanup_with_reader(&mut reader).expect("EOF read should not error");
assert!(!answer);
}
#[test]
fn test_should_accept_yes_through_reader() {
let mut reader: &[u8] = b"yes\n";
let answer = confirm_cleanup_with_reader(&mut reader).expect("read should not error");
assert!(answer);
}
}