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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
// {── Module ──────────────────────────────────────────────────────────────────
//! Defines crate-wide error types for Desktop Entry parsing and mutation operations.
//!
//! This module centralizes the public error surface used by higher-level components
//! such as `desktop`, `entry_group`, and `entry` so callers can handle failures with
//! stable, typed categories.
//!
//! Primary entry points are [`Error`] for top-level operations and
//! [`ParseEntryValueError`] for key-dependent value conversion.
//!
//! The parsing-related variants align with the
//! [XDG Desktop Entry Specification](https://specifications.freedesktop.org/desktop-entry-spec/latest/)
//! by enforcing strict key-dependent value forms, which prevents ambiguous
//! interpretation of booleans and `Type` values. File errors detected while
//! scanning input carry 1-based line numbers so callers can identify the
//! offending input line.
//!
//! # Invariants
//!
//! - Value parsing accepts UTF-8 text and does not decode backslash escapes.
//! - Multi-value keys are parsed as semicolon-delimited values.
//! - `Type` parsing accepts only `Application`, `Link`, or `Directory` with exact casing.
//! - Boolean parsing accepts only lowercase `true` or `false` as required by `bool::from_str`.

use std::fmt;
use std::io;
use std::sync::Arc;

// }{── Error ──────────────────────────────────────────────────────────────────

/// Represents failures emitted by desktop entry operations.
///
/// # Variants
///
/// - `AddActionsEntry` - An `Actions` entry could not be added
/// - `AddActionGroup` - An action group could not be added
/// - `InsertActionsEntry` - An `Actions` entry could not be inserted
/// - `EntryGroupExists` - A group with the requested name already exists
/// - `EntryGroupNotFound` - The requested group does not exist
/// - `RemoveEntry` - The requested entry could not be removed
/// - `RemoveRequiredEntry` - A required entry in the main group could not be removed
/// - `SwapEntry` - One or both entries to swap do not exist
/// - `Entry` - An entry operation failed
/// - `Group` - A group operation failed
/// - `ParseFileDesktop` - Desktop Entry document parsing failed
/// - `OpenFile` - Reading the desktop file failed
///
/// # Examples
///
/// ```rust
/// use file_desktop::error::Error;
///
/// let err: Error = std::io::Error::from(std::io::ErrorKind::NotFound).into();
///
/// assert!(matches!(
///     &err,
///     Error::OpenFile(source) if source.kind() == std::io::ErrorKind::NotFound
/// ));
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Error {
    /// An `Actions` entry cannot be added to the `[Desktop Entry]` group.
    AddActionsEntry,

    /// An action group cannot be added because it would violate the `Actions`
    /// entry association invariant.
    AddActionGroup,

    /// An `Actions` entry cannot be inserted into the `[Desktop Entry]` group.
    InsertActionsEntry,

    /// A group with the same name already exists.
    EntryGroupExists,

    /// No group with the requested name exists.
    EntryGroupNotFound,

    /// Removing an entry failed because no entry matched the requested key.
    RemoveEntry,

    /// Removing a required entry from the main `[Desktop Entry]` group was rejected.
    RemoveRequiredEntry,

    /// Swapping entries failed because one or both keys were absent.
    SwapEntry,

    /// An entry operation failed.
    Entry(EntryError),

    /// A group operation failed.
    Group(GroupError),

    /// Parsing a Desktop Entry document failed.
    ParseFileDesktop(ParseFileDesktopError),

    /// Reading a Desktop Entry file failed, preserving the underlying I/O error.
    OpenFile(Arc<io::Error>),
}

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::AddActionsEntry, Self::AddActionsEntry)
            | (Self::AddActionGroup, Self::AddActionGroup)
            | (Self::InsertActionsEntry, Self::InsertActionsEntry)
            | (Self::EntryGroupExists, Self::EntryGroupExists)
            | (Self::EntryGroupNotFound, Self::EntryGroupNotFound)
            | (Self::RemoveEntry, Self::RemoveEntry)
            | (Self::RemoveRequiredEntry, Self::RemoveRequiredEntry)
            | (Self::SwapEntry, Self::SwapEntry) => true,
            (Self::Entry(left), Self::Entry(right)) => left == right,
            (Self::Group(left), Self::Group(right)) => left == right,
            (Self::ParseFileDesktop(left), Self::ParseFileDesktop(right)) => left == right,
            (Self::OpenFile(left), Self::OpenFile(right)) => left.kind() == right.kind(),
            _ => false,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::AddActionsEntry => f.write_str("entry cannot be added to any group"),
            Self::InsertActionsEntry => f.write_str("entry cannot be inserted to any group"),
            Self::EntryGroupExists => f.write_str("entry group already exists"),
            Self::EntryGroupNotFound => f.write_str("entry group not found"),
            Self::AddActionGroup => f.write_str("failed to add an action group"),
            Self::RemoveEntry => f.write_str("failed to remove an entry"),
            Self::SwapEntry => f.write_str("failed to swap an entry"),
            Self::RemoveRequiredEntry => f.write_str("failed to remove required entry"),
            Self::Entry(kind) => write!(f, "{kind}"),
            Self::Group(kind) => write!(f, "{kind}"),
            Self::ParseFileDesktop(kind) => write!(f, "{kind}"),
            Self::OpenFile(source) => write!(f, "{source}"),
        }
    }
}

