gitpoulpi-hosting 1.1.1

Hosting and issue-tracker API clients (GitHub, GitLab, Gitea/Forgejo, Azure DevOps, Bitbucket, Gerrit, Jira, Trello, Linear, YouTrack, Redmine, local Markdown issues): project listing, clone helpers, SSH key generation and upload, remote-URL provider matching.
Documentation
//! The conversation of a Gerrit change: the header, the change messages
//! (system messages by their tag become events, the rest comments), the
//! Code-Review votes as verdicts, the inline comments as code threads, and
//! posting a message or a reply.
//!
//! What Gerrit cannot do is said, not faked: a published comment or message
//! cannot be edited, and deleting a change message is an administrator's
//! operation, so `edit_item_comment` and `delete_item_comment` are
//! `Unsupported` and the capabilities say so. Gerrit has no issues.
//!
//! Everything arrives in one answer, so the window is cut from the full
//! timeline: the `older` cursor is the index where the shown window starts.

use super::{build_threads, parse_thread_id, GerritClient};
use crate::conversation::compat::{
    check_body, comment_from_review, review_entry, sort_by_time, thread_from_review,
};
use crate::conversation::{
    Actor, ActorKind, Comment, Event, EventKind, IdentityKind, ItemHeader, ItemKey, ItemKind,
    Markup, MarkupFlavor, PageCursor, PostingIdentity, TimelineEntry, TimelineOpts, TimelinePage,
    TokenSource, WINDOW,
};
use crate::gerrit::map::{self, Account, ChangeInfo, Message};
use crate::review::invalid;
use crate::review::model::ReviewComment;
use crate::{Error, Result};

const FLAVOR: MarkupFlavor = MarkupFlavor::PlainText;

/// Gerrit shows the author of an automatic message as the service user.
fn actor_of(account: Option<&Account>) -> Actor {
    match account {
        Some(a) => {
            let mut actor = Actor::new(a.handle(), a.display(), ActorKind::User);
            actor.web_url = None;
            actor
        }
        None => Actor::unknown(),
    }
}

/// The message without Gerrit's `Patch Set N: Code-Review+1` header and its
/// `(3 comments)` line: what is left is what the person wrote.
fn message_body(message: &str) -> String {
    let mut lines: Vec<&str> = message.lines().collect();
    if lines
        .first()
        .is_some_and(|l| l.starts_with("Patch Set ") && l.contains(':'))
    {
        lines.remove(0);
    }
    let text = lines.join("\n");
    let mut kept: Vec<&str> = Vec::new();
    for block in text.split("\n\n") {
        let b = block.trim();
        let is_count = b.starts_with('(')
            && b.ends_with(')')
            && (b.contains(" comment") || b.contains(" comments"));
        if !b.is_empty() && !is_count {
            kept.push(block);
        }
    }
    kept.join("\n\n").trim().to_string()
}

fn first_line(text: &str) -> String {
    text.lines().next().unwrap_or_default().trim().to_string()
}

/// A change message as an event when it is the server's own, else a comment.
fn message_entry(change: &ChangeInfo, m: &Message) -> Option<TimelineEntry> {
    let at = map::iso(&m.date);
    let tag = m.tag.as_deref().unwrap_or_default();
    let head = first_line(&m.message);
    let event = |kind: EventKind| {
        Some(TimelineEntry::Event(Event {
            id: m.id.clone(),
            actor: Some(actor_of(m.author.as_ref())),
            at: at.clone(),
            kind,
        }))
    };
    if tag.contains("newPatchSet") || head.starts_with("Uploaded patch set") {
        let head_sha = change
            .revisions
            .iter()
            .find(|(_, r)| r._number == m._revision_number)
            .map(|(sha, _)| sha.clone());
        return event(EventKind::CommitsPushed {
            count: 1,
            head: head_sha,
        });
    }
    if tag.ends_with(":merged") || head.starts_with("Change has been successfully") {
        return event(EventKind::Merged);
    }
    if tag.ends_with(":abandon") || head.starts_with("Abandoned") {
        return event(EventKind::Closed);
    }
    if tag.ends_with(":restore") || head.starts_with("Restored") {
        return event(EventKind::Reopened);
    }
    if tag.starts_with("autogenerated:") {
        return event(EventKind::Other { text: head });
    }
    let body = message_body(&m.message);
    if body.is_empty() {
        // Only votes and a comment count: the verdicts and threads say it.
        return None;
    }
    Some(TimelineEntry::Comment(Comment {
        id: m.id.clone(),
        author: actor_of(m.author.as_ref()),
        body: Markup::new(body, FLAVOR),
        created_at: at,
        updated_at: None,
        edited: false,
        reactions: Vec::new(),
        in_reply_to: None,
        discussion_id: None,
        internal: false,
        can_edit: Some(false),
        can_delete: Some(false),
        web_url: None,
    }))
}

