plannotator-tui 0.13.1

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
//! Posting the notes to the pull request on GitHub (`ctrl+g`, or the Review menu): a
//! summary first, always, then one review in one `gh api` request
//! ([`plannotator_tui_review::post`]). Only a pull request review offers it.
//!
//! The summary names the PR, how many notes go inline and how many in the review body (and
//! why), what is left out, and the verdict: Comment unless the person picks Approve or
//! Request changes, as the browser offers them. `Enter` posts and `Esc` cancels; nothing
//! leaves the machine before `Enter`, and `Enter` counts only once the whole summary has been
//! on screen: a key typed before it appeared is not an answer to it ([`Confirm::shown`]).
//! Comments are anchored to the commit the diff was captured at, the one the person
//! reviewed; when the PR has moved on since, the summary says so.
//!
//! Both `gh` calls run on a thread of their own and wake the event loop when they answer, so
//! a slow GitHub never freezes the screen: the summary says it is checking the PR, then that
//! it is posting. A refusal posted nothing (GitHub takes the review whole or not at all), and
//! the summary stays open with the reason. An answer that never came back may have posted
//! the review, and the summary says to check the PR first. A post that succeeds marks its
//! notes posted, a state of its own beside sent, saved with the notes; a later post carries
//! only notes that are new or edited since.

use std::fmt::Write as _;
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::time::Duration;

use plannotator_tui_review::post::{Event, Plan, PostError, PostedReview, Posting, Skip, Target};
use plannotator_tui_review::{CodeAnnotation, PrSpec, PrView, Scope};
use ratatui::crossterm::event::KeyEvent;

use super::post_view::{comment_places, too_long};
use super::{Mode, Screen};
use crate::keys::{self, Action};

/// How long the check of the PR's head may take before the summary says it could not check.
const CHECK_TIMEOUT: Duration = Duration::from_secs(20);

/// The summary on screen before a post.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Confirm {
    pub(super) plan: Plan,
    pub(super) event: Event,
    /// What `gh pr view` says about the PR's head now.
    pub(super) head: Head,
    /// `closed` or `merged` when the PR is no longer open; GitHub still takes a review.
    pub(super) ended: Option<&'static str>,
    /// Why the last try did not post, or may not have.
    pub(super) failed: Option<String>,
    /// A post is under way: keys wait for GitHub's answer.
    pub(super) posting: bool,
    /// The summary was drawn whole, the PR checked. `Enter` posts only from then on.
    pub(super) shown: bool,
}

/// The PR's head on GitHub, against the commit the person reviewed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Head {
    /// `gh pr view` has not answered yet.
    Checking,
    Reviewed,
    /// The PR has newer commits than the reviewed one.
    Moved {
        now: String,
    },
    /// `gh pr view` failed; the post will say what is wrong.
    Unknown(String),
}

/// What a `gh` thread answers.
enum Answer {
    Head(Result<Box<PrView>, String>),
    Posted(Result<PostedReview, PostError>),
}

/// A `gh` call under way: its answer, and the summary a post was confirmed from.
pub(super) struct Job {
    answer: Receiver<Answer>,
    posting: Option<Confirm>,
}

impl Screen {
    /// `post-to-github`: open the summary, or say why there is nothing to post.
    pub(super) fn open_post(&mut self) {
        let (Some(pull), Some(gh)) = (&self.capture.pull, self.repo.gh()) else {
            self.status = Some(format!(
                "Post to GitHub needs a pull request review (plannotator-tui review <PR>); this one is {}",
                self.capture.scope.title()
            ));
            return;
        };
        let plan = Plan::build(
            self.store.annotations(),
            &self.capture.files,
            Target { repo: &pull.view.repo, number: pull.view.number, reviewed_head: &pull.head },
            |note| self.posting(note),
        );
        if plan.is_empty() {
            let posted = plan.count_skipped(Skip::AlreadyPosted);
            self.status = Some(match (self.store.annotations().is_empty(), posted) {
                (true, _) => "no notes to post to GitHub".to_owned(),
                (false, 0) => "nothing to post to GitHub: the notes are empty".to_owned(),
                (false, n) => format!("nothing new to post to GitHub ({n} already posted)"),
            });
            return;
        }
        // Read-only: where the PR's head is now.
        let spec = match &self.capture.scope {
            Scope::PullRequest { url, number } => PrSpec::parse(url).unwrap_or(PrSpec::Number(*number)),
            _ => PrSpec::Number(pull.view.number),
        };
        let (gh, dir) = (gh.clone(), self.repo.workdir().to_path_buf());
        let job = self.start("pr-check", None, move || {
            Answer::Head(gh.view_within(&spec, &dir, CHECK_TIMEOUT).map(Box::new).map_err(|e| e.to_string()))
        });
        let head = match job {
            Ok(job) => {
                self.post_job = Some(job);
                Head::Checking
            }
            Err(why) => Head::Unknown(why),
        };
        let confirm = Confirm {
            plan,
            event: Event::default(),
            head,
            ended: None,
            failed: None,
            posting: false,
            shown: false,
        };
        self.mode = Mode::Post(confirm);
    }

