use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, Sender, SyncSender};
use std::time::{Duration, Instant};
use plannotator_tui_review::{Capture, Commit, DiffStat, Repo, ReviewStore, Scope, Stop, project_for};
pub(crate) const PAGE: usize = 20;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Listing {
pub(crate) branch: Option<Scope>,
pub(crate) commits: Vec<Commit>,
pub(crate) more: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct Size {
pub(crate) stat: DiffStat,
pub(crate) unsent: usize,
}
pub(crate) trait Source: Send + Sync {
fn name(&self) -> String;
fn list(&self, skip: usize, count: usize) -> Result<Listing, String>;
fn size(&self, scope: &Scope) -> Result<Size, String>;
fn capture(&self, scope: &Scope) -> Result<(Repo, Capture), String>;
fn count(&self, from: &str, to: &str) -> Result<usize, String>;
}
pub(crate) struct GitSource {
pub(crate) repo: Repo,
pub(crate) data_dir: PathBuf,
}
impl Source for GitSource {
fn name(&self) -> String {
let root = self.repo.root();
root.file_name().map_or_else(|| root.display().to_string(), |n| n.to_string_lossy().into())
}
fn list(&self, skip: usize, count: usize) -> Result<Listing, String> {
let mut commits = self.repo.commits(skip, count + 1).map_err(|e| e.to_string())?;
let more = commits.len() > count;
commits.truncate(count);
let branch = if skip == 0 { self.repo.branch_choice() } else { None };
Ok(Listing { branch, commits, more })
}
fn size(&self, scope: &Scope) -> Result<Size, String> {
let stat = self.repo.diff_stat(scope).map_err(|e| match e {
plannotator_tui_review::Error::NeedsTerminal { .. } => super::rows::NEEDS_TERMINAL.to_owned(),
e => e.to_string(),
})?;
let root = self.repo.root();
let unsent =
ReviewStore::load(&self.data_dir, &project_for(root), &root.display().to_string(), scope)
.map_or(0, |store| store.pending().len());
Ok(Size { stat, unsent })
}
fn capture(&self, scope: &Scope) -> Result<(Repo, Capture), String> {
self.repo.capture(scope).map(|capture| (self.repo.clone(), capture)).map_err(|e| e.to_string())
}
fn count(&self, from: &str, to: &str) -> Result<usize, String> {
self.repo.range_count(from, to).map_err(|e| e.to_string())
}
}
#[derive(Debug, Clone)]
pub(super) enum Job {
List {
skip: usize,
count: usize,
},
Size {
row: usize,
scope: Scope,
},
Capture {
scope: Scope,
},
Count {
scope: Scope,
},
}
pub(super) enum Done {
List { generation: u64, skip: usize, listing: Result<Listing, String> },
Size { generation: u64, row: usize, size: Result<Size, String> },
Capture { generation: u64, scope: Scope, captured: Box<Result<(Repo, Capture), String>> },
Count { generation: u64, scope: Scope, count: Result<usize, String> },
}
pub(super) const AT_ONCE: usize = 2;
const STOP_WAIT: Duration = Duration::from_secs(3);
struct Started {
capture: bool,
stop: Stop,
ended: Arc<AtomicBool>,
}
pub(super) struct Work {
source: Arc<dyn Source>,
send: Sender<Done>,
done: Receiver<Done>,
wake: SyncSender<()>,
queue: VecDeque<(u64, Job)>,
started: Vec<Started>,
running: Arc<AtomicUsize>,
}
impl Work {
pub(super) fn new(source: Arc<dyn Source>, wake: SyncSender<()>) -> Self {
let (send, done) = mpsc::channel();
Self {
source,
send,
done,
wake,
queue: VecDeque::new(),
started: Vec::new(),
running: Arc::new(AtomicUsize::new(0)),
}
}
pub(super) fn ask(&mut self, generation: u64, job: Job) -> bool {
if matches!(job, Job::Capture { .. }) {
self.queue.push_front((generation, job));
} else {
self.queue.push_back((generation, job));
}
self.pump()
}
pub(super) fn has_room(&self) -> bool {
self.queue.is_empty() && self.running.load(Ordering::SeqCst) < AT_ONCE
}
pub(super) fn pump(&mut self) -> bool {
self.started.retain(|job| !job.ended.load(Ordering::SeqCst));
while self.running.load(Ordering::SeqCst) < AT_ONCE {
let Some((generation, job)) = self.queue.pop_front() else { return true };
if !self.start(generation, job) {
return false;
}
}
true
}
fn start(&mut self, generation: u64, job: Job) -> bool {
let stop = Stop::new();
let capture = matches!(job, Job::Capture { .. });
let (source, send, wake) = (Arc::clone(&self.source), self.send.clone(), self.wake.clone());
let ended = Arc::new(AtomicBool::new(false));
self.running.fetch_add(1, Ordering::SeqCst);
let guard = Ended { running: Arc::clone(&self.running), ended: Arc::clone(&ended) };
let handle = stop.clone();
let started = std::thread::Builder::new().name("pick-changes".into()).spawn(move || {
let done = handle.run(|| match job {
Job::List { skip, count } => {
Done::List { generation, skip, listing: source.list(skip, count) }
}
Job::Size { row, scope } => Done::Size { generation, row, size: source.size(&scope) },
Job::Capture { scope } => {
let captured = Box::new(source.capture(&scope));
Done::Capture { generation, scope, captured }
}
Job::Count { scope } => {
let count = match &scope {
Scope::Range { from, to } => source.count(from, to),
_ => Err("not a range".to_owned()),
};
Done::Count { generation, scope, count }
}
});
drop(guard);
if !handle.is_stopped() {
let _ = send.send(done);
}
let _ = wake.try_send(());
});
match started {
Ok(_) => {
self.started.push(Started { capture, stop, ended });
true
}
Err(_) => false,
}
}
pub(super) fn stop_all(&mut self) {
self.queue.clear();
for job in self.started.drain(..) {
job.stop.stop();
}
}
pub(super) fn stop_sizes(&mut self) {
self.queue.retain(|(_, job)| !matches!(job, Job::Size { .. }));
for job in self.started.iter().filter(|job| !job.capture) {
job.stop.stop();
}
}
pub(super) fn stop_captures(&mut self) {
self.queue.retain(|(_, job)| !matches!(job, Job::Capture { .. }));
for job in self.started.iter().filter(|job| job.capture) {
job.stop.stop();
}
}
#[cfg(test)]
pub(super) fn running(&self) -> usize {
self.running.load(Ordering::SeqCst)
}
pub(super) fn take(&self) -> Vec<Done> {
self.done.try_iter().collect()
}
}
impl Drop for Work {
fn drop(&mut self) {
self.stop_all();
let deadline = Instant::now() + STOP_WAIT;
while self.running.load(Ordering::SeqCst) > 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
}
}
struct Ended {
running: Arc<AtomicUsize>,
ended: Arc<AtomicBool>,
}
impl Drop for Ended {
fn drop(&mut self) {
self.ended.store(true, Ordering::SeqCst);
self.running.fetch_sub(1, Ordering::SeqCst);
}
}