Skip to content

Remove a key safely

err := doc.Remove("server.debug")

Removal is the operation where a naive editor destroys work, because it has to decide which nearby comments belonged to the key. yamldoc decides positionally — see Comment ownership for the reasoning.

What goes, and what stays

server:
  host: localhost

  # ==== TLS ====          ← blank line above: describes the SECTION, survives
  tls_cert: /etc/cert.pem
  # the port we bind to    ← directly above a key: belongs to it, goes with it
  port: 8080               # inline: goes with it
  # end of the block       ← trailing: hoisted onto the previous key, survives

Removing server.port from that document takes the two comments that describe port and leaves the other two exactly where they can still be read.

Emptiness is a value

Removing the last entry of a mapping leaves an empty mapping. The parent is never removed on your behalf:

feature:
  beta: true
other: 1
doc.Remove("feature.beta")
feature: {}
other: 1

This is deliberate. feature: {} and no feature key at all are different states, and code may legitimately require the parent to exist while it holds nothing. If you want the parent gone, remove the parent.

A comment on the block goes with it

Emptying a nested mapping this way currently destroys any comment attached to the block itself — a trailing comment under its only key, or a heading above it. There is no neighbour left to re-home it onto, and the collapse to {} takes it. Read the comment out with Node.Comments() first if it matters. Details, including why the same removal at the top level keeps the comment: A comment on a block that loses its last key is lost.

Removing a subtree

Removing a key removes everything beneath it:

err := doc.Remove("themes.neon")   // the whole theme, not just its first field

Removals that are refused

Remove returns ErrNotFound for a path that does not resolve. Removing something that is already absent is an error, not a no-op — silence there tends to hide a typo in a key name.

It returns ErrUnsupported when the subtree you are deleting defines an anchor that something else still points at, naming the alias that would be left dangling:

yamldoc: document contains an unsupported construct: removing "base" would leave
alias *b at "child.<<" dangling

Delete the alias first, or replace it with its value, and then remove the anchor. Every message and its cause is in Errors.