use std::fmt;
use std::mem;
use super::JobState;
use crate::compiler::fingerprint::DirtyReason;
use crate::util::CargoResult;
pub struct Job {
work: Work,
fresh: Freshness,
}
pub struct Work {
inner: Box<dyn FnOnce(&JobState<'_, '_>) -> CargoResult<()> + Send>,
}
impl Work {
pub fn new<F>(f: F) -> Work
where
F: FnOnce(&JobState<'_, '_>) -> CargoResult<()> + Send + 'static,
{
Work { inner: Box::new(f) }
}
pub fn noop() -> Work {
Work::new(|_| Ok(()))
}
pub fn call(self, tx: &JobState<'_, '_>) -> CargoResult<()> {
(self.inner)(tx)
}
pub fn then(self, next: Work) -> Work {
Work::new(move |state| {
self.call(state)?;
next.call(state)
})
}
}
impl Job {
pub fn new_fresh() -> Job {
Job {
work: Work::noop(),
fresh: Freshness::Fresh,
}
}
pub fn new_dirty(work: Work, dirty_reason: DirtyReason) -> Job {
Job {
work,
fresh: Freshness::Dirty(dirty_reason),
}
}
pub fn run(self, state: &JobState<'_, '_>) -> CargoResult<()> {
self.work.call(state)
}
pub fn freshness(&self) -> &Freshness {
&self.fresh
}
pub fn before(&mut self, next: Work) {
let prev = mem::replace(&mut self.work, Work::noop());
self.work = next.then(prev);
}
pub fn after(&mut self, next: Work) {
let prev = mem::replace(&mut self.work, Work::noop());
self.work = prev.then(next);
}
}
impl fmt::Debug for Job {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Job {{ ... }}")
}
}
#[derive(Debug, Clone)]
pub enum Freshness {
Fresh,
Dirty(DirtyReason),
}
impl Freshness {
pub fn is_dirty(&self) -> bool {
matches!(self, Freshness::Dirty(_))
}
pub fn is_fresh(&self) -> bool {
matches!(self, Freshness::Fresh)
}
}