Skip to main content

obsidian_parser/note/
note_once_lock.rs

1//! On-disk representation of an Obsidian note file with cache
2//!
3//! # Other
4//! If we not use thread-safe, use [`NoteOnceCell`]
5//!
6//! [`NoteOnceCell`]: crate::note::note_once_cell::NoteOnceCell
7
8use crate::note::parser::{self, ResultParse, parse_note};
9use crate::note::{DefaultProperties, Note};
10use serde::de::DeserializeOwned;
11use std::borrow::Cow;
12use std::path::{Path, PathBuf};
13use std::sync::OnceLock;
14use thiserror::Error;
15
16/// On-disk representation of an Obsidian note file with cache
17///
18/// # Other
19/// If we not use thread-safe, use [`NoteOnceCell`]
20///
21/// [`NoteOnceCell`]: crate::note::note_once_cell::NoteOnceCell
22#[derive(Debug, Default, PartialEq, Eq, Clone)]
23pub struct NoteOnceLock<T = DefaultProperties>
24where
25    T: Clone + DeserializeOwned,
26{
27    /// Absolute path to the source Markdown file
28    path: PathBuf,
29
30    /// Markdown content body (without frontmatter)
31    content: OnceLock<String>,
32
33    /// Parsed frontmatter properties
34    properties: OnceLock<Option<T>>,
35}
36
37/// Errors for [`NoteOnceLock`]
38#[derive(Debug, Error)]
39pub enum Error {
40    /// I/O operation failed (file reading, directory traversal, etc.)
41    #[error("IO error: {0}")]
42    IO(#[from] std::io::Error),
43
44    /// Invalid frontmatter format detected
45    ///
46    /// Occurs when:
47    /// - Frontmatter delimiters are incomplete (`---` missing)
48    /// - Content between delimiters is empty
49    ///
50    /// # Example
51    /// Parsing a file with malformed frontmatter:
52    /// ```text
53    /// ---
54    /// incomplete yaml
55    /// // Missing closing ---
56    /// ```
57    #[error("Invalid frontmatter format")]
58    InvalidFormat(#[from] parser::Error),
59
60    /// YAML parsing error in frontmatter properties
61    ///
62    /// # Example
63    /// Parsing invalid YAML syntax:
64    /// ```text
65    /// ---
66    /// key: @invalid_value
67    /// ---
68    /// ```
69    #[error("YAML parsing error: {0}")]
70    Yaml(#[from] serde_yml::Error),
71
72    /// Expected a file path
73    ///
74    /// # Example
75    /// ```no_run
76    /// use obsidian_parser::prelude::*;
77    ///
78    /// // Will fail if passed a directory path
79    /// NoteOnDisk::from_file_default("/home/test");
80    /// ```
81    #[error("Path: `{0}` is not a directory")]
82    IsNotFile(PathBuf),
83}
84
85impl<T> Note for NoteOnceLock<T>
86where
87    T: DeserializeOwned + Clone,
88{
89    type Properties = T;
90    type Error = self::Error;
91
92    /// Parses YAML frontmatter directly from disk
93    ///
94    /// # Errors
95    /// - [`Error::Yaml`] if properties can't be deserialized
96    /// - [`Error::IsNotFile`] If file doesn't exist
97    /// - [`Error::IO`] on filesystem error
98    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self), fields(path = %self.path.display())))]
99    fn properties(&self) -> Result<Option<Cow<'_, T>>, Error> {
100        #[cfg(feature = "tracing")]
101        tracing::trace!("Get properties from file");
102
103        if let Some(properties) = self.properties.get() {
104            return Ok(properties.as_ref().map(|value| Cow::Borrowed(value)));
105        }
106
107        let raw_text = std::fs::read_to_string(&self.path)?;
108
109        let result = match parse_note(&raw_text)? {
110            ResultParse::WithProperties {
111                content: _,
112                properties,
113            } => {
114                #[cfg(feature = "tracing")]
115                tracing::trace!("Frontmatter detected, parsing properties");
116
117                Some(serde_yml::from_str(properties)?)
118            }
119            ResultParse::WithoutProperties => {
120                #[cfg(feature = "tracing")]
121                tracing::trace!("No frontmatter found, storing raw content");
122
123                None
124            }
125        };
126
127        let _ = self.properties.set(result.clone()); // already check
128        Ok(result.map(|value| Cow::Owned(value)))
129    }
130
131    /// Returns the note's content body (without frontmatter)
132    ///
133    /// # Errors
134    /// - [`Error::IO`] on filesystem error
135    ///
136    /// # Performance
137    /// Performs disk read on every call. Suitable for:
138    /// - Single-pass processing (link extraction, analysis)
139    /// - Large files where in-memory storage is prohibitive
140    ///
141    /// For repeated access, consider caching or [`NoteInMemory`](crate::note::note_in_memory::NoteInMemory).
142    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self), fields(path = %self.path.display())))]
143    fn content(&self) -> Result<Cow<'_, str>, Error> {
144        #[cfg(feature = "tracing")]
145        tracing::trace!("Get content from file");
146
147        if let Some(content) = self.content.get() {
148            return Ok(Cow::Borrowed(content));
149        }
150
151        let raw_text = std::fs::read_to_string(&self.path)?;
152
153        let result = match parse_note(&raw_text)? {
154            ResultParse::WithProperties {
155                content,
156                properties: _,
157            } => {
158                #[cfg(feature = "tracing")]
159                tracing::trace!("Frontmatter detected, parsing properties");
160
161                content.to_string()
162            }
163            ResultParse::WithoutProperties => {
164                #[cfg(feature = "tracing")]
165                tracing::trace!("No frontmatter found, storing raw content");
166
167                raw_text
168            }
169        };
170
171        let _ = self.content.set(result.clone()); // already check
172        Ok(Cow::Owned(result))
173    }
174
175    /// Get path to note
176    #[inline]
177    fn path(&self) -> Option<Cow<'_, Path>> {
178        Some(Cow::Borrowed(&self.path))
179    }
180}
181
182impl<T> NoteOnceLock<T>
183where
184    T: DeserializeOwned + Clone,
185{
186    /// Set path to note
187    #[inline]
188    pub fn set_path(&mut self, path: PathBuf) {
189        self.path = path;
190    }
191}
192
193#[cfg(not(target_family = "wasm"))]
194impl<T> crate::prelude::NoteFromFile for NoteOnceLock<T>
195where
196    T: DeserializeOwned + Clone,
197{
198    /// Creates instance from file
199    fn from_file(path: impl AsRef<Path>) -> Result<Self, Error> {
200        let path = path.as_ref().to_path_buf();
201
202        if !path.is_file() {
203            return Err(Error::IsNotFile(path));
204        }
205
206        Ok(Self {
207            path,
208            content: OnceLock::default(),
209            properties: OnceLock::default(),
210        })
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use crate::note::NoteDefault;
218    use crate::note::impl_tests::impl_test_for_note;
219    use crate::note::note_aliases::tests::{from_file_have_aliases, from_file_have_not_aliases};
220    use crate::note::note_is_todo::tests::{from_file_is_not_todo, from_file_is_todo};
221    use crate::note::note_read::tests::{from_file, from_file_with_unicode};
222    use crate::note::note_tags::tests::from_file_tags;
223    use crate::note::note_write::tests::impl_all_tests_flush;
224    use std::io::Write;
225    use tempfile::NamedTempFile;
226
227    impl_all_tests_flush!(NoteOnceLock);
228    impl_test_for_note!(impl_from_file, from_file, NoteOnceLock);
229    impl_test_for_note!(impl_from_file_tags, from_file_tags, NoteOnceLock);
230
231    impl_test_for_note!(
232        impl_from_file_with_unicode,
233        from_file_with_unicode,
234        NoteOnceLock
235    );
236
237    impl_test_for_note!(impl_from_file_is_todo, from_file_is_todo, NoteOnceLock);
238    impl_test_for_note!(
239        impl_from_file_is_not_todo,
240        from_file_is_not_todo,
241        NoteOnceLock
242    );
243
244    impl_test_for_note!(
245        impl_from_file_have_aliases,
246        from_file_have_aliases,
247        NoteOnceLock
248    );
249    impl_test_for_note!(
250        impl_from_file_have_not_aliases,
251        from_file_have_not_aliases,
252        NoteOnceLock
253    );
254
255    #[cfg_attr(feature = "tracing", tracing_test::traced_test)]
256    #[test]
257    #[should_panic]
258    fn use_from_file_with_path_not_file() {
259        let temp_dir = tempfile::tempdir().unwrap();
260
261        NoteOnceLock::from_file_default(temp_dir.path()).unwrap();
262    }
263
264    #[cfg_attr(feature = "tracing", tracing_test::traced_test)]
265    #[test]
266    fn get_path() {
267        let test_file = NamedTempFile::new().unwrap();
268        let file = NoteOnceLock::from_file_default(test_file.path()).unwrap();
269
270        assert_eq!(file.path().unwrap(), test_file.path());
271        assert_eq!(file.path, test_file.path());
272    }
273
274    #[cfg_attr(feature = "tracing", tracing_test::traced_test)]
275    #[test]
276    fn get_content() {
277        let test_data = "DATA";
278        let mut test_file = NamedTempFile::new().unwrap();
279        test_file.write_all(test_data.as_bytes()).unwrap();
280
281        let file = NoteOnceLock::from_file_default(test_file.path()).unwrap();
282        assert_eq!(file.content().unwrap(), test_data);
283    }
284
285    #[cfg_attr(feature = "tracing", tracing_test::traced_test)]
286    #[test]
287    fn get_properties() {
288        let test_data = "---\ntime: now\n---\nDATA";
289        let mut test_file = NamedTempFile::new().unwrap();
290        test_file.write_all(test_data.as_bytes()).unwrap();
291
292        let file = NoteOnceLock::from_file_default(test_file.path()).unwrap();
293        let properties = file.properties().unwrap().unwrap();
294
295        assert_eq!(file.content().unwrap(), "DATA");
296        assert_eq!(properties["time"], "now");
297    }
298}