Skip to main content

ostrya_core/
keyfile.rs

1//! A parser and writer for a subset of the GLib key file format.
2//!
3//! The parse rules and the write rules are on the [`KeyFile`] type doc. The
4//! parse rules, the escape rules of `set_string`, and the removal rules come
5//! from the observation of `ostree config` with crafted config files. The
6//! tests record each observed case.
7
8use std::collections::HashMap;
9
10use crate::error::{Error, Result};
11
12/// A parsed key file, such as the repository `config` file.
13///
14/// A key file is an ordered list of groups. Each group is an ordered list of
15/// entries, and each entry is a key and its raw value text.
16///
17/// # Syntax
18///
19/// [`parse`](KeyFile::parse) reads a subset of the GLib key file format:
20///
21/// - A `[group]` line starts a group. The group name is the text from `[` to
22///   the first `]`. Only white space can follow the `]`.
23/// - A `key=value` line is an entry of the current group. The key is the text
24///   before the first `=`.
25/// - A line that starts with `#` is a comment line. Only `#` starts a comment.
26///   A `#` in a value is part of the value.
27/// - A blank line has no text or only white space.
28/// - A line ends with LF or with CRLF. The parser removes one carriage return
29///   at the end of a line.
30///
31/// The parser uses ASCII space and tab as white space:
32///
33/// - It ignores this white space around a blank line, a comment line, and a
34///   group header.
35/// - It removes this white space around a key and at the start of a value.
36/// - It keeps the white space at the end of a value.
37/// - It keeps a non-breaking space (U+00A0) and all other non-ASCII white
38///   space everywhere.
39///
40/// The parser keeps the group order, the key order, and the raw value text.
41/// It drops comment lines and blank lines. A repeated group header merges into
42/// the group of the first header. A repeated key keeps its first position and
43/// takes the last value.
44///
45/// # Writes
46///
47/// [`get_value`](KeyFile::get_value) returns the raw value text. The typed
48/// getters unescape the value on read, and
49/// [`get_string_list`](KeyFile::get_string_list) also splits it into items.
50///
51/// The [`Display`](std::fmt::Display) output parses to an equal `KeyFile`. A
52/// rewritten file keeps the groups and the keys that the caller did not
53/// change, in their order and with their value text. It does not keep the
54/// comment lines and the blank lines of the input. The `ostree` command
55/// rewrites a `config` file in the same way.
56///
57/// # Examples
58///
59/// ```
60/// use ostrya_core::KeyFile;
61///
62/// let mut config = KeyFile::parse("[core]\nrepo_version=1\nmode=archive-z2\n")?;
63/// assert_eq!(config.get_value("core", "mode"), Some("archive-z2"));
64/// assert_eq!(config.get_integer("core", "repo_version")?, Some(1));
65///
66/// config.set_string("core", "fsync", "false")?;
67/// assert_eq!(
68///     config.to_string(),
69///     "[core]\nrepo_version=1\nmode=archive-z2\nfsync=false\n",
70/// );
71/// # Ok::<(), ostrya_core::Error>(())
72/// ```
73#[derive(Clone, Default)]
74pub struct KeyFile {
75    groups: Vec<Group>,
76    /// The position in `groups` of each group, by name, so a lookup does not
77    /// scan every group.
78    index: HashMap<String, usize>,
79}
80
81impl PartialEq for KeyFile {
82    fn eq(&self, other: &KeyFile) -> bool {
83        self.groups == other.groups
84    }
85}
86
87impl Eq for KeyFile {}
88
89impl std::fmt::Debug for KeyFile {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        f.debug_struct("KeyFile")
92            .field("groups", &self.groups)
93            .finish()
94    }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
98struct Group {
99    name: String,
100    entries: Vec<(String, String)>,
101}
102
103impl KeyFile {
104    /// Parses a key file from text.
105    ///
106    /// The rules are in [`KeyFile` syntax](KeyFile#syntax).
107    ///
108    /// # Errors
109    ///
110    /// [`Error::KeyFile`] with one of these reasons, after a "line N:" prefix:
111    ///
112    /// - "group header is not closed with ']'" if a line starts with `[` and
113    ///   has no `]`.
114    /// - "group header has trailing text after ']'" if text other than white
115    ///   space follows the first `]`.
116    /// - "empty group name" if the group name is empty.
117    /// - "group name 'NAME' contains '[' or ']'" if the group name contains
118    ///   a `[`.
119    /// - "expected a key=value pair" if a line is not blank, not a comment,
120    ///   not a group header, and has no `=`.
121    /// - "empty key" if the text before the `=` is empty or only white space.
122    /// - "key 'KEY' precedes any group" if an entry comes before the first
123    ///   group header.
124    pub fn parse(input: &str) -> Result<KeyFile> {
125        let mut keyfile = KeyFile::default();
126        let mut current: Option<usize> = None;
127        // The position of each key in its group, by group position and key.
128        // With this map, a repeated key needs no scan of the group entries.
129        let mut keys: HashMap<(usize, String), usize> = HashMap::new();
130
131        // Split on '\n'. A trailing newline leaves a final empty segment that
132        // is not a line. The loop removes one trailing carriage return from
133        // each raw line, so CRLF input parses and a doubled CR keeps one CR.
134        let body = input.strip_suffix('\n').unwrap_or(input);
135        for (n, raw) in body.split('\n').enumerate() {
136            let lineno = n + 1;
137            let line = raw.strip_suffix('\r').unwrap_or(raw);
138            let trimmed = line.trim_matches(ASCII_WS);
139            if trimmed.is_empty() || trimmed.starts_with('#') {
140                continue;
141            }
142            if let Some(rest) = trimmed.strip_prefix('[') {
143                // The group name runs from '[' to the first ']'. Only white
144                // space can follow the ']', and the name cannot contain '[' or
145                // ']'. These are the rules of `validate_group`, so a header
146                // that the `ostree` command refuses does not parse here.
147                let Some(close) = rest.find(']') else {
148                    return Err(Error::KeyFile(format!(
149                        "line {lineno}: group header is not closed with ']'"
150                    )));
151                };
152                if !rest[close + 1..].trim_matches(ASCII_WS).is_empty() {
153                    return Err(Error::KeyFile(format!(
154                        "line {lineno}: group header has trailing text after ']'"
155                    )));
156                }
157                let name = &rest[..close];
158                if name.is_empty() {
159                    return Err(Error::KeyFile(format!("line {lineno}: empty group name")));
160                }
161                if name.contains(['[', ']']) {
162                    return Err(Error::KeyFile(format!(
163                        "line {lineno}: group name '{name}' contains '[' or ']'"
164                    )));
165                }
166                current = Some(keyfile.group_index_or_insert(name));
167                continue;
168            }
169            let Some(eq) = line.find('=') else {
170                return Err(Error::KeyFile(format!(
171                    "line {lineno}: expected a key=value pair"
172                )));
173            };
174            let key = line[..eq].trim_matches(ASCII_WS);
175            // The `ostree` command removes the leading white space after `=`
176            // and keeps the trailing white space as part of the value.
177            let value = line[eq + 1..].trim_start_matches(ASCII_WS);
178            if key.is_empty() {
179                return Err(Error::KeyFile(format!("line {lineno}: empty key")));
180            }
181            let Some(idx) = current else {
182                return Err(Error::KeyFile(format!(
183                    "line {lineno}: key '{key}' precedes any group"
184                )));
185            };
186            let entries = &mut keyfile.groups[idx].entries;
187            match keys.get(&(idx, key.to_string())) {
188                Some(&at) => entries[at].1 = value.to_string(),
189                None => {
190                    keys.insert((idx, key.to_string()), entries.len());
191                    entries.push((key.to_string(), value.to_string()));
192                }
193            }
194        }
195        Ok(keyfile)
196    }
197
198    /// Returns the position of `name` in `groups`. If the group is absent,
199    /// adds a new empty group at the end.
200    fn group_index_or_insert(&mut self, name: &str) -> usize {
201        if let Some(&i) = self.index.get(name) {
202            return i;
203        }
204        self.groups.push(Group {
205            name: name.to_string(),
206            entries: Vec::new(),
207        });
208        self.index.insert(name.to_string(), self.groups.len() - 1);
209        self.groups.len() - 1
210    }
211
212    fn group(&self, name: &str) -> Option<&Group> {
213        self.index.get(name).map(|&i| &self.groups[i])
214    }
215
216    /// Returns `true` if the key file has the group `group`.
217    pub fn has_group(&self, group: &str) -> bool {
218        self.index.contains_key(group)
219    }
220
221    /// Returns the name of the group `group` as the key file holds it, or
222    /// `None` if the key file has no such group.
223    ///
224    /// The name is equal to `group`. It borrows from the key file, so it
225    /// lives as long as the key file and not as long as `group`.
226    pub fn group_name(&self, group: &str) -> Option<&str> {
227        self.index
228            .get_key_value(group)
229            .map(|(name, _)| name.as_str())
230    }
231
232    /// Returns an iterator over the group names in file order.
233    pub fn groups(&self) -> impl Iterator<Item = &str> {
234        self.groups.iter().map(|g| g.name.as_str())
235    }
236
237    /// Returns an iterator over the keys of one group in file order.
238    ///
239    /// If the group is absent, the iterator is empty.
240    pub fn keys(&self, group: &str) -> impl Iterator<Item = &str> {
241        self.group(group)
242            .into_iter()
243            .flat_map(|g| g.entries.iter().map(|(k, _)| k.as_str()))
244    }
245
246    fn find(&self, group: &str, key: &str) -> Option<&str> {
247        self.group(group)?
248            .entries
249            .iter()
250            .find(|(k, _)| k == key)
251            .map(|(_, v)| v.as_str())
252    }
253
254    /// Returns the raw value text of a key.
255    ///
256    /// The text keeps its escape sequences. If the group or the key is absent,
257    /// the method returns `None`.
258    pub fn get_value(&self, group: &str, key: &str) -> Option<&str> {
259        self.find(group, key)
260    }
261
262    /// Returns the unescaped string value of a key.
263    ///
264    /// The method replaces each escape sequence with its character:
265    ///
266    /// - `\s` with a space
267    /// - `\t` with a tab
268    /// - `\n` with a newline
269    /// - `\r` with a carriage return
270    /// - `\\` with a backslash
271    /// - `\;` with a `;`
272    ///
273    /// If the group or the key is absent, the method returns `Ok(None)`.
274    ///
275    /// # Errors
276    ///
277    /// - [`Error::KeyFile`] with the reason "invalid escape '\X'" if a
278    ///   backslash comes before a character `X` that is not in the list.
279    /// - [`Error::KeyFile`] with the reason "value ends with a lone backslash"
280    ///   if the value ends with a backslash that starts no escape sequence.
281    pub fn get_string(&self, group: &str, key: &str) -> Result<Option<String>> {
282        self.find(group, key)
283            .map(KeyFile::decode_string)
284            .transpose()
285    }
286
287    /// Returns the boolean value of a key.
288    ///
289    /// The value text `true` or `1` gives `true`, and `false` or `0` gives
290    /// `false`. The match is exact. If the group or the key is absent, the
291    /// method returns `Ok(None)`.
292    ///
293    /// # Errors
294    ///
295    /// [`Error::KeyFile`] with the reason "value 'VALUE' for GROUP.KEY is not a
296    /// boolean" if the value text is not one of the four values.
297    pub fn get_bool(&self, group: &str, key: &str) -> Result<Option<bool>> {
298        match self.find(group, key) {
299            None => Ok(None),
300            Some(raw) => KeyFile::decode_bool(raw).map(Some).ok_or_else(|| {
301                Error::KeyFile(format!("value '{raw}' for {group}.{key} is not a boolean"))
302            }),
303        }
304    }
305
306    /// Returns the signed integer value of a key.
307    ///
308    /// The value text is a decimal `i64` with an optional `-` sign. If the
309    /// group or the key is absent, the method returns `Ok(None)`.
310    ///
311    /// # Errors
312    ///
313    /// [`Error::KeyFile`] with the reason "value 'VALUE' for GROUP.KEY is not
314    /// an integer" if the value text is not a decimal `i64`. White space in
315    /// the text and a leading `+` sign cause this error.
316    pub fn get_integer(&self, group: &str, key: &str) -> Result<Option<i64>> {
317        match self.find(group, key) {
318            None => Ok(None),
319            Some(v) => KeyFile::decode_integer(v).map(Some).ok_or_else(|| {
320                Error::KeyFile(format!("value '{v}' for {group}.{key} is not an integer"))
321            }),
322        }
323    }
324
325    /// Returns the list value of a key as unescaped strings.
326    ///
327    /// A `;` separates two items, and `\;` is a `;` in an item. The text after
328    /// the last `;` is an item only if it is not empty, so a trailing `;` adds
329    /// no empty item. The method unescapes each item as
330    /// [`get_string`](KeyFile::get_string) does. If the group or the key is
331    /// absent, the method returns `Ok(None)`.
332    ///
333    /// # Errors
334    ///
335    /// - [`Error::KeyFile`] with the reason "invalid escape '\X'" if a
336    ///   backslash comes before a character `X` that `get_string` does not
337    ///   accept.
338    /// - [`Error::KeyFile`] with the reason "value ends with a lone backslash"
339    ///   if the value ends with a backslash that starts no escape sequence.
340    pub fn get_string_list(&self, group: &str, key: &str) -> Result<Option<Vec<String>>> {
341        match self.find(group, key) {
342            None => Ok(None),
343            Some(v) => KeyFile::decode_string_list(v).map(Some),
344        }
345    }
346
347    /// Sets the raw value text of a key.
348    ///
349    /// If the group is absent, the method adds it at the end of the file. If
350    /// the key is present, the new value replaces the old value at the same
351    /// position. If the key is absent, the method adds it at the end of the
352    /// group.
353    ///
354    /// The method does not escape the value.
355    /// [`set_string`](KeyFile::set_string) escapes it.
356    ///
357    /// The method checks the group name, the key, and the value, so that the
358    /// [`Display`](std::fmt::Display) output parses to an equal `KeyFile`. If
359    /// a check fails, the key file does not change.
360    ///
361    /// # Errors
362    ///
363    /// [`Error::KeyFile`] if one of these conditions is true:
364    ///
365    /// - The group name is empty.
366    /// - The group name contains `[`, `]`, a newline, or a carriage return.
367    /// - The key is empty.
368    /// - The key starts or ends with a space or a tab.
369    /// - The key contains `=`, a newline, or a carriage return.
370    /// - The key starts with `#` or `[`.
371    /// - The value contains a newline or a carriage return.
372    /// - The value starts with a space or a tab.
373    pub fn set_value(&mut self, group: &str, key: &str, value: &str) -> Result<()> {
374        validate_group(group)?;
375        validate_key(key)?;
376        validate_value(value)?;
377        let idx = self.group_index_or_insert(group);
378        let entries = &mut self.groups[idx].entries;
379        match entries.iter_mut().find(|(k, _)| k == key) {
380            Some(entry) => entry.1 = value.to_string(),
381            None => entries.push((key.to_string(), value.to_string())),
382        }
383        Ok(())
384    }
385
386    /// Sets the string value of a key and escapes the value.
387    ///
388    /// The method escapes the value as the `ostree` command does when it
389    /// writes a value:
390    ///
391    /// - A backslash becomes `\\`, a newline `\n`, and a carriage return `\r`,
392    ///   at each position in the value.
393    /// - In the run of white space at the start of the value, each space
394    ///   becomes `\s` and each tab `\t`.
395    /// - A space or a tab after that run, and a `;`, stay as they are.
396    ///
397    /// The escaped value parses again to the same text, and
398    /// [`get_string`](KeyFile::get_string) returns the original value. The
399    /// method places the group and the key as
400    /// [`set_value`](KeyFile::set_value) does. `set_value` stores a value
401    /// that is already escaped.
402    ///
403    /// # Errors
404    ///
405    /// [`Error::KeyFile`] if the group name or the key fails a check of
406    /// [`set_value`](KeyFile::set_value). The escaped value always passes the
407    /// checks.
408    pub fn set_string(&mut self, group: &str, key: &str, value: &str) -> Result<()> {
409        self.set_value(group, key, &KeyFile::encode_string(value))
410    }
411
412    /// Sets the list value of a key and escapes each item.
413    ///
414    /// [`get_string_list`](KeyFile::get_string_list) returns the same list.
415    /// The method escapes each item as [`set_string`](KeyFile::set_string)
416    /// escapes a value, so each space and tab at the start of an item becomes
417    /// `\s` or `\t`. A `;` in an item becomes `\;`.
418    ///
419    /// A `;` follows each item, also the last item. An empty list gives an
420    /// empty value. Because the last item always has a separator, an empty
421    /// item reads back: `["a", ""]` gives `a;;`, and `[""]` gives `;`.
422    ///
423    /// # Errors
424    ///
425    /// [`Error::KeyFile`] if the group name or the key fails a check of
426    /// [`set_value`](KeyFile::set_value). The escaped value always passes the
427    /// checks.
428    pub fn set_string_list(
429        &mut self,
430        group: &str,
431        key: &str,
432        items: &[impl AsRef<str>],
433    ) -> Result<()> {
434        self.set_value(group, key, &KeyFile::encode_string_list(items))
435    }
436
437    /// Removes one key and returns `true` if the key was present.
438    ///
439    /// The group stays, also when it loses its last key. The `ostree` command
440    /// keeps the header of an empty group in the same way.
441    /// [`Display`](std::fmt::Display) writes the header with no entries.
442    pub fn remove_key(&mut self, group: &str, key: &str) -> bool {
443        let Some(entries) = self.index.get(group).map(|&i| &mut self.groups[i].entries) else {
444            return false;
445        };
446        let Some(index) = entries.iter().position(|(k, _)| k == key) else {
447            return false;
448        };
449        entries.remove(index);
450        true
451    }
452
453    /// Removes a group and its keys, and returns `true` if the group was
454    /// present.
455    ///
456    /// The other groups keep their order.
457    pub fn remove_group(&mut self, group: &str) -> bool {
458        let Some(index) = self.index.remove(group) else {
459            return false;
460        };
461        self.groups.remove(index);
462        for i in self.index.values_mut() {
463            if *i > index {
464                *i -= 1;
465            }
466        }
467        true
468    }
469
470    /// Decodes the raw text of a string value, as
471    /// [`get_string`](KeyFile::get_string) does.
472    ///
473    /// The function is not a stable API.
474    #[doc(hidden)]
475    pub fn decode_string(raw: &str) -> Result<String> {
476        unescape(raw)
477    }
478
479    /// Encodes a string value as raw text, as
480    /// [`set_string`](KeyFile::set_string) does.
481    ///
482    /// The function is not a stable API.
483    #[doc(hidden)]
484    pub fn encode_string(value: &str) -> String {
485        escape(value)
486    }
487
488    /// Decodes the raw text of a boolean value, as
489    /// [`get_bool`](KeyFile::get_bool) does. Returns `None` if the text is
490    /// not `true`, `1`, `false`, or `0`.
491    ///
492    /// The function is not a stable API.
493    #[doc(hidden)]
494    pub fn decode_bool(raw: &str) -> Option<bool> {
495        match raw {
496            "true" | "1" => Some(true),
497            "false" | "0" => Some(false),
498            _ => None,
499        }
500    }
501
502    /// Decodes the raw text of an integer value, as
503    /// [`get_integer`](KeyFile::get_integer) does. Returns `None` if the
504    /// text is not a decimal `i64`.
505    ///
506    /// The function is not a stable API.
507    #[doc(hidden)]
508    pub fn decode_integer(raw: &str) -> Option<i64> {
509        // `str::parse` takes a leading `+`. The `ostree` command reads such a
510        // value as no value, so the port refuses it.
511        if raw.starts_with('+') {
512            return None;
513        }
514        raw.parse::<i64>().ok()
515    }
516
517    /// Decodes the raw text of a list value, as
518    /// [`get_string_list`](KeyFile::get_string_list) does.
519    ///
520    /// The function is not a stable API.
521    #[doc(hidden)]
522    pub fn decode_string_list(raw: &str) -> Result<Vec<String>> {
523        split_list(raw)
524    }
525
526    /// Encodes a list value as raw text, as
527    /// [`set_string_list`](KeyFile::set_string_list) does.
528    ///
529    /// The function is not a stable API.
530    #[doc(hidden)]
531    pub fn encode_string_list(items: &[impl AsRef<str>]) -> String {
532        let mut value = String::new();
533        for item in items {
534            // `escape` writes a backslash only as the first character of a
535            // two-character sequence. The second character is never `;`, so
536            // each `;` that `escape` writes stands alone. The `\;` added here
537            // stays a single escape sequence.
538            for c in escape(item.as_ref()).chars() {
539                if c == ';' {
540                    value.push('\\');
541                }
542                value.push(c);
543            }
544            value.push(';');
545        }
546        value
547    }
548}
549
550/// The white space that the `ostree` command trims: ASCII space and tab.
551///
552/// These facts come from crafted config files that the `ostree` command read:
553///
554/// - It ignores a line of only spaces or only tabs.
555/// - It removes a leading space or tab before a group header or a comment.
556/// - It removes a space or a tab around a key.
557/// - It keeps a non-breaking space (U+00A0) and all other non-ASCII white
558///   space everywhere.
559const ASCII_WS: [char; 2] = [' ', '\t'];
560
561/// Checks that a group name is not empty and has no structural character.
562///
563/// A structural character changes how the `Display` output parses. The
564/// checks of `validate_key` and `validate_value` have the same purpose.
565fn validate_group(name: &str) -> Result<()> {
566    if name.is_empty() {
567        return Err(Error::KeyFile("group name is empty".into()));
568    }
569    if name.contains(['\n', '\r', '[', ']']) {
570        return Err(Error::KeyFile(format!(
571            "group name '{name}' contains a structural character"
572        )));
573    }
574    Ok(())
575}
576
577fn validate_key(key: &str) -> Result<()> {
578    if key.is_empty() {
579        return Err(Error::KeyFile("key is empty".into()));
580    }
581    if key.starts_with(ASCII_WS) || key.ends_with(ASCII_WS) {
582        return Err(Error::KeyFile(format!(
583            "key '{key}' has leading or trailing whitespace"
584        )));
585    }
586    if key.contains(['\n', '\r', '=']) {
587        return Err(Error::KeyFile(format!(
588            "key '{key}' contains a structural character"
589        )));
590    }
591    if key.starts_with('#') || key.starts_with('[') {
592        return Err(Error::KeyFile(format!(
593            "key '{key}' begins with '#' or '[' and would not reparse"
594        )));
595    }
596    Ok(())
597}
598
599fn validate_value(value: &str) -> Result<()> {
600    if value.contains(['\n', '\r']) {
601        return Err(Error::KeyFile(
602            "value contains a newline; escape it as \\n".into(),
603        ));
604    }
605    if value.starts_with([' ', '\t']) {
606        return Err(Error::KeyFile(
607            "value begins with whitespace; escape it as \\s".into(),
608        ));
609    }
610    Ok(())
611}
612
613/// Writes the groups and the keys in file order, in the GLib key file layout.
614///
615/// Each group starts with a `[name]` line, and each entry is a `key=value`
616/// line. A blank line separates two groups. `to_string` gives the text of
617/// the whole file.
618impl std::fmt::Display for KeyFile {
619    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
620        for (i, group) in self.groups.iter().enumerate() {
621            if i > 0 {
622                f.write_str("\n")?;
623            }
624            writeln!(f, "[{}]", group.name)?;
625            for (key, value) in &group.entries {
626                writeln!(f, "{key}={value}")?;
627            }
628        }
629        Ok(())
630    }
631}
632
633/// Escapes a string value as the `ostree` command does when it writes a value.
634///
635/// The rules come from `ostree config set` with crafted values and a read of
636/// the raw config bytes:
637///
638/// - A backslash becomes `\\`, a newline `\n`, and a carriage return `\r`, at
639///   each position in the value.
640/// - In the run of white space at the start of the value, each space becomes
641///   `\s` and each tab `\t`.
642/// - A space or a tab after that run, and a `;`, stay as they are.
643///
644/// [`unescape`] reverses each of these sequences.
645fn escape(s: &str) -> String {
646    let mut out = String::with_capacity(s.len());
647    let mut leading = true;
648    for c in s.chars() {
649        match c {
650            '\\' => {
651                out.push_str("\\\\");
652                leading = false;
653            }
654            '\n' => {
655                out.push_str("\\n");
656                leading = false;
657            }
658            '\r' => {
659                out.push_str("\\r");
660                leading = false;
661            }
662            ' ' if leading => out.push_str("\\s"),
663            '\t' if leading => out.push_str("\\t"),
664            _ => {
665                out.push(c);
666                leading = false;
667            }
668        }
669    }
670    out
671}
672
673fn unescape(s: &str) -> Result<String> {
674    let mut out = String::with_capacity(s.len());
675    let mut chars = s.chars();
676    while let Some(c) = chars.next() {
677        if c != '\\' {
678            out.push(c);
679            continue;
680        }
681        match chars.next() {
682            Some('s') => out.push(' '),
683            Some('n') => out.push('\n'),
684            Some('t') => out.push('\t'),
685            Some('r') => out.push('\r'),
686            Some('\\') => out.push('\\'),
687            Some(';') => out.push(';'),
688            Some(other) => return Err(Error::KeyFile(format!("invalid escape '\\{other}'"))),
689            None => return Err(Error::KeyFile("value ends with a lone backslash".into())),
690        }
691    }
692    Ok(out)
693}
694
695fn split_list(raw: &str) -> Result<Vec<String>> {
696    let mut items: Vec<String> = Vec::new();
697    let mut current = String::new();
698    let mut chars = raw.chars();
699    while let Some(c) = chars.next() {
700        match c {
701            '\\' => match chars.next() {
702                // The escape sequence stays as it is. `unescape` resolves it
703                // after the split.
704                Some(next) => {
705                    current.push('\\');
706                    current.push(next);
707                }
708                None => return Err(Error::KeyFile("value ends with a lone backslash".into())),
709            },
710            ';' => {
711                items.push(std::mem::take(&mut current));
712            }
713            _ => current.push(c),
714        }
715    }
716    if !current.is_empty() {
717        items.push(current);
718    }
719    items.iter().map(|s| unescape(s)).collect()
720}
721
722#[cfg(test)]
723mod tests {
724    use super::*;
725
726    // The exact bytes that the `ostree` command wrote for the config of an
727    // archive repo.
728    const ARCHIVE_CONFIG: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";
729
730    #[test]
731    fn parses_tool_written_config() {
732        let kf = KeyFile::parse(ARCHIVE_CONFIG).unwrap();
733        assert_eq!(kf.get_value("core", "repo_version"), Some("1"));
734        assert_eq!(kf.get_value("core", "mode"), Some("archive-z2"));
735        assert_eq!(kf.get_integer("core", "repo_version").unwrap(), Some(1));
736        assert_eq!(kf.get_value("core", "absent"), None);
737        assert_eq!(kf.get_value("nogroup", "x"), None);
738    }
739
740    #[test]
741    fn round_trips_tool_written_config_byte_for_byte() {
742        let kf = KeyFile::parse(ARCHIVE_CONFIG).unwrap();
743        assert_eq!(kf.to_string(), ARCHIVE_CONFIG);
744    }
745
746    #[test]
747    fn drops_comments_and_blanks_and_trims_leading_value_whitespace() {
748        // The parser removes the leading white space of a line, the white
749        // space around a key, and the white space after `=`. It keeps the
750        // trailing white space of a value, as the `ostree` command does.
751        let text = "# a comment\n\n[core]\n  repo_version = 1\n\n# trailing\nmode=bare \n";
752        let kf = KeyFile::parse(text).unwrap();
753        assert_eq!(kf.get_value("core", "repo_version"), Some("1"));
754        assert_eq!(kf.get_integer("core", "repo_version").unwrap(), Some(1));
755        assert_eq!(kf.get_value("core", "mode"), Some("bare "));
756    }
757
758    #[test]
759    fn value_keeps_trailing_and_strips_leading_whitespace() {
760        let kf = KeyFile::parse("[g]\nk=  a b  \n").unwrap();
761        assert_eq!(kf.get_value("g", "k"), Some("a b  "));
762    }
763
764    #[test]
765    fn hash_inside_a_value_is_literal() {
766        let kf = KeyFile::parse("[core]\nk=a # b\n").unwrap();
767        assert_eq!(kf.get_value("core", "k"), Some("a # b"));
768    }
769
770    #[test]
771    fn accepts_crlf_line_endings() {
772        let kf = KeyFile::parse("[core]\r\nrepo_version=1\r\nk=v\r\n").unwrap();
773        assert_eq!(kf.get_value("core", "k"), Some("v"));
774        assert_eq!(kf.get_integer("core", "repo_version").unwrap(), Some(1));
775    }
776
777    #[test]
778    fn strips_one_trailing_cr_per_line() {
779        // The `ostree` command removes one trailing carriage return from a
780        // raw line. A doubled CR before the newline keeps one CR in the value.
781        // A second removal drops that byte.
782        let kf = KeyFile::parse("[g]\r\nk=v\r\r\n").unwrap();
783        assert_eq!(kf.get_value("g", "k"), Some("v\r"));
784    }
785
786    #[test]
787    fn accepts_indented_comment_header_and_key() {
788        let kf = KeyFile::parse("   # c\n   [core]\n  k=v\n").unwrap();
789        assert_eq!(kf.get_value("core", "k"), Some("v"));
790    }
791
792    #[test]
793    fn duplicate_groups_merge_and_last_key_wins() {
794        let kf = KeyFile::parse("[s]\na=first\n[s]\nb=second\na=third\n").unwrap();
795        assert_eq!(kf.get_value("s", "a"), Some("third"));
796        assert_eq!(kf.get_value("s", "b"), Some("second"));
797        assert_eq!(kf.groups().count(), 1);
798    }
799
800    #[test]
801    fn rejects_empty_group_and_semicolon_line() {
802        assert!(KeyFile::parse("[]\nk=v\n").is_err());
803        // A line that starts with `;` is not a comment. With no `=`, it is an
804        // error.
805        assert!(KeyFile::parse("[core]\n;not a comment\nk=v\n").is_err());
806    }
807
808    #[test]
809    fn keys_lists_one_group_in_file_order() {
810        // A repeated header merges into the first group, and a repeated key
811        // keeps its first position.
812        let text = "[a]\nz=1\ny=2\n[b]\nx=3\n[a]\nw=4\nz=5\n";
813        let kf = KeyFile::parse(text).unwrap();
814        assert_eq!(kf.keys("a").collect::<Vec<_>>(), ["z", "y", "w"]);
815        assert_eq!(kf.keys("b").collect::<Vec<_>>(), ["x"]);
816        assert_eq!(kf.keys("absent").count(), 0);
817    }
818
819    #[test]
820    fn group_name_gives_the_held_name() {
821        let kf = KeyFile::parse("[a]\nk=v\n[remote \"o\"]\n").unwrap();
822        assert_eq!(kf.group_name("a"), Some("a"));
823        assert_eq!(kf.group_name("remote \"o\""), Some("remote \"o\""));
824        assert_eq!(kf.group_name("absent"), None);
825        assert_eq!(kf.group_name("remote \"other\""), None);
826    }
827
828    #[test]
829    fn parses_quoted_remote_group_name() {
830        let text = "[remote \"origin\"]\nurl=https://example.invalid/repo\ngpg-verify=false\n";
831        let kf = KeyFile::parse(text).unwrap();
832        assert!(kf.has_group("remote \"origin\""));
833        assert_eq!(
834            kf.get_value("remote \"origin\"", "url"),
835            Some("https://example.invalid/repo")
836        );
837        assert_eq!(
838            kf.get_bool("remote \"origin\"", "gpg-verify").unwrap(),
839            Some(false)
840        );
841    }
842
843    #[test]
844    fn boolean_and_integer_validation() {
845        let kf = KeyFile::parse(
846            "[core]\nt=true\nf=false\none=1\nzero=0\nbad=maybe\nyes=yes\ncase=True\ntwo=2\ndepth=-1\n",
847        )
848        .unwrap();
849        assert_eq!(kf.get_bool("core", "t").unwrap(), Some(true));
850        assert_eq!(kf.get_bool("core", "f").unwrap(), Some(false));
851        assert_eq!(kf.get_bool("core", "one").unwrap(), Some(true));
852        assert_eq!(kf.get_bool("core", "zero").unwrap(), Some(false));
853        // The `ostree` command accepts only `true`, `false`, `1`, and `0`,
854        // matched exactly.
855        assert!(kf.get_bool("core", "bad").is_err());
856        assert!(kf.get_bool("core", "yes").is_err());
857        assert!(kf.get_bool("core", "case").is_err());
858        assert!(kf.get_bool("core", "two").is_err());
859        assert_eq!(kf.get_integer("core", "depth").unwrap(), Some(-1));
860    }
861
862    #[test]
863    fn integer_refuses_a_leading_plus_sign() {
864        // The port reads an integer as a whole decimal value with an optional
865        // `-` sign. The `ostree` command reads `+101` as no value and applies
866        // the default of the key, so the port refuses it.
867        let kf = KeyFile::parse("[core]\nplus=+101\nminus=-5\nplain=101\n").unwrap();
868        assert_eq!(
869            kf.get_integer("core", "plus"),
870            Err(Error::KeyFile(
871                "value '+101' for core.plus is not an integer".into()
872            ))
873        );
874        assert_eq!(kf.get_integer("core", "minus").unwrap(), Some(-5));
875        assert_eq!(kf.get_integer("core", "plain").unwrap(), Some(101));
876    }
877
878    #[test]
879    fn string_list_splits_on_semicolons() {
880        let kf = KeyFile::parse("[core]\ndefault-repo-finders=config;mount\n").unwrap();
881        assert_eq!(
882            kf.get_string_list("core", "default-repo-finders").unwrap(),
883            Some(vec!["config".to_string(), "mount".to_string()])
884        );
885        // A trailing separator does not add an empty element.
886        let kf = KeyFile::parse("[core]\nl=a;b;\n").unwrap();
887        assert_eq!(
888            kf.get_string_list("core", "l").unwrap(),
889            Some(vec!["a".to_string(), "b".to_string()])
890        );
891    }
892
893    #[test]
894    fn unescape_handles_glib_sequences() {
895        let kf = KeyFile::parse("[g]\nk=a\\sb\\tc\\\\d\n").unwrap();
896        assert_eq!(
897            kf.get_string("g", "k").unwrap(),
898            Some("a b\tc\\d".to_string())
899        );
900    }
901
902    #[test]
903    fn rejects_key_before_group_and_unclosed_header() {
904        assert!(KeyFile::parse("key=value\n").is_err());
905        assert!(KeyFile::parse("[core\nkey=value\n").is_err());
906    }
907
908    #[test]
909    fn set_value_creates_group_and_updates_in_place() {
910        let mut kf = KeyFile::default();
911        kf.set_value("core", "repo_version", "1").unwrap();
912        kf.set_value("core", "mode", "bare").unwrap();
913        kf.set_value("core", "mode", "archive-z2").unwrap();
914        assert_eq!(kf.to_string(), "[core]\nrepo_version=1\nmode=archive-z2\n");
915    }
916
917    #[test]
918    fn to_string_separates_groups_with_a_blank_line() {
919        let mut kf = KeyFile::default();
920        kf.set_value("core", "repo_version", "1").unwrap();
921        kf.set_value("remote \"o\"", "url", "x").unwrap();
922        assert_eq!(
923            kf.to_string(),
924            "[core]\nrepo_version=1\n\n[remote \"o\"]\nurl=x\n"
925        );
926    }
927
928    #[test]
929    fn set_value_rejects_structural_characters() {
930        let mut kf = KeyFile::default();
931        assert!(kf.set_value("core", "k", "a\nb").is_err()); // newline in value
932        assert!(kf.set_value("core", "k", " lead").is_err()); // leading space
933        assert!(kf.set_value("core", "k", "\ttab").is_err()); // leading tab
934        assert!(kf.set_value("core", "a=b", "v").is_err()); // `=` in key
935        assert!(kf.set_value("core", "a\nb", "v").is_err()); // newline in key
936        assert!(kf.set_value("core", " spaced ", "v").is_err()); // ws around key
937        assert!(kf.set_value("", "k", "v").is_err()); // empty group
938        assert!(kf.set_value("a\nb", "k", "v").is_err()); // newline in group
939        assert!(kf.set_value("a[b]", "k", "v").is_err()); // brackets in group
940        // Spaces and semicolons inside a value are ordinary content.
941        assert!(kf.set_value("core", "list", "a;b;c").is_ok());
942        assert!(kf.set_value("core", "spaces", "a b c").is_ok());
943    }
944
945    #[test]
946    fn set_value_rejects_keys_that_would_not_reparse() {
947        let mut kf = KeyFile::default();
948        // A key that starts with '#' gives a line that the parser drops as a
949        // comment.
950        assert!(kf.set_value("core", "#weird", "v").is_err());
951        // A key that starts with '[' gives a line that the parser reads as a
952        // group header.
953        assert!(kf.set_value("core", "[k", "v").is_err());
954        // A '#' or '[' elsewhere in the key is ordinary content that reparses.
955        assert!(kf.set_value("core", "a#b", "v").is_ok());
956        assert!(kf.set_value("core", "a[b", "v").is_ok());
957        let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
958        assert_eq!(kf, reparsed);
959    }
960
961    #[test]
962    fn set_value_round_trips_through_display() {
963        let mut kf = KeyFile::default();
964        kf.set_value("remote \"o\"", "url", "https://example.invalid/repo")
965            .unwrap();
966        kf.set_value("remote \"o\"", "finders", "config;mount")
967            .unwrap();
968        kf.set_value("core", "mode", "archive-z2").unwrap();
969        let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
970        assert_eq!(kf, reparsed);
971    }
972
973    #[test]
974    fn parse_display_parse_is_stable() {
975        let text = "# note\n\n[core]\nrepo_version=1\nmode=archive-z2\nval=keep me \n\n\
976                    [remote \"o\"]\nurl=https://example.invalid/repo\ngpg-verify=false\n";
977        let first = KeyFile::parse(text).unwrap();
978        let second = KeyFile::parse(&first.to_string()).unwrap();
979        assert_eq!(first, second);
980    }
981
982    // ---- group-header brackets (observed with `ostree config`) -------------
983
984    #[test]
985    fn group_name_runs_to_first_bracket() {
986        // The `ostree` command refuses each of these whole files. The parser
987        // returns an error for each file and reads no stray group name.
988        // `[a]b]`: text follows the first ']'.
989        assert!(KeyFile::parse("[a]b]\nk=v\n").is_err());
990        // `[a]b]c`: trailing non-']' text after the first ']'.
991        assert!(KeyFile::parse("[a]b]c\nk=v\n").is_err());
992        // `[a[b]`: the group name contains '['.
993        assert!(KeyFile::parse("[a[b]\nk=v\n").is_err());
994        // `[]x]`: empty name plus trailing text.
995        assert!(KeyFile::parse("[]x]\nk=v\n").is_err());
996        // Trailing ASCII white space after the ']' is allowed.
997        let kf = KeyFile::parse("[grp]  \nk=v\n").unwrap();
998        assert_eq!(kf.get_value("grp", "k"), Some("v"));
999    }
1000
1001    // ---- ASCII-only white space trim (observed with `ostree config`) -------
1002
1003    #[test]
1004    fn non_ascii_whitespace_is_preserved() {
1005        // A line that is only a non-breaking space is not blank. With no '=',
1006        // it is a parse error, as in the `ostree` command.
1007        assert!(KeyFile::parse("[g]\n\u{a0}\nk=v\n").is_err());
1008        // A non-breaking space around a key stays part of the key name.
1009        let kf = KeyFile::parse("[g]\n\u{a0}k\u{a0}=v\n").unwrap();
1010        assert_eq!(kf.get_value("g", "\u{a0}k\u{a0}"), Some("v"));
1011        assert_eq!(kf.get_value("g", "k"), None);
1012        // A non-breaking space around a value is kept on both sides.
1013        let kf = KeyFile::parse("[g]\nvk=\u{a0}nbv\u{a0}\n").unwrap();
1014        assert_eq!(kf.get_value("g", "vk"), Some("\u{a0}nbv\u{a0}"));
1015    }
1016
1017    #[test]
1018    fn ascii_whitespace_lines_and_keys_are_trimmed() {
1019        // The parser ignores a line of only spaces or only tabs. It removes a
1020        // leading tab before a header or a comment, and the tabs around a key.
1021        let kf = KeyFile::parse("[g]\n   \n\t\n\t[h]\n\t#c\n\tk\t=v\n").unwrap();
1022        assert_eq!(kf.get_value("h", "k"), Some("v"));
1023    }
1024
1025    #[test]
1026    fn set_value_allows_non_ascii_whitespace_in_key() {
1027        let mut kf = KeyFile::default();
1028        // ASCII white space around a key does not parse back, so `set_value`
1029        // refuses it.
1030        assert!(kf.set_value("g", " k", "v").is_err());
1031        assert!(kf.set_value("g", "k\t", "v").is_err());
1032        // A trailing non-breaking space parses back, so `set_value` accepts it.
1033        assert!(kf.set_value("g", "k\u{a0}", "v").is_ok());
1034        let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
1035        assert_eq!(kf, reparsed);
1036    }
1037
1038    // ---- value escape on write (observed with `ostree config set`) ---------
1039
1040    #[test]
1041    fn set_string_escapes_like_the_tool() {
1042        // (input, stored form) pairs, read back from the raw config bytes that
1043        // the `ostree` command wrote for `ostree config set core.<k> <input>`.
1044        for (input, stored) in [
1045            ("a\nb", "a\\nb"),
1046            ("a\tb", "a\tb"), // interior tab is literal
1047            ("a\rb", "a\\rb"),
1048            ("a\\b", "a\\\\b"),
1049            ("   ab", "\\s\\s\\sab"),
1050            ("ab   ", "ab   "),   // trailing spaces are literal
1051            ("a;b", "a;b"),       // the separator is literal
1052            ("\tab", "\\tab"),    // leading tab
1053            ("ab\t", "ab\t"),     // trailing tab is literal
1054            ("a b", "a b"),       // interior space is literal
1055            ("   ", "\\s\\s\\s"), // an all-space value is all leading
1056            (" \tx", "\\s\\tx"),  // the leading run mixes space and tab
1057        ] {
1058            let mut kf = KeyFile::default();
1059            kf.set_string("core", "k", input).unwrap();
1060            assert_eq!(kf.get_value("core", "k"), Some(stored), "input {input:?}");
1061        }
1062    }
1063
1064    #[test]
1065    fn set_string_get_string_round_trips() {
1066        for v in [
1067            "plain",
1068            "a\nb\tc",
1069            "  leading and trailing  ",
1070            "back\\slash",
1071            "a\r\nb",
1072            "line1\nline2",
1073            "",
1074        ] {
1075            let mut kf = KeyFile::default();
1076            kf.set_string("core", "k", v).unwrap();
1077            // The stored value carries no raw newline, so it is a single line.
1078            assert!(!kf.get_value("core", "k").unwrap().contains(['\n', '\r']));
1079            // get_string reverses the escape sequences.
1080            assert_eq!(kf.get_string("core", "k").unwrap().as_deref(), Some(v));
1081            // The serialized file reparses to an equal KeyFile.
1082            let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
1083            assert_eq!(kf, reparsed);
1084        }
1085    }
1086
1087    // ---- string lists on write ----------------------------------------------
1088
1089    #[test]
1090    fn set_string_list_writes_a_trailing_separator() {
1091        let mut kf = KeyFile::default();
1092        kf.set_string_list("g", "k", &["a", "b"]).unwrap();
1093        assert_eq!(kf.get_value("g", "k"), Some("a;b;"));
1094        assert_eq!(kf.to_string(), "[g]\nk=a;b;\n");
1095    }
1096
1097    /// (items, stored raw value) pairs shared by the escaping and round-trip
1098    /// tests.
1099    const LIST_CASES: &[(&[&str], &str)] = &[
1100        (&["a;b", "c"], "a\\;b;c;"),
1101        (&["a b"], "a b;"),
1102        (&[" a"], "\\sa;"),
1103        (&["x", " b"], "x;\\sb;"),
1104        (&["a ", "b "], "a ;b ;"),
1105        (&["\tx", "y\tz"], "\\tx;y\tz;"), // an interior tab is literal
1106        (&["a\\b"], "a\\\\b;"),
1107        (&["\\;"], "\\\\\\;;"),
1108        (&["a\\"], "a\\\\;"),
1109        (&["\\\\;"], "\\\\\\\\\\;;"),
1110        (&[";"], "\\;;"),
1111        (&[";;"], "\\;\\;;"),
1112        (&["a\nb", "c\rd"], "a\\nb;c\\rd;"),
1113    ];
1114
1115    #[test]
1116    fn set_string_list_escapes_each_item() {
1117        for &(items, stored) in LIST_CASES {
1118            let mut kf = KeyFile::default();
1119            kf.set_string_list("g", "k", items).unwrap();
1120            assert_eq!(kf.get_value("g", "k"), Some(stored), "input {items:?}");
1121        }
1122    }
1123
1124    #[test]
1125    fn set_string_list_get_string_list_round_trips() {
1126        let extra: &[&[&str]] = &[
1127            &["#c", "=", "[g]", "k=v"],
1128            &["\u{a0}nb\u{a0}"],
1129            &["   "],
1130            &["a", "", ""],
1131        ];
1132        for &items in LIST_CASES.iter().map(|(items, _)| items).chain(extra) {
1133            let mut kf = KeyFile::default();
1134            kf.set_string_list("g", "k", items).unwrap();
1135            assert_eq!(
1136                kf.get_string_list("g", "k").unwrap().unwrap(),
1137                items,
1138                "input {items:?}"
1139            );
1140            // The stored value carries no raw newline, so it is a single line.
1141            assert!(
1142                !kf.get_value("g", "k").unwrap().contains(['\n', '\r']),
1143                "input {items:?}"
1144            );
1145            // The serialized file reparses to an equal KeyFile and list.
1146            let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
1147            assert_eq!(kf, reparsed, "input {items:?}");
1148            assert_eq!(
1149                reparsed.get_string_list("g", "k").unwrap().unwrap(),
1150                items,
1151                "input {items:?}"
1152            );
1153        }
1154        // An owned list is accepted too.
1155        let owned: Vec<String> = vec!["a;b".to_string(), " c".to_string()];
1156        let mut kf = KeyFile::default();
1157        kf.set_string_list("g", "k", &owned).unwrap();
1158        assert_eq!(kf.get_value("g", "k"), Some("a\\;b;\\sc;"));
1159        assert_eq!(kf.get_string_list("g", "k").unwrap(), Some(owned.clone()));
1160        let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
1161        assert_eq!(kf, reparsed);
1162        assert_eq!(reparsed.get_string_list("g", "k").unwrap(), Some(owned));
1163    }
1164
1165    #[test]
1166    fn set_string_list_keeps_empty_items() {
1167        for (items, stored) in [
1168            (&["a", ""][..], "a;;"),
1169            (&[""][..], ";"),
1170            (&["", "a"][..], ";a;"),
1171            (&["", ""][..], ";;"),
1172        ] {
1173            let mut kf = KeyFile::default();
1174            kf.set_string_list("g", "k", items).unwrap();
1175            assert_eq!(kf.get_value("g", "k"), Some(stored), "input {items:?}");
1176            assert_eq!(
1177                kf.get_string_list("g", "k").unwrap().unwrap(),
1178                items,
1179                "input {items:?}"
1180            );
1181            let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
1182            assert_eq!(
1183                reparsed.get_string_list("g", "k").unwrap().unwrap(),
1184                items,
1185                "input {items:?}"
1186            );
1187        }
1188    }
1189
1190    #[test]
1191    fn set_string_list_writes_an_empty_list_as_an_empty_value() {
1192        let mut kf = KeyFile::default();
1193        kf.set_string_list("g", "k", &[] as &[&str]).unwrap();
1194        assert_eq!(kf.get_value("g", "k"), Some(""));
1195        assert_eq!(kf.to_string(), "[g]\nk=\n");
1196        assert_eq!(kf.get_string_list("g", "k").unwrap(), Some(vec![]));
1197        let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
1198        assert_eq!(reparsed.get_string_list("g", "k").unwrap(), Some(vec![]));
1199    }
1200
1201    #[test]
1202    fn set_string_list_replaces_in_place_and_validates_names() {
1203        let mut kf = KeyFile::parse("[g]\nk=1\nz=2\n").unwrap();
1204        kf.set_string_list("g", "k", &["x"]).unwrap();
1205        assert_eq!(kf.to_string(), "[g]\nk=x;\nz=2\n");
1206        let before = kf.clone();
1207        assert!(kf.set_string_list("a[b", "k", &["x"]).is_err());
1208        assert_eq!(kf, before);
1209        assert!(kf.set_string_list("g", "a=b", &["x"]).is_err());
1210        assert_eq!(kf, before);
1211    }
1212
1213    // ---- removal (observed with `ostree config unset`) ----------------------
1214
1215    #[test]
1216    fn remove_key_keeps_the_group_header() {
1217        // `ostree config set g.k v` followed by `ostree config unset g.k` leaves
1218        // the emptied `[g]` header in the file, which this reproduces.
1219        let mut kf = KeyFile::parse("[core]\nrepo_version=1\nmode=archive-z2\n\n[g]\nk=v\n")
1220            .expect("the file parses");
1221        assert!(kf.remove_key("g", "k"));
1222        assert_eq!(
1223            kf.to_string(),
1224            "[core]\nrepo_version=1\nmode=archive-z2\n\n[g]\n"
1225        );
1226        assert!(kf.has_group("g"));
1227        assert_eq!(kf.get_value("g", "k"), None);
1228    }
1229
1230    #[test]
1231    fn remove_key_reports_an_absent_key_and_group() {
1232        let mut kf = KeyFile::parse(ARCHIVE_CONFIG).expect("the file parses");
1233        assert!(!kf.remove_key("core", "absent"));
1234        assert!(!kf.remove_key("nogroup", "mode"));
1235        // Nothing moved.
1236        assert_eq!(kf.to_string(), ARCHIVE_CONFIG);
1237    }
1238
1239    #[test]
1240    fn remove_key_leaves_the_other_keys_in_order() {
1241        let mut kf =
1242            KeyFile::parse("[core]\nrepo_version=1\nmode=bare\nfsync=false\n").expect("parses");
1243        assert!(kf.remove_key("core", "mode"));
1244        assert_eq!(kf.to_string(), "[core]\nrepo_version=1\nfsync=false\n");
1245    }
1246
1247    #[test]
1248    fn remove_group_drops_the_header_and_its_keys() {
1249        let text = "[core]\nrepo_version=1\nmode=bare\n\n\
1250                    [remote \"a\"]\nurl=https://a.invalid/r\n\n\
1251                    [remote \"b\"]\nurl=https://b.invalid/r\n";
1252        let mut kf = KeyFile::parse(text).expect("the file parses");
1253        assert!(kf.remove_group("remote \"a\""));
1254        assert!(!kf.remove_group("remote \"a\""));
1255        assert_eq!(
1256            kf.to_string(),
1257            "[core]\nrepo_version=1\nmode=bare\n\n[remote \"b\"]\nurl=https://b.invalid/r\n"
1258        );
1259        assert_eq!(kf.groups().collect::<Vec<_>>(), ["core", "remote \"b\""]);
1260    }
1261
1262    #[test]
1263    fn a_rewrite_keeps_untouched_groups_and_drops_comments() {
1264        // This is the rewrite of the `ostree` command. The groups and keys
1265        // that the caller did not change keep their order and their bytes. The
1266        // comment lines and the blank lines of the input are gone.
1267        let text = "# leading comment\n[core]\nrepo_version=1\nmode=archive-z2\n\
1268                    # inner comment\nfoo=bar\n\n[other]\nx=1\n";
1269        let mut kf = KeyFile::parse(text).expect("the file parses");
1270        kf.set_value("core", "new", "v").expect("the key is valid");
1271        assert_eq!(
1272            kf.to_string(),
1273            "[core]\nrepo_version=1\nmode=archive-z2\nfoo=bar\nnew=v\n\n[other]\nx=1\n"
1274        );
1275    }
1276
1277    #[test]
1278    fn set_string_matches_tool_written_line_bytes() {
1279        // The exact stored bytes `ostree config set core.knl $'a\nb'` and
1280        // `... core.klead '   ab'` produced in a fresh archive repo config.
1281        let mut kf = KeyFile::default();
1282        kf.set_value("core", "repo_version", "1").unwrap();
1283        kf.set_value("core", "mode", "archive-z2").unwrap();
1284        kf.set_string("core", "knl", "a\nb").unwrap();
1285        kf.set_string("core", "klead", "   ab").unwrap();
1286        assert_eq!(
1287            kf.to_string(),
1288            "[core]\nrepo_version=1\nmode=archive-z2\nknl=a\\nb\nklead=\\s\\s\\sab\n"
1289        );
1290    }
1291
1292    // ---- the codec functions agree with the getters and the setters ---------
1293
1294    /// The raw values that the codec tests read, each as a `k=` line.
1295    const CODEC_RAW: &[&str] = &[
1296        "",
1297        "plain",
1298        r"a\sb\tc\nd\re\\f\;g",
1299        "\\sleading",
1300        "trailing  ",
1301        "\\q",
1302        "lone\\",
1303        "true",
1304        "1",
1305        "false",
1306        "0",
1307        "yes",
1308        "True",
1309        "+1",
1310        "-1",
1311        "42",
1312        "9223372036854775807",
1313        "9223372036854775808",
1314        "-9223372036854775809",
1315        "1 ",
1316        "a;b;",
1317        r"a\;b;c",
1318        ";",
1319        ";;",
1320        "a;;b",
1321        "\\sa;b\\s;",
1322    ];
1323
1324    #[test]
1325    fn decode_functions_agree_with_the_getters() {
1326        for raw in CODEC_RAW {
1327            let kf = KeyFile::parse(&format!("[g]\nk={raw}\n")).unwrap();
1328            let raw = kf.get_value("g", "k").unwrap();
1329            assert_eq!(
1330                KeyFile::decode_string(raw).map(Some),
1331                kf.get_string("g", "k"),
1332                "{raw:?}"
1333            );
1334            assert_eq!(
1335                KeyFile::decode_bool(raw),
1336                kf.get_bool("g", "k").ok().flatten(),
1337                "{raw:?}"
1338            );
1339            assert_eq!(
1340                kf.get_bool("g", "k").is_err(),
1341                KeyFile::decode_bool(raw).is_none()
1342            );
1343            assert_eq!(
1344                KeyFile::decode_integer(raw),
1345                kf.get_integer("g", "k").ok().flatten(),
1346                "{raw:?}"
1347            );
1348            assert_eq!(
1349                kf.get_integer("g", "k").is_err(),
1350                KeyFile::decode_integer(raw).is_none()
1351            );
1352            assert_eq!(
1353                KeyFile::decode_string_list(raw).map(Some),
1354                kf.get_string_list("g", "k"),
1355                "{raw:?}"
1356            );
1357        }
1358    }
1359
1360    #[test]
1361    fn decode_bool_and_integer_take_exact_text() {
1362        assert_eq!(KeyFile::decode_bool("true"), Some(true));
1363        assert_eq!(KeyFile::decode_bool("0"), Some(false));
1364        for raw in ["yes", "True", " true", "true ", ""] {
1365            assert_eq!(KeyFile::decode_bool(raw), None, "{raw:?}");
1366        }
1367        assert_eq!(KeyFile::decode_integer("-1"), Some(-1));
1368        for raw in ["+1", " 1", "1 ", "", "9223372036854775808", "1.0"] {
1369            assert_eq!(KeyFile::decode_integer(raw), None, "{raw:?}");
1370        }
1371    }
1372
1373    #[test]
1374    fn encode_functions_agree_with_the_setters() {
1375        for value in [
1376            "", "plain", "  lead", "\ttab", "a\\b", "a\nb\r", "a;b", "trail  ",
1377        ] {
1378            let mut kf = KeyFile::default();
1379            kf.set_string("g", "k", value).unwrap();
1380            assert_eq!(
1381                kf.get_value("g", "k"),
1382                Some(KeyFile::encode_string(value).as_str()),
1383                "{value:?}"
1384            );
1385        }
1386        for &(items, stored) in LIST_CASES {
1387            assert_eq!(KeyFile::encode_string_list(items), stored, "{items:?}");
1388            let mut kf = KeyFile::default();
1389            kf.set_string_list("g", "k", items).unwrap();
1390            assert_eq!(kf.get_value("g", "k"), Some(stored), "{items:?}");
1391        }
1392        assert_eq!(KeyFile::encode_string_list(&[] as &[&str]), "");
1393        assert_eq!(KeyFile::encode_string_list(&["a", ""]), "a;;");
1394    }
1395}