impl From<AppendKeyValueError> for Error {
    fn from(error: AppendKeyValueError) -> Self {
        Self::Entry(EntryError::AppendKeyValue(error))
    }
}

/// Converts an [`io::Error`] into [`Error::OpenFile`], preserving the complete
/// error as its source.
impl From<io::Error> for Error {
    fn from(error: io::Error) -> Self {
        Self::OpenFile(Arc::new(error))
    }
}

impl From<ParseEntryValueError> for Error {
    fn from(error: ParseEntryValueError) -> Self {
        Self::Entry(EntryError::Parse(ParseEntryError::ParseValue(error)))
    }
}

impl From<ParseKeyError> for Error {
    fn from(error: ParseKeyError) -> Self {
        Self::Entry(EntryError::Parse(ParseEntryError::ParseKey(error)))
    }
}

impl From<ParseEntryError> for Error {
    fn from(error: ParseEntryError) -> Self {
        Self::Entry(EntryError::Parse(error))
    }
}

impl From<ParseFileDesktopError> for Error {
    fn from(error: ParseFileDesktopError) -> Self {
        Self::ParseFileDesktop(error)
    }
}

impl From<GroupError> for Error {
    fn from(error: GroupError) -> Self {
        Self::Group(error)
    }
}

impl From<EntryError> for Error {
    fn from(error: EntryError) -> Self {
        Self::Entry(error)
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Entry(error) => Some(error),
            Self::Group(error) => Some(error),
            Self::ParseFileDesktop(error) => Some(error),
            Self::AddActionsEntry
            | Self::AddActionGroup
            | Self::InsertActionsEntry
            | Self::EntryGroupExists
            | Self::EntryGroupNotFound
            | Self::RemoveEntry
            | Self::RemoveRequiredEntry
            | Self::SwapEntry => None,
            Self::OpenFile(source) => Some(source),
        }
    }
}

// }{── AppendKeyValueError ────────────────────────────────────────────────────

/// Reports why appending a value to a list-valued entry fails.
///
/// The error occurs when [`AnnotatedEntry::try_append`](crate::entry::AnnotatedEntry::try_append)
/// is called for an entry whose value is not an
/// [`EscapedStrings`](crate::key::EscapedStrings) or
/// [`LocaleStrings`](crate::key::LocaleStrings) value.
///
/// # Examples
///
/// ```rust
/// use file_desktop::entry::{AnnotatedEntry, Entry};
/// use file_desktop::error::AppendKeyValueError;
/// use file_desktop::key::{EscapedString, LocaleString};
///
/// let name = LocaleString::try_from("MyApp").unwrap();
/// let action = EscapedString::try_from("Open").unwrap();
/// let mut ae = AnnotatedEntry::new(Entry::Name(name));
/// let result = ae.try_append(action);
/// assert_eq!(result.unwrap_err(), AppendKeyValueError::NotEscapedStringList);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AppendKeyValueError {
    /// An [`EscapedString`](crate::key::EscapedString) was appended to an entry that is not an escaped-string list.
    NotEscapedStringList,
    /// A [`LocaleString`](crate::key::LocaleString) was appended to an entry that is not `Keywords`.
    NotLocaleStringList,
}

