rucola-notes 0.10.0

Terminal-based markdown note manager.
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use fuzzy_matcher::FuzzyMatcher;

/// Describes how to match tags when filtering
#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub enum TagMatch {
    /// Tags must be input exactly to count as matching.
    #[default]
    Exact,
    /// Entering a full prefix of a tag is enough for it match.
    Prefix,
}

impl TagMatch {
    pub fn cycle(self) -> Self {
        match self {
            TagMatch::Exact => TagMatch::Prefix,
            TagMatch::Prefix => TagMatch::Exact,
        }
    }
}

/// Describes a way to filter notes by their contained tags and/or title
#[derive(Debug, Default, Clone)]
pub struct Filter {
    /// Whether or not all specified tags must be contained in the note in order to match the filter, or only any (=at least one) of them.
    pub any: bool,
    /// Whether or not all tags must be matched exactly or only by prefix.
    pub tag_match: TagMatch,
    /// The tags to include and exclude by, hash included.
    pub tags: Vec<(String, bool)>,
    /// The links to look for or exclude, already converted to ids.
    pub links: Vec<(String, bool)>,
    /// The backlinks to look for or exclude, already converted to ids.
    pub blinks: Vec<(String, bool)>,
    /// The words to search the note title for. Will be fuzzy matched with the note title.
    pub title: String,
    /// Everything to be searched for in the full text of the notes, in lowercase.
    pub full_text: Option<String>,
}

impl Filter {
    pub fn new(filter_string: &str, any: bool, tag_match: TagMatch) -> Self {
        let mut tags = Vec::new();
        let mut links = Vec::new();
        let mut blinks = Vec::new();
        let mut title = String::new();

        let (filters, full_text) = filter_string
            .split_once('|')
            .map(|(filters, rest)| (filters, Some(rest.to_lowercase())))
            .unwrap_or((filter_string, None));

        // Go through words
        for word in filters.split_whitespace() {
            if word.starts_with("!#") {
                tags.push((word.trim_start_matches('!').to_string(), false));
                continue;
            }
            if word.starts_with('#') {
                tags.push((word.to_string(), true));
                continue;
            }
            if word.starts_with("!>") {
                links.push((
                    super::name_to_id(word.trim_start_matches("!>")).to_string(),
                    false,
                ));
                continue;
            }
            if word.starts_with('>') {
                links.push((
                    super::name_to_id(word.trim_start_matches('>')).to_string(),
                    true,
                ));
                continue;
            }
            if word.starts_with("!<") {
                blinks.push((
                    super::name_to_id(word.trim_start_matches("!<")).to_string(),
                    false,
                ));
                continue;
            }
            if word.starts_with('<') {
                blinks.push((
                    super::name_to_id(word.trim_start_matches('<')).to_string(),
                    true,
                ));
                continue;
            }
            // if nothing else fits
            title.push_str(word);
        }

        // check for any or all tags
        Self {
            any,
            tag_match,
            tags,
            links,
            blinks,
            title,
            full_text,
        }
    }

