Skip to main content

ostrya_core/config/
value.rs

1//! The text form of a config value: the trait `Value`, its error, the codec
2//! of the key file, and the values of the types of `std` and of this crate.
3
4use super::ConfigError;
5use crate::{KeyFile, RepoMode};
6
7/// The text form of a config value.
8///
9/// [`parse`](Value::parse) reads the raw text of a value, as the key file
10/// holds it, with its escape sequences. [`format`](Value::format) gives raw
11/// text that a key file can hold. For each value `v` that `parse` gives,
12/// `parse(&v.format())` gives `v` again.
13///
14/// A value type that holds text decodes the raw text first, with the
15/// helper functions of the module: [`decode_string`], [`decode_bool`],
16/// [`decode_integer`], and [`decode_string_list`]. Its `format` encodes the
17/// text with [`encode_string`], [`encode_bool`], [`encode_integer`], or
18/// [`encode_string_list`]. A value type that reads the text as written,
19/// such as `SizeSpec`, uses no helper function.
20///
21/// A value that needs more than its text, such as a path relative to the
22/// repository, parses to its text form. The code that uses the value
23/// resolves it.
24///
25/// # Examples
26///
27/// ```
28/// use ostrya_core::config::{Value, ValueError, decode_string, encode_string};
29///
30/// /// A host name with no space.
31/// #[derive(Debug, PartialEq)]
32/// struct Host {
33///     name: String,
34/// }
35///
36/// impl Value for Host {
37///     fn parse(raw: &str) -> Result<Host, ValueError> {
38///         let name = decode_string(raw)?;
39///         if name.is_empty() || name.contains(' ') {
40///             return Err(ValueError::new(format!("value '{name}' is not a host name")));
41///         }
42///         Ok(Host { name })
43///     }
44///
45///     fn format(&self) -> String {
46///         encode_string(&self.name)
47///     }
48/// }
49///
50/// let host = Host::parse("example.com").unwrap();
51/// assert_eq!(Host::parse(&host.format()), Ok(host));
52/// assert!(Host::parse("a b").is_err());
53/// ```
54pub trait Value: Sized {
55    /// Parses the raw text of a value, as the key file holds it.
56    ///
57    /// # Errors
58    ///
59    /// A [`ValueError`] if the text is not a value of the type.
60    fn parse(raw: &str) -> Result<Self, ValueError>;
61
62    /// Returns the raw text of the value, as a key file holds it.
63    fn format(&self) -> String;
64}
65
66/// The reason why the raw text of a value does not parse.
67///
68/// The config code of this crate maps the reason with the group and the key
69/// of the value, and gives a [`ConfigError`]. The `ostrya` crate converts
70/// each variant to the variant of `ostrya::Error` with the same name, with
71/// the same text.
72///
73/// - A text that is not a boolean gives [`ConfigError::Core`] with the text
74///   `value 'VALUE' for GROUP.KEY is not a boolean`, as
75///   [`KeyFile::get_bool`] gives it. An integer gives `is not an integer` in
76///   the same form.
77/// - A malformed escape sequence gives [`ConfigError::Core`] with the text
78///   of [`KeyFile::get_string`].
79/// - An error of [`malformed_item`](ValueError::malformed_item) or
80///   [`malformed_value`](ValueError::malformed_value) gives
81///   [`ConfigError::InvalidFormat`] with the text `malformed [GROUP] KEY
82///   item 'TEXT': WHY` or `malformed [GROUP] KEY value 'TEXT': WHY`.
83/// - Each other reason gives [`ConfigError::InvalidFormat`] with the text
84///   `[GROUP] KEY REASON`. `GROUP` is the group header, for example `core`
85///   or `remote "origin"`.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct ValueError {
88    kind: Kind,
89}
90
91/// The kind of a [`ValueError`].
92#[derive(Debug, Clone, PartialEq, Eq)]
93enum Kind {
94    /// The text is not a boolean.
95    NotBoolean,
96    /// The text is not an integer.
97    NotInteger,
98    /// A key-file escape error, with its text.
99    KeyFile(String),
100    /// Another refusal, with its reason.
101    Invalid(String),
102    /// A malformed item of a list or a malformed value: the word `item` or
103    /// `value`, the text, and the reason.
104    Malformed {
105        part: &'static str,
106        text: String,
107        why: String,
108    },
109}
110
111impl ValueError {
112    /// Returns an error with the reason `reason`.
113    ///
114    /// The reason is a predicate on the value, for example `is empty`, or
115    /// `value 'x' is not a host name`. A typed read writes it after the group
116    /// and the key: `[GROUP] KEY REASON`.
117    pub fn new(reason: impl Into<String>) -> ValueError {
118        ValueError {
119            kind: Kind::Invalid(reason.into()),
120        }
121    }
122
123    /// Returns the error of the malformed item `text` of a list value, with
124    /// the reason `why`.
125    ///
126    /// A typed read gives the text `malformed [GROUP] KEY item 'TEXT': WHY`.
127    /// The [`Display`](std::fmt::Display) form of the error alone is
128    /// `malformed item 'TEXT': WHY`.
129    ///
130    /// # Examples
131    ///
132    /// ```
133    /// use ostrya_core::config::ValueError;
134    ///
135    /// let err = ValueError::malformed_item("x", "the item is a number");
136    /// assert_eq!(err.to_string(), "malformed item 'x': the item is a number");
137    /// ```
138    pub fn malformed_item(text: impl Into<String>, why: impl Into<String>) -> ValueError {
139        ValueError {
140            kind: Kind::Malformed {
141                part: "item",
142                text: text.into(),
143                why: why.into(),
144            },
145        }
146    }
147
148    /// Returns the error of the malformed value `text`, with the reason
149    /// `why`.
150    ///
151    /// A typed read gives the text `malformed [GROUP] KEY value 'TEXT':
152    /// WHY`. The [`Display`](std::fmt::Display) form of the error alone is
153    /// `malformed value 'TEXT': WHY`.
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use ostrya_core::config::ValueError;
159    ///
160    /// let err = ValueError::malformed_value("x", "the value is a number");
161    /// assert_eq!(err.to_string(), "malformed value 'x': the value is a number");
162    /// ```
163    pub fn malformed_value(text: impl Into<String>, why: impl Into<String>) -> ValueError {
164        ValueError {
165            kind: Kind::Malformed {
166                part: "value",
167                text: text.into(),
168                why: why.into(),
169            },
170        }
171    }
172}
173
174impl std::fmt::Display for ValueError {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        match &self.kind {
177            Kind::NotBoolean => f.write_str("is not a boolean"),
178            Kind::NotInteger => f.write_str("is not an integer"),
179            Kind::KeyFile(text) | Kind::Invalid(text) => f.write_str(text),
180            Kind::Malformed { part, text, why } => write!(f, "malformed {part} '{text}': {why}"),
181        }
182    }
183}
184
185impl std::error::Error for ValueError {}
186
187/// Returns the config error of `err`, the refusal of the raw text `raw` of
188/// the key `key` in the group with the header `group`.
189#[doc(hidden)]
190pub fn value_error(group: &str, key: &str, raw: &str, err: ValueError) -> ConfigError {
191    match err.kind {
192        Kind::NotBoolean => ConfigError::Core(crate::Error::KeyFile(format!(
193            "value '{raw}' for {group}.{key} is not a boolean"
194        ))),
195        Kind::NotInteger => ConfigError::Core(crate::Error::KeyFile(format!(
196            "value '{raw}' for {group}.{key} is not an integer"
197        ))),
198        Kind::KeyFile(text) => ConfigError::Core(crate::Error::KeyFile(text)),
199        Kind::Invalid(reason) => ConfigError::InvalidFormat(format!("[{group}] {key} {reason}")),
200        Kind::Malformed { part, text, why } => {
201            ConfigError::InvalidFormat(format!("malformed [{group}] {key} {part} '{text}': {why}"))
202        }
203    }
204}
205
206/// Returns the value error of a key-file error.
207fn keyfile_error(err: crate::Error) -> ValueError {
208    match err {
209        crate::Error::KeyFile(text) => ValueError {
210            kind: Kind::KeyFile(text),
211        },
212        other => ValueError {
213            kind: Kind::KeyFile(other.to_string()),
214        },
215    }
216}
217
218/// Decodes the raw text of a string value.
219///
220/// The function replaces each escape sequence of the key file with its
221/// character: `\s` with a space, `\t` with a tab, `\n` with a newline, `\r`
222/// with a carriage return, `\\` with a backslash, and `\;` with a `;`.
223/// [`KeyFile::get_string`] reads a value in the same way.
224///
225/// # Errors
226///
227/// A [`ValueError`] with the text of [`KeyFile::get_string`] if the text
228/// holds a backslash that starts no escape sequence.
229pub fn decode_string(raw: &str) -> Result<String, ValueError> {
230    KeyFile::decode_string(raw).map_err(keyfile_error)
231}
232
233/// Encodes a string value as raw text.
234///
235/// The function escapes the value as [`KeyFile::set_string`] does, so
236/// [`decode_string`] gives the value again.
237pub fn encode_string(value: &str) -> String {
238    KeyFile::encode_string(value)
239}
240
241/// Decodes the raw text of a boolean value.
242///
243/// `true` and `1` give `true`, and `false` and `0` give `false`. The match
244/// is exact. [`KeyFile::get_bool`] reads a value in the same way.
245///
246/// # Errors
247///
248/// A [`ValueError`] if the text is not one of the four values.
249pub fn decode_bool(raw: &str) -> Result<bool, ValueError> {
250    KeyFile::decode_bool(raw).ok_or(ValueError {
251        kind: Kind::NotBoolean,
252    })
253}
254
255/// Encodes a boolean value as raw text: `true` or `false`.
256pub fn encode_bool(value: bool) -> String {
257    if value { "true" } else { "false" }.to_owned()
258}
259
260/// Decodes the raw text of an integer value.
261///
262/// The text is a decimal `i64` with an optional `-` sign.
263/// [`KeyFile::get_integer`] reads a value in the same way.
264///
265/// # Errors
266///
267/// A [`ValueError`] if the text is not a decimal `i64`. White space in the
268/// text and a leading `+` sign cause this error.
269pub fn decode_integer(raw: &str) -> Result<i64, ValueError> {
270    KeyFile::decode_integer(raw).ok_or(ValueError {
271        kind: Kind::NotInteger,
272    })
273}
274
275/// Encodes an integer value as raw text, in decimal.
276pub fn encode_integer(value: i64) -> String {
277    value.to_string()
278}
279
280/// Decodes the raw text of a list value.
281///
282/// A `;` separates two items, and `\;` is a `;` in an item. A trailing `;`
283/// adds no empty item. The function decodes each item as [`decode_string`]
284/// does. [`KeyFile::get_string_list`] reads a value in the same way.
285///
286/// # Errors
287///
288/// A [`ValueError`] with the text of [`KeyFile::get_string_list`] if the
289/// text holds a backslash that starts no escape sequence.
290pub fn decode_string_list(raw: &str) -> Result<Vec<String>, ValueError> {
291    KeyFile::decode_string_list(raw).map_err(keyfile_error)
292}
293
294/// Encodes a list value as raw text.
295///
296/// The function escapes each item as [`encode_string`] does, writes `\;` for
297/// a `;` in an item, and writes a `;` after each item, also after the last
298/// item. [`KeyFile::set_string_list`] writes a list in the same way, and
299/// [`decode_string_list`] gives the list again.
300pub fn encode_string_list(items: &[impl AsRef<str>]) -> String {
301    KeyFile::encode_string_list(items)
302}
303
304impl Value for bool {
305    fn parse(raw: &str) -> Result<bool, ValueError> {
306        decode_bool(raw)
307    }
308
309    fn format(&self) -> String {
310        encode_bool(*self)
311    }
312}
313
314impl Value for i64 {
315    fn parse(raw: &str) -> Result<i64, ValueError> {
316        decode_integer(raw)
317    }
318
319    fn format(&self) -> String {
320        encode_integer(*self)
321    }
322}
323
324/// Implements [`Value`] for an integer type through `i64`. A value outside
325/// the range of the type is refused.
326macro_rules! value_through_i64 {
327    ($($int:ty),*) => {$(
328        impl Value for $int {
329            fn parse(raw: &str) -> Result<$int, ValueError> {
330                let n = decode_integer(raw)?;
331                <$int>::try_from(n).map_err(|_| {
332                    ValueError::new(format!(
333                        "{n} is out of the range {}-{}",
334                        <$int>::MIN,
335                        <$int>::MAX
336                    ))
337                })
338            }
339
340            fn format(&self) -> String {
341                self.to_string()
342            }
343        }
344    )*};
345}
346
347value_through_i64!(i8, i16, i32, u8, u16, u32);
348
349/// The text rules are the rules of [`decode_integer`]: decimal digits with
350/// an optional `-` sign, and no `+` sign. The full range of `u64` parses. A
351/// negative value is refused with the range of the type, as for the other
352/// integer types.
353impl Value for u64 {
354    fn parse(raw: &str) -> Result<u64, ValueError> {
355        let n = match decode_integer(raw) {
356            Ok(n) => n,
357            // A value above `i64::MAX` is not an `i64`. `str::parse` takes a
358            // leading `+`, which `decode_integer` refuses.
359            Err(err) if raw.starts_with('+') => return Err(err),
360            Err(err) => return raw.parse::<u64>().map_err(|_| err),
361        };
362        u64::try_from(n).map_err(|_| {
363            ValueError::new(format!("{n} is out of the range {}-{}", u64::MIN, u64::MAX))
364        })
365    }
366
367    fn format(&self) -> String {
368        self.to_string()
369    }
370}
371
372impl Value for String {
373    fn parse(raw: &str) -> Result<String, ValueError> {
374        decode_string(raw)
375    }
376
377    fn format(&self) -> String {
378        encode_string(self)
379    }
380}
381
382impl Value for Vec<String> {
383    fn parse(raw: &str) -> Result<Vec<String>, ValueError> {
384        decode_string_list(raw)
385    }
386
387    fn format(&self) -> String {
388        encode_string_list(self)
389    }
390}
391
392/// The text is decoded, and then read as a mode name of
393/// [`RepoMode::from_mode_str`]. `format` gives the name of
394/// [`RepoMode::as_mode_str`].
395impl Value for RepoMode {
396    fn parse(raw: &str) -> Result<RepoMode, ValueError> {
397        let value = decode_string(raw)?;
398        RepoMode::from_mode_str(&value)
399            .ok_or_else(|| ValueError::new(format!("'{value}' names no repository mode")))
400    }
401
402    fn format(&self) -> String {
403        self.as_mode_str().to_owned()
404    }
405}
406
407#[cfg(test)]
408mod tests {
409    use super::*;
410
411    /// Checks that `parse(format(v)) == v`.
412    fn round_trips<V: Value + PartialEq + std::fmt::Debug>(value: V) {
413        let text = value.format();
414        assert_eq!(V::parse(&text), Ok(value), "{text:?}");
415    }
416
417    #[test]
418    fn helpers_decode_and_encode() {
419        assert_eq!(decode_string(r"a\sb\;c").unwrap(), "a b;c");
420        assert_eq!(
421            decode_string(r"\q").unwrap_err().to_string(),
422            r"invalid escape '\q'"
423        );
424        assert_eq!(encode_string("  a;b"), r"\s\sa;b");
425        assert_eq!(decode_bool("1"), Ok(true));
426        assert_eq!(decode_bool("0"), Ok(false));
427        assert_eq!(
428            decode_bool("yes").unwrap_err().to_string(),
429            "is not a boolean"
430        );
431        assert_eq!(encode_bool(true), "true");
432        assert_eq!(encode_bool(false), "false");
433        assert_eq!(decode_integer("-5"), Ok(-5));
434        assert_eq!(
435            decode_integer("+5").unwrap_err().to_string(),
436            "is not an integer"
437        );
438        assert_eq!(encode_integer(-5), "-5");
439        assert_eq!(
440            decode_string_list(r"a;b\;c;").unwrap(),
441            ["a".to_owned(), "b;c".to_owned()]
442        );
443        assert_eq!(
444            decode_string_list("a\\").unwrap_err().to_string(),
445            "value ends with a lone backslash"
446        );
447        assert_eq!(encode_string_list(&["a", "b;c", " d"]), r"a;b\;c;\sd;");
448    }
449
450    #[test]
451    fn value_error_renders_with_the_group_and_the_key() {
452        let render = |err| value_error("core", "fsync", "x", err).to_string();
453        assert_eq!(
454            render(decode_bool("x").unwrap_err()),
455            "keyfile: value 'x' for core.fsync is not a boolean"
456        );
457        assert_eq!(
458            render(decode_integer("x").unwrap_err()),
459            "keyfile: value 'x' for core.fsync is not an integer"
460        );
461        assert_eq!(
462            render(decode_string(r"\q").unwrap_err()),
463            r"keyfile: invalid escape '\q'"
464        );
465        assert_eq!(
466            render(ValueError::new("is empty")),
467            "invalid format: [core] fsync is empty"
468        );
469    }
470
471    #[test]
472    fn bool_integer_and_text_values() {
473        assert_eq!(bool::parse("1"), Ok(true));
474        assert!(bool::parse("yes").is_err());
475        round_trips(true);
476        round_trips(false);
477        assert_eq!(i64::parse("-9223372036854775808"), Ok(i64::MIN));
478        round_trips(i64::MIN);
479        round_trips(i64::MAX);
480        assert_eq!(u8::parse("255"), Ok(255));
481        assert_eq!(
482            u8::parse("256").unwrap_err().to_string(),
483            "256 is out of the range 0-255"
484        );
485        assert_eq!(
486            i8::parse("-129").unwrap_err().to_string(),
487            "-129 is out of the range -128-127"
488        );
489        assert_eq!(
490            u32::parse("-1").unwrap_err().to_string(),
491            "-1 is out of the range 0-4294967295"
492        );
493        round_trips(7u16);
494        round_trips(-7i32);
495        assert_eq!(String::parse(r"\sa"), Ok(" a".to_owned()));
496        round_trips("  a\\b\nc;".to_owned());
497        round_trips(String::new());
498        assert_eq!(
499            Vec::<String>::parse("a;b;"),
500            Ok(vec!["a".to_owned(), "b".to_owned()])
501        );
502        round_trips(vec!["a;b".to_owned(), " c".to_owned(), String::new()]);
503        round_trips(Vec::<String>::new());
504    }
505
506    #[test]
507    fn u64_reads_its_full_range() {
508        let above = u64::try_from(i64::MAX).unwrap() + 1;
509        assert_eq!(u64::parse("9223372036854775808"), Ok(above));
510        assert_eq!(u64::parse("18446744073709551615"), Ok(u64::MAX));
511        for value in [0, u64::try_from(i64::MAX).unwrap(), above, u64::MAX] {
512            round_trips(value);
513        }
514        assert_eq!(
515            u64::parse("-1").unwrap_err().to_string(),
516            "-1 is out of the range 0-18446744073709551615"
517        );
518        for bad in [
519            "+1",
520            "+18446744073709551615",
521            "18446744073709551616",
522            "x",
523            "",
524        ] {
525            assert_eq!(
526                u64::parse(bad).unwrap_err().to_string(),
527                "is not an integer",
528                "{bad:?}"
529            );
530        }
531    }
532
533    #[test]
534    fn mode_values() {
535        assert_eq!(RepoMode::parse("archive"), Ok(RepoMode::Archive));
536        assert_eq!(RepoMode::Archive.format(), "archive-z2");
537        assert_eq!(
538            RepoMode::parse("bogus").unwrap_err().to_string(),
539            "'bogus' names no repository mode"
540        );
541        for mode in [
542            RepoMode::Bare,
543            RepoMode::BareUser,
544            RepoMode::BareUserOnly,
545            RepoMode::BareSplitXattrs,
546            RepoMode::Archive,
547            RepoMode::BareUserShared,
548            RepoMode::BareUserPrivate,
549        ] {
550            round_trips(mode);
551        }
552    }
553
554    #[test]
555    fn malformed_errors_render_with_the_group_and_the_key() {
556        let render = |err| value_error("ex-ostrya server", "listen", "x", err).to_string();
557        assert_eq!(
558            render(ValueError::malformed_item("x", "why")),
559            "invalid format: malformed [ex-ostrya server] listen item 'x': why"
560        );
561        assert_eq!(
562            render(ValueError::malformed_value("x", "why")),
563            "invalid format: malformed [ex-ostrya server] listen value 'x': why"
564        );
565        assert_eq!(
566            ValueError::malformed_item("x", "why").to_string(),
567            "malformed item 'x': why"
568        );
569        assert_eq!(
570            ValueError::malformed_value("x", "why").to_string(),
571            "malformed value 'x': why"
572        );
573    }
574}