use super::{Citations, Ctx, DocView, deprecated::Citer};
use crate::{
Finding, RepoPath,
include::{self, RegionError, extract, render_definitions},
markdown::{IncludeTarget, Region},
source,
};
pub fn check(doc: DocView<'_>, ctx: &Ctx<'_>, citations: &mut Citations) -> Vec<Finding> {
let mut pass = Pass {
doc,
ctx,
citer: Citer::of(doc, ctx),
citations,
findings: Vec::new(),
};
if let Some(line) = doc.segments.unclosed {
pass.fail(
Some(line),
"the include block has no close marker".into(),
"SOKF_FORMAT_86",
);
}
for line in &doc.segments.stray_closes {
pass.fail(
Some(*line),
"a close marker has no open marker".into(),
"SOKF_FORMAT_86",
);
}
for block in &doc.segments.regions {
match &IncludeTarget::parse(&block.target) {
IncludeTarget::Document {
store,
id,
fragment,
} => pass.document_include(block, store.as_deref(), id, fragment.as_deref()),
IncludeTarget::File { path: file, region } => {
pass.path_include(block, file, region.as_deref());
}
}
}
pass.definition_block();
pass.findings
}
struct Pass<'a> {
doc: DocView<'a>,
ctx: &'a Ctx<'a>,
citer: Option<Citer>,
citations: &'a mut Citations,
findings: Vec<Finding>,
}
impl Pass<'_> {
fn fail(&mut self, line: Option<usize>, msg: String, key: &'static str) {
self.findings
.push(Finding::error(self.doc.path.clone(), line, key, msg));
}
fn document_include(
&mut self,
block: &Region,
store: Option<&str>,
id: &str,
fragment: Option<&str>,
) {
let ctx = self.ctx;
let written = &block.target;
let found = ctx
.knowledge
.and_then(|k| ctx.model.document_in(k, store, id).map(|t| (k, t)));
let Some((k, (target_k, target))) = found else {
self.fail(
Some(block.open_line),
format!("`sokf:include {written}` resolves to no document"),
"SOKF_FORMAT_87",
);
return;
};
if let Some(citer) = &self.citer {
self.citations.add(
target.path.clone(),
citer.cite(&target.path, None, block.open_line, true),
);
}
if let Some(canonical) = ctx.model.canonical_include(k, target_k, id, fragment)
&& canonical != *written
{
self.fail(
Some(block.open_line),
format!(
"`sokf:include {written}`: from this store, write `sokf:include {canonical}`, the shortest form that identifies the target; `--fix` rewrites it"
),
"SOKF_FORMAT_65",
);
}
if !include::includes_body(ctx.model, &target.path, fragment) {
match ctx.model.asset_of(&target.path) {
Some((_, asset)) => {
check_file_include(
self.doc,
ctx,
block,
written,
&asset.path,
fragment,
&mut self.findings,
);
}
None => self.fail(
Some(block.open_line),
format!(
"`sokf:include {written}` has a fragment, but the document is not a sidecar. A fragment can only identify a region of an asset"
),
"SOKF_FORMAT_90",
),
}
return;
}
self.body_include(block, &target.path);
}
fn body_include(&mut self, block: &Region, target: &RepoPath) {
let ctx = self.ctx;
let path = self.doc.path;
let written = &block.target;
if let Some(cycle) = ctx
.expected
.cycles
.iter()
.find(|c| c.contains(target) && c.contains(path))
{
let names: Vec<String> = cycle.iter().map(ToString::to_string).collect();
self.fail(
Some(block.open_line),
format!(
"`sokf:include {written}` lies on a cycle: {}",
names.join(", ")
),
"SOKF_FORMAT_91",
);
return;
}
match ctx.expected.include_current(path, block.open_line, &block.content) {
Some(true) => {}
Some(false) => {
self.findings.extend(ctx.expected.include_warning(
path,
block.open_line,
&block.content,
));
self.fail(
Some(block.open_line),
format!("`sokf:include {written}` is stale. Run `sokf validate --fix`"),
"SOKF_FORMAT_85",
);
}
None => self.fail(
Some(block.open_line),
format!(
"`sokf:include {written}` cannot be regenerated: {target} contains an include that does not resolve"
),
"SOKF_FORMAT_85",
),
}
}
fn path_include(&mut self, block: &Region, file: &str, region: Option<&str>) {
let ctx = self.ctx;
let written = &block.target;
let Some(rp) = RepoPath::parse(file) else {
self.fail(
Some(block.open_line),
format!("`sokf:include {written}` points to a path outside the repository"),
"SOKF_FORMAT_87",
);
return;
};
if let Some((target_k, id)) = ctx.model.id_at(&rp) {
let canonical = ctx
.knowledge
.and_then(|k| ctx.model.canonical_include(k, target_k, &id, None))
.unwrap_or(id);
self.fail(
Some(block.open_line),
format!(
"`sokf:include {written}` refers to a document by path. Include its body by id as `sokf:include {canonical}`, or show its source in a code block"
),
"SOKF_FORMAT_88",
);
return;
}
if ctx.model.is_materialized_in(ctx.knowledge, &rp) {
self.fail(
Some(block.open_line),
format!(
"`sokf:include {written}` refers by path to an additional file of this store, and an include block cannot include such a file by path"
),
"SOKF_FORMAT_89",
);
return;
}
if ctx.model.asset_at(&rp).is_some() {
let canonical = ctx
.knowledge
.and_then(|k| asset_include(ctx.model, k, &rp, region))
.unwrap_or_else(|| "<id>".into());
self.fail(
Some(block.open_line),
format!(
"`sokf:include {written}` refers to an asset by path; include it by its sidecar's id as `sokf:include {canonical}`, which `--fix` writes"
),
"SOKF_FORMAT_88",
);
return;
}
check_file_include(
self.doc,
ctx,
block,
written,
&rp,
region,
&mut self.findings,
);
}
fn definition_block(&mut self) {
let doc = self.doc;
let Some(expected) = self
.ctx
.expected
.definitions
.get(doc.path)
.and_then(|d| d.as_ref())
else {
return;
};
let rendered = render_definitions(expected);
let missing = if doc.core.is_some() {
"SOKF_FORMAT_77"
} else {
"SOKF_FORMAT_78"
};
match &doc.segments.definition {
None if expected.is_empty() => {}
None => self.fail(None, "the definition block is missing; run `sokf validate --fix`".into(), missing),
Some(def) if expected.is_empty() => self.fail(Some(def.line), "the definition block is stale: the body cites no `sokf:` label; run `sokf validate --fix`".into(), "SOKF_FORMAT_80"),
Some(def) => {
let (rendered, written) = (rendered.trim_end(), def.text.trim_end());
if def.trailing {
self.fail(Some(def.line), "content follows the definition block, which must come last in the document".into(), "SOKF_FORMAT_79");
} else if !self.ctx.expected.layout.same("md", rendered, written) {
self.findings.extend(self.ctx.expected.layout.warning("md", rendered, written));
self.fail(Some(def.line), "the definition block is stale. Run `sokf validate --fix`".into(), "SOKF_FORMAT_80");
}
}
}
}
}
pub fn asset_include(
model: &crate::Model,
citing: usize,
path: &RepoPath,
region: Option<&str>,
) -> Option<String> {
let (k, asset) = model.asset_at(path)?;
model.note(crate::model::Query::Path(asset.sidecar_path()));
let id = model.knowledges[k].documents[asset.sidecar?].id()?;
model.canonical_include(citing, k, id, region)
}
fn check_file_include(
doc: DocView<'_>,
ctx: &Ctx<'_>,
block: &Region,
written: &str,
rp: &RepoPath,
region: Option<&str>,
findings: &mut Vec<Finding>,
) {
let fail = |findings: &mut Vec<Finding>, msg: String, key: &'static str| {
findings.push(Finding::error(
doc.path.clone(),
Some(block.open_line),
key,
msg,
));
};
if !ctx.model.exists(rp) {
if !ctx.model.is_planned(rp) {
fail(
findings,
format!("`sokf:include {written}` refers to a path where no file exists"),
"SOKF_FORMAT_87",
);
}
return;
}
let text = match source::load_text(&ctx.model.tree.root, rp) {
Ok(t) => t,
Err(e) => {
fail(
findings,
format!("`sokf:include {written}`: {e}"),
"SOKF_FORMAT_87",
);
return;
}
};
match extract(&text, region) {
Err(e) => {
let key = match &e {
RegionError::AlreadyOpen { .. } => "SOKF_FORMAT_112",
_ => "SOKF_FORMAT_95",
};
findings.push(Finding::error(
rp.clone(),
Some(e.line()),
key,
e.to_string(),
));
}
Ok(None) => fail(
findings,
format!(
"`sokf:include {written}`: {rp} has no region `{}`",
region.unwrap_or("")
),
"SOKF_FORMAT_87",
),
Ok(Some(_)) => {
if ctx
.expected
.include_current(doc.path, block.open_line, &block.content)
!= Some(true)
{
findings.extend(ctx.expected.include_warning(
doc.path,
block.open_line,
&block.content,
));
fail(
findings,
format!("`sokf:include {written}` is stale. Run `sokf validate --fix`"),
"SOKF_FORMAT_85",
);
}
}
}
}