diaryx_core 0.11.1

Core library for Diaryx - a tool to manage markdown files with YAML frontmatter
Documentation
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! Search functionality for diaryx workspaces
//!
//! Provides searching through workspace files by content or frontmatter properties.
//!
//! # Async-first Design
//!
//! This module uses `AsyncFileSystem` for all filesystem operations.
//! For synchronous contexts (CLI, tests), wrap a sync filesystem with
//! `SyncToAsyncFs` and use `futures_lite::future::block_on()`.

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use ts_rs::TS;

use crate::fs::AsyncFileSystem;
use crate::workspace::Workspace;

/// Represents a search query configuration
#[derive(Debug, Clone, Serialize)]
pub struct SearchQuery {
    /// The pattern to search for
    pub pattern: String,
    /// Whether the search is case-sensitive
    pub case_sensitive: bool,
    /// Search mode: content, frontmatter, or specific property
    pub mode: SearchMode,
}

/// What to search in files
#[derive(Debug, Clone, Serialize)]
pub enum SearchMode {
    /// Search only the body content (after frontmatter)
    Content,
    /// Search all frontmatter properties
    Frontmatter,
    /// Search a specific frontmatter property
    Property(String),
}

impl SearchQuery {
    /// Create a new content search query
    pub fn content(pattern: impl Into<String>) -> Self {
        Self {
            pattern: pattern.into(),
            case_sensitive: false,
            mode: SearchMode::Content,
        }
    }

    /// Create a new frontmatter search query
    pub fn frontmatter(pattern: impl Into<String>) -> Self {
        Self {
            pattern: pattern.into(),
            case_sensitive: false,
            mode: SearchMode::Frontmatter,
        }
    }

    /// Create a search query for a specific property
    pub fn property(pattern: impl Into<String>, property_name: impl Into<String>) -> Self {
        Self {
            pattern: pattern.into(),
            case_sensitive: false,
            mode: SearchMode::Property(property_name.into()),
        }
    }

    /// Set case sensitivity
    pub fn case_sensitive(mut self, case_sensitive: bool) -> Self {
        self.case_sensitive = case_sensitive;
        self
    }
}

/// A single match within a file
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export, export_to = "bindings/")]
pub struct SearchMatch {
    /// Line number (1-based)
    pub line_number: usize,
    /// The full line content
    pub line_content: String,
    /// Column where match starts (0-based)
    pub match_start: usize,
    /// Column where match ends (0-based, exclusive)
    pub match_end: usize,
}

/// Search results for a single file
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export, export_to = "bindings/")]
pub struct FileSearchResult {
    /// Path to the file
    pub path: PathBuf,
    /// Title from frontmatter (if available)
    pub title: Option<String>,
    /// All matches found in this file
    pub matches: Vec<SearchMatch>,
}

impl FileSearchResult {
    /// Returns true if this result has any matches
    pub fn has_matches(&self) -> bool {
        !self.matches.is_empty()
    }

    /// Returns the number of matches
    pub fn match_count(&self) -> usize {
        self.matches.len()
    }
}

/// Aggregated search results
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export, export_to = "bindings/")]
pub struct SearchResults {
    /// Results per file (only files with matches)
    pub files: Vec<FileSearchResult>,
    /// Total number of files searched
    pub files_searched: usize,
}

impl SearchResults {
    /// Create empty results
    pub fn new() -> Self {
        Self {
            files: Vec::new(),
            files_searched: 0,
        }
    }

    /// Total number of matches across all files
    pub fn total_matches(&self) -> usize {
        self.files.iter().map(|f| f.match_count()).sum()
    }

    /// Number of files with matches
    pub fn files_with_matches(&self) -> usize {
        self.files.len()
    }
}

impl Default for SearchResults {
    fn default() -> Self {
        Self::new()
    }
}

/// Searcher for workspace files (async-first)
pub struct Searcher<FS: AsyncFileSystem> {
    fs: FS,
}

impl<FS: AsyncFileSystem> Searcher<FS> {
    /// Create a new searcher
    pub fn new(fs: FS) -> Self {
        Self { fs }
    }

    /// Search the entire workspace starting from the root index
    pub async fn search_workspace(
        &self,
        workspace_root: &Path,
        query: &SearchQuery,
    ) -> crate::error::Result<SearchResults>
    where
        FS: Clone,
    {
        let workspace = Workspace::new(self.fs.clone());
        let files = workspace.collect_workspace_files(workspace_root).await?;

        let mut results = SearchResults::new();
        results.files_searched = files.len();

        for file_path in files {
            if let Some(file_result) = self.search_file(&file_path, query).await?
                && file_result.has_matches()
            {
                results.files.push(file_result);
            }
        }

        Ok(results)
    }

