use clap::Subcommand;
use gitflow_core::{
CliOutput, Paged,
label::{
CreateLabelArgs, CreateMilestoneArgs, LabelData, LabelProvider, MilestoneData,
MilestoneProvider,
},
};
use gitflow_gitcode::{GitCodeLabelProvider, GitCodeMilestoneProvider};
use gitflow_github::{GitHubLabelProvider, GitHubMilestoneProvider};
use gitflow_gitlab::{GitLabLabelProvider, GitLabMilestoneProvider};
use crate::{
OutputFormat,
commands::{list_args::validate_limit, output::print_list_output},
};
#[derive(Debug, Subcommand)]
pub enum LabelCommand {
Create {
name: String,
#[arg(long)]
color: String,
#[arg(long)]
description: Option<String>,
},
List {
#[arg(long)]
limit: Option<u32>,
},
Edit {
name: String,
#[arg(long)]
color: Option<String>,
#[arg(long)]
description: Option<String>,
},
Delete {
name: String,
#[arg(short, long)]
yes: bool,
},
}
#[derive(Debug, Subcommand)]
pub enum MilestoneCommand {
Create {
#[arg(long)]
title: String,
#[arg(long)]
description: Option<String>,
#[arg(long)]
due_on: Option<String>,
},
List {
#[arg(long)]
limit: Option<u32>,
},
Edit {
number: u64,
#[arg(long)]
title: Option<String>,
#[arg(long)]
description: Option<String>,
#[arg(long)]
due_on: Option<String>,
},
Close {
number: u64,
},
Reopen {
number: u64,
},
}
fn resolve_label_by_name<'a>(
paged: &'a Paged<LabelData>,
name: &str,
) -> miette::Result<&'a LabelData> {
if paged.truncated {
return Err(miette::miette!(
"label lookup truncated; too many labels to resolve by name"
));
}
paged
.items
.iter()
.find(|l| l.name == name)
.ok_or_else(|| miette::miette!("Label '{name}' not found"))
}
fn resolve_milestone_by_number(
paged: &Paged<MilestoneData>,
number: u64,
) -> miette::Result<&MilestoneData> {
if paged.truncated {
return Err(miette::miette!(
"milestone lookup truncated; too many milestones to resolve by number"
));
}
paged
.items
.iter()
.find(|m| m.number == number)
.ok_or_else(|| miette::miette!("Milestone #{number} not found"))
}
#[allow(
clippy::too_many_lines,
reason = "Command dispatch: each match arm maps to one operation"
)]
pub async fn handle_label(
command: LabelCommand,
platform: &str,
repo: &str,
remote_url: &str,
output_format: OutputFormat,
) -> miette::Result<()> {
let provider: Box<dyn LabelProvider> = match platform {
"github" => Box::new(GitHubLabelProvider::new(repo)),
"gitlab" => {
if remote_url.is_empty() {
Box::new(GitLabLabelProvider::new(repo))
} else {
Box::new(GitLabLabelProvider::with_remote_url(repo, remote_url))
}
}
"gitcode" => Box::new(GitCodeLabelProvider::new(repo)),
other => {
return Err(miette::miette!(
"Platform '{other}' not yet supported for label commands"
));
}
};
match command {
LabelCommand::Create {
name,
color,
description,
} => {
let args = CreateLabelArgs {
name,
color,
description,
};
let label = provider
.create(args)
.await
.map_err(|e| miette::miette!("Failed to create label: {e}"))?;
let output = CliOutput::success(label, platform, "label create");
print_output(&output, &output_format)?;
}
LabelCommand::List { limit } => {
let limit = validate_limit(limit)?;
let paged = provider
.list(limit)
.await
.map_err(|e| miette::miette!("Failed to list labels: {e}"))?;
let (items, meta) = paged.into_parts();
print_list_output(items, meta, platform, "label list", &output_format)?;
}
LabelCommand::Edit {
name,
color,
description,
} => {
let (color_val, desc_val) = match (&color, &description) {
(Some(c), d) => (c.clone(), d.clone()),
(None, Some(d)) => {
let paged = provider
.list(None)
.await
.map_err(|e| miette::miette!("Failed to list labels for edit: {e}"))?;
let existing = resolve_label_by_name(&paged, &name)?;
let c = existing
.color
.clone()
.ok_or_else(|| miette::miette!("Label '{name}' has no color set"))?;
(c, Some(d.clone()))
}
(None, None) => {
return Err(miette::miette!(
"At least one of --color or --description is required for edit"
));
}
};
let args = CreateLabelArgs {
name: name.clone(),
color: color_val,
description: desc_val,
};
let label = provider
.edit(&name, args)
.await
.map_err(|e| miette::miette!("Failed to edit label '{name}': {e}"))?;
let output = CliOutput::success(label, platform, "label edit");
print_output(&output, &output_format)?;
}
LabelCommand::Delete { name, yes } => {
if !yes {
tracing::info!("Deleting label '{name}' (use --yes to skip confirmation)");
}
provider
.delete(&name)
.await
.map_err(|e| miette::miette!("Failed to delete label '{name}': {e}"))?;
let result = serde_json::json!({
"label": name,
"deleted": true,
});
let output = CliOutput::success(result, platform, "label delete");
print_output(&output, &output_format)?;
}
}
Ok(())
}
#[allow(
clippy::too_many_lines,
reason = "Command dispatch: each match arm maps to one operation"
)]
pub async fn handle_milestone(
command: MilestoneCommand,
platform: &str,
repo: &str,
output_format: OutputFormat,
) -> miette::Result<()> {
let provider: Box<dyn MilestoneProvider> = match platform {
"github" => Box::new(GitHubMilestoneProvider::new(repo)),
"gitlab" => Box::new(GitLabMilestoneProvider::new(repo)),
"gitcode" => Box::new(GitCodeMilestoneProvider::new(repo)),
other => {
return Err(miette::miette!(
"Platform '{other}' not yet supported for milestone commands"
));
}
};
match command {
MilestoneCommand::Create {
title,
description,
due_on,
} => {
let parsed_due_on = if let Some(ref s) = due_on {
Some(
chrono::DateTime::parse_from_rfc3339(s)
.map_err(|e| miette::miette!("Invalid RFC 3339 date for --due-on: {e}"))?
.with_timezone(&chrono::Utc),
)
} else {
None
};
let args = CreateMilestoneArgs {
title,
description,
due_on: parsed_due_on,
};
let milestone = provider
.create(args)
.await
.map_err(|e| miette::miette!("Failed to create milestone: {e}"))?;
let output = CliOutput::success(milestone, platform, "milestone create");
print_output(&output, &output_format)?;
}
MilestoneCommand::List { limit } => {
let limit = validate_limit(limit)?;
let paged = provider
.list(limit)
.await
.map_err(|e| miette::miette!("Failed to list milestones: {e}"))?;
let (items, meta) = paged.into_parts();
print_list_output(items, meta, platform, "milestone list", &output_format)?;
}
MilestoneCommand::Edit {
number,
title,
description,
due_on,
} => {
if title.is_none() && description.is_none() && due_on.is_none() {
return Err(miette::miette!(
"At least one of --title, --description, or --due-on is required for edit"
));
}
let paged_milestones = provider
.list(None)
.await
.map_err(|e| miette::miette!("Failed to list milestones for edit: {e}"))?;
let existing = resolve_milestone_by_number(&paged_milestones, number)?;
let resolved_title = title.clone().unwrap_or_else(|| existing.title.clone());
let resolved_description = description.clone().or(existing.description.clone());
let resolved_due_on = if let Some(ref s) = due_on {
Some(
chrono::DateTime::parse_from_rfc3339(s)
.map_err(|e| miette::miette!("Invalid RFC 3339 date for --due-on: {e}"))?
.with_timezone(&chrono::Utc),
)
} else {
existing.due_on
};
let args = CreateMilestoneArgs {
title: resolved_title,
description: resolved_description,
due_on: resolved_due_on,
};
let milestone = provider
.edit(number, args)
.await
.map_err(|e| miette::miette!("Failed to edit milestone #{number}: {e}"))?;
let output = CliOutput::success(milestone, platform, "milestone edit");
print_output(&output, &output_format)?;
}
MilestoneCommand::Close { number } => {
let milestone = provider
.close(number)
.await
.map_err(|e| miette::miette!("Failed to close milestone #{number}: {e}"))?;
let output = CliOutput::success(milestone, platform, "milestone close");
print_output(&output, &output_format)?;
}
MilestoneCommand::Reopen { number } => {
let milestone = provider
.reopen(number)
.await
.map_err(|e| miette::miette!("Failed to reopen milestone #{number}: {e}"))?;
let output = CliOutput::success(milestone, platform, "milestone reopen");
print_output(&output, &output_format)?;
}
}
Ok(())
}
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_parse_label_create() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"label",
"create",
"bug",
"--color",
"d73a4a",
"--description",
"Something broken",
])
.expect("parse");
match cli.command {
crate::Commands::Label(LabelCommand::Create {
name,
color,
description,
}) => {
assert_eq!(name, "bug");
assert_eq!(color, "d73a4a");
assert_eq!(description, Some("Something broken".into()));
}
_ => panic!("Expected LabelCommand::Create"),
}
}
#[test]
fn test_should_parse_label_list() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "label", "list", "--limit", "10"])
.expect("parse");
match cli.command {
crate::Commands::Label(LabelCommand::List { limit }) => {
assert_eq!(limit, Some(10));
}
_ => panic!("Expected LabelCommand::List"),
}
}
#[test]
fn test_should_parse_label_list_without_limit() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "label", "list"]).expect("parse");
match cli.command {
crate::Commands::Label(LabelCommand::List { limit }) => {
assert!(limit.is_none());
}
_ => panic!("Expected LabelCommand::List"),
}
}
#[test]
fn test_should_parse_label_edit() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "label", "edit", "bug", "--color", "ff0000"])
.expect("parse");
match cli.command {
crate::Commands::Label(LabelCommand::Edit {
name,
color,
description,
}) => {
assert_eq!(name, "bug");
assert_eq!(color, Some("ff0000".into()));
assert!(description.is_none());
}
_ => panic!("Expected LabelCommand::Edit"),
}
}
#[test]
fn test_should_parse_label_delete() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "label", "delete", "wontfix", "--yes"])
.expect("parse");
match cli.command {
crate::Commands::Label(LabelCommand::Delete { name, yes }) => {
assert_eq!(name, "wontfix");
assert!(yes);
}
_ => panic!("Expected LabelCommand::Delete"),
}
}
#[test]
fn test_should_parse_milestone_create() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"milestone",
"create",
"--title",
"v1.0",
"--description",
"First release",
])
.expect("parse");
match cli.command {
crate::Commands::Milestone(MilestoneCommand::Create {
title,
description,
due_on,
}) => {
assert_eq!(title, "v1.0");
assert_eq!(description, Some("First release".into()));
assert!(due_on.is_none());
}
_ => panic!("Expected MilestoneCommand::Create"),
}
}
#[test]
fn test_should_parse_milestone_list() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "milestone", "list", "--limit", "10"])
.expect("parse");
match cli.command {
crate::Commands::Milestone(MilestoneCommand::List { limit }) => {
assert_eq!(limit, Some(10));
}
_ => panic!("Expected MilestoneCommand::List"),
}
}
#[test]
fn test_should_parse_milestone_list_without_limit() {
use clap::Parser;
let cli = crate::Cli::try_parse_from(["gitflow", "milestone", "list"]).expect("parse");
match cli.command {
crate::Commands::Milestone(MilestoneCommand::List { limit }) => {
assert!(limit.is_none());
}
_ => panic!("Expected MilestoneCommand::List"),
}
}
#[test]
fn test_should_parse_milestone_edit() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "milestone", "edit", "5", "--title", "v1.1"])
.expect("parse");
match cli.command {
crate::Commands::Milestone(MilestoneCommand::Edit {
number,
title,
description,
due_on,
}) => {
assert_eq!(number, 5);
assert_eq!(title, Some("v1.1".into()));
assert!(description.is_none());
assert!(due_on.is_none());
}
_ => panic!("Expected MilestoneCommand::Edit"),
}
}
#[test]
fn test_should_parse_milestone_close() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "milestone", "close", "3"]).expect("parse");
match cli.command {
crate::Commands::Milestone(MilestoneCommand::Close { number }) => {
assert_eq!(number, 3);
}
_ => panic!("Expected MilestoneCommand::Close"),
}
}
#[test]
fn test_should_parse_milestone_reopen() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "milestone", "reopen", "3"]).expect("parse");
match cli.command {
crate::Commands::Milestone(MilestoneCommand::Reopen { number }) => {
assert_eq!(number, 3);
}
_ => panic!("Expected MilestoneCommand::Reopen"),
}
}
#[test]
fn test_should_parse_milestone_create_with_due_on() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"milestone",
"create",
"--title",
"v2.0",
"--due-on",
"2026-12-01T00:00:00Z",
])
.expect("parse");
match cli.command {
crate::Commands::Milestone(MilestoneCommand::Create { title, due_on, .. }) => {
assert_eq!(title, "v2.0");
assert_eq!(due_on, Some("2026-12-01T00:00:00Z".into()));
}
_ => panic!("Expected MilestoneCommand::Create"),
}
}
#[test]
fn test_should_parse_milestone_edit_with_due_on() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"milestone",
"edit",
"5",
"--title",
"v2.0",
"--due-on",
"2026-12-31T00:00:00Z",
])
.expect("parse");
match cli.command {
crate::Commands::Milestone(MilestoneCommand::Edit {
number,
title,
due_on,
..
}) => {
assert_eq!(number, 5);
assert_eq!(title, Some("v2.0".into()));
assert_eq!(due_on, Some("2026-12-31T00:00:00Z".into()));
}
_ => panic!("Expected MilestoneCommand::Edit"),
}
}
#[test]
fn test_should_parse_label_delete_without_yes() {
use clap::Parser;
let cli =
crate::Cli::try_parse_from(["gitflow", "label", "delete", "wontfix"]).expect("parse");
match cli.command {
crate::Commands::Label(LabelCommand::Delete { name, yes }) => {
assert_eq!(name, "wontfix");
assert!(!yes);
}
_ => panic!("Expected LabelCommand::Delete"),
}
}
#[test]
fn test_should_parse_milestone_edit_with_description() {
use clap::Parser;
let cli = crate::Cli::try_parse_from([
"gitflow",
"milestone",
"edit",
"3",
"--description",
"Updated description",
])
.expect("parse");
match cli.command {
crate::Commands::Milestone(MilestoneCommand::Edit {
number,
description,
..
}) => {
assert_eq!(number, 3);
assert_eq!(description, Some("Updated description".into()));
}
_ => panic!("Expected MilestoneCommand::Edit"),
}
}
#[test]
fn test_should_print_json_output() {
let value = serde_json::json!({"name": "test", "color": "ff0000"});
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!({"name": "test", "color": "ff0000"});
let result = print_output(&value, &OutputFormat::Toon);
assert!(result.is_ok());
}
#[test]
fn test_should_print_auto_output() {
let value = serde_json::json!({"name": "test", "color": "ff0000"});
let result = print_output(&value, &OutputFormat::Auto);
assert!(result.is_ok());
}
async fn build_truncated_label_paged() -> Paged<LabelData> {
gitflow_core::fetch_capped(
gitflow_core::FetchStrategy::SingleShot,
gitflow_core::DEFAULT_LIST_LIMIT,
|_page, _limit| async {
let items: Vec<LabelData> = (0..=gitflow_core::DEFAULT_LIST_LIMIT)
.map(|i| LabelData {
name: format!("label-{i}"),
color: Some("ffffff".into()),
description: None,
})
.collect();
Ok(items)
},
)
.await
.expect("fetch_capped should succeed")
}
async fn build_truncated_milestone_paged() -> Paged<MilestoneData> {
gitflow_core::fetch_capped(
gitflow_core::FetchStrategy::SingleShot,
gitflow_core::DEFAULT_LIST_LIMIT,
|_page, _limit| async {
let items: Vec<MilestoneData> = (0..=u64::from(gitflow_core::DEFAULT_LIST_LIMIT))
.map(|i| MilestoneData {
number: i,
title: format!("v{i}"),
description: None,
state: gitflow_core::types::State::Open,
due_on: None,
closed_issues: 0,
open_issues: 0,
})
.collect();
Ok(items)
},
)
.await
.expect("fetch_capped should succeed")
}
#[tokio::test]
async fn test_should_error_on_truncation_when_resolving_label_by_name_for_edit() {
let paged = build_truncated_label_paged().await;
assert!(paged.truncated);
let err = resolve_label_by_name(&paged, "label-0")
.expect_err("should error when lookup is truncated");
assert!(err.to_string().contains("truncated"));
}
#[tokio::test]
async fn test_should_error_on_truncation_when_resolving_milestone_by_number_for_edit() {
let paged = build_truncated_milestone_paged().await;
assert!(paged.truncated);
let err = resolve_milestone_by_number(&paged, 0)
.expect_err("should error when lookup is truncated");
assert!(err.to_string().contains("truncated"));
}
#[tokio::test]
async fn test_should_resolve_label_by_name_when_not_truncated() {
let paged = gitflow_core::fetch_capped(
gitflow_core::FetchStrategy::SingleShot,
gitflow_core::DEFAULT_LIST_LIMIT,
|_page, _limit| async {
Ok(vec![LabelData {
name: "bug".into(),
color: Some("d73a4a".into()),
description: None,
}])
},
)
.await
.expect("fetch_capped should succeed");
assert!(!paged.truncated);
let found = resolve_label_by_name(&paged, "bug").expect("should find label");
assert_eq!(found.name, "bug");
}
#[tokio::test]
async fn test_should_error_not_found_when_label_absent_and_not_truncated() {
let paged = gitflow_core::fetch_capped(
gitflow_core::FetchStrategy::SingleShot,
gitflow_core::DEFAULT_LIST_LIMIT,
|_page, _limit| async { Ok(Vec::<LabelData>::new()) },
)
.await
.expect("fetch_capped should succeed");
assert!(!paged.truncated);
let err = resolve_label_by_name(&paged, "missing").expect_err("should error");
assert!(err.to_string().contains("not found"));
}
}