okf-core 0.2.5

A pure-Rust implementation of the Open Knowledge Format (OKF) v0.2 specification: parser, model, validator, provenance/trust/attestation families, link graph, and index/log tooling.
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
//! A small YAML *subset* parser used for OKF frontmatter.
//!
//! OKF frontmatter is, in practice, a flat-ish YAML mapping of scalars, lists,
//! and occasionally nested mappings (see the [specification][spec]). A
//! full YAML 1.2 engine would be overkill and would pull in dependencies, so
//! this module implements the pragmatic subset that real frontmatter uses:
//!
//! - block mappings (`key: value`), including nested/indented blocks;
//! - block sequences (`- item`);
//! - flow collections (`[a, b]`, `{a: 1, b: 2}`);
//! - plain, single-quoted, and double-quoted scalars;
//! - literal (`|`) and folded (`>`) block scalars;
//! - `#` comments and blank lines;
//! - the core scalar types: null, bool, int, float, string.
//!
//! Plain and quoted scalars may span lines, folding each break into a single
//! space, because `PyYAML`'s `safe_dump` wraps any value past its 80-column line
//! width and the reference implementation publishes bundles that way.
//!
//! It deliberately does **not** support anchors/aliases, explicit tags
//! (`!!str`), multiple documents, or complex (non-scalar) mapping keys. Those
//! never appear in well-formed OKF frontmatter; encountering them yields a
//! clear [`YamlError`] rather than silent misbehaviour.
//!
//! The guarantee that matters for OKF round-tripping is:
//! `parse(emit(parse(x))) == parse(x)`. Emitting and re-parsing preserves the
//! logical value and key order. This mirrors the reference implementation's
//! `OKFDocument` round-trip test.
//!
//! ## Timestamps are strings
//!
//! One deliberate divergence from `PyYAML`: YAML's implicit resolver types a bare
//! `2026-12-31` as a date and a bare `2026-06-30T14:00:00Z` as a datetime, while
//! this module keeps every scalar of either shape as a string. The OKF layer
//! loses nothing, since [`DateField`](crate::DateField) and
//! [`DateTimeField`](crate::DateTimeField) keep the text beside the parsed
//! value, and it means a malformed date can be reported rather than silently
//! dropped.
//!
//! The consequence shows up on the way out. A bare ISO datetime is not stable
//! even under the reference's own round-trip: `PyYAML` loads it into a `datetime`
//! and dumps it back as `2026-06-30 14:00:00+00:00`, losing the `T` and `Z`
//! separators the spec asks for. A quoted one survives byte-identical. So the
//! emitter quotes a datetime-valued string and leaves a bare `YYYY-MM-DD` plain,
//! which is how both the specification and the reference write `stale_after`,
//! `last_modified`, and `usage_window`.
//!
//! [spec]: https://github.com/GoogleCloudPlatform/open-knowledge-format/blob/main/SPEC.md

mod emitter;
mod parser;

use std::fmt;

pub use parser::YamlError;

/// An ordered YAML mapping (preserves insertion / source order, like the
/// reference implementation which dumps with `sort_keys=False`).
///
/// Keys are [`Value`]s for generality, but OKF frontmatter keys are always
/// strings; the [`get`](Mapping::get) / [`insert`](Mapping::insert) helpers
/// operate on string keys for convenience.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Mapping {
    entries: Vec<(Value, Value)>,
}

