Source-preserving editing with ayaml-edit
When updating an existing YAML configuration file (such as a CI workflow, manifest, or lockfile), deserializing and re-emitting the entire document strips comments, blank lines, quoting style, and key alignment.
The companion crate ayaml-edit (#![forbid(unsafe_code)]) applies verified,
byte-range edits using ayaml::SpannedTree, preserving surrounding comments,
BOMs, CRLF/LF line endings, and formatting. Every edit re-parses the resulting
document and verifies both the expected Value tree and the canonical event
stream before returning Ok(VerifiedEdit).
Full Rustdoc reference: docs.rs/ayaml-edit.
Install
Section titled “Install”[dependencies]ayaml = "1.0.0"ayaml-edit = "1.0.0"To edit YAML documents parsed with libyaml compatibility (ayaml::compat::ParseOptions),
enable the optional libyaml-compat feature:
[dependencies]ayaml = { version = "1.0.0", features = ["libyaml-compat"] }ayaml-edit = { version = "1.0.0", features = ["libyaml-compat"] }Replacing a scalar value
Section titled “Replacing a scalar value”replace_scalar (and replace_scalar_with for custom EditOptions) locates
the target node by PathSegments, quotes strings automatically when plain
syntax would be ambiguous or flow-unsafe, and verifies that no unrelated node
changed:
use ayaml::{PathSegment, Value};use ayaml_edit::replace_scalar;
let src = "# Service settings\nservice:\n host: localhost # local bind\n port: 8080\n";let path = [PathSegment::key("service"), PathSegment::key("port")];let verified = replace_scalar(src, &path, &Value::from(9090_u64))?;
assert_eq!( verified.output(), "# Service settings\nservice:\n host: localhost # local bind\n port: 9090\n");assert_eq!(verified.edits().len(), 1);Removing a mapping entry or sequence item
Section titled “Removing a mapping entry or sequence item”remove_entry (and remove_entry_with) removes block mapping entries, braced
flow mapping entries ({a: 1, b: 2}), and block sequence items while keeping
neighboring comments and formatting intact. Removing the sole or all entries of
a mapping preserves empty mapping {} semantics rather than turning the parent
into null:
use ayaml::PathSegment;use ayaml_edit::remove_entry;
let src = "keep: 1\nobsolete: true\nalso_keep: 2\n";let verified = remove_entry(src, &[PathSegment::key("obsolete")])?;assert_eq!(verified.into_output(), "keep: 1\nalso_keep: 2\n");
// Emptying a single-entry mapping preserves `{}` semantics:let emptied = remove_entry("parent:\n only: 1\n", &[PathSegment::key("parent"), PathSegment::key("only")])?;assert_eq!(emptied.output(), "parent: {}\n");
// Braced flow-mapping removal preserves inner formatting and collapses cleanly to `{}`:let flow = remove_entry("opts: {a: 1, b: 2}\n", &[PathSegment::key("opts"), PathSegment::key("a")])?;assert_eq!(flow.output(), "opts: {b: 2}\n");Inserting or upserting entries and comments
Section titled “Inserting or upserting entries and comments”insert_mapping_entry, upsert_mapping_entry, insert_sequence_item, and
insert_comment (and their *_with counterparts) append entries to block
mappings, empty {} mappings, braced flow mappings, or block sequences, or
insert single-line # comments while preserving indentation, BOMs, and CRLF/LF
line endings. upsert_mapping_entry (and EditOp::UpsertMappingEntry) updates
an existing scalar key in place or inserts a new key: value entry when absent.
Comment insertions verify that both the Value tree and canonical Event
stream remain 100% identical to the original document:
use ayaml::{PathSegment, Value};use ayaml_edit::{ CommentPlacement, insert_comment, insert_mapping_entry, insert_sequence_item, upsert_mapping_entry,};
let src = "service:\n port: 8080\nroutes:\n - /health\nlabels: {}\n";let with_tls = insert_mapping_entry( src, &[PathSegment::key("service")], &Value::from("tls"), &Value::from(true),)?;let upserted = upsert_mapping_entry( with_tls.output(), &[PathSegment::key("labels")], &Value::from("env"), &Value::from("prod"),)?;let with_route = insert_sequence_item( upserted.output(), &[PathSegment::key("routes")], &Value::from("/v1"),)?;let commented = insert_comment( with_route.output(), &[PathSegment::key("service"), PathSegment::key("port")], "HTTP listener", CommentPlacement::InlineEndOfLine,)?;
assert_eq!( commented.output(), "service:\n port: 8080 # HTTP listener\n tls: true\nroutes:\n - /health\n - /v1\nlabels: {env: prod}\n");Transactional typed editing (Editable<T> and apply_batch_checked)
Section titled “Transactional typed editing (Editable<T> and apply_batch_checked)”When editing configuration files backed by a Serde schema T: DeserializeOwned,
use Editable<T> (or one-shot apply_batch_checked / apply_batch_validated).
Every mutation verifies both ayaml-edit’s structural/event invariants and
re-deserialization into T (plus any custom invariant closure in
apply_validated) before committing. On any failure, Editable<T> rolls back
atomically: schema or custom-validator failures return
EditErrorKind::ValidationFailed, while edit-planning or verification failures
return their respective EditErrorKind:
use ayaml::{PathSegment, Value};use ayaml_edit::{EditErrorKind, EditOp, Editable};use serde::Deserialize;
#[derive(Debug, Deserialize, PartialEq, Eq)]struct ServiceConfig { port: u16, #[serde(default)] tls: bool,}
let src = "# Service config\nport: 8080\n";let mut doc = Editable::<ServiceConfig>::parse(src)?;
// Schema violation rolls back cleanly without modifying `doc`:let err = doc .replace_scalar(&[PathSegment::key("port")], &Value::from("invalid")) .unwrap_err();assert_eq!(err.kind(), EditErrorKind::ValidationFailed);assert_eq!(doc.source(), src);assert_eq!(doc.value().port, 8080);
// Domain invariant check via `apply_validated`:let err = doc .apply_validated( &[EditOp::ReplaceScalar { path: vec![PathSegment::key("port")], value: Value::from(80_u64), }], |cfg, _yaml| { if cfg.port < 1024 { Err("privileged port is disallowed") } else { Ok(()) } }, ) .unwrap_err();assert_eq!(err.kind(), EditErrorKind::ValidationFailed);assert_eq!(doc.source(), src);
// Valid edit commits both source and typed value atomically:doc.insert_mapping_entry(&[], &Value::from("tls"), &Value::from(true))?;assert_eq!( doc.value(), &ServiceConfig { port: 8080, tls: true, });assert_eq!(doc.source(), "# Service config\nport: 8080\ntls: true\n");Applying or planning batches (apply_batch and plan_batch)
Section titled “Applying or planning batches (apply_batch and plan_batch)”Use apply_batch (or apply_batch_with with custom EditOptions) to apply
several non-overlapping EditOp operations in one double-verified pass. Callers
that already run their own post-edit parser or verifier can use plan_batch /
plan_batch_with to compute the exact same sorted, non-overlapping
Vec<TextEdit> without redundant post-edit re-parsing, and apply them with
apply_edits:
use ayaml::{PathSegment, Value};use ayaml_edit::{EditOp, apply_batch, apply_edits, plan_batch};
let src = "service:\n name: api\n port: 8080\n debug: true\n";let ops = [ EditOp::ReplaceScalar { path: vec![PathSegment::key("service"), PathSegment::key("port")], value: Value::from(8443_u64), }, EditOp::RemoveEntry { path: vec![PathSegment::key("service"), PathSegment::key("debug")], },];
let planned = plan_batch(src, &ops)?;let verified = apply_batch(src, &ops)?;assert_eq!(planned, verified.edits());assert_eq!(apply_edits(src, &planned)?, verified.output());assert_eq!(verified.output(), "service:\n name: api\n port: 8443\n");Editing with libyaml-compat (EditOptions::with_compat_parse_options)
Section titled “Editing with libyaml-compat (EditOptions::with_compat_parse_options)”When the libyaml-compat feature is enabled on ayaml-edit, configure
EditOptions::with_compat_parse_options(ayaml::compat::ParseOptions) to route
event scanning, span trees, tape/value verification, and typed deserialization
through ayaml::compat. Relaxed libyaml flow syntax, GlobalTags::Drop/Keep,
and untouched sibling duplicate keys (under allow_duplicates = true) edit and
double-verify cleanly while ambiguous duplicate-key target mappings remain
conservatively refused.
Conservative refusal guarantees and error kinds
Section titled “Conservative refusal guarantees and error kinds”ayaml-edit refuses to guess whenever a byte edit could silently corrupt
document semantics or delete comments unexpectedly, returning an EditError
categorized by EditErrorKind:
EditErrorKind::Parse: source YAML failed to parse under the configuredParseOptionsorayaml::compat::ParseOptions.EditErrorKind::NotFound: targetPathSegmentpath does not exist.EditErrorKind::InvalidEdit: duplicate inserted mapping key, disallowed comment characters, conflicting batch operations, or overlapping / out-of-bounds byte spans acrossTextEditoperations.EditErrorKind::VerificationFailed: the spliced document failed post-edit re-parse or semantic/event verification, or would exceed the configured input-size limit.EditErrorKind::ValidationFailed: post-edit caller validation (apply_batch_validated*,Editable::apply_validated) or typed schema deserialization (apply_batch_checked*,Editable::parse*/apply*) failed.EditErrorKind::Unsupported: document-wide or target-scoped constructs that cannot be edited conservatively:- Document-wide: multi-document streams (
---/ multiple documents) andParseOptionswithmerge_keysenabled (with_merge_keys(true)). - Target-scoped (untouched sibling branches pass through byte-for-byte):
- Targeting a block scalar (
|/>), alias (*a), anchored node (&a), or tagged node (!tag). - Traversing an ancestor that is an alias, defines an anchor referenced by
an alias elsewhere, or is a mapping containing a
<<merge key, an alias key, or duplicate keys (underlibyaml-compat). - Removing a subtree that defines an anchor referenced by an alias elsewhere in the document, or emptying a tagged/anchored block mapping.
- Targeting a block scalar (
- Layout/syntax boundaries: non-scalar targets or non-scalar
replacement/inserted values or keys, unwritten empty scalars (
key:), multiline plain/quoted scalars, scalars that cannot format on one line, implicit mapping keys exceeding 1024 characters, mid-document byte-order marks during insertion/flow-removal/emptying, unbraced flow pairs ([a: b]), flow mappings with embedded comments or explicit?keys in affected gaps, removing the document root or a flow/single-item sequence entry, inserting into flow/empty sequences or compact single-entry sequence mappings without provable indentation, inline comments on lines with existing comments or trailing tokens, or#comments immediately adjoining a scalar without whitespace.
- Document-wide: multi-document streams (
For documents that require structural transformations across multi-document
streams or targeted anchors/tags/block scalars, parse with
ayaml::parse_documents, transform the Value tree, and re-emit with
ayaml::to_string_documents_with.
When logging or returning EditError diagnostics for untrusted or sensitive
YAML documents, format error.masked() (MaskedEditError) instead of error:
it mirrors ayaml::Error::masked(), omitting all YAML document text and
returning None from std::error::Error::source().
Design boundaries
Section titled “Design boundaries”ayaml-edit intentionally restricts mutations to minimal byte-range
replacements, removals (including empty-mapping preservation and braced flow
mappings), conservative block/flow/empty mapping insertions and upserts, block
sequence insertions, and single-line comment insertions that can be
double-verified against both the expected Value tree and the canonical Event
stream, layered with transactional typed validation (Editable<T>,
apply_batch_checked, and apply_batch_validated).
Automated block-to-flow and flow-to-block collection style toggling and
arbitrary cursor AST mutation remain intentionally out of scope (deferred to
1.2+ per D113 in decisions.md) so ayaml-edit does not
introduce non-conservative layout heuristics inside flow collections with
embedded comments.