Skip to main content

file_desktop/
lib.rs

1// {── lib ─────────────────────────────────────────────────────────────────────
2#![warn(
3    missing_docs,
4    missing_debug_implementations,
5    private_interfaces,
6    private_bounds,
7    rustdoc::private_intra_doc_links
8)]
9
10//! # Desktop File Parser and Manager
11//!
12//! A Rust crate for constructing, parsing, mutating, and serializing
13//! [Desktop Entry files](https://specifications.freedesktop.org/desktop-entry-spec/latest/)
14//! as defined by the XDG Desktop Entry Specification.
15//!
16//! ## Overview
17//!
18//! The crate exposes owned document, group, entry, and key/value types for `.desktop`
19//! content. It supports creating new desktop entry documents in memory, parsing existing
20//! UTF-8 text with line-oriented parsing, mutating groups and entries,
21//! and formatting the result back into desktop-entry syntax.
22//!
23//! ## Core Features
24//!
25//! - Strongly typed representations of desktop entry documents, groups, keys, and values
26//! - Parsing through [`std::str::FromStr`]
27//! - Version-aware key filtering for Desktop Entry Specification versions 1.0 through 1.5
28//! - Explicit error types for parse and mutation failures
29//! - Comment normalization that prefixes non-blank lines with `# ` and preserves blank lines
30//!
31//! ## Modules
32//!
33//! - [`desktop`] - Main `DesktopFile` struct and desktop entry management
34//! - [`entry`] - Core entry types: `Entry`, `AnnotatedEntry`, and `LocalizedValue`
35//! - [`entry_group`] - Entry group types: `EntryGroup`, `GroupName`, and `KeyUniqueness`
36//! - [`error`] - Error types for parsing and manipulation failures
37//! - [`key`] - Desktop Entry keys and specification version management
38//! - [`iter`] - Iterator adapters for key filtering by specification version
39//!
40//! ## Quick Start
41//!
42//! ```rust
43//! use file_desktop::desktop::{DesktopFile, DesktopFileType};
44//! use file_desktop::entry::{AnnotatedEntry, Entry};
45//!
46//! let name = "MyApp".try_into().unwrap();
47//! let mut desktop_file = DesktopFile::new(name, DesktopFileType::Application);
48//!
49//! assert_eq!(
50//!     desktop_file.to_string(),
51//!     "[Desktop Entry]\nType=Application\nName=MyApp"
52//! );
53//! ```
54//!
55//! ## Parsing
56//!
57//! - [`std::str::FromStr`] parses line-oriented input without trimming the full line first.
58//!   It trims trailing whitespace from the key and leading whitespace from the value
59//!   after splitting on the first `=`, but rejects lines that begin with a literal
60//!   space character before classification.
61//!
62//! The parser trims the key and value around the first `=` and requires a
63//!  `[Desktop Entry]` group before returning success. It uses the original line for
64//!  blank-line detection, so whitespace-only lines are rejected rather than normalized into
65//!  empty lines.
66//!
67//! ## Example: Creating a Complete Desktop Entry
68//!
69//! ```rust
70//! use file_desktop::desktop::{DesktopFile, DesktopFileType};
71//! use file_desktop::entry::{AnnotatedEntry, Entry};
72//!
73//! let name = "MyApp".try_into().unwrap();
74//! let exec = "/usr/bin/myapp".try_into().unwrap();
75//! let mut desktop_file = DesktopFile::new(name, DesktopFileType::Application);
76//! desktop_file
77//!     .try_add_entry("Desktop Entry", AnnotatedEntry::new(Entry::Exec(exec)))
78//!     .unwrap();
79//!
80//! assert_eq!(
81//!     desktop_file.to_string(),
82//!     "[Desktop Entry]\nType=Application\nName=MyApp\nExec=/usr/bin/myapp"
83//! );
84//! ```
85
86pub mod desktop;
87pub mod entry;
88pub mod entry_group;
89pub mod error;
90pub mod iter;
91pub mod key;
92
93// }{── Private helpers ────────────────────────────────────────────────────────
94/// Normalizes comment text into the serialized form used by this crate.
95///
96/// Each non-blank line is prefixed with `# `, blank lines are preserved, and
97/// appended content is separated with newline characters when needed.
98#[inline]
99pub(crate) fn format_comment(comment: &mut String, string: &str) {
100    for line in string.lines() {
101        let is_blank = line.trim().is_empty();
102
103        if comment.is_empty() {
104            if is_blank {
105                comment.push('\n');
106            } else {
107                comment.push_str("# ");
108                comment.push_str(line);
109            }
110            continue;
111        }
112
113        if is_blank {
114            if !comment.ends_with('\n') {
115                comment.push('\n');
116            }
117            comment.push('\n');
118            continue;
119        }
120
121        if !comment.ends_with('\n') {
122            comment.push('\n');
123        }
124        comment.push_str("# ");
125        comment.push_str(line);
126    }
127
128    if string.ends_with('\n') && !comment.ends_with('\n') {
129        comment.push('\n');
130    }
131}
132
133// }{── Tests ──────────────────────────────────────────────────────────────────
134
135#[cfg(test)]
136mod tests_format_comment {
137    use super::*;
138
139    // Legacy tests for backward compatibility
140    #[test]
141    fn test_comment_empty_new_line() {
142        let mut comment = String::new();
143        format_comment(&mut comment, "\nTest line");
144        assert_eq!("\n# Test line", comment);
145    }
146
147    #[test]
148    fn test_comment_empty_not_new_line() {
149        let mut comment = String::new();
150        let string = "Test format comment first line";
151        format_comment(&mut comment, string);
152        assert_eq!("# Test format comment first line", comment);
153    }
154
155    #[test]
156    fn test_comment_not_empty_end_not_new_line() {
157        let mut comment = String::new();
158
159        let string = "Test format comment first line";
160        format_comment(&mut comment, string);
161        assert_eq!("# Test format comment first line", comment);
162
163        let second_line = "Test format comment second line";
164        format_comment(&mut comment, second_line);
165        assert_eq!(
166            "# Test format comment first line\n# Test format comment second line",
167            comment
168        );
169    }
170
171    #[test]
172    fn test_comment_not_empty_end_new_line() {
173        let mut comment = String::new();
174        format_comment(&mut comment, "\n");
175        assert_eq!("\n", comment);
176
177        let line = "Test format comment line";
178        format_comment(&mut comment, line);
179        assert_eq!("\n# Test format comment line", comment);
180
181        let mut comment = String::new();
182        format_comment(&mut comment, "Test format comment first line\n");
183        assert_eq!("# Test format comment first line\n", comment);
184
185        let second_line = "Test format comment second line";
186        format_comment(&mut comment, second_line);
187        assert_eq!(
188            "# Test format comment first line\n# Test format comment second line",
189            comment
190        );
191    }
192
193    #[test]
194    fn test_format_two_new_line() {
195        let mut comment = String::new();
196        let string = "Test format comment first line\nTest format comment second line\n\n";
197
198        format_comment(&mut comment, string);
199
200        assert_eq!(
201            "# Test format comment first line\n# Test format comment second line\n\n",
202            comment
203        );
204
205        let mut comment = String::new();
206        let first_string =
207            "\n\nTest format comment first line\n\nTest format comment second line\n\n";
208        format_comment(&mut comment, first_string);
209        let second_string = "\n\nTest format comment second string, first line\n\nTest format comment second, second line\n\n";
210
211        format_comment(&mut comment, second_string);
212
213        assert_eq!(
214            "\n\n# Test format comment first line\n\n# Test format comment second line\n\n\
215            \n\n# Test format comment second string, first line\n\n# Test format comment second, second line\n\n",
216            comment
217        );
218    }
219
220    // ===== Comprehensive Table-Driven Tests for XDG Desktop Entry Specification V1.1 =====
221    //
222    // These tests verify:
223    // 1. **Preservation (Round-trip)**: Lines starting with # and blank lines preserved exactly
224    // 2. **Uninterpreted Content**: Any character (except LF/\n) allowed after #
225    // 3. **UTF-8 Support**: No corruption of multibyte UTF-8 strings
226    // 4. **Line Ending Constraint**: Proper handling of LF (\n) restrictions
227    // 5. **Blank Line Integrity**: Blank lines are not stripped, preserved as required
228
229    #[test]
230    fn test_format_comment_table_driven() {
231        // Test cases: (input, expected_output)
232        // Format: input -> formatted result
233        let test_cases: Vec<(&str, &str)> = vec![
234            // === Test 1: Preservation (Round-trip) ===
235            // 1a. Simple comment line
236            ("Simple comment", "# Simple comment"),
237            // 1b. Multiple lines preserving structure
238            ("Line 1\nLine 2", "# Line 1\n# Line 2"),
239            // 1c. Multiple lines with trailing newline
240            ("Line 1\nLine 2\n", "# Line 1\n# Line 2\n"),
241            // === Test 2: Uninterpreted Content (any character except LF allowed after #) ===
242            // 2a. Special characters after #
243            ("!@$%^&*()", "# !@$%^&*()"),
244            // 2b. Mixed symbols and text
245            ("key=value#test", "# key=value#test"),
246            // 2c. Punctuation and brackets
247            ("[test] {data} <xml>", "# [test] {data} <xml>"),
248            // 2d. Forward and backward slashes
249            (
250                "/path/to/file\\windows\\path",
251                "# /path/to/file\\windows\\path",
252            ),
253            // 2e. Equals and colons (common in desktop files)
254            (
255                "Name=Application:Version:1.0",
256                "# Name=Application:Version:1.0",
257            ),
258            // 2f. Double quotes and single quotes
259            (
260                "name=\"value\" and 'quoted'",
261                "# name=\"value\" and 'quoted'",
262            ),
263            // 2g. Semicolons and commas (list separators)
264            (
265                "item1;item2;item3, and more",
266                "# item1;item2;item3, and more",
267            ),
268            // 2h. Plus, minus, multiplication, division
269            (
270                "Calculate: 2+2=4, 5-3=2, 3*2=6, 8/2=4",
271                "# Calculate: 2+2=4, 5-3=2, 3*2=6, 8/2=4",
272            ),
273            // 2i. Underscore and hyphen
274            ("my_variable-name", "# my_variable-name"),
275            // 2j. Percentage and at signs
276            ("100% complete @everyone", "# 100% complete @everyone"),
277            // 2k. Question mark and exclamation
278            ("What? Why! How?", "# What? Why! How?"),
279            // 2l. Tilde and backtick
280            ("~home `command`", "# ~home `command`"),
281            // 2m. Caret and dot
282            ("^start .end", "# ^start .end"),
283            // 2n. Pipe and ampersand
284            (
285                "process1 | process2 && process3",
286                "# process1 | process2 && process3",
287            ),
288            // === Test 3: UTF-8 Support (Non-ASCII characters) ===
289            // 3a. Basic Latin Extended (accented characters)
290            ("Café résumé naïve", "# Café résumé naïve"),
291            // 3b. Greek characters
292            ("Ελληνικά γράμματα", "# Ελληνικά γράμματα"),
293            // 3c. Cyrillic characters
294            ("Русский текст", "# Русский текст"),
295            // 3d. Arabic characters
296            ("النص العربي", "# النص العربي"),
297            // 3e. Chinese characters
298            ("中文文本", "# 中文文本"),
299            // 3f. Japanese hiragana and katakana
300            ("ひらがなカタカナ", "# ひらがなカタカナ"),
301            // 3g. Korean characters
302            ("한국어 텍스트", "# 한국어 텍스트"),
303            // 3h. Hebrew characters
304            ("טקסט עברי", "# טקסט עברי"),
305            // 3i. Emoji and symbols (UTF-8 multi-byte)
306            (
307                "Test ✓ Pass ✗ Fail 🚀 Rocket",
308                "# Test ✓ Pass ✗ Fail 🚀 Rocket",
309            ),
310            // 3j. Mixed scripts
311            (
312                "English 日本語 Русский العربية",
313                "# English 日本語 Русский العربية",
314            ),
315            // 3k. Combining diacriticals
316            ("e̊ (combining ring above)", "# e̊ (combining ring above)"),
317            // 3l. UTF-8 with special punctuation
318            (
319                "…ellipsis « quote » guillemets",
320                "# …ellipsis « quote » guillemets",
321            ),
322            // === Test 4: Line Ending Constraint (LF handling) ===
323            // 4a. Single line with trailing LF
324            ("First line\n", "# First line\n"),
325            // 4b. Multiple lines each with LF
326            ("Line 1\nLine 2\nLine 3\n", "# Line 1\n# Line 2\n# Line 3\n"),
327            // 4c. Empty comment with leading blank line preserved
328            ("\n", "\n"),
329            // 4d. Multiple leading blank lines
330            ("\n\n", "\n\n"),
331            // 4e. Leading blank line followed by content
332            ("\nContent", "\n# Content"),
333            // 4f. Content followed by blank lines
334            ("Content\n\n", "# Content\n\n"),
335            // === Test 5: Blank Line Integrity ===
336            // 5a. Single blank line between content preserved
337            ("Line 1\n\nLine 2", "# Line 1\n\n# Line 2"),
338            // 5b. Multiple blank lines preserved
339            ("Start\n\n\nEnd", "# Start\n\n\n# End"),
340            // 5c. Blank lines with trailing newline
341            ("A\n\nB\n", "# A\n\n# B\n"),
342            // 5d. Only blank lines (spaces and tabs are considered blank)
343            ("\n   \n\t\n", "\n\n\n"),
344            // 5e. Blank line separating different types of content
345            ("Title\n\nAuthor\n\nDesc", "# Title\n\n# Author\n\n# Desc"),
346            // 5f. Mixed blank and non-blank with UTF-8
347            (
348                "Item 1\n\nЦифра 2\n\n三項目",
349                "# Item 1\n\n# Цифра 2\n\n# 三項目",
350            ),
351            // === Test 6: Complex Real-World Scenarios ===
352            // 6a. Desktop file comment block
353            (
354                "Application launcher\nVersion: 1.0",
355                "# Application launcher\n# Version: 1.0",
356            ),
357            // 6b. Multiline desktop entry comment
358            (
359                "Name: Firefox\nExec: /usr/bin/firefox\nIcon: firefox",
360                "# Name: Firefox\n# Exec: /usr/bin/firefox\n# Icon: firefox",
361            ),
362            // 6c. Comment with URLs and paths
363            (
364                "Homepage: https://example.com/path?query=1&other=2\nPath: /usr/share/icons",
365                "# Homepage: https://example.com/path?query=1&other=2\n# Path: /usr/share/icons",
366            ),
367            // 6d. Comment with configuration-style entries
368            (
369                "key1=value1\nkey2=value2;value3;value4",
370                "# key1=value1\n# key2=value2;value3;value4",
371            ),
372            // 6e. Comment with categories and actions
373            (
374                "Categories=Network;WebBrowser\nActions=NewWindow;NewPrivateWindow;",
375                "# Categories=Network;WebBrowser\n# Actions=NewWindow;NewPrivateWindow;",
376            ),
377            // 6f. Full desktop entry comment with blank lines
378            (
379                "Name=MyApp\nVersion=2.0\n\nAuthor=Me\nLicense=MIT",
380                "# Name=MyApp\n# Version=2.0\n\n# Author=Me\n# License=MIT",
381            ),
382            // 6g. Comment with localized strings
383            (
384                "Name[en_US]=American App\nName[de_DE]=Deutsches Programm",
385                "# Name[en_US]=American App\n# Name[de_DE]=Deutsches Programm",
386            ),
387            // 6h. URL with special characters preserved
388            (
389                "Icon-URL: file:///home/user/Pictures/icon%20with%20spaces.png",
390                "# Icon-URL: file:///home/user/Pictures/icon%20with%20spaces.png",
391            ),
392            // === Test 7: Edge Cases ===
393            // 7a. Single space (treated as blank line due to trim())
394            (" ", "\n"),
395            // 7b. Multiple spaces (treated as blank line due to trim())
396            ("   ", "\n"),
397            // 7c. Tab character (treated as blank line due to trim())
398            ("\t", "\n"),
399            // 7d. Multiple tabs (treated as blank line due to trim())
400            ("\t\t\t", "\n"),
401            // 7e. Mixed whitespace (treated as blank line due to trim())
402            (" \t \t ", "\n"),
403            // 7f. Very long line
404            (
405                "This is a very long comment line that contains many characters and should \
406              be preserved exactly as-is without truncation or modification in any way \
407              because the spec requires uninterpreted content",
408                "# This is a very long comment line that contains many characters and should \
409              be preserved exactly as-is without truncation or modification in any way \
410              because the spec requires uninterpreted content",
411            ),
412            // 7g. Empty string
413            ("", ""),
414            // 7h. Null-like strings (just whitespace lines)
415            ("   \n   ", "\n\n"),
416        ];
417
418        for (input, expected) in test_cases {
419            let mut comment = String::new();
420            format_comment(&mut comment, input);
421            assert_eq!(
422                expected, comment,
423                "Failed for input: {:?}\nExpected: {:?}\nGot: {:?}",
424                input, expected, comment
425            );
426        }
427    }
428
429    #[test]
430    fn test_format_comment_cumulative_calls() {
431        // Test that multiple calls accumulate correctly (round-trip preservation)
432        let mut comment = String::new();
433
434        // First call: add initial comment
435        format_comment(&mut comment, "Line 1");
436        assert_eq!("# Line 1", comment);
437
438        // Second call: add another line
439        format_comment(&mut comment, "Line 2");
440        assert_eq!("# Line 1\n# Line 2", comment);
441
442        // Third call: add blank line
443        format_comment(&mut comment, "");
444        assert_eq!("# Line 1\n# Line 2", comment);
445
446        // Fourth call: add line after blank
447        format_comment(&mut comment, "Line 3");
448        assert_eq!("# Line 1\n# Line 2\n# Line 3", comment);
449    }
450
451    #[test]
452    fn test_format_comment_utf8_preservation() {
453        // Test that UTF-8 multibyte characters are not corrupted across multiple calls
454        let mut comment = String::new();
455
456        // Add first UTF-8 content
457        format_comment(&mut comment, "Café ☕");
458        assert_eq!("# Café ☕", comment);
459
460        // Add second UTF-8 content
461        format_comment(&mut comment, "日本語テキスト");
462        assert_eq!("# Café ☕\n# 日本語テキスト", comment);
463
464        // Verify no UTF-8 corruption by counting bytes
465        let bytes = comment.as_bytes();
466        // Should contain proper UTF-8 encoded characters, not truncated
467        assert!(
468            bytes.len() > "# Caf Japanese ".len(),
469            "UTF-8 content appears corrupted"
470        );
471    }
472
473    #[test]
474    fn test_format_comment_specification_invariants() {
475        // Test that key invariants from XDG Desktop Entry Spec V1.1 are maintained:
476        // - Comments start with # (hashmark)
477        // - Blank lines are preserved
478        // - No LF corruption within lines
479
480        let mut comment = String::new();
481        format_comment(&mut comment, "Test\nMultiple\n");
482
483        // Invariant 1: Non-blank lines start with "# "
484        for line in comment.lines() {
485            if !line.is_empty() {
486                assert!(
487                    line.starts_with("# "),
488                    "Non-blank line should start with '# ': {:?}",
489                    line
490                );
491            }
492        }
493
494        // Invariant 2: Result should end with \n if input ends with \n, or nothing if not
495        assert!(
496            comment.ends_with('\n'),
497            "Comment should end with newline since input did"
498        );
499
500        let mut comment2 = String::new();
501        format_comment(&mut comment2, "No trailing newline");
502        assert!(
503            !comment2.ends_with('\n'),
504            "Comment should not end with newline since input didn't"
505        );
506    }
507
508    #[test]
509    fn test_format_comment_multiline_utf8_round_trip() {
510        // Test complete round-trip with UTF-8, blank lines, and special characters
511        let input = "Title: 应用程序\nVersion: 2.0\n\nAuthor: José García\nStatus: ✓ Complete";
512        let mut comment = String::new();
513        format_comment(&mut comment, input);
514
515        // Verify structure is preserved
516        let lines: Vec<&str> = comment.lines().collect();
517        assert!(
518            lines.len() >= 5,
519            "Should have at least 5 lines (including blank)"
520        );
521
522        // Verify all non-blank lines start with "# "
523        for (i, line) in lines.iter().enumerate() {
524            if !line.is_empty() {
525                assert!(
526                    line.starts_with("# "),
527                    "Line {} should start with '# ': {:?}",
528                    i + 1,
529                    line
530                );
531            }
532        }
533
534        // Verify UTF-8 characters are intact
535        assert!(
536            comment.contains("应用程序"),
537            "Chinese characters should be preserved"
538        );
539        assert!(comment.contains("2.0"), "Version should be preserved");
540        assert!(
541            comment.contains("José García"),
542            "Accented characters should be preserved"
543        );
544        assert!(
545            comment.contains("✓"),
546            "Checkmark symbol should be preserved"
547        );
548    }
549
550    #[test]
551    fn test_format_comment_special_characters_not_escaped() {
552        // Verify that special characters are NOT escaped or modified
553        // (per spec: uninterpreted content after #)
554        let special_inputs = vec![
555            "URL: http://example.com?foo=bar&baz=qux",
556            "Regex: ^[a-zA-Z0-9]+$",
557            "Path: C:\\Program Files\\App\\",
558            "Math: 2+2=4, sqrt(16)=4",
559            "Logic: if (x > 5 && y < 10) { action(); }",
560            "Quotes: 'single' and \"double\"",
561            "Brackets: (round) [square] {curly} <angle>",
562            "Symbols: @mention #hashtag $variable %percent ^exponent",
563        ];
564
565        for input in special_inputs {
566            let mut comment = String::new();
567            format_comment(&mut comment, input);
568
569            // Extract content after "# "
570            let content = comment.strip_prefix("# ").unwrap_or("");
571            assert_eq!(
572                input, content,
573                "Special characters should not be escaped or modified"
574            );
575        }
576    }
577
578    #[test]
579    fn test_format_comment_blank_line_preservation() {
580        // Specifically test that blank lines are preserved as required by spec
581        let test_cases = vec![
582            // (input, expected_output, description)
583            ("\n", "\n", "Single leading blank line"),
584            ("\n\n", "\n\n", "Multiple leading blank lines"),
585            ("text\n\nmore", "# text\n\n# more", "Blank line in middle"),
586            (
587                "a\n\n\nb",
588                "# a\n\n\n# b",
589                "Multiple consecutive blank lines",
590            ),
591            (
592                "x\n\n\n\ny",
593                "# x\n\n\n\n# y",
594                "Four consecutive blank lines",
595            ),
596        ];
597
598        for (input, expected, description) in test_cases {
599            let mut comment = String::new();
600            format_comment(&mut comment, input);
601            assert_eq!(expected, comment, "Failed: {}", description);
602        }
603    }
604}
605
606// }────────────────────────────────────────────────────────────────────────────