| 1 |
/* |
| 2 |
Copyright 2025 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
// Package kyaml provides an encoder for KYAML, a strict subset of YAML that is |
| 18 |
// designed to be explicit and unambiguous. KYAML is YAML, so any YAML parser |
| 19 |
// should be able to read it. |
| 20 |
// |
| 21 |
// KYAML is designed to be halfway between YAML and JSON, with the following |
| 22 |
// properties: |
| 23 |
// - Not whitespace-sensitive |
| 24 |
// - Allows comments |
| 25 |
// - Allows trailing commas |
| 26 |
// - Does not require quoted keys |
| 27 |
// |
| 28 |
// KYAML is an output format, and will follow these conventions: |
| 29 |
// - Always double-quote strings, even if they are not ambiguous. |
| 30 |
// - Only quote keys that might be ambiguously interpreted (e.g. "no" is |
| 31 |
// always quoted). |
| 32 |
// - Always use `{}` for structs and maps, and `[]` for lists. |
| 33 |
// - Economize on vertical space by cuddling some kinds of brackets together. |
| 34 |
// - Render multi-line strings with YAML's line folding, which is close to |
| 35 |
// the Go string literal format. |
| 36 |
// |
| 37 |
// KYAML also includes a document-separator "header" (still valid YAML), which |
| 38 |
// helps to disambiguate a KYAML document from an ill-formed JSON document. |
| 39 |
// |
| 40 |
// Because KYAML is YAML, a KYAML multi-document is a YAML multi-document. |
| 41 |
package kyaml |
| 42 |
|
| 43 |
import ( |
| 44 |
"bytes" |
| 45 |
"encoding/json" |
| 46 |
"errors" |
| 47 |
"fmt" |
| 48 |
"io" |
| 49 |
"regexp" |
| 50 |
"strconv" |
| 51 |
"strings" |
| 52 |
"time" |
| 53 |
"unicode" |
| 54 |
"unicode/utf8" |
| 55 |
|
| 56 |
yaml "go.yaml.in/yaml/v3" |
| 57 |
) |
| 58 |
|
| 59 |
// Encoder formats objects or YAML data (JSON is valid YAML) into KYAML. KYAML |
| 60 |
// is halfway between YAML and JSON, but is a strict subset of YAML, so it |
| 61 |
// should should be readable by any YAML parser. It is designed to be explicit |
| 62 |
// and unambiguous, and eschews significant whitespace. |
| 63 |
type Encoder struct { |
| 64 |
// Compact tells the encoder to use compact formatting. This puts all the |
| 65 |
// data on one line, with no extra newlines, no comments, and no multi-line |
| 66 |
// formatting. |
| 67 |
Compact bool |
| 68 |
} |
| 69 |
|
| 70 |
// FromYAML renders a KYAML (multi-)document from YAML bytes (JSON is YAML), |
| 71 |
// including the KYAML header. The result always has a trailing newline. |
| 72 |
func (ky *Encoder) FromYAML(in io.Reader, out io.Writer) error { |
| 73 |
// We need a YAML decoder to handle multi-document streams. |
| 74 |
dec := yaml.NewDecoder(in) |
| 75 |
|
| 76 |
// Process each document in the stream. |
| 77 |
for { |
| 78 |
var doc yaml.Node |
| 79 |
err := dec.Decode(&doc) |
| 80 |
if err == io.EOF { |
| 81 |
break |
| 82 |
} |
| 83 |
if err != nil { |
| 84 |
return fmt.Errorf("error decoding: %v", err) |
| 85 |
} |
| 86 |
if doc.Kind != yaml.DocumentNode { |
| 87 |
return fmt.Errorf("kyaml internal error: line %d: expected a document node, got %s", doc.Line, ky.nodeKindString(doc.Kind)) |
| 88 |
} |
| 89 |
|
| 90 |
// Always emit a document separator, which helps disambiguate between YAML |
| 91 |
// and JSON. |
| 92 |
if _, err := fmt.Fprintln(out, "---"); err != nil { |
| 93 |
return err |
| 94 |
} |
| 95 |
|
| 96 |
if err := ky.renderDocument(&doc, 0, ky.flags(), out); err != nil { |
| 97 |
return err |
| 98 |
} |
| 99 |
fmt.Fprintf(out, "\n") |
| 100 |
} |
| 101 |
|
| 102 |
return nil |
| 103 |
} |
| 104 |
|
| 105 |
// FromObject renders a KYAML document from a Go object, including the KYAML |
| 106 |
// header. The result always has a trailing newline. |
| 107 |
func (ky *Encoder) FromObject(obj any, out io.Writer) error { |
| 108 |
jb, err := json.Marshal(obj) |
| 109 |
if err != nil { |
| 110 |
return fmt.Errorf("error marshaling to JSON: %v", err) |
| 111 |
} |
| 112 |
// JSON is YAML. |
| 113 |
return ky.FromYAML(bytes.NewReader(jb), out) |
| 114 |
} |
| 115 |
|
| 116 |
// Marshal renders a single Go object as KYAML, without the header or trailing |
| 117 |
// newline. |
| 118 |
func (ky *Encoder) Marshal(obj any) ([]byte, error) { |
| 119 |
// Convert the object to JSON bytes to take advantage of all the JSON tag |
| 120 |
// handling and things like that. |
| 121 |
jb, err := json.Marshal(obj) |
| 122 |
if err != nil { |
| 123 |
return nil, fmt.Errorf("error marshaling to JSON: %v", err) |
| 124 |
} |
| 125 |
|
| 126 |
buf := &bytes.Buffer{} |
| 127 |
// JSON is YAML. |
| 128 |
if err := ky.fromObjectYAML(bytes.NewReader(jb), buf); err != nil { |
| 129 |
return nil, fmt.Errorf("error rendering object: %v", err) |
| 130 |
} |
| 131 |
return buf.Bytes(), nil |
| 132 |
} |
| 133 |
|
| 134 |
func (ky *Encoder) fromObjectYAML(in io.Reader, out io.Writer) error { |
| 135 |
yb, err := io.ReadAll(in) |
| 136 |
if err != nil { |
| 137 |
return err |
| 138 |
} |
| 139 |
|
| 140 |
var doc yaml.Node |
| 141 |
if err := yaml.Unmarshal(yb, &doc); err != nil { |
| 142 |
return fmt.Errorf("error decoding: %v", err) |
| 143 |
} |
| 144 |
if doc.Kind != yaml.DocumentNode { |
| 145 |
return fmt.Errorf("kyaml internal error: line %d: expected document node, got %s", doc.Line, ky.nodeKindString(doc.Kind)) |
| 146 |
} |
| 147 |
|
| 148 |
if err := ky.renderNode(&doc, 0, ky.flags(), out); err != nil { |
| 149 |
return fmt.Errorf("error rendering document: %v", err) |
| 150 |
} |
| 151 |
|
| 152 |
return nil |
| 153 |
} |
| 154 |
|
| 155 |
// From the YAML spec. |
| 156 |
const ( |
| 157 |
intTag = "!!int" |
| 158 |
floatTag = "!!float" |
| 159 |
boolTag = "!!bool" |
| 160 |
strTag = "!!str" |
| 161 |
timestampTag = "!!timestamp" |
| 162 |
seqTag = "!!seq" |
| 163 |
mapTag = "!!map" |
| 164 |
nullTag = "!!null" |
| 165 |
binaryTag = "!!binary" |
| 166 |
mergeTag = "!!merge" |
| 167 |
) |
| 168 |
|
| 169 |
type flagMask uint64 |
| 170 |
|
| 171 |
const ( |
| 172 |
flagsNone flagMask = 0 |
| 173 |
flagLazyQuote flagMask = 0x01 |
| 174 |
flagCompact flagMask = 0x02 |
| 175 |
) |
| 176 |
|
| 177 |
// flags returns a flagMask representing the current encoding options. It can |
| 178 |
// be used directly or OR'ed with another mask. |
| 179 |
func (ky *Encoder) flags() flagMask { |
| 180 |
flags := flagsNone |
| 181 |
if ky.Compact { |
| 182 |
flags |= flagCompact |
| 183 |
} |
| 184 |
return flags |
| 185 |
} |
| 186 |
|
| 187 |
// renderNode processes a YAML node, calling the appropriate render function |
| 188 |
// for its type. Each render function should assume that the output "cursor" |
| 189 |
// is positioned at the start of the node and should not emit a final newline. |
| 190 |
// If a render function needs to linewrap or indent (e.g. a struct), it should |
| 191 |
// assume the indent level is currently correct for the node type itself, and |
| 192 |
// may need to indent more. |
| 193 |
func (ky *Encoder) renderNode(node *yaml.Node, indent int, flags flagMask, out io.Writer) error { |
| 194 |
if node == nil { |
| 195 |
return nil |
| 196 |
} |
| 197 |
|
| 198 |
switch node.Kind { |
| 199 |
case yaml.DocumentNode: |
| 200 |
return ky.renderDocument(node, indent, flags, out) |
| 201 |
case yaml.ScalarNode: |
| 202 |
return ky.renderScalar(node, indent, flags, out) |
| 203 |
case yaml.SequenceNode: |
| 204 |
return ky.renderSequence(node, indent, flags, out) |
| 205 |
case yaml.MappingNode: |
| 206 |
return ky.renderMapping(node, indent, flags, out) |
| 207 |
case yaml.AliasNode: |
| 208 |
return ky.renderAlias(node, indent, flags, out) |
| 209 |
} |
| 210 |
return fmt.Errorf("kyaml internal error: line %d: unknown node kind %v", node.Line, node.Kind) |
| 211 |
} |
| 212 |
|
| 213 |
// renderDocument processes a YAML document node, rendering it to the output. |
| 214 |
// This function assumes that the output "cursor" is positioned at the start of |
| 215 |
// the document. This does not emit a final newline. |
| 216 |
func (ky *Encoder) renderDocument(doc *yaml.Node, indent int, flags flagMask, out io.Writer) error { |
| 217 |
if len(doc.Content) == 0 { |
| 218 |
return fmt.Errorf("kyaml internal error: line %d: document has no content node (%d)", doc.Line, len(doc.Content)) |
| 219 |
} |
| 220 |
if len(doc.Content) > 1 { |
| 221 |
return fmt.Errorf("kyaml internal error: line %d: document has more than one content node (%d)", doc.Line, len(doc.Content)) |
| 222 |
} |
| 223 |
if indent != 0 { |
| 224 |
return fmt.Errorf("kyaml internal error: line %d: document non-zero indent (%d)", doc.Line, indent) |
| 225 |
} |
| 226 |
|
| 227 |
compact := flags&flagCompact != 0 |
| 228 |
|
| 229 |
// For document nodes, the cursor is assumed to be ready to render. |
| 230 |
child := doc.Content[0] |
| 231 |
if !compact { |
| 232 |
if len(doc.HeadComment) > 0 { |
| 233 |
ky.renderComments(doc.HeadComment, indent, out) |
| 234 |
fmt.Fprint(out, "\n") |
| 235 |
} |
| 236 |
if len(child.HeadComment) > 0 { |
| 237 |
ky.renderComments(child.HeadComment, indent, out) |
| 238 |
fmt.Fprint(out, "\n") |
| 239 |
} |
| 240 |
} |
| 241 |
if err := ky.renderNode(child, indent, flags, out); err != nil { |
| 242 |
return err |
| 243 |
} |
| 244 |
if !compact { |
| 245 |
if len(child.LineComment) > 0 { |
| 246 |
ky.renderComments(" "+child.LineComment, 0, out) |
| 247 |
} |
| 248 |
if len(child.FootComment) > 0 { |
| 249 |
fmt.Fprint(out, "\n") |
| 250 |
ky.renderComments(child.FootComment, indent, out) |
| 251 |
} |
| 252 |
if len(doc.LineComment) > 0 { |
| 253 |
fmt.Fprint(out, "\n") |
| 254 |
ky.renderComments(" "+doc.LineComment, 0, out) |
| 255 |
} |
| 256 |
if len(doc.FootComment) > 0 { |
| 257 |
fmt.Fprint(out, "\n") |
| 258 |
ky.renderComments(doc.FootComment, indent, out) |
| 259 |
} |
| 260 |
} |
| 261 |
return nil |
| 262 |
} |
| 263 |
|
| 264 |
// renderScalar processes a YAML scalar node, rendering it to the output. This |
| 265 |
// DOES NOT render a trailing newline or head/line/foot comments, as those |
| 266 |
// require the parent context. |
| 267 |
func (ky *Encoder) renderScalar(node *yaml.Node, indent int, flags flagMask, out io.Writer) error { |
| 268 |
switch node.Tag { |
| 269 |
case intTag, floatTag, boolTag, nullTag: |
| 270 |
fmt.Fprint(out, node.Value) |
| 271 |
case strTag, timestampTag: |
| 272 |
return ky.renderString(node.Value, indent+1, flags, out) |
| 273 |
default: |
| 274 |
return fmt.Errorf("kyaml internal error: line %d: unknown tag %q on scalar node %q", node.Line, node.Tag, node.Value) |
| 275 |
} |
| 276 |
return nil |
| 277 |
} |
| 278 |
|
| 279 |
const kyamlFoldStr = "\\\n" |
| 280 |
|
| 281 |
var regularEscapeMap = map[rune]string{ |
| 282 |
'\n': "\\n" + kyamlFoldStr, // use YAML's line folding to make the output more readable |
| 283 |
'\t': "\t", // literal tab |
| 284 |
} |
| 285 |
var compactEscapeMap = map[rune]string{ |
| 286 |
'\n': "\\n", |
| 287 |
'\t': "\\t", |
| 288 |
} |
| 289 |
|
| 290 |
// renderString processes a string (either single-line or multi-line), |
| 291 |
// rendering it to the output. This DOES NOT render a trailing newline. |
| 292 |
func (ky *Encoder) renderString(val string, indent int, flags flagMask, out io.Writer) error { |
| 293 |
lazyQuote := flags&flagLazyQuote != 0 |
| 294 |
compact := flags&flagCompact != 0 |
| 295 |
multi := strings.Contains(val, "\n") |
| 296 |
|
| 297 |
if !multi && lazyQuote && !needsQuotes(val) { |
| 298 |
fmt.Fprint(out, val) |
| 299 |
return nil |
| 300 |
} |
| 301 |
|
| 302 |
// Special cases for certain input. |
| 303 |
escapeOverrides := regularEscapeMap |
| 304 |
if compact { |
| 305 |
escapeOverrides = compactEscapeMap |
| 306 |
} |
| 307 |
|
| 308 |
// |
| 309 |
// The rest of this is borrowed from Go's strconv.Quote implementation. |
| 310 |
// |
| 311 |
|
| 312 |
// accumulate into a buffer |
| 313 |
buf := &bytes.Buffer{} |
| 314 |
|
| 315 |
// opening quote |
| 316 |
fmt.Fprint(buf, `"`) |
| 317 |
if multi && !compact { |
| 318 |
fmt.Fprint(buf, kyamlFoldStr) |
| 319 |
} |
| 320 |
|
| 321 |
// Iterating a string with invalid UTF8 returns RuneError rather than the |
| 322 |
// bytes, so we iterate the string and decode the runes. This is a bit |
| 323 |
// slower, but gives us a better result. |
| 324 |
s := val |
| 325 |
for width := 0; len(s) > 0; s = s[width:] { |
| 326 |
r := rune(s[0]) |
| 327 |
width = 1 |
| 328 |
if r >= utf8.RuneSelf { |
| 329 |
r, width = utf8.DecodeRuneInString(s) |
| 330 |
} |
| 331 |
if width == 1 && r == utf8.RuneError { |
| 332 |
fmt.Fprint(buf, `\x`) |
| 333 |
fmt.Fprintf(buf, "%02x", s[0]) |
| 334 |
continue |
| 335 |
} |
| 336 |
ky.appendEscapedRune(r, indent, escapeOverrides, buf) |
| 337 |
} |
| 338 |
|
| 339 |
// closing quote |
| 340 |
afterNewline := buf.Bytes()[len(buf.Bytes())-1] == '\n' |
| 341 |
if multi && !compact { |
| 342 |
if !afterNewline { |
| 343 |
fmt.Fprint(buf, kyamlFoldStr) |
| 344 |
} |
| 345 |
ky.writeIndent(indent, buf) |
| 346 |
} |
| 347 |
fmt.Fprint(buf, `"`) |
| 348 |
|
| 349 |
fmt.Fprint(out, buf.String()) |
| 350 |
|
| 351 |
return nil |
| 352 |
} |
| 353 |
|
| 354 |
var allowedUnquotedAnywhere = map[rune]bool{ |
| 355 |
'_': true, |
| 356 |
} |
| 357 |
|
| 358 |
var allowedUnquotedInterior = map[rune]bool{ |
| 359 |
'-': true, |
| 360 |
'.': true, |
| 361 |
'/': true, |
| 362 |
} |
| 363 |
|
| 364 |
func needsQuotes(s string) bool { |
| 365 |
if s == "" { |
| 366 |
return true |
| 367 |
} |
| 368 |
if isTypeAmbiguous(s) { |
| 369 |
return true |
| 370 |
} |
| 371 |
runes := []rune(s) |
| 372 |
for i, r := range runes { |
| 373 |
if unicode.IsLetter(r) || unicode.IsNumber(r) || allowedUnquotedAnywhere[r] { |
| 374 |
continue |
| 375 |
} |
| 376 |
if i > 0 && i < len(runes)-1 && allowedUnquotedInterior[r] { |
| 377 |
continue |
| 378 |
} |
| 379 |
// it's something we don't explicitly allow |
| 380 |
return true |
| 381 |
} |
| 382 |
return false |
| 383 |
} |
| 384 |
|
| 385 |
// From https://yaml.org/type/int.html and https://yaml.org/type/float.html |
| 386 |
var sexagesimalRE = regexp.MustCompile(`^[+-]?[1-9][0-9_]*(:[0-5]?[0-9])+(\.[0-9_]*)?$`) |
| 387 |
|
| 388 |
// isTypeAmbiguous returns true if a YAML parser might interpret the unquoted |
| 389 |
// form of the string argument as a YAML type other than string (e.g. `true` |
| 390 |
// would be interpreted as a boolean). |
| 391 |
func isTypeAmbiguous(s string) bool { |
| 392 |
// Null-like strings: https://yaml.org/type/null.html |
| 393 |
if len(s) <= 5 { |
| 394 |
switch strings.ToLower(s) { |
| 395 |
case "null", "~", "": |
| 396 |
return true |
| 397 |
} |
| 398 |
} |
| 399 |
|
| 400 |
// Boolean-like strings: https://yaml.org/type/bool.html |
| 401 |
if _, err := strconv.ParseBool(s); err == nil { |
| 402 |
return true |
| 403 |
} |
| 404 |
if len(s) <= 5 { |
| 405 |
switch strings.ToLower(s) { |
| 406 |
case "true", "y", "yes", "on", "false", "n", "no", "off": |
| 407 |
return true |
| 408 |
} |
| 409 |
} |
| 410 |
|
| 411 |
// Number-like strings: https://yaml.org/type/int.html and |
| 412 |
// https://yaml.org/type/float.html |
| 413 |
// |
| 414 |
// NOTE: the stripping of underscores is gross. |
| 415 |
sWithoutUnderscores := strings.ReplaceAll(s, "_", "") |
| 416 |
// Handles binary ("0b"), octal ("0" or "0o"), decimal, and hex ("0x") |
| 417 |
if _, err := strconv.ParseInt(sWithoutUnderscores, 0, 64); err == nil && !isSyntaxError(err) { |
| 418 |
return true |
| 419 |
} |
| 420 |
// Handles standard and scientific notation. |
| 421 |
if _, err := strconv.ParseFloat(sWithoutUnderscores, 64); err == nil && !isSyntaxError(err) { |
| 422 |
return true |
| 423 |
} |
| 424 |
|
| 425 |
// Sexagesimal strings like "11:00" (in YAML 1.1, removed in 1.2): |
| 426 |
// https://yaml.org/type/int.html and https://yaml.org/type/float.html |
| 427 |
if sexagesimalRE.MatchString(s) { |
| 428 |
return true |
| 429 |
} |
| 430 |
|
| 431 |
// Infinity and NaN: https://yaml.org/type/float.html |
| 432 |
if len(s) <= 5 { |
| 433 |
switch strings.ToLower(s) { |
| 434 |
case ".inf", "-.inf", "+.inf", ".nan": |
| 435 |
return true |
| 436 |
} |
| 437 |
} |
| 438 |
|
| 439 |
// Time-like strings |
| 440 |
if _, matches := parseTimestamp(s); matches { |
| 441 |
return true |
| 442 |
} |
| 443 |
|
| 444 |
return false |
| 445 |
} |
| 446 |
|
| 447 |
func isSyntaxError(err error) bool { |
| 448 |
var numerr *strconv.NumError |
| 449 |
if ok := errors.As(err, &numerr); ok { |
| 450 |
return errors.Is(numerr.Err, strconv.ErrSyntax) |
| 451 |
} |
| 452 |
return false |
| 453 |
} |
| 454 |
|
| 455 |
// This is a subset of the formats allowed by the regular expression |
| 456 |
// defined at http://yaml.org/type/timestamp.html. |
| 457 |
// |
| 458 |
// NOTE: This was copied from go.yaml.in/yaml/v2 |
| 459 |
var allowedTimestampFormats = []string{ |
| 460 |
"2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. |
| 461 |
"2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". |
| 462 |
"2006-1-2 15:4:5.999999999", // space separated with no time zone |
| 463 |
"2006-1-2", // date only |
| 464 |
// Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" |
| 465 |
// from the set of examples. |
| 466 |
} |
| 467 |
|
| 468 |
// parseTimestamp parses s as a timestamp string and |
| 469 |
// returns the timestamp and reports whether it succeeded. |
| 470 |
// Timestamp formats are defined at http://yaml.org/type/timestamp.html |
| 471 |
// |
| 472 |
// NOTE: This was copied from go.yaml.in/yaml/v2 |
| 473 |
func parseTimestamp(s string) (time.Time, bool) { |
| 474 |
// TODO write code to check all the formats supported by |
| 475 |
// http://yaml.org/type/timestamp.html instead of using time.Parse. |
| 476 |
|
| 477 |
// Quick check: all date formats start with YYYY-. |
| 478 |
i := 0 |
| 479 |
for ; i < len(s); i++ { |
| 480 |
if c := s[i]; c < '0' || c > '9' { |
| 481 |
break |
| 482 |
} |
| 483 |
} |
| 484 |
if i != 4 || i == len(s) || s[i] != '-' { |
| 485 |
return time.Time{}, false |
| 486 |
} |
| 487 |
for _, format := range allowedTimestampFormats { |
| 488 |
if t, err := time.Parse(format, s); err == nil { |
| 489 |
return t, true |
| 490 |
} |
| 491 |
} |
| 492 |
return time.Time{}, false |
| 493 |
} |
| 494 |
|
| 495 |
// We use a buffer here so we can peek backwards. |
| 496 |
func (ky *Encoder) appendEscapedRune(r rune, indent int, escapeOverrides map[rune]string, buf *bytes.Buffer) { |
| 497 |
afterNewline := buf.Bytes()[len(buf.Bytes())-1] == '\n' |
| 498 |
|
| 499 |
if afterNewline { |
| 500 |
ky.writeIndent(indent, buf) |
| 501 |
// We want to preserve leading whitespace in the source string, so if |
| 502 |
// we find whitespace, we need to escape it. We don't want to |
| 503 |
// escape lines without leading whitespace, but we DO want to render |
| 504 |
// the result with fidelity to vertical alignment, so we write an extra |
| 505 |
// space. This is OK, because all whitespace before the first |
| 506 |
// non-whitespace character is dropped, as per YAML spec. If there are |
| 507 |
// no lines with leading whitespace it looks like the indent is one too |
| 508 |
// many, which seems OK. |
| 509 |
if unicode.IsSpace(r) && r != '\n' { |
| 510 |
buf.WriteRune('\\') |
| 511 |
} else { |
| 512 |
buf.WriteRune(' ') |
| 513 |
} |
| 514 |
} |
| 515 |
if s, found := escapeOverrides[r]; found { |
| 516 |
buf.WriteString(s) |
| 517 |
return |
| 518 |
} |
| 519 |
if r == '"' || r == '\\' { // always escaped |
| 520 |
buf.WriteRune('\\') |
| 521 |
buf.WriteRune(r) |
| 522 |
return |
| 523 |
} |
| 524 |
if unicode.IsPrint(r) { |
| 525 |
buf.WriteRune(r) |
| 526 |
return |
| 527 |
} |
| 528 |
switch r { |
| 529 |
case '\a': |
| 530 |
buf.WriteString(`\a`) |
| 531 |
case '\b': |
| 532 |
buf.WriteString(`\b`) |
| 533 |
case '\f': |
| 534 |
buf.WriteString(`\f`) |
| 535 |
case '\n': |
| 536 |
buf.WriteString(`\n`) |
| 537 |
case '\r': |
| 538 |
buf.WriteString(`\r`) |
| 539 |
case '\t': |
| 540 |
buf.WriteString(`\t`) |
| 541 |
case '\v': |
| 542 |
buf.WriteString(`\v`) |
| 543 |
case '\x00': |
| 544 |
buf.WriteString(`\0`) |
| 545 |
case '\x1b': |
| 546 |
buf.WriteString(`\e`) |
| 547 |
case '\x85': |
| 548 |
buf.WriteString(`\N`) |
| 549 |
case '\xa0': |
| 550 |
buf.WriteString(`\_`) |
| 551 |
case '\u2028': |
| 552 |
buf.WriteString(`\L`) |
| 553 |
case '\u2029': |
| 554 |
buf.WriteString(`\P`) |
| 555 |
default: |
| 556 |
const hexits = "0123456789abcdef" |
| 557 |
switch { |
| 558 |
case r < ' ' || r == 0x7f: |
| 559 |
buf.WriteString(`\x`) |
| 560 |
buf.WriteByte(hexits[byte(r)>>4]) |
| 561 |
buf.WriteByte(hexits[byte(r)&0xF]) |
| 562 |
case !utf8.ValidRune(r): |
| 563 |
r = utf8.RuneError |
| 564 |
fallthrough |
| 565 |
case r < 0x10000: |
| 566 |
buf.WriteString(`\u`) |
| 567 |
for s := 12; s >= 0; s -= 4 { |
| 568 |
buf.WriteByte(hexits[r>>uint(s)&0xF]) |
| 569 |
} |
| 570 |
default: |
| 571 |
buf.WriteString(`\U`) |
| 572 |
for s := 28; s >= 0; s -= 4 { |
| 573 |
buf.WriteByte(hexits[r>>uint(s)&0xF]) |
| 574 |
} |
| 575 |
} |
| 576 |
} |
| 577 |
} |
| 578 |
|
| 579 |
// renderSequence processes a YAML sequence node, rendering it to the output. This |
| 580 |
// DOES NOT render a trailing newline or head/line/foot comments of the sequence |
| 581 |
// itself, but DOES render comments of the child nodes. |
| 582 |
func (ky *Encoder) renderSequence(node *yaml.Node, indent int, flags flagMask, out io.Writer) error { |
| 583 |
if len(node.Content) == 0 { |
| 584 |
fmt.Fprint(out, "[]") |
| 585 |
return nil |
| 586 |
} |
| 587 |
if flags&flagCompact != 0 { |
| 588 |
return ky.renderCompactSequence(node, flags, out) |
| 589 |
} |
| 590 |
|
| 591 |
// See if this list can use cuddled formatting. |
| 592 |
cuddle := true |
| 593 |
for _, child := range node.Content { |
| 594 |
if !isCuddledKind(child) { |
| 595 |
cuddle = false |
| 596 |
break |
| 597 |
} |
| 598 |
if len(child.HeadComment)+len(child.LineComment)+len(child.FootComment) > 0 { |
| 599 |
cuddle = false |
| 600 |
break |
| 601 |
} |
| 602 |
} |
| 603 |
|
| 604 |
if cuddle { |
| 605 |
return ky.renderCuddledSequence(node, indent, flags, out) |
| 606 |
} |
| 607 |
return ky.renderUncuddledSequence(node, indent, flags, out) |
| 608 |
} |
| 609 |
|
| 610 |
// renderCompactSequence renders a YAML sequence node in compact form. |
| 611 |
func (ky *Encoder) renderCompactSequence(node *yaml.Node, flags flagMask, out io.Writer) error { |
| 612 |
fmt.Fprint(out, "[") |
| 613 |
for i, child := range node.Content { |
| 614 |
if i > 0 { |
| 615 |
fmt.Fprint(out, ", ") |
| 616 |
} |
| 617 |
if err := ky.renderNode(child, 0, flags, out); err != nil { |
| 618 |
return err |
| 619 |
} |
| 620 |
} |
| 621 |
fmt.Fprint(out, "]") |
| 622 |
return nil |
| 623 |
} |
| 624 |
|
| 625 |
// renderCuddledSequence processes a YAML sequence node which has already been |
| 626 |
// determined to be cuddled. We only cuddle sequences of structs or lists |
| 627 |
// which have no comments. |
| 628 |
func (ky *Encoder) renderCuddledSequence(node *yaml.Node, indent int, flags flagMask, out io.Writer) error { |
| 629 |
fmt.Fprint(out, "[") |
| 630 |
for i, child := range node.Content { |
| 631 |
// Each iteration should leave us cuddled for the next item. |
| 632 |
if i > 0 { |
| 633 |
fmt.Fprint(out, ", ") |
| 634 |
} |
| 635 |
if err := ky.renderNode(child, indent, flags, out); err != nil { |
| 636 |
return err |
| 637 |
} |
| 638 |
} |
| 639 |
fmt.Fprint(out, "]") |
| 640 |
return nil |
| 641 |
} |
| 642 |
|
| 643 |
func (ky *Encoder) renderUncuddledSequence(node *yaml.Node, indent int, flags flagMask, out io.Writer) error { |
| 644 |
// Get into the right state for the first item. |
| 645 |
fmt.Fprint(out, "[\n") |
| 646 |
ky.writeIndent(indent, out) |
| 647 |
for _, child := range node.Content { |
| 648 |
// Each iteration should leave us ready to close the list. Since we |
| 649 |
// have an item to render, we need 1 more indent. |
| 650 |
ky.writeIndent(1, out) |
| 651 |
|
| 652 |
if len(child.HeadComment) > 0 { |
| 653 |
ky.renderComments(child.HeadComment, indent+1, out) |
| 654 |
fmt.Fprint(out, "\n") |
| 655 |
ky.writeIndent(indent+1, out) |
| 656 |
} |
| 657 |
|
| 658 |
if err := ky.renderNode(child, indent+1, flags, out); err != nil { |
| 659 |
return err |
| 660 |
} |
| 661 |
|
| 662 |
fmt.Fprint(out, ",") |
| 663 |
if len(child.LineComment) > 0 { |
| 664 |
ky.renderComments(" "+child.LineComment, 0, out) |
| 665 |
} |
| 666 |
fmt.Fprint(out, "\n") |
| 667 |
ky.writeIndent(indent, out) |
| 668 |
if len(child.FootComment) > 0 { |
| 669 |
ky.writeIndent(1, out) |
| 670 |
ky.renderComments(child.FootComment, indent+1, out) |
| 671 |
fmt.Fprint(out, "\n") |
| 672 |
ky.writeIndent(indent, out) |
| 673 |
} |
| 674 |
} |
| 675 |
fmt.Fprint(out, "]") |
| 676 |
|
| 677 |
return nil |
| 678 |
} |
| 679 |
|
| 680 |
func (ky *Encoder) nodeKindString(kind yaml.Kind) string { |
| 681 |
switch kind { |
| 682 |
case yaml.DocumentNode: |
| 683 |
return "document" |
| 684 |
case yaml.ScalarNode: |
| 685 |
return "scalar" |
| 686 |
case yaml.MappingNode: |
| 687 |
return "mapping" |
| 688 |
case yaml.SequenceNode: |
| 689 |
return "sequence" |
| 690 |
case yaml.AliasNode: |
| 691 |
return "alias" |
| 692 |
default: |
| 693 |
return "unknown" |
| 694 |
} |
| 695 |
} |
| 696 |
|
| 697 |
func isCuddledKind(node *yaml.Node) bool { |
| 698 |
if node == nil { |
| 699 |
return false |
| 700 |
} |
| 701 |
switch node.Kind { |
| 702 |
case yaml.SequenceNode, yaml.MappingNode: |
| 703 |
return true |
| 704 |
case yaml.AliasNode: |
| 705 |
return isCuddledKind(node.Alias) |
| 706 |
} |
| 707 |
return false |
| 708 |
} |
| 709 |
|
| 710 |
// renderMapping processes a YAML mapping node, rendering it to the output. This |
| 711 |
// DOES NOT render a trailing newline or head/line/foot comments of the mapping |
| 712 |
// itself, but DOES render comments of the child nodes. |
| 713 |
func (ky *Encoder) renderMapping(node *yaml.Node, indent int, flags flagMask, out io.Writer) error { |
| 714 |
if len(node.Content) == 0 { |
| 715 |
fmt.Fprint(out, "{}") |
| 716 |
return nil |
| 717 |
} |
| 718 |
|
| 719 |
if flags&flagCompact != 0 { |
| 720 |
return ky.renderCompactMapping(node, flags, out) |
| 721 |
} |
| 722 |
|
| 723 |
joinComments := func(a, b string) string { |
| 724 |
if len(a) > 0 && len(b) > 0 { |
| 725 |
return a + "\n" + b |
| 726 |
} |
| 727 |
return a + b |
| 728 |
} |
| 729 |
|
| 730 |
fmt.Fprint(out, "{\n") |
| 731 |
for i := 0; i < len(node.Content); i += 2 { |
| 732 |
key := node.Content[i] |
| 733 |
val := node.Content[i+1] |
| 734 |
|
| 735 |
ky.writeIndent(indent+1, out) |
| 736 |
|
| 737 |
// Only one of these should be set. |
| 738 |
if comments := joinComments(key.HeadComment, val.HeadComment); len(comments) > 0 { |
| 739 |
ky.renderComments(comments, indent+1, out) |
| 740 |
fmt.Fprint(out, "\n") |
| 741 |
ky.writeIndent(indent+1, out) |
| 742 |
} |
| 743 |
|
| 744 |
// Mapping keys are always strings in KYAML, even if the YAML node says |
| 745 |
// otherwise. |
| 746 |
if err := ky.renderString(key.Value, indent+1, flagLazyQuote|flagCompact, out); err != nil { |
| 747 |
return err |
| 748 |
} |
| 749 |
fmt.Fprint(out, ": ") |
| 750 |
if err := ky.renderNode(val, indent+1, flags, out); err != nil { |
| 751 |
return err |
| 752 |
} |
| 753 |
fmt.Fprint(out, ",") |
| 754 |
if len(key.LineComment) > 0 && len(val.LineComment) > 0 { |
| 755 |
return fmt.Errorf("kyaml internal error: line %d: both key and value have line comments", key.Line) |
| 756 |
} |
| 757 |
if len(key.LineComment) > 0 { |
| 758 |
ky.renderComments(" "+key.LineComment, 0, out) |
| 759 |
} else if len(val.LineComment) > 0 { |
| 760 |
ky.renderComments(" "+val.LineComment, 0, out) |
| 761 |
} |
| 762 |
fmt.Fprint(out, "\n") |
| 763 |
// Only one of these should be set. |
| 764 |
if comments := joinComments(key.FootComment, val.FootComment); len(comments) > 0 { |
| 765 |
ky.writeIndent(indent+1, out) |
| 766 |
ky.renderComments(comments, indent+1, out) |
| 767 |
fmt.Fprint(out, "\n") |
| 768 |
} |
| 769 |
} |
| 770 |
ky.writeIndent(indent, out) |
| 771 |
fmt.Fprint(out, "}") |
| 772 |
return nil |
| 773 |
} |
| 774 |
|
| 775 |
// renderCompactMapping renders a YAML mapping node in compact form. |
| 776 |
func (ky *Encoder) renderCompactMapping(node *yaml.Node, flags flagMask, out io.Writer) error { |
| 777 |
fmt.Fprint(out, "{") |
| 778 |
for i := 0; i < len(node.Content); i += 2 { |
| 779 |
key := node.Content[i] |
| 780 |
val := node.Content[i+1] |
| 781 |
|
| 782 |
if i > 0 { |
| 783 |
fmt.Fprint(out, ", ") |
| 784 |
} |
| 785 |
// Mapping keys are always strings in KYAML, even if the YAML node says |
| 786 |
// otherwise. |
| 787 |
if err := ky.renderString(key.Value, 0, flags|flagLazyQuote|flagCompact, out); err != nil { |
| 788 |
return err |
| 789 |
} |
| 790 |
fmt.Fprint(out, ": ") |
| 791 |
if err := ky.renderNode(val, 0, flags, out); err != nil { |
| 792 |
return err |
| 793 |
} |
| 794 |
} |
| 795 |
fmt.Fprint(out, "}") |
| 796 |
return nil |
| 797 |
} |
| 798 |
|
| 799 |
func (ky *Encoder) writeIndent(level int, out io.Writer) { |
| 800 |
const indentString = " " |
| 801 |
for range level { |
| 802 |
fmt.Fprint(out, indentString) |
| 803 |
} |
| 804 |
} |
| 805 |
|
| 806 |
// renderCommentBlock writes the comments node to the output. This assumes the |
| 807 |
// cursor is at the right place to start writing and DOES NOT render a trailing |
| 808 |
// newline. |
| 809 |
func (ky *Encoder) renderComments(comments string, indent int, out io.Writer) { |
| 810 |
if len(comments) == 0 { |
| 811 |
return |
| 812 |
} |
| 813 |
lines := strings.Split(comments, "\n") |
| 814 |
for i, line := range lines { |
| 815 |
if i > 0 { |
| 816 |
fmt.Fprint(out, "\n") |
| 817 |
ky.writeIndent(indent, out) |
| 818 |
} |
| 819 |
fmt.Fprint(out, line) |
| 820 |
} |
| 821 |
} |
| 822 |
|
| 823 |
func (ky *Encoder) renderAlias(node *yaml.Node, indent int, flags flagMask, out io.Writer) error { |
| 824 |
if node.Alias != nil { |
| 825 |
return ky.renderNode(node.Alias, indent+1, flags, out) |
| 826 |
} |
| 827 |
return nil |
| 828 |
} |