use std::path::{Path, PathBuf};
use serde::Serialize;
use sha2::{Digest, Sha256};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum Status {
Ok,
Cached,
Reported,
Unavailable,
Refused,
Incompatible,
LinkOnly,
}
impl std::fmt::Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Ok => "ok",
Self::Cached => "cached",
Self::Reported => "reported",
Self::Unavailable => "unavailable",
Self::Refused => "refused",
Self::Incompatible => "incompatible",
Self::LinkOnly => "link-only",
})
}
}
#[derive(Clone, Copy)]
pub(crate) enum Slot<'a> {
Read(Option<&'a str>),
Reported,
}
pub(crate) trait Held {
fn machine(&self) -> &str;
fn person(&self) -> Option<&str>;
fn pushed(&self) -> bool;
}
impl<T: Held> Held for &T {
fn machine(&self) -> &str {
(**self).machine()
}
fn person(&self) -> Option<&str> {
(**self).person()
}
fn pushed(&self) -> bool {
(**self).pushed()
}
}
impl<'a> Slot<'a> {
pub(crate) fn person(self) -> Option<&'a str> {
match self {
Self::Read(person) => person,
Self::Reported => None,
}
}
pub(crate) fn reported(self) -> bool {
matches!(self, Self::Reported)
}
pub(crate) fn holds(self, saved: &impl Held, name: &str) -> bool {
saved.machine() == name
&& saved.pushed() == self.reported()
&& saved.person() == self.person()
}
pub(crate) fn path(self, logs_dir: &Path, cache: &str, name: &str) -> PathBuf {
let mut digest = Sha256::new();
digest.update(name.as_bytes());
match self {
Self::Read(None) => {}
Self::Read(Some(person)) => {
digest.update([0]);
digest.update(person.as_bytes());
}
Self::Reported => digest.update([1]),
}
let digest = digest.finalize();
let hex: String = digest[..16]
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
logs_dir.join(cache).join(format!("{hex}.json"))
}
}