    /// Search a single file
    pub async fn search_file(
        &self,
        path: &Path,
        query: &SearchQuery,
    ) -> crate::error::Result<Option<FileSearchResult>> {
        let content = match self.fs.read_to_string(path).await {
            Ok(c) => c,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => {
                return Err(crate::error::DiaryxError::FileRead {
                    path: path.to_path_buf(),
                    source: e,
                });
            }
        };

        let (frontmatter_str, body, title) = self.parse_file_parts(&content);

        let matches = match &query.mode {
            SearchMode::Content => self.search_text(&body, &query.pattern, query.case_sensitive),
            SearchMode::Frontmatter => {
                self.search_text(&frontmatter_str, &query.pattern, query.case_sensitive)
            }
            SearchMode::Property(prop_name) => self.search_property(
                &frontmatter_str,
                prop_name,
                &query.pattern,
                query.case_sensitive,
            ),
        };

        Ok(Some(FileSearchResult {
            path: path.to_path_buf(),
            title,
            matches,
        }))
    }

    /// Parse file into frontmatter string, body, and title
    fn parse_file_parts(&self, content: &str) -> (String, String, Option<String>) {
        // Check for frontmatter
        if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
            return (String::new(), content.to_string(), None);
        }

        let rest = &content[4..]; // Skip "---\n"
        let end_idx = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n"));

