use super::{Citations, Ctx, DocView, deprecated::Citer};
use crate::{
Finding, RepoPath,
graph::{Target, resolve_to},
markdown::{Link, LinkTarget, is_url, sokf_label},
model::{
CoreFields,
frontmatter::Resource,
keys::{self, Label, Unresolved},
},
};
pub fn check_document(doc: DocView<'_>, ctx: &Ctx<'_>, citations: &mut Citations) -> Vec<Finding> {
let mut findings = Vec::new();
let path = doc.path;
let fail =
|findings: &mut Vec<Finding>, line: Option<usize>, msg: String, key: &'static str| {
findings.push(Finding::error(path.clone(), line, key, msg));
};
let knowledge = ctx.knowledge;
let citer = Citer::of(doc, ctx);
for link in &doc.body.links {
check_link(link, doc, ctx, &mut findings, citations, citer.as_ref());
}
suffix_clashes(doc, ctx, &mut findings);
let Some(core) = doc.core else {
return findings;
};
check_footnotes(doc, core, &mut findings);
check_resources(doc, core, ctx, &mut findings);
let Some(k) = knowledge else {
return findings;
};
for entry in &core.links {
let Some(target) = resolve_to(ctx.model, k, &entry.to) else {
let (message, key) = unresolved_entry(ctx, k, &entry.to);
fail(&mut findings, Some(entry.line), message, key);
continue;
};
if entry.rel == "supersedes"
&& let (
Target::Document {
path: target_path, ..
},
Some(citer),
) = (&target, &citer)
{
citations.add(target_path.clone(), citer.declare(entry.line));
}
if let Some(canonical) = canonical_to(ctx, k, &target)
&& canonical != entry.to
{
fail(
&mut findings,
Some(entry.line),
format!(
"write the `links` entry `to: {}` as `to: {canonical}`",
entry.to
),
"SOKF_FORMAT_65",
);
}
if !mirrored(doc, ctx, k, &target) {
fail(
&mut findings,
Some(entry.line),
format!(
"`links` entry `to: {}` has no body link that mirrors it",
entry.to
),
"SOKF_FORMAT_75",
);
}
}
findings
}
fn check_footnotes(doc: DocView<'_>, core: &CoreFields, findings: &mut Vec<Finding>) {
for (label, line) in &doc.body.footnote_refs {
if !core.sources.iter().any(|s| s.id.as_deref() == Some(label)) {
findings.push(Finding::error(
doc.path.clone(),
Some(*line),
"SOKF_FORMAT_41",
format!("footnote `[^{label}]` matches no `sources[].id`"),
));
}
}
}
fn check_resources(
doc: DocView<'_>,
core: &CoreFields,
ctx: &Ctx<'_>,
findings: &mut Vec<Finding>,
) {
let fail =
|findings: &mut Vec<Finding>, line: Option<usize>, msg: String, key: &'static str| {
findings.push(Finding::error(doc.path.clone(), line, key, msg));
};
for resource in core.resource.iter().flat_map(Resource::entries) {
if let Some(p) = RepoPath::parse(resource)
&& !ctx.model.exists(&p)
&& !ctx.model.is_planned(&p)
{
fail(
findings,
core.line_of("resource"),
format!("`resource` refers to a file that doesn't exist: `{resource}`"),
"SOKF_FORMAT_30",
);
}
}
for source in &core.sources {
if let Some(p) = RepoPath::parse(&source.resource) {
if !ctx.model.exists(&p) {
fail(
findings,
Some(source.line),
format!(
"`sources[].resource` refers to a file that doesn't exist: {}",
source.resource
),
"SOKF_FORMAT_37",
);
}
} else if !is_url(&source.resource) {
fail(
findings,
Some(source.line),
format!(
"`sources[].resource` must be a `/` path or a URL: {}",
source.resource
),
"SOKF_FORMAT_37",
);
}
}
}
fn unresolved_entry(ctx: &Ctx<'_>, k: usize, to: &str) -> (String, &'static str) {
match crate::model::split_store(to) {
(Some(store), _) if !to.starts_with('/') && ctx.model.store(k, store).is_none() => (
format!(
"`links` entry `to: {to}` refers to the store `{store}`, which is not a knowledge root of this repository"
),
"SOKF_FORMAT_64",
),
_ => (
format!("`links` entry `to: {to}` resolves to nothing"),
"SOKF_FORMAT_53",
),
}
}
fn mirrored(doc: DocView<'_>, ctx: &Ctx<'_>, k: usize, target: &Target) -> bool {
doc.body.links.iter().any(|l| match (&l.target, target) {
(
LinkTarget::Host(rest),
Target::Document {
path: target_path, ..
},
) => {
let label = Label::parse(rest);
label.id.is_some()
&& keys::resolve(ctx.model, ctx.keys, k, label)
.is_ok_and(|r| &r.path == target_path)
}
(
LinkTarget::Repo { path, .. },
Target::Document {
path: target_path, ..
}
| Target::File(target_path),
) => path == target_path,
(LinkTarget::Relative { target: rel, .. }, Target::File(target_path)) => {
doc.path.resolve_relative(rel).as_ref() == Some(target_path)
}
_ => false,
})
}
fn fail_at(
findings: &mut Vec<Finding>,
path: &RepoPath,
line: usize,
msg: String,
key: &'static str,
) {
findings.push(Finding::error(path.clone(), Some(line), key, msg));
}
fn check_link(
link: &Link,
doc: DocView<'_>,
ctx: &Ctx<'_>,
findings: &mut Vec<Finding>,
citations: &mut Citations,
citer: Option<&Citer>,
) {
let path = doc.path;
let what = if link.is_image { "image" } else { "link" };
match &link.target {
LinkTarget::Host(_) => check_label(link, doc, ctx, findings, citations, citer),
LinkTarget::Reference(label) => {
fail_at(
findings,
path,
link.line,
format!("reference-style link `[{label}]` matches no definition"),
"SOKF_FORMAT_74",
);
}
LinkTarget::Repo {
path: target, dir, ..
} => {
if *dir && !ctx.model.is_dir(target) && ctx.model.exists(target) {
fail_at(
findings,
path,
link.line,
format!("{what} `{target}/` names a file, not a directory"),
"SOKF_FORMAT_76",
);
} else {
check_path(target, link, doc, ctx, findings);
}
}
LinkTarget::Relative { target, .. } => match doc.path.resolve_relative(target) {
Some(resolved) => check_path(&resolved, link, doc, ctx, findings),
None => fail_at(
findings,
path,
link.line,
format!("{what} `{target}` points outside the repository"),
"SOKF_FORMAT_76",
),
},
LinkTarget::Invalid(url) => fail_at(
findings,
path,
link.line,
format!("{what} `{url}` is not a valid repository path"),
"SOKF_FORMAT_76",
),
LinkTarget::Anchor(fragment) => {
if let Err(u) = keys::resolve_in(ctx.keys, path, doc.body, fragment) {
let message = match u {
Unresolved::KeyForm(slug) => format!(
"`#{fragment}` uses the heading text. Use the slug `#{slug}` instead"
),
_ => format!("`#{fragment}` matches no heading or key in this document"),
};
fail_at(findings, path, link.line, message, "SOKF_FORMAT_73");
}
}
LinkTarget::Url(_) => {}
}
}
fn check_label(
link: &Link,
doc: DocView<'_>,
ctx: &Ctx<'_>,
findings: &mut Vec<Finding>,
citations: &mut Citations,
citer: Option<&Citer>,
) {
let label = sokf_label(link).unwrap_or_default();
let parts = Label::of(&link.target).unwrap_or_default();
match ctx.knowledge {
None => fail_at(
findings,
doc.path,
link.line,
format!("`[{label}]` cites a document from a file that is outside any knowledge root"),
"SOKF_FORMAT_61",
),
Some(k) => {
let resolved = keys::resolve(ctx.model, ctx.keys, k, parts);
if let Ok(r) = &resolved
&& let Some(citer) = citer
{
citations.add(
r.path.clone(),
citer.cite(&r.path, r.slug.clone(), link.line, false),
);
}
if let Ok(r) = &resolved
&& let Some(canonical) =
ctx.model
.canonical_label(k, r.knowledge, parts.id, parts.fragment)
&& canonical != label
{
fail_at(
findings,
doc.path,
link.line,
format!("write `[{label}]` as `[{canonical}]`"),
"SOKF_FORMAT_65",
);
}
match resolved {
Err(u) => fail_at(
findings,
doc.path,
link.line,
u.message(&label),
unresolved_key(&u, parts),
),
Ok(resolved) if link.is_image && ctx.model.asset_of(&resolved.path).is_none() => {
fail_at(
findings,
doc.path,
link.line,
format!(
"image `[{label}]` refers to the document `{}`, which is not a sidecar. An image must refer to an asset through its sidecar's id",
resolved.path
),
"SOKF_FORMAT_67",
);
}
Ok(_) => {}
}
}
}
}
fn suffix_clashes(doc: DocView<'_>, ctx: &Ctx<'_>, findings: &mut Vec<Finding>) {
let suffixed = crate::markdown::suffixed_headings(doc.body);
if suffixed.is_empty() {
return;
}
for entry in ctx.keys.of_document(doc.path) {
let key_slug = entry.id.clone();
for (line, slug) in &suffixed {
if *line != entry.line && *slug == key_slug {
findings.push(Finding::error(
doc.path.clone(),
Some(entry.line),
"SOKF_FORMAT_68",
format!(
"key `{}` has the slug `{slug}` of the heading at line {line}; keys and headings share one namespace",
entry.key
),
));
}
}
}
}
fn unresolved_key(u: &Unresolved, label: Label<'_>) -> &'static str {
match u {
Unresolved::NoStore(_) => "SOKF_FORMAT_64",
Unresolved::NoDocument if label.id.is_none() && label.fragment == Some("") => {
"SOKF_FORMAT_66"
}
Unresolved::NoDocument | Unresolved::DuplicateId => "SOKF_FORMAT_61",
Unresolved::BareDocumentScope => "SOKF_FORMAT_70",
Unresolved::KeyForm(_) => "SOKF_FORMAT_72",
Unresolved::NoFragment | Unresolved::BareNotFound | Unresolved::BareAmbiguous => {
"SOKF_FORMAT_71"
}
}
}
fn canonical_to(ctx: &Ctx<'_>, citing: usize, target: &Target) -> Option<String> {
let Target::Document { id, knowledge, .. } = target else {
return None;
};
ctx.model.canonical_include(citing, *knowledge, id, None)
}
fn check_path(
target: &RepoPath,
link: &Link,
doc: DocView<'_>,
ctx: &Ctx<'_>,
findings: &mut Vec<Finding>,
) {
let what = if link.is_image {
"the image"
} else {
"the link"
};
let named = ctx
.knowledge
.and_then(|k| crate::include::path_link_label(ctx.model, ctx.keys, k, doc.path, link));
if let Some((label, _)) = named {
let kind = if ctx.model.asset_at(target).is_some() {
"the asset"
} else {
"the document"
};
findings.push(Finding::error(
doc.path.clone(),
Some(link.line),
"SOKF_FORMAT_60",
format!(
"{what} refers to {kind} `{target}` by path. Refer to it by id as `[text][{label}]`"
),
));
return;
}
if !ctx.model.exists(target) && !ctx.model.is_planned(target) {
findings.push(Finding::error(
doc.path.clone(),
Some(link.line),
"SOKF_FORMAT_76",
format!("{what} refers to a file that doesn't exist: {target}"),
));
}
}