impl GerritClient {
    fn conv_check(key: &ItemKey) -> Result<()> {
        if key.kind != ItemKind::PullRequest {
            return Err(Error::Unsupported(
                "Gerrit has no issues, only changes".to_string(),
            ));
        }
        Ok(())
    }

    pub(crate) async fn conv_timeline(
        &self,
        project: &str,
        key: &ItemKey,
        older: Option<&PageCursor>,
        opts: &TimelineOpts,
    ) -> Result<TimelinePage> {
        Self::conv_check(key)?;
        let end: Option<usize> = match older {
            Some(c) => Some(
                c.0.parse()
                    .map_err(|_| invalid("reading a conversation", "bad page cursor"))?,
            ),
            None => None,
        };
        let change = self.change(project, key.number).await?;
        let latest = change.latest_patch_set();
        let (_, revision) = change.revision(None).unzip();
        let body = revision
            .and_then(|r| r.commit.as_ref())
            .map(|c| super::description_of(&c.message))
            .unwrap_or_default();
        let owner = actor_of(change.owner.as_ref());
        let header = ItemHeader {
            key: key.clone(),
            reference: format!("#{}", key.number),
            title: change.subject.clone(),
            state_label: match change.status.as_str() {
                "MERGED" => "merged",
                "ABANDONED" => "abandoned",
                _ if change.work_in_progress => "draft",
                _ => "open",
            }
            .to_string(),
            open: change.status == "NEW",
            author: owner,
            body: Markup::new(body, FLAVOR),
            created_at: map::iso(&change.created),
            web_url: map::change_url(&self.site(), &change.project, key.number),
            labels: change.hashtags.clone(),
        };

        let mut entries: Vec<TimelineEntry> = Vec::new();
        for m in &change.messages {
            if let Some(e) = message_entry(&change, m) {
                if opts.events || !matches!(e, TimelineEntry::Event(_)) {
                    entries.push(e);
                }
            }
        }
        for vote in change.code_review_votes() {
            entries.push(TimelineEntry::Review(review_entry(vote, FLAVOR)));
        }
        // Published comments only: a draft is not part of the conversation.
        let published: Vec<_> = self
            .comments(project, key.number)
            .await?
            .into_iter()
            .filter(|c| !c.draft)
            .collect();
        for c in published.iter().filter(|c| c.path == super::PATCHSET_LEVEL) {
            let who = c.author.as_ref();
            entries.push(TimelineEntry::Comment(Comment {
                id: c.id.clone(),
                author: actor_of(who),
                body: Markup::new(c.message.clone(), FLAVOR),
                created_at: map::iso(&c.updated),
                updated_at: None,
                edited: false,
                reactions: Vec::new(),
                in_reply_to: c.in_reply_to.clone(),
                discussion_id: None,
                internal: false,
                can_edit: Some(false),
                can_delete: Some(false),
                web_url: None,
            }));
        }
        for t in build_threads(published, latest, "") {
            entries.push(TimelineEntry::Thread(thread_from_review(t, FLAVOR)));
        }
        sort_by_time(&mut entries);

        let end = end.unwrap_or(entries.len()).min(entries.len());
        let start = end.saturating_sub(WINDOW);
        let total = entries.len() as u32;
        let window: Vec<TimelineEntry> = entries.drain(start..end).collect();
        Ok(TimelinePage {
            header,
            entries: window,
            older: (start > 0).then(|| PageCursor(start.to_string())),
            total_hint: older.is_none().then_some(total),
        })
    }

