diaryx_core 0.11.0

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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! In-memory filesystem implementation.
//!
//! Available on all targets, including WASM. Also useful for testing.

use std::collections::{HashMap, HashSet};
use std::io::{Error, ErrorKind, Result};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

use super::FileSystem;

/// An in-memory filesystem implementation
/// Useful for WASM targets where real filesystem access is not available
/// Also useful for testing
#[derive(Clone, Default)]
pub struct InMemoryFileSystem {
    /// Files stored as path -> content (text files)
    files: Arc<RwLock<HashMap<PathBuf, String>>>,
    /// Binary files stored as path -> bytes (attachments)
    binary_files: Arc<RwLock<HashMap<PathBuf, Vec<u8>>>>,
    /// Directories that exist (implicitly created when files are added)
    directories: Arc<RwLock<HashSet<PathBuf>>>,
}

impl InMemoryFileSystem {
    /// Create a new empty in-memory filesystem
    pub fn new() -> Self {
        Self {
            files: Arc::new(RwLock::new(HashMap::new())),
            binary_files: Arc::new(RwLock::new(HashMap::new())),
            directories: Arc::new(RwLock::new(HashSet::new())),
        }
    }

    /// Create a filesystem pre-populated with files
    /// Useful for loading from IndexedDB or other storage
    pub fn with_files(entries: Vec<(PathBuf, String)>) -> Self {
        let fs = Self::new();
        {
            let mut files = fs.files.write().unwrap();
            let mut dirs = fs.directories.write().unwrap();

            for (path, content) in entries {
                // Add all parent directories
                let mut current = path.as_path();
                while let Some(parent) = current.parent() {
                    if !parent.as_os_str().is_empty() {
                        dirs.insert(parent.to_path_buf());
                    }
                    current = parent;
                }
                files.insert(path, content);
            }
        }
        fs
    }

    /// Load files from a list of (path_string, content) tuples
    /// Convenience method for JavaScript interop
    pub fn load_from_entries(entries: Vec<(String, String)>) -> Self {
        let entries: Vec<(PathBuf, String)> = entries
            .into_iter()
            .map(|(path, content)| (PathBuf::from(path), content))
            .collect();
        Self::with_files(entries)
    }

    /// Export all files as (path_string, content) tuples
    /// Useful for persisting to IndexedDB or other storage
    pub fn export_entries(&self) -> Vec<(String, String)> {
        let files = self.files.read().unwrap();
        files
            .iter()
            .map(|(path, content)| (path.to_string_lossy().to_string(), content.clone()))
            .collect()
    }

    /// Export all binary files as (path_string, content_bytes) tuples
    /// For persisting attachments to IndexedDB
    pub fn export_binary_entries(&self) -> Vec<(String, Vec<u8>)> {
        let binary_files = self.binary_files.read().unwrap();
        binary_files
            .iter()
            .map(|(path, content)| (path.to_string_lossy().to_string(), content.clone()))
            .collect()
    }

    /// Load binary files from a list of (path_string, content_bytes) tuples
    pub fn load_binary_entries(&self, entries: Vec<(String, Vec<u8>)>) {
        let mut binary_files = self.binary_files.write().unwrap();
        let mut dirs = self.directories.write().unwrap();

        for (path_str, content) in entries {
            let path = PathBuf::from(&path_str);
            // Add all parent directories
            let mut current = path.as_path();
            while let Some(parent) = current.parent() {
                if !parent.as_os_str().is_empty() {
                    dirs.insert(parent.to_path_buf());
                }
                current = parent;
            }
            binary_files.insert(path, content);
        }
    }

    /// Get a list of all file paths in the filesystem
    pub fn list_all_files(&self) -> Vec<PathBuf> {
        let files = self.files.read().unwrap();
        files.keys().cloned().collect()
    }

    /// Clear all files and directories
    pub fn clear(&self) {
        let mut files = self.files.write().unwrap();
        let mut dirs = self.directories.write().unwrap();
        files.clear();
        dirs.clear();
    }

    /// Helper to normalize paths (remove . and .. components where possible)
    fn normalize_path(path: &Path) -> PathBuf {
        let mut components = Vec::new();
        for component in path.components() {
            use std::path::Component;
            match component {
                Component::CurDir => {} // Skip "."
                Component::ParentDir => {
                    // Go up one level if possible
                    if !components.is_empty() {
                        components.pop();
                    }
                }
                c => components.push(c),
            }
        }
        components.iter().collect()
    }
}

