prov 0.2.3

A self-describing plaintext workspace: structure lives in documents' own embedded metadata.
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
//! Format-preserving edits to a document's metadata, whatever carries it.
//!
//! [`MetaEditor`] dispatches on the document's [`MetaCarrier`]: a fenced block
//! is edited with fig's [`fig::Embed`] (fences and body untouched), a config
//! document with fig's [`fig::Editor`] (the whole file *is* the metadata).
//! Either way the edit is comment-preserving and byte-minimal — only the
//! changed node's bytes move — and the original carrier and format are never
//! rewritten into another.
//!
//! The workspace mutation ops build on this; the free functions are the
//! single-document surface (the CLI's `set`/`unset`).

use fig::{Embed, EmbedType, Segment};

use crate::document::MetaCarrier;
use crate::error::{Error, Result};
use crate::meta::Mapping;

/// The frontmatter archetype used to synthesize a metadata block for a document
/// that has none. YAML (`---`) is the convention when compiled in; otherwise the
/// first other format that is. Exactly one arm survives `cfg` stripping, and the
/// `compile_error!` in `lib.rs` guarantees at least one does.
fn default_embed_type() -> EmbedType {
    #[cfg(feature = "yaml")]
    return EmbedType::FrontmatterYaml;
    #[cfg(all(not(feature = "yaml"), feature = "json"))]
    return EmbedType::FrontmatterJson;
    #[cfg(all(not(feature = "yaml"), not(feature = "json"), feature = "fig-lang"))]
    return EmbedType::FrontmatterFig;
}

/// A comment-preserving editor over a document's metadata, generic over where
/// the metadata lives.
pub enum MetaEditor {
    /// Editing a fenced block inside a host file.
    Fenced(Embed),
    /// Editing a config document (the whole file is the metadata).
    Whole(fig::Editor),
}

impl MetaEditor {
    /// Open an editor over `text` for an existing carrier.
    pub fn open(text: &str, carrier: MetaCarrier) -> Result<Self> {
        Ok(match carrier {
            MetaCarrier::Fenced(kind) => MetaEditor::Fenced(Embed::open(text.as_bytes(), kind)?),
            MetaCarrier::WholeFile(format) => {
                MetaEditor::Whole(fig::Editor::open(text.as_bytes(), format)?)
            }
        })
    }

    /// Open an editor over `text`, creating the metadata block when the
    /// document has none: an explicit carrier is honored (an absent fenced
    /// block is synthesized in place), and `None` defaults to a fresh
    /// frontmatter block in [`default_embed_type`]'s archetype (`---` YAML
    /// when that feature is compiled in).
    pub fn open_or_init(text: &str, carrier: Option<MetaCarrier>) -> Result<Self> {
        Ok(match carrier {
            Some(MetaCarrier::WholeFile(format)) => {
                MetaEditor::Whole(fig::Editor::open(text.as_bytes(), format)?)
            }
            Some(MetaCarrier::Fenced(kind)) => {
                MetaEditor::Fenced(Embed::open_or_init(text.as_bytes(), kind)?)
            }
            None => MetaEditor::Fenced(Embed::open_or_init(text.as_bytes(), default_embed_type())?),
        })
    }

    /// Upsert `value` at `path` (the trailing segment must be a key).
    pub fn set_value(&mut self, path: &[Segment], value: impl Into<fig::Value>) -> Result<()> {
        match self {
            MetaEditor::Fenced(e) => e.set_value(path, value)?,
            MetaEditor::Whole(e) => e.set_value(path, value)?,
        }
        Ok(())
    }

    /// Replace the existing value at `path`.
    pub fn replace_value(&mut self, path: &[Segment], value: impl Into<fig::Value>) -> Result<()> {
        match self {
            MetaEditor::Fenced(e) => e.replace_value(path, value)?,
            MetaEditor::Whole(e) => e.replace_value(path, value)?,
        }
        Ok(())
    }

    /// Rename the key at `path`, keeping its value, position, and comments.
    pub fn replace_key(&mut self, path: &[Segment], key: &str) -> Result<()> {
        match self {
            MetaEditor::Fenced(e) => e.replace_key(path, key)?,
            MetaEditor::Whole(e) => e.replace_key(path, key)?,
        }
        Ok(())
    }

