use std::path::{Path, PathBuf};
use crate::frontmatter::{self, Frontmatter};
use crate::refs;
pub const FILE: &str = "_retired.md";
pub const LEGACY_FILE: &str = "_retired.txt";
pub const FIELD: &str = "retired";
const BODY: &str = "# Retired ids\n\nReserved ids that must never be reused. \
Managed by opys — the value is the document's last title; git records when and \
why each id was retired.\n";
pub fn path(base: &Path) -> PathBuf {
base.join(FILE)
}
pub fn legacy_path(base: &Path) -> PathBuf {
base.join(LEGACY_FILE)
}
pub fn read(base: &Path) -> Vec<(String, String)> {
if let Ok(text) = std::fs::read_to_string(path(base)) {
if let Ok((fm, _)) = frontmatter::parse(&text, FILE) {
return refs::parse_in(&fm, FIELD);
}
}
read_legacy(base)
}
fn read_legacy(base: &Path) -> Vec<(String, String)> {
let Ok(text) = std::fs::read_to_string(legacy_path(base)) else {
return Vec::new();
};
let mut out = Vec::new();
for line in text.lines() {
let head = line.split('#').next().unwrap_or("");
if let Some(id) = head.split_whitespace().next() {
if !id.is_empty() {
out.push((id.to_string(), String::new()));
}
}
}
out
}
pub fn serialize(entries: &[(String, String)]) -> String {
let mut fm = Frontmatter::new();
refs::set_in(&mut fm, FIELD, entries);
frontmatter::serialize(&fm, BODY)
}