ostrya-core 0.19.1

ostree object model, checksums, on-disk format primitives, and typed config
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! The text form of a config value: the trait `Value`, its error, the codec
//! of the key file, and the values of the types of `std` and of this crate.

use super::ConfigError;
use crate::{KeyFile, RepoMode};

/// The text form of a config value.
///
/// [`parse`](Value::parse) reads the raw text of a value, as the key file
/// holds it, with its escape sequences. [`format`](Value::format) gives raw
/// text that a key file can hold. For each value `v` that `parse` gives,
/// `parse(&v.format())` gives `v` again.
///
/// A value type that holds text decodes the raw text first, with the
/// helper functions of the module: [`decode_string`], [`decode_bool`],
/// [`decode_integer`], and [`decode_string_list`]. Its `format` encodes the
/// text with [`encode_string`], [`encode_bool`], [`encode_integer`], or
/// [`encode_string_list`]. A value type that reads the text as written,
/// such as `SizeSpec`, uses no helper function.
///
/// A value that needs more than its text, such as a path relative to the
/// repository, parses to its text form. The code that uses the value
/// resolves it.
///
/// # Examples
///
/// ```
/// use ostrya_core::config::{Value, ValueError, decode_string, encode_string};
///
/// /// A host name with no space.
/// #[derive(Debug, PartialEq)]
/// struct Host {
///     name: String,
/// }
///
/// impl Value for Host {
///     fn parse(raw: &str) -> Result<Host, ValueError> {
///         let name = decode_string(raw)?;
///         if name.is_empty() || name.contains(' ') {
///             return Err(ValueError::new(format!("value '{name}' is not a host name")));
///         }
///         Ok(Host { name })
///     }
///
///     fn format(&self) -> String {
///         encode_string(&self.name)
///     }
/// }
///
/// let host = Host::parse("example.com").unwrap();
/// assert_eq!(Host::parse(&host.format()), Ok(host));
/// assert!(Host::parse("a b").is_err());
/// ```
pub trait Value: Sized {
    /// Parses the raw text of a value, as the key file holds it.
    ///
    /// # Errors
    ///
    /// A [`ValueError`] if the text is not a value of the type.
    fn parse(raw: &str) -> Result<Self, ValueError>;

    /// Returns the raw text of the value, as a key file holds it.
    fn format(&self) -> String;
}

/// The reason why the raw text of a value does not parse.
///
/// The config code of this crate maps the reason with the group and the key
/// of the value, and gives a [`ConfigError`]. The `ostrya` crate converts
/// each variant to the variant of `ostrya::Error` with the same name, with
/// the same text.
///
/// - A text that is not a boolean gives [`ConfigError::Core`] with the text
///   `value 'VALUE' for GROUP.KEY is not a boolean`, as
///   [`KeyFile::get_bool`] gives it. An integer gives `is not an integer` in
///   the same form.
/// - A malformed escape sequence gives [`ConfigError::Core`] with the text
///   of [`KeyFile::get_string`].
/// - An error of [`malformed_item`](ValueError::malformed_item) or
///   [`malformed_value`](ValueError::malformed_value) gives
///   [`ConfigError::InvalidFormat`] with the text `malformed [GROUP] KEY
///   item 'TEXT': WHY` or `malformed [GROUP] KEY value 'TEXT': WHY`.
/// - Each other reason gives [`ConfigError::InvalidFormat`] with the text
///   `[GROUP] KEY REASON`. `GROUP` is the group header, for example `core`
///   or `remote "origin"`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValueError {
    kind: Kind,
}

/// The kind of a [`ValueError`].
#[derive(Debug, Clone, PartialEq, Eq)]
enum Kind {
    /// The text is not a boolean.
    NotBoolean,
    /// The text is not an integer.
    NotInteger,
    /// A key-file escape error, with its text.
    KeyFile(String),
    /// Another refusal, with its reason.
    Invalid(String),
    /// A malformed item of a list or a malformed value: the word `item` or
    /// `value`, the text, and the reason.
    Malformed {
        part: &'static str,
        text: String,
        why: String,
    },
}

