codeberg_cli/actions/label/
create.rsuse crate::render::color::mk_color_validator;
use crate::{actions::GeneralArgs, types::git::OwnerRepo};
use crate::render::ui::multi_fuzzy_select_with_key;
use crate::types::context::BergContext;
use forgejo_api::structs::CreateLabelOption;
use strum::*;
use crate::actions::text_manipulation::{edit_prompt_for, input_prompt_for};
use clap::Parser;
#[derive(Parser, Debug)]
pub struct CreateLabelArgs {
#[arg(short, long)]
pub name: Option<String>,
#[arg(short, long)]
pub color: Option<String>,
#[arg(short, long)]
pub description: Option<String>,
}
#[derive(Display, PartialEq, Eq, VariantArray)]
enum CreatableFields {
Description,
Color,
}
impl CreateLabelArgs {
pub async fn run(self, general_args: GeneralArgs) -> anyhow::Result<()> {
let _ = general_args;
let ctx = BergContext::new(self, general_args).await?;
let OwnerRepo { repo, owner } = ctx.owner_repo()?;
let options = create_options(&ctx).await?;
let label = ctx
.client
.issue_create_label(owner.as_str(), repo.as_str(), options)
.await?;
tracing::debug!("{label:?}");
Ok(())
}
}
async fn create_options(ctx: &BergContext<CreateLabelArgs>) -> anyhow::Result<CreateLabelOption> {
let name = match ctx.args.name.as_ref().cloned() {
Some(name) => name,
None => inquire::Text::new(input_prompt_for("Label Name").as_str()).prompt()?,
};
let color = ctx
.args
.color
.as_ref()
.cloned()
.unwrap_or(String::from("#ffffff"));
let mut options = CreateLabelOption {
name,
color,
description: None,
exclusive: None,
is_archived: None,
};
let optional_data = {
use CreatableFields::*;
[
(Description, ctx.args.description.is_none()),
(Color, ctx.args.color.is_none()),
]
.into_iter()
.filter_map(|(name, missing)| missing.then_some(name))
.collect::<Vec<_>>()
};
let chosen_optionals = multi_fuzzy_select_with_key(
&optional_data,
"Choose optional properties",
|_| false,
|o| o.to_string(),
)?;
{
use CreatableFields::*;
options.description = label_description(ctx, chosen_optionals.contains(&&Description))?;
if let Some(color) = label_color(ctx, chosen_optionals.contains(&&Color))? {
options.color = color;
}
}
Ok(options)
}
fn label_description(
ctx: &BergContext<CreateLabelArgs>,
interactive: bool,
) -> anyhow::Result<Option<String>> {
let description = match ctx.args.description.as_ref() {
Some(desc) => desc.clone(),
None => {
if !interactive {
return Ok(None);
}
inquire::Editor::new(edit_prompt_for("a description").as_str())
.with_predefined_text("Enter an issue description")
.prompt()?
}
};
Ok(Some(description))
}
fn label_color(
ctx: &BergContext<CreateLabelArgs>,
interactive: bool,
) -> anyhow::Result<Option<String>> {
let color = match ctx.args.color.as_ref() {
Some(color) => color.clone(),
None => {
if !interactive {
return Ok(None);
}
mk_color_validator(inquire::Text::new(
input_prompt_for("Enter a color").as_str(),
))
.prompt()?
}
};
Ok(Some(color))
}