1use std::fs;
12use std::path::{Path, PathBuf};
13
14use crate::frontmatter::{
15 Value, body_of, citation_labels, claimed_result, code_blocks, parse_frontmatter,
16};
17use crate::time::parse_timestamp;
18
19#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct SourceRef {
22 pub id: Option<String>,
24 pub resource: Option<String>,
26 pub sha256: Option<String>,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct Parameter {
34 pub name: String,
36 pub param_type: Option<String>,
39 pub value: Option<String>,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct VerifiedEvent {
47 pub by: Option<String>,
49 pub at_text: Option<String>,
51 pub at: Option<i64>,
53}
54
55impl VerifiedEvent {
56 pub fn is_well_formed(&self) -> bool {
58 self.by.is_some() && self.at.is_some()
59 }
60
61 pub fn malformed_reason(&self) -> Option<String> {
63 if self.by.is_none() {
64 return Some("verification event has no by actor".to_string());
65 }
66 match (&self.at_text, &self.at) {
67 (None, _) => Some("verification event has no at timestamp".to_string()),
68 (Some(text), None) => Some(format!("verification timestamp {text} does not parse")),
69 _ => None,
70 }
71 }
72
73 pub fn is_human(&self) -> bool {
76 self.by
77 .as_deref()
78 .is_some_and(|by| by.starts_with("human:"))
79 }
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct Concept {
85 pub id: String,
87 pub concept_type: String,
89 pub status: String,
91 pub superseded_by: Option<String>,
93 pub generated_at: Option<i64>,
95 pub generated_text: Option<String>,
97 pub stale_after_text: Option<String>,
99 pub stale_after: Option<i64>,
101 pub verified: Vec<VerifiedEvent>,
103 pub sources: Vec<SourceRef>,
105 pub citations: Vec<String>,
107 pub runtime: Option<String>,
109 pub parameters: Vec<Parameter>,
111 pub code_blocks: Vec<(String, String)>,
113 pub file_code: Option<String>,
116 pub claimed_result: Option<String>,
118}
119
120#[derive(Debug, Clone, Default, PartialEq, Eq)]
122pub struct Bundle {
123 pub concepts: Vec<Concept>,
125 pub okf_version: Option<String>,
127 pub files: Option<std::collections::BTreeSet<String>>,
131 pub source_bytes: std::collections::BTreeMap<String, Vec<u8>>,
134 pub source_modified: std::collections::BTreeMap<String, i64>,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
143pub(crate) enum ResourceTarget {
144 ExternalUri,
146 InBundle(String),
148 InvalidOrEscapes,
150}
151
152pub(crate) fn has_uri_scheme(raw: &str) -> bool {
156 let Some(colon) = raw.find(':') else {
157 return false;
158 };
159 let scheme = &raw[..colon];
160 if scheme.len() < 2 || scheme.contains(['/', '\\']) {
161 return false;
162 }
163 let mut chars = scheme.chars();
164 chars.next().is_some_and(|c| c.is_ascii_alphabetic())
165 && chars.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
166}
167
168pub(crate) fn classify_resource_path(from_concept: &str, raw: &str) -> ResourceTarget {
170 let raw = raw.trim();
171 if raw.is_empty() {
172 return ResourceTarget::InvalidOrEscapes;
173 }
174 if has_uri_scheme(raw) {
175 return ResourceTarget::ExternalUri;
176 }
177 if raw.len() >= 2 && raw.as_bytes()[0].is_ascii_alphabetic() && raw.as_bytes()[1] == b':' {
179 return ResourceTarget::InvalidOrEscapes;
180 }
181 let normalized = raw.replace('\\', "/");
182 let stripped = normalized.strip_prefix('/').unwrap_or(&normalized);
183 let combined = if normalized.starts_with('/') {
184 stripped.to_string()
185 } else {
186 let parent = from_concept.rsplit_once('/').map(|(p, _)| p).unwrap_or("");
187 if parent.is_empty() {
188 stripped.to_string()
189 } else {
190 format!("{parent}/{stripped}")
191 }
192 };
193 let mut parts: Vec<&str> = Vec::new();
194 for segment in combined.split('/') {
195 match segment {
196 "" | "." => {}
197 ".." => {
198 if parts.pop().is_none() {
199 return ResourceTarget::InvalidOrEscapes;
200 }
201 }
202 other => parts.push(other),
203 }
204 }
205 if parts.is_empty() {
206 ResourceTarget::InvalidOrEscapes
207 } else {
208 ResourceTarget::InBundle(parts.join("/"))
209 }
210}
211
212pub(crate) fn resolve_file_path(from_concept: &str, raw: &str) -> Option<String> {
215 match classify_resource_path(from_concept, raw) {
216 ResourceTarget::InBundle(path) => Some(path),
217 ResourceTarget::ExternalUri | ResourceTarget::InvalidOrEscapes => None,
218 }
219}
220
221impl Bundle {
222 pub fn uses_v02_fallback(&self) -> bool {
227 match &self.okf_version {
228 None => true,
229 Some(version) => {
230 let mut parts = version.split('.');
231 let (Some(Ok(major)), Some(Ok(minor))) = (
232 parts.next().map(|p| p.parse::<u32>()),
233 parts.next().map(|p| p.parse::<u32>()),
234 ) else {
235 return false;
236 };
237 (major, minor) <= (0, 2)
238 }
239 }
240 }
241
242 pub fn load(root: &Path) -> std::io::Result<Bundle> {
244 let okf_version = read_okf_version(root);
245 let mut inventory = Vec::new();
246 collect_files(root, &mut inventory)?;
247 inventory.sort();
248 let files: std::collections::BTreeSet<String> = inventory
249 .iter()
250 .map(|path| {
251 path.strip_prefix(root)
252 .unwrap_or(path)
253 .to_string_lossy()
254 .replace('\\', "/")
255 })
256 .collect();
257 let mut markdown: Vec<&PathBuf> = inventory
258 .iter()
259 .filter(|path| {
260 let name = path
261 .file_name()
262 .map(|n| n.to_string_lossy().to_string())
263 .unwrap_or_default();
264 name.ends_with(".md") && name != "index.md" && name != "log.md"
265 })
266 .collect();
267 markdown.sort();
268 let mut concepts = Vec::new();
269 for path in markdown {
270 let text = fs::read_to_string(path)?;
271 let Some(fm) = parse_frontmatter(&text) else {
272 continue;
273 };
274 if fm.get("type").and_then(Value::as_str).is_none() {
275 continue;
276 }
277 let rel = path.strip_prefix(root).unwrap_or(path);
278 let id = to_posix_id(rel);
279 concepts.push(concept_from_frontmatter(id, &fm, &text, root, &files));
280 }
281 concepts.sort_by(|a, b| a.id.cmp(&b.id));
282 let mut source_bytes = std::collections::BTreeMap::new();
283 for concept in &concepts {
284 for source in &concept.sources {
285 let Some(resource) = &source.resource else {
286 continue;
287 };
288 let Some(path) = resolve_file_path(&concept.id, resource) else {
289 continue;
290 };
291 if !files.contains(&path) {
292 continue;
293 }
294 if source.sha256.is_some() && !source_bytes.contains_key(&path) {
295 let disk_path = root.join(path_from_posix(&path));
296 source_bytes.insert(path, fs::read(disk_path)?);
297 }
298 }
299 }
300 Ok(Bundle {
301 concepts,
302 okf_version,
303 files: Some(files),
304 source_bytes,
305 source_modified: std::collections::BTreeMap::new(),
306 })
307 }
308
309 pub fn from_concepts(mut concepts: Vec<Concept>) -> Bundle {
311 concepts.sort_by(|a, b| a.id.cmp(&b.id));
312 Bundle {
313 concepts,
314 okf_version: None,
315 files: None,
316 source_bytes: std::collections::BTreeMap::new(),
317 source_modified: std::collections::BTreeMap::new(),
318 }
319 }
320
321 pub fn concept(&self, id: &str) -> Option<&Concept> {
323 self.concepts.iter().find(|c| c.id == id)
324 }
325}
326
327fn path_from_posix(posix: &str) -> PathBuf {
328 let mut pb = PathBuf::new();
329 for seg in posix.split('/') {
330 if !seg.is_empty() {
331 pb.push(seg);
332 }
333 }
334 pb
335}
336
337fn collect_files(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
338 let entries = fs::read_dir(dir)?;
339 for entry in entries {
340 let entry = entry?;
341 let name = entry.file_name().to_string_lossy().to_string();
342 if name.starts_with('.') {
343 continue;
344 }
345 let ft = entry.file_type()?;
346 if ft.is_symlink() {
347 continue;
348 }
349 let path = entry.path();
350 if ft.is_dir() {
351 collect_files(&path, out)?;
352 } else if ft.is_file() {
353 out.push(path);
354 }
355 }
356 Ok(())
357}
358
359fn read_okf_version(root: &Path) -> Option<String> {
362 let index_path = root.join("index.md");
363 let meta = fs::symlink_metadata(&index_path).ok()?;
364 if meta.file_type().is_symlink() || !meta.is_file() {
365 return None;
366 }
367 let text = fs::read_to_string(index_path).ok()?;
368 let fm = parse_frontmatter(&text)?;
369 fm.get("okf_version")
370 .and_then(Value::as_str)
371 .map(str::to_string)
372}
373
374fn to_posix_id(rel: &Path) -> String {
375 let text = rel.to_string_lossy().replace('\\', "/");
376 text.strip_suffix(".md").unwrap_or(&text).to_string()
377}
378
379fn linked_python_file(
381 id: &str,
382 body: &str,
383 root: &Path,
384 files: &std::collections::BTreeSet<String>,
385) -> Option<String> {
386 let mut rest = body;
387 while let Some(start) = rest.find("](") {
388 let after = &rest[start + 2..];
389 let Some(end) = after.find(')') else {
390 break;
391 };
392 let target = after[..end].trim();
393 if target.ends_with(".py")
394 && let Some(path) = resolve_file_path(id, target)
395 && files.contains(&path)
396 {
397 return fs::read_to_string(root.join(path_from_posix(&path))).ok();
398 }
399 rest = &after[end + 1..];
400 }
401 None
402}
403
404fn concept_from_frontmatter(
405 id: String,
406 fm: &Value,
407 text: &str,
408 root: &Path,
409 files: &std::collections::BTreeSet<String>,
410) -> Concept {
411 let status = fm
412 .get("status")
413 .and_then(Value::as_str)
414 .unwrap_or("stable")
415 .to_string();
416 let superseded_by = fm
417 .get("superseded_by")
418 .and_then(Value::as_str)
419 .map(str::to_string);
420 let generated_text = fm
421 .get("generated")
422 .and_then(|g| g.get("at"))
423 .and_then(Value::as_str)
424 .map(str::to_string);
425 let generated_at = generated_text.as_deref().and_then(parse_timestamp);
426 let stale_after_text = fm
427 .get("stale_after")
428 .and_then(Value::as_str)
429 .map(str::to_string);
430 let stale_after = stale_after_text.as_deref().and_then(parse_timestamp);
431 let mut verified = Vec::new();
432 if let Some(value) = fm.get("verified") {
433 for item in value.as_items() {
434 let by = item.get("by").and_then(Value::as_str).map(str::to_string);
435 let at_text = item.get("at").and_then(Value::as_str).map(str::to_string);
436 let at = at_text.as_deref().and_then(parse_timestamp);
437 verified.push(VerifiedEvent { by, at_text, at });
438 }
439 }
440 let mut sources = Vec::new();
441 if let Some(value) = fm.get("sources") {
442 for item in value.as_items() {
443 sources.push(SourceRef {
444 id: item.get("id").and_then(Value::as_str).map(str::to_string),
445 resource: item
446 .get("resource")
447 .and_then(Value::as_str)
448 .map(str::to_string),
449 sha256: item
450 .get("sha256")
451 .and_then(Value::as_str)
452 .map(str::to_string),
453 });
454 }
455 }
456 let mut parameters = Vec::new();
457 if let Some(value) = fm.get("parameters") {
458 for item in value.as_items() {
459 if let Some(name) = item.get("name").and_then(Value::as_str) {
460 parameters.push(Parameter {
461 name: name.to_string(),
462 param_type: item.get("type").and_then(Value::as_str).map(str::to_string),
463 value: item
464 .get("value")
465 .and_then(Value::as_str)
466 .map(str::to_string),
467 });
468 }
469 }
470 }
471 let body = body_of(text);
472 let citations = citation_labels(body);
473 let runtime = fm
474 .get("runtime")
475 .and_then(Value::as_str)
476 .map(str::to_string);
477 let blocks = code_blocks(body);
478 let file_code = linked_python_file(&id, body, root, files);
479 let claimed = claimed_result(body);
480 let concept_type = fm
481 .get("type")
482 .and_then(Value::as_str)
483 .unwrap_or("")
484 .to_string();
485 Concept {
486 id,
487 concept_type,
488 status,
489 superseded_by,
490 generated_at,
491 generated_text,
492 stale_after_text,
493 stale_after,
494 verified,
495 sources,
496 citations,
497 runtime,
498 parameters,
499 code_blocks: blocks,
500 file_code,
501 claimed_result: claimed,
502 }
503}