    pub fn apply(&self, note: &super::Note, index: &super::NoteIndex) -> Option<i64> {
        // === === TAGS === ===

        let mut any = false;
        let mut all = true;
        for (tag, included) in self.tags.iter() {
            if note
                // go over all tags
                .tags
                .iter()
                // split each tag into..
                .flat_map(|tag| {
                    // an iterator of substring starting at 0 and going to every appearance of /
                    tag.match_indices('/')
                        .map(|(index, _match)| &tag[0..index])
                        // and appended just a substring that is the whole tag
                        .chain(std::iter::once(tag.as_str()))
                        // flatten this so we have just an iterator over (sub)strs
                })
                // check if any of these substring is the searched tag or, in case of a multi-word tag, the tag with appropriate replacements.
                .any(|subtag|
                    match self.tag_match {
                        // tags needs to be matched exactly
                        TagMatch::Exact => tag.replace('-', " ") == subtag.replace('-', " "),
                        // it is enough if the typed tag is a prefix of the found tag
                        TagMatch::Prefix => subtag.replace('-', " ").starts_with(&tag.replace('-', " ")),
                    }
                )
            // now compare this to our expectation
            //  - inclusion: We _want_ one of them to be equal
            //  - exclusion: We _dont_ want one of them to be equal
             == *included
            {
                // this did match our expectation (one of them is equal in case of inclusion or none of them is equal in case of exclusion)
                // so at least one condition (this one) is true
                any = true;
            } else {
                // this did not match our expectation (none of them is equal in case of inclusion or one of them is equal in case of exclusion)
                // so not all conditions can be true
                all = false;
            }
        }

        // === === LINKS === ===

        // go through all links
        for (link, included) in self.links.iter() {
            // if the links is contained and we want it to be contained or not contained and we want it to be not contained
            if note.links.contains(link) == *included {
                // at least one condition (this one) is true
                any = true;
            } else {
                // else, at least one condition is false, so not all of them are true
                all = false;
            }
        }

        // go through all backlinks
        for (blink, included) in self.blinks.iter() {
            // check if the note with the blink-ID links to the main one passed to this function
            let exists_and_contains = if let Some(other_note) = index.inner.get(blink) {
                other_note.links.contains(&super::name_to_id(&note.name))
            } else {
                false
            };

            // if the backlink exists and we want that, set any/all as above
            if exists_and_contains == *included {
                any = true;
            } else {
                all = false;
            }
        }

        if let Some(text) = &self.full_text {
            if std::fs::read_to_string(&note.path)
                .map(|content| content.to_lowercase().contains(text))
                .unwrap_or(false)
            {
                any = true;
            } else {
                all = false;
            }
        }

        let fuz_match = if self.title.is_empty() {
            None
        } else {
            let matcher = fuzzy_matcher::skim::SkimMatcherV2::default();
            let fuzzy_match = matcher.fuzzy_match(&note.display_name, &self.title);
            if fuzzy_match.is_some() {
                any = true;
            } else {
                all = false;
            }
            fuzzy_match
        };
        // if all conditions are empty, return match score (only title search)
        if self.tags.is_empty() && self.links.is_empty() && self.blinks.is_empty() && self.full_text.is_none() && self.title.is_empty()  ||
            // also return match score if the required amount of conditions are fulfilled
            (!self.any && all || self.any && any)
        {
            fuz_match.or(Some(0))
        } else {
            // else, an exclusion criterion was triggered
            None
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::{data, io};
    use pretty_assertions::assert_eq;

    #[test]
    fn test_filter() {
        let config = crate::Config {
            vault_path: Some(std::env::current_dir().unwrap().join("tests")),
            ..Default::default()
        };

        let tracker = io::FileTracker::new(&config).unwrap();
        let builder = io::HtmlBuilder::new(&config);
        let index = data::NoteIndex::new(tracker, builder, &config).0;

        assert_eq!(index.inner.len(), 13);

        let linux = index.inner.get("linux").unwrap();
        let win = index.inner.get("windows").unwrap();
        let osx = index.inner.get("osx").unwrap();

        // === Filter 1 ===

        let filter1 = Filter {
            any: false,
            tag_match: data::TagMatch::Exact,
            tags: vec![("#os".to_string(), true), ("#os/win".to_string(), false)],
            links: vec![],
            blinks: vec![],
            title: String::new(),
            full_text: None,
        };

        assert!(filter1.apply(linux, &index).is_some());
        assert!(filter1.apply(osx, &index).is_some());
        assert!(filter1.apply(win, &index).is_none());
    }

    #[test]
    fn test_filter_prefix() {
        let config = crate::Config {
            vault_path: Some(std::env::current_dir().unwrap().join("tests")),
            ..Default::default()
        };

        let tracker = io::FileTracker::new(&config).unwrap();
        let builder = io::HtmlBuilder::new(&config);
        let index = data::NoteIndex::new(tracker, builder, &config).0;

        assert_eq!(index.inner.len(), 13);

        let linux = index.inner.get("linux").unwrap();
        let win = index.inner.get("windows").unwrap();
        let osx = index.inner.get("osx").unwrap();
        let topology = index.inner.get("topology").unwrap();
        let atlas = index.inner.get("atlas").unwrap();
        let chart = index.inner.get("chart").unwrap();
        let manifold = index.inner.get("manifold").unwrap();
        let smooth_map = index.inner.get("smooth-map").unwrap();

        // === Filter 1 ===

        let filter1 = Filter {
            any: false,
            tag_match: data::TagMatch::Prefix,
            tags: vec![("#diff".to_string(), true)],
            links: vec![],
            blinks: vec![],
            title: String::new(),
            full_text: None,
        };

        assert!(filter1.apply(linux, &index).is_none());
        assert!(filter1.apply(osx, &index).is_none());
        assert!(filter1.apply(win, &index).is_none());
        assert!(filter1.apply(topology, &index).is_none());
        assert!(filter1.apply(atlas, &index).is_some());
        assert!(filter1.apply(chart, &index).is_some());
        assert!(filter1.apply(manifold, &index).is_some());
        assert!(filter1.apply(smooth_map, &index).is_some());

        // === Filter 2 ===

        let filter2 = Filter {
            any: false,
            tag_match: data::TagMatch::Exact,
            tags: vec![("#diff".to_string(), true)],
            links: vec![],
            blinks: vec![],
            title: String::new(),
            full_text: None,
        };

        assert!(filter2.apply(linux, &index).is_none());
        assert!(filter2.apply(osx, &index).is_none());
        assert!(filter2.apply(win, &index).is_none());
        assert!(filter2.apply(topology, &index).is_none());
        assert!(filter2.apply(atlas, &index).is_none());
        assert!(filter2.apply(chart, &index).is_none());
        assert!(filter2.apply(manifold, &index).is_none());
        assert!(filter2.apply(smooth_map, &index).is_none());
    }

    #[test]
    fn test_filter_prefix_negate() {
        let config = crate::Config {
            vault_path: Some(std::env::current_dir().unwrap().join("tests")),
            ..Default::default()
        };

        let tracker = io::FileTracker::new(&config).unwrap();
        let builder = io::HtmlBuilder::new(&config);
        let index = data::NoteIndex::new(tracker, builder, &config).0;

        assert_eq!(index.inner.len(), 13);

        let linux = index.inner.get("linux").unwrap();
        let win = index.inner.get("windows").unwrap();
        let osx = index.inner.get("osx").unwrap();
        let topology = index.inner.get("topology").unwrap();
        let atlas = index.inner.get("atlas").unwrap();
        let chart = index.inner.get("chart").unwrap();
        let manifold = index.inner.get("manifold").unwrap();
        let smooth_map = index.inner.get("smooth-map").unwrap();

        // === Filter 1 ===

        let filter1 = Filter {
            any: false,
            tag_match: data::TagMatch::Prefix,
            tags: vec![("#o".to_string(), true), ("#os/wi".to_string(), false)],
            links: vec![],
            blinks: vec![],
            title: String::new(),
            full_text: None,
        };

        assert!(filter1.apply(linux, &index).is_some());
        assert!(filter1.apply(osx, &index).is_some());
        assert!(filter1.apply(win, &index).is_none());
        assert!(filter1.apply(topology, &index).is_none());
        assert!(filter1.apply(atlas, &index).is_none());
        assert!(filter1.apply(chart, &index).is_none());
        assert!(filter1.apply(manifold, &index).is_none());
        assert!(filter1.apply(smooth_map, &index).is_none());

        // === Filter 2 ===

        let filter2 = Filter {
            any: false,
            tag_match: data::TagMatch::Exact,
            tags: vec![("#o".to_string(), true), ("#os/wi".to_string(), false)],
            links: vec![],
            blinks: vec![],
            title: String::new(),
            full_text: None,
        };

        assert!(filter2.apply(linux, &index).is_none());
        assert!(filter2.apply(osx, &index).is_none());
        assert!(filter2.apply(win, &index).is_none());
        assert!(filter2.apply(topology, &index).is_none());
        assert!(filter2.apply(atlas, &index).is_none());
        assert!(filter2.apply(chart, &index).is_none());
        assert!(filter2.apply(manifold, &index).is_none());
        assert!(filter2.apply(smooth_map, &index).is_none());
    }

    #[test]
    fn test_filter_from_string() {
        let config = crate::Config {
            vault_path: Some(std::env::current_dir().unwrap().join("tests")),
            ..Default::default()
        };

        let tracker = io::FileTracker::new(&config).unwrap();
        let builder = io::HtmlBuilder::new(&config);
        let index = data::NoteIndex::new(tracker, builder, &config).0;

        assert_eq!(index.inner.len(), 13);

        // === Filter 2 ===

        let filter2 = Filter::new(
            "!#lietheo #diffgeo >Manifold !>atlas",
            false,
            TagMatch::Exact,
        );

        assert_eq!(
            filter2.tags,
            vec![
                ("#lietheo".to_string(), false),
                ("#diffgeo".to_string(), true)
            ]
        );
        assert_eq!(
            filter2.links,
            vec![("manifold".to_string(), true), ("atlas".to_string(), false)]
        );
        assert_eq!(filter2.title, "");

        let liegroup = index.inner.get("lie-group").unwrap();
        let chart = index.inner.get("chart").unwrap();
        let manifold = index.inner.get("manifold").unwrap();
        let smoothmap = index.inner.get("smooth-map").unwrap();
        let topology = index.inner.get("topology").unwrap();

        assert!(filter2.apply(liegroup, &index).is_none());
        assert!(filter2.apply(chart, &index).is_some());
        assert!(filter2.apply(manifold, &index).is_none());
        assert!(filter2.apply(smoothmap, &index).is_none());
        assert!(filter2.apply(topology, &index).is_none());
    }

    #[test]
    fn test_filter_from_string_all() {
        // === Filter 3 ===
        let filter3 = Filter::new(
            "!#topology #os >TopologY !>Smooth-mAp <atlas !<linux |equivalent",
            false,
            TagMatch::Exact,
        );

        assert_eq!(
            filter3.tags,
            vec![("#topology".to_string(), false), ("#os".to_string(), true)]
        );
        assert_eq!(
            filter3.links,
            vec![
                ("topology".to_string(), true),
                ("smooth-map".to_string(), false)
            ]
        );
        assert_eq!(
            filter3.blinks,
            vec![("atlas".to_string(), true), ("linux".to_string(), false)]
        );
        assert_eq!(filter3.title, "");

        assert_eq!(filter3.full_text, Some(String::from("equivalent")));
    }

    #[test]
    fn test_filter_from_string_case_insensitive() {
        // === Filter 4 ===
        let filter4 = Filter::new("<aTlas >Smooth-mAp", true, TagMatch::Exact);

        assert_eq!(filter4.tags, vec![]);
        assert_eq!(filter4.links, vec![("smooth-map".to_string(), true),]);
        assert_eq!(filter4.blinks, vec![("atlas".to_string(), true)]);
        assert_eq!(filter4.title, "");
    }

    #[test]
    fn test_filter_from_string_multi_word_tags() {
        let config = crate::Config {
            vault_path: Some(std::env::current_dir().unwrap().join("tests")),
            ..Default::default()
        };

        let tracker = io::FileTracker::new(&config).unwrap();
        let builder = io::HtmlBuilder::new(&config);
        let index = data::NoteIndex::new(tracker, builder, &config).0;

        assert_eq!(index.inner.len(), 13);

        // === Filter 2 ===

        let filter2 = Filter::new("#funny-abbreviations", false, TagMatch::Exact);

        assert_eq!(
            filter2.tags,
            vec![("#funny-abbreviations".to_string(), true),]
        );

        assert_eq!(filter2.links, vec![]);

        assert_eq!(filter2.title, "");

        let yamlformat = index.inner.get("note25").unwrap();
        let chart = index.inner.get("chart").unwrap();

        assert!(filter2.apply(yamlformat, &index).is_some());
        assert!(filter2.apply(chart, &index).is_none());
    }
}