Skip to main content

ostrya_core/
keyfile.rs

1//! A GKeyFile/INI subset parser for the repository `config` file.
2//!
3//! The repository config is a GLib key file: `[group]` headers, `key=value`
4//! entries, `#` comment lines, and blank lines. Parsing keeps the group and
5//! key order and the raw value text, so a parsed file re-serializes in the
6//! order the `ostree` tool wrote it. Line classification, the whitespace
7//! trimmed around a key, and a value's leading-whitespace trim all use ASCII
8//! space and tab only; a value's trailing whitespace and any non-ASCII
9//! whitespace such as a non-breaking space are kept. A group header names the
10//! text from `[` to the first `]`, with only whitespace allowed after it.
11//! Comment and blank lines are dropped, and a repeated group header merges
12//! into the existing group; [`Display`](std::fmt::Display) output reparses to
13//! an equal [`KeyFile`].
14//!
15//! [`KeyFile::get_value`] returns the raw value; the typed accessors apply
16//! the GLib string-unescaping and list-splitting rules on read.
17//! [`KeyFile::set_value`] takes a raw value and rejects group names, keys, and
18//! values whose structural characters would not survive a re-parse;
19//! [`KeyFile::set_string`] escapes a value the way the tool does on write.
20//! [`KeyFile::remove_key`] and [`KeyFile::remove_group`] are the write side's
21//! other half: a rewritten document keeps the groups and keys the caller did
22//! not touch, in the order it read them, and drops the comment and blank lines
23//! the input carried, which is what the tool's own rewrite does.
24
25use crate::error::{Error, Result};
26
27/// A parsed key file: an ordered list of groups, each an ordered list of
28/// (key, raw value) entries.
29#[derive(Debug, Clone, Default, PartialEq, Eq)]
30pub struct KeyFile {
31    groups: Vec<Group>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35struct Group {
36    name: String,
37    entries: Vec<(String, String)>,
38}
39
40impl KeyFile {
41    /// Parse a key file from text.
42    pub fn parse(input: &str) -> Result<KeyFile> {
43        let mut groups: Vec<Group> = Vec::new();
44        let mut current: Option<usize> = None;
45
46        // Split on '\n'; a trailing newline leaves a final empty segment that
47        // is not a line. One trailing carriage return is stripped per raw
48        // line, so CRLF input is accepted and a doubled CR keeps one.
49        let body = input.strip_suffix('\n').unwrap_or(input);
50        for (n, raw) in body.split('\n').enumerate() {
51            let lineno = n + 1;
52            let line = raw.strip_suffix('\r').unwrap_or(raw);
53            let trimmed = line.trim_matches(ASCII_WS);
54            if trimmed.is_empty() || trimmed.starts_with('#') {
55                continue;
56            }
57            if let Some(rest) = trimmed.strip_prefix('[') {
58                // The group name runs from '[' to the first ']'; only
59                // whitespace may follow the ']', and the name may not contain
60                // '[' or ']'. This mirrors [`validate_group`] so a header the
61                // tool rejects does not parse cleanly here either.
62                let Some(close) = rest.find(']') else {
63                    return Err(Error::KeyFile(format!(
64                        "line {lineno}: group header is not closed with ']'"
65                    )));
66                };
67                if !rest[close + 1..].trim_matches(ASCII_WS).is_empty() {
68                    return Err(Error::KeyFile(format!(
69                        "line {lineno}: group header has trailing text after ']'"
70                    )));
71                }
72                let name = &rest[..close];
73                if name.is_empty() {
74                    return Err(Error::KeyFile(format!("line {lineno}: empty group name")));
75                }
76                if name.contains(['[', ']']) {
77                    return Err(Error::KeyFile(format!(
78                        "line {lineno}: group name '{name}' contains '[' or ']'"
79                    )));
80                }
81                current = Some(match groups.iter().position(|g| g.name == name) {
82                    Some(i) => i,
83                    None => {
84                        groups.push(Group {
85                            name: name.to_string(),
86                            entries: Vec::new(),
87                        });
88                        groups.len() - 1
89                    }
90                });
91                continue;
92            }
93            let Some(eq) = line.find('=') else {
94                return Err(Error::KeyFile(format!(
95                    "line {lineno}: expected a key=value pair"
96                )));
97            };
98            let key = line[..eq].trim_matches(ASCII_WS);
99            // The tool trims leading whitespace after `=` and keeps trailing
100            // whitespace as part of the value.
101            let value = line[eq + 1..].trim_start_matches(ASCII_WS);
102            if key.is_empty() {
103                return Err(Error::KeyFile(format!("line {lineno}: empty key")));
104            }
105            let Some(idx) = current else {
106                return Err(Error::KeyFile(format!(
107                    "line {lineno}: key '{key}' precedes any group"
108                )));
109            };
110            let entries = &mut groups[idx].entries;
111            match entries.iter_mut().find(|(k, _)| k == key) {
112                Some(entry) => entry.1 = value.to_string(),
113                None => entries.push((key.to_string(), value.to_string())),
114            }
115        }
116        Ok(KeyFile { groups })
117    }
118
119    /// Whether a group is present.
120    pub fn has_group(&self, group: &str) -> bool {
121        self.groups.iter().any(|g| g.name == group)
122    }
123
124    /// Iterate group names in file order.
125    pub fn groups(&self) -> impl Iterator<Item = &str> {
126        self.groups.iter().map(|g| g.name.as_str())
127    }
128
129    fn find(&self, group: &str, key: &str) -> Option<&str> {
130        self.groups
131            .iter()
132            .find(|g| g.name == group)?
133            .entries
134            .iter()
135            .find(|(k, _)| k == key)
136            .map(|(_, v)| v.as_str())
137    }
138
139    /// The raw (still-escaped) value for a key, or `None` if absent.
140    pub fn get_value(&self, group: &str, key: &str) -> Option<&str> {
141        self.find(group, key)
142    }
143
144    /// The unescaped string value for a key.
145    pub fn get_string(&self, group: &str, key: &str) -> Result<Option<String>> {
146        self.find(group, key).map(unescape).transpose()
147    }
148
149    /// A boolean value: one of `true`, `false`, `1`, or `0`, matched exactly.
150    pub fn get_bool(&self, group: &str, key: &str) -> Result<Option<bool>> {
151        match self.find(group, key) {
152            None => Ok(None),
153            Some("true") | Some("1") => Ok(Some(true)),
154            Some("false") | Some("0") => Ok(Some(false)),
155            Some(other) => Err(Error::KeyFile(format!(
156                "value '{other}' for {group}.{key} is not a boolean"
157            ))),
158        }
159    }
160
161    /// A signed integer value.
162    pub fn get_integer(&self, group: &str, key: &str) -> Result<Option<i64>> {
163        match self.find(group, key) {
164            None => Ok(None),
165            Some(v) => v.parse::<i64>().map(Some).map_err(|_| {
166                Error::KeyFile(format!("value '{v}' for {group}.{key} is not an integer"))
167            }),
168        }
169    }
170
171    /// A `;`-separated list of unescaped strings. A trailing separator does not
172    /// produce a final empty element.
173    pub fn get_string_list(&self, group: &str, key: &str) -> Result<Option<Vec<String>>> {
174        match self.find(group, key) {
175            None => Ok(None),
176            Some(v) => split_list(v).map(Some),
177        }
178    }
179
180    /// Set a key's raw value, creating the group if needed and preserving the
181    /// position of an existing key.
182    ///
183    /// The group name, key, and value are validated so the serialized form
184    /// reparses to an equal `KeyFile`: a group name may not be empty or
185    /// contain `[`, `]`, or a newline; a key may not be empty, contain `=` or
186    /// a newline, carry leading or trailing whitespace, or begin with `#` or
187    /// `[`; a value may not contain a newline or begin with whitespace.
188    pub fn set_value(&mut self, group: &str, key: &str, value: &str) -> Result<()> {
189        validate_group(group)?;
190        validate_key(key)?;
191        validate_value(value)?;
192        let idx = match self.groups.iter().position(|g| g.name == group) {
193            Some(i) => i,
194            None => {
195                self.groups.push(Group {
196                    name: group.to_string(),
197                    entries: Vec::new(),
198                });
199                self.groups.len() - 1
200            }
201        };
202        let entries = &mut self.groups[idx].entries;
203        match entries.iter_mut().find(|(k, _)| k == key) {
204            Some(entry) => entry.1 = value.to_string(),
205            None => entries.push((key.to_string(), value.to_string())),
206        }
207        Ok(())
208    }
209
210    /// Set a key to a string value, applying the escaping the tool uses on
211    /// write so a value that contains a newline, carriage return, backslash,
212    /// or leading whitespace is stored in a form that reparses. This is the
213    /// inverse of [`get_string`](KeyFile::get_string). Use
214    /// [`set_value`](KeyFile::set_value) to store an already-escaped raw value.
215    pub fn set_string(&mut self, group: &str, key: &str, value: &str) -> Result<()> {
216        self.set_value(group, key, &escape(value))
217    }
218
219    /// Remove one key, reporting whether it was there.
220    ///
221    /// The group stays, even when the removed key was its last: the tool leaves
222    /// the header of an emptied group in place, and
223    /// [`Display`](std::fmt::Display) writes it back with no entries.
224    pub fn remove_key(&mut self, group: &str, key: &str) -> bool {
225        let Some(entries) = self
226            .groups
227            .iter_mut()
228            .find(|g| g.name == group)
229            .map(|g| &mut g.entries)
230        else {
231            return false;
232        };
233        let Some(index) = entries.iter().position(|(k, _)| k == key) else {
234            return false;
235        };
236        entries.remove(index);
237        true
238    }
239
240    /// Remove a group and every key in it, reporting whether it was there.
241    ///
242    /// The remaining groups keep their order.
243    pub fn remove_group(&mut self, group: &str) -> bool {
244        let Some(index) = self.groups.iter().position(|g| g.name == group) else {
245            return false;
246        };
247        self.groups.remove(index);
248        true
249    }
250}
251
252/// The whitespace the tool trims: ASCII space and tab only. Recovered by
253/// feeding the tool crafted config files -- a line of only spaces or only tabs
254/// is ignored, a leading space or tab before a header or comment is stripped,
255/// and a surrounding space or tab is removed from a key, while a non-breaking
256/// space (U+00A0) or other non-ASCII whitespace is preserved everywhere.
257const ASCII_WS: [char; 2] = [' ', '\t'];
258
259/// A structural character must not appear where it would change how the text
260/// reparses.
261fn validate_group(name: &str) -> Result<()> {
262    if name.is_empty() {
263        return Err(Error::KeyFile("group name is empty".into()));
264    }
265    if name.contains(['\n', '\r', '[', ']']) {
266        return Err(Error::KeyFile(format!(
267            "group name '{name}' contains a structural character"
268        )));
269    }
270    Ok(())
271}
272
273fn validate_key(key: &str) -> Result<()> {
274    if key.is_empty() {
275        return Err(Error::KeyFile("key is empty".into()));
276    }
277    if key.starts_with(ASCII_WS) || key.ends_with(ASCII_WS) {
278        return Err(Error::KeyFile(format!(
279            "key '{key}' has leading or trailing whitespace"
280        )));
281    }
282    if key.contains(['\n', '\r', '=']) {
283        return Err(Error::KeyFile(format!(
284            "key '{key}' contains a structural character"
285        )));
286    }
287    if key.starts_with('#') || key.starts_with('[') {
288        return Err(Error::KeyFile(format!(
289            "key '{key}' begins with '#' or '[' and would not reparse"
290        )));
291    }
292    Ok(())
293}
294
295fn validate_value(value: &str) -> Result<()> {
296    if value.contains(['\n', '\r']) {
297        return Err(Error::KeyFile(
298            "value contains a newline; escape it as \\n".into(),
299        ));
300    }
301    if value.starts_with([' ', '\t']) {
302        return Err(Error::KeyFile(
303            "value begins with whitespace; escape it as \\s".into(),
304        ));
305    }
306    Ok(())
307}
308
309/// Serialize in file order, matching GLib's layout: a blank line separates
310/// groups, each entry is `key=value`. Use `.to_string()` (via `Display`).
311impl std::fmt::Display for KeyFile {
312    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313        for (i, group) in self.groups.iter().enumerate() {
314            if i > 0 {
315                f.write_str("\n")?;
316            }
317            writeln!(f, "[{}]", group.name)?;
318            for (key, value) in &group.entries {
319                writeln!(f, "{key}={value}")?;
320            }
321        }
322        Ok(())
323    }
324}
325
326/// Apply the tool's write escaping to a string value. Recovered by driving
327/// `ostree config set` with crafted values and reading the raw config bytes:
328/// a backslash becomes `\\`, a newline `\n`, and a carriage return `\r`
329/// anywhere in the value; within the leading whitespace run each space becomes
330/// `\s` and each tab `\t`; a space or tab elsewhere, and a `;`, are written
331/// literally. [`unescape`] reverses each of these sequences.
332fn escape(s: &str) -> String {
333    let mut out = String::with_capacity(s.len());
334    let mut leading = true;
335    for c in s.chars() {
336        match c {
337            '\\' => {
338                out.push_str("\\\\");
339                leading = false;
340            }
341            '\n' => {
342                out.push_str("\\n");
343                leading = false;
344            }
345            '\r' => {
346                out.push_str("\\r");
347                leading = false;
348            }
349            ' ' if leading => out.push_str("\\s"),
350            '\t' if leading => out.push_str("\\t"),
351            _ => {
352                out.push(c);
353                leading = false;
354            }
355        }
356    }
357    out
358}
359
360fn unescape(s: &str) -> Result<String> {
361    let mut out = String::with_capacity(s.len());
362    let mut chars = s.chars();
363    while let Some(c) = chars.next() {
364        if c != '\\' {
365            out.push(c);
366            continue;
367        }
368        match chars.next() {
369            Some('s') => out.push(' '),
370            Some('n') => out.push('\n'),
371            Some('t') => out.push('\t'),
372            Some('r') => out.push('\r'),
373            Some('\\') => out.push('\\'),
374            Some(';') => out.push(';'),
375            Some(other) => return Err(Error::KeyFile(format!("invalid escape '\\{other}'"))),
376            None => return Err(Error::KeyFile("value ends with a lone backslash".into())),
377        }
378    }
379    Ok(out)
380}
381
382fn split_list(raw: &str) -> Result<Vec<String>> {
383    let mut items: Vec<String> = Vec::new();
384    let mut current = String::new();
385    let mut chars = raw.chars();
386    while let Some(c) = chars.next() {
387        match c {
388            '\\' => match chars.next() {
389                // Keep the escape intact; unescape resolves it below.
390                Some(next) => {
391                    current.push('\\');
392                    current.push(next);
393                }
394                None => return Err(Error::KeyFile("value ends with a lone backslash".into())),
395            },
396            ';' => {
397                items.push(std::mem::take(&mut current));
398            }
399            _ => current.push(c),
400        }
401    }
402    if !current.is_empty() {
403        items.push(current);
404    }
405    items.iter().map(|s| unescape(s)).collect()
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    // The exact bytes the `ostree` tool wrote for an archive repo config.
413    const ARCHIVE_CONFIG: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";
414
415    #[test]
416    fn parses_tool_written_config() {
417        let kf = KeyFile::parse(ARCHIVE_CONFIG).unwrap();
418        assert_eq!(kf.get_value("core", "repo_version"), Some("1"));
419        assert_eq!(kf.get_value("core", "mode"), Some("archive-z2"));
420        assert_eq!(kf.get_integer("core", "repo_version").unwrap(), Some(1));
421        assert_eq!(kf.get_value("core", "absent"), None);
422        assert_eq!(kf.get_value("nogroup", "x"), None);
423    }
424
425    #[test]
426    fn round_trips_tool_written_config_byte_for_byte() {
427        let kf = KeyFile::parse(ARCHIVE_CONFIG).unwrap();
428        assert_eq!(kf.to_string(), ARCHIVE_CONFIG);
429    }
430
431    #[test]
432    fn drops_comments_and_blanks_and_trims_leading_value_whitespace() {
433        // Leading whitespace on a line, around a key, and after `=` is
434        // removed; trailing whitespace in a value is kept, matching the tool.
435        let text = "# a comment\n\n[core]\n  repo_version = 1\n\n# trailing\nmode=bare \n";
436        let kf = KeyFile::parse(text).unwrap();
437        assert_eq!(kf.get_value("core", "repo_version"), Some("1"));
438        assert_eq!(kf.get_integer("core", "repo_version").unwrap(), Some(1));
439        assert_eq!(kf.get_value("core", "mode"), Some("bare "));
440    }
441
442    #[test]
443    fn value_keeps_trailing_and_strips_leading_whitespace() {
444        let kf = KeyFile::parse("[g]\nk=  a b  \n").unwrap();
445        assert_eq!(kf.get_value("g", "k"), Some("a b  "));
446    }
447
448    #[test]
449    fn hash_inside_a_value_is_literal() {
450        let kf = KeyFile::parse("[core]\nk=a # b\n").unwrap();
451        assert_eq!(kf.get_value("core", "k"), Some("a # b"));
452    }
453
454    #[test]
455    fn accepts_crlf_line_endings() {
456        let kf = KeyFile::parse("[core]\r\nrepo_version=1\r\nk=v\r\n").unwrap();
457        assert_eq!(kf.get_value("core", "k"), Some("v"));
458        assert_eq!(kf.get_integer("core", "repo_version").unwrap(), Some(1));
459    }
460
461    #[test]
462    fn strips_one_trailing_cr_per_line() {
463        // The tool strips a single trailing carriage return from a raw line.
464        // A doubled CR before the newline keeps one CR in the value; stripping
465        // twice would drop the byte.
466        let kf = KeyFile::parse("[g]\r\nk=v\r\r\n").unwrap();
467        assert_eq!(kf.get_value("g", "k"), Some("v\r"));
468    }
469
470    #[test]
471    fn accepts_indented_comment_header_and_key() {
472        let kf = KeyFile::parse("   # c\n   [core]\n  k=v\n").unwrap();
473        assert_eq!(kf.get_value("core", "k"), Some("v"));
474    }
475
476    #[test]
477    fn duplicate_groups_merge_and_last_key_wins() {
478        let kf = KeyFile::parse("[s]\na=first\n[s]\nb=second\na=third\n").unwrap();
479        assert_eq!(kf.get_value("s", "a"), Some("third"));
480        assert_eq!(kf.get_value("s", "b"), Some("second"));
481        assert_eq!(kf.groups().count(), 1);
482    }
483
484    #[test]
485    fn rejects_empty_group_and_semicolon_line() {
486        assert!(KeyFile::parse("[]\nk=v\n").is_err());
487        // A line starting with `;` is not a comment; with no `=` it is an error.
488        assert!(KeyFile::parse("[core]\n;not a comment\nk=v\n").is_err());
489    }
490
491    #[test]
492    fn parses_quoted_remote_group_name() {
493        let text = "[remote \"origin\"]\nurl=https://example.invalid/repo\ngpg-verify=false\n";
494        let kf = KeyFile::parse(text).unwrap();
495        assert!(kf.has_group("remote \"origin\""));
496        assert_eq!(
497            kf.get_value("remote \"origin\"", "url"),
498            Some("https://example.invalid/repo")
499        );
500        assert_eq!(
501            kf.get_bool("remote \"origin\"", "gpg-verify").unwrap(),
502            Some(false)
503        );
504    }
505
506    #[test]
507    fn boolean_and_integer_validation() {
508        let kf = KeyFile::parse(
509            "[core]\nt=true\nf=false\none=1\nzero=0\nbad=maybe\nyes=yes\ncase=True\ntwo=2\ndepth=-1\n",
510        )
511        .unwrap();
512        assert_eq!(kf.get_bool("core", "t").unwrap(), Some(true));
513        assert_eq!(kf.get_bool("core", "f").unwrap(), Some(false));
514        assert_eq!(kf.get_bool("core", "one").unwrap(), Some(true));
515        assert_eq!(kf.get_bool("core", "zero").unwrap(), Some(false));
516        // The tool accepts only true/false/1/0, matched exactly.
517        assert!(kf.get_bool("core", "bad").is_err());
518        assert!(kf.get_bool("core", "yes").is_err());
519        assert!(kf.get_bool("core", "case").is_err());
520        assert!(kf.get_bool("core", "two").is_err());
521        assert_eq!(kf.get_integer("core", "depth").unwrap(), Some(-1));
522    }
523
524    #[test]
525    fn string_list_splits_on_semicolons() {
526        let kf = KeyFile::parse("[core]\ndefault-repo-finders=config;mount\n").unwrap();
527        assert_eq!(
528            kf.get_string_list("core", "default-repo-finders").unwrap(),
529            Some(vec!["config".to_string(), "mount".to_string()])
530        );
531        // A trailing separator does not add an empty element.
532        let kf = KeyFile::parse("[core]\nl=a;b;\n").unwrap();
533        assert_eq!(
534            kf.get_string_list("core", "l").unwrap(),
535            Some(vec!["a".to_string(), "b".to_string()])
536        );
537    }
538
539    #[test]
540    fn unescape_handles_glib_sequences() {
541        let kf = KeyFile::parse("[g]\nk=a\\sb\\tc\\\\d\n").unwrap();
542        assert_eq!(
543            kf.get_string("g", "k").unwrap(),
544            Some("a b\tc\\d".to_string())
545        );
546    }
547
548    #[test]
549    fn rejects_key_before_group_and_unclosed_header() {
550        assert!(KeyFile::parse("key=value\n").is_err());
551        assert!(KeyFile::parse("[core\nkey=value\n").is_err());
552    }
553
554    #[test]
555    fn set_value_creates_group_and_updates_in_place() {
556        let mut kf = KeyFile::default();
557        kf.set_value("core", "repo_version", "1").unwrap();
558        kf.set_value("core", "mode", "bare").unwrap();
559        kf.set_value("core", "mode", "archive-z2").unwrap();
560        assert_eq!(kf.to_string(), "[core]\nrepo_version=1\nmode=archive-z2\n");
561    }
562
563    #[test]
564    fn to_string_separates_groups_with_a_blank_line() {
565        let mut kf = KeyFile::default();
566        kf.set_value("core", "repo_version", "1").unwrap();
567        kf.set_value("remote \"o\"", "url", "x").unwrap();
568        assert_eq!(
569            kf.to_string(),
570            "[core]\nrepo_version=1\n\n[remote \"o\"]\nurl=x\n"
571        );
572    }
573
574    #[test]
575    fn set_value_rejects_structural_characters() {
576        let mut kf = KeyFile::default();
577        assert!(kf.set_value("core", "k", "a\nb").is_err()); // newline in value
578        assert!(kf.set_value("core", "k", " lead").is_err()); // leading space
579        assert!(kf.set_value("core", "k", "\ttab").is_err()); // leading tab
580        assert!(kf.set_value("core", "a=b", "v").is_err()); // `=` in key
581        assert!(kf.set_value("core", "a\nb", "v").is_err()); // newline in key
582        assert!(kf.set_value("core", " spaced ", "v").is_err()); // ws around key
583        assert!(kf.set_value("", "k", "v").is_err()); // empty group
584        assert!(kf.set_value("a\nb", "k", "v").is_err()); // newline in group
585        assert!(kf.set_value("a[b]", "k", "v").is_err()); // brackets in group
586        // Spaces and semicolons inside a value are ordinary content.
587        assert!(kf.set_value("core", "list", "a;b;c").is_ok());
588        assert!(kf.set_value("core", "spaces", "a b c").is_ok());
589    }
590
591    #[test]
592    fn set_value_rejects_keys_that_would_not_reparse() {
593        let mut kf = KeyFile::default();
594        // A '#'-leading key serializes to a line the parser drops as a comment.
595        assert!(kf.set_value("core", "#weird", "v").is_err());
596        // A '['-leading key serializes to a line the parser reads as a group
597        // header.
598        assert!(kf.set_value("core", "[k", "v").is_err());
599        // A '#' or '[' elsewhere in the key is ordinary content that reparses.
600        assert!(kf.set_value("core", "a#b", "v").is_ok());
601        assert!(kf.set_value("core", "a[b", "v").is_ok());
602        let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
603        assert_eq!(kf, reparsed);
604    }
605
606    #[test]
607    fn set_value_round_trips_through_display() {
608        let mut kf = KeyFile::default();
609        kf.set_value("remote \"o\"", "url", "https://example.invalid/repo")
610            .unwrap();
611        kf.set_value("remote \"o\"", "finders", "config;mount")
612            .unwrap();
613        kf.set_value("core", "mode", "archive-z2").unwrap();
614        let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
615        assert_eq!(kf, reparsed);
616    }
617
618    #[test]
619    fn parse_display_parse_is_stable() {
620        let text = "# note\n\n[core]\nrepo_version=1\nmode=archive-z2\nval=keep me \n\n\
621                    [remote \"o\"]\nurl=https://example.invalid/repo\ngpg-verify=false\n";
622        let first = KeyFile::parse(text).unwrap();
623        let second = KeyFile::parse(&first.to_string()).unwrap();
624        assert_eq!(first, second);
625    }
626
627    // ---- B3: group-header bracket handling (observed via `ostree config`) ----
628
629    #[test]
630    fn group_name_runs_to_first_bracket() {
631        // Each of these whole files is rejected by the tool; the parser
632        // matches by erroring rather than reading a stray group name.
633        // `[a]b]`: text follows the first ']'.
634        assert!(KeyFile::parse("[a]b]\nk=v\n").is_err());
635        // `[a]b]c`: trailing non-']' text after the first ']'.
636        assert!(KeyFile::parse("[a]b]c\nk=v\n").is_err());
637        // `[a[b]`: the group name would contain '['.
638        assert!(KeyFile::parse("[a[b]\nk=v\n").is_err());
639        // `[]x]`: empty name plus trailing text.
640        assert!(KeyFile::parse("[]x]\nk=v\n").is_err());
641        // Trailing ASCII whitespace after the ']' is allowed.
642        let kf = KeyFile::parse("[grp]  \nk=v\n").unwrap();
643        assert_eq!(kf.get_value("grp", "k"), Some("v"));
644    }
645
646    // ---- B4: ASCII-only whitespace trimming (observed via `ostree config`) --
647
648    #[test]
649    fn non_ascii_whitespace_is_preserved() {
650        // A line that is only a non-breaking space is not blank; with no '='
651        // it is a parse error, matching the tool.
652        assert!(KeyFile::parse("[g]\n\u{a0}\nk=v\n").is_err());
653        // A non-breaking space around a key stays part of the key name.
654        let kf = KeyFile::parse("[g]\n\u{a0}k\u{a0}=v\n").unwrap();
655        assert_eq!(kf.get_value("g", "\u{a0}k\u{a0}"), Some("v"));
656        assert_eq!(kf.get_value("g", "k"), None);
657        // A non-breaking space around a value is kept on both sides.
658        let kf = KeyFile::parse("[g]\nvk=\u{a0}nbv\u{a0}\n").unwrap();
659        assert_eq!(kf.get_value("g", "vk"), Some("\u{a0}nbv\u{a0}"));
660    }
661
662    #[test]
663    fn ascii_whitespace_lines_and_keys_are_trimmed() {
664        // A line of only spaces or only tabs is ignored; a leading tab before
665        // a header or comment is stripped; a tab-wrapped key trims to bare.
666        let kf = KeyFile::parse("[g]\n   \n\t\n\t[h]\n\t#c\n\tk\t=v\n").unwrap();
667        assert_eq!(kf.get_value("h", "k"), Some("v"));
668    }
669
670    #[test]
671    fn set_value_allows_non_ascii_whitespace_in_key() {
672        let mut kf = KeyFile::default();
673        // ASCII whitespace around a key would not reparse and is rejected.
674        assert!(kf.set_value("g", " k", "v").is_err());
675        assert!(kf.set_value("g", "k\t", "v").is_err());
676        // A trailing non-breaking space reparses and is accepted.
677        assert!(kf.set_value("g", "k\u{a0}", "v").is_ok());
678        let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
679        assert_eq!(kf, reparsed);
680    }
681
682    // ---- B5: value escaping on write (observed via `ostree config set`) ----
683
684    #[test]
685    fn set_string_escapes_like_the_tool() {
686        // (input, stored form) pairs read back from the raw config bytes the
687        // tool wrote for `ostree config set core.<k> <input>`.
688        for (input, stored) in [
689            ("a\nb", "a\\nb"),
690            ("a\tb", "a\tb"), // interior tab is literal
691            ("a\rb", "a\\rb"),
692            ("a\\b", "a\\\\b"),
693            ("   ab", "\\s\\s\\sab"),
694            ("ab   ", "ab   "),   // trailing spaces are literal
695            ("a;b", "a;b"),       // the separator is literal
696            ("\tab", "\\tab"),    // leading tab
697            ("ab\t", "ab\t"),     // trailing tab is literal
698            ("a b", "a b"),       // interior space is literal
699            ("   ", "\\s\\s\\s"), // an all-space value is all leading
700            (" \tx", "\\s\\tx"),  // the leading run mixes space and tab
701        ] {
702            let mut kf = KeyFile::default();
703            kf.set_string("core", "k", input).unwrap();
704            assert_eq!(kf.get_value("core", "k"), Some(stored), "input {input:?}");
705        }
706    }
707
708    #[test]
709    fn set_string_get_string_round_trips() {
710        for v in [
711            "plain",
712            "a\nb\tc",
713            "  leading and trailing  ",
714            "back\\slash",
715            "a\r\nb",
716            "line1\nline2",
717            "",
718        ] {
719            let mut kf = KeyFile::default();
720            kf.set_string("core", "k", v).unwrap();
721            // The stored value carries no raw newline, so it is a single line.
722            assert!(!kf.get_value("core", "k").unwrap().contains(['\n', '\r']));
723            // get_string reverses the escaping.
724            assert_eq!(kf.get_string("core", "k").unwrap().as_deref(), Some(v));
725            // The serialized file reparses to an equal KeyFile.
726            let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
727            assert_eq!(kf, reparsed);
728        }
729    }
730
731    // ---- B6: removal (observed via `ostree config unset`) -------------------
732
733    #[test]
734    fn remove_key_keeps_the_group_header() {
735        // `ostree config set g.k v` followed by `ostree config unset g.k` leaves
736        // the emptied `[g]` header in the file, which this reproduces.
737        let mut kf = KeyFile::parse("[core]\nrepo_version=1\nmode=archive-z2\n\n[g]\nk=v\n")
738            .expect("the file parses");
739        assert!(kf.remove_key("g", "k"));
740        assert_eq!(
741            kf.to_string(),
742            "[core]\nrepo_version=1\nmode=archive-z2\n\n[g]\n"
743        );
744        assert!(kf.has_group("g"));
745        assert_eq!(kf.get_value("g", "k"), None);
746    }
747
748    #[test]
749    fn remove_key_reports_an_absent_key_and_group() {
750        let mut kf = KeyFile::parse(ARCHIVE_CONFIG).expect("the file parses");
751        assert!(!kf.remove_key("core", "absent"));
752        assert!(!kf.remove_key("nogroup", "mode"));
753        // Nothing moved.
754        assert_eq!(kf.to_string(), ARCHIVE_CONFIG);
755    }
756
757    #[test]
758    fn remove_key_leaves_the_other_keys_in_order() {
759        let mut kf =
760            KeyFile::parse("[core]\nrepo_version=1\nmode=bare\nfsync=false\n").expect("parses");
761        assert!(kf.remove_key("core", "mode"));
762        assert_eq!(kf.to_string(), "[core]\nrepo_version=1\nfsync=false\n");
763    }
764
765    #[test]
766    fn remove_group_drops_the_header_and_its_keys() {
767        let text = "[core]\nrepo_version=1\nmode=bare\n\n\
768                    [remote \"a\"]\nurl=https://a.invalid/r\n\n\
769                    [remote \"b\"]\nurl=https://b.invalid/r\n";
770        let mut kf = KeyFile::parse(text).expect("the file parses");
771        assert!(kf.remove_group("remote \"a\""));
772        assert!(!kf.remove_group("remote \"a\""));
773        assert_eq!(
774            kf.to_string(),
775            "[core]\nrepo_version=1\nmode=bare\n\n[remote \"b\"]\nurl=https://b.invalid/r\n"
776        );
777        assert_eq!(kf.groups().collect::<Vec<_>>(), ["core", "remote \"b\""]);
778    }
779
780    #[test]
781    fn a_rewrite_keeps_untouched_groups_and_drops_comments() {
782        // The tool's own rewrite: the groups and keys it did not touch keep
783        // their order and their bytes, and the comment and blank lines the
784        // input carried are gone.
785        let text = "# leading comment\n[core]\nrepo_version=1\nmode=archive-z2\n\
786                    # inner comment\nfoo=bar\n\n[other]\nx=1\n";
787        let mut kf = KeyFile::parse(text).expect("the file parses");
788        kf.set_value("core", "new", "v").expect("the key is valid");
789        assert_eq!(
790            kf.to_string(),
791            "[core]\nrepo_version=1\nmode=archive-z2\nfoo=bar\nnew=v\n\n[other]\nx=1\n"
792        );
793    }
794
795    #[test]
796    fn set_string_matches_tool_written_line_bytes() {
797        // The exact stored bytes `ostree config set core.knl $'a\nb'` and
798        // `... core.klead '   ab'` produced in a fresh archive repo config.
799        let mut kf = KeyFile::default();
800        kf.set_value("core", "repo_version", "1").unwrap();
801        kf.set_value("core", "mode", "archive-z2").unwrap();
802        kf.set_string("core", "knl", "a\nb").unwrap();
803        kf.set_string("core", "klead", "   ab").unwrap();
804        assert_eq!(
805            kf.to_string(),
806            "[core]\nrepo_version=1\nmode=archive-z2\nknl=a\\nb\nklead=\\s\\s\\sab\n"
807        );
808    }
809}