Recursive AI

Reorder YAML keys without losing comments in Rust

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

Call move_entry(1, 0) to move the second key and its comments to the top of the mapping.

Terminal
cargo add oneyaml

Requires Rust 1.85 or later.

RUST
use oneyaml::Document;
 
type Error = Box<dyn std::error::Error>;
fn main() -> Result<(), Error> {
    let yaml = "name: 'api'\n# Listener\n\
                port: 80 # HTTP\n";
    let mut doc = Document::parse(yaml)?;
    doc.root_mut()?.move_entry(1, 0)?;
    print!("{doc}");
    Ok(())
}

Running this snippet prints:

Text
# Listener
port: 80 # HTTP
name: 'api'

The full program

Unzip the example, then cargo run.

The download reads this config.yaml and writes reordered.yaml without changing config.yaml.

YAML
name: 'api'
# Public listener
port: 80 # HTTP
RUST
use oneyaml::Document;
 
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let yaml = std::fs::read_to_string("config.yaml")?;
    let mut doc = Document::parse(&yaml)?;
    doc.root_mut()?.move_entry(1, 0)?;
    std::fs::write("reordered.yaml", doc.to_string())?;
    print!("{doc}");
    Ok(())
}

cargo run prints the contents of reordered.yaml:

Text
# Public listener
port: 80 # HTTP
name: 'api'

If a move would change which anchor an alias refers to, move_entry refuses it. The file is written only after a successful edit.

Variations

Move the first key to the end. With the same two entries, swap the indices in the snippet at the top:

RUST
doc.root_mut()?.move_entry(0, 1)?;

With two keys, moving name to the end gives the same result.

The short answer

Parse the YAML into a document, take a mutable view of the mapping, and pass the old and new positions to move_entry. In the example, port starts at index 1 and ends at index 0. The method’s documentation says that “the moved entry keeps its text and comments, as a new node.”

How do you reorder YAML keys and maintain comments?

Move an entry rather than deleting the key and constructing a new one. A map of key-value pairs describes the data, not where a comment was written. Editing the document instead lets the library retain the source text for that entry. In the example, the line above port explains the listener and the note next to 80 says what the port is for. Both move with port; the single quotes around api stay as they were.

Not every nearby comment belongs to the entry. For example, an own-line comment before the root with a blank line between it and the root is a document header, not an explanation of the first key. If the result depends on which entry a comment belongs to, check the comment attachment rules before moving it.

How do you sort YAML keys while keeping comments?

move_entry handles one move within one mapping; it doesn’t alphabetize the document. To arrange several keys in a chosen order, start at the first position you want to fill. For each desired key, find its current position, move it to that slot, then work on the next slot. Reusing positions from before the first move can put the wrong key in the next slot, because the entries between source and destination shift.

This example replaces the single move_entry call in the snippet at the top. It looks up each key again after the previous move:

RUST
for (to, wanted) in ["port", "name"].into_iter().enumerate() {
    let mapping = doc.root().and_then(|root| root.as_mapping())
        .ok_or("expected a mapping")?;
    let from = mapping.iter()
        .position(|(key, _)| key.as_str().as_deref() == Some(wanted))
        .ok_or("key not found")?;
    doc.root_mut()?.move_entry(from, to)?;
}
Text
# Listener
port: 80 # HTTP
name: 'api'

Treat nested mappings separately. The indices are local to the mapping you’re editing, not line numbers from the whole file. Also check errors before saving when the file uses anchors (&name) and aliases (*name): moving a key earlier or later can change which preceding anchor an alias would resolve to. The editor rejects moves that would cause that change.

All oneyaml Rust recipes