use super::*;
pub struct Drafts {
pub(super) file: PathBuf,
spec: String,
stories: Vec<String>,
}
pub(super) const DRAFT_MAX_AGE: u64 = 7 * 24 * 60 * 60;
pub(super) fn now_seconds() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_secs())
}
impl Drafts {
pub fn new(repo: &Repo, stored_path: &str, stories: &[String]) -> Self {
let key = format!("{stored_path}\n{}", stories.join(","));
let hash = Sha256::digest(key.as_bytes());
let name: String = hash[..8].iter().map(|byte| format!("{byte:02x}")).collect();
Self {
file: repo.data.join("drafts").join(format!("{name}.json")),
spec: stored_path.to_owned(),
stories: stories.to_vec(),
}
}
pub fn previous(&self, spec: &Value) -> Result<Option<Value>> {
let text = match fs::read_to_string(&self.file) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => {
eprintln!(
"agengo: warning: ignoring the kept draft {}: {error}",
self.file.display()
);
return Ok(None);
}
};
let kept: Value = match serde_json::from_str(&text) {
Ok(kept) => kept,
Err(error) => {
eprintln!(
"agengo: warning: ignoring the kept draft {}: {error}",
self.file.display()
);
return Ok(None);
}
};
if kept["spec"] != json!(self.spec) || kept["stories"] != json!(self.stories) {
return Ok(None);
}
let saved = kept["saved_at"].as_u64().unwrap_or(0);
if now_seconds().saturating_sub(saved) > DRAFT_MAX_AGE {
return Ok(None);
}
let since = kept["round"].as_u64().unwrap_or(0);
let decisions: Vec<Value> = array_or_empty(&spec["clarifications"])
.iter()
.filter(|item| item["round"].as_u64().is_some_and(|round| round > since))
.map(|item| {
if item["question"] == DECISION {
json!({"answer": item["answer"]})
} else {
json!({"question": item["question"], "answer": item["answer"]})
}
})
.collect();
if decisions.is_empty() {
return Ok(None);
}
Ok(Some(json!({
"tasks": kept["tasks"], "questions": kept["questions"], "decisions": decisions,
})))
}
pub fn remember(&self, draft: &Value, round: &Value) -> Result<()> {
let parent = self.file.parent().context("draft path has no parent")?;
fs::create_dir_all(parent)
.with_context(|| format!("cannot create {}", parent.display()))?;
let kept = json!({
"spec": self.spec, "stories": self.stories, "round": round,
"saved_at": now_seconds(),
"tasks": draft["tasks"], "questions": draft["questions"],
});
let mut file = tempfile::NamedTempFile::new_in(parent)?;
file.write_all(&serde_json::to_vec_pretty(&kept)?)?;
file.persist(&self.file)
.with_context(|| format!("cannot write {}", self.file.display()))?;
Ok(())
}
pub fn forget(&self) -> Result<()> {
match fs::remove_file(&self.file) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
Err(error).with_context(|| format!("cannot remove {}", self.file.display()))
}
_ => Ok(()),
}
}
}