use crate::{
Cache, CacheMode, Error, RepoRoot, Result, config,
grammar::{self, RegexCache},
model::SchemaRef,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InfoLayer {
Embedded,
Repo,
Pack,
Effective,
}
pub fn info_grammar() -> String {
grammar::grammar_text()
}
pub fn info_formats(
root: Option<&RepoRoot>,
layer: InfoLayer,
schema: Option<&str>,
cache: CacheMode,
) -> Result<String> {
let grammar = grammar::load_grammar()?;
let regexes = RegexCache::new();
if let Some(id) = schema {
let root = root.ok_or(Error::NoRepository)?;
let config = config::load_config(root)?;
let repo = config::load_repo_formats(root, &grammar, ®exes)?;
let cache = Cache::open(root, cache);
let mut model = super::load_for_lookup(root, &config, &cache)?;
super::admit_schema_by_id(&mut model, root, &cache, id)?;
let compiled = grammar::compile_all(&model, grammar, &repo);
let found: Vec<SchemaRef> = model
.knowledges
.iter()
.enumerate()
.filter_map(|(k, knowledge)| {
knowledge.schema_by_id(id).map(|i| SchemaRef {
knowledge: k,
index: i,
})
})
.collect();
let roots = |ks: &mut dyn Iterator<Item = usize>| -> String {
ks.map(|k| model.knowledges[k].root.as_str())
.collect::<Vec<_>>()
.join(", ")
};
let r = match found.as_slice() {
[] => {
return Err(Error::Info(format!(
"schema `{id}` is not in any root. The roots are {}",
roots(&mut (0..model.knowledges.len()))
)));
}
[one] => *one,
many => {
return Err(Error::Info(format!(
"schema `{id}` is declared in more than one root: {}",
roots(&mut many.iter().map(|r| r.knowledge))
)));
}
};
let Some(schema) = compiled.schema(r) else {
return Err(Error::Info(format!(
"schema `{id}` does not match the grammar. Run `sokf validate` to see the errors"
)));
};
return Ok(schema.core.core.formats.to_yaml(true));
}
let embedded = grammar::embedded_formats(&grammar, ®exes)?;
match layer {
InfoLayer::Embedded => Ok(embedded.to_yaml(true)),
InfoLayer::Repo => {
let root = root.ok_or(Error::NoRepository)?;
match config::load_repo_formats(root, &grammar, ®exes)?.repo {
Some(repo) => Ok(repo.to_yaml(false)),
None => Err(Error::Info(
"the repository has no /.sokf/formats.yaml".into(),
)),
}
}
InfoLayer::Pack => {
let root = root.ok_or(Error::NoRepository)?;
match config::load_repo_formats(root, &grammar, ®exes)?.pack_layer() {
Some(packs) => Ok(packs.to_yaml(false)),
None => Err(Error::Info(
"no pack in /.sokf/packs.lock has a formats.yaml".into(),
)),
}
}
InfoLayer::Effective => {
let root = root.ok_or(Error::NoRepository)?;
let formats = config::load_repo_formats(root, &grammar, ®exes)?;
Ok(formats.effective(&embedded).to_yaml(true))
}
}
}