1use serde::{Deserialize, Serialize};
5
6use super::{CoreFields, core_fields};
7use crate::{
8 Body, Finding, RepoPath, Segments, Source, Spanned,
9 markdown::{self, BlockKind},
10 source, yaml,
11};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15pub enum ParseMode {
16 Document,
18 Plain,
20}
21
22#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24pub struct Parsed {
25 pub frontmatter: Option<Spanned>,
27 pub core: CoreFields,
29 pub body: Body,
31 pub segments: Segments,
33 pub body_line: usize,
35 pub frontmatter_found: bool,
37}
38
39pub fn parse_source(source: &Source, mode: ParseMode) -> Parsed {
41 let (frontmatter, text, body_line) = match mode {
42 ParseMode::Document => {
43 let split = source::split(source);
44 (split.frontmatter, split.body, split.body_line)
45 }
46 ParseMode::Plain => (None, source.text.as_str(), 1),
47 };
48 let yaml = frontmatter.map(|(text, line)| yaml::parse(text, line));
49 let core = match mode {
51 ParseMode::Document => core_fields(yaml.as_ref().map(|r| r.as_ref()), &source.path),
52 ParseMode::Plain => CoreFields::default(),
53 };
54 let segments = markdown::segments(text, body_line);
55 let body = markdown::parse(text, body_line, &segments);
56 Parsed {
57 frontmatter: yaml.and_then(Result::ok),
58 core,
59 body,
60 segments,
61 body_line,
62 frontmatter_found: frontmatter.is_some(),
63 }
64}
65
66#[derive(Debug, Clone, PartialEq)]
69pub struct Document {
70 pub path: RepoPath,
72 pub source: Source,
74 pub frontmatter: Option<Spanned>,
76 pub core: CoreFields,
78 pub body: Body,
80 pub segments: Segments,
82 pub body_line: usize,
84 pub lines: usize,
86 pub frontmatter_found: bool,
88}
89#[derive(Serialize)]
96struct Visible<'a> {
97 id: Option<&'a str>,
98 type_: Option<&'a str>,
99 title: Option<&'a str>,
100 description: Option<&'a str>,
101 status: Option<super::Status>,
102 resource: Option<&'a super::Resource>,
103 headings: Vec<(u8, &'a str, &'a str)>,
104 anchors: Vec<&'a str>,
105 frontmatter_found: bool,
106}
107
108impl Document {
109 pub fn new(source: Source, parsed: Parsed) -> Self {
111 Document {
112 path: source.path.clone(),
113 lines: source.line_count(),
114 source,
115 frontmatter: parsed.frontmatter,
116 core: parsed.core,
117 body: parsed.body,
118 segments: parsed.segments,
119 body_line: parsed.body_line,
120 frontmatter_found: parsed.frontmatter_found,
121 }
122 }
123
124 pub fn visible_hash(&self) -> u64 {
130 let headings = crate::markdown::link_headings(&self.body);
131 let visible = Visible {
132 id: self.core.id.as_deref(),
133 type_: self.core.type_.as_deref(),
134 title: self.core.title.as_deref(),
135 description: self.core.description.as_deref(),
136 status: self.core.status,
137 resource: self.core.resource.as_ref(),
138 headings: headings
139 .iter()
140 .map(|h| (h.level, h.text.as_str(), h.slug.as_str()))
141 .collect(),
142 anchors: self.body.anchors.iter().map(|a| a.id.as_str()).collect(),
143 frontmatter_found: self.frontmatter_found,
144 };
145 source::fnv1a64(&serde_json::to_vec(&visible).unwrap_or_default())
146 }
147
148 pub fn line_count(&self) -> usize {
150 self.lines
151 }
152
153 pub fn body_text(&self) -> &str {
156 source::split(&self.source).body
157 }
158
159 pub fn id(&self) -> Option<&str> {
161 self.core.id.as_deref()
162 }
163
164 pub fn type_name(&self) -> Option<&str> {
166 self.core.type_.as_deref()
167 }
168}
169
170#[derive(Debug, Clone, PartialEq)]
176pub struct SchemaDocument {
177 pub doc: Document,
180 pub schema_yaml: Option<Spanned>,
182 pub schema_problem: Option<Finding>,
184 pub globs: Vec<String>,
186 pub asset_globs: Vec<String>,
188 pub type_const: Option<String>,
190 pub uses: Vec<String>,
194 pub archived: super::Archived,
197 pub loaded: bool,
200}
201
202impl SchemaDocument {
203 pub fn finding(&self, criterion: &'static str, message: impl Into<String>) -> Finding {
206 Finding::error(
207 self.doc.path.clone(),
208 Some(self.doc.body_line),
209 criterion,
210 message,
211 )
212 }
213
214 pub fn placeholder(path: RepoPath, meta: super::SchemaMeta) -> Self {
219 let source = Source::from_text(path, "");
220 let mut doc = Document::new(source.clone(), parse_source(&source, ParseMode::Document));
221 doc.core.id = meta.id;
222 doc.core.type_ = Some("Schema".to_string());
223 doc.body_line = meta.body_line;
224 SchemaDocument {
225 doc,
226 schema_yaml: None,
227 schema_problem: None,
228 globs: meta.globs,
229 asset_globs: meta.asset_globs,
230 type_const: meta.type_const,
231 uses: meta.uses,
232 archived: meta.archived,
233 loaded: false,
234 }
235 }
236
237 pub fn new(doc: Document) -> Self {
240 let mut schema_yaml = None;
241 let mut schema_problem = None;
242 let fence = doc.body.blocks.iter().find(|b| b.kind == BlockKind::Code);
243 match fence {
244 Some(block) => {
245 let text = block.units.first().map_or("", |u| u.text.as_str());
246 match yaml::parse(text, block.line + 1) {
247 Ok(y) => schema_yaml = Some(y),
248 Err(e) => {
249 schema_problem = Some(Finding::error(
250 doc.path.clone(),
251 Some(e.line()),
252 "SOKF_SCHEMA_2",
253 format!("schema: {e}"),
254 ));
255 }
256 }
257 }
258 None => {
259 schema_problem = Some(Finding::error(
260 doc.path.clone(),
261 Some(doc.body_line),
262 "SOKF_SCHEMA_1",
263 "the Schema document has no schema because it has no YAML fence",
264 ));
265 }
266 }
267 let list = |key: &str| {
268 schema_yaml
269 .as_ref()
270 .and_then(|c| c.get(key))
271 .and_then(Spanned::as_str_or_list)
272 .unwrap_or_default()
273 };
274 let (globs, asset_globs) = (list("additional-files"), list("asset-files"));
275 let type_const = schema_yaml
276 .as_ref()
277 .and_then(|c| c.get("frontmatter"))
278 .and_then(|f| f.get("type"))
279 .and_then(|t| t.get("const"))
280 .and_then(Spanned::scalar_text);
281 let uses = crate::grammar::schema_uses(&doc.source.text);
282 let archived = schema_yaml
283 .as_ref()
284 .map(super::Archived::of_schema)
285 .unwrap_or_default();
286 SchemaDocument {
287 doc,
288 schema_yaml,
289 schema_problem,
290 globs,
291 asset_globs,
292 type_const,
293 uses,
294 archived,
295 loaded: true,
296 }
297 }
298
299 pub fn id(&self) -> String {
302 self.doc.id().map_or_else(
303 || {
304 self.doc
305 .path
306 .file_name()
307 .trim_end_matches(".md")
308 .to_string()
309 },
310 str::to_string,
311 )
312 }
313}
314
315#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
318pub struct SchemaRef {
319 pub knowledge: usize,
321 pub index: usize,
323}
324
325#[derive(Debug, Clone, PartialEq)]
328pub struct AdditionalFile {
329 pub path: RepoPath,
331 pub source: Source,
333 pub body: Body,
335 pub segments: Segments,
337 pub schema: Option<SchemaRef>,
339}
340
341#[derive(Debug, Clone, PartialEq, Eq)]
344pub struct Asset {
345 pub path: RepoPath,
347 pub schema: SchemaRef,
349 pub sidecar: Option<usize>,
352 pub has_sidecar: bool,
355}
356
357impl Asset {
358 pub fn sidecar_path(&self) -> RepoPath {
361 sidecar_path(&self.path)
362 }
363}
364
365pub fn sidecar_path(path: &RepoPath) -> RepoPath {
368 RepoPath::parse(&format!("{path}.md")).expect("a path plus `.md` is a path")
369}
370
371#[derive(Debug, Clone, PartialEq)]
375pub struct IndexFile {
376 pub path: RepoPath,
378 pub source: Source,
380}
381
382#[cfg(test)]
383mod tests {
384 use super::*;
385
386 fn src(text: &str) -> Source {
387 Source::from_text(RepoPath::parse("/k/schemas/s.md").unwrap(), text)
388 }
389
390 #[test]
391 fn parses_documents_and_plain_files() {
392 let s = src("---\ntype: A\nid: a\n---\n\n# T\n\n<!-- sokf:links -->\n");
393 let p = parse_source(&s, ParseMode::Document);
394 assert_eq!(p.core.type_.as_deref(), Some("A"));
395 assert_eq!(p.body.headings[0].line, 6);
396 assert_eq!(p.body_line, 5);
397 assert!(p.segments.definition.is_some());
398 let d = Document::new(s.clone(), p);
399 assert_eq!(d.line_count(), 8);
400 assert_eq!(d.body_text(), "\n# T\n\n<!-- sokf:links -->\n");
401 assert_eq!(d.id(), Some("a"));
402 assert_eq!(d.type_name(), Some("A"));
403 let plain = parse_source(&src("---\nnot: fm\n---\n# H\n"), ParseMode::Plain);
404 assert!(plain.frontmatter.is_none());
405 assert_eq!(
406 plain
407 .body
408 .headings
409 .iter()
410 .find(|h| h.text == "H")
411 .unwrap()
412 .line,
413 4
414 );
415 assert!(!plain.core.present);
416 let json = serde_json::to_string(&plain).unwrap();
417 let back: Parsed = serde_json::from_str(&json).unwrap();
418 assert_eq!(back, plain);
419 }
420
421 #[test]
423 fn a_line_shift_is_not_visible_and_a_title_is() {
424 let text = "---\ntype: A\nid: a\ntitle: T\n---\n\n# T\n\nSee [b][sokf:b].\n";
425 let doc = |t: &str| {
426 let s = Source::from_text(RepoPath::parse("/k/a.md").unwrap(), t);
427 Document::new(s.clone(), parse_source(&s, ParseMode::Document))
428 };
429 let full = doc(text);
430 let shifted = doc(&text.replacen("# T\n", "\n\n# T\n", 1));
431 assert_ne!(shifted.body.headings[0].line, full.body.headings[0].line);
432 assert_eq!(shifted.visible_hash(), full.visible_hash());
433 let renamed = doc(&text.replacen("title: T", "title: U", 1));
434 assert_ne!(renamed.visible_hash(), full.visible_hash());
435 let reheaded = doc(&text.replacen("# T\n", "# U\n", 1));
436 assert_ne!(reheaded.visible_hash(), full.visible_hash());
437 }
438
439 #[test]
440 fn schemas_extract_their_schema() {
441 let s = src(
442 "---\ntype: Schema\nid: schema-x\n---\n\n````yaml\nadditional-files: [/README.md]\nasset-files: '/k/media/**/*.png'\nfrontmatter:\n type:\n const: X\n````\n",
443 );
444 let schema = SchemaDocument::new(Document::new(
445 s.clone(),
446 parse_source(&s, ParseMode::Document),
447 ));
448 assert_eq!(schema.globs, vec!["/README.md"]);
449 assert_eq!(schema.asset_globs, vec!["/k/media/**/*.png"]);
450 assert_eq!(schema.type_const.as_deref(), Some("X"));
451 assert_eq!(
452 sidecar_path(&RepoPath::parse("/k/media/a.png").unwrap()).as_str(),
453 "/k/media/a.png.md"
454 );
455 assert_eq!(
456 schema
457 .schema_yaml
458 .as_ref()
459 .unwrap()
460 .get("additional-files")
461 .unwrap()
462 .line,
463 7
464 );
465 assert_eq!(schema.id(), "schema-x");
466 assert!(schema.schema_problem.is_none());
467 let none = src("---\ntype: Schema\n---\n\nno fence\n");
468 let schema = SchemaDocument::new(Document::new(
469 none.clone(),
470 parse_source(&none, ParseMode::Document),
471 ));
472 assert!(schema.schema_yaml.is_none());
473 assert!(
474 schema
475 .schema_problem
476 .as_ref()
477 .unwrap()
478 .message
479 .contains("no YAML fence")
480 );
481 assert_eq!(schema.id(), "s");
482 let bad = src("---\ntype: Schema\n---\n\n````yaml\na: &x 1\n````\n");
483 let schema = SchemaDocument::new(Document::new(
484 bad.clone(),
485 parse_source(&bad, ParseMode::Document),
486 ));
487 let problem = schema.schema_problem.unwrap();
488 assert_eq!(problem.line, Some(6));
489 assert!(problem.message.contains("anchor"));
490 }
491}