Skip to main content

freedesktop_rs/parser/
mod.rs

1use models::{
2    CommentEntry, ContentEntry, DesktopFile, Entry, Group, GroupContent, Locale, TopLevelEntry,
3};
4use nom::{
5    branch::alt,
6    bytes::complete::{escaped_transform, is_not, take_while},
7    character::complete::{alpha1, char, line_ending, multispace1, space0},
8    combinator::{eof, map, map_res, opt, value},
9    error::{Error, ErrorKind},
10    multi::{many0, many_till},
11    sequence::{delimited, pair, preceded, terminated},
12    AsChar, IResult, Parser,
13};
14
15/// Low level models
16pub mod models;
17
18impl TryFrom<&[u8]> for DesktopFile {
19    type Error = nom::Err<Error<Vec<u8>>>;
20
21    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
22        let res = many0(parse_top_level_entry).parse(value);
23
24        match res {
25            Ok((_, content)) => Ok(Self { content }),
26            Err(e) => Err(e.to_owned()),
27        }
28    }
29}
30
31impl TryFrom<&str> for DesktopFile {
32    type Error = nom::Err<Error<Vec<u8>>>;
33
34    fn try_from(value: &str) -> Result<Self, Self::Error> {
35        Self::try_from(value.as_bytes())
36    }
37}
38
39fn parse_top_level_entry(input: &[u8]) -> IResult<&[u8], TopLevelEntry> {
40    alt((
41        map_res(parse_group, TopLevelEntry::try_from),
42        map_res(parse_comment_entry, TopLevelEntry::try_from),
43    ))
44    .parse(input)
45}
46
47fn parse_group(input: &[u8]) -> IResult<&[u8], Group> {
48    let (input, (header, content)) = pair(parse_group_header, parse_group_content).parse(input)?;
49
50    Ok((
51        input,
52        Group {
53            header: header.to_owned(),
54            content,
55        },
56    ))
57}
58
59fn parse_group_header(input: &[u8]) -> IResult<&[u8], &str> {
60    map_res(
61        terminated(
62            delimited(char('['), take_while(|c| c != b'[' && c != b']'), char(']')),
63            opt(char('\n')),
64        ),
65        str::from_utf8,
66    )
67    .parse(input)
68}
69
70fn parse_group_content(input: &[u8]) -> IResult<&[u8], GroupContent> {
71    many0(parse_entry).parse(input)
72}
73
74fn parse_entry(input: &[u8]) -> IResult<&[u8], Entry> {
75    alt((
76        map_res(parse_comment_entry, Entry::try_from),
77        map_res(parse_content_entry, Entry::try_from),
78    ))
79    .parse(input)
80}
81
82fn parse_blank_comment_entry(input: &[u8]) -> IResult<&[u8], CommentEntry> {
83    let (input, space) = map_res(multispace1, str::from_utf8).parse(input)?;
84    Ok((input, CommentEntry::Blank(space.to_owned())))
85}
86
87fn parse_comment_entry(input: &[u8]) -> IResult<&[u8], CommentEntry> {
88    alt((parse_blank_comment_entry, parse_text_comment_entry)).parse(input)
89}
90
91fn parse_text_comment_entry(input: &[u8]) -> IResult<&[u8], CommentEntry> {
92    let (input, comment) = map_res(
93        preceded(
94            pair(char('#'), space0),
95            terminated(
96                take_while(|c: u8| {
97                    let item = c.as_char();
98                    item.is_ascii() && !item.is_newline()
99                }),
100                char('\n'),
101            ),
102        ),
103        str::from_utf8,
104    )
105    .parse(input)?;
106
107    Ok((input, CommentEntry::Text(comment.to_owned())))
108}
109
110fn parse_key(input: &[u8]) -> IResult<&[u8], &str> {
111    map_res(
112        take_while(|c: u8| {
113            let item = c.as_char();
114            item.is_alphanumeric() || item == '-'
115        }),
116        str::from_utf8,
117    )
118    .parse(input)
119}
120
121fn parse_value(input: &[u8]) -> IResult<&[u8], Vec<String>> {
122    map(
123        many_till(parse_single_value, alt((line_ending, eof))),
124        |r| r.0,
125    )
126    .parse(input)
127}
128
129fn parse_single_value(input: &[u8]) -> IResult<&[u8], String> {
130    terminated(
131        map_res(
132            escaped_transform(
133                is_not("\\;\n"),
134                '\\',
135                map(
136                    alt((
137                        value("\\n", char('n')),
138                        value("\\r", char('r')),
139                        value("\\s", char('s')),
140                        value("\\t", char('t')),
141                        value("\\", char('\\')),
142                        value("\\;", char(';')),
143                    )),
144                    |s| s.as_bytes(),
145                ),
146            ),
147            |v| String::from_utf8(v).map(|s| s.trim().to_owned()),
148        ),
149        opt(char(';')),
150    )
151    .parse(input)
152}
153
154fn parse_entry_locale(input: &[u8]) -> IResult<&[u8], Option<Locale>> {
155    let (main_input, locale_result) = opt(delimited(
156        char('['),
157        take_while(|c| c != b'[' && c != b']'),
158        char(']'),
159    ))
160    .parse(input)?;
161
162    if let Some(raw) = locale_result {
163        let modifier_parser = map_res(preceded(char('@'), alpha1), |r| str::from_utf8(r));
164        let encoding_parser = map_res(
165            preceded(
166                char('.'),
167                take_while(|b: u8| {
168                    let c = b.as_char();
169                    c.is_alphanumeric() || c == '-'
170                }),
171            ),
172            |r| str::from_utf8(r),
173        );
174        let country_parser = map_res(preceded(char('_'), alpha1), |r| str::from_utf8(r));
175        let mut lang_parser = map_res(alpha1, |r| str::from_utf8(r));
176
177        let (input, lang) = lang_parser.parse(raw)?;
178        let (input, country) = opt(country_parser).parse(input)?;
179        println!("{}", str::from_utf8(input).unwrap());
180        let (input, encoding) = opt(encoding_parser).parse(input)?;
181        let (input, modifier) = opt(modifier_parser).parse(input)?;
182        if !input.is_empty() {
183            return Err(nom::Err::Failure(Error {
184                input,
185                code: ErrorKind::NonEmpty,
186            }));
187        }
188        Ok((
189            main_input,
190            Some(Locale {
191                lang: lang.to_owned(),
192                country: country.map(ToOwned::to_owned),
193                encoding: encoding.map(ToOwned::to_owned),
194                modifiers: modifier.map(ToOwned::to_owned),
195            }),
196        ))
197    } else {
198        Ok((main_input, None))
199    }
200}
201
202fn parse_content_entry(input: &[u8]) -> IResult<&[u8], ContentEntry> {
203    let (input, key) = parse_key.parse(input)?;
204
205    let (input, locale) = parse_entry_locale.parse(input)?;
206
207    let (input, _) = (space0, char('='), space0).parse(input)?;
208    let (input, values) = parse_value.parse(input)?;
209    Ok((
210        input,
211        ContentEntry {
212            key: key.to_owned(),
213            values,
214            locale,
215        },
216    ))
217}
218
219#[cfg(test)]
220mod tests {
221
222    use nom::{error::ErrorKind, error_position};
223
224    use super::{parse_entry, *};
225
226    #[test]
227    fn test_parse_entry() {
228        let simple_entry = "Hello=World\n";
229        let locale_entry = "Hello[en_US.UTF-8]=World";
230        let no_value = "Hello=";
231        let comment = "# Comment\n";
232        let empty = "\n";
233
234        assert_eq!(
235            parse_entry(simple_entry.as_bytes()),
236            Ok((
237                "".as_bytes(),
238                Entry::Content(ContentEntry {
239                    key: "Hello".to_owned(),
240                    values: vec!["World".to_owned()],
241                    locale: None
242                })
243            ))
244        );
245
246        assert_eq!(
247            parse_entry(locale_entry.as_bytes()),
248            Ok((
249                "".as_bytes(),
250                Entry::Content(ContentEntry {
251                    key: "Hello".to_owned(),
252                    values: vec!["World".to_owned()],
253                    locale: Some(Locale {
254                        lang: String::from("en"),
255                        country: Some(String::from("US")),
256                        encoding: Some(String::from("UTF-8")),
257                        modifiers: None,
258                    })
259                })
260            ))
261        );
262
263        assert_eq!(
264            parse_entry(comment.as_bytes()),
265            Ok((
266                "".as_bytes(),
267                Entry::Comment(CommentEntry::Text("Comment".to_owned()))
268            ))
269        );
270
271        assert_eq!(
272            parse_entry(empty.as_bytes()),
273            Ok((
274                "".as_bytes(),
275                Entry::Comment(CommentEntry::Blank("\n".to_owned()))
276            ))
277        );
278
279        assert_eq!(
280            parse_entry(no_value.as_bytes()),
281            Ok((
282                "".as_bytes(),
283                Entry::Content(ContentEntry {
284                    key: String::from("Hello"),
285                    values: vec![],
286                    locale: None
287                })
288            ))
289        )
290    }
291
292    #[test]
293    fn test_group_parsing() {
294        let group = "[Desktop]
295Type=Application
296Exec=sh-test
297Id=4
298Hidden=false
299";
300
301        assert_eq!(
302            parse_group(group.as_bytes()),
303            Ok((
304                "".as_bytes(),
305                Group {
306                    header: String::from("Desktop"),
307                    content: vec![
308                        Entry::Content(ContentEntry {
309                            key: String::from("Type"),
310                            values: vec![String::from("Application")],
311                            locale: None
312                        }),
313                        Entry::Content(ContentEntry {
314                            key: String::from("Exec"),
315                            values: vec![String::from("sh-test")],
316                            locale: None
317                        }),
318                        Entry::Content(ContentEntry {
319                            key: String::from("Id"),
320                            values: vec![String::from("4")],
321                            locale: None
322                        }),
323                        Entry::Content(ContentEntry {
324                            key: String::from("Hidden"),
325                            values: vec![String::from("false")],
326                            locale: None
327                        }),
328                    ],
329                }
330            ))
331        );
332    }
333
334    #[test]
335    fn test_bad_parsing() {
336        let space_in_key = "Hello World=Yay";
337        let bad_entry = "Hell[test]o=World";
338
339        assert_eq!(
340            parse_entry(space_in_key.as_bytes()),
341            Err(nom::Err::Error(error_position!(
342                "World=Yay".as_bytes(),
343                ErrorKind::Char
344            )))
345        );
346
347        assert_eq!(
348            parse_entry(bad_entry.as_bytes()),
349            Err(nom::Err::Error(error_position!(
350                "o=World".as_bytes(),
351                ErrorKind::Char
352            )))
353        );
354    }
355
356    #[test]
357    fn test_multi_values_parsing() {
358        let values_without_final_semi = "World;Universe;all others";
359        let values = format!("{};", values_without_final_semi);
360
361        assert_eq!(
362            parse_value(values.as_bytes()),
363            Ok((
364                "".as_bytes(),
365                vec![
366                    String::from("World"),
367                    String::from("Universe"),
368                    String::from("all others")
369                ]
370            ))
371        );
372        assert_eq!(
373            parse_value(values.as_bytes()),
374            parse_value(values_without_final_semi.as_bytes())
375        )
376    }
377
378    #[test]
379    fn test_full_parsing() {
380        let single = "# Outside comment
381[Desktop]
382Type=Application
383Exec=sh test
384Id=4
385Hidden=false
386";
387        assert_eq!(
388            DesktopFile::try_from(single),
389            Ok(DesktopFile {
390                content: vec![
391                    TopLevelEntry::Comment(CommentEntry::Text("Outside comment".to_owned())),
392                    TopLevelEntry::Group(Group {
393                        header: "Desktop".to_owned(),
394                        content: vec![
395                            Entry::Content(ContentEntry {
396                                key: String::from("Type"),
397                                values: vec![String::from("Application")],
398                                locale: None
399                            }),
400                            Entry::Content(ContentEntry {
401                                key: String::from("Exec"),
402                                values: vec![String::from("sh test")],
403                                locale: None
404                            }),
405                            Entry::Content(ContentEntry {
406                                key: String::from("Id"),
407                                values: vec![String::from("4")],
408                                locale: None
409                            }),
410                            Entry::Content(ContentEntry {
411                                key: String::from("Hidden"),
412                                values: vec![String::from("false")],
413                                locale: None
414                            })
415                        ]
416                    })
417                ],
418            })
419        );
420    }
421}