impl Mapping {
    /// Creates an empty mapping.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Number of key/value pairs.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` if the mapping has no entries.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Looks up a value by string key.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.entries
            .iter()
            .find(|(k, _)| k.as_str() == Some(key))
            .map(|(_, v)| v)
    }

    /// Looks up a mutable value by string key.
    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
        self.entries
            .iter_mut()
            .find(|(k, _)| k.as_str() == Some(key))
            .map(|(_, v)| v)
    }

    /// Returns `true` if the mapping contains the given string key.
    #[must_use]
    pub fn contains_key(&self, key: &str) -> bool {
        self.get(key).is_some()
    }

    /// Inserts (or, if the string key already exists, replaces) a value,
    /// preserving the position of an existing key. Returns the previous value.
    pub fn insert(&mut self, key: impl Into<String>, value: Value) -> Option<Value> {
        let key = key.into();
        if let Some(slot) = self
            .entries
            .iter_mut()
            .find(|(k, _)| k.as_str() == Some(&key))
        {
            return Some(std::mem::replace(&mut slot.1, value));
        }
        self.entries.push((Value::String(key), value));
        None
    }

    /// Removes a value by string key, preserving order of the rest.
    pub fn remove(&mut self, key: &str) -> Option<Value> {
        let idx = self
            .entries
            .iter()
            .position(|(k, _)| k.as_str() == Some(key))?;
        Some(self.entries.remove(idx).1)
    }

    /// Pushes a raw key/value pair (used by the parser; keeps non-string keys).
    pub(crate) fn push_raw(&mut self, key: Value, value: Value) {
        self.entries.push((key, value));
    }

    /// Iterates over `(key, value)` pairs in order.
    pub fn iter(&self) -> impl Iterator<Item = (&Value, &Value)> {
        self.entries.iter().map(|(k, v)| (k, v))
    }

    /// Iterates over mutable `(key, value)` pairs in order.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&mut Value, &mut Value)> {
        self.entries.iter_mut().map(|(k, v)| (k, v))
    }

    /// Iterates over string keys (skipping any non-string keys).
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.entries.iter().filter_map(|(k, _)| k.as_str())
    }

    /// Iterates over values in order.
    pub fn values(&self) -> impl Iterator<Item = &Value> {
        self.entries.iter().map(|(_, v)| v)
    }

    /// Borrows the underlying slice of key-value entry pairs.
    #[must_use]
    pub fn entries(&self) -> &[(Value, Value)] {
        &self.entries
    }
}

/// A parsed YAML value.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    /// `null`, `~`, or an empty value.
    Null,
    /// `true` / `false`.
    Bool(bool),
    /// An integer scalar.
    Int(i64),
    /// A floating-point scalar.
    Float(f64),
    /// A string scalar.
    String(String),
    /// A sequence (`[...]` or block `- ...`).
    Sequence(Vec<Self>),
    /// A mapping (`{...}` or block `key: value`).
    Mapping(Mapping),
}

impl Value {
    /// Parses a single YAML value from text (the OKF frontmatter subset).
    ///
    /// # Errors
    ///
    /// Returns [`YamlError`] for any input outside the supported subset
    /// (anchors, tags, multiple documents, or syntactically malformed YAML).
    pub fn parse(text: &str) -> Result<Self, YamlError> {
        parser::parse(text)
    }

    /// Emits this value as YAML text using block style, preserving key order.
    #[must_use]
    pub fn to_yaml_string(&self) -> String {
        emitter::emit(self)
    }

