Skip to main content

Document

Struct Document 

Source
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

Source

pub fn new() -> Document

Create a new document

Source

pub fn new_mapping() -> Document

Create a new document with an empty mapping

Source

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().

Source

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().

Source

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.

Source

pub fn as_sequence(&self) -> Option<Sequence>

Get this document’s root value as a sequence, or None if it isn’t one.

Source

pub fn as_scalar(&self) -> Option<Scalar>

Get this document’s root value as a scalar, or None if it isn’t one.

Source

pub fn contains_key(&self, key: impl AsYaml) -> bool

Returns true if this document is a mapping that contains the given key.

Source

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.

Source

pub fn set(&self, key: impl AsYaml, value: impl AsYaml)

Set a scalar value in the document (assumes document is a mapping)

Source

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.

Source

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.

Source

pub fn keys(&self) -> impl Iterator<Item = YamlNode> + '_

Iterate over all keys in the document as YamlNodes.

Each key is a YamlNode wrapping the underlying CST node. Assumes the document is a mapping; yields nothing if it is not.

Source

pub fn is_empty(&self) -> bool

Check if the document is empty

Source

pub fn from_mapping(mapping: Mapping) -> Self

Create a document from a mapping

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn is_sequence(&self, key: impl AsYaml) -> bool

Returns true if key exists and its value is a sequence.

Source

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.

Source

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);
        }
    }
}
Source

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);
Source

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);
Source

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

Source§

fn as_node(&self) -> Option<&SyntaxNode<Lang>>

Returns a reference to the underlying SyntaxNode if one exists. Read more
Source§

fn kind(&self) -> YamlKind

Returns the kind of YAML value this represents.
Source§

fn build_content( &self, builder: &mut GreenNodeBuilder<'_>, _indent: usize, _flow_context: bool, ) -> bool

Serialize this value into a GreenNodeBuilder. Read more
Source§

fn is_inline(&self) -> bool

Returns whether this value should be rendered on the same line as its key. Read more
Source§

impl AstNode for Document

Source§

type Language = Lang

Source§

fn can_cast(kind: SyntaxKind) -> bool

Source§

fn cast(syntax: SyntaxNode<Lang>) -> Option<Self>

Source§

fn syntax(&self) -> &SyntaxNode<Lang>

Source§

fn clone_for_update(&self) -> Self
where Self: Sized,

Source§

fn clone_subtree(&self) -> Self
where Self: Sized,

Source§

impl Clone for Document

Source§

fn clone(&self) -> Document

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Document

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Document

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Document

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl DocumentResolvedExt for Document

Source§

fn get_resolved(&self, key: impl AsYaml) -> Option<YamlValue>

Get a value with anchor/alias resolution Read more
Source§

fn build_anchor_registry(&self) -> AnchorRegistry

Build the anchor registry for this document
Source§

impl FromStr for Document

Source§

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());
Source§

type Err = YamlError

The associated error which can be returned from parsing.
Source§

impl Hash for Document

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Document

Source§

fn eq(&self, other: &Document) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl YamlAccept for Document

Source§

fn accept<V: YamlVisitor>(&self, visitor: &mut V)

Accept a visitor for traversal
Source§

impl YamlPath for Document

Source§

fn get_path(&self, path: &str) -> Option<YamlNode>

Get a value at a nested path. Read more
Source§

fn set_path(&self, path: &str, value: impl AsYaml)

Set a value at a nested path, creating intermediate mappings if needed. Read more
Source§

fn remove_path(&self, path: &str) -> bool

Remove a value at a nested path. Read more
Source§

impl Eq for Document

Source§

impl StructuralPartialEq for Document

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.