use clap::Subcommand;
use gitflow_core::{
CliOutput,
review::{ReviewProvider, ReviewState},
};
use gitflow_gitcode::GitCodeReviewProvider;
use gitflow_github::GitHubReviewProvider;
use gitflow_gitlab::GitLabReviewProvider;
use crate::OutputFormat;
#[derive(Debug, Subcommand)]
pub enum ReviewCommand {
Comment {
pr_number: u64,
#[arg(long)]
body: Option<String>,
#[arg(long = "body-file")]
body_file: Option<String>,
},
Approve {
pr_number: u64,
#[arg(long)]
body: Option<String>,
#[arg(long = "body-file")]
body_file: Option<String>,
},
RequestChanges {
pr_number: u64,
#[arg(long)]
body: Option<String>,
#[arg(long = "body-file")]
body_file: Option<String>,
},
Submit {
pr_number: u64,
#[arg(long)]
body: Option<String>,
#[arg(long = "body-file")]
body_file: Option<String>,
#[arg(long)]
event: ReviewEventArg,
},
}
#[derive(Debug, Clone, clap::ValueEnum)]
pub(crate) enum ReviewEventArg {
#[value(name = "approved")]
Approved,
#[value(name = "changes_requested")]
ChangesRequested,
#[value(name = "commented")]
Commented,
}
impl From<ReviewEventArg> for ReviewState {
fn from(arg: ReviewEventArg) -> Self {
match arg {
ReviewEventArg::Approved => ReviewState::Approved,
ReviewEventArg::ChangesRequested => ReviewState::ChangesRequested,
ReviewEventArg::Commented => ReviewState::Commented,
}
}
}
#[allow(
clippy::too_many_lines,
reason = "Command dispatch: each match arm maps to one operation"
)]
pub async fn handle(
command: ReviewCommand,
platform: &str,
repo: &str,
output_format: OutputFormat,
) -> miette::Result<()> {
let provider: Box<dyn ReviewProvider> = match platform {
"github" => Box::new(GitHubReviewProvider::new(repo)),
"gitlab" => Box::new(GitLabReviewProvider::new(repo)),
"gitcode" => Box::new(GitCodeReviewProvider::new(repo)),
other => {
return Err(miette::miette!(
"Platform '{other}' not yet supported for review commands"
));
}
};
match command {
ReviewCommand::Comment {
pr_number,
body,
body_file,
} => {
let resolved_body = resolve_comment_body(body, body_file)?;
let review = provider
.comment(pr_number, &resolved_body)
.await
.map_err(|e| miette::miette!("Failed to comment on PR #{pr_number}: {e}"))?;
let output = CliOutput::success(review, platform, "review comment");
print_output(&output, &output_format)?;
}
ReviewCommand::Approve {
pr_number,
body,
body_file,
} => {
let resolved_body = resolve_body(body, body_file)?;
let review = provider
.approve(pr_number, resolved_body.as_deref())
.await
.map_err(|e| miette::miette!("Failed to approve PR #{pr_number}: {e}"))?;
let output = CliOutput::success(review, platform, "review approve");
print_output(&output, &output_format)?;
}
ReviewCommand::RequestChanges {
pr_number,
body,
body_file,
} => {
let resolved_body = resolve_comment_body(body, body_file)?;
let review = provider
.request_changes(pr_number, &resolved_body)
.await
.map_err(|e| {
miette::miette!("Failed to request changes on PR #{pr_number}: {e}")
})?;
let output = CliOutput::success(review, platform, "review request-changes");
print_output(&output, &output_format)?;
}
ReviewCommand::Submit {
pr_number,
body,
body_file,
event,
} => {
let resolved_body = resolve_body(body, body_file)?;
let state: ReviewState = event.into();
let review = provider
.submit_review(pr_number, state, resolved_body.as_deref())
.await
.map_err(|e| miette::miette!("Failed to submit review for PR #{pr_number}: {e}"))?;
let output = CliOutput::success(review, platform, "review submit");
print_output(&output, &output_format)?;
}
}
Ok(())
}
#[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!("Review body is required. Use --body or --body-file."))
}
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 super::*;
#[test]
fn test_should_resolve_body_with_body_only() {
let result = resolve_body(Some("looks good".into()), None);
assert!(result.is_ok());
assert_eq!(result.expect("already checked"), Some("looks good".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_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("Review body is required"));
}
#[test]
fn test_should_resolve_comment_body_with_body() {
let result = resolve_comment_body(Some("needs work".into()), None);
assert!(result.is_ok());
assert_eq!(result.expect("already checked"), "needs work");
}
#[test]
fn test_should_print_json_output() {
let value = serde_json::json!({"id": 1, "state": "approved"});
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_print_toon_output() {
let value = serde_json::json!({"id": 1, "state": "approved"});
let result = print_output(&value, &OutputFormat::Toon);
assert!(result.is_ok());
}
#[test]
fn test_should_print_auto_output() {
let value = serde_json::json!({"id": 1, "state": "approved"});
let result = print_output(&value, &OutputFormat::Auto);
assert!(result.is_ok());
}
#[test]
fn test_should_parse_review_comment() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "review", "comment", "42", "--body", "LGTM"])
.expect("parse");
match cli.command {
crate::Commands::Review(ReviewCommand::Comment {
pr_number,
body,
body_file,
}) => {
assert_eq!(pr_number, 42);
assert_eq!(body, Some("LGTM".into()));
assert!(body_file.is_none());
}
_ => panic!("Expected ReviewCommand::Comment"),
}
}
#[test]
fn test_should_parse_review_approve() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"review",
"approve",
"10",
"--body",
"Looks good to me",
])
.expect("parse");
match cli.command {
crate::Commands::Review(ReviewCommand::Approve {
pr_number,
body,
body_file,
}) => {
assert_eq!(pr_number, 10);
assert_eq!(body, Some("Looks good to me".into()));
assert!(body_file.is_none());
}
_ => panic!("Expected ReviewCommand::Approve"),
}
}
#[test]
fn test_should_parse_review_request_changes() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"review",
"request-changes",
"5",
"--body",
"Please fix the error handling",
])
.expect("parse");
match cli.command {
crate::Commands::Review(ReviewCommand::RequestChanges {
pr_number,
body,
body_file,
}) => {
assert_eq!(pr_number, 5);
assert_eq!(body, Some("Please fix the error handling".into()));
assert!(body_file.is_none());
}
_ => panic!("Expected ReviewCommand::RequestChanges"),
}
}
#[test]
fn test_should_parse_review_submit() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"review",
"submit",
"7",
"--body",
"Overall good",
"--event",
"approved",
])
.expect("parse");
match cli.command {
crate::Commands::Review(ReviewCommand::Submit {
pr_number,
body,
body_file,
event,
}) => {
assert_eq!(pr_number, 7);
assert_eq!(body, Some("Overall good".into()));
assert!(body_file.is_none());
assert!(matches!(event, ReviewEventArg::Approved));
}
_ => panic!("Expected ReviewCommand::Submit"),
}
}
#[test]
fn test_should_parse_review_submit_changes_requested() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"review",
"submit",
"3",
"--event",
"changes_requested",
])
.expect("parse");
match cli.command {
crate::Commands::Review(ReviewCommand::Submit {
pr_number, event, ..
}) => {
assert_eq!(pr_number, 3);
assert!(matches!(event, ReviewEventArg::ChangesRequested));
}
_ => panic!("Expected ReviewCommand::Submit"),
}
}
#[test]
fn test_should_parse_review_submit_commented() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"review",
"submit",
"15",
"--event",
"commented",
])
.expect("parse");
match cli.command {
crate::Commands::Review(ReviewCommand::Submit { event, .. }) => {
assert!(matches!(event, ReviewEventArg::Commented));
}
_ => panic!("Expected ReviewCommand::Submit"),
}
}
#[test]
fn test_should_convert_review_event_arg() {
assert!(matches!(
ReviewState::from(ReviewEventArg::Approved),
ReviewState::Approved
));
assert!(matches!(
ReviewState::from(ReviewEventArg::ChangesRequested),
ReviewState::ChangesRequested
));
assert!(matches!(
ReviewState::from(ReviewEventArg::Commented),
ReviewState::Commented
));
}
}