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