use std::path::{Path, PathBuf};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::install_paths::{InstallPathsError, MPM_DIR_NAME, try_config_dir};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CatchupState {
pub last_catchup_at: DateTime<Utc>,
pub palace_id: String,
pub last_git_sha: Option<String>,
}
fn catchup_dir(palace_id: &str, state_root: Option<&Path>) -> Result<PathBuf, InstallPathsError> {
let root = match state_root {
Some(root) => root.to_path_buf(),
None => try_config_dir()?.join(MPM_DIR_NAME),
};
Ok(root.join("projects").join(palace_id))
}
fn state_path(palace_id: &str, state_root: Option<&Path>) -> Option<PathBuf> {
Some(
catchup_dir(palace_id, state_root)
.ok()?
.join("catchup-state.json"),
)
}
pub fn load_catchup_state(palace_id: &str) -> Option<CatchupState> {
load_catchup_state_in(palace_id, None)
}
pub fn load_catchup_state_in(palace_id: &str, state_root: Option<&Path>) -> Option<CatchupState> {
let path = state_path(palace_id, state_root)?;
let bytes = std::fs::read(&path).ok()?;
serde_json::from_slice(&bytes).ok()
}
pub fn save_catchup_state(palace_id: &str, state: &CatchupState) -> anyhow::Result<()> {
save_catchup_state_in(palace_id, state, None)
}
pub fn save_catchup_state_in(
palace_id: &str,
state: &CatchupState,
state_root: Option<&Path>,
) -> anyhow::Result<()> {
let dir = catchup_dir(palace_id, state_root)
.map_err(|e| anyhow::anyhow!("could not resolve the config dir for catchup state: {e}"))?;
std::fs::create_dir_all(&dir)?;
let path = dir.join("catchup-state.json");
let json = serde_json::to_vec_pretty(state)?;
std::fs::write(&path, json)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::install_paths::{CONFIG_DIR_ENV, install_file_path};
use tempfile::TempDir;
fn sample(palace_id: &str) -> CatchupState {
CatchupState {
last_catchup_at: "2026-06-27T10:00:00Z".parse::<DateTime<Utc>>().unwrap(),
palace_id: palace_id.to_string(),
last_git_sha: Some("abc1234".to_string()),
}
}
#[test]
fn state_save_load_roundtrip() {
let tmp = TempDir::new().unwrap();
let state = sample("test-palace");
save_catchup_state_in("test-palace", &state, Some(tmp.path())).unwrap();
let loaded =
load_catchup_state_in("test-palace", Some(tmp.path())).expect("state should load back");
assert_eq!(loaded.palace_id, "test-palace");
assert_eq!(loaded.last_git_sha.as_deref(), Some("abc1234"));
}
#[test]
fn load_wrapper_delegates_with_the_home_default() {
assert_eq!(
load_catchup_state("no-such-palace-6501").is_none(),
load_catchup_state_in("no-such-palace-6501", None).is_none(),
);
assert!(load_catchup_state("no-such-palace-6501").is_none());
}
#[test]
fn save_writes_under_the_state_root() {
let tmp = TempDir::new().unwrap();
save_catchup_state_in("pinned-palace", &sample("pinned-palace"), Some(tmp.path())).unwrap();
assert!(
tmp.path()
.join("projects")
.join("pinned-palace")
.join("catchup-state.json")
.is_file(),
"the watermark must be written under the state root"
);
}
fn with_env<R>(home: &Path, config_dir: Option<&Path>, f: impl FnOnce() -> R) -> R {
let _env = crate::data_dir::ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let saved = [
("HOME", std::env::var_os("HOME")),
(CONFIG_DIR_ENV, std::env::var_os(CONFIG_DIR_ENV)),
];
unsafe {
std::env::set_var("HOME", home);
match config_dir {
Some(dir) => std::env::set_var(CONFIG_DIR_ENV, dir),
None => std::env::remove_var(CONFIG_DIR_ENV),
}
}
let out = f();
for (name, value) in saved {
unsafe {
match value {
Some(v) => std::env::set_var(name, v),
None => std::env::remove_var(name),
}
}
}
out
}
#[test]
fn catchup_dir_falls_back_to_home() {
let home = TempDir::new().unwrap();
let got = with_env(home.path(), None, || catchup_dir("p", None));
assert_eq!(MPM_DIR_NAME, ".trusty-mpm");
assert_eq!(
got.expect("a home with no install.toml resolves"),
home.path().join(MPM_DIR_NAME).join("projects").join("p")
);
}
#[test]
fn catchup_dir_follows_the_configured_config_dir() {
let home = TempDir::new().unwrap();
let cfg = TempDir::new().unwrap();
let got = with_env(home.path(), Some(cfg.path()), || catchup_dir("p", None));
assert_eq!(
got.expect("the env config dir resolves"),
cfg.path().join(MPM_DIR_NAME).join("projects").join("p")
);
let install = install_file_path(home.path());
std::fs::create_dir_all(install.parent().unwrap()).unwrap();
std::fs::write(&install, "bogus = 1\n").unwrap();
let saved = with_env(home.path(), None, || {
save_catchup_state_in("p", &sample("p"), None)
});
assert!(saved.is_err(), "a broken install.toml must fail the write");
assert!(
!home.path().join(MPM_DIR_NAME).exists(),
"a failed resolve must create no state dir under $HOME"
);
let loaded = with_env(home.path(), None, || load_catchup_state_in("p", None));
assert!(
loaded.is_none(),
"an unresolvable config dir reads as no watermark"
);
}
#[test]
fn catchup_dir_honours_state_root() {
let tmp = TempDir::new().unwrap();
assert_eq!(
catchup_dir("p", Some(tmp.path())).expect("a state root needs no resolve"),
tmp.path().join("projects").join("p")
);
}
#[test]
fn state_missing_file_returns_none() {
let tmp = TempDir::new().unwrap();
assert!(load_catchup_state_in("never-written", Some(tmp.path())).is_none());
}
#[test]
fn state_parse_failure_returns_none() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().join("projects").join("test-palace");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("catchup-state.json"), b"not valid json {{").unwrap();
assert!(
load_catchup_state_in("test-palace", Some(tmp.path())).is_none(),
"invalid JSON should yield None"
);
}
}