prov-graph 0.10.0

The read core of a prov workspace: documents, links, and the traversal over them
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
//! Documents — a plaintext file with an embedded metadata block and a body,
//! or a config file whose *entire content* is the metadata.
//!
//! The two shapes are one model: a config file is simply a document whose
//! metadata carrier is the whole file and whose body is empty. Both parse to
//! the same [`Document`], link through the same relations, and participate in
//! traversal, validation, and mutation identically — which is what lets a
//! workspace mix prose documents and config documents in one tree.

use std::path::{Path, PathBuf};

use crate::error::Result;
use crate::meta::{self, Value};

/// The embed archetype a fenced metadata block was found in. Re-exported from
/// `fig`, which owns both detection (`fig::detect`) and the fence/format
/// coupling ([`EmbedType::inner_format`]).
pub use fig::EmbedType;

/// A document's prose body, and the file it was read from.
///
/// The two halves travel together because a *separated* document keeps them in
/// different files: the text comes from the `content` target while the metadata
/// stays in the node, so a caller that renders the prose needs to know which
/// path declares its grammar. For a combined document [`path`](Body::path) is
/// simply the document's own.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Body {
    /// The prose itself. Empty for a document that has none — a config
    /// document standing for itself, or a manifest node standing for a
    /// directory.
    pub text: String,
    /// The file the prose lives in: the document's own path when combined, its
    /// [`content_path`](Document::content_path) when separated. What
    /// [`ContentFormat::from_extension`](crate::content::ContentFormat::from_extension)
    /// should be asked about.
    pub path: PathBuf,
}

/// Where a document's metadata physically lives — recorded at parse time so a
/// write can preserve the original carrier exactly (a ```` ```fig ```` block is
/// never rewritten as `---` YAML; a bare `.yaml` file never grows fences).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MetaCarrier {
    /// A fenced block inside a host file (`---` YAML, `;;;` JSON,
    /// ```` ```fig ````, endmatter), with the prose body around it.
    Fenced(EmbedType),
    /// The entire file is the metadata (a config document); the body is empty.
    /// The format comes from the file extension.
    WholeFile(fig::Format),
}

impl MetaCarrier {
    /// The format the metadata is written in.
    pub fn format(&self) -> fig::Format {
        match self {
            MetaCarrier::Fenced(kind) => kind.inner_format(),
            MetaCarrier::WholeFile(format) => *format,
        }
    }
}

/// The whole-file metadata format implied by `path`'s extension, if any.
/// These are the extensions prov treats as config documents.
///
/// Each extension is recognized only when its format feature is compiled in: a
/// `.json` file is a config document under the `json` feature, and an ordinary
/// (metadata-less) prose document without it. This keeps prov from claiming
/// to read a format whose parser was left out of the build.
pub fn whole_file_format(path: &Path) -> Option<fig::Format> {
    match path.extension()?.to_str()? {
        #[cfg(feature = "yaml")]
        "yaml" | "yml" => Some(fig::Format::Yaml),
        #[cfg(feature = "json")]
        "json" => Some(fig::Format::Json),
        #[cfg(feature = "toml")]
        "toml" => Some(fig::Format::Toml),
        #[cfg(feature = "fig-lang")]
        "fig" | "figl" => Some(fig::Format::Fig),
        _ => None,
    }
}

/// Enforce that a **record store** at `path` (the id registry, the recycle-bin
/// index, a flat vocabulary) is a whole-file config document, returning its
/// format. A [`MetaCarrier::Fenced`] carrier — markdown frontmatter — is
/// rejected with [`Error::MarkdownStore`](crate::error::Error::MarkdownStore): prov re-lays-out these stores as a
/// sorted record list (DESIGN §5), so human prose has no stable home in them and
/// unambiguous extension→format sniffing depends on the carrier being whole-file.
/// The single choke point every store loader passes through, so the rule cannot
/// be enforced in one place and forgotten in another.
pub fn require_whole_file(path: &Path, carrier: MetaCarrier) -> Result<fig::Format> {
    match carrier {
        MetaCarrier::WholeFile(format) => Ok(format),
        MetaCarrier::Fenced(_) => Err(crate::error::Error::MarkdownStore(path.to_path_buf())),
    }
}

