Skip to main content

utils/
markdown_file.rs

1use futures::future::join_all;
2use serde::de::DeserializeOwned;
3use std::{
4    fs, io,
5    path::{Path, PathBuf},
6};
7
8/// Represents a parsed markdown file with optional frontmatter
9#[derive(Debug, Clone)]
10pub struct MarkdownFile<T: DeserializeOwned> {
11    /// Parsed frontmatter (if present)
12    pub frontmatter: Option<T>,
13    /// The content after frontmatter
14    pub content: String,
15}
16
17impl<T: DeserializeOwned + Send + 'static> MarkdownFile<T> {
18    pub fn parse(path: impl AsRef<Path>) -> Result<Self, ParseError> {
19        let raw_content = fs::read_to_string(path)?;
20
21        match split_frontmatter(&raw_content) {
22            Some((yaml_str, body)) => {
23                let frontmatter = serde_yml::from_str(yaml_str).ok();
24                Ok(Self { frontmatter, content: body.to_string() })
25            }
26            None => Ok(Self { frontmatter: None, content: raw_content.trim().to_string() }),
27        }
28    }
29
30    /// List all markdown files in a directory
31    pub fn list(dir: impl AsRef<Path>) -> Result<Vec<PathBuf>, io::Error> {
32        let paths: Vec<_> = fs::read_dir(dir)?
33            .filter_map(|entry| {
34                let path = entry.ok()?.path();
35                (path.extension().and_then(|s| s.to_str()) == Some("md")).then_some(path)
36            })
37            .collect();
38
39        Ok(paths)
40    }
41
42    /// Load a single markdown file from a path
43    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, ParseError> {
44        let path = path.as_ref();
45
46        if !path.exists() {
47            return Err(ParseError::Io(io::Error::new(
48                io::ErrorKind::NotFound,
49                format!("File not found: {}", path.display()),
50            )));
51        }
52
53        Self::parse(path)
54    }
55
56    /// Load all markdown files from a directory
57    pub async fn from_dir(dir: &PathBuf) -> Result<Vec<(PathBuf, Self)>, io::Error> {
58        if !dir.exists() {
59            return Err(io::Error::new(io::ErrorKind::NotFound, format!("Directory not found: {}", dir.display())));
60        }
61
62        if !dir.is_dir() {
63            return Err(io::Error::new(io::ErrorKind::NotADirectory, format!("Not a directory: {}", dir.display())));
64        }
65
66        let parse_tasks: Vec<_> = Self::list(dir)?
67            .into_iter()
68            .map(|path| {
69                tokio::spawn(async move {
70                    let path_clone = path.clone();
71                    Self::parse(path).map(|f| (path_clone, f))
72                })
73            })
74            .collect();
75
76        let results = join_all(parse_tasks).await;
77        let items = results
78            .into_iter()
79            .filter_map(|result| {
80                result.ok().and_then(|r| r.inspect_err(|e| tracing::warn!("Failed to parse file: {}", e)).ok())
81            })
82            .collect();
83
84        Ok(items)
85    }
86
87    /// Load all markdown files from nested subdirectories, where each subdirectory
88    /// contains a file with the specified filename.
89    ///
90    /// Flat files in the parent directory are ignored. Only subdirectories containing
91    /// the specified filename are processed.
92    ///
93    /// # Example
94    /// ```ignore
95    /// // Load from:
96    /// //   skills/skill-1/SKILL.md
97    /// //   skills/skill-2/SKILL.md
98    /// //   skills/flat-file.md      -> ignored (not in a subdirectory)
99    /// let skills = MarkdownFile::from_nested_dirs(Path::new("skills"), "SKILL.md").await?;
100    /// ```
101    pub async fn from_nested_dirs(
102        parent_dir: impl AsRef<Path>,
103        filename: &str,
104    ) -> Result<Vec<(PathBuf, Self)>, io::Error> {
105        let parent_dir = parent_dir.as_ref();
106
107        if !parent_dir.exists() {
108            return Err(io::Error::new(
109                io::ErrorKind::NotFound,
110                format!("Directory not found: {}", parent_dir.display()),
111            ));
112        }
113
114        if !parent_dir.is_dir() {
115            return Err(io::Error::new(
116                io::ErrorKind::NotADirectory,
117                format!("Not a directory: {}", parent_dir.display()),
118            ));
119        }
120
121        let subdirs = list_subdirs(parent_dir)?;
122        let filename = filename.to_string();
123        let parse_tasks: Vec<_> = subdirs
124            .into_iter()
125            .map(|dir| {
126                let filename = filename.clone();
127                tokio::spawn(async move {
128                    let file_path = dir.join(&filename);
129                    Self::parse(&file_path).map(|f| (dir, f))
130                })
131            })
132            .collect();
133
134        let results = join_all(parse_tasks).await;
135        let items = results
136            .into_iter()
137            .filter_map(|result| {
138                result.ok().and_then(|r| r.inspect_err(|e| tracing::debug!("Skipping directory: {}", e)).ok())
139            })
140            .collect();
141
142        Ok(items)
143    }
144}
145
146/// Split YAML frontmatter from markdown content.
147///
148/// Returns `(yaml_str, body)` if frontmatter delimiters (`---`) are found,
149/// or `None` if the content has no frontmatter.
150pub fn split_frontmatter(content: &str) -> Option<(&str, &str)> {
151    let content = content.trim();
152    let rest = content.strip_prefix("---")?;
153    let end_pos = rest.find("\n---")?;
154    Some((&rest[..end_pos], rest[end_pos + 4..].trim()))
155}
156
157/// List all subdirectories in a directory
158fn list_subdirs(dir: impl AsRef<Path>) -> Result<Vec<PathBuf>, io::Error> {
159    let paths: Vec<_> = fs::read_dir(dir)?
160        .filter_map(|entry| {
161            let path = entry.ok()?.path();
162            path.is_dir().then_some(path)
163        })
164        .collect();
165
166    Ok(paths)
167}
168
169#[derive(Debug, thiserror::Error)]
170pub enum ParseError {
171    #[error("Invalid filename")]
172    InvalidFilename,
173    #[error("IO error: {0}")]
174    Io(#[from] io::Error),
175}