diaryx_core 1.4.4

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
//! Helper functions for entry operations.
//!
//! This module contains utility functions for working with filenames and titles.

use crate::workspace::FilenameStyle;

/// Characters that are illegal in filenames on major filesystems (Windows, macOS, Linux).
/// Also forbidden by Chrome's File System Access API on all platforms.
const FS_ILLEGAL_CHARS: &[char] = &['/', '\\', ':', '*', '?', '"', '<', '>', '|'];

/// Check if a character is a non-portable control character (U+0000-U+001F, U+007F).
fn is_control_char(c: char) -> bool {
    c <= '\x1F' || c == '\x7F'
}

/// Check if a character is non-portable in filenames.
/// This includes the 9 restricted ASCII symbols and control characters.
fn is_non_portable_char(c: char) -> bool {
    FS_ILLEGAL_CHARS.contains(&c) || is_control_char(c)
}

/// Characters that are not allowed at the start or end of filenames.
/// Chrome's File System Access API forbids `.`, `~`, and whitespace at boundaries.
const BOUNDARY_CHARS: &[char] = &['.', '~', ' ', '\t'];

/// Convert a filename to a prettier title.
/// e.g., "my-note" -> "My Note", "some_file" -> "Some File"
pub fn prettify_filename(filename: &str) -> String {
    filename
        .replace(['-', '_'], " ")
        .split_whitespace()
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().chain(chars).collect(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Slugify a string for use in URLs and filenames.
/// Converts to lowercase, replaces non-alphanumeric with dashes, removes consecutive dashes.
/// e.g., "My Cool Entry!" -> "my-cool-entry"
pub fn slugify(s: &str) -> String {
    s.to_lowercase()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '-' })
        .collect::<String>()
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-")
}

/// Convert a title to a kebab-case filename with .md extension.
/// e.g., "My Cool Entry" -> "my-cool-entry.md"
/// Handles unicode, special characters, and multiple spaces.
pub fn slugify_title(title: &str) -> String {
    let slug = slugify(title);
    if slug.is_empty() {
        "untitled.md".to_string()
    } else {
        format!("{}.md", slug)
    }
}

/// Apply a filename style to a title, returning the filename stem (without extension).
///
/// - `Preserve`: Strip only filesystem-illegal characters, keep spaces/caps/unicode.
/// - `KebabCase`: Lowercase, non-alphanumeric → dashes, collapse consecutive.
/// - `SnakeCase`: Lowercase, non-alphanumeric → underscores, collapse consecutive.
/// - `ScreamingSnakeCase`: Uppercase, non-alphanumeric → underscores, collapse consecutive.
pub fn apply_filename_style(title: &str, style: &FilenameStyle) -> String {
    match style {
        FilenameStyle::Preserve => {
            let cleaned: String = title
                .chars()
                .filter(|c| !is_non_portable_char(*c))
                .collect();
            let trimmed = cleaned.trim();
            if trimmed.is_empty() {
                "Untitled".to_string()
            } else {
                trimmed.to_string()
            }
        }
        FilenameStyle::KebabCase => slugify(title),
        FilenameStyle::SnakeCase => {
            let result: String = title
                .to_lowercase()
                .chars()
                .map(|c| if c.is_alphanumeric() { c } else { '_' })
                .collect();
            let collapsed: String = result
                .split('_')
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>()
                .join("_");
            if collapsed.is_empty() {
                "untitled".to_string()
            } else {
                collapsed
            }
        }
        FilenameStyle::ScreamingSnakeCase => {
            let result: String = title
                .to_uppercase()
                .chars()
                .map(|c| if c.is_alphanumeric() { c } else { '_' })
                .collect();
            let collapsed: String = result
                .split('_')
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>()
                .join("_");
            if collapsed.is_empty() {
                "UNTITLED".to_string()
            } else {
                collapsed
            }
        }
    }
}

