use clap::Subcommand;
use gitflow_core::{CliOutput, commit::CommitProvider};
use gitflow_gitcode::GitCodeCommitProvider;
use gitflow_github::GitHubCommitProvider;
use gitflow_gitlab::GitLabCommitProvider;
use crate::OutputFormat;
#[derive(Debug, Subcommand)]
pub enum CommitCommand {
View {
sha: String,
},
Diff {
sha: String,
},
Patch {
sha: String,
},
Comment {
sha: String,
#[arg(long)]
body: Option<String>,
#[arg(long = "body-file")]
body_file: Option<String>,
#[arg(long)]
path: Option<String>,
#[arg(long)]
line: Option<u64>,
},
}
#[allow(
clippy::too_many_lines,
reason = "Command dispatch: each match arm maps to one operation"
)]
pub async fn handle(
command: CommitCommand,
platform: &str,
repo: &str,
output_format: OutputFormat,
) -> miette::Result<()> {
let provider: Box<dyn CommitProvider> = match platform {
"github" => Box::new(GitHubCommitProvider::new(repo)),
"gitlab" => Box::new(GitLabCommitProvider::new(repo)),
"gitcode" => Box::new(GitCodeCommitProvider::new(repo)),
other => {
return Err(miette::miette!(
"Platform '{other}' not yet supported for commit commands"
));
}
};
match command {
CommitCommand::View { sha } => {
let detail = provider
.view(&sha)
.await
.map_err(|e| miette::miette!("Failed to view commit {sha}: {e}"))?;
let output = CliOutput::success(detail, platform, "commit view");
print_output(&output, &output_format)?;
}
CommitCommand::Diff { sha } => {
let diff = provider
.diff(&sha)
.await
.map_err(|e| miette::miette!("Failed to get diff for commit {sha}: {e}"))?;
let output = CliOutput::success(
serde_json::json!({ "sha": sha, "diff": diff }),
platform,
"commit diff",
);
print_output(&output, &output_format)?;
}
CommitCommand::Patch { sha } => {
let patch = provider
.patch(&sha)
.await
.map_err(|e| miette::miette!("Failed to get patch for commit {sha}: {e}"))?;
let output = CliOutput::success(
serde_json::json!({ "sha": sha, "patch": patch }),
platform,
"commit patch",
);
print_output(&output, &output_format)?;
}
CommitCommand::Comment {
sha,
body,
body_file,
path,
line,
} => {
let resolved_body = resolve_comment_body(body, body_file)?;
let path = path.ok_or_else(|| {
miette::miette!("--path is required for commit comment. Specify the file path.")
})?;
let line = line.ok_or_else(|| {
miette::miette!("--line is required for commit comment. Specify the line number.")
})?;
provider
.comment(&sha, &resolved_body, &path, line)
.await
.map_err(|e| {
miette::miette!("Failed to comment on commit {sha} at {path}:{line}: {e}")
})?;
let result = serde_json::json!({
"sha": sha,
"path": path,
"line": line,
"commented": true,
});
let output = CliOutput::success(result, platform, "commit comment");
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_comment_body(body: Option<String>, body_file: Option<String>) -> miette::Result<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 safe = gitflow_core::SafePath::new_allow_absolute(&path)
.map_err(|e| miette::miette!("无效的 --body-file 参数: {e}"))?;
let content = std::fs::read_to_string(safe.as_path())
.map_err(|e| miette::miette!("Failed to read body file '{path}': {e}"))?;
return Ok(content);
}
body.ok_or_else(|| miette::miette!("Comment 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_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_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_reject_both_body_and_body_file() {
let result = resolve_comment_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_resolve_comment_body_from_file() {
let file = tempfile::NamedTempFile::new().expect("create temp file");
std::fs::write(file.path(), "commit comment from file").expect("write temp file");
let result = resolve_comment_body(None, Some(file.path().to_string_lossy().into_owned()));
assert!(result.is_ok());
assert_eq!(result.expect("already checked"), "commit comment from file");
}
#[test]
fn test_should_error_on_missing_body_file() {
let result = resolve_comment_body(None, Some("/nonexistent/path/comment.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_body_file_with_parent_dir_traversal() {
let result = resolve_comment_body(None, Some("/tmp/../etc/passwd".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_body_file_with_null_byte() {
let result = resolve_comment_body(None, Some("/tmp/x\0y".into()));
assert!(result.is_err());
}
#[test]
fn test_should_print_json_output() {
let value = serde_json::json!({"sha": "abc123", "message": "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_print_toon_output() {
let value = serde_json::json!({"sha": "abc123", "message": "test"});
let result = print_output(&value, &OutputFormat::Toon);
assert!(result.is_ok());
}
#[test]
fn test_should_print_auto_output() {
let value = serde_json::json!({"sha": "abc123", "message": "test"});
let result = print_output(&value, &OutputFormat::Auto);
assert!(result.is_ok());
}
#[test]
fn test_should_parse_commit_view() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "commit", "view", "abc123def"]).expect("parse");
match cli.command {
crate::Commands::Commit(CommitCommand::View { sha }) => {
assert_eq!(sha, "abc123def");
}
_ => panic!("Expected CommitCommand::View"),
}
}
#[test]
fn test_should_parse_commit_diff() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "commit", "diff", "deadbeef"]).expect("parse");
match cli.command {
crate::Commands::Commit(CommitCommand::Diff { sha }) => {
assert_eq!(sha, "deadbeef");
}
_ => panic!("Expected CommitCommand::Diff"),
}
}
#[test]
fn test_should_parse_commit_patch() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "commit", "patch", "f00ba42"]).expect("parse");
match cli.command {
crate::Commands::Commit(CommitCommand::Patch { sha }) => {
assert_eq!(sha, "f00ba42");
}
_ => panic!("Expected CommitCommand::Patch"),
}
}
#[test]
fn test_should_parse_commit_comment() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"commit",
"comment",
"abc123",
"--body",
"This looks suspicious",
"--path",
"src/auth.rs",
"--line",
"42",
])
.expect("parse");
match cli.command {
crate::Commands::Commit(CommitCommand::Comment {
sha,
body,
body_file,
path,
line,
}) => {
assert_eq!(sha, "abc123");
assert_eq!(body, Some("This looks suspicious".into()));
assert!(body_file.is_none());
assert_eq!(path, Some("src/auth.rs".into()));
assert_eq!(line, Some(42));
}
_ => panic!("Expected CommitCommand::Comment"),
}
}
#[test]
fn test_should_parse_commit_comment_with_body_file() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"commit",
"comment",
"abc123",
"--body-file",
"/tmp/comment.md",
"--path",
"lib.rs",
"--line",
"10",
])
.expect("parse");
match cli.command {
crate::Commands::Commit(CommitCommand::Comment {
sha,
body,
body_file,
path,
line,
}) => {
assert_eq!(sha, "abc123");
assert!(body.is_none());
assert_eq!(body_file, Some("/tmp/comment.md".into()));
assert_eq!(path, Some("lib.rs".into()));
assert_eq!(line, Some(10));
}
_ => panic!("Expected CommitCommand::Comment"),
}
}
}