/// Whether prov can read `path` as text — a recognized body format
/// (Markdown/Djot/HTML) or a whole-file metadata format (YAML/JSON/…). Its
/// negation is an **opaque payload**: a file prov treats as bytes (an image,
/// a PDF, a font, any binary) and never parses. An *attachment* is exactly a
/// whole-file metadata sidecar whose `content` points at such a payload, which
/// is how an arbitrary file gains workspace-linked metadata without being able
/// to carry frontmatter itself.
pub fn is_opaque_payload(path: &Path) -> bool {
    crate::content::ContentFormat::from_extension(path).is_none()
        && whole_file_format(path).is_none()
}

/// The canonical whole-file extension for a metadata `format` — the inverse of
/// [`whole_file_format`]. Used when materializing a whole-file metadata document
/// (a config/registry sidecar, or the metadata half of a *separated* document):
/// `yaml`, `json`, `figl`. A format whose feature is not compiled falls back to
/// `yaml` (the always-present default).
pub fn whole_file_extension(format: fig::Format) -> &'static str {
    match format {
        #[cfg(feature = "json")]
        fig::Format::Json => "json",
        #[cfg(feature = "toml")]
        fig::Format::Toml => "toml",
        #[cfg(feature = "fig-lang")]
        fig::Format::Fig => "figl",
        _ => "yaml",
    }
}

/// The fenced-frontmatter carrier for `format` — the archetype a new document
/// gets when it inherits no parent block and the workspace default is `format`.
/// A format whose feature is not compiled falls back to YAML frontmatter (which
/// the default `yaml` feature always provides).
pub fn frontmatter_carrier(format: fig::Format) -> MetaCarrier {
    let embed = match format {
        #[cfg(feature = "json")]
        fig::Format::Json => EmbedType::FrontmatterJson,
        #[cfg(feature = "toml")]
        fig::Format::Toml => EmbedType::PlusToml,
        #[cfg(feature = "fig-lang")]
        fig::Format::Fig => EmbedType::FrontmatterFig,
        _ => EmbedType::FrontmatterYaml,
    };
    MetaCarrier::Fenced(embed)
}

/// The archetype *family* a workspace authors embedded metadata in — the
/// "embed type" the CLI's `init` prompts for, one level above the concrete
/// [`EmbedType`]. A family plus a metadata [`fig::Format`] resolves to a
/// carrier through [`embed_carrier`]: e.g. (`CodeBlock`, YAML) is a
/// ```` ```yaml ```` block, (`Delimited`, TOML) is a `+++` block, and
/// (`Separate`, JSON) is a whole-file `.json` sidecar. It is what the config
/// document records (via `prov`'s `WorkspaceConfig`) so a
/// workspace stays self-describing about *how* its metadata is embedded, not
/// just which format it is written in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmbedStyle {
    /// Character-delimited frontmatter: `---` YAML, `+++` TOML, `;;;` JSON. A
    /// Markdown convention; the fig dialect has no delimiter form.
    Delimited,
    /// A typed fenced code block — ```` ```yaml ````, ```` ```toml ````,
    /// ```` ```json ````, ```` ```fig ```` — that renders as a visible block in
    /// Markdown or Djot.
    CodeBlock,
    /// An HTML `<script type="application/…">` data island (not rendered).
    HtmlScript,
    /// An HTML `<pre><code class="language-…">` visible code block.
    HtmlCode,
    /// Metadata kept in a sibling *whole-file* document, joined to a plain body
    /// file by a `content` attribute — neither file carries fences.
    Separate,
}

impl EmbedStyle {
    /// The `embed_type` config-document spelling for this style.
    pub fn as_config_str(self) -> &'static str {
        match self {
            EmbedStyle::Delimited => "delimited",
            EmbedStyle::CodeBlock => "code_block",
            EmbedStyle::HtmlScript => "html_script",
            EmbedStyle::HtmlCode => "html_code",
            EmbedStyle::Separate => "separate",
        }
    }

    /// Parse an `embed_type` config value. Unknown → `None` (keep the default).
    pub fn from_config_str(value: &str) -> Option<Self> {
        Some(match value {
            "delimited" => EmbedStyle::Delimited,
            "code_block" => EmbedStyle::CodeBlock,
            "html_script" => EmbedStyle::HtmlScript,
            "html_code" => EmbedStyle::HtmlCode,
            "separate" => EmbedStyle::Separate,
            _ => return None,
        })
    }
}

