Debian Codegraph @

fmt.go

raw
1 package tblfmt
2
3 import (
4 "bytes"
5 "database/sql"
6 "encoding/json"
7 "fmt"
8 "reflect"
9 "strconv"
10 "strings"
11 "time"
12 "unicode"
13 "unicode/utf8"
14
15 runewidth "github.com/mattn/go-runewidth"
16 "golang.org/x/text/language"
17 "golang.org/x/text/message"
18 "golang.org/x/text/number"
19 )
20
21 // Formatter is the common interface for formatting values.
22 type Formatter interface {
23 // Header returns a slice of formatted values for the provided headers.
24 Header([]string) ([]*Value, error)
25 // Format returns a slice of formatted value the provided row values.
26 Format([]any) ([]*Value, error)
27 }
28
29 // EscapeFormatter is an escaping formatter, that handles formatting the
30 // standard Go types.
31 //
32 // When the encoder is not nil, then it will be passed any
33 // map[string]interface{} and []interface{} values encountered, otherwise the
34 // stdlib's encoding/json.Encoder will be used.
35 type EscapeFormatter struct {
36 // mask is used to format header values when the formatted value (after
37 // trimming spaces) is the empty string.
38 //
39 // Note: will have %d replaced with the column number (starting at 1).
40 mask string
41 // timeFormat is the format to use for time values.
42 timeFormat string
43 // timeLocation is the location to use for time values.
44 timeLocation *time.Location
45 // encoder will be used to encode map[string]interface{} and []interface{}
46 // types.
47 //
48 // If nil, the standard encoding/json.Encoder will be used instead.
49 encoder func(any) ([]byte, error)
50 // prefix is indent prefix used by the JSON encoder when encoder is nil.
51 prefix string
52 // indent is the indent used by the JSON encoder when encoder is nil.
53 indent string
54 // isJSON sets escaping JSON characters.
55 isJSON bool
56 // escapeHTML sets the JSON encoder used when encoder is nil to escape HTML
57 // characters.
58 escapeHTML bool
59 // isRaw sets raw escaping.
60 isRaw bool
61 // sep is the separator to use for raw (csv) encoding.
62 sep rune
63 // quote is the quote to use for raw (csv) encoding.
64 quote rune
65 // invalid is the value used for invalid utf8 runes when escaping.
66 invalid []byte
67 // invalidWidth is the rune width of the invalid value
68 invalidWidth int
69 // headerAlign is the default header values alignment
70 headerAlign Align
71 // align is the forced alignment value.
72 align Align
73 // numericLocalePrinter is the numeric locale printer.
74 numericLocalePrinter *message.Printer
75 }
76
77 // NewEscapeFormatter creates a escape formatter to handle basic Go values,
78 // such as []byte, string, time.Time, and sql.Null*. Formatting for
79 // map[string]interface{} and []interface{} will be passed to a marshaler
80 // provided by [WithEncoder], otherwise the standard [encoding/json.Encoder]
81 // will be used to marshal those values.
82 func NewEscapeFormatter(opts ...EscapeFormatterOption) *EscapeFormatter {
83 f := &EscapeFormatter{
84 mask: "%d",
85 timeFormat: time.RFC3339Nano,
86 indent: " ",
87 align: -1,
88 }
89 for _, o := range opts {
90 o(f)
91 }
92 return f
93 }
94
95 // Header satisfies the Formatter interface.
96 func (f *EscapeFormatter) Header(headers []string) ([]*Value, error) {
97 n := len(headers)
98 res := make([]*Value, n)
99 for i := range n {
100 s := strings.TrimSpace(headers[i])
101 switch {
102 case s == "" && strings.ContainsRune(f.mask, '%'):
103 s = fmt.Sprintf(f.mask, i+1)
104 case s == "":
105 s = f.mask
106 }
107 res[i] = FormatBytes([]byte(s), f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote)
108 res[i].Align = f.headerAlign
109 }
110 return res, nil
111 }
112
113 // Format satisfies the Formatter interface.
114 func (f *EscapeFormatter) Format(vals []any) ([]*Value, error) {
115 n := len(vals)
116 res := make([]*Value, n)
117 // TODO: change time to v.AppendFormat() + pool
118 // TODO: use strconv.Format* for numeric times
119 // TODO: use pool
120 // TODO: allow configurable runes that can be escaped
121 // TODO: handler driver.Valuer
122 left, right := AlignLeft, AlignRight
123 if f.align != -1 {
124 left, right = f.align, f.align
125 }
126 for i := range n {
127 val := deref(vals[i])
128 switch v := val.(type) {
129 case nil:
130 case bool:
131 res[i] = newValue(strconv.FormatBool(v), left, true)
132 case int, int8, int16, int32, int64,
133 uint, uint8, uint16, uint32, uint64:
134 var s string
135 if f.numericLocalePrinter != nil {
136 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v))
137 } else {
138 s = fmt.Sprintf("%d", v)
139 }
140 res[i] = newValue(s, right, true)
141 case float32:
142 var s string
143 if f.numericLocalePrinter != nil {
144 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v, number.MinFractionDigits(1)))
145 } else {
146 s = strconv.FormatFloat(float64(v), 'g', -1, 32)
147 }
148 res[i] = newValue(s, right, true)
149 case float64:
150 var s string
151 if f.numericLocalePrinter != nil {
152 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v, number.MinFractionDigits(1)))
153 } else {
154 s = strconv.FormatFloat(v, 'g', -1, 64)
155 }
156 res[i] = newValue(s, right, true)
157 case uintptr:
158 res[i] = newValue(fmt.Sprintf("(0x%x)", v), right, true)
159 case complex64:
160 res[i] = newValue(fmt.Sprintf("%g", v), right, false)
161 case complex128:
162 res[i] = newValue(fmt.Sprintf("%g", v), right, false)
163 case []byte:
164 res[i] = FormatBytes(v, f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote)
165 case string:
166 res[i] = FormatBytes([]byte(v), f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote)
167 case time.Time:
168 t := v
169 if f.timeLocation != nil {
170 t = t.In(f.timeLocation)
171 }
172 res[i] = newValue(t.Format(f.timeFormat), left, false)
173 case sql.NullBool:
174 if v.Valid {
175 res[i] = newValue(strconv.FormatBool(v.Bool), left, true)
176 }
177 case sql.NullByte:
178 if v.Valid {
179 var s string
180 if f.numericLocalePrinter != nil {
181 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v.Byte))
182 } else {
183 s = strconv.FormatUint(uint64(v.Byte), 10)
184 }
185 res[i] = newValue(s, right, true)
186 }
187 case sql.NullFloat64:
188 if v.Valid {
189 var s string
190 if f.numericLocalePrinter != nil {
191 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v.Float64))
192 } else {
193 s = strconv.FormatFloat(v.Float64, 'g', -1, 64)
194 }
195 res[i] = newValue(s, right, true)
196 }
197 case sql.NullInt16:
198 if v.Valid {
199 var s string
200 if f.numericLocalePrinter != nil {
201 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v.Int16))
202 } else {
203 s = strconv.FormatInt(int64(v.Int16), 10)
204 }
205 res[i] = newValue(s, right, true)
206 }
207 case sql.NullInt32:
208 if v.Valid {
209 var s string
210 if f.numericLocalePrinter != nil {
211 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v.Int32))
212 } else {
213 s = strconv.FormatInt(int64(v.Int32), 10)
214 }
215 res[i] = newValue(s, right, true)
216 }
217 case sql.NullInt64:
218 if v.Valid {
219 var s string
220 if f.numericLocalePrinter != nil {
221 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v.Int64))
222 } else {
223 s = strconv.FormatInt(v.Int64, 10)
224 }
225 res[i] = newValue(s, right, true)
226 }
227 case sql.NullString:
228 if v.Valid {
229 res[i] = FormatBytes([]byte(v.String), f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote)
230 }
231 case sql.NullTime:
232 if v.Valid {
233 t := v.Time
234 if f.timeLocation != nil {
235 t = t.In(f.timeLocation)
236 }
237 res[i] = newValue(t.Format(f.timeFormat), left, false)
238 }
239 case sql.RawBytes:
240 res[i] = FormatBytes(v, f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote)
241 case fmt.Stringer:
242 res[i] = FormatBytes([]byte(v.String()), f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote)
243 default:
244 // TODO: pool
245 if f.encoder != nil {
246 buf, err := f.encoder(v)
247 if err != nil {
248 return nil, err
249 }
250 res[i] = &Value{
251 Buf: buf,
252 Raw: true,
253 }
254 } else {
255 // json encode
256 buf := new(bytes.Buffer)
257 enc := json.NewEncoder(buf)
258 enc.SetIndent(f.prefix, f.indent)
259 enc.SetEscapeHTML(f.escapeHTML)
260 if err := enc.Encode(v); err != nil {
261 return nil, err
262 }
263 if f.isJSON {
264 res[i] = &Value{
265 Buf: bytes.TrimSpace(buf.Bytes()),
266 Raw: true,
267 }
268 } else {
269 res[i] = FormatBytes(bytes.TrimSpace(buf.Bytes()), f.invalid, f.invalidWidth, false, f.isRaw, f.sep, f.quote)
270 res[i].Raw = true
271 }
272 }
273 }
274 }
275 return res, nil
276 }
277
278 // valueFromBuffer returns a value from a buffer known not to contain
279 // characters to escape.
280 func newValue(str string, align Align, raw bool) *Value {
281 v := &Value{Buf: []byte(str), Align: align, Raw: raw}
282 v.Width = len(v.Buf)
283 return v
284 }
285
286 // lowerhex is the set of lower hex characters.
287 const lowerhex = "0123456789abcdef"
288
289 // FormatBytes parses src, saving escaped (encoded) and unescaped runes to a
290 // Value, along with tab and newline positions in the generated buf.
291 func FormatBytes(src []byte, invalid []byte, invalidWidth int, isJSON, isRaw bool, sep, quote rune) *Value {
292 res := &Value{
293 Tabs: make([][][2]int, 1),
294 }
295 var tmp [4]byte
296 var r rune
297 var l, w int
298 for ; len(src) > 0; src = src[w:] {
299 r, w = rune(src[0]), 1
300 // lazy decode
301 if r >= utf8.RuneSelf {
302 r, w = utf8.DecodeRune(src)
303 }
304 // invalid rune decoded
305 if w == 1 && r == utf8.RuneError {
306 // replace with invalid (if set), otherwise hex encode
307 switch {
308 case invalid != nil:
309 res.Buf = append(res.Buf, invalid...)
310 res.Width += invalidWidth
311 res.Quoted = true
312 case isJSON:
313 res.Buf = append(res.Buf, '\\', 'u')
314 for s := 12; s >= 0; s -= 4 {
315 res.Buf = append(res.Buf, lowerhex[r>>uint(s)&0xf])
316 }
317 default:
318 res.Buf = append(res.Buf, '\\', 'x', lowerhex[src[0]>>4], lowerhex[src[0]&0xf])
319 res.Width += 4
320 res.Quoted = true
321 }
322 continue
323 }
324 // handle json encoding
325 if isJSON {
326 switch r {
327 case '\a':
328 res.Buf = append(res.Buf, '\\', 'u', '0', '0', '0', '7')
329 res.Width += 6
330 continue
331 case '\b':
332 res.Buf = append(res.Buf, '\\', 'b')
333 res.Width += 2
334 continue
335 case '\f':
336 res.Buf = append(res.Buf, '\\', 'f')
337 res.Width += 2
338 continue
339 case '\n':
340 res.Buf = append(res.Buf, '\\', 'n')
341 res.Width += 2
342 continue
343 case '\r':
344 res.Buf = append(res.Buf, '\\', 'r')
345 res.Width += 2
346 continue
347 case '\t':
348 res.Buf = append(res.Buf, '\\', 't')
349 res.Width += 2
350 continue
351 case '"':
352 res.Buf = append(res.Buf, '\\', '"')
353 res.Width += 2
354 continue
355 case '\\':
356 res.Buf = append(res.Buf, '\\', '\\')
357 res.Width += 2
358 continue
359 }
360 }
361 // handle raw encoding
362 if isRaw {
363 n := utf8.EncodeRune(tmp[:], r)
364 res.Buf = append(res.Buf, tmp[:n]...)
365 res.Width += runewidth.RuneWidth(r)
366 switch {
367 case r == sep:
368 res.Quoted = true
369 case r == quote && quote != 0:
370 res.Buf = append(res.Buf, tmp[:n]...)
371 res.Width += runewidth.RuneWidth(r)
372 res.Quoted = true
373 default:
374 res.Quoted = res.Quoted || unicode.IsSpace(r)
375 }
376 continue
377 }
378 // printable character
379 if strconv.IsGraphic(r) {
380 n := utf8.EncodeRune(tmp[:], r)
381 res.Buf = append(res.Buf, tmp[:n]...)
382 res.Width += runewidth.RuneWidth(r)
383 continue
384 }
385 switch r {
386 // escape \a \b \f \r \v (Go special characters)
387 case '\a':
388 res.Buf = append(res.Buf, '\\', 'a')
389 res.Width += 2
390 case '\b':
391 res.Buf = append(res.Buf, '\\', 'b')
392 res.Width += 2
393 case '\f':
394 res.Buf = append(res.Buf, '\\', 'f')
395 res.Width += 2
396 case '\r':
397 res.Buf = append(res.Buf, '\\', 'r')
398 res.Width += 2
399 case '\v':
400 res.Buf = append(res.Buf, '\\', 'v')
401 res.Width += 2
402 case '\t':
403 // save position
404 res.Tabs[l] = append(res.Tabs[l], [2]int{len(res.Buf), res.Width})
405 res.Buf = append(res.Buf, '\t')
406 res.Width = 0
407 case '\n':
408 // save position
409 res.Newlines = append(res.Newlines, [2]int{len(res.Buf), res.Width})
410 res.Buf = append(res.Buf, '\n')
411 res.Width = 0
412 // increase line count
413 res.Tabs = append(res.Tabs, nil)
414 l++
415 default:
416 switch {
417 // escape as \x00
418 case r < ' ' && !isJSON:
419 res.Buf = append(res.Buf, '\\', 'x', lowerhex[byte(r)>>4], lowerhex[byte(r)&0xf])
420 res.Width += 4
421 // escape as \u0000
422 case r > utf8.MaxRune:
423 r = 0xfffd
424 fallthrough
425 case r < 0x10000:
426 res.Buf = append(res.Buf, '\\', 'u')
427 for s := 12; s >= 0; s -= 4 {
428 res.Buf = append(res.Buf, lowerhex[r>>uint(s)&0xf])
429 }
430 res.Width += 6
431 // escape as \U00000000
432 default:
433 res.Buf = append(res.Buf, '\\', 'U')
434 for s := 28; s >= 0; s -= 4 {
435 res.Buf = append(res.Buf, lowerhex[r>>uint(s)&0xf])
436 }
437 res.Width += 10
438 }
439 }
440 }
441 return res
442 }
443
444 // Value contains information pertaining to a formatted value.
445 type Value struct {
446 // Buf is the formatted value.
447 Buf []byte
448 // Newlines are the positions of newline characters in Buf.
449 Newlines [][2]int
450 // Tabs are the positions of tab characters in Buf, split per line.
451 Tabs [][][2]int
452 // Width is the remaining width.
453 Width int
454 // Align indicates value alignment.
455 Align Align
456 // Raw tracks whether or not the value should be encoded or not.
457 Raw bool
458 // Quoted tracks whether or not a raw value should be quoted or not (ie,
459 // contains a space or non printable character).
460 Quoted bool
461 }
462
463 func (v *Value) String() string {
464 return string(v.Buf)
465 }
466
467 // LineWidth returns the line width (in runes) of line l.
468 func (v *Value) LineWidth(l, offset, tab int) int {
469 var width int
470 if l < len(v.Newlines) {
471 width += v.Newlines[l][1]
472 }
473 if len(v.Tabs[l]) != 0 {
474 width += tabwidth(v.Tabs[l], offset, tab)
475 }
476 if l == len(v.Newlines) {
477 width += v.Width
478 }
479 return width
480 }
481
482 // MaxWidth calculates the maximum width (in runes) of the longest line
483 // contained in Buf, relative to starting offset and the tab width.
484 func (v *Value) MaxWidth(offset, tab int) int {
485 // simple values do not have tabulations
486 width := v.Width
487 for l := range len(v.Tabs) {
488 width = max(width, v.LineWidth(l, offset, tab))
489 }
490 return width
491 }
492
493 // Align indicates an alignment direction for a value.
494 type Align int
495
496 // Align values.
497 const (
498 AlignLeft Align = iota
499 AlignRight
500 AlignCenter
501 )
502
503 // String satisfies the fmt.Stringer interface.
504 func (a Align) String() string {
505 switch a {
506 case AlignLeft:
507 return "Left"
508 case AlignRight:
509 return "Right"
510 case AlignCenter:
511 return "Center"
512 }
513 return fmt.Sprintf("Align(%d)", a)
514 }
515
516 // tabwidth returns the rune width of buf containing tabs from start position
517 // in buf, a column offset, and given tab width.
518 func tabwidth(tabs [][2]int, offset, tab int) int {
519 // log.Printf("tabs: %v, offset: %d, tab: %d", tabs, offset, tab)
520 width := offset
521 for i := range tabs {
522 width += tabs[i][1]
523 width += (tab - width%tab)
524 }
525 // log.Printf("res: %d", width-offset)
526 return width - offset
527 }
528
529 // EscapeFormatterOption is an escape formatter option.
530 type EscapeFormatterOption func(*EscapeFormatter)
531
532 // WithMask is an escape formatter option to set the mask used for empty
533 // headers.
534 func WithMask(mask string) EscapeFormatterOption {
535 return func(f *EscapeFormatter) {
536 f.mask = mask
537 }
538 }
539
540 // WithTimeFormat is an escape formatter option to set the time format used for
541 // time values.
542 func WithTimeFormat(timeFormat string) EscapeFormatterOption {
543 return func(f *EscapeFormatter) {
544 f.timeFormat = timeFormat
545 }
546 }
547
548 // WithTimeLocation is an escape formatter option to set the time location used
549 // for time values.
550 func WithTimeLocation(timeLocation *time.Location) EscapeFormatterOption {
551 return func(f *EscapeFormatter) {
552 f.timeLocation = timeLocation
553 }
554 }
555
556 // WithEncoder is an escape formatter option to set a standard Go encoder to
557 // use for encoding the value.
558 func WithEncoder(encoder func(any) ([]byte, error)) EscapeFormatterOption {
559 return func(f *EscapeFormatter) {
560 f.encoder = encoder
561 }
562 }
563
564 // WithIsJSON is an escape formatter option to enable special escaping for JSON
565 // characters in non-complex values.
566 func WithIsJSON(isJSON bool) EscapeFormatterOption {
567 return func(f *EscapeFormatter) {
568 f.isJSON = isJSON
569 }
570 }
571
572 // WithJSONConfig is an escape formatter option to set the JSON encoding
573 // prefix, indent value, and whether or not to escape HTML. Passed to the
574 // standard encoding/json.Encoder when a marshaler has not been set on the
575 // escape formatter.
576 func WithJSONConfig(prefix, indent string, escapeHTML bool) EscapeFormatterOption {
577 return func(f *EscapeFormatter) {
578 f.prefix, f.indent, f.escapeHTML = prefix, indent, escapeHTML
579 }
580 }
581
582 // WithIsRaw is an escape formatter option to enable special escaping for raw
583 // characters in values.
584 func WithIsRaw(isRaw bool, sep, quote rune) EscapeFormatterOption {
585 return func(f *EscapeFormatter) {
586 f.isRaw, f.sep, f.quote = isRaw, sep, quote
587 }
588 }
589
590 // WithInvalid is an escape formatter option to set the invalid value used when
591 // an invalid rune is encountered during escaping.
592 func WithInvalid(invalid string) EscapeFormatterOption {
593 return func(f *EscapeFormatter) {
594 f.invalid = []byte(invalid)
595 f.invalidWidth = runewidth.StringWidth(invalid)
596 }
597 }
598
599 // WithHeaderAlign sets the alignment of header values.
600 func WithHeaderAlign(a Align) EscapeFormatterOption {
601 return func(f *EscapeFormatter) {
602 f.headerAlign = a
603 }
604 }
605
606 // WithAlign sets the forced alignment for values.
607 func WithAlign(a Align) EscapeFormatterOption {
608 return func(f *EscapeFormatter) {
609 f.align = a
610 }
611 }
612
613 // WithNumericLocale sets the numeric locale printer.
614 func WithNumericLocale(enable bool, locale string) EscapeFormatterOption {
615 return func(f *EscapeFormatter) {
616 if enable {
617 tag := language.English
618 if t, err := language.Parse(locale); err == nil {
619 tag = t
620 }
621 f.numericLocalePrinter = message.NewPrinter(tag)
622 }
623 }
624 }
625
626 // deref dereferences a pointer to an interface.
627 func deref(v any) any {
628 switch z := v.(type) {
629 case *any:
630 return *z
631 }
632 val := reflect.ValueOf(v)
633 if val.Kind() == reflect.Ptr {
634 val = val.Elem()
635 }
636 return val.Interface()
637 }