file_desktop 0.1.0

Parse, inspect, and build XDG .desktop files in Rust
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
// {── lib ─────────────────────────────────────────────────────────────────────
#![warn(
    missing_docs,
    missing_debug_implementations,
    private_interfaces,
    private_bounds,
    rustdoc::private_intra_doc_links
)]

//! # Desktop File Parser and Manager
//!
//! A Rust crate for constructing, parsing, mutating, and serializing
//! [Desktop Entry files](https://specifications.freedesktop.org/desktop-entry-spec/latest/)
//! as defined by the XDG Desktop Entry Specification.
//!
//! ## Overview
//!
//! The crate exposes owned document, group, entry, and key/value types for `.desktop`
//! content. It supports creating new desktop entry documents in memory, parsing existing
//! UTF-8 text with line-oriented parsing, mutating groups and entries,
//! and formatting the result back into desktop-entry syntax.
//!
//! ## Core Features
//!
//! - Strongly typed representations of desktop entry documents, groups, keys, and values
//! - Parsing through [`std::str::FromStr`]
//! - Version-aware key filtering for Desktop Entry Specification versions 1.0 through 1.5
//! - Explicit error types for parse and mutation failures
//! - Comment normalization that prefixes non-blank lines with `# ` and preserves blank lines
//!
//! ## Modules
//!
//! - [`desktop`] - Main `DesktopFile` struct and desktop entry management
//! - [`entry`] - Core entry types: `Entry`, `AnnotatedEntry`, and `LocalizedValue`
//! - [`entry_group`] - Entry group types: `EntryGroup`, `GroupName`, and `KeyUniqueness`
//! - [`error`] - Error types for parsing and manipulation failures
//! - [`key`] - Desktop Entry keys and specification version management
//! - [`iter`] - Iterator adapters for key filtering by specification version
//!
//! ## Quick Start
//!
//! ```rust
//! use file_desktop::desktop::{DesktopFile, DesktopFileType};
//! use file_desktop::entry::{AnnotatedEntry, Entry};
//!
//! let name = "MyApp".try_into().unwrap();
//! let mut desktop_file = DesktopFile::new(name, DesktopFileType::Application);
//!
//! assert_eq!(
//!     desktop_file.to_string(),
//!     "[Desktop Entry]\nType=Application\nName=MyApp"
//! );
//! ```
//!
//! ## Parsing
//!
//! - [`std::str::FromStr`] parses line-oriented input without trimming the full line first.
//!   It trims trailing whitespace from the key and leading whitespace from the value
//!   after splitting on the first `=`, but rejects lines that begin with a literal
//!   space character before classification.
//!
//! The parser trims the key and value around the first `=` and requires a
//!  `[Desktop Entry]` group before returning success. It uses the original line for
//!  blank-line detection, so whitespace-only lines are rejected rather than normalized into
//!  empty lines.
//!
//! ## Example: Creating a Complete Desktop Entry
//!
//! ```rust
//! use file_desktop::desktop::{DesktopFile, DesktopFileType};
//! use file_desktop::entry::{AnnotatedEntry, Entry};
//!
//! let name = "MyApp".try_into().unwrap();
//! let exec = "/usr/bin/myapp".try_into().unwrap();
//! let mut desktop_file = DesktopFile::new(name, DesktopFileType::Application);
//! desktop_file
//!     .try_add_entry("Desktop Entry", AnnotatedEntry::new(Entry::Exec(exec)))
//!     .unwrap();
//!
//! assert_eq!(
//!     desktop_file.to_string(),
//!     "[Desktop Entry]\nType=Application\nName=MyApp\nExec=/usr/bin/myapp"
//! );
//! ```

pub mod desktop;
pub mod entry;
pub mod entry_group;
pub mod error;
pub mod iter;
pub mod key;

// }{── Private helpers ────────────────────────────────────────────────────────
/// Normalizes comment text into the serialized form used by this crate.
///
/// Each non-blank line is prefixed with `# `, blank lines are preserved, and
/// appended content is separated with newline characters when needed.
#[inline]
pub(crate) fn format_comment(comment: &mut String, string: &str) {
    for line in string.lines() {
        let is_blank = line.trim().is_empty();

        if comment.is_empty() {
            if is_blank {
                comment.push('\n');
            } else {
                comment.push_str("# ");
                comment.push_str(line);
            }
            continue;
        }

        if is_blank {
            if !comment.ends_with('\n') {
                comment.push('\n');
            }
            comment.push('\n');
            continue;
        }

        if !comment.ends_with('\n') {
            comment.push('\n');
        }
        comment.push_str("# ");
        comment.push_str(line);
    }

    if string.ends_with('\n') && !comment.ends_with('\n') {
        comment.push('\n');
    }
}