    pub(crate) async fn conv_post(
        &self,
        project: &str,
        key: &ItemKey,
        body: &str,
        internal: bool,
    ) -> Result<Comment> {
        Self::conv_check(key)?;
        if internal {
            return Err(invalid(
                "commenting on a change",
                "Gerrit has no internal comments",
            ));
        }
        check_body("commenting on a change", body)?;
        self.review(
            project,
            key.number,
            "current",
            &serde_json::json!({ "message": body }),
        )
        .await?;
        let me = self.myself().await?.handle();
        // Gerrit answers the post without the new message: find it, so the
        // comment carries its id and date.
        let change = self.change(project, key.number).await?;
        let posted = change.messages.iter().rev().find(|m| {
            m.author.as_ref().map(Account::handle).as_deref() == Some(me.as_str())
                && m.message.trim_end().ends_with(body.trim_end())
        });
        let mut comment = comment_from_review(
            ReviewComment {
                id: posted.map(|m| m.id.clone()).unwrap_or_default(),
                author: me,
                body: body.to_string(),
                created_at: posted.map(|m| map::iso(&m.date)).unwrap_or_default(),
                in_reply_to: None,
                web_url: None,
            },
            None,
            FLAVOR,
        );
        comment.can_edit = Some(false);
        comment.can_delete = Some(false);
        Ok(comment)
    }

    pub(crate) async fn conv_reply(
        &self,
        project: &str,
        key: &ItemKey,
        discussion_id: &str,
        body: &str,
    ) -> Result<Comment> {
        Self::conv_check(key)?;
        check_body("replying", body)?;
        let thread = parse_thread_id(discussion_id)
            .ok_or_else(|| invalid("replying", "that is not a Gerrit thread"))?;
        let me = self.myself().await?.handle();
        self.post_thread_comment(project, key.number, &thread, body, thread.unresolved)
            .await?;
        // The review answer does not return the comment: find it.
        let posted = self
            .comments(project, key.number)
            .await?
            .into_iter()
            .filter(|c| !c.draft && c.in_reply_to.as_deref() == Some(thread.last.as_str()))
            .filter(|c| c.author.as_ref().map(Account::handle).as_deref() == Some(me.as_str()))
            .rfind(|c| c.message.trim_end() == body.trim_end());
        let mut comment = comment_from_review(
            ReviewComment {
                id: posted.as_ref().map(|c| c.id.clone()).unwrap_or_default(),
                author: me,
                body: body.to_string(),
                created_at: posted
                    .as_ref()
                    .map(|c| map::iso(&c.updated))
                    .unwrap_or_default(),
                in_reply_to: Some(thread.last.clone()),
                web_url: None,
            },
            Some(discussion_id),
            FLAVOR,
        );
        comment.can_edit = Some(false);
        comment.can_delete = Some(false);
        Ok(comment)
    }

    pub(crate) fn conv_edit_refused() -> Error {
        Error::Unsupported(
            "editing a comment on Gerrit (a published comment cannot be changed)".to_string(),
        )
    }

    pub(crate) fn conv_delete_refused() -> Error {
        Error::Unsupported(
            "deleting a comment on Gerrit (only an administrator can delete a change message)"
                .to_string(),
        )
    }

    /// The account the credentials belong to.
    pub(crate) async fn conv_identity(&self, _project: &str) -> Result<PostingIdentity> {
        let me = self.myself().await?;
        Ok(PostingIdentity::new(
            Some(me.handle()),
            IdentityKind::PersonalToken,
            TokenSource::Profile {
                id: self.integration.id.clone(),
            },
        ))
    }
}