Recursive AI

Reattach a YAML comment to another key in Rust

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

Move # Use TLS from above old to above new with set_leading. For a comment tied to a key, that key is its owner; a leading comment sits on the line above it.

Terminal
cargo add oneyaml
RUST
use oneyaml::{Document, NO_COMMENTS};
 
fn main() {
    let yaml = "# Use TLS\nold: 80\nnew: 443\n";
    let mut doc = Document::parse(yaml)
        .expect("valid YAML");
    let old = doc.get("old").expect("old value");
    let key = old.key().expect("old key").id();
    let notes = doc.comments(key).expect("notes");
    let note = notes.leading()[0]
        .text().to_owned();
    doc.get_mut("old").expect("old value")
        .set_leading(NO_COMMENTS).expect("clear");
    doc.get_mut("new").expect("new value")
        .set_leading([note]).expect("add note");
    print!("{doc}");
}

Unzip the example, then cargo run.

Requires Rust 1.85 or later. The snippet prints the YAML with the comment in its new location:

Text
old: 80
# Use TLS
new: 443

The full program

The program moves the comment while keeping both keys, then uses a fresh copy of the input to show the deletion case. set_leading can return EditError::CommentReattaches if the inserted lines would be read as belonging to a different owner.

RUST
use oneyaml::{CommentOwner, Document, NO_COMMENTS, path};
 
fn main() {
    let yaml = "# Use TLS\nold: 80\nnew: 443\n";
    let mut doc = Document::parse(yaml)
        .expect("valid YAML");
    let old = doc.get("old").expect("old value");
    let key = old.key().expect("old key").id();
    let notes = doc.comments(key).expect("notes");
    let note = notes.leading()[0]
        .text().to_owned();
    doc.get_mut("old").expect("old value")
        .set_leading(NO_COMMENTS).expect("clear");
    doc.get_mut("new").expect("new value")
        .set_leading([note]).expect("add note");
    print!("{doc}");
 
    println!("After removing old with the comment reattached:");
    let mut doc = Document::parse(yaml)
        .expect("valid YAML");
    let comment = doc.comment_ids()[0];
    let new = doc.get("new").expect("new value")
        .key().expect("new key").id();
    doc.attach_comment(comment, CommentOwner::Leading(new))
        .expect("reattach comment");
    let old = doc.id_of(&path!["old"]).expect("old entry");
    let _ = doc.remove_keep_comments(old).expect("remove old");
    let info = doc.explain_comment(comment).expect("kept note");
    assert_eq!(info.owner(), CommentOwner::Leading(new));
    print!("{doc}");
}

cargo run prints:

Text
old: 80
# Use TLS
new: 443
After removing old with the comment reattached:
# Use TLS
new: 443

Variations

If you’re deleting old and new is the next entry, you can set the comment’s in-memory owner with attach_comment, then use remove_keep_comments to keep the line when removing old. Use the same yaml input and import CommentOwner and path from the crate:

RUST
let mut doc = Document::parse(yaml)
    .expect("valid YAML");
let comment = doc.comment_ids()[0];
let new = doc.get("new").expect("new value")
    .key().expect("new key").id();
doc.attach_comment(comment, CommentOwner::Leading(new))
    .expect("reattach comment");
let old = doc.id_of(&path!["old"]).expect("old entry");
let _ = doc.remove_keep_comments(old).expect("remove old");
let info = doc.explain_comment(comment).expect("kept note");
assert_eq!(info.owner(), CommentOwner::Leading(new));
print!("{doc}");

The resulting YAML is # Use TLS above new: 443, with no old entry. attach_comment alone doesn’t change the YAML text, and ordinary remove_path can still take the comment line out with old.

The short answer

Read the existing leading comment, clear it from old with set_leading(NO_COMMENTS), and pass its text to set_leading on new. That changes the YAML itself. To save the change, write doc.to_string() after both edits succeed.

How do you put a comment above a YAML key?

In YAML text, put # on its own line above the key, at the same indentation. set_leading supplies the indentation and # prefix. It replaces the entire set of leading comments at the target: if either key has other leading notes you want to keep, include those notes in the corresponding call. Same-line notes aren’t part of that replacement.

What is the difference between a leading and an inline YAML comment?

A leading comment belongs before an entry; an inline comment, such as new: 443 # Use TLS, follows content on the same line. The library calls the latter a trailing comment. For a mapping entry, the owner is named by the key node, not by the value node for 443. That’s why the code calls .key() on the result of get("old") before asking for the entry’s comments.

The attachment API overrides the owner in memory without moving the line. If you write the YAML immediately after attach_comment, a fresh parse still infers the owner from the old position. Use set_leading when both entries should stay and the change must be visible in the file.

All oneyaml Rust recipes