this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

internal/encoding/yaml: use cue/literal to quote string scalars

The YAML decoder had a function to wrap literal.Quote to use the
multi-line """ form when the string had any newlines.
It turns out that cue/literal can already do this via the option
Form.WithOptionalTabIndent, which enables an "auto" multi-line mode
to use the """ form when any newlines are present.

While here, I noticed an optimization in our use of strings.Repeat
which has already been done upstream for Go 1.23.

Signed-off-by: Daniel Martí <mvdan@mvdan.cc>
Change-Id: Iba3b9bafb0b434001173db82718b30d1e1b680ef
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1193240
TryBot-Result: CUEcueckoo <cueckoo@cuelang.org>
Unity-Result: CUE porcuepine <cue.porcuepine@gmail.com>
Reviewed-by: Roger Peppe <rogpeppe@gmail.com>

+2 -41
+1
cue/literal/quote.go
··· 65 65 // WithOptionalIndent is like WithTabIndent, but only returns a multiline 66 66 // strings if it doesn't contain any newline characters. 67 67 func (f Form) WithOptionalTabIndent(tabs int) Form { 68 + // TODO(mvdan): remove this optimization once Go 1.23 lands with https://go.dev/cl/536615 68 69 if tabs < len(tabIndent) { 69 70 f.indent = tabIndent[:tabs] 70 71 } else {
+1 -41
internal/encoding/yaml/decode.go
··· 498 498 return &ast.BasicLit{ 499 499 ValuePos: d.pos(yn), 500 500 Kind: token.STRING, 501 - Value: quoteString(yn.Value), 501 + Value: literal.String.WithOptionalTabIndent(1).Quote(yn.Value), 502 502 }, nil 503 503 504 504 case binaryTag: ··· 616 616 node, err := d.extract(yn.Alias) 617 617 delete(d.extractingAliases, yn) 618 618 return node, err 619 - } 620 - 621 - // quoteString converts a string to a CUE multiline string if needed. 622 - // TODO(mvdan): this is brought over from the old decoder; we should consider 623 - // polishing this API and moving it someplace better like cue/literal. 624 - func quoteString(s string) string { 625 - lines := []string{} 626 - last := 0 627 - for i, c := range s { 628 - if c == '\n' { 629 - lines = append(lines, s[last:i]) 630 - last = i + 1 631 - } 632 - if c == '\r' { 633 - goto quoted 634 - } 635 - } 636 - lines = append(lines, s[last:]) 637 - if len(lines) >= 2 { 638 - buf := []byte{} 639 - buf = append(buf, `"""`+"\n"...) 640 - for _, l := range lines { 641 - if l == "" { 642 - // no indentation for empty lines 643 - buf = append(buf, '\n') 644 - continue 645 - } 646 - buf = append(buf, '\t') 647 - p := len(buf) 648 - // TODO(mvdan): do not use Go's strconv for CUE syntax. 649 - buf = strconv.AppendQuote(buf, l) 650 - // remove quotes 651 - buf[p] = '\t' 652 - buf[len(buf)-1] = '\n' 653 - } 654 - buf = append(buf, "\t\t"+`"""`...) 655 - return string(buf) 656 - } 657 - quoted: 658 - return literal.String.Quote(s) 659 619 } 660 620 661 621 func labelStr(l ast.Label) string {