/
format.go
819 lines (764 loc) · 16.6 KB
/
format.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
package toml
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"strconv"
"strings"
"time"
"unicode/utf8"
)
type FormatRule func(*Formatter) error
// Set the character to indent lines. If tab is let to 0, tab character will
// be used otherwise one or multiple space(s)
func WithTab(tab int) FormatRule {
return func(ft *Formatter) error {
if tab >= 1 {
ft.withTab = strings.Repeat(" ", tab)
}
return nil
}
}
// Tell the formatter to keep empty table when rewritting the document.
func WithEmpty(with bool) FormatRule {
return func(ft *Formatter) error {
ft.withEmpty = with
return nil
}
}
// Tell the formatter to indent nested sub table(s). If not set, all tables will
// be aligned.
func WithNest(with bool) FormatRule {
return func(ft *Formatter) error {
ft.withNest = with
return nil
}
}
// Tell the formatter to keep comments from the original document when rewritting.
func WithComment(with bool) FormatRule {
return func(ft *Formatter) error {
ft.withComment = with
return nil
}
}
// Tell the formatter to keep the format of the values as found in the original
// document.
// Using this option disables other options that format values.
func WithRaw(with bool) FormatRule {
return func(ft *Formatter) error {
ft.withRaw = with
return nil
}
}
// Tell the formatter to reformat (array of) inline table(s) to (array of) regular table(s)
func WithInline(inline bool) FormatRule {
return func(ft *Formatter) error {
ft.withInline = inline
return nil
}
}
// Tell the formatter how to reformat arrays. By default, array with 0 or 1 element
// will always be written on the same line.
func WithArray(format string) FormatRule {
return func(ft *Formatter) error {
switch strings.ToLower(format) {
case "", "mixed":
ft.withArray = arrayMixed
case "multi":
ft.withArray = arrayMulti
case "single":
ft.withArray = arraySingle
default:
return fmt.Errorf("%s: unsupported array format", format)
}
return nil
}
}
// Tell the formatter to use the precision of millisecond to use and if it is needed
// to convert offset datetime to UTC.
func WithTime(millis int, utc bool) FormatRule {
return func(ft *Formatter) error {
if millis > 9 {
millis = 9
}
pattern := "2006-01-02 15:04:05"
if millis > 0 {
pattern += "." + strings.Repeat("0", millis)
}
pattern += "-07:00"
ft.timeconv = formatTime(pattern, utc)
return nil
}
}
// Tell the formatter how to format floating point number and where to write an
// underscore to make it more readable (if needed)
func WithFloat(format string, underscore int) FormatRule {
return func(ft *Formatter) error {
var spec byte
switch strings.ToLower(format) {
case "e", "scientific":
spec = 'e'
case "", "f", "float":
spec = 'f'
case "g", "auto":
spec = 'g'
default:
return fmt.Errorf("%s: unsupported specifier", format)
}
ft.floatconv = formatFloat(spec, underscore)
return nil
}
}
// Tell the formatter which base to use to rewrite integer number and where to write
// an underscore to make it more readable (if needed)
func WithNumber(format string, underscore int) FormatRule {
return func(ft *Formatter) error {
var (
base int
prefix string
)
switch strings.ToLower(format) {
case "x", "hexa", "hex":
base, prefix = 16, "0x"
case "o", "octal", "oct":
base, prefix = 8, "0o"
case "b", "binary", "bin":
base, prefix = 2, "0b"
case "", "d", "decimal", "dec":
base = 10
default:
return fmt.Errorf("%s: unsupported base", format)
}
ft.intconv = formatInteger(base, underscore, prefix)
return nil
}
}
// Tell the formatter which sequence of character to use to write the end of line.
func WithEOL(format string) FormatRule {
return func(ft *Formatter) error {
switch strings.ToLower(format) {
case "crlf", "windows":
ft.withEOL = "\r\n"
case "lf", "linux", "":
ft.withEOL = "\n"
default:
return fmt.Errorf("%s: unsupported eof", format)
}
return nil
}
}
const (
arrayMixed int = iota
arraySingle
arrayMulti
)
// Formatter is responsible to rewrite a TOML document according to the settings
// given by user.
type Formatter struct {
doc Node
writer *bufio.Writer
floatconv func(string) (string, error)
intconv func(string) (string, error)
timeconv func(string) (string, error)
withArray int
withInline bool
withTab string
withEOL string
withEmpty bool
withComment bool
withNest bool
currLevel int
withRaw bool
}
// Create a new Formatter that will rewrite the TOML document doc according to the
// rules specify.
func NewFormatter(doc string, rules ...FormatRule) (*Formatter, error) {
identity := func(str string) (string, error) {
return str, nil
}
f := Formatter{
floatconv: identity,
intconv: identity,
timeconv: identity,
withArray: arrayMixed,
withInline: false,
withEmpty: false,
withNest: false,
withComment: true,
withTab: "\t",
withEOL: "\n",
withRaw: false,
}
buf, err := ioutil.ReadFile(doc)
if err != nil {
return nil, err
}
f.doc, err = Parse(bytes.NewReader(buf))
if err != nil {
return nil, err
}
for _, rfn := range rules {
if err := rfn(&f); err != nil {
return nil, err
}
}
return &f, nil
}
// Reformat the document
func (f *Formatter) Format(w io.Writer) error {
f.writer = bufio.NewWriter(w)
root, ok := f.doc.(*Table)
if !ok {
return fmt.Errorf("document not parsed properly")
}
if err := f.formatTable(root, nil); err != nil {
return err
}
return f.writer.Flush()
}
func (f *Formatter) formatTable(curr *Table, paths []string) error {
options := curr.listOptions()
if f.withEmpty || len(options) > 0 {
f.formatHeader(curr, paths)
err := f.formatOptions(options, append(paths, curr.key.Literal))
if err != nil {
return nil
}
f.endLine()
}
if !curr.isRoot() && curr.kind.isContainer() {
paths = append(paths, curr.key.Literal)
}
if f.canNest(curr) {
f.enterLevel(false)
defer f.leaveLevel(false)
}
for _, next := range curr.listTables() {
if err := f.formatTable(next, paths); err != nil {
return err
}
}
return nil
}
func (f *Formatter) formatOptions(options []*Option, paths []string) error {
type table struct {
prefix string
*Table
}
var (
length = longestKey(options)
array int
inlines []table
)
for _, o := range options {
if i, ok := o.value.(*Table); ok && f.withInline {
i.kind = tableRegular
i.key = o.key
i.comment = o.comment
inlines = append(inlines, table{Table: i})
continue
}
if i, ok := o.value.(*Array); ok && f.withInline {
var (
a Array
t = Table{kind: tableArray, key: o.key}
)
for _, n := range i.nodes {
if nod, ok := n.(*Table); ok {
nod.key = o.key
nod.kind = tableItem
t.nodes = append(t.nodes, nod)
} else {
a.nodes = append(a.nodes, n)
}
}
if !t.isEmpty() {
sub := table{Table: &t}
if !a.isEmpty() {
sub.prefix = fmt.Sprintf("\"#%d\"", array)
array++
}
inlines = append(inlines, sub)
}
if a.isEmpty() {
continue
}
o.value = &a
}
f.formatComment(o.comment.pre, true)
f.beginLine()
f.writeKey(o.key.Literal, length)
if err := f.formatValue(o.value); err != nil {
return err
}
f.formatComment(o.comment.post, false)
f.endLine()
}
if len(inlines) > 0 {
f.endLine()
f.enterLevel(false)
defer f.leaveLevel(false)
for _, i := range inlines {
parents := append([]string{}, paths...)
if i.prefix != "" {
parents = append(parents, i.prefix)
}
if err := f.formatTable(i.Table, parents); err != nil {
return err
}
}
}
return nil
}
func (f *Formatter) formatValue(n Node) error {
if n == nil {
return nil
}
var err error
switch n := n.(type) {
case *Literal:
if f.withRaw {
f.writer.WriteString(n.token.Raw)
break
}
err = f.formatLiteral(n)
case *Array:
err = f.formatArray(n)
case *Table:
err = f.formatInline(n)
default:
err = fmt.Errorf("unexpected value type %T", n)
}
return err
}
func (f *Formatter) formatLiteral(i *Literal) error {
if i.token.isString() {
f.formatString(i.token)
return nil
}
str, err := f.convertValue(i.token)
if err == nil {
f.writer.WriteString(str)
}
return err
}
func (f *Formatter) formatString(tok Token) {
var (
isMulti bool
quoting string
escape func(rune) (rune, bool)
)
switch tok.Type {
case TokBasic:
escape = escapeBasic
quoting = "\""
case TokBasicMulti:
escape = escapeMulti
quoting, isMulti = "\"\"\"", true
case TokLiteral:
quoting = "'"
case TokLiteralMulti:
quoting, isMulti = "'''", true
default:
return
}
f.writer.WriteString(quoting)
if isMulti {
f.endLine()
}
str := escapeString(tok.Literal, isMulti, escape)
if isMulti && strings.IndexByte(str, newline) < 0 {
str = textWrap(str)
}
f.writer.WriteString(str)
f.writer.WriteString(quoting)
}
func textWrap(str string) string {
var (
scan = bufio.NewScanner(strings.NewReader(str))
buf strings.Builder
)
const (
length = 72
limit = 8
)
scan.Split(func(data []byte, ateof bool) (int, []byte, error) {
if ateof {
return len(data), data, bufio.ErrFinalToken
}
var i, j int
for i < length {
x := bytes.IndexAny(data[i:], " \t.?,!;")
if x < 0 {
return 0, nil, nil
}
j, i = i, i+x+1
}
if i >= length+limit {
i = j
}
return i, data[:i], nil
})
scan.Scan()
for {
buf.WriteString(scan.Text())
if !scan.Scan() {
break
}
buf.WriteRune(backslash)
buf.WriteRune(newline)
}
return buf.String()
}
func escapeBasic(r rune) (rune, bool) {
switch r {
case backslash:
case dquote:
case newline:
r = 'n'
case tab:
r = 't'
case formfeed:
r = 'f'
case backspace:
r = 'b'
case carriage:
r = 'r'
default:
return r, false
}
return r, true
}
func escapeMulti(r rune) (rune, bool) {
switch r {
case backslash:
case dquote:
case tab:
r = 't'
case formfeed:
r = 'f'
case backspace:
r = 'b'
case carriage:
r = 'r'
default:
return r, false
}
return r, true
}
func escapeString(str string, multi bool, escape func(r rune) (rune, bool)) string {
if escape == nil {
return str
}
var (
i int
b strings.Builder
ok bool
)
for i < len(str) {
char, z := utf8.DecodeRuneInString(str[i:])
if char == utf8.RuneError {
break
}
if multi && char == dquote {
i += z
b.WriteRune(char)
if char, z = utf8.DecodeRuneInString(str[i:]); char == dquote {
i += z
b.WriteRune(char)
char, z = utf8.DecodeRuneInString(str[i:])
}
}
if char, ok = escape(char); ok {
b.WriteRune(backslash)
}
b.WriteRune(char)
i += z
}
return b.String()
}
func (f *Formatter) convertValue(tok Token) (string, error) {
switch tok.Type {
default:
return tok.Literal, nil
case TokDatetime:
return f.timeconv(tok.Literal)
case TokInteger:
return f.intconv(tok.Literal)
case TokFloat:
return f.floatconv(tok.Literal)
}
}
func (f *Formatter) formatArray(a *Array) error {
if len(a.nodes) <= 1 || f.withArray == arraySingle {
return f.formatArrayLine(a)
}
if f.withArray == arrayMulti {
return f.formatArrayMultiline(a)
}
if a.isMultiline() {
return f.formatArrayMultiline(a)
}
return f.formatArrayLine(a)
}
func (f *Formatter) formatArrayMultiline(a *Array) error {
retr := func(n Node) comment {
var c comment
switch n := n.(type) {
case *Literal:
c = n.comment
case *Array:
c = n.comment
case *Table:
c = n.comment
}
return c
}
f.enterArray()
defer func() {
f.leaveArray()
f.beginLine()
f.writer.WriteString("]")
}()
f.writer.WriteString("[")
f.endLine()
for _, n := range a.nodes {
com := retr(n)
f.formatComment(com.pre, true)
f.beginLine()
if err := f.formatValue(n); err != nil {
return err
}
f.writer.WriteString(",")
f.formatComment(com.post, false)
f.endLine()
}
return nil
}
func (f *Formatter) formatArrayLine(a *Array) error {
f.writer.WriteString("[")
for i, n := range a.nodes {
if err := f.formatValue(n); err != nil {
return err
}
if i < len(a.nodes)-1 {
f.writer.WriteString(", ")
}
}
f.writer.WriteString("]")
return nil
}
func (f *Formatter) formatInline(t *Table) error {
defer func(array int) {
f.withArray = array
}(f.withArray)
f.withArray = arraySingle
f.writer.WriteString("{")
for i, o := range t.listOptions() {
if i > 0 {
f.writer.WriteString(", ")
}
f.writeKey(o.key.Literal, 0)
if err := f.formatValue(o.value); err != nil {
return err
}
}
f.writer.WriteString("}")
return nil
}
func (f *Formatter) formatHeader(curr *Table, paths []string) error {
if curr.isRoot() {
return nil
}
if curr.kind != tableItem {
paths = append(paths, curr.key.Literal)
}
f.formatComment(curr.comment.pre, true)
switch str := strings.Join(paths, "."); curr.kind {
case tableRegular, tableImplicit:
f.writeRegularHeader(str)
case tableItem:
f.writeArrayHeader(str)
default:
return fmt.Errorf("%s: can not write header for %s", curr.kind, str)
}
f.formatComment(curr.comment.post, false)
f.endLine()
return nil
}
func (f *Formatter) formatComment(comment string, pre bool) error {
if !f.withComment || comment == "" {
return nil
}
scan := bufio.NewScanner(strings.NewReader(comment))
for scan.Scan() {
f.writeComment(scan.Text(), pre)
}
return scan.Err()
}
func (f *Formatter) enterArray() {
f.enterLevel(true)
}
func (f *Formatter) leaveArray() {
f.leaveLevel(true)
}
func (f *Formatter) enterLevel(force bool) {
if f.withNest || force {
f.currLevel++
}
}
func (f *Formatter) leaveLevel(force bool) {
if f.withNest || force {
f.currLevel--
}
}
func (f *Formatter) canNest(curr *Table) bool {
if curr.isRoot() {
return false
}
if curr.kind == tableImplicit && !f.withEmpty {
return false
}
return curr.kind.canNest()
}
func (f *Formatter) writeKey(str string, length int) {
n, _ := f.writer.WriteString(str)
if length > 0 {
f.writer.WriteString(strings.Repeat(" ", length-n))
}
f.writer.WriteString(" = ")
}
func (f *Formatter) writeComment(str string, pre bool) {
if pre {
f.beginLine()
} else {
f.writer.WriteString(" ")
}
f.writer.WriteString("# ")
f.writer.WriteString(str)
if pre {
f.endLine()
}
}
func (f *Formatter) writeRegularHeader(str string) {
f.beginLine()
f.writer.WriteString("[")
f.writer.WriteString(str)
f.writer.WriteString("]")
}
func (f *Formatter) writeArrayHeader(str string) {
f.beginLine()
f.writer.WriteString("[[")
f.writer.WriteString(str)
f.writer.WriteString("]]")
}
func (f *Formatter) endLine() {
f.writer.WriteString(f.withEOL)
}
func (f *Formatter) beginLine() {
if f.currLevel == 0 {
return
}
f.writer.WriteString(strings.Repeat(f.withTab, f.currLevel))
}
func longestKey(options []*Option) int {
var length int
for _, o := range options {
n := len(o.key.Literal)
if length == 0 || length < n {
length = n
}
}
return length
}
func formatString(str string) string {
return str
}
func formatTime(pattern string, utc bool) func(string) (string, error) {
if pattern == "" {
pattern = time.RFC3339
}
return func(str string) (string, error) {
var (
when time.Time
err error
)
for _, pat := range makeAllPatterns() {
when, err = time.Parse(pat, str)
if err == nil {
break
}
}
if err != nil {
return "", err
}
if utc {
when = when.UTC()
}
return when.Format(pattern), nil
}
}
func formatFloat(specifier byte, underscore int) func(string) (string, error) {
return func(str string) (string, error) {
f, err := strconv.ParseFloat(str, 64)
if err != nil {
return "", err
}
str = strconv.FormatFloat(f, specifier, -1, 64)
return withUnderscore(str, underscore), nil
}
}
func formatInteger(base, underscore int, prefix string) func(string) (string, error) {
return func(str string) (string, error) {
n, err := strconv.ParseInt(str, 0, 64)
if err != nil {
return "", err
}
str = strconv.FormatInt(n, base)
return prefix + withUnderscore(str, underscore), nil
}
}
func withUnderscore(str string, every int) string {
if every == 0 || len(str) < every {
return str
}
x := strings.Index(str, ".")
if x < 0 {
return insertUnderscore(str, every)
}
part := insertUnderscore(str[:x], every) + "."
str = str[x+1:]
x = strings.IndexAny(str, "eE")
if x < 0 {
return part + insertUnderscore(str, every)
}
part += insertUnderscore(str[:x], every)
part += "e"
if str[x+1] == '+' || str[x+1] == '-' {
x++
part += string(str[x])
}
return part + insertUnderscore(str[x+1:], every)
}
func insertUnderscore(str string, every int) string {
if len(str) <= every {
return str
}
var (
i = len(str) % every
buf bytes.Buffer
)
if i > 0 {
buf.WriteString(str[:i])
buf.WriteString("_")
}
for i < len(str) && i+every < len(str) {
buf.WriteString(str[i : i+every])
buf.WriteString("_")
i += every
}
buf.WriteString(str[i:])
return buf.String()
}