    /// Returns the string contents if this is a [`Value::String`].
    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(s) => Some(s),
            _ => None,
        }
    }

    /// Returns the boolean if this is a [`Value::Bool`].
    #[must_use]
    pub const fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Returns the integer if this is a [`Value::Int`].
    #[must_use]
    pub const fn as_int(&self) -> Option<i64> {
        match self {
            Self::Int(i) => Some(*i),
            _ => None,
        }
    }

    /// Returns the floating-point number if this is a [`Value::Float`].
    #[must_use]
    pub const fn as_float(&self) -> Option<f64> {
        match self {
            Self::Float(f) => Some(*f),
            _ => None,
        }
    }

    /// Returns the sequence elements if this is a [`Value::Sequence`].
    #[must_use]
    pub fn as_sequence(&self) -> Option<&[Self]> {
        match self {
            Self::Sequence(s) => Some(s),
            _ => None,
        }
    }

    /// Returns the mapping if this is a [`Value::Mapping`].
    #[must_use]
    pub const fn as_mapping(&self) -> Option<&Mapping> {
        match self {
            Self::Mapping(m) => Some(m),
            _ => None,
        }
    }

    /// True for `Null`, an empty string, an empty sequence, or an empty
    /// mapping. Mirrors Python's "falsy" check used by the reference
    /// implementation's `validate()` (`not frontmatter.get(k)`).
    #[must_use]
    pub const fn is_empty_value(&self) -> bool {
        match self {
            Self::Null | Self::Bool(false) | Self::Int(0) => true,
            Self::String(s) => s.is_empty(),
            Self::Sequence(s) => s.is_empty(),
            Self::Mapping(m) => m.is_empty(),
            _ => false,
        }
    }

    /// Renders a scalar as a plain display string (used for typed frontmatter
    /// accessors that coerce scalars to text, matching the reference's
    /// `str(fm.get(...))`).
    #[must_use]
    pub fn as_display_string(&self) -> Option<String> {
        match self {
            Self::String(s) => Some(s.clone()),
            Self::Bool(b) => Some(b.to_string()),
            Self::Int(i) => Some(i.to_string()),
            Self::Float(f) => Some(format!("{f}")),
            _ => None,
        }
    }

    /// The borrowing form of [`as_display_string`](Self::as_display_string):
    /// returns a [`std::borrow::Cow`] borrowing the [`String`](Self::String) case and
    /// owning the coerced form for [`Bool`](Self::Bool)/[`Int`](Self::Int)/
    /// [`Float`](Self::Float). `None` for non-scalar variants.
    ///
    /// Frontmatter accessors use this so the common case (a YAML string) is
    /// allocation-free, while the deviation case (e.g. `type: 42`) still
    /// coerces to text the way the reference's `str(fm.get(...))` does, rather
    /// than silently reading as `None`.
    #[must_use]
    pub fn as_display_str(&self) -> Option<std::borrow::Cow<'_, str>> {
        match self {
            Self::String(s) => Some(std::borrow::Cow::Borrowed(s)),
            Self::Bool(b) => Some(std::borrow::Cow::Owned(b.to_string())),
            Self::Int(i) => Some(std::borrow::Cow::Owned(i.to_string())),
            Self::Float(f) => Some(std::borrow::Cow::Owned(format!("{f}"))),
            _ => None,
        }
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_yaml_string())
    }
}

impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Self::String(s.to_string())
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Self::String(s)
    }
}

impl From<bool> for Value {
    fn from(b: bool) -> Self {
        Self::Bool(b)
    }
}

impl From<i64> for Value {
    fn from(i: i64) -> Self {
        Self::Int(i)
    }
}

impl<T: Into<Self>> From<Vec<T>> for Value {
    fn from(v: Vec<T>) -> Self {
        Self::Sequence(v.into_iter().map(Into::into).collect())
    }
}

impl From<Mapping> for Value {
    fn from(m: Mapping) -> Self {
        Self::Mapping(m)
    }
}

impl std::str::FromStr for Value {
    type Err = YamlError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

impl From<i32> for Value {
    fn from(i: i32) -> Self {
        Self::Int(i64::from(i))
    }
}

impl From<i16> for Value {
    fn from(i: i16) -> Self {
        Self::Int(i64::from(i))
    }
}

impl From<i8> for Value {
    fn from(i: i8) -> Self {
        Self::Int(i64::from(i))
    }
}

impl From<u32> for Value {
    fn from(u: u32) -> Self {
        Self::Int(i64::from(u))
    }
}

impl From<u16> for Value {
    fn from(u: u16) -> Self {
        Self::Int(i64::from(u))
    }
}

impl From<u8> for Value {
    fn from(u: u8) -> Self {
        Self::Int(i64::from(u))
    }
}

impl From<u64> for Value {
    fn from(u: u64) -> Self {
        Self::Int(i64::try_from(u).unwrap_or(i64::MAX))
    }
}

impl From<usize> for Value {
    fn from(u: usize) -> Self {
        Self::Int(i64::try_from(u).unwrap_or(i64::MAX))
    }
}

impl From<f64> for Value {
    fn from(f: f64) -> Self {
        Self::Float(f)
    }
}

impl From<f32> for Value {
    fn from(f: f32) -> Self {
        Self::Float(f64::from(f))
    }
}

impl From<&String> for Value {
    fn from(s: &String) -> Self {
        Self::String(s.clone())
    }
}

impl From<std::borrow::Cow<'_, str>> for Value {
    fn from(s: std::borrow::Cow<'_, str>) -> Self {
        Self::String(s.into_owned())
    }
}

