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 from_str_relaxed(s: &str) -> (Document, Vec<String>)
pub fn from_str_relaxed(s: &str) -> (Document, Vec<String>)
Parse a YAML string, allowing syntax errors.
Returns the first document even if there are parse errors, along with a list of error messages. This allows for error-resilient tooling that can work with partial or invalid input.
Unlike Document::from_str, this does not return an error if the
input contains multiple documents - only the first document is returned.
§Example
use yaml_edit::Document;
let (doc, errors) = Document::from_str_relaxed("key: [unclosed");
// Tree is usable even with errors
assert!(!errors.is_empty());
assert!(doc.as_mapping().is_some());Sourcepub fn from_str_ignoring_comments(s: &str) -> YamlResult<Document>
pub fn from_str_ignoring_comments(s: &str) -> YamlResult<Document>
Parse a document from a YAML string, discarding stream-level content.
Like Document::from_str but succeeds when the input contains
stream-level comments or %YAML/%TAG directives outside the document
body. Those elements are silently dropped: the returned Document will
not round-trip to the original text. Use this when you only need the
document’s content and are happy to lose stream-scoped presentation.
Multiple documents are still rejected - use YamlFile::from_str for
multi-document streams.
§Example
use yaml_edit::Document;
let yaml = "# generated by tool\n---\nkey: value\n";
let doc = Document::from_str_ignoring_comments(yaml).unwrap();
assert_eq!(doc.to_string(), "---\nkey: value\n");Sourcepub fn from_file_relaxed<P: AsRef<Path>>(
path: P,
) -> Result<(Document, Vec<String>), Error>
pub fn from_file_relaxed<P: AsRef<Path>>( path: P, ) -> Result<(Document, Vec<String>), Error>
Load a document from a file, allowing syntax errors.
Returns the first document even if there are parse errors, along with
a list of error messages. I/O errors are still returned as Err.
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 as_tagged(&self) -> Option<TaggedNode>
pub fn as_tagged(&self) -> Option<TaggedNode>
Get this document’s root value as a tagged node, or None if it
carries no tag.
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) -> bool
pub fn set(&self, key: impl AsYaml, value: impl AsYaml) -> bool
Set a key in the document’s root mapping.
If the document has no root node, a mapping is created first.
Returns true if the key was set. Returns false if the root is a
sequence or another non-mapping node (the document is left unchanged).
Sourcepub fn set_with_field_order<I, K>(
&self,
key: impl AsYaml,
value: impl AsYaml,
field_order: I,
) -> boolwhere
I: IntoIterator<Item = K>,
K: AsYaml,
pub fn set_with_field_order<I, K>(
&self,
key: impl AsYaml,
value: impl AsYaml,
field_order: I,
) -> boolwhere
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.
Returns true if the key was set. Returns false if the root is a
sequence or another non-mapping node (the document is left unchanged).
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,
) -> bool
pub fn insert_at_index( &self, index: usize, key: impl AsYaml, value: impl AsYaml, ) -> bool
Insert a key-value pair at a specific index.
Delegates to Mapping::insert_at_index. If the document has no
root node, a mapping is created first.
Returns true if the key was inserted. Returns false if the root is
a sequence or another non-mapping node (the document is left
unchanged), as set does.
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.
A tag on the value is looked through.
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.
A tag on the value is looked through.
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.
An existing new_key entry is replaced; see Mapping::rename_key.
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) -> boolwhere
I: IntoIterator<Item = K>,
K: AsYaml,
pub fn reorder_fields<I, K>(&self, order: I) -> boolwhere
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.
Returns false, leaving the document unchanged, if it 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
Sourcepub fn comments(&self) -> impl Iterator<Item = Comment>
pub fn comments(&self) -> impl Iterator<Item = Comment>
Iterate over the comments in this document, in source order.
§Example
use yaml_edit::Document;
use std::str::FromStr;
let doc = Document::from_str("key: value # trailing\n# standalone\n").unwrap();
let comments: Vec<_> = doc.comments().map(|c| c.content().to_string()).collect();
assert_eq!(comments, vec!["trailing", "standalone"]);Trait Implementations§
Source§impl AsYaml for Document
As a value, a document is its root node, or null if it has none.
impl AsYaml for Document
As a value, a document is its root node, or null if it has none.
Only the root is copied: comments outside it, such as a comment line
before it or after ---, are not.
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 DocumentMergedExt for Document
impl DocumentMergedExt for Document
Source§fn merged(&self) -> Result<Option<MergedView>, ResolveError>
fn merged(&self) -> Result<Option<MergedView>, ResolveError>
MergedMapping view over the document’s root mapping. Read moreSource§impl DocumentResolvedExt for Document
impl DocumentResolvedExt for Document
Source§fn get_resolved(
&self,
key: impl AsYaml,
) -> Result<Option<YamlValue>, ResolveError>
fn get_resolved( &self, key: impl AsYaml, ) -> Result<Option<YamlValue>, ResolveError>
Source§fn build_anchor_registry(&self) -> AnchorRegistry
fn build_anchor_registry(&self) -> AnchorRegistry
impl Eq for Document
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, or
- the string contains stream-level content (comments or
%YAML/%TAGdirectives outside the document body).
Per the YAML 1.2 spec, comments before the leading --- (or after the
trailing ...) and top-level directives belong to the stream, not the
document, so Document cannot round-trip them. Use
YamlFile::from_str if you need to preserve them, or
Document::from_str_ignoring_comments if you’re happy to drop them.
A byte order mark and blank lines before the document are kept in it,
as are comments before a document without ---, and input with no
document at all gives an empty document holding its byte order mark
and blank lines, so the result always renders back to s.
§Example
use yaml_edit::Document;
use std::str::FromStr;
let doc = Document::from_str("key: value").unwrap();
assert!(doc.as_mapping().is_some());impl StructuralPartialEq for Document
Source§impl YamlAccept for Document
impl YamlAccept for Document
Source§fn accept<V: YamlVisitor>(&self, visitor: &mut V)
fn accept<V: YamlVisitor>(&self, visitor: &mut V)
Source§impl YamlPath for Document
impl YamlPath for Document
Source§fn try_get_path_with(
&self,
path: &str,
policy: AliasPolicy,
) -> Result<YamlNode, PathError>
fn try_get_path_with( &self, path: &str, policy: AliasPolicy, ) -> Result<YamlNode, PathError>
Source§fn try_set_path_with(
&self,
path: &str,
value: impl AsYaml,
policy: AliasPolicy,
) -> Result<(), PathError>
fn try_set_path_with( &self, path: &str, value: impl AsYaml, policy: AliasPolicy, ) -> Result<(), PathError>
try_set_path, but with an explicit
AliasPolicy for intermediate segments that land on an alias. Read moreSource§fn try_remove_path_with(
&self,
path: &str,
policy: AliasPolicy,
) -> Result<YamlNode, PathError>
fn try_remove_path_with( &self, path: &str, policy: AliasPolicy, ) -> Result<YamlNode, PathError>
try_remove_path, but with an
explicit AliasPolicy for intermediate segments that land on
an alias. Read moreSource§fn get_path(&self, path: &str) -> Option<YamlNode>
fn get_path(&self, path: &str) -> Option<YamlNode>
use try_get_path; get_path swallows PathError as None