impl FileSystem for InMemoryFileSystem {
    fn read_to_string(&self, path: &Path) -> Result<String> {
        let normalized = Self::normalize_path(path);
        let files = self.files.read().unwrap();
        files
            .get(&normalized)
            .cloned()
            .ok_or_else(|| Error::new(ErrorKind::NotFound, format!("File not found: {:?}", path)))
    }

    fn write_file(&self, path: &Path, content: &str) -> Result<()> {
        let normalized = Self::normalize_path(path);

        // Ensure parent directories exist
        if let Some(parent) = normalized.parent() {
            self.create_dir_all(parent)?;
        }

        let mut files = self.files.write().unwrap();
        files.insert(normalized, content.to_string());
        Ok(())
    }

    fn create_new(&self, path: &Path, content: &str) -> Result<()> {
        let normalized = Self::normalize_path(path);

        // Check if file exists first
        {
            let files = self.files.read().unwrap();
            if files.contains_key(&normalized) {
                return Err(Error::new(
                    ErrorKind::AlreadyExists,
                    format!("File already exists: {:?}", path),
                ));
            }
        }

        // Ensure parent directories exist
        if let Some(parent) = normalized.parent() {
            self.create_dir_all(parent)?;
        }

        let mut files = self.files.write().unwrap();
        files.insert(normalized, content.to_string());
        Ok(())
    }

    fn delete_file(&self, path: &Path) -> Result<()> {
        let normalized = Self::normalize_path(path);

        // Try text files first
        {
            let mut files = self.files.write().unwrap();
            if files.remove(&normalized).is_some() {
                return Ok(());
            }
        }

        // Try binary files
        {
            let mut binary_files = self.binary_files.write().unwrap();
            if binary_files.remove(&normalized).is_some() {
                return Ok(());
            }
        }

        Err(Error::new(
            ErrorKind::NotFound,
            format!("File not found: {:?}", path),
        ))
    }

    fn list_md_files(&self, dir: &Path) -> Result<Vec<PathBuf>> {
        let normalized = Self::normalize_path(dir);
        let files = self.files.read().unwrap();

        let mut result = Vec::new();
        for path in files.keys() {
            // Check if the file is directly in this directory (not in a subdirectory)
            if let Some(parent) = path.parent()
                && parent == normalized
                && path.extension().is_some_and(|ext| ext == "md")
            {
                result.push(path.clone());
            }
        }
        Ok(result)
    }

    fn exists(&self, path: &Path) -> bool {
        let normalized = Self::normalize_path(path);
        let files = self.files.read().unwrap();
        let binary_files = self.binary_files.read().unwrap();
        let dirs = self.directories.read().unwrap();
        files.contains_key(&normalized)
            || binary_files.contains_key(&normalized)
            || dirs.contains(&normalized)
    }

    fn create_dir_all(&self, path: &Path) -> Result<()> {
        let normalized = Self::normalize_path(path);
        let mut dirs = self.directories.write().unwrap();

        // Add the directory and all parent directories
        let mut current = normalized.as_path();
        loop {
            if !current.as_os_str().is_empty() {
                dirs.insert(current.to_path_buf());
            }
            match current.parent() {
                Some(parent) if !parent.as_os_str().is_empty() => {
                    current = parent;
                }
                _ => break,
            }
        }

        Ok(())
    }

    fn is_dir(&self, path: &Path) -> bool {
        let normalized = Self::normalize_path(path);
        let dirs = self.directories.read().unwrap();
        dirs.contains(&normalized)
    }

