forked from gavv/httpexpect
-
Notifications
You must be signed in to change notification settings - Fork 3
/
formatter.go
1117 lines (934 loc) · 24.5 KB
/
formatter.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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package httpexpect
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"math"
"net/http/httputil"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"testing"
"text/template"
"github.com/fatih/color"
"github.com/mattn/go-isatty"
"github.com/mitchellh/go-wordwrap"
"github.com/sanity-io/litter"
"github.com/yudai/gojsondiff"
"github.com/yudai/gojsondiff/formatter"
)
// Formatter is used to format assertion messages into strings.
type Formatter interface {
FormatSuccess(*AssertionContext) string
FormatFailure(*AssertionContext, *AssertionFailure) string
}
// DefaultFormatter is the default Formatter implementation.
//
// DefaultFormatter gathers values from AssertionContext and AssertionFailure,
// converts them to strings, and creates FormatData struct. Then it passes
// FormatData to the template engine (text/template) to format message.
//
// You can control what is included and what is excluded from messages via
// several public fields.
//
// If desired, you can provide custom templates and function map. This may
// be easier than creating your own formatter from scratch.
type DefaultFormatter struct {
// Exclude test name and request name from failure report.
DisableNames bool
// Exclude assertion path from failure report.
DisablePaths bool
// Exclude aliased assertion path from failure report.
DisableAliases bool
// Exclude diff from failure report.
DisableDiffs bool
// Exclude HTTP request from failure report.
DisableRequests bool
// Exclude HTTP response from failure report.
DisableResponses bool
// Thousand separator.
// Default is DigitSeparatorUnderscore.
DigitSeparator DigitSeparator
// Float printing format.
// Default is FloatFormatAuto.
FloatFormat FloatFormat
// Defines whether to print stacktrace on failure and in what format.
// Default is StacktraceModeDisabled.
StacktraceMode StacktraceMode
// Colorization mode.
// Default is ColorModeAuto.
ColorMode ColorMode
// Wrap text to keep lines below given width.
// Use zero for default width, and negative value to disable wrapping.
LineWidth int
// If not empty, used to format success messages.
// If empty, default template is used.
SuccessTemplate string
// If not empty, used to format failure messages.
// If empty, default template is used.
FailureTemplate string
// When SuccessTemplate or FailureTemplate is set, this field
// defines the function map passed to template engine.
// May be nil.
TemplateFuncs template.FuncMap
}
// FormatSuccess implements Formatter.FormatSuccess.
func (f *DefaultFormatter) FormatSuccess(ctx *AssertionContext) string {
if f.SuccessTemplate != "" {
return f.applyTemplate("SuccessTemplate",
f.SuccessTemplate, f.TemplateFuncs, ctx, nil)
} else {
return f.applyTemplate("SuccessTemplate",
defaultSuccessTemplate, defaultTemplateFuncs, ctx, nil)
}
}
// FormatFailure implements Formatter.FormatFailure.
func (f *DefaultFormatter) FormatFailure(
ctx *AssertionContext, failure *AssertionFailure,
) string {
if f.FailureTemplate != "" {
return f.applyTemplate("FailureTemplate",
f.FailureTemplate, f.TemplateFuncs, ctx, failure)
} else {
return f.applyTemplate("FailureTemplate",
defaultFailureTemplate, defaultTemplateFuncs, ctx, failure)
}
}
// DigitSeparator defines the separator used to format integers and floats.
type DigitSeparator int
const (
// Separate using underscore
DigitSeparatorUnderscore DigitSeparator = iota
// Separate using comma
DigitSeparatorComma
// Separate using apostrophe
DigitSeparatorApostrophe
// Do not separate
DigitSeparatorNone
)
// FloatFormat defines the format in which all floats are printed.
type FloatFormat int
const (
// Print floats in scientific notation for large exponents,
// otherwise print in decimal notation.
// Precision is the smallest needed to identify the value uniquely.
// Similar to %g format.
FloatFormatAuto FloatFormat = iota
// Always print floats in decimal notation.
// Precision is the smallest needed to identify the value uniquely.
// Similar to %f format.
FloatFormatDecimal
// Always print floats in scientific notation.
// Precision is the smallest needed to identify the value uniquely.
// Similar to %e format.
FloatFormatScientific
)
// StacktraceMode defines the format of stacktrace.
type StacktraceMode int
const (
// Don't print stacktrace.
StacktraceModeDisabled StacktraceMode = iota
// Standard, verbose format.
StacktraceModeStandard
// Compact format.
StacktraceModeCompact
)
// ColorMode defines how the text color is enabled.
type ColorMode int
const (
// Automatically enable colors if ALL of the following is true:
// - stdout is a tty / console
// - AssertionHandler is known to output to testing.T
// - testing.Verbose() is true
//
// Colors are forcibly enabled if FORCE_COLOR environment variable
// is set to a positive integer.
//
// Colors are forcibly disabled if TERM is "dumb" or NO_COLOR
// environment variable is set to non-empty string.
ColorModeAuto ColorMode = iota
// Unconditionally enable colors.
ColorModeAlways
// Unconditionally disable colors.
ColorModeNever
)
// FormatData defines data passed to template engine when DefaultFormatter
// formats assertion. You can use these fields in your custom templates.
type FormatData struct {
TestName string
RequestName string
AssertPath []string
AssertType string
AssertSeverity string
Errors []string
HaveActual bool
Actual string
HaveExpected bool
IsNegation bool
IsComparison bool
ExpectedKind string
Expected []string
HaveReference bool
Reference string
HaveDelta bool
Delta string
HaveDiff bool
Diff string
HaveRequest bool
Request string
HaveResponse bool
Response string
HaveStacktrace bool
Stacktrace []string
EnableColors bool
LineWidth int
}
const (
kindRange = "range"
kindSchema = "schema"
kindPath = "path"
kindRegexp = "regexp"
kindFormat = "format"
kindFormatList = "formats"
kindKey = "key"
kindElement = "element"
kindSubset = "subset"
kindValue = "value"
kindValueList = "values"
)
func (f *DefaultFormatter) applyTemplate(
templateName string,
templateString string,
templateFuncs template.FuncMap,
ctx *AssertionContext,
failure *AssertionFailure,
) string {
templateData := f.buildFormatData(ctx, failure)
t, err := template.New(templateName).Funcs(templateFuncs).Parse(templateString)
if err != nil {
panic(err)
}
var b bytes.Buffer
err = t.Execute(&b, templateData)
if err != nil {
panic(err)
}
return b.String()
}
func (f *DefaultFormatter) buildFormatData(
ctx *AssertionContext, failure *AssertionFailure,
) *FormatData {
data := FormatData{}
f.fillGeneral(&data, ctx)
if failure != nil {
data.AssertType = failure.Type.String()
data.AssertSeverity = failure.Severity.String()
f.fillErrors(&data, ctx, failure)
if failure.Actual != nil {
f.fillActual(&data, ctx, failure)
}
if failure.Expected != nil {
f.fillExpected(&data, ctx, failure)
f.fillIsNegation(&data, ctx, failure)
f.fillIsComparison(&data, ctx, failure)
}
if failure.Reference != nil {
f.fillReference(&data, ctx, failure)
}
if failure.Delta != nil {
f.fillDelta(&data, ctx, failure)
}
f.fillRequest(&data, ctx, failure)
f.fillResponse(&data, ctx, failure)
f.fillStacktrace(&data, ctx, failure)
}
return &data
}
func (f *DefaultFormatter) fillGeneral(
data *FormatData, ctx *AssertionContext,
) {
if !f.DisableNames {
data.TestName = ctx.TestName
data.RequestName = ctx.RequestName
}
if !f.DisablePaths {
if !f.DisableAliases {
data.AssertPath = ctx.AliasedPath
} else {
data.AssertPath = ctx.Path
}
}
switch f.ColorMode {
case ColorModeAuto:
switch colorMode() {
case colorsUnsupported:
data.EnableColors = false
case colorsForced:
data.EnableColors = true
case colorsSupported:
data.EnableColors = ctx.TestingTB && flag.Parsed() && testing.Verbose()
}
case ColorModeAlways:
data.EnableColors = true
case ColorModeNever:
data.EnableColors = false
}
if f.LineWidth != 0 {
data.LineWidth = f.LineWidth
} else {
data.LineWidth = defaultLineWidth
}
}
func (f *DefaultFormatter) fillErrors(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
data.Errors = []string{}
for _, err := range failure.Errors {
if refIsNil(err) {
continue
}
data.Errors = append(data.Errors, err.Error())
}
}
func (f *DefaultFormatter) fillActual(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
switch failure.Type { //nolint
case AssertUsage, AssertOperation:
data.HaveActual = false
case AssertType, AssertNotType:
data.HaveActual = true
data.Actual = f.formatTypedValue(failure.Actual.Value)
default:
data.HaveActual = true
data.Actual = f.formatValue(failure.Actual.Value)
}
}
func (f *DefaultFormatter) fillExpected(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
switch failure.Type {
case AssertUsage, AssertOperation,
AssertType, AssertNotType,
AssertValid, AssertNotValid,
AssertNil, AssertNotNil,
AssertEmpty, AssertNotEmpty,
AssertNotEqual:
data.HaveExpected = false
case AssertEqual:
data.HaveExpected = true
data.ExpectedKind = kindValue
data.Expected = []string{
f.formatValue(failure.Expected.Value),
}
if !f.DisableDiffs && failure.Actual != nil && failure.Expected != nil {
data.Diff, data.HaveDiff = f.formatDiff(
failure.Expected.Value, failure.Actual.Value)
}
case AssertLt, AssertLe, AssertGt, AssertGe:
data.HaveExpected = true
data.ExpectedKind = kindValue
data.Expected = []string{
f.formatValue(failure.Expected.Value),
}
case AssertInRange, AssertNotInRange:
data.HaveExpected = true
data.ExpectedKind = kindRange
data.Expected = f.formatRangeValue(failure.Expected.Value)
case AssertMatchSchema, AssertNotMatchSchema:
data.HaveExpected = true
data.ExpectedKind = kindSchema
data.Expected = []string{
f.formatMatchValue(failure.Expected.Value),
}
case AssertMatchPath, AssertNotMatchPath:
data.HaveExpected = true
data.ExpectedKind = kindPath
data.Expected = []string{
f.formatMatchValue(failure.Expected.Value),
}
case AssertMatchRegexp, AssertNotMatchRegexp:
data.HaveExpected = true
data.ExpectedKind = kindRegexp
data.Expected = []string{
f.formatMatchValue(failure.Expected.Value),
}
case AssertMatchFormat, AssertNotMatchFormat:
data.HaveExpected = true
if extractList(failure.Expected.Value) != nil {
data.ExpectedKind = kindFormatList
} else {
data.ExpectedKind = kindFormat
}
data.Expected = f.formatListValue(failure.Expected.Value)
case AssertContainsKey, AssertNotContainsKey:
data.HaveExpected = true
data.ExpectedKind = kindKey
data.Expected = []string{
f.formatValue(failure.Expected.Value),
}
case AssertContainsElement, AssertNotContainsElement:
data.HaveExpected = true
data.ExpectedKind = kindElement
data.Expected = []string{
f.formatValue(failure.Expected.Value),
}
case AssertContainsSubset, AssertNotContainsSubset:
data.HaveExpected = true
data.ExpectedKind = kindSubset
data.Expected = []string{
f.formatValue(failure.Expected.Value),
}
case AssertBelongs, AssertNotBelongs:
data.HaveExpected = true
data.ExpectedKind = kindValueList
data.Expected = f.formatListValue(failure.Expected.Value)
}
}
func (f *DefaultFormatter) fillIsNegation(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
switch failure.Type {
case AssertUsage, AssertOperation,
AssertType,
AssertValid,
AssertNil,
AssertEmpty,
AssertEqual,
AssertLt, AssertLe, AssertGt, AssertGe,
AssertInRange,
AssertMatchSchema,
AssertMatchPath,
AssertMatchRegexp,
AssertMatchFormat,
AssertContainsKey,
AssertContainsElement,
AssertContainsSubset,
AssertBelongs:
break
case AssertNotType,
AssertNotValid,
AssertNotNil,
AssertNotEmpty,
AssertNotEqual,
AssertNotInRange,
AssertNotMatchSchema,
AssertNotMatchPath,
AssertNotMatchRegexp,
AssertNotMatchFormat,
AssertNotContainsKey,
AssertNotContainsElement,
AssertNotContainsSubset,
AssertNotBelongs:
data.IsNegation = true
}
}
func (f *DefaultFormatter) fillIsComparison(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
switch failure.Type { //nolint
case AssertLt, AssertLe, AssertGt, AssertGe:
data.IsComparison = true
}
}
func (f *DefaultFormatter) fillReference(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
data.HaveReference = true
data.Reference = f.formatValue(failure.Reference.Value)
}
func (f *DefaultFormatter) fillDelta(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
data.HaveDelta = true
data.Delta = f.formatValue(failure.Delta.Value)
}
func (f *DefaultFormatter) fillRequest(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
if !f.DisableRequests && ctx.Request != nil && ctx.Request.httpReq != nil {
dump, err := httputil.DumpRequest(ctx.Request.httpReq, false)
if err != nil {
return
}
data.HaveRequest = true
data.Request = string(dump)
}
}
func (f *DefaultFormatter) fillResponse(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
if !f.DisableResponses && ctx.Response != nil && ctx.Response.httpResp != nil {
dump, err := httputil.DumpResponse(ctx.Response.httpResp, false)
if err != nil {
return
}
text := strings.Replace(string(dump), "\r\n", "\n", -1)
lines := strings.SplitN(text, "\n", 2)
data.HaveResponse = true
data.Response = fmt.Sprintf("%s %s\n%s", lines[0], ctx.Response.rtt, lines[1])
}
}
func (f *DefaultFormatter) fillStacktrace(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
data.Stacktrace = []string{}
switch f.StacktraceMode {
case StacktraceModeDisabled:
break
case StacktraceModeStandard:
for _, entry := range failure.Stacktrace {
data.HaveStacktrace = true
data.Stacktrace = append(data.Stacktrace,
fmt.Sprintf("%s()\n\t%s:%d +0x%x",
entry.Func.Name(), entry.File, entry.Line, entry.FuncOffset))
}
case StacktraceModeCompact:
for _, entry := range failure.Stacktrace {
if entry.IsEntrypoint {
break
}
data.HaveStacktrace = true
data.Stacktrace = append(data.Stacktrace,
fmt.Sprintf("%s() at %s:%d (%s)",
entry.FuncName, filepath.Base(entry.File), entry.Line, entry.FuncPackage))
}
}
}
func (f *DefaultFormatter) formatValue(value interface{}) string {
if flt := extractFloat32(value); flt != nil {
return f.reformatNumber(f.formatFloatValue(*flt, 32))
}
if flt := extractFloat64(value); flt != nil {
return f.reformatNumber(f.formatFloatValue(*flt, 64))
}
if refIsNum(value) {
return f.reformatNumber(fmt.Sprintf("%v", value))
}
if !refIsNil(value) && !refIsHTTP(value) {
if s, _ := value.(fmt.Stringer); s != nil {
if ss := s.String(); strings.TrimSpace(ss) != "" {
return ss
}
}
if b, err := json.MarshalIndent(value, "", defaultIndent); err == nil {
return string(b)
}
}
sq := litter.Options{
Separator: defaultIndent,
}
return sq.Sdump(value)
}
func (f *DefaultFormatter) formatFloatValue(value float64, bits int) string {
switch f.FloatFormat {
case FloatFormatAuto:
if _, frac := math.Modf(value); frac != 0 {
return strconv.FormatFloat(value, 'g', -1, bits)
} else {
return strconv.FormatFloat(value, 'f', -1, bits)
}
case FloatFormatDecimal:
return strconv.FormatFloat(value, 'f', -1, bits)
case FloatFormatScientific:
return strconv.FormatFloat(value, 'e', -1, bits)
default:
return fmt.Sprintf("%v", value)
}
}
func (f *DefaultFormatter) formatTypedValue(value interface{}) string {
if refIsNum(value) {
return fmt.Sprintf("%T(%v)", value, f.formatValue(value))
}
return fmt.Sprintf("%T(%#v)", value, value)
}
func (f *DefaultFormatter) formatMatchValue(value interface{}) string {
if str := extractString(value); str != nil {
return *str
}
return f.formatValue(value)
}
func (f *DefaultFormatter) formatRangeValue(value interface{}) []string {
if rng := exctractRange(value); rng != nil {
if refIsNum(rng.Min) && refIsNum(rng.Max) {
return []string{
fmt.Sprintf("[%v; %v]", f.formatValue(rng.Min), f.formatValue(rng.Max)),
}
} else {
return []string{
fmt.Sprintf("%v", rng.Min),
fmt.Sprintf("%v", rng.Max),
}
}
} else {
return []string{
f.formatValue(value),
}
}
}
func (f *DefaultFormatter) formatListValue(value interface{}) []string {
if lst := extractList(value); lst != nil {
s := make([]string, 0, len(*lst))
for _, e := range *lst {
s = append(s, f.formatValue(e))
}
return s
} else {
return []string{
f.formatValue(value),
}
}
}
func (f *DefaultFormatter) formatDiff(expected, actual interface{}) (string, bool) {
differ := gojsondiff.New()
var diff gojsondiff.Diff
if ve, ok := expected.(map[string]interface{}); ok {
if va, ok := actual.(map[string]interface{}); ok {
diff = differ.CompareObjects(ve, va)
} else {
return "", false
}
} else if ve, ok := expected.([]interface{}); ok {
if va, ok := actual.([]interface{}); ok {
diff = differ.CompareArrays(ve, va)
} else {
return "", false
}
} else {
return "", false
}
if !diff.Modified() {
return "", false
}
config := formatter.AsciiFormatterConfig{
ShowArrayIndex: true,
}
fa := formatter.NewAsciiFormatter(expected, config)
str, err := fa.Format(diff)
if err != nil {
return "", false
}
diffText := "--- expected\n+++ actual\n" + str
return diffText, true
}
func (f *DefaultFormatter) reformatNumber(numStr string) string {
signPart, intPart, fracPart, expPart := f.decomposeNumber(numStr)
if intPart == "" {
return numStr
}
var sb strings.Builder
sb.WriteString(signPart)
sb.WriteString(f.applySeparator(intPart, -1))
if fracPart != "" {
sb.WriteString(".")
sb.WriteString(f.applySeparator(fracPart, +1))
}
if expPart != "" {
sb.WriteString("e")
sb.WriteString(expPart)
}
return sb.String()
}
var (
decomposeRegexp = regexp.MustCompile(`^([+-])?(\d+)([.](\d+))?([eE]([+-]?\d+))?$`)
)
func (f *DefaultFormatter) decomposeNumber(numStr string) (
signPart, intPart, fracPart, expPart string,
) {
parts := decomposeRegexp.FindStringSubmatch(numStr)
if len(parts) > 1 {
signPart = parts[1]
}
if len(parts) > 2 {
intPart = parts[2]
}
if len(parts) > 4 {
fracPart = parts[4]
}
if len(parts) > 6 {
expPart = parts[6]
}
return
}
func (f *DefaultFormatter) applySeparator(numStr string, dir int) string {
var separator string
switch f.DigitSeparator {
case DigitSeparatorUnderscore:
separator = "_"
break
case DigitSeparatorApostrophe:
separator = "'"
break
case DigitSeparatorComma:
separator = ","
break
case DigitSeparatorNone:
default:
return numStr
}
var sb strings.Builder
cnt := 0
if dir < 0 {
cnt = len(numStr)
}
for i := 0; i != len(numStr); i++ {
sb.WriteByte(numStr[i])
cnt += dir
if cnt%3 == 0 && i != len(numStr)-1 {
sb.WriteString(separator)
}
}
return sb.String()
}
func extractString(value interface{}) *string {
switch s := value.(type) {
case string:
return &s
default:
return nil
}
}
func extractFloat32(value interface{}) *float64 {
switch f := value.(type) {
case float32:
ff := float64(f)
return &ff
default:
return nil
}
}
func extractFloat64(value interface{}) *float64 {
switch f := value.(type) {
case float64:
return &f
default:
return nil
}
}
func exctractRange(value interface{}) *AssertionRange {
switch rng := value.(type) {
case AssertionRange:
return &rng
case *AssertionRange: // invalid, but we handle it
return rng
default:
return nil
}
}
func extractList(value interface{}) *AssertionList {
switch lst := value.(type) {
case AssertionList:
return &lst
case *AssertionList: // invalid, but we handle it
return lst
default:
return nil
}
}
var (
colorsSupportedOnce sync.Once
colorsSupportedMode int
)
const (
colorsUnsupported = iota
colorsSupported
colorsForced
)
func colorMode() int {
colorsSupportedOnce.Do(func() {
if s := os.Getenv("FORCE_COLOR"); len(s) != 0 {
if n, err := strconv.Atoi(s); err == nil && n > 0 {
colorsSupportedMode = colorsForced
return
}
}
if (isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())) &&
len(os.Getenv("NO_COLOR")) == 0 &&
!strings.HasPrefix(os.Getenv("TERM"), "dumb") {
colorsSupportedMode = colorsSupported
return
}
colorsSupportedMode = colorsUnsupported
return
})
return colorsSupportedMode
}
const (
defaultIndent = " "
defaultLineWidth = 60
)
var defaultColors = map[string]color.Attribute{
// regular
"Black": color.FgBlack,
"Red": color.FgRed,
"Green": color.FgGreen,
"Yellow": color.FgYellow,
"Magenta": color.FgMagenta,
"Cyan": color.FgCyan,
"White": color.FgWhite,
// bright
"HiBlack": color.FgHiBlack,
"HiRed": color.FgHiRed,
"HiGreen": color.FgHiGreen,
"HiYellow": color.FgHiYellow,
"HiMagenta": color.FgHiMagenta,
"HiCyan": color.FgHiCyan,
"HiWhite": color.FgHiWhite,
}
var defaultTemplateFuncs = template.FuncMap{
"trim": func(input string) string {
return strings.TrimSpace(input)
},
"indent": func(input string) string {
var sb strings.Builder
for _, s := range strings.Split(input, "\n") {
if sb.Len() != 0 {
sb.WriteString("\n")
}
sb.WriteString(defaultIndent)
sb.WriteString(s)
}
return sb.String()
},
"wrap": func(width int, input string) string {
input = strings.TrimSpace(input)
width -= len(defaultIndent)
if width <= 0 {
return input
}
return wordwrap.WrapString(input, uint(width))
},
"join": func(width int, tokenList []string) string {
width -= len(defaultIndent)
if width <= 0 {
return strings.Join(tokenList, ".")
}
var sb strings.Builder
lineLen := 0
lineNum := 0
write := func(s string) {
sb.WriteString(s)
lineLen += len(s)
}
for n, token := range tokenList {
if lineLen+len(token)+1 > width {
write("\n")
lineLen = 0
if lineNum < 2 {
lineNum++
}
}
if lineLen == 0 {
for l := 0; l < lineNum; l++ {
write(defaultIndent)
}
}
write(token)
if n != len(tokenList)-1 {
write(".")
}
}
return sb.String()
},