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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use crate::prelude::*;

mod entry;
mod loader;
mod persistence;
mod topic;

pub use entry::*;
pub use loader::*;
pub use persistence::*;
pub use topic::*;

pub struct Journal<LOADER>
where
    LOADER: JournalLoaderTrait,
{
    /// directory realative to the mdbook `SUMMARY.md`
    source_root: PathBuf,
    /// All of the topics tracked by journal
    topics: TopicMap,
    /// Responsible for saving and loading entries
    persistence: LOADER::DataDriver,
}

impl<LOADER> Journal<LOADER>
where
    LOADER: JournalLoaderTrait,
{
    pub fn install(config: LOADER::ConfigSource) -> Result<()> {
        LOADER::install(config)
    }

    pub fn load(config: LOADER::ConfigSource) -> Result<Self> {
        let (persistence, topics, source_root) = LOADER::load(config)?;

        Ok(Self {
            source_root,
            persistence,
            topics,
        })
    }

    pub fn with_topic<T>(&self, topic: &T) -> Result<&Topic>
    where
        T: AsRef<str>,
    {
        self.topics
            .find(topic)
            .with_context(|| format!("Topic Not Found [{}]", topic.as_ref()))
    }

    pub fn each_topic(&self) -> impl Iterator<Item = &Topic> {
        self.topics.iter()
    }

    pub fn persist_entry(&self, entry: &Entry) -> Result<PathBuf> {
        let topic = self.with_topic(&entry.topic_name())?;
        let file_location = self.source_root.join(topic.source_path(entry)?);
        let data = &self.persistence.serialize(entry)?;
        self.persistence.persist(&file_location, data)?;
        Ok(file_location)
    }

    pub fn fetch_entry(&self, path: &Path) -> Result<Entry> {
        self.persistence.fetch(path)
    }

    pub fn entries_for_topic<T>(&self, topic: &T) -> Result<Vec<Entry>>
    where
        T: AsRef<str>,
    {
        self.persistence
            .query(&Query::ForTopic(self.with_topic(topic)?))
    }

    pub fn all_entries(&self) -> Result<Vec<Entry>> {
        self.persistence.query(&Query::AllEntries)
    }
}

#[cfg(test)]
mod test {
    use crate::prelude::*;
    use crate::support::prelude::*;
    use pretty_assertions::assert_eq;

    #[rstest]
    fn full_generation() -> Result<()> {
        let journal: Journal<MockJournalLoaderTrait> = Journal {
            persistence: FilePersistence::new("/tmp/mdbook-journal-test"),
            source_root: "/tmp/mdbook-journal-test".into(),
            topics: TopicMap::default().insert(
                Topic::builder("code-blog")
                    .add_variable(Variable::new("title").required())
                    .build(),
            )?,
        };

        let topic = journal.with_topic(&"code-blog")?;
        assert_eq!("code-blog", topic.name());

        let mut adapter = MockEntryGenerationTrait::new();

        adapter
            .expect_created_at()
            .returning(|| Ok(Utc.with_ymd_and_hms(2024, 10, 19, 16, 20, 0).unwrap()));

        adapter
            .expect_collect_value()
            .withf(|var| var.key() == "title")
            .returning(|_| Ok(Some(MetaValue::String("Test Entry".to_owned()))));

        let entry = topic.generate_entry(adapter)?;

        assert_eq!(entry.topic_name(), "code-blog");
        assert_eq!(entry.created_at().year(), 2024);
        assert_eq!(entry.created_at().month(), 10);
        assert_eq!(
            entry.meta_value(&"title").unwrap(),
            &MetaValue::String("Test Entry".to_owned())
        );
        assert_eq!(entry.content(), "");

        let file_location = journal.persist_entry(&entry)?;
        let reloaded = journal.fetch_entry(&file_location)?;

        assert_eq!(entry.topic_name(), reloaded.topic_name());
        assert_eq!(entry.created_at(), reloaded.created_at());
        assert_eq!(entry.content(), reloaded.content());
        assert_eq!(entry.meta_value(&"title"), reloaded.meta_value(&"title"));
        assert_eq!(&file_location, reloaded.file_location().unwrap());

        let entries = journal.entries_for_topic(&"code-blog")?;
        assert_eq!(entry.meta_value(&"title"), entries[0].meta_value(&"title"));

        let entries = journal.all_entries()?;
        assert_eq!(entry.meta_value(&"title"), entries[0].meta_value(&"title"));
        Ok(())
    }
}