impl From<()> for Value {
    fn from((): ()) -> Self {
        Self::Null
    }
}

impl<T: Into<Self>> From<Option<T>> for Value {
    fn from(opt: Option<T>) -> Self {
        opt.map_or(Self::Null, Into::into)
    }
}

impl fmt::Display for Mapping {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&Value::Mapping(self.clone()).to_yaml_string())
    }
}

impl IntoIterator for Mapping {
    type Item = (Value, Value);
    type IntoIter = std::vec::IntoIter<(Value, Value)>;
    fn into_iter(self) -> Self::IntoIter {
        self.entries.into_iter()
    }
}

impl<'a> IntoIterator for &'a Mapping {
    type Item = (&'a Value, &'a Value);
    type IntoIter = std::iter::Map<
        std::slice::Iter<'a, (Value, Value)>,
        fn(&(Value, Value)) -> (&Value, &Value),
    >;
    fn into_iter(self) -> Self::IntoIter {
        const fn map_ref(entry: &(Value, Value)) -> (&Value, &Value) {
            (&entry.0, &entry.1)
        }
        self.entries.iter().map(map_ref)
    }
}

impl<'a> IntoIterator for &'a mut Mapping {
    type Item = (&'a mut Value, &'a mut Value);
    type IntoIter = std::iter::Map<
        std::slice::IterMut<'a, (Value, Value)>,
        fn(&mut (Value, Value)) -> (&mut Value, &mut Value),
    >;
    fn into_iter(self) -> Self::IntoIter {
        const fn map_mut(entry: &mut (Value, Value)) -> (&mut Value, &mut Value) {
            (&mut entry.0, &mut entry.1)
        }
        self.entries.iter_mut().map(map_mut)
    }
}

impl FromIterator<(Value, Value)> for Mapping {
    fn from_iter<T: IntoIterator<Item = (Value, Value)>>(iter: T) -> Self {
        Self {
            entries: iter.into_iter().collect(),
        }
    }
}

impl FromIterator<(String, Value)> for Mapping {
    fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
        let mut map = Self::new();
        for (k, v) in iter {
            map.insert(k, v);
        }
        map
    }
}

impl<'a> FromIterator<(&'a str, Value)> for Mapping {
    fn from_iter<T: IntoIterator<Item = (&'a str, Value)>>(iter: T) -> Self {
        let mut map = Self::new();
        for (k, v) in iter {
            map.insert(k, v);
        }
        map
    }
}

impl Extend<(Value, Value)> for Mapping {
    fn extend<T: IntoIterator<Item = (Value, Value)>>(&mut self, iter: T) {
        self.entries.extend(iter);
    }
}

impl Extend<(String, Value)> for Mapping {
    fn extend<T: IntoIterator<Item = (String, Value)>>(&mut self, iter: T) {
        for (k, v) in iter {
            self.insert(k, v);
        }
    }
}

impl<'a> Extend<(&'a str, Value)> for Mapping {
    fn extend<T: IntoIterator<Item = (&'a str, Value)>>(&mut self, iter: T) {
        for (k, v) in iter {
            self.insert(k, v);
        }
    }
}