    fn move_file(&self, from: &Path, to: &Path) -> Result<()> {
        let from_norm = Self::normalize_path(from);
        let to_norm = Self::normalize_path(to);

        if from_norm == to_norm {
            return Ok(());
        }

        // Check if this is a directory move
        let is_dir = self.is_dir(&from_norm);

        if is_dir {
            // Moving a directory: relocate all files within it
            let files_to_move: Vec<(PathBuf, String)>;
            {
                let files = self.files.read().unwrap();
                files_to_move = files
                    .iter()
                    .filter(|(path, _)| path.starts_with(&from_norm))
                    .map(|(path, content)| (path.clone(), content.clone()))
                    .collect();
            }

            if files_to_move.is_empty() && !self.is_dir(&from_norm) {
                return Err(Error::new(
                    ErrorKind::NotFound,
                    format!("Source directory not found or empty: {:?}", from),
                ));
            }

            // Check destination doesn't already exist as a file or directory
            {
                let files = self.files.read().unwrap();
                let dirs = self.directories.read().unwrap();
                if files.contains_key(&to_norm) || dirs.contains(&to_norm) {
                    return Err(Error::new(
                        ErrorKind::AlreadyExists,
                        format!("Destination already exists: {:?}", to),
                    ));
                }
            }

            // Move all files to new location
            {
                let mut files = self.files.write().unwrap();
                for (old_path, content) in files_to_move {
                    files.remove(&old_path);
                    // Replace the source prefix with the destination prefix
                    let relative = old_path.strip_prefix(&from_norm).unwrap();
                    let new_path = to_norm.join(relative);
                    files.insert(new_path, content);
                }
            }

            // Update directories: remove old, add new
            {
                let mut dirs = self.directories.write().unwrap();
                // Remove old directory and its subdirectories
                let old_dirs: Vec<PathBuf> = dirs
                    .iter()
                    .filter(|d| d.starts_with(&from_norm) || **d == from_norm)
                    .cloned()
                    .collect();
                for old_dir in old_dirs {
                    dirs.remove(&old_dir);
                    // Add corresponding new directory
                    if old_dir == from_norm {
                        dirs.insert(to_norm.clone());
                    } else if let Ok(relative) = old_dir.strip_prefix(&from_norm) {
                        dirs.insert(to_norm.join(relative));
                    }
                }

                // Ensure parent directories of destination exist
                let mut current = to_norm.as_path();
                loop {
                    match current.parent() {
                        Some(parent) if !parent.as_os_str().is_empty() => {
                            dirs.insert(parent.to_path_buf());
                            current = parent;
                        }
                        _ => break,
                    }
                }
            }

            Ok(())
        } else {
            // Moving a single file (original behavior)
            // Validate existence and destination availability up-front.
            {
                let files = self.files.read().unwrap();

                if !files.contains_key(&from_norm) {
                    return Err(Error::new(
                        ErrorKind::NotFound,
                        format!("Source file not found: {:?}", from),
                    ));
                }

                if files.contains_key(&to_norm) {
                    return Err(Error::new(
                        ErrorKind::AlreadyExists,
                        format!("Destination already exists: {:?}", to),
                    ));
                }
            }

            // Ensure destination parent directories exist.
            if let Some(parent) = to_norm.parent() {
                self.create_dir_all(parent)?;
            }

            // Perform the move.
            let mut files = self.files.write().unwrap();
            let content = files.remove(&from_norm).ok_or_else(|| {
                Error::new(
                    ErrorKind::NotFound,
                    format!("Source file not found: {:?}", from),
                )
            })?;
            files.insert(to_norm, content);

            Ok(())
        }
    }

    fn read_binary(&self, path: &Path) -> Result<Vec<u8>> {
        let normalized = Self::normalize_path(path);

        // First check binary files
        {
            let binary_files = self.binary_files.read().unwrap();
            if let Some(data) = binary_files.get(&normalized) {
                return Ok(data.clone());
            }
        }

        // Fall back to text files (convert to bytes)
        let files = self.files.read().unwrap();
        files
            .get(&normalized)
            .map(|s| s.as_bytes().to_vec())
            .ok_or_else(|| Error::new(ErrorKind::NotFound, format!("File not found: {:?}", path)))
    }

    fn write_binary(&self, path: &Path, content: &[u8]) -> Result<()> {
        let normalized = Self::normalize_path(path);

        // Ensure parent directories exist
        if let Some(parent) = normalized.parent() {
            self.create_dir_all(parent)?;
        }

        let mut binary_files = self.binary_files.write().unwrap();
        binary_files.insert(normalized, content.to_vec());
        Ok(())
    }

