vimwiki-server 0.1.0

Daemon that supports parsing and modifying vimwiki files.
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use crate::data::{
    Element, ElementQuery, FromVimwikiElement, GqlPageFilter,
    GraphqlDatabaseError, InlineElement, InlineElementQuery, Page, PageQuery,
    Region,
};
use entity::*;
use entity_async_graphql::*;
use std::fmt;
use vimwiki::{self as v, Located};

#[simple_ent]
#[derive(EntFilter)]
pub struct DefinitionList {
    #[ent(field(graphql(filter_untyped)))]
    region: Region,

    #[ent(edge(policy = "deep"))]
    terms: Vec<Term>,

    #[ent(edge(policy = "deep"))]
    definitions: Vec<Definition>,

    /// Page containing the element
    #[ent(edge)]
    page: Page,

    /// Parent element to this element
    #[ent(edge(policy = "shallow", wrap, graphql(filter_untyped)))]
    parent: Option<Element>,
}

/// Represents a single list of terms & definitions in a document
#[async_graphql::Object]
impl DefinitionList {
    /// The terms found within the list
    #[graphql(name = "terms")]
    async fn gql_terms(&self) -> async_graphql::Result<Vec<Term>> {
        self.load_terms()
            .map_err(|x| async_graphql::Error::new(x.to_string()))
    }

    /// The definitions found within the list
    #[graphql(name = "definitions")]
    async fn gql_definitions(&self) -> async_graphql::Result<Vec<Definition>> {
        self.load_definitions()
            .map_err(|x| async_graphql::Error::new(x.to_string()))
    }

    /// The definitions for a specific term
    #[graphql(name = "definitions_for_term")]
    async fn gql_definitions_for_term(
        &self,
        term: String,
    ) -> async_graphql::Result<Vec<Definition>> {
        let terms = self
            .load_terms()
            .map_err(|x| async_graphql::Error::new(x.to_string()))?;
        for t in terms {
            if t.to_string() == term {
                return t
                    .load_definitions()
                    .map_err(|x| async_graphql::Error::new(x.to_string()));
            }
        }
        Ok(Vec::new())
    }

    /// The page containing this definition list
    #[graphql(name = "page")]
    async fn gql_page(&self) -> async_graphql::Result<Page> {
        self.load_page()
            .map_err(|x| async_graphql::Error::new(x.to_string()))
    }

    /// The parent element containing this definition list
    #[graphql(name = "parent")]
    async fn gql_parent(&self) -> async_graphql::Result<Option<Element>> {
        self.load_parent()
            .map_err(|x| async_graphql::Error::new(x.to_string()))
    }
}

impl<'a> FromVimwikiElement<'a> for DefinitionList {
    type Element = Located<v::DefinitionList<'a>>;

    fn from_vimwiki_element(
        page_id: Id,
        parent_id: Option<Id>,
        element: Self::Element,
    ) -> Result<Self, GraphqlDatabaseError> {
        let region = Region::from(element.region());

        // First, create a definition list that has no terms or definitions
        // so we can get its id to use as the parent for each of those
        let mut definition_list = GraphqlDatabaseError::wrap(
            Self::build()
                .region(region)
                .terms(Vec::new())
                .definitions(Vec::new())
                .page(page_id)
                .parent(parent_id)
                .finish_and_commit(),
        )?;

        // Second, create all of the children terms and definitions
        let mut terms: Vec<Id> = Vec::new();
        let mut definitions: Vec<Id> = Vec::new();
        for (term, defs) in element.into_inner() {
            let mut ent_term = Term::from_vimwiki_element(
                page_id,
                Some(definition_list.id()),
                term,
            )?;

            let mut ent_def_ids: Vec<Id> = Vec::new();
            for def in defs {
                ent_def_ids.push(
                    Definition::from_vimwiki_element(
                        page_id,
                        Some(definition_list.id()),
                        def,
                    )?
                    .id(),
                );
            }

            // NOTE: When first created, the ent term won't have any definitions
            //       associated, so we need to make it aware of them and update
            //       it within the database
            ent_term.set_definitions_ids(ent_def_ids.clone());
            ent_term.commit().map_err(GraphqlDatabaseError::Database)?;

            terms.push(ent_term.id());
            definitions.extend(ent_def_ids);
        }

        // Third, update the definition list with the created term and definition ids
        definition_list.set_terms_ids(terms);
        definition_list.set_definitions_ids(definitions);
        definition_list
            .commit()
            .map_err(GraphqlDatabaseError::Database)?;

        Ok(definition_list)
    }
}

#[gql_ent]
pub struct Term {
    /// The segment of the document this term covers
    #[ent(field(graphql(filter_untyped)))]
    region: Region,

    /// The content within the term as individual elements
    #[ent(edge(policy = "deep", wrap, graphql(filter_untyped)))]
    contents: Vec<InlineElement>,

    /// The content within the term as it would be read by humans without frills
    #[ent(field(computed = "self.to_string()"))]
    text: String,

    /// The definitions associated with this term
    #[ent(edge(policy = "deep"))]
    definitions: Vec<Definition>,

    /// The page containing this term
    #[ent(edge)]
    page: Page,

    /// The parent element containing this term
    #[ent(edge(policy = "shallow", wrap, graphql(filter_untyped)))]
    parent: Option<Element>,
}

impl fmt::Display for Term {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.load_contents() {
            Ok(contents) => {
                for content in contents {
                    write!(f, "{}", content.to_string())?;
                }
                Ok(())
            }
            Err(x) => {
                write!(f, "{}", x)?;
                Ok(())
            }
        }
    }
}

impl<'a> FromVimwikiElement<'a> for Term {
    type Element = Located<v::Term<'a>>;