impl ValueError {
    /// Returns an error with the reason `reason`.
    ///
    /// The reason is a predicate on the value, for example `is empty`, or
    /// `value 'x' is not a host name`. A typed read writes it after the group
    /// and the key: `[GROUP] KEY REASON`.
    pub fn new(reason: impl Into<String>) -> ValueError {
        ValueError {
            kind: Kind::Invalid(reason.into()),
        }
    }

    /// Returns the error of the malformed item `text` of a list value, with
    /// the reason `why`.
    ///
    /// A typed read gives the text `malformed [GROUP] KEY item 'TEXT': WHY`.
    /// The [`Display`](std::fmt::Display) form of the error alone is
    /// `malformed item 'TEXT': WHY`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya_core::config::ValueError;
    ///
    /// let err = ValueError::malformed_item("x", "the item is a number");
    /// assert_eq!(err.to_string(), "malformed item 'x': the item is a number");
    /// ```
    pub fn malformed_item(text: impl Into<String>, why: impl Into<String>) -> ValueError {
        ValueError {
            kind: Kind::Malformed {
                part: "item",
                text: text.into(),
                why: why.into(),
            },
        }
    }

    /// Returns the error of the malformed value `text`, with the reason
    /// `why`.
    ///
    /// A typed read gives the text `malformed [GROUP] KEY value 'TEXT':
    /// WHY`. The [`Display`](std::fmt::Display) form of the error alone is
    /// `malformed value 'TEXT': WHY`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya_core::config::ValueError;
    ///
    /// let err = ValueError::malformed_value("x", "the value is a number");
    /// assert_eq!(err.to_string(), "malformed value 'x': the value is a number");
    /// ```
    pub fn malformed_value(text: impl Into<String>, why: impl Into<String>) -> ValueError {
        ValueError {
            kind: Kind::Malformed {
                part: "value",
                text: text.into(),
                why: why.into(),
            },
        }
    }
}

impl std::fmt::Display for ValueError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.kind {
            Kind::NotBoolean => f.write_str("is not a boolean"),
            Kind::NotInteger => f.write_str("is not an integer"),
            Kind::KeyFile(text) | Kind::Invalid(text) => f.write_str(text),
            Kind::Malformed { part, text, why } => write!(f, "malformed {part} '{text}': {why}"),
        }
    }
}

impl std::error::Error for ValueError {}

/// Returns the config error of `err`, the refusal of the raw text `raw` of
/// the key `key` in the group with the header `group`.
#[doc(hidden)]
pub fn value_error(group: &str, key: &str, raw: &str, err: ValueError) -> ConfigError {
    match err.kind {
        Kind::NotBoolean => ConfigError::Core(crate::Error::KeyFile(format!(
            "value '{raw}' for {group}.{key} is not a boolean"
        ))),
        Kind::NotInteger => ConfigError::Core(crate::Error::KeyFile(format!(
            "value '{raw}' for {group}.{key} is not an integer"
        ))),
        Kind::KeyFile(text) => ConfigError::Core(crate::Error::KeyFile(text)),
        Kind::Invalid(reason) => ConfigError::InvalidFormat(format!("[{group}] {key} {reason}")),
        Kind::Malformed { part, text, why } => {
            ConfigError::InvalidFormat(format!("malformed [{group}] {key} {part} '{text}': {why}"))
        }
    }
}

/// Returns the value error of a key-file error.
fn keyfile_error(err: crate::Error) -> ValueError {
    match err {
        crate::Error::KeyFile(text) => ValueError {
            kind: Kind::KeyFile(text),
        },
        other => ValueError {
            kind: Kind::KeyFile(other.to_string()),
        },
    }
}