    /// Append `value` to the sequence at `path`.
    pub fn append_value(&mut self, path: &[Segment], value: impl Into<fig::Value>) -> Result<()> {
        match self {
            MetaEditor::Fenced(e) => e.append_value(path, value)?,
            MetaEditor::Whole(e) => e.append_value(path, value)?,
        }
        Ok(())
    }

    /// Delete the mapping entry at `path`.
    pub fn delete(&mut self, path: &[Segment]) -> Result<()> {
        match self {
            MetaEditor::Fenced(e) => e.delete(path)?,
            MetaEditor::Whole(e) => e.delete(path)?,
        }
        Ok(())
    }

    /// Remove the item at `index` from the sequence at `path`.
    pub fn remove_item(&mut self, path: &[Segment], index: usize) -> Result<()> {
        match self {
            MetaEditor::Fenced(e) => e.remove_item(path, index)?,
            MetaEditor::Whole(e) => e.remove_item(path, index)?,
        }
        Ok(())
    }

    /// Reorder the mapping entries at `path` (empty path = root) so `keys`
    /// come first, in that order; entries not listed keep their original
    /// relative order and follow. Unknown keys are ignored. Every entry keeps
    /// its comments and interleaved trivia.
    pub fn reorder_keys<S: AsRef<str>>(&mut self, path: &[Segment], keys: &[S]) -> Result<()> {
        match self {
            MetaEditor::Fenced(e) => e.reorder_keys(path, keys)?,
            MetaEditor::Whole(e) => e.reorder_keys(path, keys)?,
        }
        Ok(())
    }

    /// Reorder the sequence at `path` so the items at `indices` (positions in
    /// the current order) come first, in that order; items not listed keep
    /// their original relative order and follow. Out-of-range indices are
    /// ignored.
    pub fn reorder_items(&mut self, path: &[Segment], indices: &[usize]) -> Result<()> {
        match self {
            MetaEditor::Fenced(e) => e.reorder_items(path, indices)?,
            MetaEditor::Whole(e) => e.reorder_items(path, indices)?,
        }
        Ok(())
    }

    /// Render the full document text with the edits applied.
    pub fn render(&mut self) -> Result<String> {
        Ok(match self {
            MetaEditor::Fenced(e) => e.render()?.to_string(),
            MetaEditor::Whole(e) => e.source()?.to_string(),
        })
    }
}

/// Parse a dotted key path (`a.b.0.c`) into fig path segments. An all-digit
/// segment indexes a sequence; anything else names a mapping key.
pub fn key_path(dotted: &str) -> Vec<Segment<'_>> {
    dotted
        .split('.')
        .map(|part| match part.parse::<usize>() {
            Ok(index) => Segment::Index(index),
            Err(_) => Segment::Key(part),
        })
        .collect()
}

/// Interpret a CLI-provided scalar: `true`/`false`, integers, floats, and
/// `null` become their typed values; everything else stays a string.
pub fn infer_scalar(s: &str) -> fig::Value {
    match s {
        "true" => fig::Value::Bool(true),
        "false" => fig::Value::Bool(false),
        "null" | "~" => fig::Value::Null,
        _ => {
            if let Ok(i) = s.parse::<i64>() {
                fig::Value::Int(i)
            } else if let Ok(f) = s.parse::<f64>() {
                fig::Value::Float(f)
            } else {
                fig::Value::Str(s.to_string())
            }
        }
    }
}

/// Upsert `dotted` to `value` in `text`'s metadata (carrier-aware), creating
/// a YAML frontmatter block when the document has none. Returns the full
/// re-rendered document text.
pub fn set_in_text(
    text: &str,
    carrier: Option<MetaCarrier>,
    dotted: &str,
    value: fig::Value,
) -> Result<String> {
    let mut editor = MetaEditor::open_or_init(text, carrier)?;
    let path = key_path(dotted);
    match path.last() {
        // fig's `set` upserts a trailing *key*; an index-terminated path is a
        // pure replacement (there is no "insert at absent index" to upsert).
        Some(Segment::Index(_)) => editor.replace_value(&path, value)?,
        _ => editor.set_value(&path, value)?,
    }
    editor.render()
}

/// Delete the entry at `dotted` from `text`'s metadata (carrier-aware).
/// Returns the full re-rendered document text. Errors when the document has
/// no metadata or the path does not exist.
pub fn unset_in_text(text: &str, carrier: Option<MetaCarrier>, dotted: &str) -> Result<String> {
    let carrier = carrier
        .ok_or_else(|| Error::Structure("document has no embedded metadata block".into()))?;
    let mut editor = MetaEditor::open(text, carrier)?;
    editor.delete(&key_path(dotted))?;
    editor.render()
}