impl AppendKeyValueError {
    pub(crate) fn as_str(&self) -> &str {
        match self {
            Self::NotEscapedStringList => "entry does not contain an EscapedStrings value",
            Self::NotLocaleStringList => "entry does not contain a LocaleStrings value",
        }
    }
}

impl fmt::Display for AppendKeyValueError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::error::Error for AppendKeyValueError {}

// }{── EntryError ─────────────────────────────────────────────────────────────

/// Classifies failures while mutating or parsing an entry.
///
/// # Examples
///
/// ```rust
/// use file_desktop::entry::Entry;
/// use file_desktop::error::{EntryError, ParseEntryError};
///
/// let err = Entry::try_from("MissingSeparator").unwrap_err();
/// let error = EntryError::Parse(err);
/// assert!(matches!(error, EntryError::Parse(ParseEntryError::MissingSeparator(_))));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EntryError {
    /// Appending a value to a list-valued entry failed.
    AppendKeyValue(AppendKeyValueError),
    /// Get an entry key value as an incompatible value type failed.
    Value(ValueError),
    /// Mutating an entry key value as an incompatible value type failed.
    MutationValue(MutationValueError),
    /// Parsing an entry failed.
    Parse(ParseEntryError),
}

impl fmt::Display for EntryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::AppendKeyValue(kind) => write!(f, "{kind}"),
            Self::Parse(kind) => write!(f, "{kind}"),
            Self::Value(kind) => write!(f, "{kind}"),
            Self::MutationValue(kind) => write!(f, "{kind}"),
        }
    }
}

impl std::error::Error for EntryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::AppendKeyValue(error) => Some(error),
            Self::Parse(error) => Some(error),
            Self::Value(_) | Self::MutationValue(_) => None,
        }
    }
}

impl From<AppendKeyValueError> for EntryError {
    fn from(err: AppendKeyValueError) -> Self {
        Self::AppendKeyValue(err)
    }
}

impl From<ValueError> for EntryError {
    fn from(err: ValueError) -> Self {
        Self::Value(err)
    }
}

impl From<MutationValueError> for EntryError {
    fn from(err: MutationValueError) -> Self {
        Self::MutationValue(err)
    }
}

impl From<ParseEntryError> for EntryError {
    fn from(err: ParseEntryError) -> Self {
        Self::Parse(err)
    }
}

// }{── GroupError ─────────────────────────────────────────────────────────────

/// Classifies failures while creating or mutating an entry group.
///
/// # Examples
///
/// ```rust
/// use file_desktop::entry_group::GroupName;
/// use file_desktop::error::GroupError;
///
/// let err = GroupName::try_from("bad[name]").unwrap_err();
/// assert_eq!(err, GroupError::InvalidGroupName);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GroupError {
    /// An entry operation failed.
    Entry(EntryError),

    /// An `Actions` entry cannot be added to the group.
    AddActionsEntry,

    /// The insertion position key appears more than once.
    DuplicatePosition,

    /// An entry with the same key already exists.
    EntryExists,

    /// No entry matches the requested key.
    EntryNotFound,

    /// The group name is empty, e.g. `[]`.
    EmptyGroupName,

    /// A group name is empty or contains an invalid character.
    InvalidGroupName,

    /// A group header is not enclosed in square brackets.
    InvalidGroupHeader,

    /// The requested insertion position key does not exist.
    PositionNotFound,
}

impl fmt::Display for GroupError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Entry(kind) => write!(f, "{kind}"),
            Self::AddActionsEntry => f.write_str(""),
            Self::DuplicatePosition => {
                f.write_str("position key appears more than once in the group")
            }
            Self::EmptyGroupName => f.write_str("group name is empty"),
            Self::EntryExists => f.write_str("entry already exists"),
            Self::EntryNotFound => f.write_str("failed to get an entry"),
            Self::InvalidGroupName => {
                f.write_str("invalid group name (must not contain '[', ']', or control characters)")
            }
            Self::InvalidGroupHeader => f.write_str("invalid group header"),
            Self::PositionNotFound => f.write_str("position key was not found in the group"),
        }
    }
}

