Recursive AI

Add a YAML footer comment in Rust

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

Use push_footer for a note after the last item in the ports list, or set_footer for a note at the end of the whole document.

Terminal
cargo add oneyaml

Requires Rust 1.85 or later.

RUST
use oneyaml::Document;
 
fn main() {
    let yaml = "ports:\n  - 443\nmode: live\n";
    let mut doc = Document::parse(yaml)
        .expect("valid YAML");
    let list = doc.get("ports")
        .expect("ports").id();
    doc.push_footer(list, "Add HTTPS ports here")
        .expect("append footer");
    print!("{doc}");
}

Unzip the example, then cargo run.

cargo run prints:

Text
ports:
  - 443
  # Add HTTPS ports here
mode: live

push_footer returns EditError::Unsupported if you pass the ID of a scalar, such as mode: live’s value, instead of a collection.

Variations

For a note at the end of the whole document, replace the let list statement and the push_footer call with this call. It prints the same YAML with # End of config on its own line after mode: live.

RUST
doc.set_footer(["End of config"])
    .expect("set document footer");

The short answer

Get the ID of the list with doc.get("ports").expect("ports").id(), then pass it and the note text to push_footer. For an indented list, the result is its own # line at the list’s indentation, after its final item. If the list already has a footer, this adds a line rather than replacing the footer.

How do you add a comment at the end of a YAML file?

Use set_footer for a document-wide note instead of push_footer on the root collection. set_footer writes at column zero, before ... if the document has that end marker. It replaces the document footer, so pass the whole set of lines you want to keep. Like the list edit, it changes the document in memory; use the printed YAML if you want to save the new version.

An empty document has no root to follow. In a multi-document file, a note before the next --- can belong to the next document instead. set_footer rejects the edit with EditError::CommentReattaches in these cases.

Yes. Use one # line per note, not a single string with embedded line breaks. To give the entire document two notes, pass two strings to set_footer, one per line. For an indented list like ports, call push_footer once per new line. The collection footer method puts new lines after existing ones for a block list. If a list uses brackets instead, the footer goes before the closing bracket, and that bracket must start its own line.

All oneyaml Rust recipes