/// Re-emit `mapping` as a fresh metadata block of archetype `target`, placed in
/// `target`'s canonical position around the plain `body` (before it for
/// frontmatter, after it for endmatter) — the reconstruction a *format
/// conversion* performs. Unlike the comment-preserving edits above, this
/// deliberately rebuilds the block: a conversion crosses formats (a YAML comment
/// has no JSON home), so only the values survive.
///
/// The content is rendered by prov's canonical [`serialize_mapping`] — the
/// same serializer behind `prov meta --format`, so a converted block's
/// sequence and scalar layout matches the rest of the codebase (fig's per-key
/// [`Embed`] splice path renders some formats, notably fig sequences,
/// differently). The block's fences and placement come from fig, by synthesizing
/// an empty `target` block around `body` and splicing the serialized content into
/// its content slot.
///
/// The content is spliced verbatim — the same bytes prov's reader
/// ([`Document::parse`](crate::Document::parse), via [`fig::split`]) hands back to
/// the format parser, which does not HTML-decode a `<pre><code>` island. Writing
/// what that reader expects keeps a converted value round-tripping through
/// `prov get`/`check` rather than acquiring stray `&lt;` entities.
///
/// [`serialize_mapping`]: crate::meta::serialize_mapping
pub fn reformat_block(body: &str, mapping: &Mapping, target: EmbedType) -> Result<String> {
    let mut inner = crate::meta::serialize_mapping(mapping, target.inner_format())?;
    // The content slot sits between the opening fence's trailing newline and the
    // closing fence, so the content must end in exactly one newline for the close
    // fence to land on its own line.
    if !inner.ends_with('\n') {
        inner.push('\n');
    }
    // Synthesize an empty `target` block in its canonical place around `body`,
    // then replace its (empty) content slot with the serialized content: fig owns
    // the fences and placement, we own what goes between them.
    let rendered = Embed::open_or_init(body.as_bytes(), target)?
        .render()?
        .to_string();
    let content = Embed::extract(&rendered, target)?.region().content;
    let mut out = String::with_capacity(rendered.len() + inner.len());
    out.push_str(&rendered[..content.start]);
    out.push_str(&inner);
    out.push_str(&rendered[content.end..]);
    Ok(out)
}

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

    fn carrier_of(path: &str, text: &str) -> Option<MetaCarrier> {
        crate::document::Document::parse(path, text)
            .unwrap()
            .carrier
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn set_preserves_comments_and_format() {
        let text = "---\n# keep me\ntitle: Old\n---\nbody\n";
        let out =
            set_in_text(text, carrier_of("x.md", text), "title", infer_scalar("New")).unwrap();
        assert_eq!(out, "---\n# keep me\ntitle: New\n---\nbody\n");
    }

    #[cfg(feature = "fig-lang")]
    #[test]
    fn set_in_a_fig_block_stays_fig() {
        let text = "```fig\ntitle = prov\n```\nbody\n";
        let out = set_in_text(
            text,
            carrier_of("x.md", text),
            "title",
            infer_scalar("renamed"),
        )
        .unwrap();
        assert!(out.starts_with("```fig\n"), "fence preserved: {out}");
        assert!(
            out.contains("title = renamed"),
            "fig dialect preserved: {out}"
        );
        assert!(out.ends_with("```\nbody\n"));
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn set_edits_a_bare_config_document() {
        let text = "# workspace registry\ntitle: ID registry\nregistry:\n  abc: a.md\n";
        let out = set_in_text(
            text,
            carrier_of("registry.yaml", text),
            "registry.abc",
            infer_scalar("moved/a.md"),
        )
        .unwrap();
        assert!(out.contains("# workspace registry"), "comment kept: {out}");
        assert!(out.contains("abc: moved/a.md"), "{out}");
        assert!(!out.contains("---"), "no fences grown: {out}");
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn set_creates_a_block_when_none_exists() {
        let out = set_in_text("just a body\n", None, "title", infer_scalar("T")).unwrap();
        assert!(out.starts_with("---\ntitle: T\n---\n"), "{out}");
        assert!(out.ends_with("just a body\n"));
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn unset_removes_only_the_named_key() {
        let text = "---\ntitle: T\ndraft: true\n---\nbody\n";
        let out = unset_in_text(text, carrier_of("x.md", text), "draft").unwrap();
        assert_eq!(out, "---\ntitle: T\n---\nbody\n");
        assert!(unset_in_text("no meta\n", None, "x").is_err());
    }

    #[test]
    fn scalars_are_inferred() {
        assert_eq!(infer_scalar("true"), fig::Value::Bool(true));
        assert_eq!(infer_scalar("42"), fig::Value::Int(42));
        assert_eq!(infer_scalar("4.5"), fig::Value::Float(4.5));
        assert_eq!(infer_scalar("null"), fig::Value::Null);
        assert_eq!(infer_scalar("hello"), fig::Value::Str("hello".into()));
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn dotted_paths_mix_keys_and_indices() {
        let text = "---\ncontents:\n- a.md\n- b.md\n---\n";
        let out = set_in_text(
            text,
            carrier_of("x.md", text),
            "contents.1",
            infer_scalar("c.md"),
        )
        .unwrap();
        assert!(out.contains("- a.md\n- c.md"), "{out}");
    }

    // ---- MetaEditor parity with fig::Embed: reorder_items/replace_key/reorder_keys ----

    #[cfg(feature = "yaml")]
    #[test]
    fn replace_key_renames_the_key_and_preserves_comments_elsewhere() {
        let text = "---\n# keep me\ntitle: Old\nauthor: me\n---\nbody\n";
        let mut editor = MetaEditor::open(text, carrier_of("x.md", text).unwrap()).unwrap();
        editor.replace_key(&key_path("title"), "name").unwrap();
        let out = editor.render().unwrap();
        assert!(out.contains("name: Old"), "{out}");
        assert!(!out.contains("title:"), "{out}");
        assert!(out.contains("# keep me"), "comment lost: {out}");
        assert!(out.contains("author: me"), "{out}");
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn reorder_keys_moves_listed_keys_first_and_preserves_comments() {
        let text = "---\n# c1\ntitle: T\n# c2\nauthor: me\ndraft: true\n---\nbody\n";
        let mut editor = MetaEditor::open(text, carrier_of("x.md", text).unwrap()).unwrap();
        editor
            .reorder_keys(&[] as &[Segment], &["draft", "title"])
            .unwrap();
        let out = editor.render().unwrap();
        let draft_pos = out.find("draft:").unwrap();
        let title_pos = out.find("title:").unwrap();
        let author_pos = out.find("author:").unwrap();
        assert!(draft_pos < title_pos && title_pos < author_pos, "{out}");
        assert!(out.contains("# c1"), "comment lost: {out}");
        assert!(out.contains("# c2"), "comment lost: {out}");
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn reorder_items_moves_listed_items_first_and_preserves_comments() {
        let text = "---\ncontents:\n- a # keep a\n- b # keep b\n- c # keep c\n---\nbody\n";
        let mut editor = MetaEditor::open(text, carrier_of("x.md", text).unwrap()).unwrap();
        editor
            .reorder_items(&key_path("contents"), &[2, 0])
            .unwrap();
        let out = editor.render().unwrap();
        assert!(out.contains("# keep a"), "comment lost: {out}");
        assert!(out.contains("# keep b"), "comment lost: {out}");
        assert!(out.contains("# keep c"), "comment lost: {out}");
        let a_pos = out.find("- a").unwrap();
        let b_pos = out.find("- b").unwrap();
        let c_pos = out.find("- c").unwrap();
        // indices [2, 0] -> c, a first (in that order), then the unlisted b follows.
        assert!(c_pos < a_pos && a_pos < b_pos, "{out}");
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn reorder_keys_works_on_a_whole_file_config_document() {
        // Exercises the `MetaEditor::Whole` arm (a config document, not a
        // fenced block) — the same op, the other carrier.
        let text =
            "# workspace registry\ntitle: ID registry\npart_of: index.md\nregistry:\n  abc: a.md\n";
        let mut editor =
            MetaEditor::open(text, carrier_of("registry.yaml", text).unwrap()).unwrap();
        editor
            .reorder_keys(&[] as &[Segment], &["part_of"])
            .unwrap();
        let out = editor.render().unwrap();
        let part_of_pos = out.find("part_of:").unwrap();
        let title_pos = out.find("title:").unwrap();
        assert!(part_of_pos < title_pos, "{out}");
        assert!(out.contains("# workspace registry"), "comment lost: {out}");
    }
}