/// Convert a title to a filename with .md extension, using the given filename style.
#[allow(dead_code)]
pub fn slugify_title_with_style(title: &str, style: &FilenameStyle) -> String {
    let stem = apply_filename_style(title, style);
    format!("{}.md", stem)
}

/// Check if a filename contains non-portable characters.
///
/// Returns `Some(reason)` describing the problem, or `None` if the filename is portable.
/// Checks for:
/// - Any of the 9 restricted ASCII symbols (`/ \ : * ? " < > |`) and control chars
/// - Starting or ending with `.`, `~`, or whitespace
///
/// The `filename` argument should be just the filename (no directory components).
pub fn has_non_portable_chars(filename: &str) -> Option<String> {
    // Strip .md extension for checking (if present), since boundary rules apply to the stem
    let stem = filename.strip_suffix(".md").unwrap_or(filename);

    // Check for non-portable characters anywhere
    for c in stem.chars() {
        if FS_ILLEGAL_CHARS.contains(&c) {
            return Some(format!("contains '{}'", c));
        }
        if is_control_char(c) {
            return Some(format!("contains control character U+{:04X}", c as u32));
        }
    }

    // Check boundary characters at start of stem
    if let Some(first) = stem.chars().next()
        && BOUNDARY_CHARS.contains(&first)
    {
        return Some(format!("starts with '{}'", first));
    }

    // Check boundary characters at end of stem
    if let Some(last) = stem.chars().last()
        && BOUNDARY_CHARS.contains(&last)
    {
        return Some(format!("ends with '{}'", last));
    }

    None
}

/// Sanitize a filename by removing non-portable characters.
///
/// - Strips the 9 restricted ASCII symbols and control characters
/// - Trims `.`, `~`, and whitespace from start and end of the stem
/// - Preserves the `.md` extension if present
/// - Returns `"Untitled.md"` if nothing remains
pub fn sanitize_filename(filename: &str) -> String {
    let (stem, ext) = if let Some(s) = filename.strip_suffix(".md") {
        (s, ".md")
    } else {
        (filename, "")
    };

    // Remove non-portable characters
    let cleaned: String = stem.chars().filter(|c| !is_non_portable_char(*c)).collect();

    // Trim boundary characters from start and end
    let trimmed = cleaned
        .trim_start_matches(|c: char| BOUNDARY_CHARS.contains(&c))
        .trim_end_matches(|c: char| BOUNDARY_CHARS.contains(&c));

    if trimmed.is_empty() {
        format!("Untitled{}", ext)
    } else {
        format!("{}{}", trimmed, ext)
    }
}

/// Extract title from strict first-line H1.
/// Only returns Some if the first non-blank line starts with "# " and has text after it.
pub fn extract_first_line_h1(content: &str) -> Option<String> {
    let first_line = content.lines().find(|l| !l.trim().is_empty())?;
    let title = first_line.strip_prefix("# ")?.trim();
    if title.is_empty() {
        None
    } else {
        Some(title.to_string())
    }
}