/// Decodes the raw text of a string value.
///
/// The function replaces each escape sequence of the key file with its
/// character: `\s` with a space, `\t` with a tab, `\n` with a newline, `\r`
/// with a carriage return, `\\` with a backslash, and `\;` with a `;`.
/// [`KeyFile::get_string`] reads a value in the same way.
///
/// # Errors
///
/// A [`ValueError`] with the text of [`KeyFile::get_string`] if the text
/// holds a backslash that starts no escape sequence.
pub fn decode_string(raw: &str) -> Result<String, ValueError> {
    KeyFile::decode_string(raw).map_err(keyfile_error)
}

/// Encodes a string value as raw text.
///
/// The function escapes the value as [`KeyFile::set_string`] does, so
/// [`decode_string`] gives the value again.
pub fn encode_string(value: &str) -> String {
    KeyFile::encode_string(value)
}

/// Decodes the raw text of a boolean value.
///
/// `true` and `1` give `true`, and `false` and `0` give `false`. The match
/// is exact. [`KeyFile::get_bool`] reads a value in the same way.
///
/// # Errors
///
/// A [`ValueError`] if the text is not one of the four values.
pub fn decode_bool(raw: &str) -> Result<bool, ValueError> {
    KeyFile::decode_bool(raw).ok_or(ValueError {
        kind: Kind::NotBoolean,
    })
}

/// Encodes a boolean value as raw text: `true` or `false`.
pub fn encode_bool(value: bool) -> String {
    if value { "true" } else { "false" }.to_owned()
}

/// Decodes the raw text of an integer value.
///
/// The text is a decimal `i64` with an optional `-` sign.
/// [`KeyFile::get_integer`] reads a value in the same way.
///
/// # Errors
///
/// A [`ValueError`] if the text is not a decimal `i64`. White space in the
/// text and a leading `+` sign cause this error.
pub fn decode_integer(raw: &str) -> Result<i64, ValueError> {
    KeyFile::decode_integer(raw).ok_or(ValueError {
        kind: Kind::NotInteger,
    })
}

/// Encodes an integer value as raw text, in decimal.
pub fn encode_integer(value: i64) -> String {
    value.to_string()
}

/// Decodes the raw text of a list value.
///
/// A `;` separates two items, and `\;` is a `;` in an item. A trailing `;`
/// adds no empty item. The function decodes each item as [`decode_string`]
/// does. [`KeyFile::get_string_list`] reads a value in the same way.
///
/// # Errors
///
/// A [`ValueError`] with the text of [`KeyFile::get_string_list`] if the
/// text holds a backslash that starts no escape sequence.
pub fn decode_string_list(raw: &str) -> Result<Vec<String>, ValueError> {
    KeyFile::decode_string_list(raw).map_err(keyfile_error)
}

/// Encodes a list value as raw text.
///
/// The function escapes each item as [`encode_string`] does, writes `\;` for
/// a `;` in an item, and writes a `;` after each item, also after the last
/// item. [`KeyFile::set_string_list`] writes a list in the same way, and
/// [`decode_string_list`] gives the list again.
pub fn encode_string_list(items: &[impl AsRef<str>]) -> String {
    KeyFile::encode_string_list(items)
}

impl Value for bool {
    fn parse(raw: &str) -> Result<bool, ValueError> {
        decode_bool(raw)
    }

    fn format(&self) -> String {
        encode_bool(*self)
    }
}

impl Value for i64 {
    fn parse(raw: &str) -> Result<i64, ValueError> {
        decode_integer(raw)
    }

    fn format(&self) -> String {
        encode_integer(*self)
    }
}

/// Implements [`Value`] for an integer type through `i64`. A value outside
/// the range of the type is refused.
macro_rules! value_through_i64 {
    ($($int:ty),*) => {$(
        impl Value for $int {
            fn parse(raw: &str) -> Result<$int, ValueError> {
                let n = decode_integer(raw)?;
                <$int>::try_from(n).map_err(|_| {
                    ValueError::new(format!(
                        "{n} is out of the range {}-{}",
                        <$int>::MIN,
                        <$int>::MAX
                    ))
                })
            }

            fn format(&self) -> String {
                self.to_string()
            }
        }
    )*};
}