        match end_idx {
            Some(idx) => {
                let frontmatter_str = rest[..idx].to_string();
                let body = rest[idx + 5..].to_string(); // Skip "\n---\n"

                // Extract title from frontmatter
                let title = self.extract_title(&frontmatter_str);

                (frontmatter_str, body, title)
            }
            None => {
                // Malformed frontmatter, treat entire content as body
                (String::new(), content.to_string(), None)
            }
        }
    }

    /// Extract title from frontmatter string
    fn extract_title(&self, frontmatter: &str) -> Option<String> {
        for line in frontmatter.lines() {
            let line = line.trim();
            if let Some(rest) = line.strip_prefix("title:") {
                let title = rest.trim();
                // Remove quotes if present
                let title = title.trim_matches('"').trim_matches('\'');
                if !title.is_empty() {
                    return Some(title.to_string());
                }
            }
        }
        None
    }

    /// Search text for pattern, returning all matches with line info
    fn search_text(&self, text: &str, pattern: &str, case_sensitive: bool) -> Vec<SearchMatch> {
        let mut matches = Vec::new();

        let search_pattern = if case_sensitive {
            pattern.to_string()
        } else {
            pattern.to_lowercase()
        };

        for (line_idx, line) in text.lines().enumerate() {
            let search_line = if case_sensitive {
                line.to_string()
            } else {
                line.to_lowercase()
            };

            // Find all occurrences in this line
            let mut start = 0;
            while let Some(pos) = search_line[start..].find(&search_pattern) {
                let match_start = start + pos;
                let match_end = match_start + pattern.len();

                matches.push(SearchMatch {
                    line_number: line_idx + 1,
                    line_content: line.to_string(),
                    match_start,
                    match_end,
                });

                start = match_end;
            }
        }

        matches
    }

    /// Search for pattern within a specific frontmatter property
    fn search_property(
        &self,
        frontmatter: &str,
        property: &str,
        pattern: &str,
        case_sensitive: bool,
    ) -> Vec<SearchMatch> {
        let mut matches = Vec::new();
        let mut in_property = false;
        let mut property_indent: Option<usize> = None;

        let prop_prefix = format!("{}:", property);
        let search_pattern = if case_sensitive {
            pattern.to_string()
        } else {
            pattern.to_lowercase()
        };

        for (line_idx, line) in frontmatter.lines().enumerate() {
            let trimmed = line.trim_start();
            let indent = line.len() - trimmed.len();

            // Check if this line starts a new property
            if trimmed.contains(':') && !trimmed.starts_with('-') && !trimmed.starts_with('#') {
                // Check if it's our target property
                if trimmed.starts_with(&prop_prefix) {
                    in_property = true;
                    property_indent = Some(indent);

                    // Check value on same line
                    let value_part = trimmed[prop_prefix.len()..].trim();
                    if !value_part.is_empty() {
                        let search_value = if case_sensitive {
                            value_part.to_string()
                        } else {
                            value_part.to_lowercase()
                        };

                        if let Some(pos) = search_value.find(&search_pattern) {
                            let offset = line.find(value_part).unwrap_or(0);
                            matches.push(SearchMatch {
                                line_number: line_idx + 1,
                                line_content: line.to_string(),
                                match_start: offset + pos,
                                match_end: offset + pos + pattern.len(),
                            });
                        }
                    }
                } else if indent <= property_indent.unwrap_or(0) {
                    // Different property at same or lower indent level
                    in_property = false;
                    property_indent = None;
                }
            } else if in_property {
                // Continuation of property value (array items, multiline, etc.)
                if let Some(prop_indent) = property_indent {
                    if indent <= prop_indent && !trimmed.is_empty() {
                        // Back to same or lower indent, property ended
                        in_property = false;
                        property_indent = None;
                    } else {
                        // Still in property, search this line
                        let search_line = if case_sensitive {
                            line.to_string()
                        } else {
                            line.to_lowercase()
                        };

                        if let Some(pos) = search_line.find(&search_pattern) {
                            matches.push(SearchMatch {
                                line_number: line_idx + 1,
                                line_content: line.to_string(),
                                match_start: pos,
                                match_end: pos + pattern.len(),
                            });
                        }
                    }
                }
            }
        }

        matches
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fs::{FileSystem, InMemoryFileSystem, SyncToAsyncFs, block_on_test};

    type TestFs = SyncToAsyncFs<InMemoryFileSystem>;

    fn make_test_fs() -> InMemoryFileSystem {
        InMemoryFileSystem::new()
    }

    #[test]
    fn test_search_content() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/test/entry.md"),
            "---\ntitle: Test Entry\n---\n\nThis is some content.\nWith multiple lines.\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let searcher = Searcher::new(async_fs);
        let query = SearchQuery::content("content");

        let result = block_on_test(searcher.search_file(Path::new("/test/entry.md"), &query))
            .unwrap()
            .unwrap();

        assert_eq!(result.title, Some("Test Entry".to_string()));
        assert_eq!(result.matches.len(), 1);
        assert_eq!(result.matches[0].line_number, 2); // Line 2 of body
        assert!(result.matches[0].line_content.contains("content"));
    }

    #[test]
    fn test_search_content_case_insensitive() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/test/entry.md"),
            "---\ntitle: Test\n---\n\nHello WORLD and world.\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let searcher = Searcher::new(async_fs);
        let query = SearchQuery::content("world");

        let result = block_on_test(searcher.search_file(Path::new("/test/entry.md"), &query))
            .unwrap()
            .unwrap();

        // Should find both "WORLD" and "world"
        assert_eq!(result.matches.len(), 2);
    }

    #[test]
    fn test_search_content_case_sensitive() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/test/entry.md"),
            "---\ntitle: Test\n---\n\nHello WORLD and world.\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let searcher = Searcher::new(async_fs);
        let query = SearchQuery::content("world").case_sensitive(true);

        let result = block_on_test(searcher.search_file(Path::new("/test/entry.md"), &query))
            .unwrap()
            .unwrap();

        // Should only find lowercase "world"
        assert_eq!(result.matches.len(), 1);
    }

    #[test]
    fn test_search_frontmatter() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/test/entry.md"),
            "---\ntitle: Important Meeting\ndescription: A very important meeting\n---\n\nBody content here.\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let searcher = Searcher::new(async_fs);
        let query = SearchQuery::frontmatter("important");

        let result = block_on_test(searcher.search_file(Path::new("/test/entry.md"), &query))
            .unwrap()
            .unwrap();

        // Should find in both title and description
        assert_eq!(result.matches.len(), 2);
    }

    #[test]
    fn test_search_specific_property() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/test/entry.md"),
            "---\ntitle: Meeting Notes\ntags:\n  - important\n  - work\n---\n\nSome important content.\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let searcher = Searcher::new(async_fs);
        let query = SearchQuery::property("important", "tags");

        let result = block_on_test(searcher.search_file(Path::new("/test/entry.md"), &query))
            .unwrap()
            .unwrap();

        // Should only find in tags, not in body
        assert_eq!(result.matches.len(), 1);
        assert!(result.matches[0].line_content.contains("important"));
    }

    #[test]
    fn test_search_no_frontmatter() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/test/entry.md"),
            "Just plain content.\nNo frontmatter.\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let searcher = Searcher::new(async_fs);
        let query = SearchQuery::content("plain");

        let result = block_on_test(searcher.search_file(Path::new("/test/entry.md"), &query))
            .unwrap()
            .unwrap();

        assert!(result.title.is_none());
        assert_eq!(result.matches.len(), 1);
    }

    #[test]
    fn test_extract_title_with_quotes() {
        let fs = make_test_fs();
        fs.write_file(
            Path::new("/test/entry.md"),
            "---\ntitle: \"Quoted Title\"\n---\n\nContent.\n",
        )
        .unwrap();

        let async_fs: TestFs = SyncToAsyncFs::new(fs);
        let searcher = Searcher::new(async_fs);
        let query = SearchQuery::content("Content");

        let result = block_on_test(searcher.search_file(Path::new("/test/entry.md"), &query))
            .unwrap()
            .unwrap();

        assert_eq!(result.title, Some("Quoted Title".to_string()));
    }
}