Skip to main content

freedesktop_rs/parser/
models.rs

1use std::fmt::Display;
2
3use crate::error::Error;
4
5/// Trait implemented by entries to dynamically check whether the entry is blank or a comment.
6pub trait CanBeComment {
7    /// Returns whether the entry is a blank line.
8    fn is_blank(&self) -> bool;
9    /// Returns whether the entry is a comment.
10    fn is_comment(&self) -> bool;
11}
12
13/// Trait implemented by entites that contain multiple entries (eg. [Group] and [TopLevelEntry]).
14pub trait EntrySet<E> {
15    /// Returns a vector of the entries that are not comments or blanks.
16    fn without_comments(&self) -> Vec<&E>;
17
18    /// Returs a vector of the entries that are comments or blanks (no key-values entries).
19    fn only_comments(&self) -> Vec<&CommentEntry>;
20
21    /// Find the first entry for this key, or `None` if no entry with this key was found.
22    fn find(&self, key: &str) -> Option<&E>;
23
24    /// Similar to [Self::find], but throws if the key is not found.
25    fn get(&self, key: &str) -> Result<&E, Error> {
26        self.find(key).ok_or(Error::NotFound(key.to_owned()))
27    }
28
29    /// Find the first entry for this key and returns it as a mutable reference, or `None` if no entry with this key was found.
30    fn find_mut(&mut self, key: &str) -> Option<&mut E>;
31
32    /// Similar to [Self::find_mut], but throws if the key is not found.    
33    fn get_mut(&mut self, key: &str) -> Result<&mut E, Error> {
34        self.find_mut(key).ok_or(Error::NotFound(key.to_owned()))
35    }
36}
37
38/// Defines what options of a [Locale] are significant when searching for an entry.
39pub struct LocaleOptions<'a> {
40    /// A reference to the locale to be found.
41    pub locale: &'a Locale,
42    /// Whether the country is significant.
43    pub country: bool,
44    /// Whether the country is significant.
45    pub encoding: bool,
46    /// Whether the country is significant.
47    pub modifier: bool,
48}
49
50impl<'a> LocaleOptions<'a> {
51    /// Creates a new instance in which all options are insignificant (besides language).
52    pub fn new(locale: &'a Locale) -> Self {
53        Self {
54            locale,
55            country: false,
56            encoding: false,
57            modifier: false,
58        }
59    }
60    /// Creates a new instance in which all options are significant.
61    pub fn all(locale: &'a Locale) -> Self {
62        Self {
63            locale,
64            country: true,
65            encoding: true,
66            modifier: true,
67        }
68    }
69
70    /// Makes all options insignificant but the language.
71    pub fn language_only(self) -> Self {
72        Self {
73            locale: self.locale,
74            country: false,
75            encoding: false,
76            modifier: false,
77        }
78    }
79
80    /// Makes all options significant.
81    pub fn all_significant(self) -> Self {
82        self.significant_country()
83            .significant_encoding()
84            .significant_modifiers()
85    }
86
87    /// Makes the encoding significant.
88    pub fn significant_encoding(mut self) -> Self {
89        self.encoding = true;
90        self
91    }
92
93    /// Makes the country significant.
94    pub fn significant_country(mut self) -> Self {
95        self.country = true;
96        self
97    }
98
99    /// Makes the modifiers significant.
100    pub fn significant_modifiers(mut self) -> Self {
101        self.modifier = true;
102        self
103    }
104
105    /// Changes the locale.
106    pub fn with_locale(mut self, locale: &'a Locale) -> Self {
107        self.locale = locale;
108        self
109    }
110}
111
112/// A group of entries.
113///
114/// This represents a section in a freedesktop file.
115#[derive(Debug, Eq, PartialEq, Clone)]
116pub struct Group {
117    /// The section name.
118    pub header: String,
119
120    /// The content of the section.
121    pub content: GroupContent,
122}
123
124impl Display for Group {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        writeln!(f, "[{}]", self.header)?;
127
128        write_content(f, &self.content)
129    }
130}
131
132impl EntrySet<ContentEntry> for Group {
133    fn without_comments(&self) -> Vec<&ContentEntry> {
134        self.content
135            .iter()
136            .filter_map(|e| {
137                if let Entry::Content(content) = e {
138                    Some(content)
139                } else {
140                    None
141                }
142            })
143            .collect()
144    }
145
146    fn only_comments(&self) -> Vec<&CommentEntry> {
147        self.content
148            .iter()
149            .filter_map(|e| {
150                if let Entry::Comment(comment) = e {
151                    Some(comment)
152                } else {
153                    None
154                }
155            })
156            .collect()
157    }
158
159    fn find(&self, key: &str) -> Option<&ContentEntry> {
160        self.content
161            .iter()
162            .filter_map(|i| match i {
163                Entry::Content(content_entry) => Some(content_entry),
164                Entry::Comment(_) => None,
165            })
166            .find(|e| e.key == key)
167    }
168
169    fn find_mut(&mut self, key: &str) -> Option<&mut ContentEntry> {
170        self.content
171            .iter_mut()
172            .filter_map(|i| match i {
173                Entry::Content(content_entry) => Some(content_entry),
174                Entry::Comment(_) => None,
175            })
176            .find(|e| e.key == key)
177    }
178}
179
180impl Group {
181    /// Find the first entry for this key and locale, or `None` if no entry with this key was found.
182    pub fn find_with_locale(&self, key: &str, options: &LocaleOptions) -> Option<&ContentEntry> {
183        self.content
184            .iter()
185            .filter_map(|i| match i {
186                Entry::Content(content_entry) => Some(content_entry),
187                Entry::Comment(_) => None,
188            })
189            .find(|e| {
190                e.key == key
191                    && e.locale
192                        .as_ref()
193                        .map_or(true, |locale| locale.equals_options(options))
194            })
195    }
196    /// Find the first entry for this key and locale and returns it as a mutable reference, or `None` if no entry with this key was found.
197    pub fn find_with_locale_mut(
198        &mut self,
199        key: &str,
200        options: &LocaleOptions,
201    ) -> Option<&mut ContentEntry> {
202        self.content
203            .iter_mut()
204            .filter_map(|i| match i {
205                Entry::Content(content_entry) => Some(content_entry),
206                Entry::Comment(_) => None,
207            })
208            .find(|e| {
209                e.key == key
210                    && e.locale
211                        .as_ref()
212                        .map_or(true, |locale| locale.equals_options(options))
213            })
214    }
215}
216
217/// Content of a section.
218///
219/// This an alias for Vec<Entry>.
220pub type GroupContent = Vec<Entry>;
221
222/// An entry in the file
223#[derive(Debug, Eq, PartialEq, Clone)]
224pub enum Entry {
225    /// A key-values entry
226    Content(ContentEntry),
227    /// A comment or blank line
228    Comment(CommentEntry),
229}
230
231impl From<CommentEntry> for Entry {
232    fn from(value: CommentEntry) -> Self {
233        Entry::Comment(value)
234    }
235}
236
237impl From<ContentEntry> for Entry {
238    fn from(value: ContentEntry) -> Self {
239        Entry::Content(value)
240    }
241}
242
243impl Display for Entry {
244    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245        match self {
246            Entry::Content(content_entry) => content_entry.fmt(f),
247            Entry::Comment(comment_entry) => comment_entry.fmt(f),
248        }
249    }
250}
251
252impl CanBeComment for Entry {
253    fn is_comment(&self) -> bool {
254        match self {
255            Entry::Content(_) => false,
256            Entry::Comment(_) => true,
257        }
258    }
259
260    fn is_blank(&self) -> bool {
261        if let Self::Comment(comment) = self {
262            comment.is_blank()
263        } else {
264            false
265        }
266    }
267}
268
269/// An entry at the root of the file.
270#[derive(Debug, Eq, PartialEq, Clone)]
271pub enum TopLevelEntry {
272    /// A section as per the Freedesktop specification.
273    Group(Group),
274
275    /// A comment or blank line.
276    Comment(CommentEntry),
277}
278
279impl From<CommentEntry> for TopLevelEntry {
280    fn from(value: CommentEntry) -> Self {
281        TopLevelEntry::Comment(value)
282    }
283}
284
285impl From<Group> for TopLevelEntry {
286    fn from(value: Group) -> Self {
287        TopLevelEntry::Group(value)
288    }
289}
290
291impl Display for TopLevelEntry {
292    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
293        match self {
294            TopLevelEntry::Group(group) => group.fmt(f),
295            TopLevelEntry::Comment(comment_entry) => comment_entry.fmt(f),
296        }
297    }
298}
299
300impl CanBeComment for TopLevelEntry {
301    fn is_comment(&self) -> bool {
302        match self {
303            TopLevelEntry::Group(_) => false,
304            TopLevelEntry::Comment(_) => true,
305        }
306    }
307
308    fn is_blank(&self) -> bool {
309        if let Self::Comment(comment) = self {
310            comment.is_blank()
311        } else {
312            false
313        }
314    }
315}
316
317/// A comment or a blank line.
318#[derive(Debug, Eq, PartialEq, Clone)]
319pub enum CommentEntry {
320    /// A textual comment. Contains the line content.
321    Text(String),
322    /// A blank line. Containes a number of "\n" for each subsequent lines.
323    Blank(String),
324}
325
326impl Display for CommentEntry {
327    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328        match self {
329            CommentEntry::Text(s) => write!(f, "# {s}"),
330
331            // No line feed since it's in its content already
332            CommentEntry::Blank(s) => write!(f, "{s}"),
333        }
334    }
335}
336
337impl CommentEntry {
338    fn is_blank(&self) -> bool {
339        match self {
340            CommentEntry::Text(_) => false,
341            CommentEntry::Blank(_) => true,
342        }
343    }
344}
345
346/// A key-values entry.
347#[derive(Debug, Eq, PartialEq, Clone)]
348pub struct ContentEntry {
349    /// The key of the entry.
350    pub key: String,
351
352    /// The values of the entry.
353    pub values: Vec<String>,
354
355    /// The potential locale of the entry.
356    pub locale: Option<Locale>,
357}
358
359impl Display for ContentEntry {
360    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361        write!(f, "{}", self.key)?;
362        if let Some(locale) = &self.locale {
363            write!(f, "[")?;
364            locale.fmt(f)?;
365            write!(f, "]")?;
366        }
367        write!(f, "={}", self.values.join(";"))
368    }
369}
370
371/// A locale of an entry.
372///
373/// If given to an entry, the only required argument is the language. Everything else is optional.
374#[derive(Debug, Eq, PartialEq, Clone)]
375pub struct Locale {
376    /// The language of the bound value.
377    pub lang: String,
378    /// The encoding of the bound value.
379    pub encoding: Option<String>,
380    /// The country variant of the language as per the specification.
381    pub country: Option<String>,
382    /// Any other variant of the language as per the specification.
383    pub modifiers: Option<String>,
384}
385
386impl Locale {
387    /// Check whether this locale respects the options
388    pub fn equals_options(&self, options: &LocaleOptions) -> bool {
389        let rhs = options.locale;
390        let mut res = self.lang == rhs.lang;
391        if options.country {
392            res &= self.country == rhs.country;
393        }
394        if options.encoding {
395            res &= self.encoding == rhs.encoding;
396        }
397        if options.modifier {
398            res &= self.modifiers == rhs.modifiers;
399        }
400        res
401    }
402}
403
404impl Display for Locale {
405    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
406        write!(f, "{}", self.lang)?;
407        if let Some(country) = &self.country {
408            write!(f, "_{}", country.to_uppercase())?;
409        }
410
411        if let Some(encoding) = &self.encoding {
412            write!(f, ".{encoding}")?;
413        }
414
415        if let Some(modifier) = &self.modifiers {
416            write!(f, "@{modifier}")?;
417        }
418
419        Ok(())
420    }
421}
422
423/// The representation of a Freedesktop file, which contains [TopLevelEntry].
424///
425/// This struct is used to parse raw data, see its implementations of [From<...>] for more information.
426#[derive(Debug, Eq, PartialEq, Clone)]
427pub struct DesktopFile {
428    /// The top-level entries of the file.
429    pub content: Vec<TopLevelEntry>,
430}
431
432impl EntrySet<Group> for DesktopFile {
433    fn without_comments(&self) -> Vec<&Group> {
434        self.content
435            .iter()
436            .filter_map(|tle| match tle {
437                TopLevelEntry::Group(group) => Some(group),
438                _ => None,
439            })
440            .collect()
441    }
442
443    fn only_comments(&self) -> Vec<&CommentEntry> {
444        self.content
445            .iter()
446            .filter_map(|tle| match tle {
447                TopLevelEntry::Comment(comment) => Some(comment),
448                _ => None,
449            })
450            .collect()
451    }
452
453    fn find(&self, header: &str) -> Option<&Group> {
454        self.without_comments()
455            .iter()
456            .find(|g| g.header == header)
457            .copied()
458    }
459
460    fn find_mut(&mut self, header: &str) -> Option<&mut Group> {
461        self.content
462            .iter_mut()
463            .filter_map(|i| match i {
464                TopLevelEntry::Group(group) => Some(group),
465                _ => None,
466            })
467            .find(|g| g.header == header)
468    }
469}
470
471impl Display for DesktopFile {
472    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
473        write_content(f, &self.content)
474    }
475}
476
477fn write_content<T: CanBeComment + Display>(
478    f: &mut std::fmt::Formatter<'_>,
479    content: &[T],
480) -> std::fmt::Result {
481    let mut peekable = content.iter().peekable();
482    while let Some(item) = peekable.next() {
483        item.fmt(f)?;
484
485        // Add new line if it is a written entry before the end of iteration
486        if peekable.peek().is_some() && !item.is_blank() {
487            writeln!(f)?;
488        }
489    }
490    Ok(())
491}
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496
497    #[test]
498    fn test_single_value_entry_format() {
499        let single_value_entry = Entry::Content(ContentEntry {
500            key: String::from("Hello"),
501            values: vec![String::from("World")],
502            locale: None,
503        });
504        let single_value_locale_entry = Entry::Content(ContentEntry {
505            key: String::from("Hello"),
506            values: vec![String::from("World")],
507            locale: Some(Locale {
508                lang: String::from("en"),
509                encoding: None,
510                country: Some(String::from("US")),
511                modifiers: Some(String::from("new")),
512            }),
513        });
514
515        assert_eq!(&single_value_entry.to_string(), "Hello=World");
516        assert_eq!(
517            &single_value_locale_entry.to_string(),
518            "Hello[en_US@new]=World"
519        );
520    }
521
522    #[test]
523    fn test_multi_values_entry_format() {
524        let multi_values = Entry::Content(ContentEntry {
525            key: String::from("Hello"),
526            values: vec![
527                String::from("World"),
528                String::from(" Universe"),
529                String::from("all others"),
530            ],
531            locale: None,
532        });
533        assert_eq!(
534            &multi_values.to_string(),
535            "Hello=World; Universe;all others"
536        );
537    }
538
539    #[test]
540    fn test_comments_format() {
541        let text_comment = Entry::Comment(CommentEntry::Text(String::from("Test with spaces")));
542        let blank_comment = Entry::Comment(CommentEntry::Blank(String::from("\n\t")));
543
544        assert_eq!(&text_comment.to_string(), "# Test with spaces");
545        assert_eq!(&blank_comment.to_string(), "\n\t");
546    }
547
548    #[test]
549    fn test_full_file() {
550        let file = DesktopFile {
551            content: vec![
552                TopLevelEntry::Comment(CommentEntry::Text(String::from("First group"))),
553                TopLevelEntry::Group(Group {
554                    header: String::from("First"),
555                    content: vec![
556                        Entry::Content(ContentEntry {
557                            key: String::from("Title"),
558                            values: vec![String::from("First group")],
559                            locale: None,
560                        }),
561                        Entry::Comment(CommentEntry::Blank(String::from("\n"))),
562                        Entry::Comment(CommentEntry::Text(String::from("End of group"))),
563                    ],
564                }),
565                TopLevelEntry::Group(Group {
566                    header: String::from("Second"),
567                    content: vec![],
568                }),
569            ],
570        };
571
572        assert_eq!(
573            &file.to_string(),
574            "# First group
575[First]
576Title=First group
577
578# End of group
579[Second]
580"
581        )
582    }
583}