value_through_i64!(i8, i16, i32, u8, u16, u32);

/// The text rules are the rules of [`decode_integer`]: decimal digits with
/// an optional `-` sign, and no `+` sign. The full range of `u64` parses. A
/// negative value is refused with the range of the type, as for the other
/// integer types.
impl Value for u64 {
    fn parse(raw: &str) -> Result<u64, ValueError> {
        let n = match decode_integer(raw) {
            Ok(n) => n,
            // A value above `i64::MAX` is not an `i64`. `str::parse` takes a
            // leading `+`, which `decode_integer` refuses.
            Err(err) if raw.starts_with('+') => return Err(err),
            Err(err) => return raw.parse::<u64>().map_err(|_| err),
        };
        u64::try_from(n).map_err(|_| {
            ValueError::new(format!("{n} is out of the range {}-{}", u64::MIN, u64::MAX))
        })
    }

    fn format(&self) -> String {
        self.to_string()
    }
}

impl Value for String {
    fn parse(raw: &str) -> Result<String, ValueError> {
        decode_string(raw)
    }

    fn format(&self) -> String {
        encode_string(self)
    }
}

impl Value for Vec<String> {
    fn parse(raw: &str) -> Result<Vec<String>, ValueError> {
        decode_string_list(raw)
    }

    fn format(&self) -> String {
        encode_string_list(self)
    }
}

/// The text is decoded, and then read as a mode name of
/// [`RepoMode::from_mode_str`]. `format` gives the name of
/// [`RepoMode::as_mode_str`].
impl Value for RepoMode {
    fn parse(raw: &str) -> Result<RepoMode, ValueError> {
        let value = decode_string(raw)?;
        RepoMode::from_mode_str(&value)
            .ok_or_else(|| ValueError::new(format!("'{value}' names no repository mode")))
    }

