//! `labels [list|add|remove] [labels...]` — manage labels on //! an issue or PR. Default action: list. use anyhow::{Result, bail}; use clap::{Args as ClapArgs, Subcommand}; use forgejo_api::structs::{DeleteLabelsOption, IssueLabelsOption, IssueListLabelsQuery, Label}; use serde_json::json; use crate::client::{Client, index}; use crate::verbs::{all_pages, print_json}; #[derive(ClapArgs)] pub struct Args { /// Issue or PR number. pub(crate) number: u64, #[command(subcommand)] action: Option, } #[derive(Subcommand)] enum Action { /// List labels (default when you give no action). List, /// Add labels by name. Add { /// Label names to add. labels: Vec, }, /// Remove labels by name. Remove { /// Label names to remove. labels: Vec, }, } pub fn run(client: &Client, args: Args) -> Result<()> { let (owner, name) = client.owner_repo()?; let idx = index(args.number)?; match args.action.unwrap_or(Action::List) { Action::List => { let labels = client.api().issue_get_labels(owner, name, idx).send()?; print_label_names(&labels); } Action::Add { labels } => { if labels.is_empty() { bail!("hive-forge labels add: pass at least one label name"); } let all = repo_labels(client)?; let ids: Vec = resolve_ids(&all, &labels)? .into_iter() .map(|id| json!(id)) .collect(); let resp = client .api() .issue_add_label( owner, name, idx, IssueLabelsOption { labels: Some(ids), updated_at: None, }, ) .send()?; print_label_names(&resp); } Action::Remove { labels } => { if labels.is_empty() { bail!("hive-forge labels remove: pass at least one label name"); } let all = repo_labels(client)?; // Same strict resolution as `add` — a typo used to be silently // skipped here instead of refused. let ids = resolve_ids(&all, &labels)?; for id in ids { client .api() .issue_remove_label( owner, name, idx, &id.to_string(), DeleteLabelsOption { updated_at: None }, ) .send()?; } let current = client.api().issue_get_labels(owner, name, idx).send()?; // Forgejo can 200 a remove it silently didn't apply (e.g. // insufficient permission), same as the assignee case in // `assign.rs` — diff the result against the intent instead of // trusting the status code. let still_present = still_present_names(&labels, ¤t); if !still_present.is_empty() { bail!( "label(s) still present on #{} after remove — the forge \ rejected the change: {}", args.number, still_present.join(", ") ); } print_label_names(¤t); } } Ok(()) } /// The repo's whole label set, for name → id resolution. `pub(crate)` so /// other verbs (`issue create`, `pr create`, `list`, `repo-labels`) share /// one lookup. /// /// Every page, not one: a page size with no page loop silently truncates /// the set, and a truncated set makes a *valid* label past the cut fail to /// resolve, with an "available labels" list that is itself incomplete, so /// the error argues for the typo. pub(crate) fn repo_labels(client: &Client) -> Result> { let (owner, name) = client.owner_repo()?; all_pages(|page, size| { let (_, batch) = client .api() .issue_list_labels(owner, name, IssueListLabelsQuery::default()) .page(page) .page_size(size) .send()?; Ok(batch) }) } /// Resolve label names to ids, hard-erroring if any name doesn't match an /// existing repo label. A typo used to silently produce fewer labels than /// intended with no signal — not even a nonzero exit code — so callers /// (`labels add`, `issue create --label`, `pr create --label`) had no way /// to notice without manually diffing what they asked for against what /// landed. The error lists both the exact names that didn't resolve and /// every label actually available on the repo, so it's fixable from the /// error alone without a second round-trip to `labels list`. pub(crate) fn resolve_ids(all: &[Label], names: &[String]) -> Result> { let mut ids = Vec::with_capacity(names.len()); let mut unresolved = Vec::new(); for n in names { match lookup_id(all, n) { Some(id) => ids.push(id), None => unresolved.push(n.as_str()), } } if !unresolved.is_empty() { let available: Vec<&str> = all.iter().filter_map(|l| l.name.as_deref()).collect(); bail!( "unresolved label name(s): {} — available labels: {}", crate::verbs::with_suggestions(&unresolved, &available), if available.is_empty() { "(none)".to_owned() } else { available.join(", ") } ); } Ok(ids) } fn lookup_id(all: &[Label], name: &str) -> Option { all.iter() .find(|l| l.name.as_deref() == Some(name)) .and_then(|l| l.id) } /// Which of `requested` names are still present in `current` — the /// remove-verb's post-condition check. A non-empty result means the forge /// didn't actually drop those labels even though the call returned 200. fn still_present_names(requested: &[String], current: &[Label]) -> Vec { requested .iter() .filter(|r| { current .iter() .any(|l| l.name.as_deref() == Some(r.as_str())) }) .cloned() .collect() } fn print_label_names(labels: &[Label]) { let names: Vec<&str> = labels.iter().filter_map(|l| l.name.as_deref()).collect(); let _ = print_json(&json!(names)); } #[cfg(test)] mod tests { use super::{resolve_ids, still_present_names}; use forgejo_api::structs::Label; fn label(id: i64, name: &str) -> Label { Label { color: Some(String::new()), description: Some(String::new()), exclusive: None, id: Some(id), is_archived: None, name: Some(name.to_owned()), url: None, } } #[test] fn all_names_resolve_returns_ids_in_order() { let all = vec![label(1, "area/ops"), label(2, "type/bug")]; let ids = resolve_ids(&all, &["type/bug".to_owned(), "area/ops".to_owned()]).unwrap(); assert_eq!(ids, vec![2, 1]); } #[test] fn unresolved_name_errors_listing_the_typo_and_available_labels() { let all = vec![label(1, "area/ops"), label(2, "type/bug")]; let err = resolve_ids(&all, &["area/op".to_owned()]).unwrap_err(); let msg = err.to_string(); assert!(msg.contains("area/op"), "missing typo'd name: {msg}"); assert!(msg.contains("area/ops"), "missing available label: {msg}"); assert!(msg.contains("type/bug"), "missing available label: {msg}"); } #[test] fn unresolved_name_on_empty_repo_says_none_available() { let err = resolve_ids(&[], &["anything".to_owned()]).unwrap_err(); assert!(err.to_string().contains("(none)")); } #[test] fn unresolved_remove_name_is_refused_like_add() { // `remove` resolves names through the same `resolve_ids` as `add`, // so a typo is refused up front instead of silently doing nothing. let all = vec![label(1, "area/ops")]; let err = resolve_ids(&all, &["area:ops".to_owned()]).unwrap_err(); assert!(err.to_string().contains("area:ops")); } #[test] fn still_present_control_all_removed_reports_none() { // Happy path: none of the requested names remain, so the caller // should not bail. let requested = vec!["area/ops".to_owned(), "type/bug".to_owned()]; let current = vec![label(3, "state/open")]; assert!(still_present_names(&requested, ¤t).is_empty()); } #[test] fn still_present_names_reports_labels_the_forge_kept() { // A remove the forge silently rejected — the label is still on the // issue after the "successful" call. This is the case the old code // (`let _ = …send();` with no re-check) let through as success. let requested = vec!["area/ops".to_owned(), "type/bug".to_owned()]; let current = vec![label(1, "area/ops")]; assert_eq!( still_present_names(&requested, ¤t), vec!["area/ops".to_owned()] ); } }