obsidian_parser/note/
note_once_lock.rs1use 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#[derive(Debug, Default, PartialEq, Eq, Clone)]
23pub struct NoteOnceLock<T = DefaultProperties>
24where
25 T: Clone + DeserializeOwned,
26{
27 path: PathBuf,
29
30 content: OnceLock<String>,
32
33 properties: OnceLock<Option<T>>,
35}
36
37#[derive(Debug, Error)]
39pub enum Error {
40 #[error("IO error: {0}")]
42 IO(#[from] std::io::Error),
43
44 #[error("Invalid frontmatter format")]
58 InvalidFormat(#[from] parser::Error),
59
60 #[error("YAML parsing error: {0}")]
70 Yaml(#[from] serde_yml::Error),
71
72 #[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 #[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()); Ok(result.map(|value| Cow::Owned(value)))
129 }
130
131 #[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()); Ok(Cow::Owned(result))
173 }
174
175 #[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 #[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 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}