-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
logger.go
1614 lines (1383 loc) · 37.3 KB
/
logger.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 logger
// Logging is currently designed to look and feel like clang's error format.
// Errors are streamed asynchronously as they happen, each error contains the
// contents of the line with the error, and the error count is limited by
// default.
import (
"fmt"
"os"
"runtime"
"sort"
"strings"
"sync"
"time"
"unicode/utf8"
)
const defaultTerminalWidth = 80
type Log struct {
AddMsg func(Msg)
HasErrors func() bool
// This is called after the build has finished but before writing to stdout.
// It exists to ensure that deferred warning messages end up in the terminal
// before the data written to stdout.
AlmostDone func()
Done func() []Msg
Level LogLevel
}
type LogLevel int8
const (
LevelNone LogLevel = iota
LevelVerbose
LevelDebug
LevelInfo
LevelWarning
LevelError
LevelSilent
)
type MsgKind uint8
const (
Error MsgKind = iota
Warning
Info
Note
Debug
Verbose
)
func (kind MsgKind) String() string {
switch kind {
case Error:
return "ERROR"
case Warning:
return "WARNING"
case Info:
return "INFO"
case Note:
return "NOTE"
case Debug:
return "DEBUG"
case Verbose:
return "VERBOSE"
default:
panic("Internal error")
}
}
func (kind MsgKind) Icon() string {
// Special-case Windows command prompt, which only supports a few characters
if isProbablyWindowsCommandPrompt() {
switch kind {
case Error:
return "X"
case Warning:
return "▲"
case Info:
return "►"
case Note:
return "→"
case Debug:
return "●"
case Verbose:
return "♦"
default:
panic("Internal error")
}
}
switch kind {
case Error:
return "✘"
case Warning:
return "▲"
case Info:
return "▶"
case Note:
return "→"
case Debug:
return "●"
case Verbose:
return "⬥"
default:
panic("Internal error")
}
}
var windowsCommandPrompt struct {
mutex sync.Mutex
once bool
isProbablyCMD bool
}
func isProbablyWindowsCommandPrompt() bool {
windowsCommandPrompt.mutex.Lock()
defer windowsCommandPrompt.mutex.Unlock()
if !windowsCommandPrompt.once {
windowsCommandPrompt.once = true
// Assume we are running in Windows Command Prompt if we're on Windows. If
// so, we can't use emoji because it won't be supported. Except we can
// still use emoji if the WT_SESSION environment variable is present
// because that means we're running in the new Windows Terminal instead.
if runtime.GOOS == "windows" {
windowsCommandPrompt.isProbablyCMD = true
for _, env := range os.Environ() {
if strings.HasPrefix(env, "WT_SESSION=") {
windowsCommandPrompt.isProbablyCMD = false
break
}
}
}
}
return windowsCommandPrompt.isProbablyCMD
}
type Msg struct {
Notes []MsgData
PluginName string
Data MsgData
Kind MsgKind
}
type MsgData struct {
// Optional user-specified data that is passed through unmodified
UserDetail interface{}
Location *MsgLocation
Text string
DisableMaximumWidth bool
}
type MsgLocation struct {
File string
Namespace string
LineText string
Suggestion string
Line int // 1-based
Column int // 0-based, in bytes
Length int // in bytes
}
type Loc struct {
// This is the 0-based index of this location from the start of the file, in bytes
Start int32
}
type Range struct {
Loc Loc
Len int32
}
func (r Range) End() int32 {
return r.Loc.Start + r.Len
}
type Span struct {
Text string
Range Range
}
// This type is just so we can use Go's native sort function
type SortableMsgs []Msg
func (a SortableMsgs) Len() int { return len(a) }
func (a SortableMsgs) Swap(i int, j int) { a[i], a[j] = a[j], a[i] }
func (a SortableMsgs) Less(i int, j int) bool {
ai := a[i]
aj := a[j]
aiLoc := ai.Data.Location
ajLoc := aj.Data.Location
if aiLoc == nil || ajLoc == nil {
return aiLoc == nil && ajLoc != nil
}
if aiLoc.File != ajLoc.File {
return aiLoc.File < ajLoc.File
}
if aiLoc.Line != ajLoc.Line {
return aiLoc.Line < ajLoc.Line
}
if aiLoc.Column != ajLoc.Column {
return aiLoc.Column < ajLoc.Column
}
if ai.Kind != aj.Kind {
return ai.Kind < aj.Kind
}
return ai.Data.Text < aj.Data.Text
}
// This is used to represent both file system paths (Namespace == "file") and
// abstract module paths (Namespace != "file"). Abstract module paths represent
// "virtual modules" when used for an input file and "package paths" when used
// to represent an external module.
type Path struct {
Text string
Namespace string
// This feature was added to support ancient CSS libraries that append things
// like "?#iefix" and "#icons" to some of their import paths as a hack for IE6.
// The intent is for these suffix parts to be ignored but passed through to
// the output. This is supported by other bundlers, so we also support this.
IgnoredSuffix string
Flags PathFlags
}
type PathFlags uint8
const (
// This corresponds to a value of "false' in the "browser" package.json field
PathDisabled PathFlags = 1 << iota
)
func (p Path) IsDisabled() bool {
return (p.Flags & PathDisabled) != 0
}
func (a Path) ComesBeforeInSortedOrder(b Path) bool {
return a.Namespace > b.Namespace ||
(a.Namespace == b.Namespace && (a.Text < b.Text ||
(a.Text == b.Text && (a.Flags < b.Flags ||
(a.Flags == b.Flags && a.IgnoredSuffix < b.IgnoredSuffix)))))
}
var noColorResult bool
var noColorOnce sync.Once
func hasNoColorEnvironmentVariable() bool {
noColorOnce.Do(func() {
for _, key := range os.Environ() {
// Read "NO_COLOR" from the environment. This is a convention that some
// software follows. See https://no-color.org/ for more information.
if strings.HasPrefix(key, "NO_COLOR=") {
noColorResult = true
}
}
})
return noColorResult
}
// This has a custom implementation instead of using "filepath.Dir/Base/Ext"
// because it should work the same on Unix and Windows. These names end up in
// the generated output and the generated output should not depend on the OS.
func PlatformIndependentPathDirBaseExt(path string) (dir string, base string, ext string) {
for {
i := strings.LastIndexAny(path, "/\\")
// Stop if there are no more slashes
if i < 0 {
base = path
break
}
// Stop if we found a non-trailing slash
if i+1 != len(path) {
dir, base = path[:i], path[i+1:]
break
}
// Ignore trailing slashes
path = path[:i]
}
// Strip off the extension
if dot := strings.LastIndexByte(base, '.'); dot >= 0 {
base, ext = base[:dot], base[dot:]
}
return
}
type Source struct {
// This is used for error messages and the metadata JSON file.
//
// This is a mostly platform-independent path. It's relative to the current
// working directory and always uses standard path separators. Use this for
// referencing a file in all output data. These paths still use the original
// case of the path so they may still work differently on file systems that
// are case-insensitive vs. case-sensitive.
PrettyPath string
// An identifier that is mixed in to automatically-generated symbol names to
// improve readability. For example, if the identifier is "util" then the
// symbol for an "export default" statement will be called "util_default".
IdentifierName string
Contents string
// This is used as a unique key to identify this source file. It should never
// be shown to the user (e.g. never print this to the terminal).
//
// If it's marked as an absolute path, it's a platform-dependent path that
// includes environment-specific things such as Windows backslash path
// separators and potentially the user's home directory. Only use this for
// passing to syscalls for reading and writing to the file system. Do not
// include this in any output data.
//
// If it's marked as not an absolute path, it's an opaque string that is used
// to refer to an automatically-generated module.
KeyPath Path
Index uint32
}
func (s *Source) TextForRange(r Range) string {
return s.Contents[r.Loc.Start : r.Loc.Start+r.Len]
}
func (s *Source) LocBeforeWhitespace(loc Loc) Loc {
for loc.Start > 0 {
c, width := utf8.DecodeLastRuneInString(s.Contents[:loc.Start])
if c != ' ' && c != '\t' && c != '\r' && c != '\n' {
break
}
loc.Start -= int32(width)
}
return loc
}
func (s *Source) RangeOfOperatorBefore(loc Loc, op string) Range {
text := s.Contents[:loc.Start]
index := strings.LastIndex(text, op)
if index >= 0 {
return Range{Loc: Loc{Start: int32(index)}, Len: int32(len(op))}
}
return Range{Loc: loc}
}
func (s *Source) RangeOfOperatorAfter(loc Loc, op string) Range {
text := s.Contents[loc.Start:]
index := strings.Index(text, op)
if index >= 0 {
return Range{Loc: Loc{Start: loc.Start + int32(index)}, Len: int32(len(op))}
}
return Range{Loc: loc}
}
func (s *Source) RangeOfString(loc Loc) Range {
text := s.Contents[loc.Start:]
if len(text) == 0 {
return Range{Loc: loc, Len: 0}
}
quote := text[0]
if quote == '"' || quote == '\'' {
// Search for the matching quote character
for i := 1; i < len(text); i++ {
c := text[i]
if c == quote {
return Range{Loc: loc, Len: int32(i + 1)}
} else if c == '\\' {
i += 1
}
}
}
return Range{Loc: loc, Len: 0}
}
func (s *Source) RangeOfNumber(loc Loc) (r Range) {
text := s.Contents[loc.Start:]
r = Range{Loc: loc, Len: 0}
if len(text) > 0 {
if c := text[0]; c >= '0' && c <= '9' {
r.Len = 1
for int(r.Len) < len(text) {
c := text[r.Len]
if (c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '.' && c != '_' {
break
}
r.Len++
}
}
}
return
}
func (s *Source) RangeOfLegacyOctalEscape(loc Loc) (r Range) {
text := s.Contents[loc.Start:]
r = Range{Loc: loc, Len: 0}
if len(text) >= 2 && text[0] == '\\' {
r.Len = 2
for r.Len < 4 && int(r.Len) < len(text) {
c := text[r.Len]
if c < '0' || c > '9' {
break
}
r.Len++
}
}
return
}
func plural(prefix string, count int, shown int, someAreMissing bool) string {
var text string
if count == 1 {
text = fmt.Sprintf("%d %s", count, prefix)
} else {
text = fmt.Sprintf("%d %ss", count, prefix)
}
if shown < count {
text = fmt.Sprintf("%d of %s", shown, text)
} else if someAreMissing && count > 1 {
text = "all " + text
}
return text
}
func errorAndWarningSummary(errors int, warnings int, shownErrors int, shownWarnings int) string {
someAreMissing := shownWarnings < warnings || shownErrors < errors
switch {
case errors == 0:
return plural("warning", warnings, shownWarnings, someAreMissing)
case warnings == 0:
return plural("error", errors, shownErrors, someAreMissing)
default:
return fmt.Sprintf("%s and %s",
plural("warning", warnings, shownWarnings, someAreMissing),
plural("error", errors, shownErrors, someAreMissing))
}
}
type APIKind uint8
const (
GoAPI APIKind = iota
CLIAPI
JSAPI
)
// This can be used to customize error messages for the current API kind
var API APIKind
type TerminalInfo struct {
IsTTY bool
UseColorEscapes bool
Width int
Height int
}
func NewStderrLog(options OutputOptions) Log {
var mutex sync.Mutex
var msgs SortableMsgs
terminalInfo := GetTerminalInfo(os.Stderr)
errors := 0
warnings := 0
shownErrors := 0
shownWarnings := 0
hasErrors := false
remainingMessagesBeforeLimit := options.MessageLimit
if remainingMessagesBeforeLimit == 0 {
remainingMessagesBeforeLimit = 0x7FFFFFFF
}
var deferredWarnings []Msg
didFinalizeLog := false
finalizeLog := func() {
if didFinalizeLog {
return
}
didFinalizeLog = true
// Print the deferred warning now if there was no error after all
for remainingMessagesBeforeLimit > 0 && len(deferredWarnings) > 0 {
shownWarnings++
writeStringWithColor(os.Stderr, deferredWarnings[0].String(options, terminalInfo))
deferredWarnings = deferredWarnings[1:]
remainingMessagesBeforeLimit--
}
// Print out a summary
if options.MessageLimit > 0 && errors+warnings > options.MessageLimit {
writeStringWithColor(os.Stderr, fmt.Sprintf("%s shown (disable the message limit with --log-limit=0)\n",
errorAndWarningSummary(errors, warnings, shownErrors, shownWarnings)))
} else if options.LogLevel <= LevelInfo && (warnings != 0 || errors != 0) {
writeStringWithColor(os.Stderr, fmt.Sprintf("%s\n",
errorAndWarningSummary(errors, warnings, shownErrors, shownWarnings)))
}
}
switch options.Color {
case ColorNever:
terminalInfo.UseColorEscapes = false
case ColorAlways:
terminalInfo.UseColorEscapes = SupportsColorEscapes
}
return Log{
Level: options.LogLevel,
AddMsg: func(msg Msg) {
mutex.Lock()
defer mutex.Unlock()
msgs = append(msgs, msg)
switch msg.Kind {
case Verbose:
if options.LogLevel <= LevelVerbose {
writeStringWithColor(os.Stderr, msg.String(options, terminalInfo))
}
case Debug:
if options.LogLevel <= LevelDebug {
writeStringWithColor(os.Stderr, msg.String(options, terminalInfo))
}
case Info:
if options.LogLevel <= LevelInfo {
writeStringWithColor(os.Stderr, msg.String(options, terminalInfo))
}
case Error:
hasErrors = true
if options.LogLevel <= LevelError {
errors++
}
case Warning:
if options.LogLevel <= LevelWarning {
warnings++
}
}
// Be silent if we're past the limit so we don't flood the terminal
if remainingMessagesBeforeLimit == 0 {
return
}
switch msg.Kind {
case Error:
if options.LogLevel <= LevelError {
shownErrors++
writeStringWithColor(os.Stderr, msg.String(options, terminalInfo))
remainingMessagesBeforeLimit--
}
case Warning:
if options.LogLevel <= LevelWarning {
if remainingMessagesBeforeLimit > (options.MessageLimit+1)/2 {
shownWarnings++
writeStringWithColor(os.Stderr, msg.String(options, terminalInfo))
remainingMessagesBeforeLimit--
} else {
// If we have less than half of the slots left, wait for potential
// future errors instead of using up all of the slots with warnings.
// We want the log for a failed build to always have at least one
// error in it.
deferredWarnings = append(deferredWarnings, msg)
}
}
}
},
HasErrors: func() bool {
mutex.Lock()
defer mutex.Unlock()
return hasErrors
},
AlmostDone: func() {
mutex.Lock()
defer mutex.Unlock()
finalizeLog()
},
Done: func() []Msg {
mutex.Lock()
defer mutex.Unlock()
finalizeLog()
sort.Stable(msgs)
return msgs
},
}
}
func PrintErrorToStderr(osArgs []string, text string) {
PrintMessageToStderr(osArgs, Msg{Kind: Error, Data: MsgData{Text: text}})
}
func OutputOptionsForArgs(osArgs []string) OutputOptions {
options := OutputOptions{IncludeSource: true}
// Implement a mini argument parser so these options always work even if we
// haven't yet gotten to the general-purpose argument parsing code
for _, arg := range osArgs {
switch arg {
case "--color=false":
options.Color = ColorNever
case "--color=true":
options.Color = ColorAlways
case "--log-level=info":
options.LogLevel = LevelInfo
case "--log-level=warning":
options.LogLevel = LevelWarning
case "--log-level=error":
options.LogLevel = LevelError
case "--log-level=silent":
options.LogLevel = LevelSilent
}
}
return options
}
func PrintMessageToStderr(osArgs []string, msg Msg) {
log := NewStderrLog(OutputOptionsForArgs(osArgs))
log.AddMsg(msg)
log.Done()
}
type Colors struct {
Reset string
Bold string
Dim string
Underline string
Red string
Green string
Blue string
Cyan string
Magenta string
Yellow string
RedBgRed string
RedBgWhite string
GreenBgGreen string
GreenBgWhite string
BlueBgBlue string
BlueBgWhite string
CyanBgCyan string
CyanBgBlack string
MagentaBgMagenta string
MagentaBgBlack string
YellowBgYellow string
YellowBgBlack string
}
var TerminalColors = Colors{
Reset: "\033[0m",
Bold: "\033[1m",
Dim: "\033[37m",
Underline: "\033[4m",
Red: "\033[31m",
Green: "\033[32m",
Blue: "\033[34m",
Cyan: "\033[36m",
Magenta: "\033[35m",
Yellow: "\033[33m",
RedBgRed: "\033[41;31m",
RedBgWhite: "\033[41;97m",
GreenBgGreen: "\033[42;32m",
GreenBgWhite: "\033[42;97m",
BlueBgBlue: "\033[44;34m",
BlueBgWhite: "\033[44;97m",
CyanBgCyan: "\033[46;36m",
CyanBgBlack: "\033[46;30m",
MagentaBgMagenta: "\033[45;35m",
MagentaBgBlack: "\033[45;30m",
YellowBgYellow: "\033[43;33m",
YellowBgBlack: "\033[43;30m",
}
func PrintText(file *os.File, level LogLevel, osArgs []string, callback func(Colors) string) {
options := OutputOptionsForArgs(osArgs)
// Skip logging these if these logs are disabled
if options.LogLevel > level {
return
}
PrintTextWithColor(file, options.Color, callback)
}
func PrintTextWithColor(file *os.File, useColor UseColor, callback func(Colors) string) {
var useColorEscapes bool
switch useColor {
case ColorNever:
useColorEscapes = false
case ColorAlways:
useColorEscapes = SupportsColorEscapes
case ColorIfTerminal:
useColorEscapes = GetTerminalInfo(file).UseColorEscapes
}
var colors Colors
if useColorEscapes {
colors = TerminalColors
}
writeStringWithColor(file, callback(colors))
}
type SummaryTableEntry struct {
Dir string
Base string
Size string
Bytes int
IsSourceMap bool
}
// This type is just so we can use Go's native sort function
type SummaryTable []SummaryTableEntry
func (t SummaryTable) Len() int { return len(t) }
func (t SummaryTable) Swap(i int, j int) { t[i], t[j] = t[j], t[i] }
func (t SummaryTable) Less(i int, j int) bool {
ti := t[i]
tj := t[j]
// Sort source maps last
if !ti.IsSourceMap && tj.IsSourceMap {
return true
}
if ti.IsSourceMap && !tj.IsSourceMap {
return false
}
// Sort by size first
if ti.Bytes > tj.Bytes {
return true
}
if ti.Bytes < tj.Bytes {
return false
}
// Sort alphabetically by directory first
if ti.Dir < tj.Dir {
return true
}
if ti.Dir > tj.Dir {
return false
}
// Then sort alphabetically by file name
return ti.Base < tj.Base
}
// Show a warning icon next to output files that are 1mb or larger
const sizeWarningThreshold = 1024 * 1024
func PrintSummary(useColor UseColor, table SummaryTable, start *time.Time) {
PrintTextWithColor(os.Stderr, useColor, func(colors Colors) string {
isProbablyWindowsCommandPrompt := isProbablyWindowsCommandPrompt()
sb := strings.Builder{}
if len(table) > 0 {
info := GetTerminalInfo(os.Stderr)
// Truncate the table in case it's really long
maxLength := info.Height / 2
if info.Height == 0 {
maxLength = 20
} else if maxLength < 5 {
maxLength = 5
}
length := len(table)
sort.Sort(table)
if length > maxLength {
table = table[:maxLength]
}
// Compute the maximum width of the size column
spacingBetweenColumns := 2
hasSizeWarning := false
maxPath := 0
maxSize := 0
for _, entry := range table {
path := len(entry.Dir) + len(entry.Base)
size := len(entry.Size) + spacingBetweenColumns
if path > maxPath {
maxPath = path
}
if size > maxSize {
maxSize = size
}
if !entry.IsSourceMap && entry.Bytes >= sizeWarningThreshold {
hasSizeWarning = true
}
}
margin := " "
layoutWidth := info.Width
if layoutWidth < 1 {
layoutWidth = defaultTerminalWidth
}
layoutWidth -= 2 * len(margin)
if hasSizeWarning {
// Add space for the warning icon
layoutWidth -= 2
}
if layoutWidth > maxPath+maxSize {
layoutWidth = maxPath + maxSize
}
sb.WriteByte('\n')
for _, entry := range table {
dir, base := entry.Dir, entry.Base
pathWidth := layoutWidth - maxSize
// Truncate the path with "..." to fit on one line
if len(dir)+len(base) > pathWidth {
// Trim the directory from the front, leaving the trailing slash
if len(dir) > 0 {
n := pathWidth - len(base) - 3
if n < 1 {
n = 1
}
dir = "..." + dir[len(dir)-n:]
}
// Trim the file name from the back
if len(dir)+len(base) > pathWidth {
n := pathWidth - len(dir) - 3
if n < 0 {
n = 0
}
base = base[:n] + "..."
}
}
spacer := layoutWidth - len(entry.Size) - len(dir) - len(base)
if spacer < 0 {
spacer = 0
}
// Put a warning next to the size if it's above a certain threshold
sizeColor := colors.Cyan
sizeWarning := ""
if !entry.IsSourceMap && entry.Bytes >= sizeWarningThreshold {
sizeColor = colors.Yellow
// Emoji don't work in Windows Command Prompt
if !isProbablyWindowsCommandPrompt {
sizeWarning = " ⚠️"
}
}
sb.WriteString(fmt.Sprintf("%s%s%s%s%s%s%s%s%s%s%s%s\n",
margin,
colors.Dim,
dir,
colors.Reset,
colors.Bold,
base,
colors.Reset,
strings.Repeat(" ", spacer),
sizeColor,
entry.Size,
sizeWarning,
colors.Reset,
))
}
// Say how many remaining files are not shown
if length > maxLength {
plural := "s"
if length == maxLength+1 {
plural = ""
}
sb.WriteString(fmt.Sprintf("%s%s...and %d more output file%s...%s\n", margin, colors.Dim, length-maxLength, plural, colors.Reset))
}
}
sb.WriteByte('\n')
lightningSymbol := "⚡ "
// Emoji don't work in Windows Command Prompt
if isProbablyWindowsCommandPrompt {
lightningSymbol = ""
}
// Printing the time taken is optional
if start != nil {
sb.WriteString(fmt.Sprintf("%s%sDone in %dms%s\n",
lightningSymbol,
colors.Green,
time.Since(*start).Milliseconds(),
colors.Reset,
))
}
return sb.String()
})
}
type DeferLogKind uint8
const (
DeferLogAll DeferLogKind = iota
DeferLogNoVerboseOrDebug
)
func NewDeferLog(kind DeferLogKind) Log {
var msgs SortableMsgs
var mutex sync.Mutex
var hasErrors bool
return Log{
Level: LevelInfo,
AddMsg: func(msg Msg) {
if kind == DeferLogNoVerboseOrDebug && (msg.Kind == Verbose || msg.Kind == Debug) {
return
}
mutex.Lock()
defer mutex.Unlock()
if msg.Kind == Error {
hasErrors = true
}
msgs = append(msgs, msg)
},
HasErrors: func() bool {
mutex.Lock()
defer mutex.Unlock()
return hasErrors
},
AlmostDone: func() {
},
Done: func() []Msg {
mutex.Lock()
defer mutex.Unlock()
sort.Stable(msgs)
return msgs
},
}
}
type UseColor uint8
const (
ColorIfTerminal UseColor = iota
ColorNever
ColorAlways
)
type OutputOptions struct {
MessageLimit int
IncludeSource bool
Color UseColor
LogLevel LogLevel
}
func (msg Msg) String(options OutputOptions, terminalInfo TerminalInfo) string {
// Format the message
text := msgString(options.IncludeSource, terminalInfo, msg.Kind, msg.Data, msg.PluginName)
// Format the notes
var oldData MsgData
for i, note := range msg.Notes {
if options.IncludeSource && (i == 0 || strings.IndexByte(oldData.Text, '\n') >= 0 || oldData.Location != nil) {
text += "\n"
}
text += msgString(options.IncludeSource, terminalInfo, Note, note, "")
oldData = note
}