pub struct Document(/* private fields */);Expand description
A single YAML document
Note: This type uses interior mutability through the rowan library.
Mutation methods work even when called through &self. See the crate-level
documentation for details on the mutability model.
Implementations§
Source§impl Document
impl Document
Sourcepub fn new_mapping() -> Document
pub fn new_mapping() -> Document
Create a new document with an empty mapping
Sourcepub fn from_file<P: AsRef<Path>>(path: P) -> YamlResult<Document>
pub fn from_file<P: AsRef<Path>>(path: P) -> YamlResult<Document>
Load a document from a file
Returns an error if the file contains multiple documents.
For multi-document YAML files, parse manually with YamlFile::from_str().
This follows the standard Rust naming convention of from_file()
to pair with to_file().
Sourcepub fn to_file<P: AsRef<Path>>(&self, path: P) -> YamlResult<()>
pub fn to_file<P: AsRef<Path>>(&self, path: P) -> YamlResult<()>
Write the document to a file, creating directories as needed
This follows the standard Rust naming convention of to_file()
to pair with from_file().
Sourcepub fn as_mapping(&self) -> Option<Mapping>
pub fn as_mapping(&self) -> Option<Mapping>
Get this document as a mapping, if it is one.
Note: Mapping supports mutation even though this method takes &self.
Mutations are applied directly to the underlying syntax tree via rowan’s
persistent data structures. All references to the tree will see the changes.
Sourcepub fn as_sequence(&self) -> Option<Sequence>
pub fn as_sequence(&self) -> Option<Sequence>
Get this document’s root value as a sequence, or None if it isn’t one.
Sourcepub fn as_scalar(&self) -> Option<Scalar>
pub fn as_scalar(&self) -> Option<Scalar>
Get this document’s root value as a scalar, or None if it isn’t one.
Sourcepub fn contains_key(&self, key: impl AsYaml) -> bool
pub fn contains_key(&self, key: impl AsYaml) -> bool
Returns true if this document is a mapping that contains the given key.
Sourcepub fn get(&self, key: impl AsYaml) -> Option<YamlNode>
pub fn get(&self, key: impl AsYaml) -> Option<YamlNode>
Get the value for a key from the document’s root mapping.
Returns None if the document is not a mapping or the key doesn’t exist.
Sourcepub fn set(&self, key: impl AsYaml, value: impl AsYaml)
pub fn set(&self, key: impl AsYaml, value: impl AsYaml)
Set a scalar value in the document (assumes document is a mapping)
Sourcepub fn set_with_field_order<I, K>(
&self,
key: impl AsYaml,
value: impl AsYaml,
field_order: I,
)where
I: IntoIterator<Item = K>,
K: AsYaml,
pub fn set_with_field_order<I, K>(
&self,
key: impl AsYaml,
value: impl AsYaml,
field_order: I,
)where
I: IntoIterator<Item = K>,
K: AsYaml,
Set a key-value pair with field ordering support.
If the key exists, updates its value. If the key doesn’t exist, inserts it at the correct position based on the provided field order. Fields not in the order list are placed at the end.
Sourcepub fn remove(&self, key: impl AsYaml) -> Option<MappingEntry>
pub fn remove(&self, key: impl AsYaml) -> Option<MappingEntry>
Remove a key from the document (assumes document is a mapping).
Returns Some(entry) if the key existed and was removed, or None if
the key was not found or the document is not a mapping. The returned
MappingEntry is detached from the tree; callers can inspect its key
and value or re-insert it elsewhere.
Sourcepub fn from_mapping(mapping: Mapping) -> Self
pub fn from_mapping(mapping: Mapping) -> Self
Create a document from a mapping
Sourcepub fn insert_after(
&self,
after_key: impl AsYaml,
key: impl AsYaml,
value: impl AsYaml,
) -> bool
pub fn insert_after( &self, after_key: impl AsYaml, key: impl AsYaml, value: impl AsYaml, ) -> bool
Insert a key-value pair immediately after after_key in this document’s mapping.
If key already exists, its value is updated in-place and it stays at its
current position (it is not moved). Returns false if after_key is not
found or the document is not a mapping.
Use move_after if you want an existing entry to be
removed from its current position and re-inserted after after_key.
Sourcepub fn move_after(
&self,
after_key: impl AsYaml,
key: impl AsYaml,
value: impl AsYaml,
) -> bool
pub fn move_after( &self, after_key: impl AsYaml, key: impl AsYaml, value: impl AsYaml, ) -> bool
Move a key-value pair to immediately after after_key in this document’s mapping.
If key already exists, it is removed from its current position and
re-inserted after after_key with the new value. Returns false if
after_key is not found or the document is not a mapping.
Use insert_after if you want an existing entry to be
updated in-place rather than moved.
Sourcepub fn insert_before(
&self,
before_key: impl AsYaml,
key: impl AsYaml,
value: impl AsYaml,
) -> bool
pub fn insert_before( &self, before_key: impl AsYaml, key: impl AsYaml, value: impl AsYaml, ) -> bool
Insert a key-value pair immediately before before_key in this document’s mapping.
If key already exists, its value is updated in-place and it stays at its
current position (it is not moved). Returns false if before_key is not
found or the document is not a mapping.
Use move_before if you want an existing entry to be
removed from its current position and re-inserted before before_key.
Sourcepub fn move_before(
&self,
before_key: impl AsYaml,
key: impl AsYaml,
value: impl AsYaml,
) -> bool
pub fn move_before( &self, before_key: impl AsYaml, key: impl AsYaml, value: impl AsYaml, ) -> bool
Move a key-value pair to immediately before before_key in this document’s mapping.
If key already exists, it is removed from its current position and
re-inserted before before_key with the new value. Returns false if
before_key is not found or the document is not a mapping.
Use insert_before if you want an existing entry to be
updated in-place rather than moved.
Sourcepub fn insert_at_index(
&self,
index: usize,
key: impl AsYaml,
value: impl AsYaml,
)
pub fn insert_at_index( &self, index: usize, key: impl AsYaml, value: impl AsYaml, )
Insert a key-value pair at a specific index (assumes document is a mapping).
If the document already contains a mapping, delegates to
Mapping::insert_at_index. If no mapping exists yet, creates one and
uses Mapping::insert_at_index_preserving.
Sourcepub fn get_string(&self, key: impl AsYaml) -> Option<String>
pub fn get_string(&self, key: impl AsYaml) -> Option<String>
Get the scalar value for key as a decoded String.
Returns None if the key does not exist or its value is not a scalar
(i.e. the value is a sequence or mapping). Quotes are stripped and
escape sequences are processed (e.g. \" → ", \n → newline).
For tagged scalars (e.g. !!str foo) the tag is ignored and the
value part is returned.
Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Get the number of top-level key-value pairs in this document.
Returns 0 if the document is not a mapping or is empty.
Sourcepub fn get_mapping(&self, key: impl AsYaml) -> Option<Mapping>
pub fn get_mapping(&self, key: impl AsYaml) -> Option<Mapping>
Get a nested mapping value for a key.
Returns None if the key doesn’t exist or its value is not a mapping.
Sourcepub fn get_sequence(&self, key: impl AsYaml) -> Option<Sequence>
pub fn get_sequence(&self, key: impl AsYaml) -> Option<Sequence>
Get a nested sequence value for a key.
Returns None if the key doesn’t exist or its value is not a sequence.
Sourcepub fn rename_key(&self, old_key: impl AsYaml, new_key: impl AsYaml) -> bool
pub fn rename_key(&self, old_key: impl AsYaml, new_key: impl AsYaml) -> bool
Rename a top-level key while preserving its value and formatting.
The new key is automatically escaped/quoted as needed. Returns true if
the key was found and renamed, false if old_key does not exist.
Sourcepub fn is_sequence(&self, key: impl AsYaml) -> bool
pub fn is_sequence(&self, key: impl AsYaml) -> bool
Returns true if key exists and its value is a sequence.
Sourcepub fn reorder_fields<I, K>(&self, order: I)where
I: IntoIterator<Item = K>,
K: AsYaml,
pub fn reorder_fields<I, K>(&self, order: I)where
I: IntoIterator<Item = K>,
K: AsYaml,
Reorder fields in the document’s root mapping according to the specified order.
Fields not in the order list will appear after the ordered fields, in their original relative order. Has no effect if the document is not a mapping.
Sourcepub fn validate_schema(
&self,
validator: &SchemaValidator,
) -> ValidationResult<()>
pub fn validate_schema( &self, validator: &SchemaValidator, ) -> ValidationResult<()>
Validate this document against a YAML schema
§Examples
use yaml_edit::{Document, Schema, SchemaValidator};
let yaml = r#"
name: "John"
age: 30
active: true
"#;
let parsed = yaml.parse::<yaml_edit::YamlFile>().unwrap();
let doc = parsed.document().unwrap();
// Validate against JSON schema
let validator = SchemaValidator::json();
match doc.validate_schema(&validator) {
Ok(_) => println!("Valid JSON schema"),
Err(errors) => {
for error in errors {
println!("Validation error: {}", error);
}
}
}Sourcepub fn byte_range(&self) -> TextPosition
pub fn byte_range(&self) -> TextPosition
Get the byte offset range of this document in the source text.
Returns the start and end byte offsets as a TextPosition.
§Examples
use yaml_edit::Document;
use std::str::FromStr;
let text = "name: Alice\nage: 30";
let doc = Document::from_str(text).unwrap();
let range = doc.byte_range();
assert_eq!(range.start, 0);Sourcepub fn start_position(&self, source_text: &str) -> LineColumn
pub fn start_position(&self, source_text: &str) -> LineColumn
Get the line and column where this document starts.
Requires the original source text to calculate line/column from byte offsets. Line and column numbers are 1-indexed.
§Arguments
source_text- The original YAML source text
§Examples
use yaml_edit::Document;
use std::str::FromStr;
let text = "name: Alice";
let doc = Document::from_str(text).unwrap();
let pos = doc.start_position(text);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 1);Sourcepub fn end_position(&self, source_text: &str) -> LineColumn
pub fn end_position(&self, source_text: &str) -> LineColumn
Get the line and column where this document ends.
Requires the original source text to calculate line/column from byte offsets. Line and column numbers are 1-indexed.
§Arguments
source_text- The original YAML source text
Trait Implementations§
Source§impl AsYaml for Document
impl AsYaml for Document
Source§fn as_node(&self) -> Option<&SyntaxNode<Lang>>
fn as_node(&self) -> Option<&SyntaxNode<Lang>>
SyntaxNode if one exists. Read moreSource§fn build_content(
&self,
builder: &mut GreenNodeBuilder<'_>,
_indent: usize,
_flow_context: bool,
) -> bool
fn build_content( &self, builder: &mut GreenNodeBuilder<'_>, _indent: usize, _flow_context: bool, ) -> bool
GreenNodeBuilder. Read moreSource§impl DocumentResolvedExt for Document
impl DocumentResolvedExt for Document
Source§fn get_resolved(&self, key: impl AsYaml) -> Option<YamlValue>
fn get_resolved(&self, key: impl AsYaml) -> Option<YamlValue>
Source§fn build_anchor_registry(&self) -> AnchorRegistry
fn build_anchor_registry(&self) -> AnchorRegistry
Source§impl FromStr for Document
impl FromStr for Document
Source§fn from_str(s: &str) -> Result<Self, Self::Err>
fn from_str(s: &str) -> Result<Self, Self::Err>
Parse a document from a YAML string.
Returns an error if the string contains multiple documents.
For multi-document YAML, use YamlFile::from_str() instead.
§Example
use yaml_edit::Document;
use std::str::FromStr;
let doc = Document::from_str("key: value").unwrap();
assert!(doc.as_mapping().is_some());