use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct State {
map: BTreeMap<(String, String), String>,
path: PathBuf,
}
#[must_use]
pub fn default_path() -> PathBuf {
resolve(
std::env::var("SHERD_STATE").ok(),
git_common_dir(Path::new(".")),
)
}
#[must_use]
pub fn resolve(env: Option<String>, git_common: Option<PathBuf>) -> PathBuf {
match (env, git_common) {
(Some(p), _) => PathBuf::from(p),
(None, Some(dir)) => dir.join("sherd-state"),
(None, None) => PathBuf::from(".sherd-state"),
}
}
#[must_use]
pub fn git_common_dir(dir: &Path) -> Option<PathBuf> {
let out = crate::git::at(
dir,
&["rev-parse", "--path-format=absolute", "--git-common-dir"],
)
.output()
.ok()?;
let s = String::from_utf8(out.stdout).ok()?;
let s = s.trim();
(out.status.success() && !s.is_empty()).then(|| PathBuf::from(s))
}
impl State {
#[must_use]
pub fn load() -> Self {
Self::at(default_path())
}
#[must_use]
pub fn at(path: impl Into<PathBuf>) -> Self {
let path = path.into();
let mut s = Self {
path: path.clone(),
..Self::default()
};
let Ok(text) = std::fs::read_to_string(&path) else {
return s;
};
for (n, line) in text.lines().enumerate() {
if line.starts_with('#') || line.trim().is_empty() {
continue;
}
let mut it = line.splitn(3, ' ');
match (it.next(), it.next(), it.next()) {
(Some(k), Some(key), Some(v)) => {
s.map.insert((k.into(), unescape_key(key)), v.into());
}
_ => {
eprintln!("sherd-state:{}: unparsable line, ignored", n + 1)
}
}
}
s
}
pub fn save(&self) {
let out = format!(
"# generated by sherd. Idempotent -- rewriting unchanged state is a no-op.\n{}",
self.serialise()
);
let _ = std::fs::write(&self.path, out);
}
#[must_use]
pub fn get(&self, kind: &str, key: &str) -> Option<&str> {
self.map.get(&(kind.into(), key.into())).map(String::as_str)
}
pub fn set(&mut self, kind: &str, key: &str, value: impl Into<String>) {
self.map.insert((kind.into(), key.into()), value.into());
}
#[must_use]
pub fn get_u64(&self, kind: &str, key: &str) -> Option<u64> {
self.get(kind, key).and_then(|v| v.parse().ok())
}
pub fn clear_kind(&mut self, kind: &str) {
self.map.retain(|(k, _), _| k != kind);
}
#[must_use]
pub fn all(&self, kind: &str) -> Vec<String> {
self.map
.iter()
.filter(|((k, _), _)| k == kind)
.map(|(_, v)| v.clone())
.collect()
}
pub fn push(&mut self, log: Log, dedup: &str, value: impl Into<String>) {
let kind = log.kind;
if self.find_key(kind, dedup).is_some() {
return;
}
self.set(kind, &format!("{:08}-{dedup}", self.next_seq(kind)), value);
let ordered = self.oldest_first(kind);
let over = ordered.len().saturating_sub(log.cap);
for k in ordered.into_iter().take(over) {
self.map.remove(&(kind.to_string(), k));
}
}
fn next_seq(&self, kind: &str) -> u64 {
self.keys_of(kind)
.iter()
.filter_map(|k| seq_of(k))
.max()
.map_or(0, |n| n.saturating_add(1))
}
#[must_use]
pub fn find_key(&self, kind: &str, dedup: &str) -> Option<String> {
let suffix = format!("-{dedup}");
self.keys_of(kind)
.into_iter()
.find(|k| k.ends_with(&suffix))
}
fn oldest_first(&self, kind: &str) -> Vec<String> {
let mut keys = self.keys_of(kind);
keys.sort_by_key(|k| (seq_of(k), k.clone()));
keys
}
fn keys_of(&self, kind: &str) -> Vec<String> {
self.map
.keys()
.filter(|(k, _)| k == kind)
.map(|(_, key)| key.clone())
.collect()
}
#[must_use]
pub fn serialise(&self) -> String {
self.map
.iter()
.map(|((k, key), v)| format!("{k} {} {v}\n", escape_key(key)))
.collect()
}
}
#[derive(Debug, Clone, Copy)]
pub struct Log<'a> {
pub kind: &'a str,
pub cap: usize,
}
impl<'a> Log<'a> {
#[must_use]
pub const fn new(kind: &'a str, cap: usize) -> Self {
Self { kind, cap }
}
}
fn seq_of(key: &str) -> Option<u64> {
key.split_once('-').and_then(|(n, _)| n.parse().ok())
}
fn escape_key(key: &str) -> String {
key.replace('%', "%25").replace(' ', "%20")
}
fn unescape_key(key: &str) -> String {
key.replace("%20", " ").replace("%25", "%")
}
#[must_use]
pub fn content_hash(bytes: &[u8]) -> String {
let mut h = std::collections::hash_map::DefaultHasher::new();
bytes.hash(&mut h);
format!("{:016x}", h.finish())
}
pub fn cached_tokens(
st: &mut State,
path: &std::path::Path,
) -> std::io::Result<u64> {
let bytes = std::fs::read(path)?;
let key = path.to_string_lossy().to_string();
let h = content_hash(&bytes);
if st.get("hash", &key) == Some(h.as_str())
&& let Some(n) = st.get_u64("tok", &key)
{
return Ok(n);
}
let n = crate::tokens::count(&String::from_utf8_lossy(&bytes)).tokens;
st.set("hash", &key, h);
st.set("tok", &key, n.to_string());
Ok(n)
}
#[cfg(test)]
#[path = "tests/state.rs"]
mod tests;
#[cfg(test)]
#[path = "tests/path.rs"]
mod path_tests;