/// The [`EmbedStyle`] *family* a concrete [`EmbedType`] belongs to — the inverse
/// (on the style axis) of [`embed_carrier`], which resolves a `(style, format)`
/// pair back to a carrier. Pairing it with a new metadata format is how a
/// *format conversion* keeps a document's embedding shape while changing only its
/// frontmatter language: classify the current archetype, then [`embed_carrier`]
/// the same style with the target format.
///
/// The bare delimiter frontmatters (`---`/`+++`/`;;;`) and the labeled markdown
/// frontmatters (`---json`/`---toml`/`---fig`) are all [`Delimited`](EmbedStyle::Delimited);
/// [`embed_carrier`] then lands each format on prov's canonical delimiter
/// spelling. Endmatter is grouped with the fenced [`CodeBlock`](EmbedStyle::CodeBlock)
/// forms (it is a trailing ```` ```endmatter ```` block); converting it to another
/// format therefore moves it to a leading fenced block, since only YAML has an
/// endmatter archetype.
pub fn embed_style_of(kind: EmbedType) -> EmbedStyle {
    use EmbedType as E;
    match kind {
        E::FrontmatterYaml
        | E::FrontmatterJson
        | E::PlusToml
        | E::MdFrontmatterJson
        | E::MdFrontmatterToml
        | E::MdFrontmatterFig => EmbedStyle::Delimited,
        E::EndmatterYaml | E::FencedYaml | E::FencedJson | E::FencedToml | E::FrontmatterFig => {
            EmbedStyle::CodeBlock
        }
        E::HtmlScriptYaml | E::HtmlScriptJson | E::HtmlScriptToml | E::HtmlScriptFig => {
            EmbedStyle::HtmlScript
        }
        E::HtmlCodeYaml | E::HtmlCodeJson | E::HtmlCodeToml | E::HtmlCodeFig => {
            EmbedStyle::HtmlCode
        }
        // `EmbedType` is `#[non_exhaustive]`: a fig version newer than this crate
        // may detect an archetype prov doesn't know yet. Guessing a style here
        // would risk silently misclassifying a real document mid-`convert`, so
        // this needs an actual case added (here, `embed_carrier`, and the prose
        // in `about.rs`/`history/docs.rs`) before such a document can be handled.
        _ => unreachable!("unhandled fig::EmbedType variant — add a case in embed_style_of"),
    }
}

/// Resolve an [`EmbedStyle`] + metadata `format` to the carrier a new document
/// should get. `Separate` maps to a whole-file sidecar in `format`; every other
/// style maps to the concrete [`EmbedType`] for that `(style, format)` pair.
/// `None` for a combination that has no archetype — notably `Delimited` + fig
/// (the dialect has no `---`-style delimiter) and any fenced style paired with a
/// format fig cannot fence (`Zon`).
pub fn embed_carrier(style: EmbedStyle, format: fig::Format) -> Option<MetaCarrier> {
    use EmbedType as E;
    use fig::Format as F;
    // JSON's three dialects share one fenced/frontmatter archetype.
    let is_json = matches!(format, F::Json | F::Jsonc | F::Json5);
    let kind = match style {
        EmbedStyle::Separate => return Some(MetaCarrier::WholeFile(format)),
        EmbedStyle::Delimited => match format {
            F::Yaml => E::FrontmatterYaml,
            F::Toml => E::PlusToml,
            _ if is_json => E::FrontmatterJson,
            _ => return None,
        },
        EmbedStyle::CodeBlock => match format {
            F::Yaml => E::FencedYaml,
            F::Toml => E::FencedToml,
            F::Fig => E::FrontmatterFig,
            _ if is_json => E::FencedJson,
            _ => return None,
        },
        EmbedStyle::HtmlScript => match format {
            F::Yaml => E::HtmlScriptYaml,
            F::Toml => E::HtmlScriptToml,
            F::Fig => E::HtmlScriptFig,
            _ if is_json => E::HtmlScriptJson,
            _ => return None,
        },
        EmbedStyle::HtmlCode => match format {
            F::Yaml => E::HtmlCodeYaml,
            F::Toml => E::HtmlCodeToml,
            F::Fig => E::HtmlCodeFig,
            _ if is_json => E::HtmlCodeJson,
            _ => return None,
        },
    };
    Some(MetaCarrier::Fenced(kind))
}