impl std::error::Error for GroupError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Entry(error) => Some(error),
            Self::AddActionsEntry
            | Self::DuplicatePosition
            | Self::EntryExists
            | Self::EntryNotFound
            | Self::EmptyGroupName
            | Self::InvalidGroupName
            | Self::InvalidGroupHeader
            | Self::PositionNotFound => None,
        }
    }
}

// }{── ValueError ─────────────────────────────────────────────────────

/// An error indicating that an invalid value was encountered.
///
/// The contained value is the value that caused the error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValueError(pub(crate) String);

impl fmt::Display for ValueError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid value: {}", self.0)
    }
}

impl ValueError {
    /// Returns the value associated with this error.
    #[inline]
    #[must_use]
    pub fn value(&self) -> &str {
        &self.0
    }
}

impl std::error::Error for ValueError {}

// }{── MutationValueError ─────────────────────────────────────────────────────

/// Indicates that a mutation attempted to borrow an entry as the wrong value type.
///
/// The inner string stores the entry's actual value type name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MutationValueError(pub(crate) String);

impl fmt::Display for MutationValueError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid value: {}", self.0)
    }
}

impl std::error::Error for MutationValueError {}

// }{── ParseFileDesktopError ──────────────────────────────────────────────────

/// Classifies parse-file failures detected while reading desktop file content.
///
/// Variants that occur while scanning input carry a 1-based `line` field indicating
/// the offending line. `EmptyFile`, `MissingRequiredGroup`, and `MissingRequiredKeys`
/// are unit variants because they are detected before any input is read or only after
/// the full input has been consumed, so no single line number applies.
///
/// # Variants
///
/// - `EmptyFile` - The desktop file is empty
/// - `InvalidComment { line }` - A non-empty line was not recognized as a comment, group header, or entry
/// - `EmptyGroupName { line }` - A group header `[]` has an empty name
/// - `InvalidGroupHeader { line, source }` - A group header could not be parsed
/// - `ParseEntry { line, source }` - An entry's key or value is invalid (including an empty key)
/// - `DuplicateGroup { line }` - The same group appears twice in one file
/// - `DuplicateEntry { line }` - The same key appears twice in one group
/// - `EntryOutsideGroup { line }` - A key-value entry appears before the first group header
/// - `MissingRequiredGroup` - The required `[Desktop Entry]` group is missing
/// - `MissingRequiredKeys` - The required keys for the parsed `Type` are missing
/// - `InconsistentActions` - The `Actions` entry does not match the desktop action groups
///
/// # Examples
///
/// ```rust
/// use file_desktop::error::ParseFileDesktopError;
///
/// let err = ParseFileDesktopError::EmptyFile;
/// assert_eq!(err.to_string(), "desktop entry file is empty");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseFileDesktopError {
    /// A group header could not be parsed.
    InvalidGroupHeader {
        /// The 1-based line number of the invalid header.
        line: usize,
        /// The reason the group header is invalid.
        source: GroupError,
    },
    /// An entry could not be parsed.
    ParseEntry {
        /// The 1-based line number of the invalid entry.
        line: usize,
        /// The reason the entry is invalid.
        source: ParseEntryError,
    },
    /// A duplicate group was found within the same file.
    DuplicateGroup {
        /// The 1-based line number where the duplicate group was encountered.
        line: usize,
    },
    /// A duplicate key was found within the same group.
    DuplicateEntry {
        /// The 1-based line number where the duplicate key was encountered.
        line: usize,
    },
    /// A key-value entry appeared before the first group header.
    EntryOutsideGroup {
        /// The 1-based line number where the entry was encountered.
        line: usize,
    },
    /// The Desktop Entry document is empty.
    EmptyFile,
    /// A group header contains an empty name (i.e. `[]`).
    EmptyGroupName {
        /// The 1-based line number where the empty group name was encountered.
        line: usize,
    },
    /// A comment or other non-empty line has invalid syntax.
    InvalidComment {
        /// The 1-based line number where the invalid line was encountered.
        line: usize,
    },
    /// The required `[Desktop Entry]` group is missing.
    MissingRequiredGroup,
    /// One or more required keys are missing.
    MissingRequiredKeys,
    /// The `Actions` entry does not match the desktop action groups.
    InconsistentActions,
}

