use std::path::Path;
use shep_core::config::DogsConfig;
use super::spec::DogError;
fn read_dogs_toml(path: &Path) -> Result<Option<String>, DogError> {
match std::fs::read_to_string(path) {
Ok(source) => Ok(Some(source)),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(DogError::Io(err)),
}
}
pub fn dog_section(path: &Path, name: &str) -> Result<String, DogError> {
let Some(source) = read_dogs_toml(path)? else {
return Ok(String::new());
};
let config =
DogsConfig::load(Some(&source)).map_err(|err| DogError::Config(err.to_string()))?;
let Some(table) = config.dog.get(name) else {
return Ok(String::new());
};
let doc: toml_edit::DocumentMut = source
.parse()
.map_err(|err: toml_edit::TomlError| DogError::Config(err.to_string()))?;
match doc.get(name) {
Some(toml_edit::Item::Table(spanned)) => {
let mut section = spanned.clone();
section.set_implicit(true);
*section.decor_mut() = toml_edit::Decor::default();
let mut out = toml_edit::DocumentMut::new();
*out.as_table_mut() = section;
Ok(out.to_string())
}
_ => toml::to_string(table).map_err(|err| DogError::Config(err.to_string())),
}
}
pub fn set_dog_section(path: &Path, name: &str, section: &str) -> Result<(), DogError> {
use std::io::Write as _;
use toml_edit::{DocumentMut, Item};
let _lock = shep_core::config_lock::ConfigLock::acquire(path).map_err(DogError::Io)?;
let existing = read_dogs_toml(path)?.unwrap_or_default();
let mut doc: DocumentMut = existing.parse().map_err(|err: toml_edit::TomlError| {
DogError::Config(format!("dogs.toml does not parse: {err}"))
})?;
let incoming: DocumentMut = section.parse().map_err(|err: toml_edit::TomlError| {
DogError::Config(format!("[{name}] does not parse: {err}"))
})?;
let mut table = incoming.as_table().clone();
table.set_implicit(false);
if let Some(Item::Table(existing)) = doc.get(name) {
*table.decor_mut() = existing.decor().clone();
}
doc[name] = Item::Table(table);
let rendered = doc.to_string();
DogsConfig::load(Some(&rendered))
.map_err(|err| DogError::Config(format!("[{name}] would not load: {err}")))?;
let parent = path.parent().unwrap_or_else(|| Path::new("."));
let mut tmp = shep_core::config_lock::create_config_file(parent).map_err(DogError::Io)?;
tmp.write_all(rendered.as_bytes()).map_err(DogError::Io)?;
shep_core::atomic_file::publish(tmp, path).map_err(DogError::Io)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_section_written_with_sub_tables_reaches_the_dog_as_its_own_document() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("dogs.toml");
let source = "# above the header\n[bark]\n# above poll\npoll = \"5s\"\n\n[bark.sinks.local]\nkind = \"json\"\nurl = \"https://example.invalid/h\"\n\n[[bark.rules]]\non = \"event\"\nkinds = [\"exit\"]\nsinks = [\"local\"]\n\n[otel]\nendpoint = \"https://collector.invalid\"\n";
std::fs::write(&path, source).unwrap();
let section = dog_section(&path, "bark").unwrap();
let parsed: toml::Table = section.parse().unwrap();
assert!(parsed.contains_key("sinks"), "{section}");
assert!(parsed.contains_key("rules"), "{section}");
assert_eq!(
parsed["sinks"]["local"]["kind"].as_str(),
Some("json"),
"{section}"
);
assert_eq!(
parsed["rules"].as_array().map(Vec::len),
Some(1),
"{section}"
);
assert!(section.contains("# above poll"), "{section}");
assert!(!section.contains("# above the header"), "{section}");
assert!(!section.contains("otel"), "{section}");
}
#[test]
fn a_sub_table_section_survives_a_read_and_a_write_back() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("dogs.toml");
std::fs::write(
&path,
"# keep me\n[bark]\npoll = \"5s\"\n\n[bark.sinks.local]\nkind = \"json\"\nurl = \"https://example.invalid/h\"\n",
)
.unwrap();
let section = dog_section(&path, "bark").unwrap();
set_dog_section(&path, "bark", §ion).unwrap();
let after = std::fs::read_to_string(&path).unwrap();
let reloaded: toml::Table = after.parse().unwrap();
assert_eq!(
reloaded["bark"]["sinks"]["local"]["url"].as_str(),
Some("https://example.invalid/h"),
"{after}"
);
assert!(after.contains("# keep me"), "{after}");
assert_eq!(dog_section(&path, "bark").unwrap(), section, "{after}");
}
#[test]
fn a_dogs_section_comes_back_as_its_own_table_and_nothing_else() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("dogs.toml");
std::fs::write(
&path,
"[bark]\ndebounce = \"30s\"\n\n[metrics]\nport = 9615\n",
)
.unwrap();
let bark = dog_section(&path, "bark").unwrap();
assert!(bark.contains("debounce"));
assert!(
!bark.contains("9615"),
"one dog never sees another's config"
);
let parsed: toml::Table = toml::from_str(&bark).unwrap();
assert_eq!(parsed["debounce"].as_str(), Some("30s"));
assert_eq!(dog_section(&path, "absent").unwrap(), "");
assert_eq!(
dog_section(&dir.path().join("gone.toml"), "bark").unwrap(),
""
);
}
#[test]
fn a_section_reaches_the_wire_exactly_as_it_did_from_shep_toml() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("dogs.toml");
std::fs::write(&path, "[bark]\ndebounce = \"30s\"\n").expect("write");
assert_eq!(
dog_section(&path, "bark").expect("section"),
"debounce = \"30s\"\n"
);
}
#[test]
fn a_dog_with_no_section_still_gets_an_empty_string() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("dogs.toml");
std::fs::write(&path, "[bark]\ndebounce = \"30s\"\n").expect("write");
assert_eq!(dog_section(&path, "metrics").expect("section"), "");
}
#[test]
fn set_dog_section_replaces_one_table_and_leaves_the_rest_untouched() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("dogs.toml");
std::fs::write(
&path,
"# top comment\n[metrics]\nbind = \"127.0.0.1:9100\"\n\n[bark]\npoll = \"60s\"\n",
)
.unwrap();
set_dog_section(&path, "bark", "poll = \"30s\"\nhistory_bytes = 4096\n").unwrap();
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.starts_with("# top comment"), "{text}");
assert!(text.contains("bind = \"127.0.0.1:9100\""), "{text}");
assert!(text.contains("poll = \"30s\""), "{text}");
assert!(!text.contains("poll = \"60s\""), "{text}");
let parsed = DogsConfig::load(Some(&text)).unwrap();
assert_eq!(parsed.dog["bark"]["history_bytes"].as_integer(), Some(4096));
}
#[test]
fn a_pane_round_trip_keeps_the_comments_and_the_key_order() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("dogs.toml");
std::fs::write(
&path,
"# what bark is for\n[bark]\n# why bark polls slowly\npoll = \"60s\"\nzz_last = 1\naa_first = 2\n",
)
.unwrap();
let section = dog_section(&path, "bark").unwrap();
assert!(section.contains("# why bark polls slowly"), "{section}");
assert!(
section.find("zz_last") < section.find("aa_first"),
"the keys come back in the operator\'s order: {section}"
);
set_dog_section(&path, "bark", §ion.replace("60s", "30s")).unwrap();
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("# why bark polls slowly"), "{text}");
assert!(
text.contains("# what bark is for"),
"the header's own comment lives on the table, not inside it: {text}"
);
assert!(text.contains("poll = \"30s\""), "{text}");
assert!(
text.find("zz_last") < text.find("aa_first"),
"the write keeps the order the read handed it: {text}"
);
}
#[test]
fn a_dogs_toml_that_cannot_be_read_is_an_io_error_for_both_functions() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("dogs.toml");
std::fs::create_dir(&path).unwrap();
let read = dog_section(&path, "bark").unwrap_err();
assert!(matches!(read, DogError::Io(_)), "{read}");
let write = set_dog_section(&path, "bark", "poll = \"30s\"\n").unwrap_err();
assert!(matches!(write, DogError::Io(_)), "{write}");
}
#[test]
fn set_dog_section_creates_the_file_when_there_is_none() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("dogs.toml");
set_dog_section(&path, "bark", "poll = \"30s\"\n").unwrap();
let parsed = DogsConfig::load(Some(&std::fs::read_to_string(&path).unwrap())).unwrap();
assert!(parsed.dog.contains_key("bark"));
}
#[test]
fn set_dog_section_refuses_text_that_is_not_a_table_and_writes_nothing() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("dogs.toml");
std::fs::write(&path, "[bark]\npoll = \"60s\"\n").unwrap();
let err = set_dog_section(&path, "bark", "this is = = not toml").unwrap_err();
assert!(err.to_string().contains("bark"), "{err}");
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"[bark]\npoll = \"60s\"\n"
);
}
#[test]
fn set_dog_section_refuses_a_result_the_daemon_could_not_read_back() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("dogs.toml");
std::fs::write(&path, "port = 9100\n[bark]\npoll = \"60s\"\n").unwrap();
let err = set_dog_section(&path, "bark", "poll = \"30s\"\n").unwrap_err();
assert!(err.to_string().contains("bark"), "{err}");
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"port = 9100\n[bark]\npoll = \"60s\"\n"
);
}
#[test]
fn set_dog_section_leaves_the_table_behind_when_the_section_is_emptied() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("dogs.toml");
std::fs::write(&path, "[bark]\npoll = \"60s\"\n").unwrap();
set_dog_section(&path, "bark", "").unwrap();
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("[bark]"), "{text}");
let parsed = DogsConfig::load(Some(&text)).unwrap();
assert!(parsed.dog["bark"].is_empty(), "{text}");
}
#[cfg(unix)]
#[test]
fn set_dog_section_writes_owner_only() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("dogs.toml");
set_dog_section(&path, "bark", "poll = \"30s\"\n").unwrap();
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
}
}