use std::collections::BTreeMap;
use tramlines_md::grammar::lower_common;
use super::{Block, RuleCommon, Schema, Unit};
use crate::{Finding, RepoPath, Spanned};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Dispatch {
Type(String),
Globs(Vec<String>),
}
#[derive(Debug, Clone)]
pub struct LinkRule {
pub common: RuleCommon,
pub rel: String,
pub to_type: Vec<String>,
pub min: usize,
pub max: Option<usize>,
pub guidance: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CitedFrom {
Types(Vec<String>),
Marker(String),
}
#[derive(Debug, Clone)]
pub struct CitationRule {
pub common: RuleCommon,
pub from: CitedFrom,
pub keys: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Clone)]
pub struct PathPlan {
pub common: RuleCommon,
pub section: String,
}
#[derive(Debug, Clone)]
pub struct SokfSchema {
pub core: Schema,
pub dispatch: Dispatch,
pub asset_files: Vec<String>,
pub root: Option<String>,
pub paths: Vec<String>,
pub links: Vec<LinkRule>,
pub links_open: bool,
pub cited_by: Vec<CitationRule>,
pub markers: Option<Vec<String>>,
pub plans_paths: Vec<PathPlan>,
pub current_links: Vec<regex::Regex>,
pub unit_types: BTreeMap<usize, Vec<String>>,
}
fn fail(
path: &RepoPath,
line: usize,
criterion: &'static str,
message: impl Into<String>,
) -> Finding {
Finding::error(path.clone(), Some(line), criterion, message)
}
fn glob_problem(g: &str) -> Option<String> {
if !g.starts_with('/') {
return Some("does not start with /".into());
}
globset::Glob::new(g)
.err()
.map(|e| format!("does not parse: {e}"))
}
fn list(node: &Spanned) -> Vec<String> {
node.as_str_or_list().unwrap_or_default()
}
fn kebab(rel: &str) -> Option<String> {
let mut out = String::new();
let mut prev_lower = false;
for c in rel.chars() {
if c.is_ascii_uppercase() && prev_lower {
out.push('-');
}
prev_lower = c.is_ascii_lowercase() || c.is_ascii_digit();
out.push(match c {
'_' | ' ' => '-',
c => c.to_ascii_lowercase(),
});
}
crate::markdown::is_slug(&out).then_some(out)
}
pub fn glob_inside(glob: &str, dir: &RepoPath) -> bool {
let prefix: String = glob
.chars()
.take_while(|c| !matches!(c, '*' | '?' | '[' | '{'))
.collect();
let dir = format!("{}/", dir.as_str().trim_end_matches('/'));
prefix.starts_with(&dir)
}
impl SokfSchema {
pub fn of_schema_document(core: Schema) -> Self {
SokfSchema {
core,
dispatch: Dispatch::Type("Schema".into()),
asset_files: vec![],
root: None,
paths: vec![],
links: vec![],
links_open: true,
cited_by: vec![],
markers: None,
plans_paths: vec![],
current_links: vec![],
unit_types: BTreeMap::new(),
}
}
pub fn lower(core: Schema, yaml: &Spanned, path: &RepoPath) -> (Self, Vec<Finding>) {
let mut findings = Vec::new();
let ext = |key: &str| core.extensions.get(key);
let globs = ext("additional-files").map(list);
let assets = ext("asset-files").map(list);
let dispatch = match (core.core.type_const().map(str::to_string), globs) {
(Some(_), Some(_)) => {
findings.push(fail(
path,
yaml.line,
"SOKF_SCHEMA_3",
"the schema declares both a `type` const and `additional-files`. Declare only one of them",
));
Dispatch::Globs(vec![])
}
(None, None) => {
let message = if assets.is_some() {
"`asset-files` needs a `type` const as well"
} else {
"the schema declares neither a `type` const nor `additional-files`. Declare one of them"
};
findings.push(fail(path, yaml.line, "SOKF_SCHEMA_3", message));
Dispatch::Globs(vec![])
}
(Some(t), None) => Dispatch::Type(t),
(None, Some(globs)) => {
let line = ext("additional-files").map_or(yaml.line, |a| a.line);
for g in &globs {
if let Some(why) = glob_problem(g) {
findings.push(fail(
path,
line,
"SOKF_SCHEMA_5",
format!("`additional-files` glob `{g}` {why}"),
));
}
}
Dispatch::Globs(globs)
}
};
let asset_files = match assets {
None => vec![],
Some(globs) => {
if ext("additional-files").is_some() {
let line = ext("asset-files").map_or(yaml.line, |a| a.line);
findings.push(fail(
path,
line,
"SOKF_SCHEMA_4",
"the schema declares `asset-files` together with `additional-files`. Declare only one of them",
));
}
globs
}
};
let paths: Vec<String> = core
.core
.lifecycle
.iter()
.filter(|d| {
d.extensions
.get("path")
.and_then(|p| p.as_bool())
.unwrap_or(false)
})
.map(|d| d.key.clone())
.collect();
let root = ext("root").and_then(|r| r.as_str()).map(str::to_string);
for d in &core.core.lifecycle {
let Some(node) = d.extensions.get("archived") else {
continue;
};
for state in list(node) {
if !d.states.contains(&state) {
findings.push(fail(
path,
node.line,
"SOKF_SCHEMA_50",
format!(
"`archived` state `{state}` is not a state of the dimension `{}`",
d.key
),
));
}
}
}
if let Some(a) = ext("archived")
&& !core.core.lifecycle.is_empty()
{
findings.push(fail(
path,
a.line,
"SOKF_SCHEMA_50",
"the schema declares `archived` together with `lifecycle`. Declare `archived` on a dimension",
));
}
if let Some(l) = yaml.get("lifecycle") {
if ext("additional-files").is_some() {
findings.push(fail(
path,
l.line,
"SOKF_SCHEMA_4",
"the schema declares `lifecycle` together with `additional-files`. Declare only one of them",
));
}
if !paths.is_empty() && root.is_none() {
findings.push(fail(
path,
l.line,
"SOKF_SCHEMA_27",
"a path-enforced dimension needs `root`",
));
}
}
if let Some(r) = ext("root")
&& root.as_deref().and_then(RepoPath::parse).is_none()
{
findings.push(fail(
path,
r.line,
"SOKF_SCHEMA_27",
"`root` is not a valid repository path: it must start with / and have no empty, `.`, or `..` segment",
));
}
findings.extend(asset_globs(
path,
ext("asset-files").map_or(yaml.line, |a| a.line),
&asset_files,
root.as_deref(),
));
let mut links = Vec::new();
for node in ext("links").and_then(|l| l.as_seq()).unwrap_or(&[]) {
let (common, problems) = lower_common(node, &core.core, path);
findings.extend(problems);
let usize_of = |key: &str| {
node.get(key)
.and_then(|v| v.as_int())
.map(|i| usize::try_from(i).unwrap_or(0))
};
links.push(LinkRule {
common,
rel: node
.get("rel")
.and_then(|r| r.as_str())
.unwrap_or_default()
.to_string(),
to_type: node.get("to-type").map(list).unwrap_or_default(),
min: usize_of("min").unwrap_or(1),
max: usize_of("max"),
guidance: node
.get("guidance")
.and_then(|g| g.as_str())
.map(str::to_string),
});
}
let links_open = ext("links-open").and_then(|l| l.as_bool()).unwrap_or(false);
let mut cited_by = Vec::new();
for node in ext("cited-by").and_then(|l| l.as_seq()).unwrap_or(&[]) {
let (common, problems) = lower_common(node, &core.core, path);
findings.extend(problems);
let keys = node
.get("keys")
.and_then(|k| k.as_str())
.map(str::to_string);
if let Some(k) = &keys
&& let Err(why) = core.rule_captures_key(k)
{
findings.push(fail(
path,
node.line,
"SOKF_SCHEMA_35",
why.message("keys", k),
));
}
let from = match (node.get("from-type"), node.get("from-marker")) {
(None, Some(m)) => CitedFrom::Marker(m.as_str().unwrap_or_default().to_string()),
(t, _) => CitedFrom::Types(t.map(list).unwrap_or_default()),
};
let message = node
.get("message")
.and_then(|m| m.as_str())
.map(str::to_string);
cited_by.push(CitationRule {
common,
from,
keys,
message,
});
}
let markers_node = ext("markers");
let markers = markers_node.map(list);
for item in markers_node.and_then(|n| n.as_seq()).unwrap_or(&[]) {
let Some(rel) = item.as_str() else { continue };
if crate::markdown::is_slug(rel) {
continue;
}
let fix = match kebab(rel) {
Some(k) => format!("Write it as `{k}`"),
None => "Write it as lowercase words of letters and digits joined by `-`".into(),
};
findings.push(fail(
path,
item.line,
"EXT-9_AC-11",
format!(
"`markers` names the relationship `{rel}`, which isn't lowercase kebab case, so it matches no marker. {fix}"
),
));
}
let mut plans_paths = Vec::new();
for node in ext("plans-paths").and_then(|l| l.as_seq()).unwrap_or(&[]) {
let (common, problems) = lower_common(node, &core.core, path);
findings.extend(problems);
let section = node
.get("section")
.and_then(|s| s.as_str())
.unwrap_or_default()
.to_string();
if !core
.sections
.iter()
.any(|s| s.rule_id.as_deref() == Some(section.as_str()))
{
findings.push(fail(
path,
node.line,
"SOKF_SCHEMA_52",
format!("`section: {section}` names no section of the schema; give the `rule-id` of a section"),
));
}
plans_paths.push(PathPlan { common, section });
}
let current_links = ext("current-links")
.map(list)
.unwrap_or_default()
.iter()
.filter_map(|p| regex::Regex::new(p).ok())
.collect();
let unit_types = unit_types(&core);
let schema = SokfSchema {
core,
dispatch,
asset_files,
root,
paths,
links,
links_open,
cited_by,
markers,
plans_paths,
current_links,
unit_types,
};
(schema, findings)
}
pub fn has_assets(&self) -> bool {
!self.asset_files.is_empty()
}
pub fn is_path(&self, key: &str) -> bool {
self.paths.iter().any(|p| p == key)
}
}
fn unit_types(schema: &Schema) -> BTreeMap<usize, Vec<String>> {
let mut out = BTreeMap::new();
let mut blocks: Vec<&Block> = schema
.sections
.iter()
.filter_map(|s| s.blocks.as_deref())
.chain(schema.preamble.iter().filter_map(|p| p.blocks.as_deref()))
.flatten()
.collect();
while let Some(b) = blocks.pop() {
blocks.extend(b.blocks.iter().flatten());
let mut units: Vec<&Unit> = b.units().collect();
while let Some(u) = units.pop() {
units.extend(u.lines.iter().flatten());
blocks.extend(u.blocks.iter().flatten());
if let Some(types) = u.extensions.get("to-type") {
out.insert(u.index, list(types));
}
}
}
out
}
fn asset_globs(path: &RepoPath, line: usize, globs: &[String], root: Option<&str>) -> Vec<Finding> {
let mut findings = Vec::new();
let knowledge = path.parent().and_then(|d| d.parent());
for g in globs {
if let Some(why) = glob_problem(g) {
findings.push(fail(
path,
line,
"SOKF_SCHEMA_8",
format!("`asset-files` glob `{g}` {why}"),
));
continue;
}
if let Some(k) = &knowledge
&& !glob_inside(g, k)
{
findings.push(fail(
path,
line,
"SOKF_SCHEMA_8",
format!("`asset-files` glob `{g}` lies outside the knowledge root `{k}`"),
));
}
if let Some(r) = root
&& !g.starts_with(&format!("{}/**/", r.trim_end_matches('/')))
{
findings.push(fail(
path,
line,
"SOKF_SCHEMA_10",
format!(
"`asset-files` glob `{g}` does not begin with `{r}/**/`, where `{r}` is the lifecycle root"
),
));
}
}
findings
}