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")]
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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
60pub enum SymlinkPolicy {
61 #[default]
63 Follow,
64 NoFollow,
68}
69
70#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
72pub enum CreateMode {
73 #[default]
75 NewOnly,
76 Replace,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct CreateOptions {
83 mode: CreateMode,
84 unix_mode: Option<u32>,
85}
86
87impl CreateOptions {
88 #[must_use]
93 pub const fn new() -> Self {
94 Self {
95 mode: CreateMode::NewOnly,
96 unix_mode: None,
97 }
98 }
99
100 #[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 #[must_use]
113 pub const fn replace(mut self) -> Self {
114 self.mode = CreateMode::Replace;
115 self
116 }
117
118 #[must_use]
120 pub const fn mode(&self) -> CreateMode {
121 self.mode
122 }
123
124 #[must_use]
129 pub const fn configured_unix_mode(&self) -> Option<u32> {
130 self.unix_mode
131 }
132
133 const fn effective_unix_mode(&self, target_exists: bool) -> Option<u32> {
135 match self.unix_mode {
136 Some(mode) => Some(mode),
137 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#[derive(Debug, Clone)]
161pub struct Document {
162 source: String,
163 value: Value,
164 format: Format,
165}
166
167impl Document {
168 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 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 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 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 #[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 pub fn value(&self) -> &Value {
268 &self.value
269 }
270
271 pub fn source(&self) -> &str {
275 &self.source
276 }
277
278 pub fn format(&self) -> Format {
280 self.format
281 }
282
283 #[must_use]
289 pub fn addressing(&self) -> Addressing<'static> {
290 Addressing::INDEX_ONLY.with_array_rule(self.format.array_rule())
291 }
292
293 #[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 pub fn value_at(&self, path: &str) -> DocumentResult<Value> {
308 crate::document::get_path(&self.value, path, self.addressing())
309 }
310
311 pub fn locate(&self, path: &str) -> DocumentResult<crate::document::Located<'_>> {
317 crate::document::locate(&self.value, path, self.addressing())
318 }
319
320 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 pub fn decode<T: serde::de::DeserializeOwned>(&self) -> DocumentResult<T> {
347 crate::document::from_value(self.value(), "")
348 }
349
350 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 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 pub fn encode(&self) -> DocumentResult<String> {
382 self.format.save(&self.value)
383 }
384}
385
386#[derive(Debug, Clone)]
395pub struct DocumentFile {
396 doc: Document,
397 path: PathBuf,
398}
399
400impl DocumentFile {
401 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 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 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 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 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 pub fn path(&self) -> &Path {
504 &self.path
505 }
506
507 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 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 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 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 #[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 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 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 #[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 #[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 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 #[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 pub fn unset(&mut self, key: &str) -> DocumentResult<bool> {
852 let addressing = self.addressing();
853 self.unset_addressed(key, addressing)
854 }
855
856 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 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 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 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 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 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 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 (a, b) if (a.is_integer() || a.is_float()) && (b.is_integer() || b.is_float()) => {
1110 let decimal = |value: &Value| match value {
1111 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 assert!(DocumentFile::open_capped(&path, None, 1024).is_ok());
1246
1247 let err = DocumentFile::open_capped(&path, None, 4).unwrap_err();
1250 assert_eq!(err.code(), "document_too_large");
1251
1252 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 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 #[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 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 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 #[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 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 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 #[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 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 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 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 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 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 let mut doc = DocumentFile::open(&link, None).unwrap();
1874
1875 doc.set("port", Value::Integer(1024)).unwrap();
1877 let err = doc.save().unwrap_err();
1878 assert!(matches!(err, DocumentError::UnsupportedOperation { .. }));
1879
1880 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 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(); 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 assert!(!doc.unset("service.missing").unwrap());
1937 assert!(!doc.unset("missing.parent").unwrap());
1938 assert!(!doc.unset("missing.deeply.nested").unwrap());
1939
1940 assert!(doc.unset("service.host.child").is_err()); assert!(doc.unset("service.ports.9").is_err()); assert!(doc.unset(r"service\q").is_err()); }
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 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 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 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 assert!(DocumentFile::open(&path, None).is_err());
1995
1996 let doc = DocumentFile::open(&path, Some(Format::Markdown)).unwrap();
1997 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}