    fn posting(&self, note: &CodeAnnotation) -> Posting {
        if self.store.is_posted(note) {
            Posting::Posted
        } else if self.store.was_posted(note) {
            Posting::Edited
        } else {
            Posting::New
        }
    }

    /// Run `work` on a thread named `name`, waking the event loop when it answers.
    fn start(
        &self,
        name: &str,
        posting: Option<Confirm>,
        work: impl FnOnce() -> Answer + Send + 'static,
    ) -> Result<Job, String> {
        let (tell, answer) = mpsc::sync_channel(1);
        let wake = self.wake.clone();
        std::thread::Builder::new()
            .name(name.to_owned())
            .spawn(move || {
                let _ = tell.send(work());
                let _ = wake.try_send(());
            })
            .map_err(|err| format!("could not start gh: {err}"))?;
        Ok(Job { answer, posting })
    }

    /// Take a `gh` answer that arrived. Returns whether the screen changed.
    pub(super) fn poll_post(&mut self) -> bool {
        let Some(job) = &self.post_job else { return false };
        let answer = match job.answer.try_recv() {
            Ok(answer) => answer,
            Err(TryRecvError::Empty) => return false,
            Err(TryRecvError::Disconnected) if job.posting.is_some() => {
                Answer::Posted(Err(PostError::Uncertain { detail: "the post stopped".into() }))
            }
            Err(TryRecvError::Disconnected) => Answer::Head(Err("the check stopped".into())),
        };
        let Some(job) = self.post_job.take() else { return false };
        match (answer, job.posting) {
            (Answer::Posted(result), Some(confirm)) => self.finish_post(confirm, result),
            (Answer::Head(view), _) => {
                // A summary closed meanwhile has no use for it.
                let (Mode::Post(confirm), Some(pull)) = (&mut self.mode, &self.capture.pull) else {
                    return true;
                };
                (confirm.head, confirm.ended) = match view {
                    Ok(view) if view.head_sha == pull.head => (Head::Reviewed, view.ended()),
                    Ok(view) => {
                        let ended = view.ended();
                        (Head::Moved { now: view.head_sha }, ended)
                    }
                    Err(why) => (Head::Unknown(why), None),
                };
            }
            (Answer::Posted(_), None) => {}
        }
        true
    }

    /// After a frame: the summary, checked, was on screen. True the first time, so the event
    /// loop drops the keys that were already waiting: they were typed before it showed.
    pub(super) fn post_shown(&mut self) -> bool {
        match &mut self.mode {
            Mode::Post(confirm) if !confirm.shown && confirm.head != Head::Checking => {
                confirm.shown = true;
                true
            }
            _ => false,
        }
    }

    pub(super) fn post_key(&mut self, key: KeyEvent, mut confirm: Confirm) {
        let step = |event: Event, by: isize| {
            let at = Event::ALL.iter().position(|e| *e == event).unwrap_or(0);
            let next = at.saturating_add_signed(by).min(Event::ALL.len() - 1);
            Event::ALL.get(next).copied().unwrap_or_default()
        };
        if confirm.posting {
            // It is GitHub's turn; the answer closes or updates the summary.
            self.mode = Mode::Post(confirm);
            return;
        }
        match self.keys.action(&key, keys::POST_REVIEW) {
            Some(Action::Left) => confirm.event = step(confirm.event, -1),
            Some(Action::Right) => confirm.event = step(confirm.event, 1),
            Some(Action::Confirm) if confirm.shown => return self.post(confirm),
            Some(Action::Back | Action::Interrupt) => {
                self.post_job = None;
                self.mode = Mode::Browse;
                self.status = Some("nothing posted to GitHub".into());
                return;
            }
            _ => {}
        }
        self.mode = Mode::Post(confirm);
    }

