Debian Codegraph @

crates/bazaar/src/config/configobj.rs

raw
1 //! A parser and writer for the ConfigObj INI dialect breezy stores config in.
2 //!
3 //! Breezy loads config files as UTF-8 with `list_values=False` and
4 //! interpolation off, and only ever uses depth-1 sections in practice
5 //! (`branch.conf`/`bazaar.conf` use the top-level no-name section plus an
6 //! optional `[DEFAULT]`; `locations.conf` uses `[path]` sections). This module
7 //! supports exactly that: the top-level scalars and any number of `[name]`
8 //! sections, preserving order and comment/blank lines so a rewrite only changes
9 //! the value that changed.
10 //!
11 //! With `list_values=False`, the parser does not strip surrounding quotes or
12 //! split comma lists; that happens later when a [`super::Stack`] unquotes a
13 //! value. Writing goes through breezy's list-aware quoting via [`quote_value`].
14
15 use super::Section;
16
17 /// A parse error from [`ConfigObj::parse`].
18 #[derive(Debug, PartialEq, Eq)]
19 pub enum ConfigObjError {
20 /// A section header bracket run was malformed (unbalanced `[`/`]`).
21 BadSectionHeader(String),
22 /// A non-blank, non-comment, non-header line had no `=`.
23 MissingEquals(String),
24 /// A line referenced a deeper nesting than supported (breezy uses depth 1).
25 NestingTooDeep(String),
26 /// The content was not valid UTF-8.
27 NotUtf8,
28 }
29
30 impl std::fmt::Display for ConfigObjError {
31 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 match self {
33 ConfigObjError::BadSectionHeader(l) => write!(f, "bad section header: {l:?}"),
34 ConfigObjError::MissingEquals(l) => write!(f, "line is not key = value: {l:?}"),
35 ConfigObjError::NestingTooDeep(l) => write!(f, "section nested too deeply: {l:?}"),
36 ConfigObjError::NotUtf8 => write!(f, "config content is not valid UTF-8"),
37 }
38 }
39 }
40
41 impl std::error::Error for ConfigObjError {}
42
43 /// One physical line of a parsed config file, kept so the file round-trips.
44 #[derive(Debug, Clone, PartialEq, Eq)]
45 enum Line {
46 /// A blank or `#`-comment line, stored verbatim (without its newline).
47 Verbatim(String),
48 /// A `[name]` section header introducing the section with this name.
49 SectionHeader(String),
50 /// A `key = value` entry. `section` is the owning section name (`None` for
51 /// the top-level no-name section). `trailing` keeps any inline comment so
52 /// it survives a rewrite.
53 Entry {
54 section: Option<String>,
55 key: String,
56 value: String,
57 trailing: String,
58 },
59 }
60
61 /// A parsed ConfigObj file.
62 ///
63 /// Holds the lines in order. Lookups and mutations work through the logical
64 /// section/key model while the physical line order is preserved for writing.
65 pub struct ConfigObj {
66 lines: Vec<Line>,
67 }
68
69 impl ConfigObj {
70 /// An empty config (no lines).
71 pub fn empty() -> Self {
72 ConfigObj { lines: Vec::new() }
73 }
74
75 /// Parse `bytes` (UTF-8) into a config.
76 pub fn parse(bytes: &[u8]) -> Result<Self, ConfigObjError> {
77 let text = std::str::from_utf8(bytes).map_err(|_| ConfigObjError::NotUtf8)?;
78 let mut lines = Vec::new();
79 let mut current_section: Option<String> = None;
80 for raw in text.split('\n') {
81 // `split('\n')` yields a trailing empty element for a final newline;
82 // a file ending in "\n" should not gain a spurious blank line.
83 let line = raw.strip_suffix('\r').unwrap_or(raw);
84 let trimmed = line.trim();
85 if trimmed.is_empty() || trimmed.starts_with('#') {
86 lines.push(Line::Verbatim(line.to_string()));
87 continue;
88 }
89 if let Some(rest) = trimmed.strip_prefix('[') {
90 let name = parse_section_header(rest)?;
91 current_section = Some(name.clone());
92 lines.push(Line::SectionHeader(name));
93 continue;
94 }
95 let eq = trimmed
96 .find('=')
97 .ok_or_else(|| ConfigObjError::MissingEquals(line.to_string()))?;
98 let key = unquote_name(trimmed[..eq].trim());
99 let (value, trailing) = split_value_and_comment(trimmed[eq + 1..].trim_start());
100 lines.push(Line::Entry {
101 section: current_section.clone(),
102 key,
103 value,
104 trailing,
105 });
106 }
107 // A file that ended with a newline produced a final empty Verbatim;
108 // drop it so writing reproduces the input rather than appending a line.
109 if matches!(lines.last(), Some(Line::Verbatim(s)) if s.is_empty()) {
110 lines.pop();
111 }
112 Ok(ConfigObj { lines })
113 }
114
115 /// All sections in file order: the no-name section first if it has any
116 /// scalars, then each named section.
117 pub fn sections(&self) -> Vec<Section> {
118 let mut order: Vec<Option<String>> = Vec::new();
119 let mut seen: std::collections::HashSet<Option<String>> = std::collections::HashSet::new();
120 // The no-name section exists iff there's a top-level entry.
121 for line in &self.lines {
122 if let Line::Entry { section, .. } = line {
123 if seen.insert(section.clone()) {
124 order.push(section.clone());
125 }
126 }
127 }
128 order
129 .into_iter()
130 .map(|id| self.section(id.as_deref()).expect("section was just seen"))
131 .collect()
132 }
133
134 /// The section with the given id (`None` = no-name), or `None` if it has no
135 /// entries.
136 pub fn section(&self, id: Option<&str>) -> Option<Section> {
137 let mut pairs = Vec::new();
138 for line in &self.lines {
139 if let Line::Entry {
140 section,
141 key,
142 value,
143 ..
144 } = line
145 {
146 if section.as_deref() == id {
147 pairs.push((key.clone(), value.clone()));
148 }
149 }
150 }
151 if pairs.is_empty() {
152 None
153 } else {
154 Some(Section::new(id.map(|s| s.to_string()), pairs))
155 }
156 }
157
158 /// Set `key` to `value` in section `id`, in place if it already exists,
159 /// otherwise appended after the last entry of that section (creating the
160 /// section header if needed).
161 pub fn set_value(&mut self, id: Option<&str>, key: &str, value: &str) {
162 // In-place update if the key already exists in the section.
163 for line in &mut self.lines {
164 if let Line::Entry {
165 section,
166 key: k,
167 value: v,
168 ..
169 } = line
170 {
171 if section.as_deref() == id && k == key {
172 *v = value.to_string();
173 return;
174 }
175 }
176 }
177 self.insert_new_entry(id, key, value);
178 }
179
180 /// Remove `key` from section `id` if present.
181 pub fn remove_value(&mut self, id: Option<&str>, key: &str) {
182 self.lines.retain(|line| {
183 !matches!(
184 line,
185 Line::Entry { section, key: k, .. }
186 if section.as_deref() == id && k == key
187 )
188 });
189 }
190
191 fn insert_new_entry(&mut self, id: Option<&str>, key: &str, value: &str) {
192 let entry = Line::Entry {
193 section: id.map(|s| s.to_string()),
194 key: key.to_string(),
195 value: value.to_string(),
196 trailing: String::new(),
197 };
198 match id {
199 // No-name entries go at the very top, before any section header, so
200 // they stay in the top-level section.
201 None => {
202 let pos = self
203 .lines
204 .iter()
205 .position(|l| matches!(l, Line::SectionHeader(_)))
206 .unwrap_or(self.lines.len());
207 self.lines.insert(pos, entry);
208 }
209 Some(name) => {
210 // Find the section header; append after its last entry. Create
211 // the header at end of file if the section doesn't exist yet.
212 let header = self
213 .lines
214 .iter()
215 .position(|l| matches!(l, Line::SectionHeader(n) if n == name));
216 match header {
217 Some(h) => {
218 let mut insert_at = h + 1;
219 for (i, line) in self.lines.iter().enumerate().skip(h + 1) {
220 match line {
221 Line::SectionHeader(_) => break,
222 Line::Entry { section, .. } if section.as_deref() == id => {
223 insert_at = i + 1;
224 }
225 _ => {}
226 }
227 }
228 self.lines.insert(insert_at, entry);
229 }
230 None => {
231 self.lines.push(Line::SectionHeader(name.to_string()));
232 self.lines.push(entry);
233 }
234 }
235 }
236 }
237 }
238
239 /// Serialize back to bytes (UTF-8), newline-terminated.
240 pub fn to_bytes(&self) -> Vec<u8> {
241 let mut out = String::new();
242 for line in &self.lines {
243 match line {
244 Line::Verbatim(s) => out.push_str(s),
245 Line::SectionHeader(name) => {
246 out.push('[');
247 out.push_str(name);
248 out.push(']');
249 }
250 Line::Entry {
251 key,
252 value,
253 trailing,
254 ..
255 } => {
256 out.push_str(key);
257 out.push_str(" = ");
258 out.push_str(value);
259 out.push_str(trailing);
260 }
261 }
262 out.push('\n');
263 }
264 out.into_bytes()
265 }
266 }
267
268 /// Parse the part of a section header after the opening `[`, returning the
269 /// section name. Only depth-1 headers (`[name]`) are supported, matching
270 /// breezy's actual usage.
271 fn parse_section_header(rest: &str) -> Result<String, ConfigObjError> {
272 let line = format!("[{rest}");
273 // Strip an optional inline comment after the closing bracket.
274 let body = match rest.rsplit_once(']') {
275 Some((before, _after)) => before,
276 None => return Err(ConfigObjError::BadSectionHeader(line)),
277 };
278 if body.starts_with('[') {
279 // [[sub]] -> depth 2 or more; breezy config files don't use these.
280 return Err(ConfigObjError::NestingTooDeep(line));
281 }
282 let name = unquote_name(body.trim());
283 if name.is_empty() {
284 return Err(ConfigObjError::BadSectionHeader(line));
285 }
286 Ok(name)
287 }
288
289 /// Strip a matched surrounding quote pair from a section or key name, as
290 /// configobj's `_unquote` does.
291 fn unquote_name(s: &str) -> String {
292 let bytes = s.as_bytes();
293 if bytes.len() >= 2 {
294 let first = bytes[0];
295 let last = bytes[bytes.len() - 1];
296 if first == last && (first == b'"' || first == b'\'') {
297 return s[1..s.len() - 1].to_string();
298 }
299 }
300 s.to_string()
301 }
302
303 /// Split a raw value into the value text and any trailing inline comment.
304 ///
305 /// With `list_values=False`, configobj keeps a quoted value's quotes in the
306 /// stored string and only treats `#` as a comment start when it's outside
307 /// quotes. We preserve the value verbatim (quotes included) and capture the
308 /// comment in `trailing` so a rewrite reproduces it.
309 fn split_value_and_comment(s: &str) -> (String, String) {
310 if let Some(quote) = s.chars().next().filter(|c| *c == '"' || *c == '\'') {
311 // Quoted value: the value runs to the matching closing quote; anything
312 // after is a trailing comment (kept verbatim, including leading space).
313 if let Some(end) = s[1..].find(quote) {
314 let value_end = 1 + end + 1;
315 let value = s[..value_end].to_string();
316 let trailing = s[value_end..].to_string();
317 return (value, trailing);
318 }
319 // Unterminated quote: treat the whole thing as the value.
320 return (s.to_string(), String::new());
321 }
322 match s.find('#') {
323 Some(h) => {
324 // The value is everything before the `#`, with trailing whitespace
325 // stripped. `trailing` keeps that whitespace and the comment so a
326 // rewrite (which writes value then trailing) reproduces the gap.
327 let value = s[..h].trim_end();
328 let trailing = &s[value.len()..];
329 (value.to_string(), trailing.to_string())
330 }
331 None => (s.trim_end().to_string(), String::new()),
332 }
333 }
334
335 /// Quote `value` for writing, matching breezy's list-aware `Store.quote`.
336 ///
337 /// A scalar needs no quotes unless its first/last char is whitespace or a
338 /// quote, or it contains a comma or `#`. Empty string becomes `""`.
339 pub fn quote_value(value: &str) -> String {
340 if value.is_empty() {
341 return "\"\"".to_string();
342 }
343 let needs_quote = {
344 let bytes = value.as_bytes();
345 let first = bytes[0];
346 let last = bytes[bytes.len() - 1];
347 let edge_ws_or_quote = |c: u8| matches!(c, b' ' | b'\t' | b'\r' | b'\n' | b'"' | b'\'');
348 edge_ws_or_quote(first)
349 || edge_ws_or_quote(last)
350 || value.contains(',')
351 || value.contains('#')
352 };
353 if !needs_quote {
354 return value.to_string();
355 }
356 // Prefer single quotes; use double quotes if the value contains a single
357 // quote (configobj's rule). Both present is not expected for the keys we
358 // write (locations/booleans), so fall back to double quoting.
359 if value.contains('\'') {
360 format!("\"{value}\"")
361 } else {
362 format!("'{value}'")
363 }
364 }
365
366 /// Strip a matched surrounding quote pair from a raw value, as
367 /// `Store.unquote` (configobj's `_unquote`).
368 pub fn unquote_value(value: &str) -> String {
369 unquote_name(value)
370 }
371
372 #[cfg(test)]
373 mod tests {
374 use super::*;
375
376 #[test]
377 fn parses_no_name_section() {
378 let c = ConfigObj::parse(b"a = 1\nb = two\n").unwrap();
379 let sec = c.section(None).unwrap();
380 assert_eq!(sec.get("a"), Some("1"));
381 assert_eq!(sec.get("b"), Some("two"));
382 }
383
384 #[test]
385 fn parses_named_section() {
386 let c = ConfigObj::parse(b"top = x\n[/home/foo]\nkey = val\n").unwrap();
387 assert_eq!(c.section(None).unwrap().get("top"), Some("x"));
388 assert_eq!(
389 c.section(Some("/home/foo")).unwrap().get("key"),
390 Some("val")
391 );
392 }
393
394 #[test]
395 fn round_trips_verbatim_comments_and_blanks() {
396 let input = b"# a comment\n\nnickname = trunk\n";
397 let c = ConfigObj::parse(input).unwrap();
398 assert_eq!(c.to_bytes(), input);
399 }
400
401 #[test]
402 fn round_trips_without_trailing_newline() {
403 // Input without trailing newline still writes one (configobj ensures a
404 // final newline), but no extra blank line appears.
405 let c = ConfigObj::parse(b"a = 1").unwrap();
406 assert_eq!(c.to_bytes(), b"a = 1\n");
407 }
408
409 #[test]
410 fn set_value_updates_in_place() {
411 let mut c = ConfigObj::parse(b"a = 1\nb = 2\n").unwrap();
412 c.set_value(None, "a", "99");
413 assert_eq!(c.to_bytes(), b"a = 99\nb = 2\n");
414 }
415
416 #[test]
417 fn set_value_appends_new_no_name_key_before_sections() {
418 let mut c = ConfigObj::parse(b"a = 1\n[s]\nx = y\n").unwrap();
419 c.set_value(None, "b", "2");
420 assert_eq!(c.to_bytes(), b"a = 1\nb = 2\n[s]\nx = y\n");
421 }
422
423 #[test]
424 fn set_value_creates_section() {
425 let mut c = ConfigObj::parse(b"a = 1\n").unwrap();
426 c.set_value(Some("loc"), "k", "v");
427 assert_eq!(c.to_bytes(), b"a = 1\n[loc]\nk = v\n");
428 }
429
430 #[test]
431 fn set_value_appends_after_last_entry_of_section() {
432 // A section that already has two entries, followed by a later section.
433 // A new key must land directly after the section's last entry, not
434 // after its header and not after the following section.
435 let mut c = ConfigObj::parse(b"[s1]\nx = 1\ny = 2\n[s2]\nz = 3\n").unwrap();
436 c.set_value(Some("s1"), "w", "4");
437 assert_eq!(c.to_bytes(), b"[s1]\nx = 1\ny = 2\nw = 4\n[s2]\nz = 3\n");
438 }
439
440 #[test]
441 fn set_value_skips_foreign_entries_when_appending() {
442 // configobj keeps physical line order, so a [s1] entry can appear after
443 // an [s2] header only via interleaving; here we just confirm the append
444 // stops at the next header and ignores entries of other sections.
445 let mut c = ConfigObj::parse(b"[s1]\nx = 1\n# note\n[s2]\nz = 3\n").unwrap();
446 c.set_value(Some("s1"), "y", "2");
447 assert_eq!(c.to_bytes(), b"[s1]\nx = 1\ny = 2\n# note\n[s2]\nz = 3\n");
448 }
449
450 #[test]
451 fn set_value_appends_into_empty_header_section() {
452 // A header with no entries of its own, immediately followed by another
453 // header. The new key must land right after the [s1] header (insert_at
454 // = header_pos + 1), before [s2], not before the [s1] header.
455 let mut c = ConfigObj::parse(b"[s1]\n[s2]\nz = 3\n").unwrap();
456 c.set_value(Some("s1"), "k", "v");
457 assert_eq!(c.to_bytes(), b"[s1]\nk = v\n[s2]\nz = 3\n");
458 }
459
460 #[test]
461 fn set_value_appends_after_first_block_of_interleaved_section() {
462 // The same section name appears twice with another section between.
463 // set_value targets the FIRST [s1] block: scanning stops at the [s2]
464 // header (the break arm), so the new key lands after the first block's
465 // entry, not after the second [s1] block far below.
466 let mut c = ConfigObj::parse(b"[s1]\nx = 1\n[s2]\nz = 3\n[s1]\nw = 4\n").unwrap();
467 c.set_value(Some("s1"), "y", "2");
468 assert_eq!(
469 c.to_bytes(),
470 b"[s1]\nx = 1\ny = 2\n[s2]\nz = 3\n[s1]\nw = 4\n"
471 );
472 }
473
474 #[test]
475 fn remove_value_drops_line() {
476 let mut c = ConfigObj::parse(b"a = 1\nb = 2\n").unwrap();
477 c.remove_value(None, "a");
478 assert_eq!(c.to_bytes(), b"b = 2\n");
479 }
480
481 #[test]
482 fn quote_value_rules() {
483 assert_eq!(quote_value("plain"), "plain");
484 assert_eq!(quote_value(""), "\"\"");
485 assert_eq!(quote_value(" leading"), "' leading'");
486 assert_eq!(quote_value("a,b"), "'a,b'");
487 assert_eq!(quote_value("has#hash"), "'has#hash'");
488 // A mid-string quote needs no quoting (no comma/#, not an edge char).
489 assert_eq!(quote_value("has'quote"), "has'quote");
490 // A value that needs quoting and contains a single quote uses doubles.
491 assert_eq!(quote_value("a,'b"), "\"a,'b\"");
492 }
493
494 #[test]
495 fn unquote_value_strips_pair() {
496 assert_eq!(unquote_value("'x'"), "x");
497 assert_eq!(unquote_value("\"x\""), "x");
498 assert_eq!(unquote_value("x"), "x");
499 }
500
501 #[test]
502 fn inline_comment_round_trips() {
503 let input = b"a = 1 # hi\n";
504 let c = ConfigObj::parse(input).unwrap();
505 assert_eq!(c.section(None).unwrap().get("a"), Some("1"));
506 assert_eq!(c.to_bytes(), input);
507 }
508
509 #[test]
510 fn quoted_value_keeps_quotes_and_trailing_comment() {
511 // With list_values=False the value keeps its surrounding quotes, and a
512 // comment after the closing quote is captured verbatim so it round-trips.
513 let input = b"a = \"v a l\" # tail\n";
514 let c = ConfigObj::parse(input).unwrap();
515 assert_eq!(c.section(None).unwrap().get("a"), Some("\"v a l\""));
516 assert_eq!(c.to_bytes(), input);
517 }
518
519 #[test]
520 fn quoted_value_without_comment_round_trips() {
521 let input = b"a = 'q'\n";
522 let c = ConfigObj::parse(input).unwrap();
523 assert_eq!(c.section(None).unwrap().get("a"), Some("'q'"));
524 assert_eq!(c.to_bytes(), input);
525 }
526
527 #[test]
528 fn single_quoted_value_with_hash_is_not_a_comment() {
529 // A single-quoted value containing `#` keeps the whole quoted run as the
530 // value; the `#` must not start a comment because it is inside quotes.
531 let input = b"a = '#x'\n";
532 let c = ConfigObj::parse(input).unwrap();
533 assert_eq!(c.section(None).unwrap().get("a"), Some("'#x'"));
534 assert_eq!(c.to_bytes(), input);
535 }
536
537 #[test]
538 fn unterminated_quote_is_whole_value() {
539 let c = ConfigObj::parse(b"a = \"oops\n").unwrap();
540 assert_eq!(c.section(None).unwrap().get("a"), Some("\"oops"));
541 }
542
543 #[test]
544 fn unquote_name_only_strips_real_quote_pairs() {
545 // A doubled non-quote char (first == last but not a quote) is left alone.
546 let c = ConfigObj::parse(b"aa = 1\n").unwrap();
547 assert_eq!(c.section(None).unwrap().get("aa"), Some("1"));
548 // A genuine quote pair around a key is stripped.
549 let c = ConfigObj::parse(b"\"k\" = 1\n").unwrap();
550 assert_eq!(c.section(None).unwrap().get("k"), Some("1"));
551 // Mismatched edge chars (a...z) are not a pair.
552 let c = ConfigObj::parse(b"az = 1\n").unwrap();
553 assert_eq!(c.section(None).unwrap().get("az"), Some("1"));
554 }
555
556 #[test]
557 fn missing_equals_is_error() {
558 match ConfigObj::parse(b"not a config line\n") {
559 Err(ConfigObjError::MissingEquals(line)) => assert_eq!(line, "not a config line"),
560 other => panic!("expected MissingEquals, got {:?}", other.map(|_| "ok")),
561 }
562 }
563 }