1use crate::error::{Error, Result};
26
27#[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 pub fn parse(input: &str) -> Result<KeyFile> {
43 let mut groups: Vec<Group> = Vec::new();
44 let mut current: Option<usize> = None;
45
46 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 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 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 pub fn has_group(&self, group: &str) -> bool {
121 self.groups.iter().any(|g| g.name == group)
122 }
123
124 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 pub fn get_value(&self, group: &str, key: &str) -> Option<&str> {
141 self.find(group, key)
142 }
143
144 pub fn get_string(&self, group: &str, key: &str) -> Result<Option<String>> {
146 self.find(group, key).map(unescape).transpose()
147 }
148
149 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 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 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 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 pub fn set_string(&mut self, group: &str, key: &str, value: &str) -> Result<()> {
216 self.set_value(group, key, &escape(value))
217 }
218
219 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 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
252const ASCII_WS: [char; 2] = [' ', '\t'];
258
259fn 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
309impl 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
326fn 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 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 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 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 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 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 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 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()); assert!(kf.set_value("core", "k", " lead").is_err()); assert!(kf.set_value("core", "k", "\ttab").is_err()); assert!(kf.set_value("core", "a=b", "v").is_err()); assert!(kf.set_value("core", "a\nb", "v").is_err()); assert!(kf.set_value("core", " spaced ", "v").is_err()); assert!(kf.set_value("", "k", "v").is_err()); assert!(kf.set_value("a\nb", "k", "v").is_err()); assert!(kf.set_value("a[b]", "k", "v").is_err()); 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 assert!(kf.set_value("core", "#weird", "v").is_err());
596 assert!(kf.set_value("core", "[k", "v").is_err());
599 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 #[test]
630 fn group_name_runs_to_first_bracket() {
631 assert!(KeyFile::parse("[a]b]\nk=v\n").is_err());
635 assert!(KeyFile::parse("[a]b]c\nk=v\n").is_err());
637 assert!(KeyFile::parse("[a[b]\nk=v\n").is_err());
639 assert!(KeyFile::parse("[]x]\nk=v\n").is_err());
641 let kf = KeyFile::parse("[grp] \nk=v\n").unwrap();
643 assert_eq!(kf.get_value("grp", "k"), Some("v"));
644 }
645
646 #[test]
649 fn non_ascii_whitespace_is_preserved() {
650 assert!(KeyFile::parse("[g]\n\u{a0}\nk=v\n").is_err());
653 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 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 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 assert!(kf.set_value("g", " k", "v").is_err());
675 assert!(kf.set_value("g", "k\t", "v").is_err());
676 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 #[test]
685 fn set_string_escapes_like_the_tool() {
686 for (input, stored) in [
689 ("a\nb", "a\\nb"),
690 ("a\tb", "a\tb"), ("a\rb", "a\\rb"),
692 ("a\\b", "a\\\\b"),
693 (" ab", "\\s\\s\\sab"),
694 ("ab ", "ab "), ("a;b", "a;b"), ("\tab", "\\tab"), ("ab\t", "ab\t"), ("a b", "a b"), (" ", "\\s\\s\\s"), (" \tx", "\\s\\tx"), ] {
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 assert!(!kf.get_value("core", "k").unwrap().contains(['\n', '\r']));
723 assert_eq!(kf.get_string("core", "k").unwrap().as_deref(), Some(v));
725 let reparsed = KeyFile::parse(&kf.to_string()).unwrap();
727 assert_eq!(kf, reparsed);
728 }
729 }
730
731 #[test]
734 fn remove_key_keeps_the_group_header() {
735 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 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 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 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}