1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
use super::display_pull_request;
use crate::actions::{text_manipulation::select_prompt_for, GeneralArgs};
use crate::render::comment::render_comment;
use crate::render::datetime::render_datetime_and_info;
use crate::render::option::option_display;
use crate::render::spinner::spin_until_ready;
use crate::render::ui::fuzzy_select_with_key;
use crate::types::api::state_type::StateType;
use crate::types::context::BergContext;
use crate::types::git::OwnerRepo;
use anyhow::Context;
use clap::Parser;
use forgejo_api::structs::{
    IssueGetCommentsQuery, PullRequest, RepoListPullRequestsQuery, RepoListPullRequestsQueryState,
};
use itertools::Itertools;

#[derive(Parser, Debug)]
#[command(about = "View details of a selected pull request")]
pub struct ViewPullRequestsArgs {
    /// Select from pull requests with the chosen state
    #[arg(
        short,
        long,
        value_enum,
        default_value_t = StateType::All,
    )]
    pub state: StateType,

    /// Disabled: display issue summary | Enabled: display issue comment history
    #[arg(short, long)]
    pub comments: bool,
}

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

        let OwnerRepo { repo, owner } = ctx.owner_repo()?;
        let state = match ctx.args.state {
            StateType::Closed => RepoListPullRequestsQueryState::Closed,
            StateType::Open => RepoListPullRequestsQueryState::Open,
            StateType::All => RepoListPullRequestsQueryState::All,
        };
        let pull_requests_list = spin_until_ready(ctx.client.repo_list_pull_requests(
            owner.as_str(),
            repo.as_str(),
            RepoListPullRequestsQuery {
                state: Some(state),
                ..Default::default()
            },
        ))
        .await?;

        let pull_request = fuzzy_select_with_key(
            &pull_requests_list,
            select_prompt_for("pull request"),
            display_pull_request,
        )?;

        if ctx.args.comments {
            spin_until_ready(present_pull_request_comments(&ctx, pull_request)).await?;
        } else {
            present_pull_request_overview(&ctx, pull_request);
        }

        Ok(())
    }
}

fn present_pull_request_overview(
    ctx: &BergContext<ViewPullRequestsArgs>,
    pull_request: &PullRequest,
) {
    let rendered_datetime = pull_request
        .created_at
        .as_ref()
        .map(render_datetime_and_info)
        .unwrap_or_else(|| String::from("?"));

    let mut table = ctx.make_table();

    table
        .set_header(vec![format!(
            "Pull Request #{}",
            option_display(&pull_request.id)
        )])
        .add_row(vec![
            String::from("Title"),
            option_display(&pull_request.title),
        ])
        .add_row(vec![String::from("Created"), rendered_datetime])
        .add_row(vec![
            String::from("Labels"),
            pull_request
                .labels
                .iter()
                .flatten()
                .map(|label| option_display(&label.name))
                .join(", "),
        ])
        .add_row(vec![
            String::from("Description"),
            option_display(&pull_request.body),
        ]);

    println!("{table}");
}

async fn present_pull_request_comments(
    ctx: &BergContext<ViewPullRequestsArgs>,
    pull_request: &PullRequest,
) -> anyhow::Result<()> {
    let OwnerRepo { repo, owner } = ctx.owner_repo()?;
    let comments = ctx
        .client
        .issue_get_comments(
            owner.as_str(),
            repo.as_str(),
            pull_request.id.context("Selected pull request has no ID")?,
            IssueGetCommentsQuery::default(),
        )
        .await?;
    let header = format!(
        "Pull Request #{} {}",
        option_display(&pull_request.id),
        if comments.is_empty() {
            "(no comments)"
        } else {
            "comments"
        }
    );

    let mut table = ctx.make_table();

    table
        .set_header(vec![header])
        .add_rows(comments.into_iter().filter_map(|comment| {
            let username = comment.user.as_ref()?.login.as_ref()?.as_str();
            let creation_time = comment.created_at.as_ref()?;
            let comment = comment.body.as_ref()?;
            let comment = render_comment(&ctx.config, username, creation_time, comment);
            Some(vec![comment])
        }));

    println!("{table}");

    Ok(())
}