1mod read;
24mod write;
25
26use write::{guard_mutation, write_atomic, write_atomic_create};
27
28#[cfg(feature = "cli")]
29use read::read_capped_source;
30#[cfg(all(test, unix))]
31use read::{inspect_capped_source, read_capped_contents};
32use read::{open_read_handle, read_capped_source_bytes};
33use std::fs;
34#[cfg(all(test, unix))]
35use std::fs::OpenOptions;
36use std::path::{Path, PathBuf};
37
38use crate::document::{Addressing, DocumentError, DocumentResult, Format, KeyedList, Value};
39
40#[cfg(feature = "cli")]
41pub(crate) fn read_capped_file(
42 path: &Path,
43 max_bytes: u64,
44 symlink_policy: SymlinkPolicy,
45) -> DocumentResult<String> {
46 let file = open_read_handle(path, symlink_policy)?;
47 read_capped_source(file, path, max_bytes)
48}
49
50#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
59pub enum SymlinkPolicy {
60 #[default]
62 Follow,
63 NoFollow,
67}
68
69#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
71pub enum CreateMode {
72 #[default]
74 NewOnly,
75 Replace,
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct CreateOptions {
82 mode: CreateMode,
83 unix_mode: Option<u32>,
84}
85
86impl CreateOptions {
87 #[must_use]
92 pub const fn new() -> Self {
93 Self {
94 mode: CreateMode::NewOnly,
95 unix_mode: None,
96 }
97 }
98
99 #[must_use]
105 pub const fn unix_mode(mut self, unix_mode: u32) -> Self {
106 self.unix_mode = Some(unix_mode);
107 self
108 }
109
110 #[must_use]
112 pub const fn replace(mut self) -> Self {
113 self.mode = CreateMode::Replace;
114 self
115 }
116
117 #[must_use]
119 pub const fn mode(&self) -> CreateMode {
120 self.mode
121 }
122
123 #[must_use]
128 pub const fn configured_unix_mode(&self) -> Option<u32> {
129 self.unix_mode
130 }
131
132 const fn effective_unix_mode(&self, target_exists: bool) -> Option<u32> {
134 match self.unix_mode {
135 Some(mode) => Some(mode),
136 None if target_exists => None,
141 None => Some(0o600),
142 }
143 }
144}
145
146impl Default for CreateOptions {
147 fn default() -> Self {
148 Self::new()
149 }
150}
151
152#[derive(Debug, Clone)]
160pub struct Document {
161 source: String,
162 value: Value,
163 format: Format,
164}
165
166impl Document {
167 pub fn parse(source: &str, format: Format) -> DocumentResult<Document> {
173 let value = format.load(source)?;
174 Ok(Document {
175 source: source.to_string(),
176 value,
177 format,
178 })
179 }
180
181 pub fn from_reader<R: std::io::Read>(
187 mut reader: R,
188 format: Format,
189 ) -> DocumentResult<Document> {
190 let mut bytes = Vec::new();
191 reader.read_to_end(&mut bytes)?;
192 if let Some(document) = Document::parse_binary(&bytes, format)? {
193 return Ok(document);
194 }
195 let source = String::from_utf8(bytes)
196 .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
197 Document::parse_labelled(&source, format, "input")
198 }
199
200 fn parse_labelled(source: &str, format: Format, label: &str) -> DocumentResult<Document> {
205 match Document::parse(source, format) {
206 Err(DocumentError::ParseError { .. }) if source.is_empty() => {
207 Err(DocumentError::EmptyInput {
208 source: label.to_string(),
209 })
210 }
211 #[cfg(feature = "plist")]
212 Err(DocumentError::ParseError { .. })
213 if format == Format::Json
214 && crate::document::format::plist::looks_like_xml(source.as_bytes()) =>
215 {
216 Err(crate::document::format::plist::wrong_format_xml(
217 format.name(),
218 ))
219 }
220 other => other,
221 }
222 }
223
224 fn from_bytes(bytes: Vec<u8>, format: Format, label: &str) -> DocumentResult<Document> {
227 if let Some(document) = Document::parse_binary(&bytes, format)? {
228 return Ok(document);
229 }
230 let source = String::from_utf8(bytes).map_err(|error| DocumentError::IoError {
231 detail: format!(
232 "read `{label}`: document is not UTF-8 (valid through byte {})",
233 error.utf8_error().valid_up_to()
234 ),
235 })?;
236 Document::parse_labelled(&source, format, label)
237 }
238
239 #[cfg(feature = "plist")]
244 fn parse_binary(bytes: &[u8], format: Format) -> DocumentResult<Option<Document>> {
245 use crate::document::format::plist;
246 if !plist::is_binary(bytes) {
247 return Ok(None);
248 }
249 if format != Format::Plist {
250 return Err(plist::wrong_format(format.name()));
251 }
252 Ok(Some(Document {
253 source: String::new(),
254 value: plist::load_binary(bytes)?,
255 format,
256 }))
257 }
258
259 #[cfg(not(feature = "plist"))]
260 #[allow(clippy::unnecessary_wraps)]
261 fn parse_binary(_bytes: &[u8], _format: Format) -> DocumentResult<Option<Document>> {
262 Ok(None)
263 }
264
265 pub fn value(&self) -> &Value {
267 &self.value
268 }
269
270 pub fn source(&self) -> &str {
274 &self.source
275 }
276
277 pub fn format(&self) -> Format {
279 self.format
280 }
281
282 #[must_use]
288 pub fn addressing(&self) -> Addressing<'static> {
289 Addressing::INDEX_ONLY.with_array_rule(self.format.array_rule())
290 }
291
292 #[must_use]
295 pub fn addressing_keyed<'a>(&self, keyed_lists: &'a [KeyedList<'a>]) -> Addressing<'a> {
296 Addressing::keyed(keyed_lists).with_array_rule(self.format.array_rule())
297 }
298
299 pub fn value_at(&self, path: &str) -> DocumentResult<Value> {
307 crate::document::get_path(&self.value, path, self.addressing())
308 }
309
310 pub fn locate(&self, path: &str) -> DocumentResult<crate::document::Located<'_>> {
316 crate::document::locate(&self.value, path, self.addressing())
317 }
318
319 pub fn value_at_typed(
323 &self,
324 path: &str,
325 expected: crate::document::ValueType,
326 ) -> DocumentResult<Value> {
327 let value = self.value_at(path)?;
328 if crate::document::value_matches_type(&value, expected) {
329 Ok(value)
330 } else {
331 Err(DocumentError::TypeMismatch {
332 path: path.to_string(),
333 expected: expected.name().to_string(),
334 got: value.kind_name().to_string(),
335 hint: None,
336 })
337 }
338 }
339
340 pub fn decode<T: serde::de::DeserializeOwned>(&self) -> DocumentResult<T> {
346 crate::document::from_value(self.value(), "")
347 }
348
349 pub fn set_typed(
352 &mut self,
353 key: &str,
354 raw: Option<&str>,
355 value_type: crate::document::ValueType,
356 ) -> DocumentResult<()> {
357 let value = crate::document::value_from_type(value_type, raw)?;
358 self.set(key, value)
359 }
360
361 fn ensure_writable(&self, operation: &str) -> DocumentResult<()> {
369 if self.format.is_read_only() {
370 return Err(self.format.read_only_error(operation));
371 }
372 Ok(())
373 }
374
375 pub fn encode(&self) -> DocumentResult<String> {
381 self.format.save(&self.value)
382 }
383}
384
385#[derive(Debug, Clone)]
394pub struct DocumentFile {
395 doc: Document,
396 path: PathBuf,
397}
398
399impl DocumentFile {
400 pub fn open(
406 path: impl AsRef<Path>,
407 format_override: Option<Format>,
408 ) -> DocumentResult<DocumentFile> {
409 let path = path.as_ref().to_path_buf();
410 let format = resolve_format(&path, format_override)?;
411 let bytes = fs::read(&path).map_err(|error| DocumentError::IoError {
412 detail: format!("read `{}`: {error}", path.display()),
413 })?;
414 Ok(DocumentFile {
415 doc: Document::from_bytes(bytes, format, &path.display().to_string())?,
416 path,
417 })
418 }
419
420 pub fn open_capped(
434 path: impl AsRef<Path>,
435 format_override: Option<Format>,
436 max_bytes: u64,
437 ) -> DocumentResult<DocumentFile> {
438 Self::open_capped_with_policy(path, format_override, max_bytes, SymlinkPolicy::Follow)
439 }
440
441 pub fn open_capped_with_policy(
447 path: impl AsRef<Path>,
448 format_override: Option<Format>,
449 max_bytes: u64,
450 symlink_policy: SymlinkPolicy,
451 ) -> DocumentResult<DocumentFile> {
452 let path = path.as_ref().to_path_buf();
453 let format = resolve_format(&path, format_override)?;
454 let file = open_read_handle(&path, symlink_policy)?;
455 let bytes = read_capped_source_bytes(file, &path, max_bytes)?;
456 Ok(DocumentFile {
457 doc: Document::from_bytes(bytes, format, &path.display().to_string())?,
458 path,
459 })
460 }
461
462 pub fn create_atomic(
473 path: impl AsRef<Path>,
474 document: Document,
475 options: CreateOptions,
476 ) -> DocumentResult<DocumentFile> {
477 let path = path.as_ref().to_path_buf();
478 document.ensure_writable("create")?;
479 let path_format = resolve_format(&path, None)?;
482 if path_format != document.format() {
483 return Err(DocumentError::UnsupportedOperation {
484 format: document.format().name().to_string(),
485 operation: "create".to_string(),
486 detail: format!(
487 "path resolves to {}, so the created file could not be reopened",
488 path_format.name()
489 ),
490 });
491 }
492 validate_source_for_write(&document)?;
493 validate_create_options(options)?;
494 write_atomic_create(&path, document.source().as_bytes(), options)?;
495 Ok(DocumentFile {
496 doc: document,
497 path,
498 })
499 }
500
501 pub fn path(&self) -> &Path {
503 &self.path
504 }
505
506 pub fn ensure_mutable(&self, operation: &str) -> DocumentResult<()> {
515 self.doc.ensure_writable(operation)?;
516 guard_mutation(&self.path, operation)?;
517 Ok(())
518 }
519}
520
521impl Document {
522 pub fn set(&mut self, key: &str, value: Value) -> DocumentResult<()> {
536 let addressing = self.addressing();
537 self.set_addressed(key, value, addressing)
538 }
539
540 pub fn set_addressed(
548 &mut self,
549 key: &str,
550 value: Value,
551 addressing: Addressing<'_>,
552 ) -> DocumentResult<()> {
553 self.ensure_writable("set")?;
554 let base = self.set_base();
555 let key = &crate::document::resolve_path(&base, key, addressing)?;
556 let mut new_doc = base;
557 crate::document::set_path(&mut new_doc, key, &value, Addressing::INDEX_ONLY)?;
558 let target = value;
559 #[allow(unreachable_patterns)]
560 let output = match self.format {
561 #[cfg(feature = "toml")]
562 Format::Toml => {
563 crate::document::format::toml::set_preserving(&self.source, key, &target)?
564 }
565 #[cfg(feature = "yaml")]
566 Format::Yaml => {
567 crate::document::format::yaml::set_preserving(&self.source, key, &target)?
568 }
569 Format::Json => {
570 crate::document::format::json::set_preserving(&self.source, key, &target)?
571 }
572 #[cfg(feature = "dotenv")]
573 Format::Dotenv => {
574 crate::document::format::dotenv::set_preserving(&self.source, key, &target)?
575 }
576 #[cfg(feature = "ini")]
577 Format::Ini => {
578 crate::document::format::ini::set_preserving(&self.source, key, &target)?
579 }
580 #[cfg(feature = "toml")]
581 Format::TomlFrontmatter => {
582 let parts = crate::document::format::frontmatter::split(
583 &self.source,
584 crate::document::format::frontmatter::Delimiter::Plus,
585 )?;
586 let new_fm =
587 crate::document::format::toml::set_preserving(parts.frontmatter, key, &target)?;
588 format!("{}{}{}", parts.pre, new_fm, parts.post)
589 }
590 #[cfg(feature = "yaml")]
591 Format::YamlFrontmatter => {
592 let parts = crate::document::format::frontmatter::split(
593 &self.source,
594 crate::document::format::frontmatter::Delimiter::Dash,
595 )?;
596 let new_fm =
597 crate::document::format::yaml::set_preserving(parts.frontmatter, key, &target)?;
598 format!("{}{}{}", parts.pre, new_fm, parts.post)
599 }
600 _ => self.format.save(&new_doc)?,
601 };
602 self.source = output;
603 self.value = new_doc;
604 Ok(())
605 }
606
607 fn set_base(&self) -> Value {
611 #[cfg(feature = "yaml")]
612 if self.value.is_null() && self.blank_yaml_document() {
613 return Value::Object(Default::default());
614 }
615 self.value.clone()
616 }
617
618 #[cfg(feature = "yaml")]
620 fn blank_yaml_document(&self) -> bool {
621 match self.format {
622 Format::Yaml => crate::document::format::yaml::is_blank_document(&self.source),
623 Format::YamlFrontmatter => crate::document::format::frontmatter::split(
624 &self.source,
625 crate::document::format::frontmatter::Delimiter::Dash,
626 )
627 .is_ok_and(|parts| crate::document::format::yaml::is_blank_document(parts.frontmatter)),
628 _ => false,
629 }
630 }
631
632 pub fn add(
641 &mut self,
642 key: &str,
643 slug: &str,
644 slug_field: &str,
645 fields: &[(String, Value)],
646 ) -> DocumentResult<()> {
647 self.ensure_writable("add")?;
648 let mut value = self.value.clone();
649 let keyed_lists = [KeyedList {
650 prefix: key,
651 slug_field,
652 }];
653 crate::document::add_keyed(&mut value, key, slug, &keyed_lists, None, fields)?;
654 let array = if key.is_empty() {
655 &value
656 } else {
657 crate::document::get_path_ref(&value, key, self.addressing_keyed(&keyed_lists))?
658 };
659 let item = array
660 .as_array()
661 .and_then(|items| items.last())
662 .ok_or_else(|| DocumentError::UnsupportedOperation {
663 format: self.format.name().to_string(),
664 operation: "add".to_string(),
665 detail: "keyed list did not produce an array item".to_string(),
666 })?;
667 #[allow(unreachable_patterns)]
671 let output: String = match self.format {
672 Format::Json => crate::document::format::json::append_array_item_preserving(
673 &self.source,
674 key,
675 item,
676 )?,
677 #[cfg(feature = "yaml")]
678 Format::Yaml => crate::document::format::yaml::append_array_item_preserving(
679 &self.source,
680 key,
681 item,
682 )?,
683 #[cfg(feature = "yaml")]
688 Format::YamlFrontmatter => {
689 let parts = crate::document::format::frontmatter::split(
690 &self.source,
691 crate::document::format::frontmatter::Delimiter::Dash,
692 )?;
693 let new_fm = crate::document::format::yaml::append_array_item_preserving(
694 parts.frontmatter,
695 key,
696 item,
697 )?;
698 format!("{}{}{}", parts.pre, new_fm, parts.post)
699 }
700 _ => {
701 return Err(DocumentError::UnsupportedOperation {
702 format: self.format.name().to_string(),
703 operation: "add".to_string(),
704 detail: "keyed collection source editor is not implemented for this backend"
705 .to_string(),
706 });
707 }
708 };
709 self.source = output;
710 self.value = value;
711 Ok(())
712 }
713
714 pub fn remove(&mut self, key: &str, slug: &str, slug_field: &str) -> DocumentResult<()> {
722 self.ensure_writable("remove")?;
723 let mut value = self.value.clone();
724 let keyed_lists = [KeyedList {
725 prefix: key,
726 slug_field,
727 }];
728 let removed_index = crate::document::remove_keyed(&mut value, key, slug, &keyed_lists)?;
729 #[allow(unreachable_patterns)]
733 let output: String = match self.format {
734 Format::Json => crate::document::format::json::remove_array_item_preserving(
735 &self.source,
736 key,
737 removed_index,
738 )?,
739 #[cfg(feature = "yaml")]
740 Format::Yaml => crate::document::format::yaml::remove_array_item_preserving(
741 &self.source,
742 key,
743 removed_index,
744 )?,
745 #[cfg(feature = "yaml")]
746 Format::YamlFrontmatter => {
747 let parts = crate::document::format::frontmatter::split(
748 &self.source,
749 crate::document::format::frontmatter::Delimiter::Dash,
750 )?;
751 let new_fm = crate::document::format::yaml::remove_array_item_preserving(
752 parts.frontmatter,
753 key,
754 removed_index,
755 )?;
756 format!("{}{}{}", parts.pre, new_fm, parts.post)
757 }
758 _ => {
759 return Err(DocumentError::UnsupportedOperation {
760 format: self.format.name().to_string(),
761 operation: "remove".to_string(),
762 detail: "keyed collection source editor is not implemented for this backend"
763 .to_string(),
764 });
765 }
766 };
767 self.source = output;
768 self.value = value;
769 Ok(())
770 }
771
772 pub fn unset(&mut self, key: &str) -> DocumentResult<bool> {
797 let addressing = self.addressing();
798 self.unset_addressed(key, addressing)
799 }
800
801 pub fn unset_addressed(
806 &mut self,
807 key: &str,
808 addressing: Addressing<'_>,
809 ) -> DocumentResult<bool> {
810 self.ensure_writable("unset")?;
811 let key = &crate::document::resolve_path(&self.value, key, addressing)?;
812 let segments = crate::document::parse_path(key)?;
813 let (leaf, parents) = segments.split_last().ok_or(DocumentError::EmptyPath)?;
814 let parent = if parents.is_empty() {
815 &self.value
816 } else {
817 let parent_path = crate::document::join_path(parents);
818 match crate::document::get_path_ref(&self.value, &parent_path, Addressing::INDEX_ONLY) {
819 Ok(parent) => parent,
820 Err(DocumentError::UnknownSegment { .. }) => return Ok(false),
822 Err(error) => return Err(error),
823 }
824 };
825 match parent {
826 Value::Object(object) => {
827 if !object.contains_key(leaf) {
828 return Ok(false);
829 }
830 }
831 Value::Array(_) if leaf == "-" => {
832 return Err(crate::document::append_position_refused(parents, true));
833 }
834 Value::Array(array) => {
835 let index =
836 leaf.parse::<usize>()
837 .map_err(|_| DocumentError::UnregisteredArray {
838 path: crate::document::join_path(parents),
839 })?;
840 if index >= array.len() {
841 return Err(DocumentError::IndexOutOfBounds {
842 path: crate::document::join_path(parents),
843 index,
844 len: array.len(),
845 });
846 }
847 }
848 value => {
849 return Err(DocumentError::NotTraversable {
850 path: crate::document::join_path(parents),
851 got: value.kind_name().to_string(),
852 });
853 }
854 }
855 let mut value = self.value.clone();
856 crate::document::unset_path(&mut value, key)?;
857 #[allow(unreachable_patterns)]
858 let output = match self.format {
859 Format::Json => crate::document::format::json::unset_preserving(&self.source, key)?,
860 #[cfg(feature = "toml")]
861 Format::Toml => crate::document::format::toml::unset_preserving(&self.source, key)?,
862 #[cfg(feature = "yaml")]
863 Format::Yaml => crate::document::format::yaml::unset_preserving(&self.source, key)?,
864 #[cfg(feature = "dotenv")]
865 Format::Dotenv => crate::document::format::dotenv::unset_preserving(&self.source, key)?,
866 #[cfg(feature = "ini")]
867 Format::Ini => crate::document::format::ini::unset_preserving(&self.source, key)?,
868 #[cfg(feature = "toml")]
869 Format::TomlFrontmatter => {
870 let parts = crate::document::format::frontmatter::split(
871 &self.source,
872 crate::document::format::frontmatter::Delimiter::Plus,
873 )?;
874 let new_fm =
875 crate::document::format::toml::unset_preserving(parts.frontmatter, key)?;
876 format!("{}{}{}", parts.pre, new_fm, parts.post)
877 }
878 #[cfg(feature = "yaml")]
879 Format::YamlFrontmatter => {
880 let parts = crate::document::format::frontmatter::split(
881 &self.source,
882 crate::document::format::frontmatter::Delimiter::Dash,
883 )?;
884 let new_fm =
885 crate::document::format::yaml::unset_preserving(parts.frontmatter, key)?;
886 format!("{}{}{}", parts.pre, new_fm, parts.post)
887 }
888 _ => self.format.save(&value)?,
889 };
890 self.source = output;
891 self.value = value;
892 Ok(true)
893 }
894}
895
896impl DocumentFile {
897 pub fn edit<F>(&mut self, edit: F) -> DocumentResult<()>
904 where
905 F: FnOnce(&mut Document) -> DocumentResult<()>,
906 {
907 let mut draft = self.doc.clone();
908 edit(&mut draft)?;
909 self.save_document(&draft)?;
910 self.doc = draft;
911 Ok(())
912 }
913
914 pub fn edit_and_validate<T>(
925 &mut self,
926 edit: impl FnOnce(&mut Document) -> DocumentResult<()>,
927 ) -> DocumentResult<T>
928 where
929 T: serde::de::DeserializeOwned,
930 {
931 let mut draft = self.doc.clone();
932 edit(&mut draft)?;
933 let decoded = draft.decode::<T>()?;
934 self.save_document(&draft)?;
935 self.doc = draft;
936 Ok(decoded)
937 }
938
939 pub fn edit_and_validate_with<T>(
942 &mut self,
943 options: CreateOptions,
944 edit: impl FnOnce(&mut Document) -> DocumentResult<()>,
945 ) -> DocumentResult<T>
946 where
947 T: serde::de::DeserializeOwned,
948 {
949 let mut draft = self.doc.clone();
950 edit(&mut draft)?;
951 let decoded = draft.decode::<T>()?;
952 *self = Self::create_atomic(&self.path, draft, options.replace())?;
953 Ok(decoded)
954 }
955
956 pub fn save(&self) -> DocumentResult<()> {
970 self.save_atomic(self.doc.source())
971 }
972
973 pub(crate) fn save_atomic(&self, new_source: &str) -> DocumentResult<()> {
986 self.ensure_writable("save")?;
990 validate_source_text_for_write(new_source, self.format)?;
997 write_atomic(&self.path, new_source.as_bytes(), "write")
998 }
999
1000 fn save_document(&self, document: &Document) -> DocumentResult<()> {
1001 document.ensure_writable("save")?;
1002 validate_source_for_write(document)?;
1003 write_atomic(&self.path, document.source().as_bytes(), "write")
1004 }
1005}
1006
1007impl std::ops::Deref for DocumentFile {
1008 type Target = Document;
1009
1010 fn deref(&self) -> &Document {
1011 &self.doc
1012 }
1013}
1014
1015impl std::ops::DerefMut for DocumentFile {
1016 fn deref_mut(&mut self) -> &mut Document {
1017 &mut self.doc
1018 }
1019}
1020
1021fn resolve_format(path: &Path, format_override: Option<Format>) -> DocumentResult<Format> {
1022 match format_override {
1023 Some(format) => Ok(format),
1024 None => match Format::detect(path) {
1029 Some(format) => Ok(format),
1030 None => Err(match Format::unavailable(path) {
1031 Some(feature) => DocumentError::UnsupportedOperation {
1032 format: feature.to_string(),
1033 operation: "open".to_string(),
1034 detail: format!("requires Cargo feature `{feature}`"),
1035 },
1036 None => DocumentError::FormatUnknown {
1037 path: path.display().to_string(),
1038 },
1039 }),
1040 },
1041 }
1042}
1043
1044fn validate_source_for_write(document: &Document) -> DocumentResult<()> {
1045 validate_source_text_for_write(document.source(), document.format())
1046}
1047
1048fn validate_source_text_for_write(source: &str, format: Format) -> DocumentResult<()> {
1049 Document::parse(source, format).map_err(|error| DocumentError::WriteWouldCorrupt {
1050 format: format.name().to_string(),
1051 detail: error.redacted_message(),
1052 })?;
1053 Ok(())
1054}
1055
1056fn validate_create_options(options: CreateOptions) -> DocumentResult<()> {
1057 crate::atomic_file::validate_unix_mode(options.unix_mode).map_err(|error| {
1058 DocumentError::InvalidArgument {
1059 detail: error.to_string(),
1060 }
1061 })
1062}
1063
1064#[cfg(test)]
1065mod tests {
1066 #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
1067 use super::*;
1068 use std::io::Cursor;
1069
1070 fn write_temp(dir: &Path, name: &str, contents: &str) -> PathBuf {
1071 let path = dir.join(name);
1072 fs::write(&path, contents).unwrap();
1073 path
1074 }
1075
1076 #[test]
1077 fn round_trip_open_json() {
1078 let dir = tempfile::tempdir().unwrap();
1079 let contents = r#"{"host": "example.com", "port": 993}"#;
1080 let path = write_temp(dir.path(), "config.json", contents);
1081
1082 let doc = DocumentFile::open(&path, None).unwrap();
1083
1084 assert_eq!(doc.format(), Format::Json);
1085 assert_eq!(
1086 doc.value().get("host").and_then(Value::as_str),
1087 Some("example.com")
1088 );
1089 assert_eq!(doc.source(), contents);
1090 }
1091
1092 #[test]
1093 fn value_at_reads_a_nested_address() {
1094 let dir = tempfile::tempdir().unwrap();
1095 let path = write_temp(
1096 dir.path(),
1097 "config.json",
1098 r#"{"database": {"url": "postgres://x"}}"#,
1099 );
1100 let doc = DocumentFile::open(&path, None).unwrap();
1101
1102 assert_eq!(
1103 doc.value_at("database.url").unwrap(),
1104 Value::String("postgres://x".to_string())
1105 );
1106 assert_eq!(
1107 doc.value_at("database.missing").unwrap_err().code(),
1108 "document_path_not_found"
1109 );
1110 }
1111
1112 #[test]
1113 fn open_capped_enforces_size_and_regular_file() {
1114 let dir = tempfile::tempdir().unwrap();
1115 let path = write_temp(dir.path(), "config.json", r#"{"k": "v"}"#);
1116
1117 assert!(DocumentFile::open_capped(&path, None, 1024).is_ok());
1119
1120 let err = DocumentFile::open_capped(&path, None, 4).unwrap_err();
1123 assert_eq!(err.code(), "document_too_large");
1124
1125 let dir_err = DocumentFile::open_capped(dir.path(), Some(Format::Json), 1024).unwrap_err();
1127 assert_eq!(dir_err.code(), "document_io_failed");
1128
1129 let missing =
1131 DocumentFile::open_capped(dir.path().join("absent.json"), None, 1024).unwrap_err();
1132 assert_ne!(missing.code(), "document_too_large");
1133 }
1134
1135 #[cfg(unix)]
1136 #[test]
1137 fn capped_read_uses_the_open_handle_when_the_path_is_replaced() {
1138 let dir = tempfile::tempdir().unwrap();
1139 let original = r#"{"source":"original"}"#;
1140 let path = write_temp(dir.path(), "config.json", original);
1141 let handle = open_read_handle(&path, SymlinkPolicy::Follow).unwrap();
1142 inspect_capped_source(&handle, &path, 64).unwrap();
1143
1144 fs::rename(&path, dir.path().join("original.json")).unwrap();
1145 fs::write(&path, r#"{"source":"replacement"}"#).unwrap();
1146
1147 let source = read_capped_contents(handle, &path, 64).unwrap();
1148 assert_eq!(source, original);
1149 }
1150
1151 #[cfg(unix)]
1152 #[test]
1153 fn capped_read_rechecks_the_actual_bytes_after_metadata() {
1154 use std::io::Write as _;
1155
1156 let dir = tempfile::tempdir().unwrap();
1157 let path = write_temp(dir.path(), "config.json", "{}");
1158 let handle = open_read_handle(&path, SymlinkPolicy::Follow).unwrap();
1159 inspect_capped_source(&handle, &path, 4).unwrap();
1160
1161 let mut writer = OpenOptions::new().append(true).open(&path).unwrap();
1162 writer.write_all(b"123").unwrap();
1163 writer.sync_all().unwrap();
1164
1165 let error = read_capped_contents(handle, &path, 4).unwrap_err();
1166 assert_eq!(error.code(), "document_too_large");
1167 }
1168
1169 #[cfg(all(unix, feature = "libc"))]
1170 #[test]
1171 fn open_capped_can_atomically_refuse_a_symlink() {
1172 let dir = tempfile::tempdir().unwrap();
1173 let target = write_temp(dir.path(), "target.json", r#"{"k": "v"}"#);
1174 let link = dir.path().join("link.json");
1175 std::os::unix::fs::symlink(&target, &link).unwrap();
1176
1177 assert!(
1178 DocumentFile::open_capped_with_policy(&link, None, 1024, SymlinkPolicy::Follow).is_ok()
1179 );
1180 let error =
1181 DocumentFile::open_capped_with_policy(&link, None, 1024, SymlinkPolicy::NoFollow)
1182 .unwrap_err();
1183 assert_eq!(error.code(), "document_io_failed");
1184 }
1185
1186 #[test]
1187 fn create_atomic_is_no_clobber_and_returns_a_file_handle() {
1188 let dir = tempfile::tempdir().unwrap();
1189 let path = dir.path().join("config.json");
1190 let document = Document::parse(r#"{"port": 993}"#, Format::Json).unwrap();
1191
1192 let created = DocumentFile::create_atomic(&path, document, CreateOptions::new()).unwrap();
1193 assert_eq!(created.path(), path);
1194 assert_eq!(fs::read_to_string(&path).unwrap(), r#"{"port": 993}"#);
1195
1196 let replacement = Document::parse(r#"{"port": 1024}"#, Format::Json).unwrap();
1197 let error =
1198 DocumentFile::create_atomic(&path, replacement, CreateOptions::new()).unwrap_err();
1199 assert_eq!(error.code(), "document_target_exists");
1200 assert_eq!(fs::read_to_string(&path).unwrap(), r#"{"port": 993}"#);
1201 }
1202
1203 #[test]
1204 fn create_atomic_requires_explicit_replace() {
1205 let dir = tempfile::tempdir().unwrap();
1206 let path = write_temp(dir.path(), "config.json", r#"{"port": 993}"#);
1207 let replacement = Document::parse(r#"{"port": 1024}"#, Format::Json).unwrap();
1208
1209 let created =
1210 DocumentFile::create_atomic(&path, replacement, CreateOptions::new().replace())
1211 .unwrap();
1212
1213 assert_eq!(created.value_at("port").unwrap(), Value::Integer(1024));
1214 assert_eq!(fs::read_to_string(&path).unwrap(), r#"{"port": 1024}"#);
1215 }
1216
1217 #[cfg(unix)]
1222 #[test]
1223 fn create_atomic_replace_preserves_the_targets_mode_unless_told_otherwise() {
1224 use std::os::unix::fs::PermissionsExt as _;
1225
1226 let dir = tempfile::tempdir().unwrap();
1227 let mode_of = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777;
1228
1229 for original in [0o644, 0o600, 0o640] {
1230 let path = write_temp(dir.path(), &format!("m{original:o}.json"), r#"{"a": 1}"#);
1231 fs::set_permissions(&path, fs::Permissions::from_mode(original)).unwrap();
1232 let replacement = Document::parse(r#"{"a": 2}"#, Format::Json).unwrap();
1233 DocumentFile::create_atomic(&path, replacement, CreateOptions::new().replace())
1234 .unwrap();
1235 assert_eq!(
1236 mode_of(&path),
1237 original,
1238 "replace must keep the file's mode"
1239 );
1240 }
1241
1242 let path = write_temp(dir.path(), "explicit.json", r#"{"a": 1}"#);
1244 fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
1245 let replacement = Document::parse(r#"{"a": 2}"#, Format::Json).unwrap();
1246 DocumentFile::create_atomic(
1247 &path,
1248 replacement,
1249 CreateOptions::new().replace().unix_mode(0o600),
1250 )
1251 .unwrap();
1252 assert_eq!(mode_of(&path), 0o600);
1253
1254 let fresh = dir.path().join("fresh.json");
1256 let document = Document::parse(r#"{"a": 1}"#, Format::Json).unwrap();
1257 DocumentFile::create_atomic(&fresh, document, CreateOptions::new()).unwrap();
1258 assert_eq!(mode_of(&fresh), 0o600);
1259 }
1260
1261 #[cfg(feature = "toml")]
1265 #[test]
1266 fn create_atomic_refuses_a_document_the_path_could_not_reopen() {
1267 let dir = tempfile::tempdir().unwrap();
1268 let path = dir.path().join("mismatch.toml");
1269 let document = Document::parse(r#"{"port": 993}"#, Format::Json).unwrap();
1270
1271 let error = DocumentFile::create_atomic(&path, document, CreateOptions::new()).unwrap_err();
1272
1273 assert_eq!(error.code(), "document_unsupported_operation");
1274 assert!(
1275 !path.exists(),
1276 "nothing may be written when the check fails"
1277 );
1278 }
1279
1280 #[cfg(unix)]
1281 #[test]
1282 fn create_atomic_applies_requested_private_mode() {
1283 use std::os::unix::fs::PermissionsExt as _;
1284
1285 let dir = tempfile::tempdir().unwrap();
1286 let path = dir.path().join("config.json");
1287 let document = Document::parse(r#"{"port": 993}"#, Format::Json).unwrap();
1288
1289 DocumentFile::create_atomic(&path, document, CreateOptions::new().unix_mode(0o640))
1290 .unwrap();
1291
1292 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
1293 assert_eq!(mode, 0o640);
1294 }
1295
1296 #[test]
1297 fn create_atomic_rejects_invalid_permission_bits_before_writing() {
1298 let dir = tempfile::tempdir().unwrap();
1299 let path = dir.path().join("config.json");
1300 let document = Document::parse(r#"{"port": 993}"#, Format::Json).unwrap();
1301
1302 let error =
1303 DocumentFile::create_atomic(&path, document, CreateOptions::new().unix_mode(0o1600))
1304 .unwrap_err();
1305
1306 assert_eq!(error.code(), "document_invalid_argument");
1307 assert!(!path.exists());
1308 }
1309
1310 #[cfg(unix)]
1311 #[test]
1312 fn create_atomic_replace_refuses_symlinks_and_hardlinks() {
1313 let dir = tempfile::tempdir().unwrap();
1314 let target = write_temp(dir.path(), "target.json", r#"{"port": 993}"#);
1315 let symlink = dir.path().join("symlink.json");
1316 std::os::unix::fs::symlink(&target, &symlink).unwrap();
1317 let replacement = Document::parse(r#"{"port": 1024}"#, Format::Json).unwrap();
1318
1319 let symlink_error = DocumentFile::create_atomic(
1320 &symlink,
1321 replacement.clone(),
1322 CreateOptions::new().replace(),
1323 )
1324 .unwrap_err();
1325 assert_eq!(symlink_error.code(), "document_unsupported_operation");
1326 assert_eq!(fs::read_to_string(&target).unwrap(), r#"{"port": 993}"#);
1327
1328 let hardlink = dir.path().join("hardlink.json");
1329 fs::hard_link(&target, &hardlink).unwrap();
1330 let hardlink_error =
1331 DocumentFile::create_atomic(&hardlink, replacement, CreateOptions::new().replace())
1332 .unwrap_err();
1333 assert_eq!(hardlink_error.code(), "document_unsupported_operation");
1334 assert_eq!(fs::read_to_string(&target).unwrap(), r#"{"port": 993}"#);
1335 }
1336
1337 #[cfg(unix)]
1338 #[test]
1339 fn create_atomic_replace_refuses_a_dangling_symlink() {
1340 let dir = tempfile::tempdir().unwrap();
1341 let missing = dir.path().join("missing.json");
1342 let symlink = dir.path().join("dangling.json");
1343 std::os::unix::fs::symlink(&missing, &symlink).unwrap();
1344 let replacement = Document::parse(r#"{"port": 1024}"#, Format::Json).unwrap();
1345
1346 let error =
1347 DocumentFile::create_atomic(&symlink, replacement, CreateOptions::new().replace())
1348 .unwrap_err();
1349
1350 assert_eq!(error.code(), "document_unsupported_operation");
1351 assert!(
1352 fs::symlink_metadata(&symlink)
1353 .unwrap()
1354 .file_type()
1355 .is_symlink()
1356 );
1357 assert!(!missing.exists());
1358 }
1359
1360 #[test]
1361 fn edit_rolls_back_memory_and_disk_when_the_closure_fails() {
1362 let dir = tempfile::tempdir().unwrap();
1363 let original = r#"{"port": 993}"#;
1364 let path = write_temp(dir.path(), "config.json", original);
1365 let mut document = DocumentFile::open(&path, None).unwrap();
1366
1367 let error = document
1368 .edit(|draft| {
1369 draft.set("port", Value::Integer(1024))?;
1370 Err(DocumentError::InvalidArgument {
1371 detail: "validation failed".to_string(),
1372 })
1373 })
1374 .unwrap_err();
1375
1376 assert_eq!(error.code(), "document_invalid_argument");
1377 assert_eq!(document.source(), original);
1378 assert_eq!(document.value_at("port").unwrap(), Value::Integer(993));
1379 assert_eq!(fs::read_to_string(&path).unwrap(), original);
1380 }
1381
1382 #[test]
1383 fn typed_get_and_set_enforce_the_stated_type() {
1384 use crate::document::ValueType;
1385 let dir = tempfile::tempdir().unwrap();
1386 let path = write_temp(dir.path(), "config.json", r#"{"port": 8080, "host": "x"}"#);
1387 let mut doc = DocumentFile::open(&path, None).unwrap();
1388
1389 assert!(doc.value_at_typed("port", ValueType::Number).is_ok());
1392 assert_eq!(
1393 doc.value_at_typed("port", ValueType::String)
1394 .unwrap_err()
1395 .code(),
1396 "document_type_mismatch"
1397 );
1398 assert!(doc.value_at_typed("host", ValueType::Json).is_ok());
1399
1400 doc.set_typed("port", Some("9090"), ValueType::Number)
1402 .unwrap();
1403 assert_eq!(
1404 doc.value_at("port").unwrap(),
1405 Value::from(serde_json::json!(9090))
1406 );
1407 assert_eq!(
1408 doc.set_typed("port", Some("not-a-number"), ValueType::Number)
1409 .unwrap_err()
1410 .code(),
1411 "document_parse_failed"
1412 );
1413 }
1414
1415 #[test]
1416 fn decode_and_edit_and_validate_share_one_typed_boundary() {
1417 #[derive(Debug, serde::Deserialize)]
1418 #[serde(deny_unknown_fields)]
1419 struct Config {
1420 port: u16,
1421 }
1422
1423 let dir = tempfile::tempdir().unwrap();
1424 let original = r#"{"port": 8080}"#;
1425 let path = write_temp(dir.path(), "config.json", original);
1426 let mut document = DocumentFile::open(&path, None).unwrap();
1427
1428 assert_eq!(document.decode::<Config>().unwrap().port, 8080);
1429
1430 let error = document
1431 .edit_and_validate::<Config>(|draft| {
1432 draft.set("port", Value::String("invalid".to_string()))
1433 })
1434 .unwrap_err();
1435 assert_eq!(error.code(), "document_type_mismatch");
1436 assert_eq!(document.source(), original);
1437 assert_eq!(fs::read_to_string(&path).unwrap(), original);
1438
1439 let config = document
1440 .edit_and_validate::<Config>(|draft| draft.set("port", Value::Unsigned(9090)))
1441 .unwrap();
1442 assert_eq!(config.port, 9090);
1443 assert_eq!(document.value_at("port").unwrap(), Value::Unsigned(9090));
1444 }
1445
1446 #[cfg(feature = "toml")]
1447 #[test]
1448 fn round_trip_open_toml() {
1449 let dir = tempfile::tempdir().unwrap();
1450 let contents = "# leading comment\nhost = \"example.com\"\nport = 993\n";
1451 let path = write_temp(dir.path(), "config.toml", contents);
1452
1453 let doc = DocumentFile::open(&path, None).unwrap();
1454
1455 assert_eq!(doc.format(), Format::Toml);
1456 assert_eq!(
1457 doc.value().get("host").and_then(Value::as_str),
1458 Some("example.com")
1459 );
1460 assert_eq!(doc.source(), contents);
1461 }
1462
1463 #[cfg(feature = "toml")]
1464 #[test]
1465 fn set_scalar_preserves_toml_comments_and_formatting() {
1466 let dir = tempfile::tempdir().unwrap();
1467 let contents = "# leading comment\nhost = \"example.com\"\nport = 993 # inline comment\n";
1468 let path = write_temp(dir.path(), "config.toml", contents);
1469 let mut doc = DocumentFile::open(&path, None).unwrap();
1470
1471 doc.set("port", Value::Integer(1024)).unwrap();
1472 doc.save().unwrap();
1473
1474 let saved = fs::read_to_string(&path).unwrap();
1475 assert!(saved.contains("# leading comment"));
1476 assert!(saved.contains("port = 1024"));
1477 assert_eq!(
1478 doc.value().get("port").and_then(Value::as_integer),
1479 Some(1024)
1480 );
1481 assert_eq!(doc.source(), saved);
1482 }
1483
1484 #[cfg(feature = "toml")]
1489 #[test]
1490 fn toml_array_edits_never_invent_or_misattribute_a_comment() {
1491 let contents = "paths = [\n \"one\", # first\n \"two\", # second\n]\n";
1492
1493 let mut grown = Document::parse(contents, Format::Toml).unwrap();
1494 grown
1495 .set(
1496 "paths",
1497 Value::Array(vec![
1498 Value::String("a".into()),
1499 Value::String("b".into()),
1500 Value::String("c".into()),
1501 ]),
1502 )
1503 .unwrap();
1504 assert_eq!(
1505 grown.source(),
1506 "paths = [\n \"a\", # first\n \"b\", # second\n \"c\",\n]\n",
1507 "an appended element must carry no comment of its own"
1508 );
1509
1510 let mut shrunk = Document::parse(contents, Format::Toml).unwrap();
1511 shrunk
1512 .set("paths", Value::Array(vec![Value::String("only".into())]))
1513 .unwrap();
1514 assert_eq!(
1515 shrunk.source(),
1516 "paths = [\n \"only\", # first\n]\n",
1517 "the surviving element keeps its own comment, not the removed one's"
1518 );
1519
1520 let mut replaced = Document::parse(contents, Format::Toml).unwrap();
1522 replaced
1523 .set(
1524 "paths",
1525 Value::Array(vec![Value::String("x".into()), Value::String("y".into())]),
1526 )
1527 .unwrap();
1528 assert_eq!(
1529 replaced.source(),
1530 "paths = [\n \"x\", # first\n \"y\", # second\n]\n"
1531 );
1532
1533 let mut inline = Document::parse("paths = [ \"one\" ]\n", Format::Toml).unwrap();
1535 inline
1536 .set(
1537 "paths",
1538 Value::Array(vec![
1539 Value::String("one".into()),
1540 Value::String("two".into()),
1541 ]),
1542 )
1543 .unwrap();
1544 assert_eq!(inline.source(), "paths = [ \"one\", \"two\" ]\n");
1545 }
1546
1547 #[cfg(feature = "toml")]
1548 #[test]
1549 fn set_toml_array_preserves_single_line_decor() {
1550 let contents = "# before\npaths = [ \"old\", 'second', ] # keep this\nother = 42\n";
1551 let mut document = Document::parse(contents, Format::Toml).unwrap();
1552
1553 document
1554 .set(
1555 "paths",
1556 Value::Array(vec![
1557 Value::String("new".to_string()),
1558 Value::String("next".to_string()),
1559 ]),
1560 )
1561 .unwrap();
1562
1563 assert_eq!(
1564 document.source(),
1565 "# before\npaths = [ \"new\", \"next\", ] # keep this\nother = 42\n"
1566 );
1567 }
1568
1569 #[cfg(feature = "toml")]
1570 #[test]
1571 fn set_toml_array_preserves_multiline_comments_and_trailing_comma() {
1572 let contents = "paths = [\n \"one\", # first\n \"two\", # second\n]\nother = 42\n";
1573 let mut document = Document::parse(contents, Format::Toml).unwrap();
1574
1575 document
1576 .set(
1577 "paths",
1578 Value::Array(vec![
1579 Value::String("uno".to_string()),
1580 Value::String("dos".to_string()),
1581 ]),
1582 )
1583 .unwrap();
1584
1585 assert_eq!(
1586 document.source(),
1587 "paths = [\n \"uno\", # first\n \"dos\", # second\n]\nother = 42\n"
1588 );
1589 }
1590
1591 #[cfg(feature = "toml")]
1592 #[test]
1593 fn set_toml_array_element_preserves_its_neighbors() {
1594 let contents = "paths = [\n \"one\", # first\n \"two\", # second\n]\n";
1595 let mut document = Document::parse(contents, Format::Toml).unwrap();
1596
1597 document
1598 .set("paths.1", Value::String("changed".to_string()))
1599 .unwrap();
1600
1601 assert_eq!(
1602 document.source(),
1603 "paths = [\n \"one\", # first\n \"changed\", # second\n]\n"
1604 );
1605 }
1606
1607 #[cfg(feature = "toml")]
1608 #[test]
1609 fn set_toml_array_can_become_empty_without_touching_neighbors() {
1610 let contents = "before = 1\npaths = [ \"one\", ] # list\nafter = 2\n";
1611 let mut document = Document::parse(contents, Format::Toml).unwrap();
1612
1613 document.set("paths", Value::Array(Vec::new())).unwrap();
1614
1615 assert_eq!(
1616 document.source(),
1617 "before = 1\npaths = [ ] # list\nafter = 2\n"
1618 );
1619 }
1620
1621 #[cfg(feature = "toml")]
1622 #[test]
1623 fn set_toml_inline_table_preserves_layout_and_comments() {
1624 let contents = "cache = { ttl_s = 1, enabled = true } # cache\nother = 42\n";
1625 let mut document = Document::parse(contents, Format::Toml).unwrap();
1626 let replacement = Value::from(serde_json::json!({
1627 "enabled": false,
1628 "ttl_s": 60
1629 }));
1630
1631 document.set("cache", replacement).unwrap();
1632
1633 assert_eq!(
1634 document.source(),
1635 "cache = { ttl_s = 60, enabled = false } # cache\nother = 42\n"
1636 );
1637 }
1638
1639 #[cfg(feature = "toml")]
1640 #[test]
1641 fn set_toml_ordinary_table_preserves_header_and_unrelated_section() {
1642 let contents = "# lead\n[cache] # cache header\nttl_s = 1 # ttl\nenabled = true\n\n[next]\nvalue = 9\n";
1643 let mut document = Document::parse(contents, Format::Toml).unwrap();
1644 let replacement = Value::from(serde_json::json!({
1645 "enabled": false,
1646 "ttl_s": 60
1647 }));
1648
1649 document.set("cache", replacement).unwrap();
1650
1651 assert_eq!(
1652 document.source(),
1653 "# lead\n[cache] # cache header\nttl_s = 60 # ttl\nenabled = false\n\n[next]\nvalue = 9\n"
1654 );
1655 }
1656
1657 #[cfg(feature = "toml")]
1658 #[test]
1659 fn set_toml_collection_preserves_unchanged_datetime_syntax() {
1660 let contents = "[cache]\nexpires_at = 2026-08-04T12:30:00Z\npaths = [\"one\"]\n";
1661 let mut document = Document::parse(contents, Format::Toml).unwrap();
1662 let replacement = document.value_at("cache").unwrap();
1663
1664 document.set("cache", replacement).unwrap();
1665
1666 assert_eq!(document.source(), contents);
1667 }
1668
1669 #[cfg(feature = "toml")]
1670 #[test]
1671 fn set_toml_array_of_tables_is_explicitly_refused() {
1672 let contents = "[[servers]]\nname = \"one\"\n[[servers]]\nname = \"two\"\n";
1673 let mut document = Document::parse(contents, Format::Toml).unwrap();
1674 let replacement = document.value_at("servers").unwrap();
1675
1676 let error = document.set("servers", replacement).unwrap_err();
1677
1678 assert_eq!(error.code(), "document_unsupported_operation");
1679 assert_eq!(document.source(), contents);
1680 }
1681
1682 #[cfg(feature = "ini")]
1683 #[test]
1684 fn save_refuses_source_its_own_parser_rejects() {
1685 let dir = tempfile::tempdir().unwrap();
1689 let original = "[db]\nhost=localhost\n";
1690 let path = write_temp(dir.path(), "config.ini", original);
1691 let doc = DocumentFile::open(&path, None).unwrap();
1692
1693 let error = doc
1694 .save_atomic("[db]\nhost=localhost\n\n[db]\nport=5432\n")
1695 .unwrap_err();
1696 assert_eq!(error.code(), "document_write_would_corrupt");
1697 assert_eq!(fs::read_to_string(&path).unwrap(), original);
1699 }
1700
1701 #[cfg(feature = "ini")]
1702 #[test]
1703 fn save_writes_source_the_parser_accepts() {
1704 let dir = tempfile::tempdir().unwrap();
1705 let path = write_temp(dir.path(), "config.ini", "[db]\nhost=localhost\n");
1706 let mut doc = DocumentFile::open(&path, None).unwrap();
1707
1708 doc.set("db.port", Value::String("5432".to_string()))
1709 .unwrap();
1710 doc.save().unwrap();
1711
1712 assert_eq!(
1715 fs::read_to_string(&path).unwrap(),
1716 "[db]\nhost=localhost\nport=5432\n"
1717 );
1718 assert!(DocumentFile::open(&path, None).is_ok());
1719 }
1720
1721 #[cfg(unix)]
1722 #[test]
1723 fn atomic_save_preserves_file_mode() {
1724 use std::os::unix::fs::PermissionsExt;
1725
1726 let dir = tempfile::tempdir().unwrap();
1727 let path = write_temp(dir.path(), "config.json", r#"{"port": 993}"#);
1728 fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap();
1729 let mut doc = DocumentFile::open(&path, None).unwrap();
1730
1731 doc.set("port", Value::Integer(1024)).unwrap();
1732 doc.save().unwrap();
1733
1734 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
1735 assert_eq!(mode, 0o640);
1736 }
1737
1738 #[cfg(unix)]
1739 #[test]
1740 fn symlink_target_is_rejected_for_mutation() {
1741 let dir = tempfile::tempdir().unwrap();
1742 let target = write_temp(dir.path(), "target.json", r#"{"port": 993}"#);
1743 let link = dir.path().join("link.json");
1744 std::os::unix::fs::symlink(&target, &link).unwrap();
1745
1746 let mut doc = DocumentFile::open(&link, None).unwrap();
1748
1749 doc.set("port", Value::Integer(1024)).unwrap();
1751 let err = doc.save().unwrap_err();
1752 assert!(matches!(err, DocumentError::UnsupportedOperation { .. }));
1753
1754 let target_contents = fs::read_to_string(&target).unwrap();
1756 assert_eq!(target_contents, r#"{"port": 993}"#);
1757 }
1758
1759 #[test]
1760 fn from_reader_parses_in_memory_cursor() {
1761 let cursor = Cursor::new(br#"{"host": "example.com"}"#.to_vec());
1762
1763 let doc = Document::from_reader(cursor, Format::Json).unwrap();
1764
1765 assert_eq!(
1766 doc.value().get("host").and_then(Value::as_str),
1767 Some("example.com")
1768 );
1769 }
1770
1771 #[test]
1772 fn document_from_str_encode_round_trip() {
1773 let doc = Document::parse(r#"{"a": 1}"#, Format::Json).unwrap();
1774 let encoded = doc.encode().unwrap();
1775 let reparsed = Document::parse(&encoded, Format::Json).unwrap();
1776 assert_eq!(
1777 reparsed.value().get("a").and_then(Value::as_integer),
1778 Some(1)
1779 );
1780 }
1781
1782 #[test]
1783 fn document_edits_source_in_memory_without_a_file() {
1784 let mut doc = Document::parse("{\n \"host\": \"old\"\n}\n", Format::Json).unwrap();
1787 doc.set("host", Value::String("new".to_string())).unwrap();
1788 doc.set("imap.port", Value::Integer(993)).unwrap(); assert_eq!(
1791 doc.source(),
1792 "{\n \"host\": \"new\",\n \"imap\": {\n \"port\": 993\n }\n}\n"
1793 );
1794 assert_eq!(
1795 doc.value_at("imap.port").unwrap(),
1796 Value::from(serde_json::json!(993))
1797 );
1798 }
1799
1800 #[test]
1801 fn unset_is_false_for_anything_already_absent() {
1802 let mut doc = Document::parse(
1803 r#"{"service":{"host":"example","ports":[80]}}"#,
1804 Format::Json,
1805 )
1806 .unwrap();
1807
1808 assert!(!doc.unset("service.missing").unwrap());
1811 assert!(!doc.unset("missing.parent").unwrap());
1812 assert!(!doc.unset("missing.deeply.nested").unwrap());
1813
1814 assert!(doc.unset("service.host.child").is_err()); assert!(doc.unset("service.ports.9").is_err()); assert!(doc.unset(r"service\q").is_err()); }
1820
1821 #[cfg(feature = "markdown")]
1822 #[test]
1823 fn every_markdown_write_verb_is_refused() {
1824 let source = "# Title\n\nThe lead.\n";
1825 let mut doc = Document::parse(source, Format::Markdown).unwrap();
1826
1827 assert_eq!(
1830 doc.value_at("h1.0.text").unwrap(),
1831 Value::String("Title".to_string())
1832 );
1833 assert_eq!(
1834 doc.value_at("h1.Tit.paragraph.0.text").unwrap(),
1835 Value::String("The lead.".to_string())
1836 );
1837
1838 let refusals: Vec<DocumentError> = vec![
1842 doc.set("h1.0.text", Value::String("New".to_string()))
1843 .unwrap_err(),
1844 doc.add("preamble", "x", "type", &[]).unwrap_err(),
1845 doc.remove("preamble", "x", "type").unwrap_err(),
1846 doc.unset("h1.0").unwrap_err(),
1847 doc.unset("nothing.here").unwrap_err(),
1848 doc.encode().unwrap_err(),
1849 ];
1850 for error in refusals {
1851 assert_eq!(error.code(), "document_unsupported_operation");
1852 assert!(
1853 error.to_string().contains("read-only"),
1854 "refusal must name the reason: {error}"
1855 );
1856 }
1857
1858 assert_eq!(doc.source(), source);
1860 }
1861
1862 #[cfg(feature = "markdown")]
1863 #[test]
1864 fn markdown_save_never_reaches_disk() {
1865 let dir = tempfile::tempdir().unwrap();
1866 let path = write_temp(dir.path(), "README.md", "# Title\n");
1867 assert!(DocumentFile::open(&path, None).is_err());
1869
1870 let doc = DocumentFile::open(&path, Some(Format::Markdown)).unwrap();
1871 let error = doc.save().unwrap_err();
1873 assert_eq!(error.code(), "document_unsupported_operation");
1874 assert_eq!(fs::read_to_string(&path).unwrap(), "# Title\n");
1875 }
1876
1877 #[cfg(feature = "yaml")]
1878 #[test]
1879 fn yaml_write_rejects_cst_ambiguous_mapping_segments() {
1880 let mut numeric = Document::parse("\"123\": value\n", Format::Yaml).unwrap();
1881 assert!(
1882 numeric
1883 .set("123", Value::String("changed".to_string()))
1884 .is_err()
1885 );
1886 assert!(numeric.unset("123").is_err());
1887
1888 let mut bracketed = Document::parse("\"a[0]\": value\n", Format::Yaml).unwrap();
1889 assert!(
1890 bracketed
1891 .set("a[0]", Value::String("changed".to_string()))
1892 .is_err()
1893 );
1894 }
1895}