/// A parsed document: its path, its embedded metadata, and its body text.
///
/// Metadata is stored as a dynamic [`Value`] (a mapping, or [`Value::Null`] when
/// the document has no frontmatter) because link fields are configurable and
/// therefore accessed dynamically.
#[derive(Debug, Clone)]
pub struct Document {
    /// Path this document was read from (workspace-relative or absolute — the
    /// caller decides; prov does not interpret it here).
    pub path: PathBuf,
    /// Parsed embedded metadata.
    pub meta: Value,
    /// Everything outside the metadata block (the host prose). Empty for a
    /// config document.
    pub body: String,
    /// Where the metadata was found, or `None` when the document has no
    /// (well-formed) metadata. Preserved on write.
    pub carrier: Option<MetaCarrier>,
}

impl Document {
    /// Parse a document from its full text.
    ///
    /// If `path` has a config extension (`.yaml`, `.yml`, `.json`, `.fig`,
    /// `.figl`), the entire text is the metadata and the body is empty.
    /// Otherwise the embedded metadata block is auto-detected via
    /// `fig::detect` — any archetype fig knows (`---` YAML, `;;;` JSON,
    /// ```` ```fig ````, ```` ```endmatter ````) — and parsed in that
    /// archetype's inner format. If there is no (well-formed) block, `meta`
    /// is [`Value::Null`] and the whole text is the body. An unterminated
    /// opening fence is treated as no metadata — we do not guess where it
    /// ends.
    pub fn parse(path: impl Into<PathBuf>, text: &str) -> Result<Self> {
        let path = path.into();
        if let Some(format) = whole_file_format(&path) {
            let meta = meta::parse_value(text, format)?;
            return Ok(Self {
                path,
                meta,
                body: String::new(),
                carrier: Some(MetaCarrier::WholeFile(format)),
            });
        }
        let (meta, body, carrier) = match fig::detect(text) {
            Some(kind) => match fig::Embed::extract(text, kind) {
                Ok(found) => (
                    meta::parse_value(found.content(), kind.inner_format())?,
                    // *Both* host sides, in file order. A block at an edge leaves
                    // one of them empty, which is every markdown document; a
                    // mid-document block — an HTML `<script>` island below a
                    // `<head>` — leaves text on both, and taking fig's one-sided
                    // `body()` view there silently drops everything above the
                    // island. What that cost: a body write losing the `<head>`,
                    // and `content_hash` covering a suffix while reporting that
                    // it covered the document (fig 3.3 exposes both sides).
                    [found.host_before(), found.host_after()].concat(),
                    Some(MetaCarrier::Fenced(kind)),
                ),
                // Detected by its open delimiter but with no matching close:
                // recognized-but-malformed degrades to "no metadata".
                Err(_) => (Value::Null, text.to_owned(), None),
            },
            None => (Value::Null, text.to_owned(), None),
        };
        Ok(Self {
            path,
            meta,
            body,
            carrier,
        })
    }

    /// Zero-copy counterpart to [`parse`](Self::parse): locate a fenced
    /// metadata block in `text` without parsing it, returning the
    /// [`MetaCarrier`] found and the three slices it borrows from `text` —
    /// `(meta_block, body_before, body_after)`. Mirrors
    /// `fig::detect`/`fig::Embed::extract` composed into one step, the same
    /// primitives `parse` builds its owned, parsed [`Value`] from.
    ///
    /// The body comes back in **two** pieces because a block need not sit at an
    /// edge. Frontmatter leaves `body_before` empty and endmatter leaves
    /// `body_after` empty, but an HTML `<script>` data island below a `<head>`
    /// has host text on both sides, and a single slice cannot name both — the
    /// one-sided view this used to return dropped whichever side it could not
    /// see. Concatenated in order they are [`Document::body`]; a caller
    /// splicing text back together wants them separate, since only their
    /// offsets say where the block sat.
    ///
    /// Only recognizes a *fenced* carrier — a whole-file (config) document has
    /// no split to offer, since its entire text already is the metadata; a
    /// caller steering by path extension (as `parse` does via
    /// [`whole_file_format`]) should check that first. Returns `None` when
    /// `text` opens no known archetype, or its opening fence has no matching
    /// close (an unterminated fence degrades to "no metadata", matching
    /// `parse`).
    ///
    /// The caller who wants the parsed [`Value`] should use [`parse`](Self::parse)
    /// instead; this exists for one who wants to defer parsing to their own
    /// deserializer, or just needs the raw borrowed text (e.g. to detect which
    /// archetype a document uses without allocating).
    pub fn split(text: &str) -> Option<(MetaCarrier, &str, &str, &str)> {
        let kind = fig::detect(text)?;
        let found = fig::Embed::extract(text, kind).ok()?;
        Some((
            MetaCarrier::Fenced(kind),
            found.content(),
            found.host_before(),
            found.host_after(),
        ))
    }