impl ParseFileDesktopError {
    pub(crate) fn message(&self) -> String {
        match self {
            Self::InvalidGroupHeader { line, source } => {
                format!("failed to parse group header at line {line}: {source}")
            }
            Self::ParseEntry { line, source } => {
                format!("failed to parse entry at line {line}: {source}")
            }
            Self::DuplicateGroup { line } => {
                format!("duplicate group encountered at line {line}")
            }
            Self::DuplicateEntry { line } => {
                format!("duplicate entry encountered at line {line}")
            }
            Self::InconsistentActions => {
                "actions entry does not match desktop action groups".to_string()
            }
            Self::MissingRequiredGroup => "missing required Desktop Entry group".to_string(),
            Self::MissingRequiredKeys => "missing one or more required keys".to_string(),
            Self::EntryOutsideGroup { line } => {
                format!("desktop entry encountered before any group header at line {line}")
            }
            Self::EmptyFile => "desktop entry file is empty".to_string(),
            Self::EmptyGroupName { line } => format!("desktop group name is empty at line {line}"),
            Self::InvalidComment { line } => {
                format!("invalid comment syntax at line {line}")
            }
        }
    }
}

impl fmt::Display for ParseFileDesktopError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&self.message())
    }
}

impl std::error::Error for ParseFileDesktopError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::InvalidGroupHeader { source, .. } => Some(source),
            Self::ParseEntry { source, .. } => Some(source),
            Self::DuplicateGroup { .. }
            | Self::DuplicateEntry { .. }
            | Self::EntryOutsideGroup { .. }
            | Self::EmptyFile
            | Self::EmptyGroupName { .. }
            | Self::InvalidComment { .. }
            | Self::InconsistentActions
            | Self::MissingRequiredGroup
            | Self::MissingRequiredKeys => None,
        }
    }
}

// }{── ParseEntryError ────────────────────────────────────────────────────────

/// Describes why parsing one `key=value` entry failed.
///
/// # Examples
///
/// ```rust
/// use file_desktop::entry::Entry;
/// use file_desktop::error::ParseEntryError;
///
/// let err = Entry::try_from("Name").unwrap_err();
/// assert!(matches!(err, ParseEntryError::MissingSeparator(_)));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseEntryError {
    /// The key is not a valid standard, localized standard, or extension key.
    ParseKey(ParseKeyError),
    /// The value is invalid for the parsed key.
    ParseValue(ParseEntryValueError),
    /// The input does not contain an `=` separator.
    MissingSeparator(String),
}

impl fmt::Display for ParseEntryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ParseKey(error) => write!(f, "{error}"),
            Self::ParseValue(error) => write!(f, "{error}"),
            Self::MissingSeparator(line) => {
                write!(f, "entry is missing the '=' separator: '{line}'")
            }
        }
    }
}

impl From<ParseKeyError> for ParseEntryError {
    fn from(error: ParseKeyError) -> Self {
        Self::ParseKey(error)
    }
}

impl From<ParseEntryValueError> for ParseEntryError {
    fn from(error: ParseEntryValueError) -> Self {
        Self::ParseValue(error)
    }
}

impl std::error::Error for ParseEntryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::ParseKey(error) => Some(error),
            Self::ParseValue(error) => Some(error),
            Self::MissingSeparator(_) => None,
        }
    }
}

// }{── ParseEntryValueError ───────────────────────────────────────────────────

