use clap::Subcommand;
use gitflow_cli_core::{
CliOutput,
issue::{CreateIssueArgs, IssueProvider, ListIssueArgs},
types::State,
};
use gitflow_cli_gitcode::GitCodeIssueProvider;
use gitflow_cli_github::GitHubIssueProvider;
use gitflow_cli_gitlab::GitLabIssueProvider;
use crate::OutputFormat;
#[derive(Debug, Subcommand)]
pub enum IssueCommand {
Create {
#[arg(long)]
title: String,
#[arg(long)]
body: Option<String>,
#[arg(long = "body-file")]
body_file: Option<String>,
#[arg(long = "label")]
label: Vec<String>,
#[arg(long = "assignee")]
assignee: Vec<String>,
#[arg(long)]
repo: Option<String>,
},
List {
#[arg(long)]
state: Option<String>,
#[arg(long)]
search: Option<String>,
#[arg(long = "label")]
label: Vec<String>,
#[arg(long)]
limit: Option<u32>,
},
View {
number: u64,
},
Close {
number: u64,
},
Reopen {
number: u64,
},
Comment {
number: u64,
#[arg(long)]
body: Option<String>,
#[arg(long = "body-file")]
body_file: Option<String>,
},
AddLabel {
number: u64,
#[arg(long = "label", num_args = 1.., required = true)]
label: Vec<String>,
},
RemoveLabel {
number: u64,
#[arg(long)]
label: String,
},
}
#[allow(
clippy::too_many_lines,
reason = "Command dispatch: each match arm maps to one operation"
)]
pub async fn handle(
command: IssueCommand,
platform: &str,
repo: &str,
output_format: OutputFormat,
) -> miette::Result<()> {
let effective_repo = match &command {
IssueCommand::Create {
repo: Some(override_repo),
..
} => override_repo.as_str(),
_ => repo,
};
let provider: Box<dyn IssueProvider> = match platform {
"github" => Box::new(GitHubIssueProvider::new(effective_repo)),
"gitlab" => Box::new(GitLabIssueProvider::new(effective_repo)),
"gitcode" => Box::new(GitCodeIssueProvider::new(effective_repo)),
other => {
return Err(miette::miette!(
"Platform '{other}' not yet supported for issue commands"
));
}
};
match command {
IssueCommand::Create {
title,
body,
body_file,
label,
assignee,
repo: _,
} => {
let resolved_body = resolve_body(body, body_file)?;
let args = CreateIssueArgs {
title,
body: resolved_body,
labels: label,
assignees: assignee,
};
let issue = provider
.create(args)
.await
.map_err(|e| miette::miette!("Failed to create issue: {e}"))?;
let output = CliOutput::success(issue, platform, "issue create");
print_output(&output, &output_format)?;
}
IssueCommand::List {
state,
search,
label,
limit,
} => {
let parsed_state = state
.as_deref()
.map(|s| match s {
"open" => Ok(State::Open),
"closed" => Ok(State::Closed),
other => Err(miette::miette!(
"Invalid state '{other}'. Expected 'open' or 'closed'."
)),
})
.transpose()?;
let args = ListIssueArgs {
state: parsed_state,
labels: label,
assignee: None,
search,
limit,
};
let issues = provider
.list(args)
.await
.map_err(|e| miette::miette!("Failed to list issues: {e}"))?;
let output = CliOutput::success(issues, platform, "issue list");
print_output(&output, &output_format)?;
}
IssueCommand::View { number } => {
let issue = provider
.view(number)
.await
.map_err(|e| miette::miette!("Failed to view issue #{number}: {e}"))?;
let output = CliOutput::success(issue, platform, "issue view");
print_output(&output, &output_format)?;
}
IssueCommand::Close { number } => {
let issue = provider
.close(number)
.await
.map_err(|e| miette::miette!("Failed to close issue #{number}: {e}"))?;
let output = CliOutput::success(issue, platform, "issue close");
print_output(&output, &output_format)?;
}
IssueCommand::Reopen { number } => {
let issue = provider
.reopen(number)
.await
.map_err(|e| miette::miette!("Failed to reopen issue #{number}: {e}"))?;
let output = CliOutput::success(issue, platform, "issue reopen");
print_output(&output, &output_format)?;
}
IssueCommand::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 issue #{number}: {e}"))?;
let output = CliOutput::success(comment, platform, "issue comment");
print_output(&output, &output_format)?;
}
IssueCommand::AddLabel { number, label } => {
provider
.add_labels(number, &label)
.await
.map_err(|e| miette::miette!("Failed to add labels to issue #{number}: {e}"))?;
let result = serde_json::json!({
"number": number,
"labels_added": label,
});
let output = CliOutput::success(result, platform, "issue add-label");
print_output(&output, &output_format)?;
}
IssueCommand::RemoveLabel { number, label } => {
provider
.remove_label(number, &label)
.await
.map_err(|e| miette::miette!("Failed to remove label from issue #{number}: {e}"))?;
let result = serde_json::json!({
"number": number,
"label_removed": label,
});
let output = CliOutput::success(result, platform, "issue remove-label");
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!("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_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 dir = std::env::temp_dir();
let path = dir.join("gitflow_test_body.md");
std::fs::write(&path, "file content here").expect("write temp file");
let result = resolve_body(None, Some(path.to_string_lossy().into_owned()));
let _ = std::fs::remove_file(&path);
assert!(result.is_ok());
assert_eq!(
result.expect("already checked"),
Some("file content here".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("a comment".into()), None);
assert!(result.is_ok());
assert_eq!(result.expect("already checked"), "a comment");
}
#[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_issue_close() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "issue", "close", "42"]).expect("parse");
match cli.command {
crate::Commands::Issue(IssueCommand::Close { number }) => {
assert_eq!(number, 42);
}
_ => panic!("Expected IssueCommand::Close"),
}
}
#[test]
fn test_should_parse_issue_reopen() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "issue", "reopen", "7"]).expect("parse");
match cli.command {
crate::Commands::Issue(IssueCommand::Reopen { number }) => {
assert_eq!(number, 7);
}
_ => panic!("Expected IssueCommand::Reopen"),
}
}
#[test]
fn test_should_parse_issue_comment_with_body() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "issue", "comment", "10", "--body", "LGTM"])
.expect("parse");
match cli.command {
crate::Commands::Issue(IssueCommand::Comment {
number,
body,
body_file,
}) => {
assert_eq!(number, 10);
assert_eq!(body, Some("LGTM".into()));
assert!(body_file.is_none());
}
_ => panic!("Expected IssueCommand::Comment"),
}
}
#[test]
fn test_should_parse_issue_add_label() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"issue",
"add-label",
"5",
"--label",
"bug",
"urgent",
])
.expect("parse");
match cli.command {
crate::Commands::Issue(IssueCommand::AddLabel { number, label }) => {
assert_eq!(number, 5);
assert_eq!(label, vec!["bug".to_string(), "urgent".to_string()]);
}
_ => panic!("Expected IssueCommand::AddLabel"),
}
}
#[test]
fn test_should_parse_issue_remove_label() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"issue",
"remove-label",
"3",
"--label",
"wontfix",
])
.expect("parse");
match cli.command {
crate::Commands::Issue(IssueCommand::RemoveLabel { number, label }) => {
assert_eq!(number, 3);
assert_eq!(label, "wontfix");
}
_ => panic!("Expected IssueCommand::RemoveLabel"),
}
}
#[test]
fn test_should_parse_issue_create_with_repo() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"issue",
"create",
"--title",
"Bug report",
"--repo",
"owner/repo",
])
.expect("parse");
match cli.command {
crate::Commands::Issue(IssueCommand::Create { title, repo, .. }) => {
assert_eq!(title, "Bug report");
assert_eq!(repo, Some("owner/repo".to_string()));
}
_ => panic!("Expected IssueCommand::Create"),
}
}
#[test]
fn test_should_parse_issue_create_without_repo() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "issue", "create", "--title", "Bug report"])
.expect("parse");
match cli.command {
crate::Commands::Issue(IssueCommand::Create { repo, .. }) => {
assert!(repo.is_none());
}
_ => panic!("Expected IssueCommand::Create"),
}
}
}