//! 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}; use crate::format::MetaFormat; /// 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 `+++` TOML block is never /// rewritten as `---` YAML; a bare `.yaml` file never grows fences). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MetaCarrier { /// A frontmatter block opening a host file, with the prose body after it: /// `---` YAML, `+++` TOML, or `---` in any of the four formats /// (`---json`, `---figl`, …). twig locates it (`twig::meta`) and keeps its /// fences byte for byte on an edit. Fenced(MetaFormat), /// The entire file is the metadata (a config document); the body is empty. /// The format comes from the file extension. WholeFile(MetaFormat), } impl MetaCarrier { /// The format the metadata is written in. pub fn format(&self) -> MetaFormat { match self { MetaCarrier::Fenced(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: `.yaml`/`.yml`, /// `.json`, `.toml`, and `.figl` (or fig 5's `.fig`). pub fn whole_file_format(path: &Path) -> Option { MetaFormat::from_extension(path.extension()?.to_str()?) } /// 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 { 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`, `toml`, `figl`. pub fn whole_file_extension(format: MetaFormat) -> &'static str { format.extension() } /// The frontmatter carrier for `format` — the block a new document gets when it /// inherits no parent block and the workspace default is `format`. twig writes /// its fences: `---` for YAML, `+++` for TOML, `---json` and `---figl` for the /// others. pub fn frontmatter_carrier(format: MetaFormat) -> MetaCarrier { MetaCarrier::Fenced(format) } /// The *family* a workspace authors embedded metadata in — the "embed type" the /// CLI's `init` prompts for, one level above the [`MetaCarrier`]. A family plus a /// [`MetaFormat`] resolves to a carrier through [`embed_carrier`]: (`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. /// /// Through prov 0.18 there were three more: fenced code blocks (with /// ```` ```endmatter ````), HTML `\n

Body

\n"; let doc = Document::parse("index.html", text).unwrap(); assert_eq!(doc.carrier, Some(MetaCarrier::Fenced(MetaFormat::Yaml))); assert_eq!(doc.meta.get("title").and_then(Value::as_str), Some("Page")); assert_eq!(doc.body, "

Body

\n"); } #[test] fn an_island_in_head_splits_the_page_around_it() { let text = "\n\n\n\n\n"; let (carrier, meta, before, after) = Document::split(text).unwrap(); assert_eq!(carrier, MetaCarrier::Fenced(MetaFormat::Json)); assert_eq!(meta, "{\"title\": \"T\"}\n"); assert_eq!(before, "\n\n"); assert_eq!(after, "\n\n"); } #[test] fn a_page_script_that_is_not_an_island_is_body() { let text = "\n

Body

\n"; assert_eq!(Document::split(text), None); } #[test] fn a_djot_document_reads_its_frontmatter_too() { let text = "---\ntitle: Dj\n---\n_body_\n"; let doc = Document::parse("note.dj", text).unwrap(); assert_eq!(doc.meta.get("title").and_then(Value::as_str), Some("Dj")); assert_eq!(doc.body, "_body_\n"); } #[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(MetaFormat::Yaml))); assert_eq!(doc.body, "body\r\n"); // Exact scalar — fig treats \r\n as a single line break. assert_eq!(doc.meta.get("title").and_then(Value::as_str), Some("Root")); } }