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