Validate a document¶
A file that is not YAML fails at Parse. A file that is YAML but does not
mean anything under its schema, such as one with a dangling alias, an !!int
whose text is not a number, or two keys that are the same value spelt
differently, parses and round-trips exactly, and Validate says what is wrong.
f, err := yamldoc.Parse(src, yamldoc.Options{})
if err != nil {
return err // not YAML: ErrSyntax, ErrUnsupportedVersion, ErrVersionConflict, or an encoding error
}
report, err := f.Snapshot().Validate(yamldoc.ValidationOptions{})
if err != nil {
for _, d := range report.Diagnostics {
fmt.Printf("%d:%d %s\n", d.Location.Start.Line, d.Location.Start.Column, d.Message)
}
return err
}
Every diagnostic carries a message, the location of the offending node and
any related locations (both halves of a duplicate key, for instance).
report.UnavailableChecks lists the checks that could not run because they
depend on a node that already failed, so one root cause does not produce a
cascade.
Why validate before editing¶
An edit that depends on invalid semantics is refused with ErrSemantic. A
scalar write under a mapping whose keys are ambiguous, or anything inside a
document with a dangling alias, cannot be checked against an independent
statement of what the edit meant, so the engine will not commit it. Validating
first turns a refusal mid-batch into a message before the user has typed
anything.
Reading is more forgiving: Entries, Items, Raw and Syntax inspect the
literal structure of anything that parsed, so a tool can still show a user
where the problem is.
Partial validation¶
ValidationOptions{Mode: yamldoc.PartialValidation} is for a file you
cannot fully resolve: one using a tag the profile does not know, such as
!secret, or a non-specific tag nothing resolves. Full mode fails on it.
Partial mode returns the same diagnostics, does not fail, and fills
UnavailableChecks with each check that could not run and the nodes it was
waiting on, so a linter can still report everything else about the file.
Genuinely invalid content, a dangling alias or a duplicate key, fails in
either mode. Reading a document
shows the two reports side by side.
What used to be "unsupported"¶
The goccy-backed version of this library reported constructs it could not
round-trip, such as a multi-line flow collection with a comment inside it, and
refused to emit a file containing one. The owned engine round-trips every
construct it parses, so that report and its ErrUnsupported are gone. What
remains is the distinction above: syntax fails to parse, semantics fail to
validate.