    /// The document's path.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// `true` if the document declares any embedded metadata mapping.
    pub fn has_meta(&self) -> bool {
        self.meta.as_mapping().is_some()
    }

    /// The raw `content` attribute — the relative path to a *separated*
    /// document's body file — or `None` for an ordinary (combined) document
    /// whose body is [`self.body`](Document::body). A separated document is a
    /// whole-file metadata document (`.yaml`/`.json`/`.figl`) that points at its
    /// prose body in a sibling file, keeping both halves plain text and linked.
    pub fn content_attr(&self) -> Option<&str> {
        self.meta.get("content").and_then(Value::as_str)
    }

    /// The raw `manifest` attribute — the relative path to the manifest
    /// document listing the files this node stands for — or `None` for a node
    /// that stands for itself.
    ///
    /// The bulk counterpart of [`content_attr`](Document::content_attr) and
    /// **mutually exclusive** with it: a node covers one payload or a set of
    /// them, never both. See [`manifest`](crate::manifest) for the record shape.
    pub fn manifest_attr(&self) -> Option<&str> {
        self.meta
            .get(crate::manifest::MANIFEST_KEY)
            .and_then(Value::as_str)
    }

    /// `true` when this document is a **manifest node**: it declares a
    /// `manifest` pointer, so the files it stands for are listed there rather
    /// than being a single `content` payload.
    pub fn is_manifest_node(&self) -> bool {
        self.manifest_attr().is_some()
    }

    /// `true` when this document declares *both* `content` and `manifest` —
    /// a node claiming to be a single payload's sidecar and a whole
    /// directory's at once. Neither reading is safe to pick, so the pair is
    /// reported rather than resolved.
    pub fn manifest_conflicts(&self) -> bool {
        self.content_attr().is_some() && self.manifest_attr().is_some()
    }

    /// The path of this document's separated body file — its `content` target
    /// joined onto its own directory — or `None` for a combined document, whose
    /// prose is [`self.body`](Document::body).
    ///
    /// Plain path joining, deliberately: `content` names a file *beside* the
    /// node (§5's placement rule), so this is the one link-ish value with no
    /// root-absolute spelling to honour, and staying free of the workspace-root
    /// coordinate is what lets a caller holding a real filesystem path — the
    /// CLI reading a file it was handed — resolve it the same way a caller
    /// holding a workspace-relative one does. Matches the resolution
    /// `attach`'s reverse lookup and the mutation verbs already make.
    pub fn content_path(&self, doc_path: &Path) -> Option<PathBuf> {
        let dir = doc_path.parent().unwrap_or(Path::new(""));
        Some(crate::link::normalize(dir.join(self.content_attr()?)))
    }

    /// The path of the file that actually holds this document's prose: its
    /// [`content_path`](Document::content_path) when separated, and `doc_path`
    /// itself when combined.
    ///
    /// This is the path whose extension declares the body's grammar
    /// ([`ContentFormat::from_extension`](crate::content::ContentFormat::from_extension)).
    /// Reading that off a separated document's *own* path asks a `.yaml` node
    /// what grammar its prose is in, and the honest answer — "none, a config
    /// file has no body" — is the wrong question rather than a wrong answer.
    pub fn body_path(&self, doc_path: &Path) -> PathBuf {
        self.content_path(doc_path)
            .unwrap_or_else(|| doc_path.to_path_buf())
    }

