Skip to main content

specfold_core/assets/
asset.rs

1//! One asset file as read: its kind, location, frontmatter and text.
2
3use crate::config::types::AssetKind;
4use crate::corpus::graph::{Graph, Resolution};
5use crate::model::markdown::frontmatter;
6use serde_json::{Map, Value};
7use std::collections::BTreeSet;
8
9#[derive(Debug, Clone)]
10pub struct Asset {
11    pub kind: AssetKind,
12    /// Repository-relative path of the file read (SKILL.md for a skill).
13    pub path: String,
14    /// The name the location gives: a skill's directory, otherwise the file stem.
15    pub stem: String,
16    /// Frontmatter; None when the file has none.
17    pub fields: Option<Map<String, Value>>,
18    /// Why the frontmatter could not be read.
19    pub invalid: Option<String>,
20    /// 1-based line where the body starts.
21    pub body_line: usize,
22    pub text: String,
23}
24
25impl Asset {
26    /// A frontmatter string field.
27    pub fn field(&self, key: &str) -> Option<&str> {
28        self.fields.as_ref()?.get(key)?.as_str()
29    }
30
31    /// The declared name, or the one the location gives.
32    pub fn name(&self) -> &str {
33        self.field("name").unwrap_or(&self.stem)
34    }
35
36    pub fn body(&self) -> &str {
37        frontmatter::split(&self.text).body
38    }
39
40    /// The documents this asset names, by index: a token that is a document id or path, written
41    /// from the repository root or relative to the asset. Aliases are left out so a common word
42    /// is never a link. Only read: nothing is added to the graph.
43    pub fn docs(&self, g: &Graph) -> Vec<usize> {
44        let dir = self.path.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
45        let mut out = BTreeSet::new();
46        let ok = |c: char| c.is_ascii_alphanumeric() || ":/._#-".contains(c);
47        for raw in self.text.split(|c: char| !ok(c)) {
48            let t = raw.trim_end_matches(['.', ':', '#']);
49            if !(t.contains(':') || t.contains('/') || t.ends_with(".md")) || t.contains("://") {
50                continue;
51            }
52            for cand in [t.to_string(), join(dir, t)] {
53                if let Resolution::Doc { idx, via_alias: false, .. } = g.resolve(&cand) {
54                    out.insert(idx);
55                    break;
56                }
57            }
58        }
59        out.into_iter().collect()
60    }
61}
62
63/// `dir/rel` with `.` and `..` folded; a path climbing above the root stays as written.
64pub(super) fn join(dir: &str, rel: &str) -> String {
65    let mut parts: Vec<&str> = if dir.is_empty() { vec![] } else { dir.split('/').collect() };
66    for c in rel.split('/') {
67        match c {
68            "" | "." => {}
69            ".." => {
70                if parts.pop().is_none() {
71                    return rel.to_string();
72                }
73            }
74            c => parts.push(c),
75        }
76    }
77    parts.join("/")
78}