use std::collections::BTreeMap;
use schemars::JsonSchema;
use serde::Serialize;
use crate::{
Cache, CacheMode, Error, RepoRoot, Result, config,
grammar::{self, FormatRegistry, RegexCache, TypeDef},
graph::yaml_json,
model::SchemaRef,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InfoLayer {
Embedded,
Repo,
FormatsD,
Effective,
}
pub fn info_grammar() -> String {
grammar::grammar_text()
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[schemars(title = "sokf info formats registry")]
pub struct FormatsJson {
pub types: BTreeMap<String, FormatType>,
pub registry: BTreeMap<String, FormatEntry>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct FormatType {
#[serde(rename = "match")]
pub matches: TypeMatch,
pub source: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(untagged)]
pub enum TypeMatch {
Regex(String),
Choices(Vec<String>),
}
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
pub struct FormatEntry {
#[serde(flatten)]
pub entry: serde_json::Map<String, serde_json::Value>,
pub source: String,
}
fn formats_json(registry: &FormatRegistry, built_ins: bool) -> FormatsJson {
let types = if built_ins {
registry.types_seen()
} else {
registry.types.clone()
};
FormatsJson {
types: types
.entries
.iter()
.map(|(name, (def, source))| {
let matches = match def {
TypeDef::Regex(r) => TypeMatch::Regex(r.clone()),
TypeDef::Choices(c) => TypeMatch::Choices(c.clone()),
};
let source = source.label().into_owned();
(name.clone(), FormatType { matches, source })
})
.collect(),
registry: registry
.entries
.iter()
.map(|(name, (format, source))| {
let mut entry = match yaml_json(&format.raw) {
serde_json::Value::Object(map) => map,
_ => serde_json::Map::new(),
};
entry.retain(|key, _| key != "source");
let source = source.label().into_owned();
(name.clone(), FormatEntry { entry, source })
})
.collect(),
}
}
pub fn info_formats(
root: Option<&RepoRoot>,
layer: InfoLayer,
schema: Option<&str>,
cache: CacheMode,
) -> Result<String> {
let (formats, built_ins) = registry(root, layer, schema, cache)?;
Ok(formats.to_yaml(built_ins))
}
pub fn info_formats_json(
root: Option<&RepoRoot>,
layer: InfoLayer,
schema: Option<&str>,
cache: CacheMode,
) -> Result<FormatsJson> {
let (formats, built_ins) = registry(root, layer, schema, cache)?;
Ok(formats_json(&formats, built_ins))
}
fn registry(
root: Option<&RepoRoot>,
layer: InfoLayer,
schema: Option<&str>,
cache: CacheMode,
) -> Result<(FormatRegistry, bool)> {
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, crate::Texts::english());
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.clone(), true));
}
let embedded = grammar::embedded_formats(&grammar, ®exes)?;
match layer {
InfoLayer::Embedded => Ok((embedded, true)),
InfoLayer::Repo => {
let root = root.ok_or(Error::NoRepository)?;
match config::load_repo_formats(root, &grammar, ®exes)?.repo {
Some(repo) => Ok((repo, false)),
None => Err(Error::Info(
"the repository has no /.sokf/formats.yaml".into(),
)),
}
}
InfoLayer::FormatsD => {
let root = root.ok_or(Error::NoRepository)?;
match config::load_repo_formats(root, &grammar, ®exes)?.folder_layer() {
Some(folder) => Ok((folder, false)),
None => Err(Error::Info(format!(
"/{}/ holds no file *.yaml",
config::FORMATS_DIR
))),
}
}
InfoLayer::Effective => {
let root = root.ok_or(Error::NoRepository)?;
let formats = config::load_repo_formats(root, &grammar, ®exes)?;
Ok((formats.effective(&embedded), true))
}
}
}