    fn format(&self) -> String {
        self.as_mode_str().to_owned()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Checks that `parse(format(v)) == v`.
    fn round_trips<V: Value + PartialEq + std::fmt::Debug>(value: V) {
        let text = value.format();
        assert_eq!(V::parse(&text), Ok(value), "{text:?}");
    }

    #[test]
    fn helpers_decode_and_encode() {
        assert_eq!(decode_string(r"a\sb\;c").unwrap(), "a b;c");
        assert_eq!(
            decode_string(r"\q").unwrap_err().to_string(),
            r"invalid escape '\q'"
        );
        assert_eq!(encode_string("  a;b"), r"\s\sa;b");
        assert_eq!(decode_bool("1"), Ok(true));
        assert_eq!(decode_bool("0"), Ok(false));
        assert_eq!(
            decode_bool("yes").unwrap_err().to_string(),
            "is not a boolean"
        );
        assert_eq!(encode_bool(true), "true");
        assert_eq!(encode_bool(false), "false");
        assert_eq!(decode_integer("-5"), Ok(-5));
        assert_eq!(
            decode_integer("+5").unwrap_err().to_string(),
            "is not an integer"
        );
        assert_eq!(encode_integer(-5), "-5");
        assert_eq!(
            decode_string_list(r"a;b\;c;").unwrap(),
            ["a".to_owned(), "b;c".to_owned()]
        );
        assert_eq!(
            decode_string_list("a\\").unwrap_err().to_string(),
            "value ends with a lone backslash"
        );
        assert_eq!(encode_string_list(&["a", "b;c", " d"]), r"a;b\;c;\sd;");
    }

    #[test]
    fn value_error_renders_with_the_group_and_the_key() {
        let render = |err| value_error("core", "fsync", "x", err).to_string();
        assert_eq!(
            render(decode_bool("x").unwrap_err()),
            "keyfile: value 'x' for core.fsync is not a boolean"
        );
        assert_eq!(
            render(decode_integer("x").unwrap_err()),
            "keyfile: value 'x' for core.fsync is not an integer"
        );
        assert_eq!(
            render(decode_string(r"\q").unwrap_err()),
            r"keyfile: invalid escape '\q'"
        );
        assert_eq!(
            render(ValueError::new("is empty")),
            "invalid format: [core] fsync is empty"
        );
    }

    #[test]
    fn bool_integer_and_text_values() {
        assert_eq!(bool::parse("1"), Ok(true));
        assert!(bool::parse("yes").is_err());
        round_trips(true);
        round_trips(false);
        assert_eq!(i64::parse("-9223372036854775808"), Ok(i64::MIN));
        round_trips(i64::MIN);
        round_trips(i64::MAX);
        assert_eq!(u8::parse("255"), Ok(255));
        assert_eq!(
            u8::parse("256").unwrap_err().to_string(),
            "256 is out of the range 0-255"
        );
        assert_eq!(
            i8::parse("-129").unwrap_err().to_string(),
            "-129 is out of the range -128-127"
        );
        assert_eq!(
            u32::parse("-1").unwrap_err().to_string(),
            "-1 is out of the range 0-4294967295"
        );
        round_trips(7u16);
        round_trips(-7i32);
        assert_eq!(String::parse(r"\sa"), Ok(" a".to_owned()));
        round_trips("  a\\b\nc;".to_owned());
        round_trips(String::new());
        assert_eq!(
            Vec::<String>::parse("a;b;"),
            Ok(vec!["a".to_owned(), "b".to_owned()])
        );
        round_trips(vec!["a;b".to_owned(), " c".to_owned(), String::new()]);
        round_trips(Vec::<String>::new());
    }

    #[test]
    fn u64_reads_its_full_range() {
        let above = u64::try_from(i64::MAX).unwrap() + 1;
        assert_eq!(u64::parse("9223372036854775808"), Ok(above));
        assert_eq!(u64::parse("18446744073709551615"), Ok(u64::MAX));
        for value in [0, u64::try_from(i64::MAX).unwrap(), above, u64::MAX] {
            round_trips(value);
        }
        assert_eq!(
            u64::parse("-1").unwrap_err().to_string(),
            "-1 is out of the range 0-18446744073709551615"
        );
        for bad in [
            "+1",
            "+18446744073709551615",
            "18446744073709551616",
            "x",
            "",
        ] {
            assert_eq!(
                u64::parse(bad).unwrap_err().to_string(),
                "is not an integer",
                "{bad:?}"
            );
        }
    }

    #[test]
    fn mode_values() {
        assert_eq!(RepoMode::parse("archive"), Ok(RepoMode::Archive));
        assert_eq!(RepoMode::Archive.format(), "archive-z2");
        assert_eq!(
            RepoMode::parse("bogus").unwrap_err().to_string(),
            "'bogus' names no repository mode"
        );
        for mode in [
            RepoMode::Bare,
            RepoMode::BareUser,
            RepoMode::BareUserOnly,
            RepoMode::BareSplitXattrs,
            RepoMode::Archive,
            RepoMode::BareUserShared,
            RepoMode::BareUserPrivate,
        ] {
            round_trips(mode);
        }
    }

    #[test]
    fn malformed_errors_render_with_the_group_and_the_key() {
        let render = |err| value_error("ex-ostrya server", "listen", "x", err).to_string();
        assert_eq!(
            render(ValueError::malformed_item("x", "why")),
            "invalid format: malformed [ex-ostrya server] listen item 'x': why"
        );
        assert_eq!(
            render(ValueError::malformed_value("x", "why")),
            "invalid format: malformed [ex-ostrya server] listen value 'x': why"
        );
        assert_eq!(
            ValueError::malformed_item("x", "why").to_string(),
            "malformed item 'x': why"
        );
        assert_eq!(
            ValueError::malformed_value("x", "why").to_string(),
            "malformed value 'x': why"
        );
    }
}