    fn from_vimwiki_element(
        page_id: Id,
        parent_id: Option<Id>,
        element: Self::Element,
    ) -> Result<Self, GraphqlDatabaseError> {
        let region = Region::from(element.region());

        // NOTE: We are not populating definitions here because the vimwiki
        //       Term does not have a connection by itself
        let mut term = GraphqlDatabaseError::wrap(
            Self::build()
                .region(region)
                .contents(Vec::new())
                .definitions(Vec::new())
                .page(page_id)
                .parent(parent_id)
                .finish_and_commit(),
        )?;

        let mut contents = Vec::new();
        for content in element.into_inner().into_inner() {
            contents.push(
                InlineElement::from_vimwiki_element(
                    page_id,
                    Some(term.id()),
                    content,
                )?
                .id(),
            );
        }

        term.set_contents_ids(contents);
        term.commit().map_err(GraphqlDatabaseError::Database)?;

        Ok(term)
    }
}

#[gql_ent]
pub struct Definition {
    /// The segment of the document this definition covers
    #[ent(field(graphql(filter_untyped)))]
    region: Region,

    /// The content within the definition as individual elements
    #[ent(edge(policy = "deep", wrap, graphql(filter_untyped)))]
    contents: Vec<InlineElement>,

    /// The content within the definition as it would be read by humans
    /// without frills
    #[ent(field(computed = "self.to_string()"))]
    text: String,

    /// The page containing this definition
    #[ent(edge)]
    page: Page,

    /// The parent element containing this definition
    #[ent(edge(policy = "shallow", wrap, graphql(filter_untyped)))]
    parent: Option<Element>,
}

impl fmt::Display for Definition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.load_contents() {
            Ok(contents) => {
                for content in contents {
                    write!(f, "{}", content.to_string())?;
                }
                Ok(())
            }
            Err(x) => {
                write!(f, "{}", x)?;
                Ok(())
            }
        }
    }
}

impl<'a> FromVimwikiElement<'a> for Definition {
    type Element = Located<v::Definition<'a>>;

    fn from_vimwiki_element(
        page_id: Id,
        parent_id: Option<Id>,
        element: Self::Element,
    ) -> Result<Self, GraphqlDatabaseError> {
        let region = Region::from(element.region());

        let mut definition = GraphqlDatabaseError::wrap(
            Self::build()
                .region(region)
                .contents(Vec::new())
                .page(page_id)
                .parent(parent_id)
                .finish_and_commit(),
        )?;

        let mut contents = Vec::new();
        for content in element.into_inner().into_inner() {
            contents.push(
                InlineElement::from_vimwiki_element(
                    page_id,
                    Some(definition.id()),
                    content,
                )?
                .id(),
            );
        }

        definition.set_contents_ids(contents);
        definition
            .commit()
            .map_err(GraphqlDatabaseError::Database)?;

        Ok(definition)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use entity_inmemory::InmemoryDatabase;
    use vimwiki::macros::*;

    #[test]
    fn should_fully_populate_from_vimwiki_element() {
        global::with_db(InmemoryDatabase::default(), || {
            let element = vimwiki_definition_list! {r#"
                    term1:: definition 1
                    term2::
                    :: definition 2
                    :: definition 3
                "#};
            let region = Region::from(element.region());

            let ent =
                DefinitionList::from_vimwiki_element(999, Some(123), element)
                    .expect("Failed to convert from element");
            assert_eq!(ent.region(), &region);
            assert_eq!(ent.page_id(), 999);
            assert_eq!(ent.parent_id(), Some(123));

            let mut terms = ent.load_terms().expect("Failed to load terms");
            let mut defs =
                ent.load_definitions().expect("Failed to load definitions");

            // NOTE: Sorting to ensure that term1 comes before term2
            terms.sort_unstable_by_key(|k| k.to_string());
            defs.sort_unstable_by_key(|k| k.to_string());

            // Verify that all children have same page and parent
            for term in terms.iter() {
                assert_eq!(term.page_id(), 999);
                assert_eq!(term.parent_id(), Some(ent.id()));
                for content in
                    term.load_contents().expect("Failed to load term contents")
                {
                    assert_eq!(content.page_id(), 999);
                    assert_eq!(content.parent_id(), Some(term.id()));
                }
            }
            for def in defs.iter() {
                assert_eq!(def.page_id(), 999);
                assert_eq!(def.parent_id(), Some(ent.id()));
                for content in def
                    .load_contents()
                    .expect("Failed to load definition contents")
                {
                    assert_eq!(content.page_id(), 999);
                    assert_eq!(content.parent_id(), Some(def.id()));
                }
            }

            macro_rules! assert_contains_same {
                ($t:ty, $a:expr, $b:expr) => {{
                    use std::collections::HashSet;
                    let aa: HashSet<$t> = ($a).into_iter().collect();
                    let bb: HashSet<$t> = ($b).into_iter().collect();
                    assert_eq!(aa, bb);
                }};
            }

            assert_contains_same!(
                String,
                terms
                    .iter()
                    .map(ToString::to_string)
                    .collect::<Vec<String>>(),
                vec!["term1".to_string(), "term2".to_string()]
            );
            assert_contains_same!(
                Id,
                terms[0].definitions_ids().clone(),
                vec![defs[0].id()]
            );
            assert_contains_same!(
                Id,
                terms[1].definitions_ids().clone(),
                vec![defs[1].id(), defs[2].id()]
            );

            assert_contains_same!(
                String,
                defs.iter()
                    .map(ToString::to_string)
                    .collect::<Vec<String>>(),
                vec![
                    "definition 1".to_string(),
                    "definition 2".to_string(),
                    "definition 3".to_string()
                ]
            );
        });
    }
}