    /// The person confirmed: post on a thread of its own; [`Self::finish_post`] takes the answer.
    fn post(&mut self, mut confirm: Confirm) {
        let (Some(pull), Some(gh)) = (&self.capture.pull, self.repo.gh()) else {
            self.mode = Mode::Browse;
            return;
        };
        if !too_long(&confirm.plan).is_empty() {
            confirm.failed = Some("Nothing was posted: shorten the notes named above first.".into());
            self.mode = Mode::Post(confirm);
            return;
        }
        let request = confirm.plan.request(confirm.event);
        let (gh, repo, number) = (gh.clone(), pull.view.repo.clone(), pull.view.number);
        confirm.failed = None;
        confirm.posting = true;
        let work = move || Answer::Posted(gh.post_review(&repo, number, &request));
        match self.start("pr-post", Some(confirm.clone()), work) {
            Ok(job) => {
                self.post_job = Some(job);
                self.status = Some("posting to GitHub\u{2026}".into());
            }
            Err(why) => {
                confirm.posting = false;
                confirm.shown = false;
                confirm.failed = Some(format!("Nothing was posted: {why}."));
            }
        }
        self.mode = Mode::Post(confirm);
    }

    /// GitHub answered the post confirmed with `confirm`.
    fn finish_post(&mut self, mut confirm: Confirm, result: Result<PostedReview, PostError>) {
        confirm.posting = false;
        // What a failure says is new on screen: a key typed before it is drawn does not answer it.
        confirm.shown = false;
        match result {
            Ok(review) => {
                let ids = confirm.plan.ids();
                let saved = self.store.record_post(&review.url, &confirm.plan.commit_id, &ids);
                let mut status = if review.confirmed {
                    let (inline, body) = (confirm.plan.comments.len(), confirm.plan.in_body.len());
                    format!("posted to GitHub: {inline} inline, {body} in the body \u{b7} {}", review.url)
                } else {
                    format!(
                        "posted to GitHub, but gh's reply could not be read; the notes are marked posted so \
                         they are not posted twice \u{b7} check {}",
                        review.url
                    )
                };
                if let Err(err) = saved {
                    let _ = write!(
                        status,
                        " \u{b7} could not save the posted state ({err}); after a restart a post may repeat \
                         these notes"
                    );
                }
                self.status = Some(status);
                self.mode = Mode::Browse;
                self.after_note_change();
            }
            Err(err) if err.may_have_posted() => {
                let url = self.capture.pull.as_ref().map(|p| p.view.url.clone()).unwrap_or_default();
                confirm.failed = Some(format!(
                    "This may have been posted: {err}. Check the pull request on GitHub before you post \
                     again: {url}"
                ));
                self.status = Some("may have been posted to GitHub: check the pull request".into());
                self.mode = Mode::Post(confirm);
            }
            Err(err) => {
                let mut why = format!("Nothing was posted: {err}.");
                if matches!(err, PostError::Positions { .. }) {
                    let _ = write!(
                        why,
                        " The inline comments, each checked against the diff you reviewed, were on {}.",
                        comment_places(&confirm.plan)
                    );
                    if let Head::Moved { now } = &confirm.head {
                        let reload = self.keys.labelled(Action::Reload, "reloads it").unwrap_or_default();
                        let _ =
                            write!(why, " The PR is at {} now; {reload} and the notes follow.", short(now));
                    }
                }
                self.status = Some(format!("nothing posted to GitHub: {}", short_reason(&err)));
                confirm.failed = Some(why);
                self.mode = Mode::Post(confirm);
            }
        }
    }

    /// The Review menu row's words.
    pub(super) fn post_menu_label(&self) -> String {
        if self.capture.pull.is_none() {
            return "Post to GitHub\u{2026} \u{b7} pull requests only".to_owned();
        }
        let new = self.store.annotations().iter().filter(|n| !self.store.is_posted(n)).count();
        format!("Post to GitHub\u{2026} \u{b7} {new} new")
    }
}

/// A few words for the footer; the summary has the rest.
fn short_reason(err: &PostError) -> &'static str {
    match err {
        PostError::GhMissing => "gh is not installed",
        PostError::NotLoggedIn { .. } => "gh is not logged in",
        PostError::NoPermission { .. } => "no permission",
        PostError::RateLimited { .. } => "rate limited",
        PostError::Offline { .. } => "GitHub unreachable",
        PostError::HeadGone { .. } => "the reviewed commit is gone from the PR",
        PostError::Positions { .. } => "GitHub refused a comment's place",
        PostError::OwnPullRequest { .. } => "your own pull request",
        PostError::Other { .. } => "gh api failed",
        PostError::Uncertain { .. } => "no answer from GitHub",
    }
}

pub(super) fn short(sha: &str) -> &str {
    sha.get(..7).unwrap_or(sha)
}