use std::path::{Path, PathBuf};
const FILE: &str = "properties.toml";
const TITLE: &str = "title";
const ARCHIVED: &str = "archived";
pub fn path(content: &Path) -> Option<PathBuf> {
Some(content.with_file_name(FILE))
}
pub fn title(content: &Path) -> String {
let Some(path) = path(content) else {
return String::new();
};
read(&path)
.get(TITLE)
.and_then(|title| title.as_str())
.unwrap_or_default()
.to_owned()
}
pub fn set_title(content: &Path, title: &str) {
set(
content,
TITLE,
(!title.is_empty()).then(|| toml_edit::value(title)),
);
}
pub fn archived(content: &Path) -> bool {
let Some(path) = path(content) else {
return false;
};
read(&path)
.get(ARCHIVED)
.and_then(|archived| archived.as_bool())
.unwrap_or_default()
}
pub fn set_archived(content: &Path, archived: bool) {
set(content, ARCHIVED, archived.then(|| toml_edit::value(true)));
}
fn set(content: &Path, key: &str, value: Option<toml_edit::Item>) {
let Some(path) = path(content) else {
return;
};
let mut doc = read(&path);
match value {
Some(value) => doc[key] = value,
None => {
doc.remove(key);
}
}
if doc.is_empty() {
let _ = std::fs::remove_file(&path);
return;
}
let _ = std::fs::write(&path, doc.to_string());
}
fn read(path: &Path) -> toml_edit::DocumentMut {
std::fs::read_to_string(path)
.ok()
.and_then(|text| text.parse().ok())
.unwrap_or_default()
}