basalt_core/obsidian/note.rs
1use std::{fs, path::PathBuf, time::SystemTime};
2
3use crate::obsidian::{Error, Result};
4
5/// Represents a single note (Markdown file) within a vault.
6#[derive(Debug, Clone, PartialEq)]
7pub struct Note {
8 /// The base filename without `.md` extension.
9 pub name: String,
10
11 /// Filesystem path to the `.md` file.
12 pub path: PathBuf,
13
14 /// File creation time.
15 ///
16 /// TODO: Use chrono or time crates for better time format handling
17 pub created: SystemTime,
18}
19
20impl Default for Note {
21 fn default() -> Self {
22 Self {
23 name: String::default(),
24 path: PathBuf::default(),
25 created: SystemTime::UNIX_EPOCH,
26 }
27 }
28}
29
30impl Note {
31 /// Reads the note's contents from disk to a `String`.
32 ///
33 /// # Examples
34 ///
35 /// ```
36 /// use basalt_core::obsidian::Note;
37 ///
38 /// let note = Note {
39 /// name: "Example".to_string(),
40 /// path: "path/to/Example.md".into(),
41 /// ..Default::default()
42 /// };
43 ///
44 /// _ = Note::read_to_string(¬e);
45 /// ```
46 pub fn read_to_string(note: &Note) -> Result<String> {
47 fs::read_to_string(¬e.path).map_err(Error::Io)
48 }
49
50 /// Writes given content to notes path.
51 ///
52 /// # Examples
53 ///
54 /// ```
55 /// use basalt_core::obsidian::Note;
56 ///
57 /// let note = Note {
58 /// name: "Example".to_string(),
59 /// path: "path/to/Example.md".into(),
60 /// ..Default::default()
61 /// };
62 ///
63 /// _ = Note::write(¬e, String::from("# Heading"));
64 /// ```
65 pub fn write(note: &Note, contents: String) -> Result<()> {
66 fs::write(¬e.path, contents).map_err(Error::Io)
67 }
68}