use crate::RepoRoot;
use crate::{
Error, RepoPath, Result,
grammar::{FormatRegistry, FormatSource, Grammar, RegexCache},
pack,
source::{Fnv, read_optional},
yaml,
};
pub fn formats_path() -> RepoPath {
RepoPath::parse("/.sokf/formats.yaml").expect("literal")
}
#[derive(Debug, Clone, Default)]
pub struct RepoFormats {
pub repo: Option<FormatRegistry>,
pub packs: Option<FormatRegistry>,
pub hash: u64,
}
impl RepoFormats {
pub fn effective(&self, embedded: &FormatRegistry) -> FormatRegistry {
let none = FormatRegistry::default();
let repo = self.repo.as_ref().unwrap_or(&none);
self.packs.as_ref().unwrap_or(embedded).layered(repo)
}
pub fn pack_layer(&self) -> Option<FormatRegistry> {
let layer = self.packs.as_ref()?;
let mut packs = FormatRegistry::default();
let pack = |s: &FormatSource| matches!(s, FormatSource::Pack(_));
packs.entries = layer
.entries
.iter()
.filter(|(_, (_, s))| pack(s))
.map(|(n, e)| (n.clone(), e.clone()))
.collect();
packs.types.entries = layer
.types
.entries
.iter()
.filter(|(_, (_, s))| pack(s))
.map(|(n, e)| (n.clone(), e.clone()))
.collect();
Some(packs)
}
}
pub fn load_repo_formats(
root: &RepoRoot,
grammar: &Grammar,
regexes: &RegexCache,
) -> Result<RepoFormats> {
let mut hash = Fnv::new();
let lock = pack::read_lock(root)?;
let embedded = crate::grammar::embedded_formats(grammar, regexes)?;
let mut layer: Option<FormatRegistry> = None;
for name in pack::ordered(root, &lock) {
let path = pack::formats_of(&name);
let Some(text) = read_optional(&path.to_fs(root))? else {
continue;
};
hash.update(path.as_str().as_bytes());
hash.update(text.as_bytes());
let below = layer.as_ref().unwrap_or(&embedded);
let registry = parse(
&path,
&text,
FormatSource::Pack(name.clone()),
grammar,
regexes,
below,
)?;
layer = Some(below.layered(®istry));
}
let mut formats = RepoFormats {
repo: None,
packs: layer,
hash: 0,
};
let path = formats_path();
if let Some(text) = read_optional(&path.to_fs(root))? {
hash.update(text.as_bytes());
let below = formats.packs.as_ref().unwrap_or(&embedded);
formats.repo = Some(parse(
&path,
&text,
FormatSource::Repo,
grammar,
regexes,
below,
)?);
}
formats.hash = hash.finish();
Ok(formats)
}
fn parse(
path: &RepoPath,
text: &str,
source: FormatSource,
grammar: &Grammar,
regexes: &RegexCache,
base: &FormatRegistry,
) -> Result<FormatRegistry> {
let doc = yaml::parse(text, 1).map_err(|e| Error::formats(path.clone(), e.to_string()))?;
let registry = doc
.get("registry")
.ok_or_else(|| Error::formats(path.clone(), "The file has no `registry` map."))?;
FormatRegistry::from_yaml_at(
registry,
doc.get("types"),
source,
grammar,
regexes,
path,
Some(base),
)
.map_err(|findings| {
let messages: Vec<String> = findings
.iter()
.map(|f| match f.line {
Some(l) => format!("line {l}: {}", crate::report::message(f)),
None => crate::report::message(f),
})
.collect();
Error::formats(path.clone(), messages.join("; "))
})
}
#[cfg(test)]
mod tests {
use std::{
fs,
path::{Path, PathBuf},
};
use super::*;
use crate::grammar::load_grammar;
fn temp(name: &str) -> PathBuf {
let dir = crate::test_support::fresh_dir(&format!("formats-{name}"));
fs::create_dir_all(dir.join(".sokf")).unwrap();
dir
}
fn with(dir: &Path, text: Option<&str>) -> Result<Option<FormatRegistry>> {
with_all(dir, text).map(|f| f.repo)
}
fn with_all(dir: &Path, text: Option<&str>) -> Result<RepoFormats> {
if let Some(text) = text {
fs::write(dir.join(".sokf/formats.yaml"), text).unwrap();
}
let grammar = load_grammar().unwrap();
load_repo_formats(
&RepoRoot::new(dir.to_path_buf()),
&grammar,
&RegexCache::new(),
)
}
#[test]
fn absent_file_is_none_and_a_good_file_is_the_repo_layer() {
let dir = temp("ok");
assert!(with(&dir, None).unwrap().is_none());
let r = with(
&dir,
Some("registry:\n requirement-ears:\n pattern: '.*'\n example: x\n"),
)
.unwrap()
.unwrap();
assert_eq!(r.entries["requirement-ears"].1, FormatSource::Repo);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn refuses_bad_files() {
let dir = temp("bad");
for text in [
"registry: [",
"other: 1\n",
"registry:\n requirement-ears:\n doc: d\n",
"registry:\n requirement-ears:\n doc: d\n example: e\n pattern: '('\n",
] {
let e = with(&dir, Some(text)).unwrap_err();
assert!(matches!(e, Error::FormatsFile { .. }), "{text:?} -> {e}");
assert!(e.to_string().starts_with("/.sokf/formats.yaml: "), "{e}");
}
fs::remove_dir_all(&dir).unwrap();
}
}