/// Describes why parsing a typed Desktop Entry value failed.
///
/// This error is returned by the `FromStr` and `TryFrom` implementations for
/// the value types in [`crate::key`], and while parsing an [`crate::entry::Entry`].
///
/// # Examples
///
/// ```rust
/// use file_desktop::error::ParseEntryValueError;
/// use file_desktop::key::Bool;
///
/// assert_eq!(Bool::try_from("maybe"), Err(ParseEntryValueError::ParseBool));
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseEntryValueError {
    /// The `Type` key contained an invalid value.
    ///
    /// Valid values are exactly `"Application"`, `"Link"`, or `"Directory"`
    /// (case-sensitive).
    ParseDesktopType,

    /// A boolean value could not be parsed.
    ///
    /// Valid values are `"true"` and `"false"`.
    ParseBool,

    /// The `Version` key contained an unsupported version string.
    ///
    /// Accepted values are `"1.0"`, `"1.1"`, `"1.2"`, `"1.3"`, `"1.4"`,
    /// and `"1.5"`.
    ParseVersion,

    /// A numeric value could not be parsed as a floating-point number.
    ParseNumeric,

    /// A `string`-typed value contained an invalid character or escape
    /// sequence.
    ///
    /// String values must contain only ASCII characters other than ASCII
    /// control characters. Supported escape sequences are `\s`, `\n`, `\t`,
    /// `\r`, and `\\`.
    ParseEscapedString,

    /// A `localestring`-typed value contained an invalid character or escape
    /// sequence.
    ///
    /// UTF-8 characters are allowed, but raw control characters are not.
    /// Supported escape sequences are `\s`, `\n`, `\t`, `\r`, and `\\`.
    ParseLocaleString,
    /// An `iconstring`-typed value contained an invalid character or escape sequence.
    ParseIconString,

    /// A semicolon-delimited `strings` value could not be parsed.
    ///
    /// Each element must be a valid `string` value. The `\;` escape sequence
    /// is used to represent a literal semicolon within an element.
    ParseEscapedStrings,

    /// A semicolon-delimited `localestrings` value could not be parsed.
    ///
    /// Each element must be a valid `localestring` value. The `\;` escape
    /// sequence is used to represent a literal semicolon within an element.
    ParseLocaleStrings,

    /// An `ExtensionValue` (the value of an `X-` extension key) could not be
    /// parsed: it must be UTF-8 with no control characters.
    ParseExtensionString,
}

impl ParseEntryValueError {
    pub(crate) fn as_str(&self) -> &str {
        match self {
            Self::ParseExtensionString => {
                "invalid 'ExtensionString' value: expected UTF-8 characters excluding control characters"
            }
            Self::ParseDesktopType => {
                "invalid value for key 'Type': expected exactly 'Application', 'Link', or 'Directory'"
            }
            Self::ParseBool => "invalid 'Bool' value: expected exactly 'true' or 'false'",
            Self::ParseVersion => {
                "invalid 'Version' value: expected '1.0', '1.1', '1.2', '1.3', '1.4', or '1.5'"
            }
            Self::ParseNumeric => "invalid 'Numeric' value: expected a valid floating-point number",
            Self::ParseEscapedString => {
                "invalid 'EscapedString' value: expected ASCII characters excluding control characters and unsupported escape sequences"
            }
            Self::ParseLocaleString => {
                "invalid 'LocaleString' value: expected UTF-8 characters excluding control characters and unsupported escape sequences"
            }
            Self::ParseIconString => {
                "invalid 'IconString' value: expected UTF-8 characters excluding control characters and unsupported escape sequences"
            }
            Self::ParseEscapedStrings => {
                "invalid 'EscapedStrings' value: expected a semicolon-delimited list of valid 'EscapedString' values"
            }
            Self::ParseLocaleStrings => {
                "invalid 'LocaleStrings' value: expected a semicolon-delimited list of valid 'LocaleString' values"
            }
        }
    }
}

impl fmt::Display for ParseEntryValueError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::error::Error for ParseEntryValueError {}

// }{── ParseKeyError ──────────────────────────────────────────────────────────

/// Describes why parsing a standard Desktop Entry key failed.
///
/// # Examples
///
/// ```rust
/// use file_desktop::error::ParseKeyError;
/// use file_desktop::key::EntryKeys;
///
/// assert_eq!("Unknown".parse::<EntryKeys>(), Err(ParseKeyError::NonStandardKey));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseKeyError {
    /// The key does not match the required format.
    InvalidFormat,
    /// An `X-` extension key has an invalid remainder token.
    InvalidExtensionKey,
    /// A locale suffix inside a localized key is malformed.
    InvalidLocale,
    /// The base key does not support locale suffixes.
    NotLocalizable,
    /// The key is not a standard Desktop Entry key.
    NonStandardKey,
    /// The key is neither standard nor a supported extension key.
    UnknownKey(String),
}

impl fmt::Display for ParseKeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidFormat => f.write_str("invalid key format"),
            Self::InvalidLocale => f.write_str("invalid locale format"),
            Self::InvalidExtensionKey => f.write_str("invalid extension key"),
            Self::NonStandardKey => f.write_str("key is not a standard desktop entry key"),
            Self::NotLocalizable => f.write_str("not localizable key"),
            Self::UnknownKey(key) => {
                write!(f, "unknown desktop entry key '{key}'")
            }
        }
    }
}

