Skip to main content

rightkit_document_workspace/
markdown_index.rs

1//! Markdown folder index: the Markdown files beside a document, with titles, for a link picker
2//! or completion provider. Hard caps: 1 000 files, 20 MiB total, 2 MiB per file, depth 8.
3
4use crate::WorkspaceError;
5use serde::Serialize;
6use std::path::Path;
7use walkdir::WalkDir;
8
9pub const MAX_FILES: usize = 1_000;
10pub const MAX_TOTAL_BYTES: u64 = 20 * 1024 * 1024;
11pub const MAX_PER_FILE_BYTES: u64 = 2 * 1024 * 1024;
12pub const MAX_DEPTH: usize = 8;
13
14#[derive(Debug, Serialize)]
15#[serde(rename_all = "camelCase")]
16pub struct IndexedMarkdownFile {
17    pub absolute_path: String,
18    pub relative_path: String,
19    pub byte_length: u64,
20    pub title: Option<String>,
21}
22
23#[derive(Debug, Serialize)]
24#[serde(rename_all = "camelCase")]
25pub struct IndexedMarkdownFolderResult {
26    pub files: Vec<IndexedMarkdownFile>,
27    pub truncated: bool,
28}
29
30/// Walk the document's parent directory and return metadata for every
31/// Markdown file under it (subject to the documented caps).
32///
33/// The directory walk (walkdir + per-file `metadata` + `read_to_string` title extraction) runs on a
34/// Index the Markdown files beside `document` (an already authorized, existing file): its parent
35/// folder, recursively to depth 8 when `recursive`, skipping hidden and build-output folders.
36/// Refused over 1 000 files, 20 MiB in total or 2 MiB for one file. Folder enumeration must be
37/// an explicit user choice; the caller checks consent and path grants before calling.
38pub fn index_markdown_folder(
39    document: &Path,
40    recursive: bool,
41) -> Result<IndexedMarkdownFolderResult, WorkspaceError> {
42    let doc_path = document.to_path_buf();
43    let parent = doc_path
44        .parent()
45        .ok_or_else(|| WorkspaceError::Other("no-document-parent".to_string()))?
46        .to_path_buf();
47    let parent = std::fs::canonicalize(parent)
48        .map_err(|error| WorkspaceError::Io(format!("canonicalize markdown folder: {error}")))?;
49
50    let mut files = Vec::new();
51    let mut total: u64 = 0;
52    let walker = WalkDir::new(&parent)
53        .max_depth(if recursive { MAX_DEPTH } else { 1 })
54        .follow_links(false)
55        .into_iter()
56        .filter_entry(|e| !is_skipped_dir(e.path()));
57
58    for entry in walker {
59        let entry =
60            entry.map_err(|error| WorkspaceError::Io(format!("walk markdown folder: {error}")))?;
61        if !entry.file_type().is_file() {
62            continue;
63        }
64        let path = entry.path();
65        if !is_markdown_file(path) {
66            continue;
67        }
68        let metadata = std::fs::metadata(path)
69            .map_err(|error| WorkspaceError::Io(format!("inspect markdown file: {error}")))?;
70        let len = metadata.len();
71        if len > MAX_PER_FILE_BYTES {
72            return Err(WorkspaceError::DocumentTooLarge(format!(
73                "markdown index file exceeds {MAX_PER_FILE_BYTES} bytes"
74            )));
75        }
76        if total + len > MAX_TOTAL_BYTES {
77            return Err(WorkspaceError::DocumentTooLarge(format!(
78                "markdown index exceeds {MAX_TOTAL_BYTES} total bytes"
79            )));
80        }
81        if files.len() >= MAX_FILES {
82            return Err(WorkspaceError::DocumentTooLarge(format!(
83                "markdown index exceeds {MAX_FILES} files"
84            )));
85        }
86        total += len;
87        files.push(IndexedMarkdownFile {
88            absolute_path: path.to_string_lossy().to_string(),
89            relative_path: relative_to(&parent, path),
90            byte_length: len,
91            title: extract_title(path),
92        });
93    }
94
95    Ok(IndexedMarkdownFolderResult {
96        files,
97        truncated: false,
98    })
99}
100
101fn is_skipped_dir(path: &Path) -> bool {
102    if !path.is_dir() {
103        return false;
104    }
105    let name = match path.file_name().and_then(|n| n.to_str()) {
106        Some(n) => n,
107        None => return false,
108    };
109    name.starts_with('.')
110        || matches!(
111            name,
112            "node_modules"
113                | "dist"
114                | "build"
115                | "target"
116                | ".next"
117                | ".cache"
118                | ".turbo"
119                | ".parcel-cache"
120                | ".DS_Store"
121        )
122}
123
124fn is_markdown_file(path: &Path) -> bool {
125    let ext = path
126        .extension()
127        .and_then(|e| e.to_str())
128        .map(|e| e.to_ascii_lowercase());
129    matches!(ext.as_deref(), Some("md") | Some("markdown") | Some("mdx"))
130}
131
132fn relative_to(base: &Path, target: &Path) -> String {
133    target
134        .strip_prefix(base)
135        .map(|p| p.to_string_lossy().replace('\\', "/"))
136        .unwrap_or_else(|_| target.to_string_lossy().replace('\\', "/"))
137}
138
139/// Extract the first H1 (or H2 fallback) from the file as a
140/// best-effort title. Returns `None` when the file cannot be read.
141fn extract_title(path: &Path) -> Option<String> {
142    let text = std::fs::read_to_string(path).ok()?;
143    for line in text.lines() {
144        let trimmed = line.trim_start_matches('\u{feff}');
145        if let Some(rest) = trimmed.strip_prefix("# ") {
146            return Some(rest.trim().to_string());
147        }
148    }
149    None
150}