forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfmt.zig
1854 lines (1623 loc) · 64.6 KB
/
fmt.zig
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
const std = @import("std");
const bun = @import("root").bun;
const Output = bun.Output;
const strings = bun.strings;
const string = bun.string;
const js_lexer = bun.js_lexer;
const ComptimeStringMap = bun.ComptimeStringMap;
const fmt = std.fmt;
const Environment = bun.Environment;
const sha = bun.sha;
pub usingnamespace std.fmt;
pub const TableSymbols = struct {
enable_ansi_colors: bool,
pub const unicode = TableSymbols{ .enable_ansi_colors = true };
pub const ascii = TableSymbols{ .enable_ansi_colors = false };
pub fn topLeftSep(comptime s: TableSymbols) []const u8 {
return if (s.enable_ansi_colors) "┌" else "|";
}
pub fn topRightSep(comptime s: TableSymbols) []const u8 {
return if (s.enable_ansi_colors) "┐" else "|";
}
pub fn topColumnSep(comptime s: TableSymbols) []const u8 {
return if (s.enable_ansi_colors) "┬" else "-";
}
pub fn bottomLeftSep(comptime s: TableSymbols) []const u8 {
return if (s.enable_ansi_colors) "└" else "|";
}
pub fn bottomRightSep(comptime s: TableSymbols) []const u8 {
return if (s.enable_ansi_colors) "┘" else "|";
}
pub fn bottomColumnSep(comptime s: TableSymbols) []const u8 {
return if (s.enable_ansi_colors) "┴" else "-";
}
pub fn middleLeftSep(comptime s: TableSymbols) []const u8 {
return if (s.enable_ansi_colors) "├" else "|";
}
pub fn middleRightSep(comptime s: TableSymbols) []const u8 {
return if (s.enable_ansi_colors) "┤" else "|";
}
pub fn middleColumnSep(comptime s: TableSymbols) []const u8 {
return if (s.enable_ansi_colors) "┼" else "|";
}
pub fn horizontalEdge(comptime s: TableSymbols) []const u8 {
return if (s.enable_ansi_colors) "─" else "-";
}
pub fn verticalEdge(comptime s: TableSymbols) []const u8 {
return if (s.enable_ansi_colors) "│" else "|";
}
};
pub fn Table(
comptime column_color: []const u8,
comptime column_left_pad: usize,
comptime column_right_pad: usize,
comptime enable_ansi_colors: bool,
) type {
const symbols = TableSymbols{ .enable_ansi_colors = enable_ansi_colors };
return struct {
column_names: []const []const u8,
column_inside_lengths: []const usize,
comptime symbols: TableSymbols = symbols,
pub fn init(column_names_: []const []const u8, column_inside_lengths_: []const usize) @This() {
return .{
.column_names = column_names_,
.column_inside_lengths = column_inside_lengths_,
};
}
pub fn printTopLineSeparator(this: *const @This()) void {
this.printLine(symbols.topLeftSep(), symbols.topRightSep(), symbols.topColumnSep());
}
pub fn printBottomLineSeparator(this: *const @This()) void {
this.printLine(symbols.bottomLeftSep(), symbols.bottomRightSep(), symbols.bottomColumnSep());
}
pub fn printLineSeparator(this: *const @This()) void {
this.printLine(symbols.middleLeftSep(), symbols.middleRightSep(), symbols.middleColumnSep());
}
pub fn printLine(this: *const @This(), left_edge_separator: string, right_edge_separator: string, column_separator: string) void {
for (this.column_inside_lengths, 0..) |column_inside_length, i| {
if (i == 0) {
Output.pretty("{s}", .{left_edge_separator});
} else {
Output.pretty("{s}", .{column_separator});
}
for (0..column_left_pad + column_inside_length + column_right_pad) |_| Output.pretty("{s}", .{symbols.horizontalEdge()});
if (i == this.column_inside_lengths.len - 1) {
Output.pretty("{s}\n", .{right_edge_separator});
}
}
}
pub fn printColumnNames(this: *const @This()) void {
for (this.column_inside_lengths, 0..) |column_inside_length, i| {
Output.pretty("{s}", .{symbols.verticalEdge()});
for (0..column_left_pad) |_| Output.pretty(" ", .{});
Output.pretty("<b><" ++ column_color ++ ">{s}<r>", .{this.column_names[i]});
for (this.column_names[i].len..column_inside_length + column_right_pad) |_| Output.pretty(" ", .{});
if (i == this.column_inside_lengths.len - 1) {
Output.pretty("{s}\n", .{symbols.verticalEdge()});
}
}
}
};
}
pub const RedactedNpmUrlFormatter = struct {
url: string,
pub fn format(this: @This(), comptime _: string, _: std.fmt.FormatOptions, writer: anytype) !void {
var i: usize = 0;
while (i < this.url.len) {
if (strings.startsWithUUID(this.url[i..])) {
try writer.writeAll("***");
i += 36;
continue;
}
const npm_secret_len = strings.startsWithNpmSecret(this.url[i..]);
if (npm_secret_len > 0) {
try writer.writeAll("***");
i += npm_secret_len;
continue;
}
// TODO: redact password from `https://username:[email protected]/`
try writer.writeByte(this.url[i]);
i += 1;
}
}
};
pub fn redactedNpmUrl(str: string) RedactedNpmUrlFormatter {
return .{
.url = str,
};
}
pub const RedactedSourceFormatter = struct {
text: string,
pub fn format(this: @This(), comptime _: string, _: std.fmt.FormatOptions, writer: anytype) !void {
var i: usize = 0;
while (i < this.text.len) {
if (strings.startsWithSecret(this.text[i..])) |secret| {
const offset, const len = secret;
try writer.writeAll(this.text[i..][0..offset]);
try writer.writeByteNTimes('*', len);
i += offset + len;
continue;
}
try writer.writeByte(this.text[i]);
i += 1;
}
}
};
pub fn redactedSource(str: string) RedactedSourceFormatter {
return .{
.text = str,
};
}
// https://github.com/npm/cli/blob/63d6a732c3c0e9c19fd4d147eaa5cc27c29b168d/node_modules/npm-package-arg/lib/npa.js#L163
pub const DependencyUrlFormatter = struct {
url: string,
pub fn format(this: @This(), comptime _: string, _: std.fmt.FormatOptions, writer: anytype) !void {
var remain = this.url;
while (strings.indexOfChar(remain, '/')) |slash| {
try writer.writeAll(remain[0..slash]);
try writer.writeAll("%2f");
remain = remain[slash + 1 ..];
}
try writer.writeAll(remain);
}
};
pub fn dependencyUrl(url: string) DependencyUrlFormatter {
return .{
.url = url,
};
}
const IntegrityFormatStyle = enum {
short,
full,
};
pub fn IntegrityFormatter(comptime style: IntegrityFormatStyle) type {
return struct {
bytes: [sha.SHA512.digest]u8,
pub fn format(this: @This(), comptime _: string, _: std.fmt.FormatOptions, writer: anytype) !void {
var buf: [std.base64.standard.Encoder.calcSize(sha.SHA512.digest)]u8 = undefined;
const count = bun.simdutf.base64.encode(this.bytes[0..sha.SHA512.digest], &buf, false);
const encoded = buf[0..count];
if (comptime style == .short)
try writer.print("sha512-{s}[...]{s}", .{ encoded[0..13], encoded[encoded.len - 15 ..] })
else
try writer.print("sha512-{s}", .{encoded});
}
};
}
pub fn integrity(bytes: [sha.SHA512.digest]u8, comptime style: IntegrityFormatStyle) IntegrityFormatter(style) {
return .{ .bytes = bytes };
}
const JSONFormatter = struct {
input: []const u8,
pub fn format(self: JSONFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try bun.js_printer.writeJSONString(self.input, @TypeOf(writer), writer, .latin1);
}
};
const JSONFormatterUTF8 = struct {
input: []const u8,
pub fn format(self: JSONFormatterUTF8, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try bun.js_printer.writeJSONString(self.input, @TypeOf(writer), writer, .utf8);
}
};
/// Expects latin1
pub fn formatJSONString(text: []const u8) JSONFormatter {
return .{ .input = text };
}
pub fn formatJSONStringUTF8(text: []const u8) JSONFormatterUTF8 {
return .{ .input = text };
}
const SharedTempBuffer = [32 * 1024]u8;
fn getSharedBuffer() []u8 {
return std.mem.asBytes(shared_temp_buffer_ptr orelse brk: {
shared_temp_buffer_ptr = bun.default_allocator.create(SharedTempBuffer) catch unreachable;
break :brk shared_temp_buffer_ptr.?;
});
}
threadlocal var shared_temp_buffer_ptr: ?*SharedTempBuffer = null;
pub fn formatUTF16Type(comptime Slice: type, slice_: Slice, writer: anytype) !void {
var chunk = getSharedBuffer();
// Defensively ensure recursion doesn't cause the buffer to be overwritten in-place
shared_temp_buffer_ptr = null;
defer {
if (shared_temp_buffer_ptr) |existing| {
if (existing != chunk.ptr) {
bun.default_allocator.destroy(@as(*SharedTempBuffer, @ptrCast(chunk.ptr)));
}
} else {
shared_temp_buffer_ptr = @ptrCast(chunk.ptr);
}
}
var slice = slice_;
while (slice.len > 0) {
const result = strings.copyUTF16IntoUTF8(chunk, Slice, slice, true);
if (result.read == 0 or result.written == 0)
break;
try writer.writeAll(chunk[0..result.written]);
slice = slice[result.read..];
}
}
pub fn formatUTF16TypeWithPathOptions(comptime Slice: type, slice_: Slice, writer: anytype, opts: PathFormatOptions) !void {
var chunk = getSharedBuffer();
// Defensively ensure recursion doesn't cause the buffer to be overwritten in-place
shared_temp_buffer_ptr = null;
defer {
if (shared_temp_buffer_ptr) |existing| {
if (existing != chunk.ptr) {
bun.default_allocator.destroy(@as(*SharedTempBuffer, @ptrCast(chunk.ptr)));
}
} else {
shared_temp_buffer_ptr = @ptrCast(chunk.ptr);
}
}
var slice = slice_;
while (slice.len > 0) {
const result = strings.copyUTF16IntoUTF8(chunk, Slice, slice, true);
if (result.read == 0 or result.written == 0)
break;
const to_write = chunk[0..result.written];
if (!opts.escape_backslashes and opts.path_sep == .any) {
try writer.writeAll(to_write);
} else {
var ptr = to_write;
while (strings.indexOfAny(ptr, "\\/")) |i| {
const sep = switch (opts.path_sep) {
.windows => '\\',
.posix => '/',
.auto => std.fs.path.sep,
.any => ptr[i],
};
try writer.writeAll(ptr[0..i]);
try writer.writeByte(sep);
if (opts.escape_backslashes and sep == '\\') {
try writer.writeByte(sep);
}
ptr = ptr[i + 1 ..];
}
try writer.writeAll(ptr);
}
slice = slice[result.read..];
}
}
pub inline fn utf16(slice_: []const u16) FormatUTF16 {
return FormatUTF16{ .buf = slice_ };
}
/// Debug, this does not handle invalid utf32
pub inline fn debugUtf32PathFormatter(path: []const u32) DebugUTF32PathFormatter {
return DebugUTF32PathFormatter{ .path = path };
}
pub const DebugUTF32PathFormatter = struct {
path: []const u32,
pub fn format(this: @This(), comptime _: []const u8, _: anytype, writer: anytype) !void {
var path_buf: bun.PathBuffer = undefined;
const result = bun.simdutf.convert.utf32.to.utf8.with_errors.le(this.path, &path_buf);
const converted = if (result.isSuccessful())
path_buf[0..result.count]
else
"Invalid UTF32!";
try writer.writeAll(converted);
}
};
pub const FormatUTF16 = struct {
buf: []const u16,
path_fmt_opts: ?PathFormatOptions = null,
pub fn format(self: @This(), comptime _: []const u8, _: anytype, writer: anytype) !void {
if (self.path_fmt_opts) |opts| {
try formatUTF16TypeWithPathOptions([]const u16, self.buf, writer, opts);
} else {
try formatUTF16Type([]const u16, self.buf, writer);
}
}
};
pub const FormatUTF8 = struct {
buf: []const u8,
path_fmt_opts: ?PathFormatOptions = null,
pub fn format(self: @This(), comptime _: []const u8, _: anytype, writer: anytype) !void {
if (self.path_fmt_opts) |opts| {
if (opts.path_sep == .any and opts.escape_backslashes == false) {
try writer.writeAll(self.buf);
return;
}
var ptr = self.buf;
while (strings.indexOfAny(ptr, "\\/")) |i| {
const sep = switch (opts.path_sep) {
.windows => '\\',
.posix => '/',
.auto => std.fs.path.sep,
.any => ptr[i],
};
try writer.writeAll(ptr[0..i]);
try writer.writeByte(sep);
if (opts.escape_backslashes and sep == '\\') {
try writer.writeByte(sep);
}
ptr = ptr[i + 1 ..];
}
try writer.writeAll(ptr);
return;
}
try writer.writeAll(self.buf);
}
};
pub const PathFormatOptions = struct {
// The path separator used when formatting the path.
path_sep: Sep = .any,
/// Any backslashes are escaped, including backslashes
/// added through `path_sep`.
escape_backslashes: bool = false,
pub const Sep = enum {
/// Keep paths separators as is.
any,
/// Replace all path separators with the current platform path separator.
auto,
/// Replace all path separators with `/`.
posix,
/// Replace all path separators with `\`.
windows,
};
};
pub const FormatOSPath = if (Environment.isWindows) FormatUTF16 else FormatUTF8;
pub fn fmtOSPath(buf: bun.OSPathSlice, options: PathFormatOptions) FormatOSPath {
return FormatOSPath{
.buf = buf,
.path_fmt_opts = options,
};
}
pub fn fmtPath(
comptime T: type,
path: []const T,
options: PathFormatOptions,
) if (T == u8) FormatUTF8 else FormatUTF16 {
if (T == u8) {
return FormatUTF8{
.buf = path,
.path_fmt_opts = options,
};
}
return FormatUTF16{
.buf = path,
.path_fmt_opts = options,
};
}
pub fn formatLatin1(slice_: []const u8, writer: anytype) !void {
var chunk = getSharedBuffer();
var slice = slice_;
// Defensively ensure recursion doesn't cause the buffer to be overwritten in-place
shared_temp_buffer_ptr = null;
defer {
if (shared_temp_buffer_ptr) |existing| {
if (existing != chunk.ptr) {
bun.default_allocator.destroy(@as(*SharedTempBuffer, @ptrCast(chunk.ptr)));
}
} else {
shared_temp_buffer_ptr = @ptrCast(chunk.ptr);
}
}
while (strings.firstNonASCII(slice)) |i| {
if (i > 0) {
try writer.writeAll(slice[0..i]);
slice = slice[i..];
}
const result = strings.copyLatin1IntoUTF8(chunk, @TypeOf(slice), slice[0..@min(chunk.len, slice.len)]);
if (result.read == 0 or result.written == 0)
break;
try writer.writeAll(chunk[0..result.written]);
slice = slice[result.read..];
}
if (slice.len > 0)
try writer.writeAll(slice); // write the remaining bytes
}
pub const URLFormatter = struct {
proto: Proto = .http,
hostname: ?string = null,
port: ?u16 = null,
const Proto = enum {
http,
https,
unix,
abstract,
};
pub fn format(this: URLFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try writer.print("{s}://", .{switch (this.proto) {
.http => "http",
.https => "https",
.unix => "unix",
.abstract => "abstract",
}});
if (this.hostname) |hostname| {
const needs_brackets = hostname[0] != '[' and strings.isIPV6Address(hostname);
if (needs_brackets) {
try writer.print("[{s}]", .{hostname});
} else {
try writer.writeAll(hostname);
}
} else {
try writer.writeAll("localhost");
}
if (this.proto == .unix) {
return;
}
const is_port_optional = this.port == null or (this.proto == .https and this.port == 443) or
(this.proto == .http and this.port == 80);
if (is_port_optional) {
try writer.writeAll("/");
} else {
try writer.print(":{d}/", .{this.port.?});
}
}
};
pub const HostFormatter = struct {
host: string,
port: ?u16 = null,
is_https: bool = false,
pub fn format(formatter: HostFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
if (strings.indexOfChar(formatter.host, ':') != null) {
try writer.writeAll(formatter.host);
return;
}
try writer.writeAll(formatter.host);
const is_port_optional = formatter.port == null or (formatter.is_https and formatter.port == 443) or
(!formatter.is_https and formatter.port == 80);
if (!is_port_optional) {
try writer.print(":{d}", .{formatter.port.?});
return;
}
}
};
/// Format a string to an ECMAScript identifier.
/// Unlike the string_mutable.zig version, this always allocate/copy
pub fn fmtIdentifier(name: string) FormatValidIdentifier {
return FormatValidIdentifier{ .name = name };
}
/// Format a string to an ECMAScript identifier.
/// Different implementation than string_mutable because string_mutable may avoid allocating
/// This will always allocate
pub const FormatValidIdentifier = struct {
name: string,
pub fn format(self: FormatValidIdentifier, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
var iterator = strings.CodepointIterator.init(self.name);
var cursor = strings.CodepointIterator.Cursor{};
var has_needed_gap = false;
var needs_gap = false;
var start_i: usize = 0;
if (!iterator.next(&cursor)) {
try writer.writeAll("_");
return;
}
// Common case: no gap necessary. No allocation necessary.
needs_gap = !js_lexer.isIdentifierStart(cursor.c);
if (!needs_gap) {
// Are there any non-alphanumeric chars at all?
while (iterator.next(&cursor)) {
if (!js_lexer.isIdentifierContinue(cursor.c) or cursor.width > 1) {
needs_gap = true;
start_i = cursor.i;
break;
}
}
}
if (needs_gap) {
needs_gap = false;
if (start_i > 0) try writer.writeAll(self.name[0..start_i]);
var slice = self.name[start_i..];
iterator = strings.CodepointIterator.init(slice);
cursor = strings.CodepointIterator.Cursor{};
while (iterator.next(&cursor)) {
if (js_lexer.isIdentifierContinue(cursor.c) and cursor.width == 1) {
if (needs_gap) {
try writer.writeAll("_");
needs_gap = false;
has_needed_gap = true;
}
try writer.writeAll(slice[cursor.i .. cursor.i + @as(u32, cursor.width)]);
} else if (!needs_gap) {
needs_gap = true;
// skip the code point, replace it with a single _
}
}
// If it ends with an emoji
if (needs_gap) {
try writer.writeAll("_");
needs_gap = false;
has_needed_gap = true;
}
return;
}
try writer.writeAll(self.name);
}
};
// Formats a string to be safe to output in a Github action.
// - Encodes "\n" as "%0A" to support multi-line strings.
// https://github.com/actions/toolkit/issues/193#issuecomment-605394935
// - Strips ANSI output as it will appear malformed.
pub fn githubActionWriter(writer: anytype, self: string) !void {
var offset: usize = 0;
const end = @as(u32, @truncate(self.len));
while (offset < end) {
if (strings.indexOfNewlineOrNonASCIIOrANSI(self, @as(u32, @truncate(offset)))) |i| {
const byte = self[i];
if (byte > 0x7F) {
offset += @max(strings.wtf8ByteSequenceLength(byte), 1);
continue;
}
if (i > 0) {
try writer.writeAll(self[offset..i]);
}
var n: usize = 1;
if (byte == '\n') {
try writer.writeAll("%0A");
} else if (i + 1 < end) {
const next = self[i + 1];
if (byte == '\r' and next == '\n') {
n += 1;
try writer.writeAll("%0A");
} else if (byte == '\x1b' and next == '[') {
n += 1;
if (i + 2 < end) {
const remain = self[(i + 2)..@min(i + 5, end)];
if (strings.indexOfChar(remain, 'm')) |j| {
n += j + 1;
}
}
}
}
offset = i + n;
} else {
try writer.writeAll(self[offset..end]);
break;
}
}
}
pub const GithubActionFormatter = struct {
text: string,
pub fn format(this: GithubActionFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try githubActionWriter(writer, this.text);
}
};
pub fn githubAction(self: string) strings.GithubActionFormatter {
return GithubActionFormatter{
.text = self,
};
}
pub fn quotedWriter(writer: anytype, self: string) !void {
const remain = self;
if (strings.containsNewlineOrNonASCIIOrQuote(remain)) {
try bun.js_printer.writeJSONString(self, @TypeOf(writer), writer, strings.Encoding.utf8);
} else {
try writer.writeAll("\"");
try writer.writeAll(self);
try writer.writeAll("\"");
}
}
pub const QuotedFormatter = struct {
text: []const u8,
pub fn format(this: QuotedFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try quotedWriter(writer, this.text);
}
};
pub fn fmtJavaScript(text: []const u8, opts: QuickAndDirtyJavaScriptSyntaxHighlighter.Options) QuickAndDirtyJavaScriptSyntaxHighlighter {
return QuickAndDirtyJavaScriptSyntaxHighlighter{
.text = text,
.opts = opts,
};
}
pub const QuickAndDirtyJavaScriptSyntaxHighlighter = struct {
text: []const u8,
opts: Options,
pub const Options = struct {
enable_colors: bool,
check_for_unhighlighted_write: bool = true,
redact_sensitive_information: bool = false,
pub const default: Options = .{
.enable_colors = Output.enable_ansi_colors,
.check_for_no_highlighting = true,
.redact_sensitive_information = false,
};
};
const ColorCode = enum {
magenta,
blue,
orange,
red,
pink,
pub fn color(this: ColorCode) []const u8 {
return switch (this) {
.magenta => "\x1b[35m",
.blue => "\x1b[34m",
.orange => "\x1b[33m",
.red => "\x1b[31m",
// light pink
.pink => "\x1b[38;5;206m",
};
}
};
pub const Keyword = enum {
abstract,
as,
@"async",
@"await",
case,
@"catch",
class,
@"const",
@"continue",
debugger,
default,
delete,
do,
@"else",
@"enum",
@"export",
extends,
false,
finally,
@"for",
function,
@"if",
implements,
import,
in,
instanceof,
interface,
let,
new,
null,
package,
private,
protected,
public,
@"return",
static,
super,
@"switch",
this,
throw,
@"break",
true,
@"try",
type,
typeof,
@"var",
void,
@"while",
with,
yield,
string,
number,
boolean,
symbol,
any,
object,
unknown,
never,
namespace,
declare,
readonly,
undefined,
pub fn colorCode(this: Keyword) ColorCode {
return switch (this) {
.abstract => .blue,
.as => .blue,
.@"async" => .magenta,
.@"await" => .magenta,
.case => .magenta,
.@"catch" => .magenta,
.class => .magenta,
.@"const" => .magenta,
.@"continue" => .magenta,
.debugger => .magenta,
.default => .magenta,
.delete => .red,
.do => .magenta,
.@"else" => .magenta,
.@"break" => .magenta,
.undefined => .orange,
.@"enum" => .blue,
.@"export" => .magenta,
.extends => .magenta,
.false => .orange,
.finally => .magenta,
.@"for" => .magenta,
.function => .magenta,
.@"if" => .magenta,
.implements => .blue,
.import => .magenta,
.in => .magenta,
.instanceof => .magenta,
.interface => .blue,
.let => .magenta,
.new => .magenta,
.null => .orange,
.package => .magenta,
.private => .blue,
.protected => .blue,
.public => .blue,
.@"return" => .magenta,
.static => .magenta,
.super => .magenta,
.@"switch" => .magenta,
.this => .orange,
.throw => .magenta,
.true => .orange,
.@"try" => .magenta,
.type => .blue,
.typeof => .magenta,
.@"var" => .magenta,
.void => .magenta,
.@"while" => .magenta,
.with => .magenta,
.yield => .magenta,
.string => .blue,
.number => .blue,
.boolean => .blue,
.symbol => .blue,
.any => .blue,
.object => .blue,
.unknown => .blue,
.never => .blue,
.namespace => .blue,
.declare => .blue,
.readonly => .blue,
};
}
};
pub const Keywords = bun.ComptimeEnumMap(Keyword);
pub const RedactedKeyword = enum {
_auth,
_authToken,
token,
_password,
email,
};
pub const RedactedKeywords = bun.ComptimeEnumMap(RedactedKeyword);
pub fn format(this: @This(), comptime unused_fmt: []const u8, _: fmt.FormatOptions, writer: anytype) !void {
comptime bun.assert(unused_fmt.len == 0);
var text = this.text;
if (this.opts.check_for_unhighlighted_write) {
if (!this.opts.enable_colors or text.len > 2048 or text.len == 0 or !strings.isAllASCII(text)) {
if (this.opts.redact_sensitive_information) {
try writer.print("{}", .{redactedSource(text)});
} else {
try writer.writeAll(text);
}
return;
}
}
var prev_keyword: ?Keyword = null;
var should_redact_value = false;
outer: while (text.len > 0) {
if (js_lexer.isIdentifierStart(text[0])) {
var i: usize = 1;
while (i < text.len and js_lexer.isIdentifierContinue(text[i])) {
i += 1;
}
if (Keywords.get(text[0..i])) |keyword| {
should_redact_value = false;
if (keyword != .as)
prev_keyword = keyword;
const code = keyword.colorCode();
try writer.print(Output.prettyFmt("<r>{s}{s}<r>", true), .{ code.color(), text[0..i] });
} else {
should_redact_value = this.opts.redact_sensitive_information and RedactedKeywords.has(text[0..i]);
write: {
if (prev_keyword) |prev| {
switch (prev) {
.new => {
prev_keyword = null;
if (i < text.len and text[i] == '(') {
try writer.print(Output.prettyFmt("<r><b>{s}<r>", true), .{text[0..i]});
break :write;
}
},
.abstract, .namespace, .declare, .type, .interface => {
try writer.print(Output.prettyFmt("<r><b><blue>{s}<r>", true), .{text[0..i]});
prev_keyword = null;
break :write;
},
.import => {
if (strings.eqlComptime(text[0..i], "from")) {
const code = ColorCode.magenta;
try writer.print(Output.prettyFmt("<r>{s}{s}<r>", true), .{ code.color(), text[0..i] });
prev_keyword = null;
break :write;
}
},
else => {},
}
}
try writer.writeAll(text[0..i]);
}
}
text = text[i..];
} else {
if (this.opts.redact_sensitive_information and should_redact_value) {
while (text.len > 0 and std.ascii.isWhitespace(text[0])) {
try writer.writeByte(text[0]);
text = text[1..];
}
if (text.len > 0 and (text[0] == '=' or text[0] == ':')) {
try writer.writeByte(text[0]);
text = text[1..];
while (text.len > 0 and std.ascii.isWhitespace(text[0])) {
try writer.writeByte(text[0]);
text = text[1..];
}
if (text.len == 0) return;
}
}
switch (text[0]) {
'0'...'9' => |num| {
if (this.opts.redact_sensitive_information) {
if (should_redact_value) {
should_redact_value = false;
const end = strings.indexOfChar(text, '\n') orelse text.len;
text = text[end..];
try writer.writeAll(Output.prettyFmt("<r><yellow>***<r>", true));
continue;
}
if (strings.startsWithUUID(text)) {
text = text[36..];
try writer.writeAll(Output.prettyFmt("<r><yellow>***<r>", true));
continue;
}
}
prev_keyword = null;
var i: usize = 1;
if (text.len > 1 and num == '0' and text[1] == 'x') {
i += 1;
while (i < text.len and switch (text[i]) {
'0'...'9', 'a'...'f', 'A'...'F' => true,
else => false,
}) {
i += 1;
}
} else {
while (i < text.len and switch (text[i]) {