Recursive AI

Rename a YAML anchor and its aliases in Rust

oneyaml is a free, open-source YAML library for Rust from Recursive AI. MIT or Apache-2.0, no unsafe code.

set_anchor renames &old and the *old references to it in one edit.

Terminal
cargo add oneyaml

In a main that returns Result<(), Box<dyn std::error::Error>>:

RUST
use oneyaml::Document;
 
let yaml = "base: &old 'blue'\nweb: *old\n";
let mut doc = Document::parse(yaml)?;
let base = doc.get_path("base")
    .ok_or("missing base")?.id();
doc.set_anchor(base, Some("color"))?;
print!("{doc}");

The example is the full program below: unzip it and cargo run. To run only the code above, paste it into src/main.rs of a new cargo new example project and cargo run.

The snippet prints:

YAML
base: &color 'blue'
web: *color

The full program

The download adds a second alias and checks that both resolve to the renamed node. The input has a comment, a blank line and a single-quoted value, all of which stay as written.

RUST
use oneyaml::Document;
 
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
 
fn main() -> Result<()> {
    let yaml = "base: &old 'blue' # shared\n\nweb: *old\njobs: *old\n";
    let mut doc = Document::parse(yaml)?;
    let anchor = doc.get_path("base").ok_or("missing base")?.id();
    let renamed = doc.set_anchor(anchor, Some("color"))?;
    print!("{doc}");
 
    for key in ["web", "jobs"] {
        let alias = doc.get_path(key).ok_or("missing alias")?;
        let target = alias.alias_target().ok_or("unresolved alias")?;
        assert_eq!(target.id(), renamed);
        let color = target.as_str().ok_or("expected a string")?;
        println!("{key} resolves to {color}");
    }
    Ok(())
}

cargo run prints the edited YAML, then the two results from resolving the aliases:

Text
base: &color 'blue' # shared
 
web: *color
jobs: *color
web resolves to blue
jobs resolves to blue

If an anchor with the proposed name already exists in the document, set_anchor returns EditError::DuplicateAnchor; choose a name that isn’t in use.

Variations

Count the aliases before renaming. Insert this just before set_anchor in the full program:

RUST
println!("{} aliases", doc.aliases_of(anchor)?.len());

This adds 2 aliases before the edited YAML.

The short answer

With oneyaml-rust, find the node carrying the anchor and pass its ID to doc.set_anchor(id, Some("new_name")). Pass the bare name, without an & or *. The edit renames the anchor and every alias that resolves to that node, so callers that read an alias still get the same value. It does not rename the mapping key, base in this example.

How do YAML aliases know which anchor to use?

An alias refers to the most recent preceding anchor of that name in the same document, as defined in the YAML specification. If a file uses the same anchor name twice, an alias between the two definitions still refers to the first definition. An alias after the second definition refers to that second node. Renaming one definition with set_anchor updates only the references to that node. Changing every matching string in the file would miss this distinction and could also change comments or quoted text.

Use alias_target() to check where a reference goes. It returns None if the node isn’t a resolved alias. In the full program, the target ID for each alias matches the ID returned by set_anchor; checking only the alias name would verify the spelling, not where the alias points.

Can I remove a YAML anchor if aliases still use it?

In oneyaml-rust, set_anchor(id, None) returns EditError::AnchorInUse if the node still has aliases. Use aliases_of(id) to find those references first. If the references must stay, rename the anchor instead of removing it. The operation also refuses a new name that would make a previously unresolved alias point to this node. These checks keep a rename from changing which values the references resolve to.

All oneyaml Rust recipes