// }{── Tests ──────────────────────────────────────────────────────────────────

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

    // Legacy tests for backward compatibility
    #[test]
    fn test_comment_empty_new_line() {
        let mut comment = String::new();
        format_comment(&mut comment, "\nTest line");
        assert_eq!("\n# Test line", comment);
    }

    #[test]
    fn test_comment_empty_not_new_line() {
        let mut comment = String::new();
        let string = "Test format comment first line";
        format_comment(&mut comment, string);
        assert_eq!("# Test format comment first line", comment);
    }

    #[test]
    fn test_comment_not_empty_end_not_new_line() {
        let mut comment = String::new();

        let string = "Test format comment first line";
        format_comment(&mut comment, string);
        assert_eq!("# Test format comment first line", comment);

        let second_line = "Test format comment second line";
        format_comment(&mut comment, second_line);
        assert_eq!(
            "# Test format comment first line\n# Test format comment second line",
            comment
        );
    }

    #[test]
    fn test_comment_not_empty_end_new_line() {
        let mut comment = String::new();
        format_comment(&mut comment, "\n");
        assert_eq!("\n", comment);

        let line = "Test format comment line";
        format_comment(&mut comment, line);
        assert_eq!("\n# Test format comment line", comment);

        let mut comment = String::new();
        format_comment(&mut comment, "Test format comment first line\n");
        assert_eq!("# Test format comment first line\n", comment);

        let second_line = "Test format comment second line";
        format_comment(&mut comment, second_line);
        assert_eq!(
            "# Test format comment first line\n# Test format comment second line",
            comment
        );
    }

    #[test]
    fn test_format_two_new_line() {
        let mut comment = String::new();
        let string = "Test format comment first line\nTest format comment second line\n\n";

        format_comment(&mut comment, string);

        assert_eq!(
            "# Test format comment first line\n# Test format comment second line\n\n",
            comment
        );

        let mut comment = String::new();
        let first_string =
            "\n\nTest format comment first line\n\nTest format comment second line\n\n";
        format_comment(&mut comment, first_string);
        let second_string = "\n\nTest format comment second string, first line\n\nTest format comment second, second line\n\n";

        format_comment(&mut comment, second_string);

        assert_eq!(
            "\n\n# Test format comment first line\n\n# Test format comment second line\n\n\
            \n\n# Test format comment second string, first line\n\n# Test format comment second, second line\n\n",
            comment
        );
    }

    // ===== Comprehensive Table-Driven Tests for XDG Desktop Entry Specification V1.1 =====
    //
    // These tests verify:
    // 1. **Preservation (Round-trip)**: Lines starting with # and blank lines preserved exactly
    // 2. **Uninterpreted Content**: Any character (except LF/\n) allowed after #
    // 3. **UTF-8 Support**: No corruption of multibyte UTF-8 strings
    // 4. **Line Ending Constraint**: Proper handling of LF (\n) restrictions
    // 5. **Blank Line Integrity**: Blank lines are not stripped, preserved as required

    #[test]
    fn test_format_comment_table_driven() {
        // Test cases: (input, expected_output)
        // Format: input -> formatted result
        let test_cases: Vec<(&str, &str)> = vec![
            // === Test 1: Preservation (Round-trip) ===
            // 1a. Simple comment line
            ("Simple comment", "# Simple comment"),
            // 1b. Multiple lines preserving structure
            ("Line 1\nLine 2", "# Line 1\n# Line 2"),
            // 1c. Multiple lines with trailing newline
            ("Line 1\nLine 2\n", "# Line 1\n# Line 2\n"),
            // === Test 2: Uninterpreted Content (any character except LF allowed after #) ===
            // 2a. Special characters after #
            ("!@$%^&*()", "# !@$%^&*()"),
            // 2b. Mixed symbols and text
            ("key=value#test", "# key=value#test"),
            // 2c. Punctuation and brackets
            ("[test] {data} <xml>", "# [test] {data} <xml>"),
            // 2d. Forward and backward slashes
            (
                "/path/to/file\\windows\\path",
                "# /path/to/file\\windows\\path",
            ),
            // 2e. Equals and colons (common in desktop files)
            (
                "Name=Application:Version:1.0",
                "# Name=Application:Version:1.0",
            ),
            // 2f. Double quotes and single quotes
            (
                "name=\"value\" and 'quoted'",
                "# name=\"value\" and 'quoted'",
            ),
            // 2g. Semicolons and commas (list separators)
            (
                "item1;item2;item3, and more",
                "# item1;item2;item3, and more",
            ),
            // 2h. Plus, minus, multiplication, division
            (
                "Calculate: 2+2=4, 5-3=2, 3*2=6, 8/2=4",
                "# Calculate: 2+2=4, 5-3=2, 3*2=6, 8/2=4",
            ),
            // 2i. Underscore and hyphen
            ("my_variable-name", "# my_variable-name"),
            // 2j. Percentage and at signs
            ("100% complete @everyone", "# 100% complete @everyone"),
            // 2k. Question mark and exclamation
            ("What? Why! How?", "# What? Why! How?"),
            // 2l. Tilde and backtick
            ("~home `command`", "# ~home `command`"),
            // 2m. Caret and dot
            ("^start .end", "# ^start .end"),
            // 2n. Pipe and ampersand
            (
                "process1 | process2 && process3",
                "# process1 | process2 && process3",
            ),
            // === Test 3: UTF-8 Support (Non-ASCII characters) ===
            // 3a. Basic Latin Extended (accented characters)
            ("Café résumé naïve", "# Café résumé naïve"),
            // 3b. Greek characters
            ("Ελληνικά γράμματα", "# Ελληνικά γράμματα"),
            // 3c. Cyrillic characters
            ("Русский текст", "# Русский текст"),
            // 3d. Arabic characters
            ("النص العربي", "# النص العربي"),
            // 3e. Chinese characters
            ("中文文本", "# 中文文本"),
            // 3f. Japanese hiragana and katakana
            ("ひらがなカタカナ", "# ひらがなカタカナ"),
            // 3g. Korean characters
            ("한국어 텍스트", "# 한국어 텍스트"),
            // 3h. Hebrew characters
            ("טקסט עברי", "# טקסט עברי"),
            // 3i. Emoji and symbols (UTF-8 multi-byte)
            (
                "Test ✓ Pass ✗ Fail 🚀 Rocket",
                "# Test ✓ Pass ✗ Fail 🚀 Rocket",
            ),
            // 3j. Mixed scripts
            (
                "English 日本語 Русский العربية",
                "# English 日本語 Русский العربية",
            ),
            // 3k. Combining diacriticals
            ("e̊ (combining ring above)", "# e̊ (combining ring above)"),
            // 3l. UTF-8 with special punctuation
            (
                "…ellipsis « quote » guillemets",
                "# …ellipsis « quote » guillemets",
            ),
            // === Test 4: Line Ending Constraint (LF handling) ===
            // 4a. Single line with trailing LF
            ("First line\n", "# First line\n"),
            // 4b. Multiple lines each with LF
            ("Line 1\nLine 2\nLine 3\n", "# Line 1\n# Line 2\n# Line 3\n"),
            // 4c. Empty comment with leading blank line preserved
            ("\n", "\n"),
            // 4d. Multiple leading blank lines
            ("\n\n", "\n\n"),
            // 4e. Leading blank line followed by content
            ("\nContent", "\n# Content"),
            // 4f. Content followed by blank lines
            ("Content\n\n", "# Content\n\n"),
            // === Test 5: Blank Line Integrity ===
            // 5a. Single blank line between content preserved
            ("Line 1\n\nLine 2", "# Line 1\n\n# Line 2"),
            // 5b. Multiple blank lines preserved
            ("Start\n\n\nEnd", "# Start\n\n\n# End"),
            // 5c. Blank lines with trailing newline
            ("A\n\nB\n", "# A\n\n# B\n"),
            // 5d. Only blank lines (spaces and tabs are considered blank)
            ("\n   \n\t\n", "\n\n\n"),
            // 5e. Blank line separating different types of content
            ("Title\n\nAuthor\n\nDesc", "# Title\n\n# Author\n\n# Desc"),
            // 5f. Mixed blank and non-blank with UTF-8
            (
                "Item 1\n\nЦифра 2\n\n三項目",
                "# Item 1\n\n# Цифра 2\n\n# 三項目",
            ),
            // === Test 6: Complex Real-World Scenarios ===
            // 6a. Desktop file comment block
            (
                "Application launcher\nVersion: 1.0",
                "# Application launcher\n# Version: 1.0",
            ),
            // 6b. Multiline desktop entry comment
            (
                "Name: Firefox\nExec: /usr/bin/firefox\nIcon: firefox",
                "# Name: Firefox\n# Exec: /usr/bin/firefox\n# Icon: firefox",
            ),
            // 6c. Comment with URLs and paths
            (
                "Homepage: https://example.com/path?query=1&other=2\nPath: /usr/share/icons",
                "# Homepage: https://example.com/path?query=1&other=2\n# Path: /usr/share/icons",
            ),
            // 6d. Comment with configuration-style entries
            (
                "key1=value1\nkey2=value2;value3;value4",
                "# key1=value1\n# key2=value2;value3;value4",
            ),
            // 6e. Comment with categories and actions
            (
                "Categories=Network;WebBrowser\nActions=NewWindow;NewPrivateWindow;",
                "# Categories=Network;WebBrowser\n# Actions=NewWindow;NewPrivateWindow;",
            ),
            // 6f. Full desktop entry comment with blank lines
            (
                "Name=MyApp\nVersion=2.0\n\nAuthor=Me\nLicense=MIT",
                "# Name=MyApp\n# Version=2.0\n\n# Author=Me\n# License=MIT",
            ),
            // 6g. Comment with localized strings
            (
                "Name[en_US]=American App\nName[de_DE]=Deutsches Programm",
                "# Name[en_US]=American App\n# Name[de_DE]=Deutsches Programm",
            ),
            // 6h. URL with special characters preserved
            (
                "Icon-URL: file:///home/user/Pictures/icon%20with%20spaces.png",
                "# Icon-URL: file:///home/user/Pictures/icon%20with%20spaces.png",
            ),
            // === Test 7: Edge Cases ===
            // 7a. Single space (treated as blank line due to trim())
            (" ", "\n"),
            // 7b. Multiple spaces (treated as blank line due to trim())
            ("   ", "\n"),
            // 7c. Tab character (treated as blank line due to trim())
            ("\t", "\n"),
            // 7d. Multiple tabs (treated as blank line due to trim())
            ("\t\t\t", "\n"),
            // 7e. Mixed whitespace (treated as blank line due to trim())
            (" \t \t ", "\n"),
            // 7f. Very long line
            (
                "This is a very long comment line that contains many characters and should \
              be preserved exactly as-is without truncation or modification in any way \
              because the spec requires uninterpreted content",
                "# This is a very long comment line that contains many characters and should \
              be preserved exactly as-is without truncation or modification in any way \
              because the spec requires uninterpreted content",
            ),
            // 7g. Empty string
            ("", ""),
            // 7h. Null-like strings (just whitespace lines)
            ("   \n   ", "\n\n"),
        ];

        for (input, expected) in test_cases {
            let mut comment = String::new();
            format_comment(&mut comment, input);
            assert_eq!(
                expected, comment,
                "Failed for input: {:?}\nExpected: {:?}\nGot: {:?}",
                input, expected, comment
            );
        }
    }

    #[test]
    fn test_format_comment_cumulative_calls() {
        // Test that multiple calls accumulate correctly (round-trip preservation)
        let mut comment = String::new();

        // First call: add initial comment
        format_comment(&mut comment, "Line 1");
        assert_eq!("# Line 1", comment);

        // Second call: add another line
        format_comment(&mut comment, "Line 2");
        assert_eq!("# Line 1\n# Line 2", comment);

        // Third call: add blank line
        format_comment(&mut comment, "");
        assert_eq!("# Line 1\n# Line 2", comment);

        // Fourth call: add line after blank
        format_comment(&mut comment, "Line 3");
        assert_eq!("# Line 1\n# Line 2\n# Line 3", comment);
    }

    #[test]
    fn test_format_comment_utf8_preservation() {
        // Test that UTF-8 multibyte characters are not corrupted across multiple calls
        let mut comment = String::new();

        // Add first UTF-8 content
        format_comment(&mut comment, "Café ☕");
        assert_eq!("# Café ☕", comment);

        // Add second UTF-8 content
        format_comment(&mut comment, "日本語テキスト");
        assert_eq!("# Café ☕\n# 日本語テキスト", comment);

        // Verify no UTF-8 corruption by counting bytes
        let bytes = comment.as_bytes();
        // Should contain proper UTF-8 encoded characters, not truncated
        assert!(
            bytes.len() > "# Caf Japanese ".len(),
            "UTF-8 content appears corrupted"
        );
    }

    #[test]
    fn test_format_comment_specification_invariants() {
        // Test that key invariants from XDG Desktop Entry Spec V1.1 are maintained:
        // - Comments start with # (hashmark)
        // - Blank lines are preserved
        // - No LF corruption within lines

        let mut comment = String::new();
        format_comment(&mut comment, "Test\nMultiple\n");

        // Invariant 1: Non-blank lines start with "# "
        for line in comment.lines() {
            if !line.is_empty() {
                assert!(
                    line.starts_with("# "),
                    "Non-blank line should start with '# ': {:?}",
                    line
                );
            }
        }

        // Invariant 2: Result should end with \n if input ends with \n, or nothing if not
        assert!(
            comment.ends_with('\n'),
            "Comment should end with newline since input did"
        );

        let mut comment2 = String::new();
        format_comment(&mut comment2, "No trailing newline");
        assert!(
            !comment2.ends_with('\n'),
            "Comment should not end with newline since input didn't"
        );
    }

    #[test]
    fn test_format_comment_multiline_utf8_round_trip() {
        // Test complete round-trip with UTF-8, blank lines, and special characters
        let input = "Title: 应用程序\nVersion: 2.0\n\nAuthor: José García\nStatus: ✓ Complete";
        let mut comment = String::new();
        format_comment(&mut comment, input);

        // Verify structure is preserved
        let lines: Vec<&str> = comment.lines().collect();
        assert!(
            lines.len() >= 5,
            "Should have at least 5 lines (including blank)"
        );

        // Verify all non-blank lines start with "# "
        for (i, line) in lines.iter().enumerate() {
            if !line.is_empty() {
                assert!(
                    line.starts_with("# "),
                    "Line {} should start with '# ': {:?}",
                    i + 1,
                    line
                );
            }
        }

        // Verify UTF-8 characters are intact
        assert!(
            comment.contains("应用程序"),
            "Chinese characters should be preserved"
        );
        assert!(comment.contains("2.0"), "Version should be preserved");
        assert!(
            comment.contains("José García"),
            "Accented characters should be preserved"
        );
        assert!(
            comment.contains("✓"),
            "Checkmark symbol should be preserved"
        );
    }

    #[test]
    fn test_format_comment_special_characters_not_escaped() {
        // Verify that special characters are NOT escaped or modified
        // (per spec: uninterpreted content after #)
        let special_inputs = vec![
            "URL: http://example.com?foo=bar&baz=qux",
            "Regex: ^[a-zA-Z0-9]+$",
            "Path: C:\\Program Files\\App\\",
            "Math: 2+2=4, sqrt(16)=4",
            "Logic: if (x > 5 && y < 10) { action(); }",
            "Quotes: 'single' and \"double\"",
            "Brackets: (round) [square] {curly} <angle>",
            "Symbols: @mention #hashtag $variable %percent ^exponent",
        ];

        for input in special_inputs {
            let mut comment = String::new();
            format_comment(&mut comment, input);

            // Extract content after "# "
            let content = comment.strip_prefix("# ").unwrap_or("");
            assert_eq!(
                input, content,
                "Special characters should not be escaped or modified"
            );
        }
    }

    #[test]
    fn test_format_comment_blank_line_preservation() {
        // Specifically test that blank lines are preserved as required by spec
        let test_cases = vec![
            // (input, expected_output, description)
            ("\n", "\n", "Single leading blank line"),
            ("\n\n", "\n\n", "Multiple leading blank lines"),
            ("text\n\nmore", "# text\n\n# more", "Blank line in middle"),
            (
                "a\n\n\nb",
                "# a\n\n\n# b",
                "Multiple consecutive blank lines",
            ),
            (
                "x\n\n\n\ny",
                "# x\n\n\n\n# y",
                "Four consecutive blank lines",
            ),
        ];

        for (input, expected, description) in test_cases {
            let mut comment = String::new();
            format_comment(&mut comment, input);
            assert_eq!(expected, comment, "Failed: {}", description);
        }
    }
}

// }────────────────────────────────────────────────────────────────────────────