use std::path::Path;
use anyhow::Result;
use super::resolve_instance;
use crate::state::{Instance, State};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownInstance(pub String);
impl std::fmt::Display for UnknownInstance {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "no instance `{}`", self.0)
}
}
impl std::error::Error for UnknownInstance {}
pub fn done(name: &str, done: bool) -> Result<()> {
let state = State::load()?;
let key = resolve_instance(&state, name)?;
println!("{}", set_saved(&key, done)?);
Ok(())
}
pub fn set_saved(key: &str, done: bool) -> Result<String> {
set_saved_at(&State::path()?, key, done)
}
pub fn set_saved_at(state: &Path, key: &str, done: bool) -> Result<String> {
State::update_at(state, |state| Ok(set(state, key, done, Instance::now()).map(|(_, msg)| msg)?))
}
fn set(state: &mut State, key: &str, done: bool, now: u64) -> Result<(bool, String), UnknownInstance> {
let info = state.instances.get_mut(key).ok_or_else(|| UnknownInstance(key.to_string()))?;
let line = status_line(key, done, info.done.is_some());
let changed = done != info.done.is_some();
if changed {
info.done = done.then_some(now);
}
Ok((changed, line))
}
pub(crate) fn status_line(key: &str, done: bool, was: bool) -> String {
match (done, was) {
(true, true) => format!("`{key}` is already done"),
(false, false) => format!("`{key}` is not done"),
(true, false) => format!("marked {key} done"),
(false, true) => format!("marked {key} not done"),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn state() -> State {
toml::from_str(
"[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
)
.unwrap()
}
#[test]
fn set_and_clear_are_idempotent() {
let mut s = state();
assert_eq!(set(&mut s, "a", true, 10).unwrap(), (true, "marked a done".into()));
assert_eq!(s.instances["a"].done, Some(10));
assert_eq!(set(&mut s, "a", true, 20).unwrap(), (false, "`a` is already done".into()));
assert_eq!(s.instances["a"].done, Some(10));
assert_eq!(set(&mut s, "a", false, 30).unwrap(), (true, "marked a not done".into()));
assert_eq!(s.instances["a"].done, None);
assert_eq!(set(&mut s, "a", false, 40).unwrap(), (false, "`a` is not done".into()));
}
#[test]
fn unknown_instance_is_an_error() {
let mut s = state();
assert!(set(&mut s, "zz", true, 1).unwrap_err().to_string().contains("no instance `zz`"));
}
}