impl std::error::Error for ParseKeyError {}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error as StdError;
    use std::io::ErrorKind;

    #[test]
    fn test_parse_file_desktop_error_kind_display_messages() {
        assert_eq!(
            ParseFileDesktopError::DuplicateGroup { line: 3 }.to_string(),
            "duplicate group encountered at line 3"
        );
        assert_eq!(
            ParseFileDesktopError::MissingRequiredGroup.to_string(),
            "missing required Desktop Entry group"
        );
        assert_eq!(
            ParseFileDesktopError::MissingRequiredKeys.to_string(),
            "missing one or more required keys"
        );
        assert_eq!(
            ParseFileDesktopError::EntryOutsideGroup { line: 2 }.to_string(),
            "desktop entry encountered before any group header at line 2"
        );
        assert_eq!(
            ParseFileDesktopError::DuplicateEntry { line: 6 }.to_string(),
            "duplicate entry encountered at line 6"
        );
        assert_eq!(
            ParseFileDesktopError::EmptyFile.to_string(),
            "desktop entry file is empty"
        );
        assert_eq!(
            ParseFileDesktopError::EmptyGroupName { line: 7 }.to_string(),
            "desktop group name is empty at line 7"
        );
        assert_eq!(
            ParseFileDesktopError::InvalidComment { line: 10 }.to_string(),
            "invalid comment syntax at line 10"
        );
    }

    #[test]
    fn test_parse_entry_value_error_display_messages() {
        assert_eq!(
            ParseEntryValueError::ParseEscapedString.to_string(),
            "invalid 'EscapedString' value: expected ASCII characters excluding control characters and unsupported escape sequences"
        );
        assert_eq!(
            ParseEntryValueError::ParseLocaleString.to_string(),
            "invalid 'LocaleString' value: expected UTF-8 characters excluding control characters and unsupported escape sequences"
        );
    }

    #[test]
    fn test_error_display_messages() {
        assert_eq!(
            Error::from(io::Error::from(ErrorKind::NotFound)).to_string(),
            "entity not found"
        );
    }

    #[test]
    fn test_from_io_error_for_error_keeps_error_kind() {
        let io_error = io::Error::new(ErrorKind::PermissionDenied, "no permission");
        let error = Error::from(io_error);

        assert!(matches!(
            error,
            Error::OpenFile(source) if source.kind() == ErrorKind::PermissionDenied
        ));
    }

    #[test]
    fn io_errors_remain_error_sources() {
        let error = Error::from(io::Error::new(ErrorKind::PermissionDenied, "no permission"));

        assert_eq!(
            StdError::source(&error).unwrap().to_string(),
            "no permission"
        );
    }

    #[test]
    fn test_from_parse_entry_value_error_for_error() {
        let error = Error::from(ParseEntryValueError::ParseBool);
        assert_eq!(
            error,
            Error::Entry(EntryError::Parse(ParseEntryError::ParseValue(
                ParseEntryValueError::ParseBool
            )))
        );
    }

    #[test]
    fn nested_errors_expose_their_sources() {
        let error = Error::ParseFileDesktop(ParseFileDesktopError::ParseEntry {
            line: 4,
            source: ParseEntryError::ParseValue(ParseEntryValueError::ParseBool),
        });

        let file_error = StdError::source(&error).unwrap();
        assert_eq!(
            file_error.to_string(),
            "failed to parse entry at line 4: invalid 'Bool' value: expected exactly 'true' or 'false'"
        );

        let entry_error = file_error.source().unwrap();
        assert_eq!(
            entry_error.to_string(),
            "invalid 'Bool' value: expected exactly 'true' or 'false'"
        );

        let value_error = entry_error.source().unwrap();
        assert_eq!(
            value_error.to_string(),
            "invalid 'Bool' value: expected exactly 'true' or 'false'"
        );
        assert!(value_error.source().is_none());

        let group_error = GroupError::Entry(EntryError::MutationValue(MutationValueError(
            "Bool".to_owned(),
        )));
        assert_eq!(
            StdError::source(&group_error).unwrap().to_string(),
            "invalid value: Bool"
        );
    }
}

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