basalt_core/obsidian/
note.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use std::{fs, path::PathBuf, time::SystemTime};

use crate::obsidian::{Error, Result};

/// Represents a single note (Markdown file) within a vault.
#[derive(Debug, Clone, PartialEq)]
pub struct Note {
    /// The base filename without `.md` extension.
    pub name: String,

    /// Filesystem path to the `.md` file.
    pub path: PathBuf,

    /// File creation time.
    ///
    /// TODO: Use chrono or time crates for better time format handling
    pub created: SystemTime,
}

impl Note {
    /// Reads the note's contents from disk to a `String`.
    ///
    /// # Examples
    ///
    /// ```
    /// use basalt_core::obsidian::Note;
    ///
    /// let note = Note {
    ///     name: "Example".to_string(),
    ///     path: "path/to/Example.md".into(),
    ///     ..Default::default()
    /// };
    ///
    /// _ = Note::read_to_string(&note);
    /// ```
    pub fn read_to_string(note: &Note) -> Result<String> {
        fs::read_to_string(&note.path).map_err(Error::Io)
    }

    /// Writes given content to notes path.
    ///
    /// # Examples
    ///
    /// ```
    /// use basalt_core::obsidian::Note;
    ///
    /// let note = Note {
    ///     name: "Example".to_string(),
    ///     path: "path/to/Example.md".into(),
    ///     ..Default::default()
    /// };
    ///
    /// _ = Note::write(&note, String::from("# Heading"));
    /// ```
    pub fn write(note: &Note, contents: String) -> Result<()> {
        fs::write(&note.path, contents).map_err(Error::Io)
    }
}