/// Update the first-line H1 in a body string to match the given title.
/// If no H1 exists on the first non-blank line, prepend one.
/// Returns the modified body.
pub fn sync_h1_in_body(body: &str, title: &str) -> String {
    // Find the first non-blank line
    let mut found = false;
    let mut new_lines: Vec<String> = Vec::new();
    let mut is_first_nonblank = true;

    for line in body.lines() {
        if is_first_nonblank && !line.trim().is_empty() {
            is_first_nonblank = false;
            if line.starts_with("# ") {
                // Replace existing H1
                new_lines.push(format!("# {}", title));
                found = true;
            } else {
                // First non-blank line is not an H1 — prepend one
                new_lines.push(format!("# {}", title));
                new_lines.push(String::new());
                new_lines.push(line.to_string());
                found = true;
            }
        } else {
            new_lines.push(line.to_string());
        }
    }

    if !found {
        // Body is empty or all blank lines
        if body.is_empty() {
            return format!("# {}\n\n", title);
        } else {
            // Prepend H1 before the blank lines
            let mut result = format!("# {}\n\n", title);
            result.push_str(body);
            return result;
        }
    }

    let mut result = new_lines.join("\n");
    // Preserve trailing newline if original had one
    if body.ends_with('\n') && !result.ends_with('\n') {
        result.push('\n');
    }
    result
}

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

    #[test]
    fn test_prettify_filename() {
        assert_eq!(prettify_filename("my-note"), "My Note");
        assert_eq!(prettify_filename("some_file"), "Some File");
        assert_eq!(prettify_filename("already-cool"), "Already Cool");
    }

    #[test]
    fn test_slugify_title() {
        assert_eq!(slugify_title("My Cool Entry"), "my-cool-entry.md");
        assert_eq!(slugify_title("Hello World!"), "hello-world.md");
        assert_eq!(slugify_title("  spaces  "), "spaces.md");
        assert_eq!(slugify_title(""), "untitled.md");
    }

    #[test]
    fn test_preserve_style() {
        assert_eq!(
            apply_filename_style("My Entry: A Story", &FilenameStyle::Preserve),
            "My Entry A Story"
        );
        assert_eq!(
            apply_filename_style("Hello World!", &FilenameStyle::Preserve),
            "Hello World!"
        );
        assert_eq!(
            apply_filename_style("café notes", &FilenameStyle::Preserve),
            "café notes"
        );
        assert_eq!(
            apply_filename_style("file/with\\bad:chars", &FilenameStyle::Preserve),
            "filewithbadchars"
        );
        assert_eq!(
            apply_filename_style("", &FilenameStyle::Preserve),
            "Untitled"
        );
        assert_eq!(
            apply_filename_style("***", &FilenameStyle::Preserve),
            "Untitled"
        );
    }

    #[test]
    fn test_kebab_case_style() {
        assert_eq!(
            apply_filename_style("My Cool Entry", &FilenameStyle::KebabCase),
            "my-cool-entry"
        );
        assert_eq!(
            apply_filename_style("Hello World!", &FilenameStyle::KebabCase),
            "hello-world"
        );
    }

    #[test]
    fn test_snake_case_style() {
        assert_eq!(
            apply_filename_style("My Cool Entry", &FilenameStyle::SnakeCase),
            "my_cool_entry"
        );
        assert_eq!(
            apply_filename_style("Hello World!", &FilenameStyle::SnakeCase),
            "hello_world"
        );
        assert_eq!(
            apply_filename_style("", &FilenameStyle::SnakeCase),
            "untitled"
        );
    }

    #[test]
    fn test_screaming_snake_case_style() {
        assert_eq!(
            apply_filename_style("My Cool Entry", &FilenameStyle::ScreamingSnakeCase),
            "MY_COOL_ENTRY"
        );
        assert_eq!(
            apply_filename_style("Hello World!", &FilenameStyle::ScreamingSnakeCase),
            "HELLO_WORLD"
        );
        assert_eq!(
            apply_filename_style("", &FilenameStyle::ScreamingSnakeCase),
            "UNTITLED"
        );
    }

    #[test]
    fn test_has_non_portable_chars() {
        // Clean filenames
        assert_eq!(has_non_portable_chars("my-note.md"), None);
        assert_eq!(has_non_portable_chars("Hello World.md"), None);
        assert_eq!(has_non_portable_chars("café notes.md"), None);
        assert_eq!(has_non_portable_chars("README.md"), None);

        // Restricted ASCII symbols
        assert!(has_non_portable_chars("what?.md").is_some());
        assert!(has_non_portable_chars("he said \"hello\".md").is_some());
        assert!(has_non_portable_chars("file:name.md").is_some());
        assert!(has_non_portable_chars("a*b.md").is_some());
        assert!(has_non_portable_chars("a|b.md").is_some());
        assert!(has_non_portable_chars("a<b>.md").is_some());

        // Boundary characters
        assert!(has_non_portable_chars(".hidden.md").is_some());
        assert!(has_non_portable_chars("~temp.md").is_some());
        assert!(has_non_portable_chars(" leading-space.md").is_some());
        assert!(has_non_portable_chars("trailing-space .md").is_some());

        // Control characters
        assert!(has_non_portable_chars("file\x00name.md").is_some());
        assert!(has_non_portable_chars("file\x1Fname.md").is_some());
        assert!(has_non_portable_chars("file\x7Fname.md").is_some());
    }

    #[test]
    fn test_sanitize_filename() {
        // Remove restricted chars
        assert_eq!(sanitize_filename("what?.md"), "what.md");
        assert_eq!(
            sanitize_filename("he said \"hello\".md"),
            "he said hello.md"
        );
        assert_eq!(sanitize_filename("a:b:c.md"), "abc.md");

        // Trim boundary chars
        assert_eq!(sanitize_filename(".hidden.md"), "hidden.md");
        assert_eq!(sanitize_filename("~temp.md"), "temp.md");
        assert_eq!(sanitize_filename(" leading.md"), "leading.md");
        assert_eq!(sanitize_filename("trailing .md"), "trailing.md");
        assert_eq!(sanitize_filename("...dots...md"), "dots.md"); // dots trimmed from stem boundaries

        // Fallback
        assert_eq!(sanitize_filename("???.md"), "Untitled.md");
        assert_eq!(sanitize_filename("*"), "Untitled");

        // Preserve extension
        assert_eq!(sanitize_filename("good-name.md"), "good-name.md");
        assert_eq!(sanitize_filename("no-ext"), "no-ext");
    }

    #[test]
    fn test_slugify_title_with_style() {
        assert_eq!(
            slugify_title_with_style("My Entry", &FilenameStyle::Preserve),
            "My Entry.md"
        );
        assert_eq!(
            slugify_title_with_style("My Entry", &FilenameStyle::KebabCase),
            "my-entry.md"
        );
        assert_eq!(
            slugify_title_with_style("My Entry", &FilenameStyle::SnakeCase),
            "my_entry.md"
        );
        assert_eq!(
            slugify_title_with_style("My Entry", &FilenameStyle::ScreamingSnakeCase),
            "MY_ENTRY.md"
        );
    }

    #[test]
    fn test_extract_first_line_h1() {
        assert_eq!(
            extract_first_line_h1("# My Title\n\nBody text"),
            Some("My Title".to_string())
        );
        assert_eq!(
            extract_first_line_h1("\n\n# My Title\n\nBody text"),
            Some("My Title".to_string())
        );
        assert_eq!(extract_first_line_h1("No heading here"), None);
        assert_eq!(extract_first_line_h1("## Not H1"), None);
        assert_eq!(extract_first_line_h1("# "), None);
        assert_eq!(extract_first_line_h1("# \n\nBody"), None);
        assert_eq!(extract_first_line_h1(""), None);
        assert_eq!(extract_first_line_h1("Body\n# Later Heading"), None);
    }

    #[test]
    fn test_sync_h1_in_body() {
        // Replace existing H1
        assert_eq!(
            sync_h1_in_body("# Old Title\n\nBody text", "New Title"),
            "# New Title\n\nBody text"
        );
        // Prepend H1 when none exists
        assert_eq!(
            sync_h1_in_body("Body text\nMore text", "New Title"),
            "# New Title\n\nBody text\nMore text"
        );
        // Empty body
        assert_eq!(sync_h1_in_body("", "New Title"), "# New Title\n\n");
        // Preserve trailing newline
        assert_eq!(
            sync_h1_in_body("# Old Title\n\nBody\n", "New Title"),
            "# New Title\n\nBody\n"
        );
        // H1 with leading blank lines
        assert_eq!(
            sync_h1_in_body("\n\n# Old Title\n\nBody", "New Title"),
            "\n\n# New Title\n\nBody"
        );
    }
}