Handle multi-document files¶
A YAML file may hold several documents separated by ---. yamldoc exposes all
of them, and editing one leaves the others untouched.
f, _ := yamldoc.Parse(src, yamldoc.Options{})
documents, _ := f.Snapshot().Documents()
fmt.Println(len(documents)) // 3
err := documents[1].Set("server.port", 7070)
Separators, per-document directives and comments, the bytes between documents, and every other document survive exactly.
Each document has its own version¶
A %YAML directive applies to the document it introduces and no other; a
document without one uses Options.Version, or negotiates its own when that
is zero. Document.Version reports what was selected and
Document.Directives what the document declared. A caller version that
contradicts a directive is refused at parse rather than silently overridden
either way.
The library assigns no meaning to their order¶
This matters, and it is easy to assume otherwise.
YAML defines a multi-document stream as a sequence of independent documents. Kubernetes treats them as separate resources. A configuration system might reasonably treat later documents as overriding earlier ones.
yamldoc takes no position. It hands you the documents in file order and lets
you decide what that order means:
// A configuration loader might merge them, later winning:
for _, d := range documents {
mergeInto(effective, d)
}
// A manifest tool might treat them as unrelated:
for _, d := range documents {
apply(d)
}
Detecting the separator correctly¶
A --- inside a block scalar is content, not a separator:
That is one document, and yamldoc reports it as one.
Adding and removing documents¶
An empty stream can be given its first document with tx.CreateDocument,
which respects a comment-only header by adding an explicit --- after it.
Beyond that the set of documents in a file is fixed by the file: you can edit
any of them, but you cannot add a fourth or delete the second. Those are
separate decisions the design has not taken.