    /// `true` when this document is an **attachment sidecar**: a whole-file
    /// metadata document whose `content` points at an [opaque
    /// payload](is_opaque_payload) rather than a prose body. Recognized two ways,
    /// so a hand-written sidecar need not be verbose: an explicit `attachment:
    /// true` flag (what `prov`'s `Workspace::attach` writes),
    /// **or** a `content` target whose extension prov cannot read as text.
    ///
    /// A *separated prose* document (`content` → a `.md`/`.dj`/`.html` body) is
    /// deliberately **not** an attachment: its body is a prov document in its
    /// own right, scanned for links and titles; an attachment's payload is bytes
    /// prov never opens.
    pub fn is_attachment(&self) -> bool {
        match self.content_attr() {
            None => false,
            Some(content) => {
                self.meta.get("attachment").and_then(Value::as_bool) == Some(true)
                    || is_opaque_payload(Path::new(content))
            }
        }
    }
}

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

    #[cfg(feature = "yaml")]
    #[test]
    fn content_path_joins_the_target_onto_the_node_s_own_directory() {
        let doc = Document::parse("notes/a.yaml", "title: A\ncontent: a.md\n").unwrap();
        assert_eq!(
            doc.content_path(Path::new("notes/a.yaml")),
            Some(PathBuf::from("notes/a.md"))
        );
        assert_eq!(
            doc.body_path(Path::new("notes/a.yaml")),
            PathBuf::from("notes/a.md")
        );
    }

    /// The CLI resolves by real filesystem path, so the join must not assume a
    /// workspace-root coordinate.
    #[cfg(feature = "yaml")]
    #[test]
    fn content_path_resolves_an_absolute_node_path_as_absolute() {
        let doc = Document::parse("/vault/notes/a.yaml", "title: A\ncontent: a.md\n").unwrap();
        assert_eq!(
            doc.content_path(Path::new("/vault/notes/a.yaml")),
            Some(PathBuf::from("/vault/notes/a.md"))
        );
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn a_combined_document_has_no_content_path_and_is_its_own_body_path() {
        let doc = Document::parse("notes/a.md", "---\ntitle: A\n---\nprose\n").unwrap();
        assert_eq!(doc.content_path(Path::new("notes/a.md")), None);
        assert_eq!(
            doc.body_path(Path::new("notes/a.md")),
            PathBuf::from("notes/a.md")
        );
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn parses_yaml_frontmatter_and_body() {
        let text = "---\ntitle: Root\ncontents:\n- a.md\n---\n# Body\n\nhello\n";
        let doc = Document::parse("index.md", text).unwrap();
        assert_eq!(doc.meta.get("title").and_then(Value::as_str), Some("Root"));
        assert_eq!(doc.body, "# Body\n\nhello\n");
        assert_eq!(
            doc.carrier,
            Some(MetaCarrier::Fenced(EmbedType::FrontmatterYaml))
        );
        assert!(doc.has_meta());
    }

    #[cfg(feature = "fig-lang")]
    #[test]
    fn parses_fig_fenced_frontmatter() {
        let text = "```fig\ntitle = prov\ncontents = [docs/design.md]\n```\n# Body\n";
        let doc = Document::parse("README.md", text).unwrap();
        assert_eq!(doc.meta.get("title").and_then(Value::as_str), Some("prov"));
        assert_eq!(doc.body, "# Body\n");
        assert_eq!(
            doc.carrier,
            Some(MetaCarrier::Fenced(EmbedType::FrontmatterFig))
        );
        assert!(doc.has_meta());
    }

    #[cfg(feature = "json")]
    #[test]
    fn parses_json_frontmatter() {
        let text = ";;;\n{\"title\": \"Root\"}\n;;;\nbody\n";
        let doc = Document::parse("note.md", text).unwrap();
        assert_eq!(doc.meta.get("title").and_then(Value::as_str), Some("Root"));
        assert_eq!(
            doc.carrier,
            Some(MetaCarrier::Fenced(EmbedType::FrontmatterJson))
        );
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn parses_yaml_endmatter() {
        let text = "# Body first\n```endmatter\ntitle: Tail\n```\n";
        let doc = Document::parse("note.md", text).unwrap();
        assert_eq!(doc.meta.get("title").and_then(Value::as_str), Some("Tail"));
        assert_eq!(doc.body, "# Body first\n");
        assert_eq!(
            doc.carrier,
            Some(MetaCarrier::Fenced(EmbedType::EndmatterYaml))
        );
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn a_config_file_is_a_document_whose_content_is_all_metadata() {
        let text = "title: ID registry\npart_of: index.md\nregistry:\n  abc: a.md\n";
        let doc = Document::parse("registry.yaml", text).unwrap();
        assert_eq!(
            doc.meta.get("title").and_then(Value::as_str),
            Some("ID registry")
        );
        assert_eq!(
            doc.meta.get("part_of").and_then(Value::as_str),
            Some("index.md")
        );
        assert_eq!(doc.body, "");
        assert_eq!(doc.carrier, Some(MetaCarrier::WholeFile(fig::Format::Yaml)));
        assert!(doc.has_meta());
    }

    #[cfg(feature = "fig-lang")]
    #[test]
    fn a_fig_config_file_parses_the_dialect() {
        let text = "title = settings\npart_of = index.md\n";
        let doc = Document::parse("settings.figl", text).unwrap();
        assert_eq!(
            doc.meta.get("title").and_then(Value::as_str),
            Some("settings")
        );
        assert_eq!(doc.carrier, Some(MetaCarrier::WholeFile(fig::Format::Fig)));
    }

    #[test]
    fn embed_style_config_str_round_trips() {
        for style in [
            EmbedStyle::Delimited,
            EmbedStyle::CodeBlock,
            EmbedStyle::HtmlScript,
            EmbedStyle::HtmlCode,
            EmbedStyle::Separate,
        ] {
            assert_eq!(
                EmbedStyle::from_config_str(style.as_config_str()),
                Some(style)
            );
        }
        assert_eq!(EmbedStyle::from_config_str("nonsense"), None);
    }

    #[test]
    fn embed_carrier_resolves_style_and_format_to_a_carrier() {
        use fig::Format;
        let fenced = |k| Some(MetaCarrier::Fenced(k));
        // Delimited: the three delimiter formats, but the fig dialect has none.
        assert_eq!(
            embed_carrier(EmbedStyle::Delimited, Format::Yaml),
            fenced(EmbedType::FrontmatterYaml)
        );
        assert_eq!(
            embed_carrier(EmbedStyle::Delimited, Format::Toml),
            fenced(EmbedType::PlusToml)
        );
        assert_eq!(
            embed_carrier(EmbedStyle::Delimited, Format::Json),
            fenced(EmbedType::FrontmatterJson)
        );
        assert_eq!(embed_carrier(EmbedStyle::Delimited, Format::Fig), None);
        // Code block: fig lands in the ```fig block; the rest in ```lang blocks.
        assert_eq!(
            embed_carrier(EmbedStyle::CodeBlock, Format::Fig),
            fenced(EmbedType::FrontmatterFig)
        );
        assert_eq!(
            embed_carrier(EmbedStyle::CodeBlock, Format::Yaml),
            fenced(EmbedType::FencedYaml)
        );
        // HTML islands, both shapes.
        assert_eq!(
            embed_carrier(EmbedStyle::HtmlScript, Format::Json),
            fenced(EmbedType::HtmlScriptJson)
        );
        assert_eq!(
            embed_carrier(EmbedStyle::HtmlCode, Format::Toml),
            fenced(EmbedType::HtmlCodeToml)
        );
        // Separate is a whole-file sidecar in the chosen format (any format).
        assert_eq!(
            embed_carrier(EmbedStyle::Separate, Format::Yaml),
            Some(MetaCarrier::WholeFile(Format::Yaml))
        );
        assert_eq!(
            embed_carrier(EmbedStyle::Separate, Format::Fig),
            Some(MetaCarrier::WholeFile(Format::Fig))
        );
    }

    #[test]
    fn no_frontmatter_is_all_body() {
        let doc = Document::parse("note.md", "# Just a note\n").unwrap();
        assert!(doc.meta.is_null());
        assert_eq!(doc.body, "# Just a note\n");
        assert_eq!(doc.carrier, None);
        assert!(!doc.has_meta());
    }

    #[test]
    fn unterminated_fence_is_not_frontmatter() {
        let text = "---\ntitle: oops\nno closing fence\n";
        let doc = Document::parse("x.md", text).unwrap();
        assert!(doc.meta.is_null());
        assert_eq!(doc.body, text);
        assert_eq!(doc.carrier, None);
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn split_borrows_yaml_frontmatter_and_body_without_parsing() {
        let text = "---\ntitle: Root\n---\n# Body\n\nhello\n";
        let (carrier, meta, before, after) = Document::split(text).unwrap();
        assert_eq!(carrier, MetaCarrier::Fenced(EmbedType::FrontmatterYaml));
        assert_eq!(meta, "title: Root\n");
        assert_eq!(before, "", "frontmatter has no host text above it");
        assert_eq!(after, "# Body\n\nhello\n");
        let body = after;
        // Byte-identical to what `parse` extracts, just unparsed and borrowed.
        let doc = Document::parse("x.md", text).unwrap();
        assert_eq!(doc.body, body);
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn split_handles_crlf_line_endings() {
        let text = "---\r\ntitle: Root\r\n---\r\nbody\r\n";
        let (carrier, meta, before, after) = Document::split(text).unwrap();
        assert_eq!(carrier, MetaCarrier::Fenced(EmbedType::FrontmatterYaml));
        assert_eq!(meta, "title: Root\r\n");
        assert_eq!(before, "");
        assert_eq!(after, "body\r\n");
    }

    #[test]
    fn split_is_none_with_no_frontmatter() {
        assert_eq!(Document::split("# Just a note\n"), None);
    }

    #[test]
    fn split_is_none_for_an_unterminated_fence() {
        let text = "---\ntitle: oops\nno closing fence\n";
        assert_eq!(Document::split(text), None);
    }

    #[cfg(feature = "fig-lang")]
    #[test]
    fn split_recognizes_a_non_yaml_carrier() {
        let text = "```fig\ntitle = prov\n```\n# Body\n";
        let (carrier, meta, before, after) = Document::split(text).unwrap();
        assert_eq!(carrier, MetaCarrier::Fenced(EmbedType::FrontmatterFig));
        assert_eq!(meta, "title = prov\n");
        assert_eq!(before, "");
        assert_eq!(after, "# Body\n");
    }

    #[cfg(feature = "json")]
    #[test]
    fn split_recognizes_json_frontmatter() {
        let text = ";;;\n{\"title\": \"Root\"}\n;;;\nbody\n";
        let (carrier, meta, before, after) = Document::split(text).unwrap();
        assert_eq!(carrier, MetaCarrier::Fenced(EmbedType::FrontmatterJson));
        assert_eq!(meta, "{\"title\": \"Root\"}\n");
        assert_eq!(before, "");
        assert_eq!(after, "body\n");
    }

    /// A `<script>` island below a `<head>` has host text on *both* sides. fig's
    /// one-sided `body()` view returned only the tail, so the whole document head
    /// vanished from `doc.body` — and from everything reading it: a separated
    /// document's prose file, `prov body`, and the bytes `content_hash` covers.
    #[cfg(feature = "yaml")]
    #[test]
    fn a_mid_document_island_keeps_the_host_text_on_both_sides() {
        let text = concat!(
            "<!doctype html>\n",
            "<html><head><title>KEEP ME</title></head>\n",
            "<body>\n",
            "<script type=\"application/yaml\">\n",
            "title: Mid\n",
            "</script>\n",
            "<p>tail</p>\n",
            "</html>\n",
        );
        let doc = Document::parse("page.html", text).unwrap();
        assert_eq!(doc.meta.get("title").and_then(Value::as_str), Some("Mid"));
        assert!(
            doc.body.contains("KEEP ME"),
            "the head above the island was dropped: {:?}",
            doc.body
        );
        assert!(doc.body.contains("<p>tail</p>"), "the tail was dropped");

        // The two sides, in file order, and nothing of the block itself.
        let (_, meta, before, after) = Document::split(text).unwrap();
        assert_eq!(doc.body, format!("{before}{after}"));
        assert!(
            !doc.body.contains("<script"),
            "the island leaked into the body"
        );
        assert_eq!(meta, "title: Mid\n");
    }

    #[cfg(feature = "yaml")]
    #[test]
    fn crlf_fences_are_handled() {
        let text = "---\r\ntitle: Root\r\n---\r\nbody\r\n";
        let doc = Document::parse("x.md", text).unwrap();
        assert_eq!(
            doc.carrier,
            Some(MetaCarrier::Fenced(EmbedType::FrontmatterYaml))
        );
        assert_eq!(doc.body, "body\r\n");
        // Exact scalar — fig ≥ 2.1.1 treats \r\n as a single line break.
        assert_eq!(doc.meta.get("title").and_then(Value::as_str), Some("Root"));
    }
}