1.7 KiB · text History b868907
//! A repository's labels — the ones `gg pull label` can attach.

use anyhow::Result;

use crate::api::RepoRef;
use crate::cli::LabelCommand;
use crate::commands::Ctx;
use crate::output::{Table, Tone, note, paint};

pub async fn run(ctx: &Ctx, command: Option<&LabelCommand>) -> Result<()> {
    let repo = ctx.repo()?;

    match command {
        None | Some(LabelCommand::List) => list(ctx, &repo).await,

        Some(LabelCommand::Create {
            name,
            color,
            description,
        }) => {
            let res = ctx
                .api
                .create_label(&repo, name, color.as_deref(), description.as_deref())
                .await?;
            if ctx.emitted(&res.raw)? {
                return Ok(());
            }
            println!(
                "{} label {} in {repo}.",
                paint("Created", Tone::Good),
                res.label.name
            );
            Ok(())
        }
    }
}

pub async fn list(ctx: &Ctx, repo: &RepoRef) -> Result<()> {
    let res = ctx.api.labels(repo).await?;
    if ctx.emitted(&res.raw)? {
        return Ok(());
    }
    if res.labels.is_empty() {
        note(&format!(
            "No labels in {repo}. A repository admin can add one with `gg labels create NAME`."
        ));
        return Ok(());
    }

    let mut table = Table::new(["NAME", "COLOR", "FROM", "DESCRIPTION"]);
    for label in &res.labels {
        table.row([
            label.name.clone(),
            label.color.clone().unwrap_or_default(),
            if label.inherited {
                "organization".to_string()
            } else {
                "repository".to_string()
            },
            label.description.clone().unwrap_or_default(),
        ]);
    }
    table.print();
    Ok(())
}