Documentation
¶
Overview ¶
Package transform rewrites a YAML document a piece at a time: Walk reads the document and calls a Transformer, which writes each piece unchanged or rewritten.
A document reaches a Transformer as a run of Piece values, in the order the document wrote them. The pieces tile the source: Copy on every one of them writes the file back byte for byte, comments, blank lines and spelling included. A transform writes some of them differently; see the example of Walk, which upper-cases every mapping key.
The pieces come from the tokens ¶
The scanner's tokens cover the whole document and the parser's nodes do not: over a real file, a fifth to nearly half of the bytes stand outside every node -- the comments, the "-" and ":" indicators, the indentation, the "---", a directive's words and a block scalar's body. So each piece is a token, and carries the node the parse opened on it where there is one: Piece.Token is always set, Piece.Node only there.
Piece.Role names every piece, from the node where there is one and from the token where there is not, so a transform can switch on it without reading either.
What a transform sees ¶
Walk holds one token at a time and hands nothing else over, so a transform keeps what it needs itself. It cannot look ahead, look up at a parent, or reach the node an alias names. Write the document to a buffer and parse it with github.com/go-openapi/go-yaml/parser where the work needs those.
github.com/go-openapi/go-yaml/transform/colorize draws a document in color through the renderer of package github.com/go-openapi/go-yaml/ast, not through this package.
A transform that copies every piece copies the document. TestIdentityRebuildsTheCorpus checks it over every corpus document the parse accepts.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Copy ¶
Copy writes a piece as the document wrote it.
It is the identity transform. Call it for a piece a transform leaves alone.
func Walk ¶
Walk reads src through and calls t for each piece of it, writing to w.
The pieces tile the source, so a t that calls Copy for every piece writes src back byte for byte. The walk holds one token between pieces, and a transform keeps whatever else it needs itself.
Where the parse rejects the document, Walk returns its error and whatever was written up to that point stands. Write to a buffer where a partial document is worse than none.
Example ¶
ExampleWalk upper-cases every mapping key and copies every other piece, so the comments, the layout and the values come out as written.
package main
import (
"bytes"
"io"
"os"
"github.com/go-openapi/go-yaml/transform"
)
func main() {
src := []byte(`# a store
store:
book: [{author: john, price: 10}] # inline
open: true
`)
upper := transform.Func(func(w io.Writer, p transform.Piece) error {
if p.Role != transform.RoleKey {
return transform.Copy(w, p)
}
if _, err := w.Write(p.Lead); err != nil {
return err
}
_, err := w.Write(bytes.ToUpper(p.Text))
return err
})
if err := transform.Walk(os.Stdout, src, upper); err != nil {
panic(err)
}
}
Output: # a store STORE: BOOK: [{AUTHOR: john, PRICE: 10}] # inline OPEN: true
Example (ReplaceValue) ¶
ExampleWalk_replaceValue sets the value of the "version" key and copies every other piece, so the comment after the value and the indentation of the sequence stay as written.
package main
import (
"io"
"os"
"github.com/go-openapi/go-yaml/transform"
)
func main() {
src := []byte(`# service
name: pet-store
version: 1.2.3 # bump me
ports:
- 80
- 443
`)
var next bool // the piece after the "version" key is its value
bump := transform.Func(func(w io.Writer, p transform.Piece) error {
switch {
case p.Role == transform.RoleKey:
next = p.Depth == 1 && string(p.Trimmed()) == "version"
case next && p.Role == transform.RoleValue:
next = false
if _, err := w.Write(p.Lead); err != nil {
return err
}
if _, err := io.WriteString(w, "2.0.0"); err != nil {
return err
}
_, err := w.Write(p.Filler())
return err
}
return transform.Copy(w, p)
})
if err := transform.Walk(os.Stdout, src, bump); err != nil {
panic(err)
}
}
Output: # service name: pet-store version: 2.0.0 # bump me ports: - 80 - 443
Types ¶
type Func ¶
Func adapts a function to Transformer.
type Option ¶
type Option func(*config)
Option configures Walk.
func WithNodePaths ¶
func WithNodePaths() Option
WithNodePaths records each node's path in the document, so a Transformer can read ast.Node.GetPath on Piece.Node.
It is off by default. The path trie grows with the document's length, where everything else a transform holds grows with its depth: a flat document of 10,000 keys pays 370 KB for it, a tenth of what the whole transform allocates, and nothing in this module reads a path.
func WithParserOptions ¶
WithParserOptions passes options on to the parse.
⚠️ Do not pass parser.WithComments: a comment reaches a transform as a piece of its own without it, and with it a directive written after a comment reaches the transform twice.
Use WithNodePaths to have the paths recorded.
func WithYAMLVersion ¶
func WithYAMLVersion(v parser.YAMLVersion) Option
WithYAMLVersion sets the version of the specification a document is read under where it declares none. See parser.WithYAMLVersion. The version sets how a plain scalar resolves, so it sets the ast.NodeType of a piece's node: "yes" is a boolean under 1.1 and a string under 1.2.
type Piece ¶
type Piece struct {
// Lead is the source between the piece before and this one's text: the
// indentation of a line and the spaces separating a token from the one
// before it. Nothing in it belongs to the token.
//
// Write it out unchanged, unless the transform rewrites the layout. A colorizer that wrapped it would paint
// the indentation.
Lead []byte
// Text is the token as the document wrote it.
//
// ⚠️ It runs to the end of the token's extent, which can hold blanks after the token's own characters: the "2"
// of "b: 2 # c" arrives as "2 ". Read [Piece.Token].Value for the value alone, and see [Piece.Trimmed] for
// the text without the blanks after it.
Text []byte
// At is where Text starts in the source, and Lead runs from At-len(Lead).
At int
// Token holds the scanner's reading of Text: its type, its position and its value. It is nil only for the
// piece closing a document that ends in text the scanner opens no token on.
Token *token.Token
// Node is the node the parse opened on this piece, and nil where the parse
// opened none: a comment, an indicator, an indentation, a "---".
//
// Node.Type() gives the type the parse resolved the text to -- [ast.IntegerType] for a plain "1",
// [ast.StringType] for a quoted one -- which the token type does not always give.
//
// [ast.Node.GetPath] returns "" unless the walk was given [WithNodePaths]:
// recording a path for every node costs memory that grows with the document,
// and a piece is named by its own token.
//
// ⚠️ Read it during the call and do not keep it. The parse reuses a node's cells once the walk moves past
// it, so a node kept for one more piece reads whichever node the parse built over it. The walk hands each
// piece over while its node still stands, and TestANodeStillPointsWhereTheWalkNamedIt checks that over the
// corpus. Copy what you need from the node, or copy [Piece.Text].
Node ast.Node
// Role names what the piece holds, for every piece, where Node is set only on some. Switch on it to treat
// keys, values, comments and indicators apart.
Role Role
// Depth counts the nodes enclosing Node: collections, and the anchors, tags
// and "?" keys written on them. A document's own body is at depth 0, and so
// is a piece no node stands on.
//
// Use it to indent: a transform that rewrites a collection reads its depth here, with no stack of its own.
Depth int
// Key reports that Node is a mapping key, so Role is RoleKey. A key and its value are two pieces of one
// entry, and the node alone cannot distinguish them.
Key bool
}
Piece is one stretch of a document, with the token and the node the parse read there.
The pieces tile the source: Lead and Text of every piece, written out one after the other, give the document back byte for byte. A transform that writes each piece unchanged copies the document, and one that writes some of them differently changes only those.
func (Piece) Filler ¶
Filler returns what Trimmed cut: the spaces and line breaks between this piece's text and the next piece's.
func (Piece) Trimmed ¶
Trimmed returns Text without the run of spaces and line breaks at its end.
⚠️ A block scalar's body ends in the line break the document wrote, and this cuts it. Use it on a piece a colorizer is wrapping, where painting the space after a token is the thing to avoid; do not use it to rebuild the document.
type Role ¶
type Role uint8
Role names what a piece holds: a key, a value, a comment, an indicator, and so on.
Every piece has one, including the comments and the "-" and ":" indicators, which carry no node.
const ( // RoleFill marks source no token opened: the text after the last token of a // document. RoleFill Role = iota // RoleKey marks a mapping key, or the "?" and the collection written as one. RoleKey // RoleValue marks a scalar written as a value or a sequence entry. Read // [Piece.Node].Type() for what the parse resolved it to. RoleValue // RoleAnchor marks an "&" and the name after it. RoleAnchor // RoleAlias marks a "*" and the name after it. RoleAlias // RoleTag marks a "!" tag, shorthand or verbatim. RoleTag // RoleComment marks a "#" comment and the line break closing it. RoleComment // RoleIndicator marks a character that writes the structure: "-", ":", // "?", ",", and the brackets and braces of a flow collection. RoleIndicator // RoleMarker marks a "---" or a "...". RoleMarker // RoleDirective marks a "%YAML" or "%TAG" line. RoleDirective // RoleText marks text the parse read and opened no node on: the body of a // block scalar, and a directive's arguments. RoleText )
type Transformer ¶
Transformer writes a document out one piece at a time.
Walk calls Piece once for every piece of the source, in the order the document wrote them. Writing Piece.Lead and Piece.Text unchanged copies the document; a transform writes something else for some of the pieces.