codeberg-cli 0.4.9

CLI Tool for codeberg similar to gh and glab
Documentation
use super::display_pull_request;
use crate::actions::text_manipulation::select_prompt_for;
use crate::actions::GeneralArgs;
use crate::render::option::option_display;
use crate::render::spinner::spin_until_ready;
use crate::render::ui::fuzzy_select_with_key;
use crate::types::context::BergContext;
use crate::types::git::OwnerRepo;
use anyhow::Context;
use clap::Parser;
use forgejo_api::structs::{CreateIssueCommentOption, PullRequest, RepoListPullRequestsQuery};

/// Add comment to selected pull request
#[derive(Parser, Debug)]
pub struct CommentPullRequestArgs {}

impl CommentPullRequestArgs {
    pub async fn run(self, general_args: GeneralArgs) -> anyhow::Result<()> {
        let _ = general_args;
        let ctx = BergContext::new(self, general_args).await?;

        let OwnerRepo { owner, repo } = ctx.owner_repo()?;
        let pull_request = select_pull_request(&ctx).await?;
        let pull_request_id = pull_request
            .id
            .context("Selected milestone doesn't have an ID")?;

        let options = create_options(&ctx, &pull_request).await?;

        let comment = ctx
            .client
            .issue_create_comment(
                owner.as_str(),
                repo.as_str(),
                pull_request_id as u64,
                options,
            )
            .await?;

        tracing::debug!("{comment:?}");

        Ok(())
    }
}

async fn create_options(
    ctx: &BergContext<CommentPullRequestArgs>,
    pull_request: &PullRequest,
) -> anyhow::Result<CreateIssueCommentOption> {
    let body = ctx.editor_for(
        "a comment",
        format!(
            "Write a comment for pull_request \"{}\"",
            option_display(&pull_request.title)
        )
        .as_str(),
    )?;

    Ok(CreateIssueCommentOption {
        body,
        updated_at: None,
    })
}

async fn select_pull_request(
    ctx: &BergContext<CommentPullRequestArgs>,
) -> anyhow::Result<PullRequest> {
    let OwnerRepo { owner, repo } = ctx.owner_repo()?;
    let pull_requests_list = spin_until_ready(ctx.client.repo_list_pull_requests(
        owner.as_str(),
        repo.as_str(),
        RepoListPullRequestsQuery::default(),
    ))
    .await?;

    fuzzy_select_with_key(
        &pull_requests_list,
        select_prompt_for("pull request"),
        display_pull_request,
    )
    .cloned()
}