    fn list_files(&self, dir: &Path) -> Result<Vec<PathBuf>> {
        let normalized = Self::normalize_path(dir);
        let files = self.files.read().unwrap();
        let binary_files = self.binary_files.read().unwrap();
        let dirs = self.directories.read().unwrap();

        let mut result = Vec::new();

        // Check text files
        for path in files.keys() {
            if let Some(parent) = path.parent()
                && parent == normalized
            {
                result.push(path.clone());
            }
        }

        // Check binary files
        for path in binary_files.keys() {
            if let Some(parent) = path.parent()
                && parent == normalized
            {
                result.push(path.clone());
            }
        }

        // Check subdirectories
        for path in dirs.iter() {
            if let Some(parent) = path.parent()
                && parent == normalized
                && path != &normalized
            {
                result.push(path.clone());
            }
        }

        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_in_memory_fs_basic_operations() {
        let fs = InMemoryFileSystem::new();

        // Create and read a file
        fs.write_file(Path::new("test.md"), "Hello, World!")
            .unwrap();
        assert_eq!(
            fs.read_to_string(Path::new("test.md")).unwrap(),
            "Hello, World!"
        );

        // Check existence
        assert!(fs.exists(Path::new("test.md")));
        assert!(!fs.exists(Path::new("nonexistent.md")));

        // Delete file
        fs.delete_file(Path::new("test.md")).unwrap();
        assert!(!fs.exists(Path::new("test.md")));
    }

    #[test]
    fn test_in_memory_fs_create_new() {
        let fs = InMemoryFileSystem::new();

        // Create new file
        fs.create_new(Path::new("new.md"), "Content").unwrap();
        assert_eq!(fs.read_to_string(Path::new("new.md")).unwrap(), "Content");

        // Try to create same file again - should fail
        let result = fs.create_new(Path::new("new.md"), "Other content");
        assert!(result.is_err());
    }

    #[test]
    fn test_in_memory_fs_directories() {
        let fs = InMemoryFileSystem::new();

        // Create a file in a nested directory
        fs.write_file(Path::new("a/b/c/file.md"), "Content")
            .unwrap();

        // Parent directories should exist
        assert!(fs.is_dir(Path::new("a")));
        assert!(fs.is_dir(Path::new("a/b")));
        assert!(fs.is_dir(Path::new("a/b/c")));

        // File should exist
        assert!(fs.exists(Path::new("a/b/c/file.md")));
    }

    #[test]
    fn test_in_memory_fs_list_md_files() {
        let fs = InMemoryFileSystem::new();

        fs.write_file(Path::new("dir/file1.md"), "Content 1")
            .unwrap();
        fs.write_file(Path::new("dir/file2.md"), "Content 2")
            .unwrap();
        fs.write_file(Path::new("dir/file.txt"), "Not markdown")
            .unwrap();
        fs.write_file(Path::new("dir/subdir/file3.md"), "Content 3")
            .unwrap();

        let md_files = fs.list_md_files(Path::new("dir")).unwrap();

        // Should only include direct children that are .md files
        assert_eq!(md_files.len(), 2);
        assert!(md_files.contains(&PathBuf::from("dir/file1.md")));
        assert!(md_files.contains(&PathBuf::from("dir/file2.md")));
    }

    #[test]
    fn test_in_memory_fs_export_import() {
        let fs = InMemoryFileSystem::new();

        fs.write_file(Path::new("file1.md"), "Content 1").unwrap();
        fs.write_file(Path::new("dir/file2.md"), "Content 2")
            .unwrap();

        // Export
        let entries = fs.export_entries();
        assert_eq!(entries.len(), 2);

        // Import into new filesystem
        let fs2 = InMemoryFileSystem::load_from_entries(entries);

        // Verify contents
        assert_eq!(
            fs2.read_to_string(Path::new("file1.md")).unwrap(),
            "Content 1"
        );
        assert_eq!(
            fs2.read_to_string(Path::new("dir/file2.md")).unwrap(),
            "Content 2"
        );
    }

    #[test]
    fn test_in_memory_fs_path_normalization() {
        let fs = InMemoryFileSystem::new();

        fs.write_file(Path::new("dir/file.md"), "Content").unwrap();

        // Should be able to read with different path representations
        assert!(fs.exists(Path::new("dir/file.md")));
        assert!(fs.exists(Path::new("dir/./file.md")));
        assert!(fs.exists(Path::new("dir/subdir/../file.md")));
    }
}