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};
const CHECK_TIMEOUT: Duration = Duration::from_secs(20);
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Confirm {
pub(super) plan: Plan,
pub(super) event: Event,
pub(super) head: Head,
pub(super) ended: Option<&'static str>,
pub(super) failed: Option<String>,
pub(super) posting: bool,
pub(super) shown: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Head {
Checking,
Reviewed,
Moved {
now: String,
},
Unknown(String),
}
enum Answer {
Head(Result<Box<PrView>, String>),
Posted(Result<PostedReview, PostError>),
}
pub(super) struct Job {
answer: Receiver<Answer>,
posting: Option<Confirm>,
}
impl Screen {
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;
}
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
}
}
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 })
}
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), _) => {
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
}
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 {
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);
}
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);
}
fn finish_post(&mut self, mut confirm: Confirm, result: Result<PostedReview, PostError>) {
confirm.posting = false;
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);
}
}
}
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")
}
}
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)
}