Skip to main content

arks_config/
parse.rs

1//! git-config file syntax (§SYNTAX): sections, subsections, quoting, escapes,
2//! continuation lines, comments.
3
4use std::fmt;
5
6/// One `key = value` occurrence; `key` is normalized to `section[.subsection].name`
7/// with section and name lowercased and subsection kept case-sensitive.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct RawEntry {
10    pub key: String,
11    /// `None` for a bare `name` line (boolean true per git-config).
12    pub value: Option<String>,
13}
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct ParseError {
17    pub line: usize,
18    pub message: String,
19}
20
21impl fmt::Display for ParseError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        write!(f, "bad config line {}: {}", self.line, self.message)
24    }
25}
26
27impl std::error::Error for ParseError {}
28
29/// Parse one config file body.
30pub fn parse_config_text(text: &str) -> Result<Vec<RawEntry>, ParseError> {
31    let mut out = Vec::new();
32    let mut section: Option<String> = None;
33    let lines: Vec<&str> = text.lines().collect();
34    let mut i = 0;
35    while i < lines.len() {
36        let line_no = i + 1;
37        let line = lines[i].trim_start_matches('\u{feff}');
38        i += 1;
39        let trimmed = line.trim_start();
40        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
41            continue;
42        }
43        let mut rest = trimmed;
44        if rest.starts_with('[') {
45            let (sec, after) = parse_section_header(rest).map_err(|m| ParseError {
46                line: line_no,
47                message: m,
48            })?;
49            section = Some(sec);
50            rest = after.trim_start();
51            if rest.is_empty() || rest.starts_with('#') || rest.starts_with(';') {
52                continue;
53            }
54        }
55        let Some(sec) = section.as_ref() else {
56            return Err(ParseError {
57                line: line_no,
58                message: "variable outside any section".into(),
59            });
60        };
61        let name_end = rest
62            .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
63            .unwrap_or(rest.len());
64        let name = &rest[..name_end];
65        if name.is_empty() || !name.as_bytes()[0].is_ascii_alphabetic() {
66            return Err(ParseError {
67                line: line_no,
68                message: "invalid variable name".into(),
69            });
70        }
71        let after_name = rest[name_end..].trim_start();
72        let key = format!("{sec}.{}", name.to_ascii_lowercase());
73        if after_name.is_empty() || after_name.starts_with('#') || after_name.starts_with(';') {
74            out.push(RawEntry { key, value: None });
75            continue;
76        }
77        let Some(value_src) = after_name.strip_prefix('=') else {
78            return Err(ParseError {
79                line: line_no,
80                message: "expected '=' after variable name".into(),
81            });
82        };
83        // Join continuation lines (backslash-newline) into one logical value.
84        let mut logical = value_src.to_string();
85        while ends_with_unescaped_backslash(&logical) && i < lines.len() {
86            logical.pop();
87            logical.push_str(lines[i]);
88            i += 1;
89        }
90        let value = parse_value(&logical).map_err(|m| ParseError {
91            line: line_no,
92            message: m,
93        })?;
94        out.push(RawEntry {
95            key,
96            value: Some(value),
97        });
98    }
99    Ok(out)
100}
101
102fn ends_with_unescaped_backslash(s: &str) -> bool {
103    let trailing = s.bytes().rev().take_while(|b| *b == b'\\').count();
104    trailing % 2 == 1
105}
106
107fn parse_section_header(s: &str) -> Result<(String, &str), String> {
108    let body = &s[1..];
109    let name_end = body
110        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '.'))
111        .unwrap_or(body.len());
112    let name = &body[..name_end];
113    if name.is_empty() {
114        return Err("empty section name".into());
115    }
116    let mut rest = &body[name_end..];
117    if let Some(r) = rest.strip_prefix(']') {
118        // `[section]` or legacy `[section.subsection]` (subsection lowercased).
119        return Ok((name.to_ascii_lowercase(), r));
120    }
121    rest = rest.trim_start();
122    let Some(q) = rest.strip_prefix('"') else {
123        return Err("malformed section header".into());
124    };
125    let mut sub = String::new();
126    let mut chars = q.char_indices();
127    loop {
128        let Some((idx, c)) = chars.next() else {
129            return Err("unterminated subsection".into());
130        };
131        match c {
132            '\\' => {
133                if let Some((_, n)) = chars.next() {
134                    sub.push(n);
135                }
136            }
137            '"' => {
138                let after = &q[idx + 1..];
139                let Some(r) = after.strip_prefix(']') else {
140                    return Err("expected ']' after subsection".into());
141                };
142                return Ok((format!("{}.{}", name.to_ascii_lowercase(), sub), r));
143            }
144            '\n' => return Err("newline in subsection".into()),
145            other => sub.push(other),
146        }
147    }
148}
149
150fn parse_value(src: &str) -> Result<String, String> {
151    let mut out = String::new();
152    let mut in_quote = false;
153    // Whitespace seen outside quotes is held back so trailing runs get trimmed.
154    let mut pending_ws = String::new();
155    let mut started = false;
156    let mut chars = src.chars();
157    while let Some(c) = chars.next() {
158        match c {
159            '"' => {
160                out.push_str(&pending_ws);
161                pending_ws.clear();
162                in_quote = !in_quote;
163                started = true;
164            }
165            '\\' => {
166                out.push_str(&pending_ws);
167                pending_ws.clear();
168                started = true;
169                match chars.next() {
170                    Some('n') => out.push('\n'),
171                    Some('t') => out.push('\t'),
172                    Some('b') => {
173                        out.pop();
174                    }
175                    Some('\\') => out.push('\\'),
176                    Some('"') => out.push('"'),
177                    Some('\n') => {}
178                    Some(other) => return Err(format!("invalid escape '\\{other}'")),
179                    None => {}
180                }
181            }
182            '#' | ';' if !in_quote => break,
183            c if c.is_whitespace() && !in_quote => {
184                if started {
185                    pending_ws.push(c);
186                }
187            }
188            c => {
189                out.push_str(&pending_ws);
190                pending_ws.clear();
191                out.push(c);
192                started = true;
193            }
194        }
195    }
196    if in_quote {
197        return Err("unterminated quote".into());
198    }
199    Ok(out)
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    fn kv(text: &str) -> Vec<(String, Option<String>)> {
207        parse_config_text(text)
208            .unwrap()
209            .into_iter()
210            .map(|e| (e.key, e.value))
211            .collect()
212    }
213
214    #[test]
215    fn sections_subsections_and_case() {
216        let got = kv("[User]\n\tName = A B\n[remote \"Origin\"]\n url = x # c\n[a.B]\nk\n");
217        assert_eq!(
218            got,
219            vec![
220                ("user.name".into(), Some("A B".into())),
221                ("remote.Origin.url".into(), Some("x".into())),
222                ("a.b.k".into(), None),
223            ]
224        );
225    }
226
227    #[test]
228    fn quotes_escapes_continuation() {
229        let got = kv("[s]\nv = \"  a;b \" c\\tq\nw = one \\\n two\n");
230        assert_eq!(got[0].1.as_deref(), Some("  a;b  c\tq"));
231        assert_eq!(got[1].1.as_deref(), Some("one  two"));
232    }
233
234    #[test]
235    fn errors_are_reported() {
236        assert!(parse_config_text("k = v\n").is_err());
237        assert!(parse_config_text("[s]\nv = \"open\n").is_err());
238    }
239}