Skip to main content

agent_first_data/document/
file.rs

1//! Format-neutral document editing: an in-memory [`Document`] with
2//! source-preserving edits, and a [`DocumentFile`] that adds the file boundary.
3//!
4//! [`Document`] holds the source text, its parsed [`Value`], and the
5//! [`Format`]. Its verbs — [`set`](Document::set) / [`unset`](Document::unset)
6//! / [`add`](Document::add) / [`remove`](Document::remove) — edit the source in
7//! place (comments, ordering, and untouched formatting survive) and update the
8//! parsed value alongside; [`source`](Document::source) reads the result and
9//! [`encode`](Document::encode) re-renders a fresh, non-preserving copy from the
10//! value. No file, no I/O, no guards — just editing.
11//!
12//! [`DocumentFile`] is a [`Document`] plus a path, reachable through
13//! [`Deref`](std::ops::Deref): read and edit exactly as above, then commit with
14//! [`save`](DocumentFile::save) or the [`edit`](DocumentFile::edit) closure.
15//! Every write refuses a symlink/hardlinked target and goes to a
16//! same-directory temp file that is fsynced, has the original permissions
17//! re-applied, and is atomically renamed over the target — so a crash mid-write
18//! never leaves a partial file.
19//!
20//! This module never redacts values — it reads and writes raw values as-is;
21//! redaction is the caller's responsibility.
22
23mod read;
24mod write;
25
26use write::{guard_mutation, write_atomic, write_atomic_create};
27
28#[cfg(feature = "cli")]
29use read::read_capped_source;
30#[cfg(all(test, unix))]
31use read::{inspect_capped_source, read_capped_contents};
32use read::{open_read_handle, read_capped_source_bytes};
33use std::fs;
34#[cfg(all(test, unix))]
35use std::fs::OpenOptions;
36use std::path::{Path, PathBuf};
37
38use crate::document::{Addressing, DocumentError, DocumentResult, Format, KeyedList, Value};
39
40#[cfg(feature = "cli")]
41pub(crate) fn read_capped_file(
42    path: &Path,
43    max_bytes: u64,
44    symlink_policy: SymlinkPolicy,
45) -> DocumentResult<String> {
46    let file = open_read_handle(path, symlink_policy)?;
47    read_capped_source(file, path, max_bytes)
48}
49
50/// Whether a capped file read may follow a symbolic link.
51///
52/// [`NoFollow`](SymlinkPolicy::NoFollow) is implemented with the operating
53/// system's atomic `O_NOFOLLOW` open on unix when Cargo feature `libc` is
54/// enabled. Windows opens the final component itself and rejects reparse points
55/// by inspecting that handle. Other platforms and unix builds without the feature return
56/// [`DocumentError::UnsupportedOperation`] rather than pretending a
57/// check-before-open sequence provides the same guarantee.
58#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
59pub enum SymlinkPolicy {
60    /// Follow a symbolic link in the same way as [`std::fs::File::open`].
61    #[default]
62    Follow,
63    /// Refuse a symbolic-link final path component atomically.
64    ///
65    /// This requires Cargo feature `libc` on unix.
66    NoFollow,
67}
68
69/// Whether [`DocumentFile::create_atomic`] may replace an existing target.
70#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
71pub enum CreateMode {
72    /// Fail with `document_target_exists` if the target already exists.
73    #[default]
74    NewOnly,
75    /// Atomically replace an existing target, or create it when absent.
76    Replace,
77}
78
79/// Options for a safe first commit with [`DocumentFile::create_atomic`].
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct CreateOptions {
82    mode: CreateMode,
83    unix_mode: Option<u32>,
84}
85
86impl CreateOptions {
87    /// Create with no-clobber semantics and unix mode `0o600` for a new file.
88    ///
89    /// Replacing an existing target preserves that target's mode unless
90    /// [`unix_mode`](Self::unix_mode) asks for a specific one.
91    #[must_use]
92    pub const fn new() -> Self {
93        Self {
94            mode: CreateMode::NewOnly,
95            unix_mode: None,
96        }
97    }
98
99    /// Set the target's unix permission bits.
100    ///
101    /// The value must contain only the low `0o777` permission bits. It is
102    /// ignored on non-unix platforms. Setting it explicitly also applies the
103    /// mode when replacing an existing file, which otherwise keeps its own.
104    #[must_use]
105    pub const fn unix_mode(mut self, unix_mode: u32) -> Self {
106        self.unix_mode = Some(unix_mode);
107        self
108    }
109
110    /// Explicitly allow an existing target to be atomically replaced.
111    #[must_use]
112    pub const fn replace(mut self) -> Self {
113        self.mode = CreateMode::Replace;
114        self
115    }
116
117    /// The configured target-existence behavior.
118    #[must_use]
119    pub const fn mode(&self) -> CreateMode {
120        self.mode
121    }
122
123    /// The explicitly configured unix permission bits, if any.
124    ///
125    /// `None` means "`0o600` when creating, and keep the existing mode when
126    /// replacing".
127    #[must_use]
128    pub const fn configured_unix_mode(&self) -> Option<u32> {
129        self.unix_mode
130    }
131
132    /// The mode to apply, given whether the target already exists.
133    const fn effective_unix_mode(&self, target_exists: bool) -> Option<u32> {
134        match self.unix_mode {
135            Some(mode) => Some(mode),
136            // Replacing must not silently re-permission a file the caller did
137            // not ask about: `save()` preserves the original, and a second
138            // write path with the opposite rule would quietly widen a 0600
139            // secrets file to the create default, or narrow a shared one.
140            None if target_exists => None,
141            None => Some(0o600),
142        }
143    }
144}
145
146impl Default for CreateOptions {
147    fn default() -> Self {
148        Self::new()
149    }
150}
151
152/// A format-neutral in-memory document: the original source text, its parsed
153/// [`Value`], and the [`Format`] both came from. Has no file coupling —
154/// construct it from a string or any [`std::io::Read`] the caller supplies,
155/// edit it source-preservingly with [`set`](Document::set) /
156/// [`unset`](Document::unset) / [`add`](Document::add) /
157/// [`remove`](Document::remove), and read the result back with
158/// [`source`](Document::source). [`DocumentFile`] is just this plus a path.
159#[derive(Debug, Clone)]
160pub struct Document {
161    source: String,
162    value: Value,
163    format: Format,
164}
165
166impl Document {
167    /// Parse `source` in the given `format`.
168    ///
169    /// Named `parse` (not `from_str`) deliberately: this takes an explicit
170    /// `format` argument, so it is not the single-argument `std::str::FromStr`
171    /// contract that `from_str` would imply.
172    pub fn parse(source: &str, format: Format) -> DocumentResult<Document> {
173        let value = format.load(source)?;
174        Ok(Document {
175            source: source.to_string(),
176            value,
177            format,
178        })
179    }
180
181    /// Read `reader` fully to a `String`, then parse it in the given
182    /// `format`.
183    ///
184    /// Reads only from the supplied `reader` — never touches the process's
185    /// own stdin.
186    pub fn from_reader<R: std::io::Read>(
187        mut reader: R,
188        format: Format,
189    ) -> DocumentResult<Document> {
190        let mut bytes = Vec::new();
191        reader.read_to_end(&mut bytes)?;
192        if let Some(document) = Document::parse_binary(&bytes, format)? {
193            return Ok(document);
194        }
195        let source = String::from_utf8(bytes)
196            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
197        Document::parse_labelled(&source, format, "input")
198    }
199
200    /// Parse `source`; when it is zero bytes and the format rejects it, say so
201    /// as `EmptyInput` naming `label` instead of a parser position.
202    /// JSON that fails to parse but opens like an XML property list names
203    /// `--input-format plist` instead of a parser position.
204    fn parse_labelled(source: &str, format: Format, label: &str) -> DocumentResult<Document> {
205        match Document::parse(source, format) {
206            Err(DocumentError::ParseError { .. }) if source.is_empty() => {
207                Err(DocumentError::EmptyInput {
208                    source: label.to_string(),
209                })
210            }
211            #[cfg(feature = "plist")]
212            Err(DocumentError::ParseError { .. })
213                if format == Format::Json
214                    && crate::document::format::plist::looks_like_xml(source.as_bytes()) =>
215            {
216                Err(crate::document::format::plist::wrong_format_xml(
217                    format.name(),
218                ))
219            }
220            other => other,
221        }
222    }
223
224    /// Parse raw bytes: a binary property list is decoded without UTF-8
225    /// handling, everything else is decoded as UTF-8 text first.
226    fn from_bytes(bytes: Vec<u8>, format: Format, label: &str) -> DocumentResult<Document> {
227        if let Some(document) = Document::parse_binary(&bytes, format)? {
228            return Ok(document);
229        }
230        let source = String::from_utf8(bytes).map_err(|error| DocumentError::IoError {
231            detail: format!(
232                "read `{label}`: document is not UTF-8 (valid through byte {})",
233                error.utf8_error().valid_up_to()
234            ),
235        })?;
236        Document::parse_labelled(&source, format, label)
237    }
238
239    /// Recognise a binary property list from its magic. `Some` carries the
240    /// parsed document, whose `source` is empty because plist is read-only and
241    /// nothing reads the source of a read-only format; a binary plist read as
242    /// any other format is a parse failure naming `--input-format plist`.
243    #[cfg(feature = "plist")]
244    fn parse_binary(bytes: &[u8], format: Format) -> DocumentResult<Option<Document>> {
245        use crate::document::format::plist;
246        if !plist::is_binary(bytes) {
247            return Ok(None);
248        }
249        if format != Format::Plist {
250            return Err(plist::wrong_format(format.name()));
251        }
252        Ok(Some(Document {
253            source: String::new(),
254            value: plist::load_binary(bytes)?,
255            format,
256        }))
257    }
258
259    #[cfg(not(feature = "plist"))]
260    #[allow(clippy::unnecessary_wraps)]
261    fn parse_binary(_bytes: &[u8], _format: Format) -> DocumentResult<Option<Document>> {
262        Ok(None)
263    }
264
265    /// Borrow the parsed value (reflects the last successful edit).
266    pub fn value(&self) -> &Value {
267        &self.value
268    }
269
270    /// Borrow the current source text — the original bytes with every
271    /// source-preserving edit applied. This is what [`DocumentFile::save`]
272    /// writes.
273    pub fn source(&self) -> &str {
274        &self.source
275    }
276
277    /// The format this document was parsed from.
278    pub fn format(&self) -> Format {
279        self.format
280    }
281
282    /// How a non-numeric path segment resolves against an array in this
283    /// document: whatever its format declares (see [`Format::array_rule`]),
284    /// with no caller-declared keyed lists.
285    ///
286    /// Use [`addressing_keyed`](Document::addressing_keyed) to add those.
287    #[must_use]
288    pub fn addressing(&self) -> Addressing<'static> {
289        Addressing::INDEX_ONLY.with_array_rule(self.format.array_rule())
290    }
291
292    /// [`addressing`](Document::addressing) plus the caller's keyed lists,
293    /// which take precedence over the format rule for the arrays they name.
294    #[must_use]
295    pub fn addressing_keyed<'a>(&self, keyed_lists: &'a [KeyedList<'a>]) -> Addressing<'a> {
296        Addressing::keyed(keyed_lists).with_array_rule(self.format.array_rule())
297    }
298
299    /// Resolve a dotted `path` against the parsed document and return the value
300    /// at that address.
301    ///
302    /// A non-empty ASCII-decimal segment against an array is an index;
303    /// anything else goes through the format's own rule, so a Markdown document answers
304    /// `h2.look` while a JSON one refuses `deps.foo`. See
305    /// [`addressing`](Document::addressing).
306    pub fn value_at(&self, path: &str) -> DocumentResult<Value> {
307        crate::document::get_path(&self.value, path, self.addressing())
308    }
309
310    /// [`value_at`](Document::value_at) that also returns the structural route
311    /// to the value, for showing it with
312    /// [`Redactor::value_at`](crate::Redactor::value_at). With keyed lists, call
313    /// [`locate`](crate::document::locate) with
314    /// [`addressing_keyed`](Document::addressing_keyed).
315    pub fn locate(&self, path: &str) -> DocumentResult<crate::document::Located<'_>> {
316        crate::document::locate(&self.value, path, self.addressing())
317    }
318
319    /// [`value_at`](Document::value_at) that also asserts the value at `path`
320    /// satisfies `expected`, returning a [`DocumentError::TypeMismatch`]
321    /// otherwise.
322    pub fn value_at_typed(
323        &self,
324        path: &str,
325        expected: crate::document::ValueType,
326    ) -> DocumentResult<Value> {
327        let value = self.value_at(path)?;
328        if crate::document::value_matches_type(&value, expected) {
329            Ok(value)
330        } else {
331            Err(DocumentError::TypeMismatch {
332                path: path.to_string(),
333                expected: expected.name().to_string(),
334                got: value.kind_name().to_string(),
335                hint: None,
336            })
337        }
338    }
339
340    /// Deserialize the complete document into a typed serde model.
341    ///
342    /// This is the convenience form of
343    /// [`crate::document::from_value(self.value(), "")`](crate::document::from_value).
344    /// Type errors are returned as content-redactable [`DocumentError`] values.
345    pub fn decode<T: serde::de::DeserializeOwned>(&self) -> DocumentResult<T> {
346        crate::document::from_value(self.value(), "")
347    }
348
349    /// Build a value from the CLI string `raw` per an explicit
350    /// [`ValueType`](crate::document::ValueType) and [`set`](Document::set) it.
351    pub fn set_typed(
352        &mut self,
353        key: &str,
354        raw: Option<&str>,
355        value_type: crate::document::ValueType,
356    ) -> DocumentResult<()> {
357        let value = crate::document::value_from_type(value_type, raw)?;
358        self.set(key, value)
359    }
360
361    /// Refuse `operation` when this document's format has no writer at all.
362    ///
363    /// A read-only format (see [`Format::is_read_only`]) is refused here, at
364    /// the top of every mutating verb, rather than at the backend dispatch
365    /// below it. The verbs stage an edit against the parsed value first, so a
366    /// later refusal would report whichever backend step happened to notice —
367    /// naming the wrong reason for a document that was never writable.
368    fn ensure_writable(&self, operation: &str) -> DocumentResult<()> {
369        if self.format.is_read_only() {
370            return Err(self.format.read_only_error(operation));
371        }
372        Ok(())
373    }
374
375    /// Re-render the current value in its format via [`Format::save`].
376    ///
377    /// This is a fresh, non-source-preserving render: comments and original
378    /// formatting are not retained. Use [`source`](Document::source) after
379    /// source-preserving edits to keep the original formatting.
380    pub fn encode(&self) -> DocumentResult<String> {
381        self.format.save(&self.value)
382    }
383}
384
385/// A file-backed [`Document`]: the in-memory document plus the path it was
386/// read from.
387///
388/// All reads and source-preserving edits come from [`Document`] through
389/// [`std::ops::Deref`]/[`std::ops::DerefMut`]; `DocumentFile` adds only the file
390/// boundary — reading on [`open`](DocumentFile::open) and an atomic,
391/// symlink-guarded commit on [`save`](DocumentFile::save) /
392/// [`edit`](DocumentFile::edit).
393#[derive(Debug, Clone)]
394pub struct DocumentFile {
395    doc: Document,
396    path: PathBuf,
397}
398
399impl DocumentFile {
400    /// Open and parse `path`.
401    ///
402    /// `format_override` takes precedence; otherwise the format is detected
403    /// from the file extension via [`Format::detect`]. Reading is always
404    /// allowed — this does not run the mutation guard.
405    pub fn open(
406        path: impl AsRef<Path>,
407        format_override: Option<Format>,
408    ) -> DocumentResult<DocumentFile> {
409        let path = path.as_ref().to_path_buf();
410        let format = resolve_format(&path, format_override)?;
411        let bytes = fs::read(&path).map_err(|error| DocumentError::IoError {
412            detail: format!("read `{}`: {error}", path.display()),
413        })?;
414        Ok(DocumentFile {
415            doc: Document::from_bytes(bytes, format, &path.display().to_string())?,
416            path,
417        })
418    }
419
420    /// Open and parse `path` like [`DocumentFile::open`], but reject any
421    /// non-regular file and limit the actual read to `max_bytes + 1`.
422    ///
423    /// Use this over [`open`](DocumentFile::open) when reading untrusted or
424    /// secret-bearing config, where an unbounded read of an arbitrary path is
425    /// a denial-of-service risk. The file is opened exactly once; both metadata
426    /// and contents come from that same handle, so replacing or growing the
427    /// path cannot bypass the cap.
428    ///
429    /// On unix, Cargo feature `libc` also opens with `O_NONBLOCK`, so a special
430    /// file such as a FIFO cannot block before metadata rejects it. Without
431    /// that feature, the single-handle and byte-cap guarantees still hold, but
432    /// opening a special file can block before its type is inspected.
433    pub fn open_capped(
434        path: impl AsRef<Path>,
435        format_override: Option<Format>,
436        max_bytes: u64,
437    ) -> DocumentResult<DocumentFile> {
438        Self::open_capped_with_policy(path, format_override, max_bytes, SymlinkPolicy::Follow)
439    }
440
441    /// [`open_capped`](DocumentFile::open_capped) with an explicit symbolic-link
442    /// policy.
443    ///
444    /// [`SymlinkPolicy::NoFollow`] requires Cargo feature `libc` on unix and is
445    /// also supported on Windows.
446    pub fn open_capped_with_policy(
447        path: impl AsRef<Path>,
448        format_override: Option<Format>,
449        max_bytes: u64,
450        symlink_policy: SymlinkPolicy,
451    ) -> DocumentResult<DocumentFile> {
452        let path = path.as_ref().to_path_buf();
453        let format = resolve_format(&path, format_override)?;
454        let file = open_read_handle(&path, symlink_policy)?;
455        let bytes = read_capped_source_bytes(file, &path, max_bytes)?;
456        Ok(DocumentFile {
457            doc: Document::from_bytes(bytes, format, &path.display().to_string())?,
458            path,
459        })
460    }
461
462    /// Safely create and commit a new file-backed document.
463    ///
464    /// The document must already have passed a supported parser through
465    /// [`Document::parse`]. Its source is parsed once more before any write,
466    /// then written to a private same-directory temporary file, fsynced, and
467    /// atomically installed. The default [`CreateOptions`] never replaces an
468    /// existing path; replacement must be explicitly requested.
469    ///
470    /// The document's format must match what the path resolves to, so a commit
471    /// cannot produce a file [`open`](DocumentFile::open) would then reject.
472    pub fn create_atomic(
473        path: impl AsRef<Path>,
474        document: Document,
475        options: CreateOptions,
476    ) -> DocumentResult<DocumentFile> {
477        let path = path.as_ref().to_path_buf();
478        document.ensure_writable("create")?;
479        // Resolving the path's own format is what `open` does; disagreeing here
480        // would install a document that only this call can read back.
481        let path_format = resolve_format(&path, None)?;
482        if path_format != document.format() {
483            return Err(DocumentError::UnsupportedOperation {
484                format: document.format().name().to_string(),
485                operation: "create".to_string(),
486                detail: format!(
487                    "path resolves to {}, so the created file could not be reopened",
488                    path_format.name()
489                ),
490            });
491        }
492        validate_source_for_write(&document)?;
493        validate_create_options(options)?;
494        write_atomic_create(&path, document.source().as_bytes(), options)?;
495        Ok(DocumentFile {
496            doc: document,
497            path,
498        })
499    }
500
501    /// The file path this document was opened from.
502    pub fn path(&self) -> &Path {
503        &self.path
504    }
505
506    /// Preflight-check that this document format is writable and this file is
507    /// safe to mutate — not a symlink, and on unix not hardlinked — without
508    /// performing any write.
509    ///
510    /// [`save`](DocumentFile::save) runs this same guard before it writes, so
511    /// calling it directly is only useful to front-run a *separate* side effect
512    /// with the same guarantee — e.g. a CLI reading a secret from stdin for a
513    /// `set` should refuse an unsafe target before consuming that input.
514    pub fn ensure_mutable(&self, operation: &str) -> DocumentResult<()> {
515        self.doc.ensure_writable(operation)?;
516        guard_mutation(&self.path, operation)?;
517        Ok(())
518    }
519}
520
521impl Document {
522    /// Set `key` to the typed `value`, preserving the rest of the source
523    /// document. The edit is staged in memory — call
524    /// [`save`](DocumentFile::save) to persist it.
525    ///
526    /// Backend capability mirrors [`crate::document::set_path`] where the
527    /// source editor allows it: the JSON backend replaces an existing value
528    /// (scalar or collection) and creates missing intermediate parent objects;
529    /// YAML replaces collection blocks while preserving bytes outside the
530    /// replaced block; TOML updates arrays, inline tables, and ordinary tables
531    /// in place. Arrays of tables are refused because this editor has no
532    /// explicit element-identity policy. Backends return
533    /// [`DocumentError::UnsupportedOperation`] when an edit cannot be expressed
534    /// source-preservingly.
535    pub fn set(&mut self, key: &str, value: Value) -> DocumentResult<()> {
536        let addressing = self.addressing();
537        self.set_addressed(key, value, addressing)
538    }
539
540    /// [`set`](Document::set) with the caller's own addressing, so a path that
541    /// names an array element by its content — `identities.me.email` — can be
542    /// written and not merely read.
543    ///
544    /// The address is canonicalized to indices first (see
545    /// [`crate::document::resolve_path`]); everything below this point, the
546    /// source-preserving backends included, sees only `identities.0.email`.
547    pub fn set_addressed(
548        &mut self,
549        key: &str,
550        value: Value,
551        addressing: Addressing<'_>,
552    ) -> DocumentResult<()> {
553        self.ensure_writable("set")?;
554        let base = self.set_base();
555        let key = &crate::document::resolve_path(&base, key, addressing)?;
556        let mut new_doc = base;
557        crate::document::set_path(&mut new_doc, key, &value, Addressing::INDEX_ONLY)?;
558        let target = value;
559        #[allow(unreachable_patterns)]
560        let output = match self.format {
561            #[cfg(feature = "toml")]
562            Format::Toml => {
563                crate::document::format::toml::set_preserving(&self.source, key, &target)?
564            }
565            #[cfg(feature = "yaml")]
566            Format::Yaml => {
567                crate::document::format::yaml::set_preserving(&self.source, key, &target)?
568            }
569            Format::Json => {
570                crate::document::format::json::set_preserving(&self.source, key, &target)?
571            }
572            #[cfg(feature = "dotenv")]
573            Format::Dotenv => {
574                crate::document::format::dotenv::set_preserving(&self.source, key, &target)?
575            }
576            #[cfg(feature = "ini")]
577            Format::Ini => {
578                crate::document::format::ini::set_preserving(&self.source, key, &target)?
579            }
580            #[cfg(feature = "toml")]
581            Format::TomlFrontmatter => {
582                let parts = crate::document::format::frontmatter::split(
583                    &self.source,
584                    crate::document::format::frontmatter::Delimiter::Plus,
585                )?;
586                let new_fm =
587                    crate::document::format::toml::set_preserving(parts.frontmatter, key, &target)?;
588                format!("{}{}{}", parts.pre, new_fm, parts.post)
589            }
590            #[cfg(feature = "yaml")]
591            Format::YamlFrontmatter => {
592                let parts = crate::document::format::frontmatter::split(
593                    &self.source,
594                    crate::document::format::frontmatter::Delimiter::Dash,
595                )?;
596                let new_fm =
597                    crate::document::format::yaml::set_preserving(parts.frontmatter, key, &target)?;
598                format!("{}{}{}", parts.pre, new_fm, parts.post)
599            }
600            _ => self.format.save(&new_doc)?,
601        };
602        self.source = output;
603        self.value = new_doc;
604        Ok(())
605    }
606
607    /// The value a `set` edits. A YAML document with no node in it reads as
608    /// null, and a `set` starts its mapping — as an empty TOML, dotenv, or INI
609    /// file already does.
610    fn set_base(&self) -> Value {
611        #[cfg(feature = "yaml")]
612        if self.value.is_null() && self.blank_yaml_document() {
613            return Value::Object(Default::default());
614        }
615        self.value.clone()
616    }
617
618    /// Whether this is YAML (or YAML frontmatter) holding no node at all.
619    #[cfg(feature = "yaml")]
620    fn blank_yaml_document(&self) -> bool {
621        match self.format {
622            Format::Yaml => crate::document::format::yaml::is_blank_document(&self.source),
623            Format::YamlFrontmatter => crate::document::format::frontmatter::split(
624                &self.source,
625                crate::document::format::frontmatter::Delimiter::Dash,
626            )
627            .is_ok_and(|parts| crate::document::format::yaml::is_blank_document(parts.frontmatter)),
628            _ => false,
629        }
630    }
631
632    /// Add a new element to the keyed list at `key`, identified by
633    /// `slug`/`slug_field`, with the given `fields`. Preserves the rest of
634    /// the source document. An empty `key` targets the document root when the
635    /// root is itself the keyed array.
636    ///
637    /// Only JSON and YAML backends implement a source-preserving
638    /// keyed-collection editor today; other formats return
639    /// [`DocumentError::UnsupportedOperation`].
640    pub fn add(
641        &mut self,
642        key: &str,
643        slug: &str,
644        slug_field: &str,
645        fields: &[(String, Value)],
646    ) -> DocumentResult<()> {
647        self.ensure_writable("add")?;
648        let mut value = self.value.clone();
649        let keyed_lists = [KeyedList {
650            prefix: key,
651            slug_field,
652        }];
653        crate::document::add_keyed(&mut value, key, slug, &keyed_lists, None, fields)?;
654        let array = if key.is_empty() {
655            &value
656        } else {
657            crate::document::get_path_ref(&value, key, self.addressing_keyed(&keyed_lists))?
658        };
659        let item = array
660            .as_array()
661            .and_then(|items| items.last())
662            .ok_or_else(|| DocumentError::UnsupportedOperation {
663                format: self.format.name().to_string(),
664                operation: "add".to_string(),
665                detail: "keyed list did not produce an array item".to_string(),
666            })?;
667        // The catch-all covers the formats with no source-preserving keyed
668        // editor. A build with only JSON has none left to catch, which makes it
669        // unreachable there and reachable everywhere else — the arm stays.
670        #[allow(unreachable_patterns)]
671        let output: String = match self.format {
672            Format::Json => crate::document::format::json::append_array_item_preserving(
673                &self.source,
674                key,
675                item,
676            )?,
677            #[cfg(feature = "yaml")]
678            Format::Yaml => crate::document::format::yaml::append_array_item_preserving(
679                &self.source,
680                key,
681                item,
682            )?,
683            // Same editor as `set` reaches through frontmatter: the delimited
684            // block is an ordinary YAML document, and the body is spliced back
685            // untouched. Without this arm a keyed list was editable in a `.yaml`
686            // file and refused in the frontmatter of a `.md` one.
687            #[cfg(feature = "yaml")]
688            Format::YamlFrontmatter => {
689                let parts = crate::document::format::frontmatter::split(
690                    &self.source,
691                    crate::document::format::frontmatter::Delimiter::Dash,
692                )?;
693                let new_fm = crate::document::format::yaml::append_array_item_preserving(
694                    parts.frontmatter,
695                    key,
696                    item,
697                )?;
698                format!("{}{}{}", parts.pre, new_fm, parts.post)
699            }
700            _ => {
701                return Err(DocumentError::UnsupportedOperation {
702                    format: self.format.name().to_string(),
703                    operation: "add".to_string(),
704                    detail: "keyed collection source editor is not implemented for this backend"
705                        .to_string(),
706                });
707            }
708        };
709        self.source = output;
710        self.value = value;
711        Ok(())
712    }
713
714    /// Remove the element identified by `slug`/`slug_field` from the keyed
715    /// list at `key`. Preserves the rest of the source document. An empty
716    /// `key` targets the document root when the root is itself the keyed array.
717    ///
718    /// Only JSON and YAML backends implement a source-preserving
719    /// keyed-collection editor today; other formats return
720    /// [`DocumentError::UnsupportedOperation`].
721    pub fn remove(&mut self, key: &str, slug: &str, slug_field: &str) -> DocumentResult<()> {
722        self.ensure_writable("remove")?;
723        let mut value = self.value.clone();
724        let keyed_lists = [KeyedList {
725            prefix: key,
726            slug_field,
727        }];
728        let removed_index = crate::document::remove_keyed(&mut value, key, slug, &keyed_lists)?;
729        // The catch-all covers the formats with no source-preserving keyed
730        // editor. A build with only JSON has none left to catch, which makes it
731        // unreachable there and reachable everywhere else — the arm stays.
732        #[allow(unreachable_patterns)]
733        let output: String = match self.format {
734            Format::Json => crate::document::format::json::remove_array_item_preserving(
735                &self.source,
736                key,
737                removed_index,
738            )?,
739            #[cfg(feature = "yaml")]
740            Format::Yaml => crate::document::format::yaml::remove_array_item_preserving(
741                &self.source,
742                key,
743                removed_index,
744            )?,
745            #[cfg(feature = "yaml")]
746            Format::YamlFrontmatter => {
747                let parts = crate::document::format::frontmatter::split(
748                    &self.source,
749                    crate::document::format::frontmatter::Delimiter::Dash,
750                )?;
751                let new_fm = crate::document::format::yaml::remove_array_item_preserving(
752                    parts.frontmatter,
753                    key,
754                    removed_index,
755                )?;
756                format!("{}{}{}", parts.pre, new_fm, parts.post)
757            }
758            _ => {
759                return Err(DocumentError::UnsupportedOperation {
760                    format: self.format.name().to_string(),
761                    operation: "remove".to_string(),
762                    detail: "keyed collection source editor is not implemented for this backend"
763                        .to_string(),
764                });
765            }
766        };
767        self.source = output;
768        self.value = value;
769        Ok(())
770    }
771
772    /// Remove the entry at `key` entirely, preserving the rest of the source
773    /// document. The edit is staged in memory — call
774    /// [`DocumentFile::save`] to persist it.
775    ///
776    /// Idempotent, like [`HashSet::remove`](std::collections::HashSet::remove):
777    /// returns `Ok(false)` when there was nothing at `key` to remove (nothing
778    /// is staged), and `Ok(true)` when it was removed.
779    ///
780    /// "Nothing there" does not depend on how deep the path is. A missing leaf
781    /// and a missing ancestor are the same fact — `a.b.c` is absent whether
782    /// `a.b` exists or not — so both answer `Ok(false)`. Only a path that is
783    /// *malformed* stays an error: bad syntax, an index into a non-array, or a
784    /// segment that tries to traverse through a scalar. Those describe a caller
785    /// asking something incoherent, not a document that already lacks the key.
786    ///
787    /// A read-only format is the one case that errors *before* the idempotent
788    /// answer: "nothing to remove" would report success for a document this
789    /// verb can never edit.
790    ///
791    /// A content-addressed segment that matches no element is also an error
792    /// ([`DocumentError::SlugNotFound`]), not `Ok(false)`. It is not the same
793    /// fact as an absent key: the caller named an element and the document has
794    /// none by that name, which is how a mistyped slug looks, and answering
795    /// "removed nothing, all good" would swallow it.
796    pub fn unset(&mut self, key: &str) -> DocumentResult<bool> {
797        let addressing = self.addressing();
798        self.unset_addressed(key, addressing)
799    }
800
801    /// [`unset`](Document::unset) with the caller's own addressing, so an
802    /// element named by its content can be removed and not merely read. See
803    /// [`set_addressed`](Document::set_addressed) for why the address is
804    /// canonicalized before anything below sees it.
805    pub fn unset_addressed(
806        &mut self,
807        key: &str,
808        addressing: Addressing<'_>,
809    ) -> DocumentResult<bool> {
810        self.ensure_writable("unset")?;
811        let key = &crate::document::resolve_path(&self.value, key, addressing)?;
812        let segments = crate::document::parse_path(key)?;
813        let (leaf, parents) = segments.split_last().ok_or(DocumentError::EmptyPath)?;
814        let parent = if parents.is_empty() {
815            &self.value
816        } else {
817            let parent_path = crate::document::join_path(parents);
818            match crate::document::get_path_ref(&self.value, &parent_path, Addressing::INDEX_ONLY) {
819                Ok(parent) => parent,
820                // The ancestor is absent, so the leaf below it is too.
821                Err(DocumentError::UnknownSegment { .. }) => return Ok(false),
822                Err(error) => return Err(error),
823            }
824        };
825        match parent {
826            Value::Object(object) => {
827                if !object.contains_key(leaf) {
828                    return Ok(false);
829                }
830            }
831            Value::Array(_) if leaf == "-" => {
832                return Err(crate::document::append_position_refused(parents, true));
833            }
834            Value::Array(array) => {
835                let index =
836                    leaf.parse::<usize>()
837                        .map_err(|_| DocumentError::UnregisteredArray {
838                            path: crate::document::join_path(parents),
839                        })?;
840                if index >= array.len() {
841                    return Err(DocumentError::IndexOutOfBounds {
842                        path: crate::document::join_path(parents),
843                        index,
844                        len: array.len(),
845                    });
846                }
847            }
848            value => {
849                return Err(DocumentError::NotTraversable {
850                    path: crate::document::join_path(parents),
851                    got: value.kind_name().to_string(),
852                });
853            }
854        }
855        let mut value = self.value.clone();
856        crate::document::unset_path(&mut value, key)?;
857        #[allow(unreachable_patterns)]
858        let output = match self.format {
859            Format::Json => crate::document::format::json::unset_preserving(&self.source, key)?,
860            #[cfg(feature = "toml")]
861            Format::Toml => crate::document::format::toml::unset_preserving(&self.source, key)?,
862            #[cfg(feature = "yaml")]
863            Format::Yaml => crate::document::format::yaml::unset_preserving(&self.source, key)?,
864            #[cfg(feature = "dotenv")]
865            Format::Dotenv => crate::document::format::dotenv::unset_preserving(&self.source, key)?,
866            #[cfg(feature = "ini")]
867            Format::Ini => crate::document::format::ini::unset_preserving(&self.source, key)?,
868            #[cfg(feature = "toml")]
869            Format::TomlFrontmatter => {
870                let parts = crate::document::format::frontmatter::split(
871                    &self.source,
872                    crate::document::format::frontmatter::Delimiter::Plus,
873                )?;
874                let new_fm =
875                    crate::document::format::toml::unset_preserving(parts.frontmatter, key)?;
876                format!("{}{}{}", parts.pre, new_fm, parts.post)
877            }
878            #[cfg(feature = "yaml")]
879            Format::YamlFrontmatter => {
880                let parts = crate::document::format::frontmatter::split(
881                    &self.source,
882                    crate::document::format::frontmatter::Delimiter::Dash,
883                )?;
884                let new_fm =
885                    crate::document::format::yaml::unset_preserving(parts.frontmatter, key)?;
886                format!("{}{}{}", parts.pre, new_fm, parts.post)
887            }
888            _ => self.format.save(&value)?,
889        };
890        self.source = output;
891        self.value = value;
892        Ok(true)
893    }
894}
895
896impl DocumentFile {
897    /// Run `edit` against the in-memory [`Document`], then commit once with
898    /// [`save`](DocumentFile::save). The single-call form of stage-then-save:
899    /// closure and pre-install failures reach neither this handle nor disk,
900    /// while a successful commit updates both. As with [`save`](Self::save), a
901    /// parent-directory fsync error after installation is commit-uncertain and
902    /// callers should reopen the path.
903    pub fn edit<F>(&mut self, edit: F) -> DocumentResult<()>
904    where
905        F: FnOnce(&mut Document) -> DocumentResult<()>,
906    {
907        let mut draft = self.doc.clone();
908        edit(&mut draft)?;
909        self.save_document(&draft)?;
910        self.doc = draft;
911        Ok(())
912    }
913
914    /// Transactionally edit, deserialize, and validate the complete document
915    /// before committing it.
916    ///
917    /// The closure works on a clone. Editing, typed decoding, and every
918    /// pre-install write failure leave both this handle and the file in their
919    /// original state. No partial file is observable. If the final parent
920    /// directory fsync fails after the rename, a complete new file may already
921    /// be installed even though durability could not be confirmed; reopen the
922    /// file after that error. On success the decoded model is returned so
923    /// callers need not deserialize a second time.
924    pub fn edit_and_validate<T>(
925        &mut self,
926        edit: impl FnOnce(&mut Document) -> DocumentResult<()>,
927    ) -> DocumentResult<T>
928    where
929        T: serde::de::DeserializeOwned,
930    {
931        let mut draft = self.doc.clone();
932        edit(&mut draft)?;
933        let decoded = draft.decode::<T>()?;
934        self.save_document(&draft)?;
935        self.doc = draft;
936        Ok(decoded)
937    }
938
939    /// Edit and decode a draft before atomically replacing the backing file
940    /// with the requested permissions.
941    pub fn edit_and_validate_with<T>(
942        &mut self,
943        options: CreateOptions,
944        edit: impl FnOnce(&mut Document) -> DocumentResult<()>,
945    ) -> DocumentResult<T>
946    where
947        T: serde::de::DeserializeOwned,
948    {
949        let mut draft = self.doc.clone();
950        edit(&mut draft)?;
951        let decoded = draft.decode::<T>()?;
952        *self = Self::create_atomic(&self.path, draft, options.replace())?;
953        Ok(decoded)
954    }
955
956    /// Persist the document — every edit staged since [`open`](DocumentFile::open)
957    /// — to its path in a single atomic write.
958    ///
959    /// The mutation verbs (`set`/`unset`/`add`/`remove`) stage their
960    /// source-preserving edit in memory and do **not** touch disk; this is the
961    /// one commit point. That lets a caller apply several edits and inspect the
962    /// result via [`value`](Document::value) (e.g. deserialize-and-validate)
963    /// before any bytes are written. The complete edit set is installed together.
964    ///
965    /// Saves are last-writer-wins: if two handles edit the same file, the later
966    /// save replaces the earlier one. Callers must serialize concurrent edits
967    /// themselves; saving does not compare the file to the handle's original
968    /// snapshot.
969    pub fn save(&self) -> DocumentResult<()> {
970        self.save_atomic(self.doc.source())
971    }
972
973    /// Atomically replace the file's contents with `new_source`: guard
974    /// against symlinks/hardlinked files, write to a same-directory temp
975    /// file, fsync it, re-apply the original file's permissions, then
976    /// `rename` it over the target. No partial write is ever observable.
977    /// Failures before the rename leave the original untouched. A failure
978    /// syncing the parent directory after the rename means the complete new
979    /// file may already be installed, but its crash durability could not be
980    /// confirmed.
981    ///
982    /// Crate-internal write seam behind the public [`save`](DocumentFile::save);
983    /// it is not exported, so callers cannot write arbitrary raw text that
984    /// bypasses the parse/edit path.
985    pub(crate) fn save_atomic(&self, new_source: &str) -> DocumentResult<()> {
986        // A read-only format never reaches disk, even when nothing was staged
987        // and the bytes would be identical: a `save` that succeeds is a claim
988        // this file is under afdata's control for writing, and it is not.
989        self.ensure_writable("save")?;
990        // Read back what is about to be written, before writing it. A
991        // source-preserving edit splices text, and a splice that lands in the
992        // wrong place can produce a file this very parser rejects — an INI key
993        // added to a section that had already closed, for one. Of the three
994        // possible outcomes, reporting success and leaving an unreadable file
995        // behind is the only unrecoverable one.
996        validate_source_text_for_write(new_source, self.format)?;
997        write_atomic(&self.path, new_source.as_bytes(), "write")
998    }
999
1000    fn save_document(&self, document: &Document) -> DocumentResult<()> {
1001        document.ensure_writable("save")?;
1002        validate_source_for_write(document)?;
1003        write_atomic(&self.path, document.source().as_bytes(), "write")
1004    }
1005}
1006
1007impl std::ops::Deref for DocumentFile {
1008    type Target = Document;
1009
1010    fn deref(&self) -> &Document {
1011        &self.doc
1012    }
1013}
1014
1015impl std::ops::DerefMut for DocumentFile {
1016    fn deref_mut(&mut self) -> &mut Document {
1017        &mut self.doc
1018    }
1019}
1020
1021fn resolve_format(path: &Path, format_override: Option<Format>) -> DocumentResult<Format> {
1022    match format_override {
1023        Some(format) => Ok(format),
1024        // A `.toml` file read by a build without the `toml` feature is not an
1025        // unknown format — it is a known one this binary cannot read, and
1026        // saying so names the fix. Only `Format::unavailable` can tell the two
1027        // apart, because `detect` answers `None` for both.
1028        None => match Format::detect(path) {
1029            Some(format) => Ok(format),
1030            None => Err(match Format::unavailable(path) {
1031                Some(feature) => DocumentError::UnsupportedOperation {
1032                    format: feature.to_string(),
1033                    operation: "open".to_string(),
1034                    detail: format!("requires Cargo feature `{feature}`"),
1035                },
1036                None => DocumentError::FormatUnknown {
1037                    path: path.display().to_string(),
1038                },
1039            }),
1040        },
1041    }
1042}
1043
1044fn validate_source_for_write(document: &Document) -> DocumentResult<()> {
1045    validate_source_text_for_write(document.source(), document.format())
1046}
1047
1048fn validate_source_text_for_write(source: &str, format: Format) -> DocumentResult<()> {
1049    Document::parse(source, format).map_err(|error| DocumentError::WriteWouldCorrupt {
1050        format: format.name().to_string(),
1051        detail: error.redacted_message(),
1052    })?;
1053    Ok(())
1054}
1055
1056fn validate_create_options(options: CreateOptions) -> DocumentResult<()> {
1057    crate::atomic_file::validate_unix_mode(options.unix_mode).map_err(|error| {
1058        DocumentError::InvalidArgument {
1059            detail: error.to_string(),
1060        }
1061    })
1062}
1063
1064#[cfg(test)]
1065mod tests {
1066    #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
1067    use super::*;
1068    use std::io::Cursor;
1069
1070    fn write_temp(dir: &Path, name: &str, contents: &str) -> PathBuf {
1071        let path = dir.join(name);
1072        fs::write(&path, contents).unwrap();
1073        path
1074    }
1075
1076    #[test]
1077    fn round_trip_open_json() {
1078        let dir = tempfile::tempdir().unwrap();
1079        let contents = r#"{"host": "example.com", "port": 993}"#;
1080        let path = write_temp(dir.path(), "config.json", contents);
1081
1082        let doc = DocumentFile::open(&path, None).unwrap();
1083
1084        assert_eq!(doc.format(), Format::Json);
1085        assert_eq!(
1086            doc.value().get("host").and_then(Value::as_str),
1087            Some("example.com")
1088        );
1089        assert_eq!(doc.source(), contents);
1090    }
1091
1092    #[test]
1093    fn value_at_reads_a_nested_address() {
1094        let dir = tempfile::tempdir().unwrap();
1095        let path = write_temp(
1096            dir.path(),
1097            "config.json",
1098            r#"{"database": {"url": "postgres://x"}}"#,
1099        );
1100        let doc = DocumentFile::open(&path, None).unwrap();
1101
1102        assert_eq!(
1103            doc.value_at("database.url").unwrap(),
1104            Value::String("postgres://x".to_string())
1105        );
1106        assert_eq!(
1107            doc.value_at("database.missing").unwrap_err().code(),
1108            "document_path_not_found"
1109        );
1110    }
1111
1112    #[test]
1113    fn open_capped_enforces_size_and_regular_file() {
1114        let dir = tempfile::tempdir().unwrap();
1115        let path = write_temp(dir.path(), "config.json", r#"{"k": "v"}"#);
1116
1117        // Within the cap: opens normally.
1118        assert!(DocumentFile::open_capped(&path, None, 1024).is_ok());
1119
1120        // Over the cap: rejected without parsing, under its own code so a
1121        // caller enforcing a size budget need not match on the message.
1122        let err = DocumentFile::open_capped(&path, None, 4).unwrap_err();
1123        assert_eq!(err.code(), "document_too_large");
1124
1125        // A directory is not a regular file, and that is a different failure.
1126        let dir_err = DocumentFile::open_capped(dir.path(), Some(Format::Json), 1024).unwrap_err();
1127        assert_eq!(dir_err.code(), "document_io_failed");
1128
1129        // Missing is different again — the three must stay distinguishable.
1130        let missing =
1131            DocumentFile::open_capped(dir.path().join("absent.json"), None, 1024).unwrap_err();
1132        assert_ne!(missing.code(), "document_too_large");
1133    }
1134
1135    #[cfg(unix)]
1136    #[test]
1137    fn capped_read_uses_the_open_handle_when_the_path_is_replaced() {
1138        let dir = tempfile::tempdir().unwrap();
1139        let original = r#"{"source":"original"}"#;
1140        let path = write_temp(dir.path(), "config.json", original);
1141        let handle = open_read_handle(&path, SymlinkPolicy::Follow).unwrap();
1142        inspect_capped_source(&handle, &path, 64).unwrap();
1143
1144        fs::rename(&path, dir.path().join("original.json")).unwrap();
1145        fs::write(&path, r#"{"source":"replacement"}"#).unwrap();
1146
1147        let source = read_capped_contents(handle, &path, 64).unwrap();
1148        assert_eq!(source, original);
1149    }
1150
1151    #[cfg(unix)]
1152    #[test]
1153    fn capped_read_rechecks_the_actual_bytes_after_metadata() {
1154        use std::io::Write as _;
1155
1156        let dir = tempfile::tempdir().unwrap();
1157        let path = write_temp(dir.path(), "config.json", "{}");
1158        let handle = open_read_handle(&path, SymlinkPolicy::Follow).unwrap();
1159        inspect_capped_source(&handle, &path, 4).unwrap();
1160
1161        let mut writer = OpenOptions::new().append(true).open(&path).unwrap();
1162        writer.write_all(b"123").unwrap();
1163        writer.sync_all().unwrap();
1164
1165        let error = read_capped_contents(handle, &path, 4).unwrap_err();
1166        assert_eq!(error.code(), "document_too_large");
1167    }
1168
1169    #[cfg(all(unix, feature = "libc"))]
1170    #[test]
1171    fn open_capped_can_atomically_refuse_a_symlink() {
1172        let dir = tempfile::tempdir().unwrap();
1173        let target = write_temp(dir.path(), "target.json", r#"{"k": "v"}"#);
1174        let link = dir.path().join("link.json");
1175        std::os::unix::fs::symlink(&target, &link).unwrap();
1176
1177        assert!(
1178            DocumentFile::open_capped_with_policy(&link, None, 1024, SymlinkPolicy::Follow).is_ok()
1179        );
1180        let error =
1181            DocumentFile::open_capped_with_policy(&link, None, 1024, SymlinkPolicy::NoFollow)
1182                .unwrap_err();
1183        assert_eq!(error.code(), "document_io_failed");
1184    }
1185
1186    #[test]
1187    fn create_atomic_is_no_clobber_and_returns_a_file_handle() {
1188        let dir = tempfile::tempdir().unwrap();
1189        let path = dir.path().join("config.json");
1190        let document = Document::parse(r#"{"port": 993}"#, Format::Json).unwrap();
1191
1192        let created = DocumentFile::create_atomic(&path, document, CreateOptions::new()).unwrap();
1193        assert_eq!(created.path(), path);
1194        assert_eq!(fs::read_to_string(&path).unwrap(), r#"{"port": 993}"#);
1195
1196        let replacement = Document::parse(r#"{"port": 1024}"#, Format::Json).unwrap();
1197        let error =
1198            DocumentFile::create_atomic(&path, replacement, CreateOptions::new()).unwrap_err();
1199        assert_eq!(error.code(), "document_target_exists");
1200        assert_eq!(fs::read_to_string(&path).unwrap(), r#"{"port": 993}"#);
1201    }
1202
1203    #[test]
1204    fn create_atomic_requires_explicit_replace() {
1205        let dir = tempfile::tempdir().unwrap();
1206        let path = write_temp(dir.path(), "config.json", r#"{"port": 993}"#);
1207        let replacement = Document::parse(r#"{"port": 1024}"#, Format::Json).unwrap();
1208
1209        let created =
1210            DocumentFile::create_atomic(&path, replacement, CreateOptions::new().replace())
1211                .unwrap();
1212
1213        assert_eq!(created.value_at("port").unwrap(), Value::Integer(1024));
1214        assert_eq!(fs::read_to_string(&path).unwrap(), r#"{"port": 1024}"#);
1215    }
1216
1217    /// Two write paths must not disagree about permissions. `save()` preserves
1218    /// the target's mode, so a replace does too unless the caller names one —
1219    /// otherwise committing through the other verb silently re-permissions a
1220    /// file, which on a secrets file means widening it.
1221    #[cfg(unix)]
1222    #[test]
1223    fn create_atomic_replace_preserves_the_targets_mode_unless_told_otherwise() {
1224        use std::os::unix::fs::PermissionsExt as _;
1225
1226        let dir = tempfile::tempdir().unwrap();
1227        let mode_of = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777;
1228
1229        for original in [0o644, 0o600, 0o640] {
1230            let path = write_temp(dir.path(), &format!("m{original:o}.json"), r#"{"a": 1}"#);
1231            fs::set_permissions(&path, fs::Permissions::from_mode(original)).unwrap();
1232            let replacement = Document::parse(r#"{"a": 2}"#, Format::Json).unwrap();
1233            DocumentFile::create_atomic(&path, replacement, CreateOptions::new().replace())
1234                .unwrap();
1235            assert_eq!(
1236                mode_of(&path),
1237                original,
1238                "replace must keep the file's mode"
1239            );
1240        }
1241
1242        // An explicit mode still wins.
1243        let path = write_temp(dir.path(), "explicit.json", r#"{"a": 1}"#);
1244        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
1245        let replacement = Document::parse(r#"{"a": 2}"#, Format::Json).unwrap();
1246        DocumentFile::create_atomic(
1247            &path,
1248            replacement,
1249            CreateOptions::new().replace().unix_mode(0o600),
1250        )
1251        .unwrap();
1252        assert_eq!(mode_of(&path), 0o600);
1253
1254        // A first creation still defaults to owner-only.
1255        let fresh = dir.path().join("fresh.json");
1256        let document = Document::parse(r#"{"a": 1}"#, Format::Json).unwrap();
1257        DocumentFile::create_atomic(&fresh, document, CreateOptions::new()).unwrap();
1258        assert_eq!(mode_of(&fresh), 0o600);
1259    }
1260
1261    /// A "safe first commit" that installs a file `open` would reject is not
1262    /// safe. The format the path resolves to and the document's own format have
1263    /// to agree before anything is written.
1264    #[cfg(feature = "toml")]
1265    #[test]
1266    fn create_atomic_refuses_a_document_the_path_could_not_reopen() {
1267        let dir = tempfile::tempdir().unwrap();
1268        let path = dir.path().join("mismatch.toml");
1269        let document = Document::parse(r#"{"port": 993}"#, Format::Json).unwrap();
1270
1271        let error = DocumentFile::create_atomic(&path, document, CreateOptions::new()).unwrap_err();
1272
1273        assert_eq!(error.code(), "document_unsupported_operation");
1274        assert!(
1275            !path.exists(),
1276            "nothing may be written when the check fails"
1277        );
1278    }
1279
1280    #[cfg(unix)]
1281    #[test]
1282    fn create_atomic_applies_requested_private_mode() {
1283        use std::os::unix::fs::PermissionsExt as _;
1284
1285        let dir = tempfile::tempdir().unwrap();
1286        let path = dir.path().join("config.json");
1287        let document = Document::parse(r#"{"port": 993}"#, Format::Json).unwrap();
1288
1289        DocumentFile::create_atomic(&path, document, CreateOptions::new().unix_mode(0o640))
1290            .unwrap();
1291
1292        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
1293        assert_eq!(mode, 0o640);
1294    }
1295
1296    #[test]
1297    fn create_atomic_rejects_invalid_permission_bits_before_writing() {
1298        let dir = tempfile::tempdir().unwrap();
1299        let path = dir.path().join("config.json");
1300        let document = Document::parse(r#"{"port": 993}"#, Format::Json).unwrap();
1301
1302        let error =
1303            DocumentFile::create_atomic(&path, document, CreateOptions::new().unix_mode(0o1600))
1304                .unwrap_err();
1305
1306        assert_eq!(error.code(), "document_invalid_argument");
1307        assert!(!path.exists());
1308    }
1309
1310    #[cfg(unix)]
1311    #[test]
1312    fn create_atomic_replace_refuses_symlinks_and_hardlinks() {
1313        let dir = tempfile::tempdir().unwrap();
1314        let target = write_temp(dir.path(), "target.json", r#"{"port": 993}"#);
1315        let symlink = dir.path().join("symlink.json");
1316        std::os::unix::fs::symlink(&target, &symlink).unwrap();
1317        let replacement = Document::parse(r#"{"port": 1024}"#, Format::Json).unwrap();
1318
1319        let symlink_error = DocumentFile::create_atomic(
1320            &symlink,
1321            replacement.clone(),
1322            CreateOptions::new().replace(),
1323        )
1324        .unwrap_err();
1325        assert_eq!(symlink_error.code(), "document_unsupported_operation");
1326        assert_eq!(fs::read_to_string(&target).unwrap(), r#"{"port": 993}"#);
1327
1328        let hardlink = dir.path().join("hardlink.json");
1329        fs::hard_link(&target, &hardlink).unwrap();
1330        let hardlink_error =
1331            DocumentFile::create_atomic(&hardlink, replacement, CreateOptions::new().replace())
1332                .unwrap_err();
1333        assert_eq!(hardlink_error.code(), "document_unsupported_operation");
1334        assert_eq!(fs::read_to_string(&target).unwrap(), r#"{"port": 993}"#);
1335    }
1336
1337    #[cfg(unix)]
1338    #[test]
1339    fn create_atomic_replace_refuses_a_dangling_symlink() {
1340        let dir = tempfile::tempdir().unwrap();
1341        let missing = dir.path().join("missing.json");
1342        let symlink = dir.path().join("dangling.json");
1343        std::os::unix::fs::symlink(&missing, &symlink).unwrap();
1344        let replacement = Document::parse(r#"{"port": 1024}"#, Format::Json).unwrap();
1345
1346        let error =
1347            DocumentFile::create_atomic(&symlink, replacement, CreateOptions::new().replace())
1348                .unwrap_err();
1349
1350        assert_eq!(error.code(), "document_unsupported_operation");
1351        assert!(
1352            fs::symlink_metadata(&symlink)
1353                .unwrap()
1354                .file_type()
1355                .is_symlink()
1356        );
1357        assert!(!missing.exists());
1358    }
1359
1360    #[test]
1361    fn edit_rolls_back_memory_and_disk_when_the_closure_fails() {
1362        let dir = tempfile::tempdir().unwrap();
1363        let original = r#"{"port": 993}"#;
1364        let path = write_temp(dir.path(), "config.json", original);
1365        let mut document = DocumentFile::open(&path, None).unwrap();
1366
1367        let error = document
1368            .edit(|draft| {
1369                draft.set("port", Value::Integer(1024))?;
1370                Err(DocumentError::InvalidArgument {
1371                    detail: "validation failed".to_string(),
1372                })
1373            })
1374            .unwrap_err();
1375
1376        assert_eq!(error.code(), "document_invalid_argument");
1377        assert_eq!(document.source(), original);
1378        assert_eq!(document.value_at("port").unwrap(), Value::Integer(993));
1379        assert_eq!(fs::read_to_string(&path).unwrap(), original);
1380    }
1381
1382    #[test]
1383    fn typed_get_and_set_enforce_the_stated_type() {
1384        use crate::document::ValueType;
1385        let dir = tempfile::tempdir().unwrap();
1386        let path = write_temp(dir.path(), "config.json", r#"{"port": 8080, "host": "x"}"#);
1387        let mut doc = DocumentFile::open(&path, None).unwrap();
1388
1389        // Typed get: matching type returns, wrong type is a caught error, Json
1390        // matches anything.
1391        assert!(doc.value_at_typed("port", ValueType::Number).is_ok());
1392        assert_eq!(
1393            doc.value_at_typed("port", ValueType::String)
1394                .unwrap_err()
1395                .code(),
1396            "document_type_mismatch"
1397        );
1398        assert!(doc.value_at_typed("host", ValueType::Json).is_ok());
1399
1400        // Typed set: the literal is validated against the stated type.
1401        doc.set_typed("port", Some("9090"), ValueType::Number)
1402            .unwrap();
1403        assert_eq!(
1404            doc.value_at("port").unwrap(),
1405            Value::from(serde_json::json!(9090))
1406        );
1407        assert_eq!(
1408            doc.set_typed("port", Some("not-a-number"), ValueType::Number)
1409                .unwrap_err()
1410                .code(),
1411            "document_parse_failed"
1412        );
1413    }
1414
1415    #[test]
1416    fn decode_and_edit_and_validate_share_one_typed_boundary() {
1417        #[derive(Debug, serde::Deserialize)]
1418        #[serde(deny_unknown_fields)]
1419        struct Config {
1420            port: u16,
1421        }
1422
1423        let dir = tempfile::tempdir().unwrap();
1424        let original = r#"{"port": 8080}"#;
1425        let path = write_temp(dir.path(), "config.json", original);
1426        let mut document = DocumentFile::open(&path, None).unwrap();
1427
1428        assert_eq!(document.decode::<Config>().unwrap().port, 8080);
1429
1430        let error = document
1431            .edit_and_validate::<Config>(|draft| {
1432                draft.set("port", Value::String("invalid".to_string()))
1433            })
1434            .unwrap_err();
1435        assert_eq!(error.code(), "document_type_mismatch");
1436        assert_eq!(document.source(), original);
1437        assert_eq!(fs::read_to_string(&path).unwrap(), original);
1438
1439        let config = document
1440            .edit_and_validate::<Config>(|draft| draft.set("port", Value::Unsigned(9090)))
1441            .unwrap();
1442        assert_eq!(config.port, 9090);
1443        assert_eq!(document.value_at("port").unwrap(), Value::Unsigned(9090));
1444    }
1445
1446    #[cfg(feature = "toml")]
1447    #[test]
1448    fn round_trip_open_toml() {
1449        let dir = tempfile::tempdir().unwrap();
1450        let contents = "# leading comment\nhost = \"example.com\"\nport = 993\n";
1451        let path = write_temp(dir.path(), "config.toml", contents);
1452
1453        let doc = DocumentFile::open(&path, None).unwrap();
1454
1455        assert_eq!(doc.format(), Format::Toml);
1456        assert_eq!(
1457            doc.value().get("host").and_then(Value::as_str),
1458            Some("example.com")
1459        );
1460        assert_eq!(doc.source(), contents);
1461    }
1462
1463    #[cfg(feature = "toml")]
1464    #[test]
1465    fn set_scalar_preserves_toml_comments_and_formatting() {
1466        let dir = tempfile::tempdir().unwrap();
1467        let contents = "# leading comment\nhost = \"example.com\"\nport = 993 # inline comment\n";
1468        let path = write_temp(dir.path(), "config.toml", contents);
1469        let mut doc = DocumentFile::open(&path, None).unwrap();
1470
1471        doc.set("port", Value::Integer(1024)).unwrap();
1472        doc.save().unwrap();
1473
1474        let saved = fs::read_to_string(&path).unwrap();
1475        assert!(saved.contains("# leading comment"));
1476        assert!(saved.contains("port = 1024"));
1477        assert_eq!(
1478            doc.value().get("port").and_then(Value::as_integer),
1479            Some(1024)
1480        );
1481        assert_eq!(doc.source(), saved);
1482    }
1483
1484    /// A comment documents the value it was written beside. Growing an array
1485    /// must not copy a neighbour's comment onto a value the author never wrote
1486    /// it for, and shrinking must not leave a removed element's comment
1487    /// documenting a survivor. Both are content this module invented.
1488    #[cfg(feature = "toml")]
1489    #[test]
1490    fn toml_array_edits_never_invent_or_misattribute_a_comment() {
1491        let contents = "paths = [\n  \"one\", # first\n  \"two\", # second\n]\n";
1492
1493        let mut grown = Document::parse(contents, Format::Toml).unwrap();
1494        grown
1495            .set(
1496                "paths",
1497                Value::Array(vec![
1498                    Value::String("a".into()),
1499                    Value::String("b".into()),
1500                    Value::String("c".into()),
1501                ]),
1502            )
1503            .unwrap();
1504        assert_eq!(
1505            grown.source(),
1506            "paths = [\n  \"a\", # first\n  \"b\", # second\n  \"c\",\n]\n",
1507            "an appended element must carry no comment of its own"
1508        );
1509
1510        let mut shrunk = Document::parse(contents, Format::Toml).unwrap();
1511        shrunk
1512            .set("paths", Value::Array(vec![Value::String("only".into())]))
1513            .unwrap();
1514        assert_eq!(
1515            shrunk.source(),
1516            "paths = [\n  \"only\", # first\n]\n",
1517            "the surviving element keeps its own comment, not the removed one's"
1518        );
1519
1520        // Same length: every comment stays exactly where the author put it.
1521        let mut replaced = Document::parse(contents, Format::Toml).unwrap();
1522        replaced
1523            .set(
1524                "paths",
1525                Value::Array(vec![Value::String("x".into()), Value::String("y".into())]),
1526            )
1527            .unwrap();
1528        assert_eq!(
1529            replaced.source(),
1530            "paths = [\n  \"x\", # first\n  \"y\", # second\n]\n"
1531        );
1532
1533        // Growing a single-line array keeps the bracket spacing.
1534        let mut inline = Document::parse("paths = [ \"one\" ]\n", Format::Toml).unwrap();
1535        inline
1536            .set(
1537                "paths",
1538                Value::Array(vec![
1539                    Value::String("one".into()),
1540                    Value::String("two".into()),
1541                ]),
1542            )
1543            .unwrap();
1544        assert_eq!(inline.source(), "paths = [ \"one\", \"two\" ]\n");
1545    }
1546
1547    #[cfg(feature = "toml")]
1548    #[test]
1549    fn set_toml_array_preserves_single_line_decor() {
1550        let contents = "# before\npaths = [ \"old\", 'second', ] # keep this\nother = 42\n";
1551        let mut document = Document::parse(contents, Format::Toml).unwrap();
1552
1553        document
1554            .set(
1555                "paths",
1556                Value::Array(vec![
1557                    Value::String("new".to_string()),
1558                    Value::String("next".to_string()),
1559                ]),
1560            )
1561            .unwrap();
1562
1563        assert_eq!(
1564            document.source(),
1565            "# before\npaths = [ \"new\", \"next\", ] # keep this\nother = 42\n"
1566        );
1567    }
1568
1569    #[cfg(feature = "toml")]
1570    #[test]
1571    fn set_toml_array_preserves_multiline_comments_and_trailing_comma() {
1572        let contents = "paths = [\n  \"one\", # first\n  \"two\", # second\n]\nother = 42\n";
1573        let mut document = Document::parse(contents, Format::Toml).unwrap();
1574
1575        document
1576            .set(
1577                "paths",
1578                Value::Array(vec![
1579                    Value::String("uno".to_string()),
1580                    Value::String("dos".to_string()),
1581                ]),
1582            )
1583            .unwrap();
1584
1585        assert_eq!(
1586            document.source(),
1587            "paths = [\n  \"uno\", # first\n  \"dos\", # second\n]\nother = 42\n"
1588        );
1589    }
1590
1591    #[cfg(feature = "toml")]
1592    #[test]
1593    fn set_toml_array_element_preserves_its_neighbors() {
1594        let contents = "paths = [\n  \"one\", # first\n  \"two\", # second\n]\n";
1595        let mut document = Document::parse(contents, Format::Toml).unwrap();
1596
1597        document
1598            .set("paths.1", Value::String("changed".to_string()))
1599            .unwrap();
1600
1601        assert_eq!(
1602            document.source(),
1603            "paths = [\n  \"one\", # first\n  \"changed\", # second\n]\n"
1604        );
1605    }
1606
1607    #[cfg(feature = "toml")]
1608    #[test]
1609    fn set_toml_array_can_become_empty_without_touching_neighbors() {
1610        let contents = "before = 1\npaths = [ \"one\", ] # list\nafter = 2\n";
1611        let mut document = Document::parse(contents, Format::Toml).unwrap();
1612
1613        document.set("paths", Value::Array(Vec::new())).unwrap();
1614
1615        assert_eq!(
1616            document.source(),
1617            "before = 1\npaths = [ ] # list\nafter = 2\n"
1618        );
1619    }
1620
1621    #[cfg(feature = "toml")]
1622    #[test]
1623    fn set_toml_inline_table_preserves_layout_and_comments() {
1624        let contents = "cache = { ttl_s = 1, enabled = true } # cache\nother = 42\n";
1625        let mut document = Document::parse(contents, Format::Toml).unwrap();
1626        let replacement = Value::from(serde_json::json!({
1627            "enabled": false,
1628            "ttl_s": 60
1629        }));
1630
1631        document.set("cache", replacement).unwrap();
1632
1633        assert_eq!(
1634            document.source(),
1635            "cache = { ttl_s = 60, enabled = false } # cache\nother = 42\n"
1636        );
1637    }
1638
1639    #[cfg(feature = "toml")]
1640    #[test]
1641    fn set_toml_ordinary_table_preserves_header_and_unrelated_section() {
1642        let contents = "# lead\n[cache] # cache header\nttl_s = 1 # ttl\nenabled = true\n\n[next]\nvalue = 9\n";
1643        let mut document = Document::parse(contents, Format::Toml).unwrap();
1644        let replacement = Value::from(serde_json::json!({
1645            "enabled": false,
1646            "ttl_s": 60
1647        }));
1648
1649        document.set("cache", replacement).unwrap();
1650
1651        assert_eq!(
1652            document.source(),
1653            "# lead\n[cache] # cache header\nttl_s = 60 # ttl\nenabled = false\n\n[next]\nvalue = 9\n"
1654        );
1655    }
1656
1657    #[cfg(feature = "toml")]
1658    #[test]
1659    fn set_toml_collection_preserves_unchanged_datetime_syntax() {
1660        let contents = "[cache]\nexpires_at = 2026-08-04T12:30:00Z\npaths = [\"one\"]\n";
1661        let mut document = Document::parse(contents, Format::Toml).unwrap();
1662        let replacement = document.value_at("cache").unwrap();
1663
1664        document.set("cache", replacement).unwrap();
1665
1666        assert_eq!(document.source(), contents);
1667    }
1668
1669    #[cfg(feature = "toml")]
1670    #[test]
1671    fn set_toml_array_of_tables_is_explicitly_refused() {
1672        let contents = "[[servers]]\nname = \"one\"\n[[servers]]\nname = \"two\"\n";
1673        let mut document = Document::parse(contents, Format::Toml).unwrap();
1674        let replacement = document.value_at("servers").unwrap();
1675
1676        let error = document.set("servers", replacement).unwrap_err();
1677
1678        assert_eq!(error.code(), "document_unsupported_operation");
1679        assert_eq!(document.source(), contents);
1680    }
1681
1682    #[cfg(feature = "ini")]
1683    #[test]
1684    fn save_refuses_source_its_own_parser_rejects() {
1685        // The read-back guard, exercised directly: no backend should be able to
1686        // splice text into this shape any more, so the corrupt source is
1687        // supplied by hand rather than provoked through a verb.
1688        let dir = tempfile::tempdir().unwrap();
1689        let original = "[db]\nhost=localhost\n";
1690        let path = write_temp(dir.path(), "config.ini", original);
1691        let doc = DocumentFile::open(&path, None).unwrap();
1692
1693        let error = doc
1694            .save_atomic("[db]\nhost=localhost\n\n[db]\nport=5432\n")
1695            .unwrap_err();
1696        assert_eq!(error.code(), "document_write_would_corrupt");
1697        // The whole point is that the guard runs before any bytes land.
1698        assert_eq!(fs::read_to_string(&path).unwrap(), original);
1699    }
1700
1701    #[cfg(feature = "ini")]
1702    #[test]
1703    fn save_writes_source_the_parser_accepts() {
1704        let dir = tempfile::tempdir().unwrap();
1705        let path = write_temp(dir.path(), "config.ini", "[db]\nhost=localhost\n");
1706        let mut doc = DocumentFile::open(&path, None).unwrap();
1707
1708        doc.set("db.port", Value::String("5432".to_string()))
1709            .unwrap();
1710        doc.save().unwrap();
1711
1712        // A key added to a section that is not the file's last one used to be
1713        // appended at end of file, re-opening a section that had closed.
1714        assert_eq!(
1715            fs::read_to_string(&path).unwrap(),
1716            "[db]\nhost=localhost\nport=5432\n"
1717        );
1718        assert!(DocumentFile::open(&path, None).is_ok());
1719    }
1720
1721    #[cfg(unix)]
1722    #[test]
1723    fn atomic_save_preserves_file_mode() {
1724        use std::os::unix::fs::PermissionsExt;
1725
1726        let dir = tempfile::tempdir().unwrap();
1727        let path = write_temp(dir.path(), "config.json", r#"{"port": 993}"#);
1728        fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap();
1729        let mut doc = DocumentFile::open(&path, None).unwrap();
1730
1731        doc.set("port", Value::Integer(1024)).unwrap();
1732        doc.save().unwrap();
1733
1734        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
1735        assert_eq!(mode, 0o640);
1736    }
1737
1738    #[cfg(unix)]
1739    #[test]
1740    fn symlink_target_is_rejected_for_mutation() {
1741        let dir = tempfile::tempdir().unwrap();
1742        let target = write_temp(dir.path(), "target.json", r#"{"port": 993}"#);
1743        let link = dir.path().join("link.json");
1744        std::os::unix::fs::symlink(&target, &link).unwrap();
1745
1746        // Reading through the symlink is fine.
1747        let mut doc = DocumentFile::open(&link, None).unwrap();
1748
1749        // Editing in memory is fine; committing through the symlink is not.
1750        doc.set("port", Value::Integer(1024)).unwrap();
1751        let err = doc.save().unwrap_err();
1752        assert!(matches!(err, DocumentError::UnsupportedOperation { .. }));
1753
1754        // The target file was never touched.
1755        let target_contents = fs::read_to_string(&target).unwrap();
1756        assert_eq!(target_contents, r#"{"port": 993}"#);
1757    }
1758
1759    #[test]
1760    fn from_reader_parses_in_memory_cursor() {
1761        let cursor = Cursor::new(br#"{"host": "example.com"}"#.to_vec());
1762
1763        let doc = Document::from_reader(cursor, Format::Json).unwrap();
1764
1765        assert_eq!(
1766            doc.value().get("host").and_then(Value::as_str),
1767            Some("example.com")
1768        );
1769    }
1770
1771    #[test]
1772    fn document_from_str_encode_round_trip() {
1773        let doc = Document::parse(r#"{"a": 1}"#, Format::Json).unwrap();
1774        let encoded = doc.encode().unwrap();
1775        let reparsed = Document::parse(&encoded, Format::Json).unwrap();
1776        assert_eq!(
1777            reparsed.value().get("a").and_then(Value::as_integer),
1778            Some(1)
1779        );
1780    }
1781
1782    #[test]
1783    fn document_edits_source_in_memory_without_a_file() {
1784        // The point of the Document/DocumentFile split: source-preserving
1785        // editing with no file, no I/O, no guards.
1786        let mut doc = Document::parse("{\n  \"host\": \"old\"\n}\n", Format::Json).unwrap();
1787        doc.set("host", Value::String("new".to_string())).unwrap();
1788        doc.set("imap.port", Value::Integer(993)).unwrap(); // creates the parent
1789
1790        assert_eq!(
1791            doc.source(),
1792            "{\n  \"host\": \"new\",\n  \"imap\": {\n    \"port\": 993\n  }\n}\n"
1793        );
1794        assert_eq!(
1795            doc.value_at("imap.port").unwrap(),
1796            Value::from(serde_json::json!(993))
1797        );
1798    }
1799
1800    #[test]
1801    fn unset_is_false_for_anything_already_absent() {
1802        let mut doc = Document::parse(
1803            r#"{"service":{"host":"example","ports":[80]}}"#,
1804            Format::Json,
1805        )
1806        .unwrap();
1807
1808        // Absent is absent, at any depth — the answer must not change with the
1809        // number of segments the caller had to write to name the same nothing.
1810        assert!(!doc.unset("service.missing").unwrap());
1811        assert!(!doc.unset("missing.parent").unwrap());
1812        assert!(!doc.unset("missing.deeply.nested").unwrap());
1813
1814        // Still errors: these describe a path no document could satisfy, not a
1815        // document that happens not to carry the key.
1816        assert!(doc.unset("service.host.child").is_err()); // through a scalar
1817        assert!(doc.unset("service.ports.9").is_err()); // index out of range
1818        assert!(doc.unset(r"service\q").is_err()); // malformed syntax
1819    }
1820
1821    #[cfg(feature = "markdown")]
1822    #[test]
1823    fn every_markdown_write_verb_is_refused() {
1824        let source = "# Title\n\nThe lead.\n";
1825        let mut doc = Document::parse(source, Format::Markdown).unwrap();
1826
1827        // Reading is the whole point, and works — including by content, which
1828        // `value_at` gets from the format's own rule.
1829        assert_eq!(
1830            doc.value_at("h1.0.text").unwrap(),
1831            Value::String("Title".to_string())
1832        );
1833        assert_eq!(
1834            doc.value_at("h1.Tit.paragraph.0.text").unwrap(),
1835            Value::String("The lead.".to_string())
1836        );
1837
1838        // Every mutating verb refuses, including the two that would otherwise
1839        // answer before reaching a backend: `unset` on an absent path (which
1840        // is `Ok(false)` for a writable format) and `encode`.
1841        let refusals: Vec<DocumentError> = vec![
1842            doc.set("h1.0.text", Value::String("New".to_string()))
1843                .unwrap_err(),
1844            doc.add("preamble", "x", "type", &[]).unwrap_err(),
1845            doc.remove("preamble", "x", "type").unwrap_err(),
1846            doc.unset("h1.0").unwrap_err(),
1847            doc.unset("nothing.here").unwrap_err(),
1848            doc.encode().unwrap_err(),
1849        ];
1850        for error in refusals {
1851            assert_eq!(error.code(), "document_unsupported_operation");
1852            assert!(
1853                error.to_string().contains("read-only"),
1854                "refusal must name the reason: {error}"
1855            );
1856        }
1857
1858        // Nothing was staged by any of them.
1859        assert_eq!(doc.source(), source);
1860    }
1861
1862    #[cfg(feature = "markdown")]
1863    #[test]
1864    fn markdown_save_never_reaches_disk() {
1865        let dir = tempfile::tempdir().unwrap();
1866        let path = write_temp(dir.path(), "README.md", "# Title\n");
1867        // `.md` resolves to no format, so the reading has to be named.
1868        assert!(DocumentFile::open(&path, None).is_err());
1869
1870        let doc = DocumentFile::open(&path, Some(Format::Markdown)).unwrap();
1871        // Even an unmodified save, whose bytes would be identical, is refused.
1872        let error = doc.save().unwrap_err();
1873        assert_eq!(error.code(), "document_unsupported_operation");
1874        assert_eq!(fs::read_to_string(&path).unwrap(), "# Title\n");
1875    }
1876
1877    #[cfg(feature = "yaml")]
1878    #[test]
1879    fn yaml_write_rejects_cst_ambiguous_mapping_segments() {
1880        let mut numeric = Document::parse("\"123\": value\n", Format::Yaml).unwrap();
1881        assert!(
1882            numeric
1883                .set("123", Value::String("changed".to_string()))
1884                .is_err()
1885        );
1886        assert!(numeric.unset("123").is_err());
1887
1888        let mut bracketed = Document::parse("\"a[0]\": value\n", Format::Yaml).unwrap();
1889        assert!(
1890            bracketed
1891                .set("a[0]", Value::String("changed".to_string()))
1892                .is_err()
1893        );
1894    }
1895}