Read one subtree of a large file
The task: take one schema out of an OpenAPI file. The rest of the file does not need a tree, and need not even be read.
The file
// The second document is broken: "[" is never closed.
const src = `openapi: 3.1.0
paths:
/pets:
get:
operationId: listPets
components:
schemas:
Pet:
type: object
required: [id]
properties:
id:
type: integer
Error:
type: object
---
broken: [
`Full source: docs/examples/documents/subtree/example_test.go
The stream ends in a second document that does not parse.
The visitor
// pick keeps the node at one path whole, writes it, and stops the walk.
type pick struct {
w io.Writer
want string // the path to keep, as "components.schemas.Pet"
keys []string // the last key seen at each depth
found bool
}
func (v *pick) Enter(node ast.Node, at parser.Cursor) error {
d := at.Depth()
if at.IsKey() {
for len(v.keys) < d-1 {
v.keys = append(v.keys, "") // a sequence level holds no key
}
v.keys = append(v.keys[:d-1], node.String())
return nil
}
if d > 0 && d <= len(v.keys) && strings.Join(v.keys[:d], ".") == v.want {
v.found = true
// Receive the node whole at its Leave, and nothing below it before then.
return parser.ErrKeepNode
}
return nil
}
func (v *pick) Leave(node ast.Node, _ parser.Closing) error {
if !v.found {
return nil
}
// The node is valid until Leave returns. Clone it to keep it longer.
fmt.Fprintln(v.w, ast.Clone(node))
// Nothing more is handed over, and the parse reads no further.
return parser.ErrStopWalk
}Full source: docs/examples/documents/subtree/example_test.go
Parser.Walk hands each node to Enter as the parse reaches it. A key and
its value arrive as two calls at the same depth, so pick keeps the last key
seen at each depth and joins them into a path.
Three returns steer the walk:
nilfromEnterhands over the node’s content next.parser.ErrKeepNodefromEnterhands over nothing below the node, and callsLeavewith the node whole: the mapping holds its entries.parser.ErrStopWalkfromLeavestops the walk and the parse.
Walk
v := &pick{w: os.Stdout, want: "components.schemas.Pet"}
f, err := parser.New().Walk([]byte(src), v)
fmt.Println("error:", err)
fmt.Println("documents read:", len(f.Docs))Full source: docs/examples/documents/subtree/example_test.go
type: object
required: [id]
properties:
id:
type: integer
error: <nil>
documents read: 0Full source: docs/examples/documents/subtree/example_test.go
Walk returns no error: the parse stopped inside the first document and never
reached the broken one. The returned file holds the documents read before the
one the walk stopped in, so here it holds none.
The walk held the cells of Pet from its Enter to its Leave, beside the
nodes still open above it. A walk holds memory in proportion to the document’s
depth, and a kept subtree adds its own size.
Parse, for comparison
_, err := parser.ParseBytes([]byte(src))
fmt.Println(errors.Is(err, yerrors.ErrSyntax))
fmt.Println(err)Full source: docs/examples/documents/subtree/example_test.go
true
[17:9] a flow sequence is not closed by ']'
14 | Error:
15 | type: object
16 | ---
> 17 | broken: [
^Full source: docs/examples/documents/subtree/example_test.go
ParseBytes reads the whole stream and rejects it at the second document.
Variations
- Several subtrees. Return
ErrKeepNodefor each andnilfromLeave; the walk then reads to the end, and rejects the broken document. - Keep the error. A visitor that returns an error stops the walk, but the
parse still reads the rest of the stream, and a later rejection replaces the
visitor’s error. Store the error in the visitor and read it after
Walk. - A path with sequences.
pickleaves an empty key for a sequence level. TrackCursor.In()and an index per depth to address[n].
See Walking a stream for the handover order, the life
of a node, and the rest of the Cursor.