This repository was archived by the owner on Jan 2, 2026. It is now read-only.
forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglob.zig
More file actions
3143 lines (2831 loc) · 130 KB
/
glob.zig
File metadata and controls
3143 lines (2831 loc) · 130 KB
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
// Portions of this file are derived from works under the MIT License:
//
// Copyright (c) 2023 Devon Govett
// Copyright (c) 2023 Stephen Gregoratto
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
const std = @import("std");
const math = std.math;
const mem = std.mem;
const BunString = @import("./bun.zig").String;
const expect = std.testing.expect;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayListUnmanaged;
const ArrayListManaged = std.ArrayList;
const DirIterator = @import("./bun.js/node/dir_iterator.zig");
const bun = @import("./bun.zig");
const Syscall = bun.sys;
const PathLike = @import("./bun.js/node/types.zig").PathLike;
const Maybe = @import("./bun.js/node/types.zig").Maybe;
const Dirent = @import("./bun.js/node/types.zig").Dirent;
const PathString = @import("./string_types.zig").PathString;
const ZigString = @import("./bun.js/bindings/bindings.zig").ZigString;
const isAllAscii = @import("./string_immutable.zig").isAllASCII;
const EntryKind = @import("./bun.js/node/types.zig").Dirent.Kind;
const Arena = std.heap.ArenaAllocator;
const GlobAscii = @import("./glob_ascii.zig");
const C = @import("./c.zig");
const ResolvePath = @import("./resolver/resolve_path.zig");
const eqlComptime = @import("./string_immutable.zig").eqlComptime;
const isWindows = @import("builtin").os.tag == .windows;
const CodepointIterator = @import("./string_immutable.zig").PackedCodepointIterator;
const Codepoint = CodepointIterator.Cursor.CodePointType;
// const Codepoint = u32;
const Cursor = CodepointIterator.Cursor;
const CursorState = struct {
cursor: CodepointIterator.Cursor = .{},
/// The index in terms of codepoints
// cp_idx: usize,
fn init(iterator: *const CodepointIterator) CursorState {
var this_cursor: CodepointIterator.Cursor = .{};
_ = iterator.next(&this_cursor);
return .{
// .cp_idx = 0,
.cursor = this_cursor,
};
}
/// Return cursor pos of next codepoint without modifying the current.
///
/// NOTE: If there is no next codepoint (cursor is at the last one), then
/// the returned cursor will have `c` as zero value and `i` will be >=
/// sourceBytes.len
fn peek(this: *const CursorState, iterator: *const CodepointIterator) CursorState {
var cpy = this.*;
// If outside of bounds
if (!iterator.next(&cpy.cursor)) {
// This will make `i >= sourceBytes.len`
cpy.cursor.i += cpy.cursor.width;
cpy.cursor.width = 1;
cpy.cursor.c = CodepointIterator.ZeroValue;
}
// cpy.cp_idx += 1;
return cpy;
}
fn bump(this: *CursorState, iterator: *const CodepointIterator) void {
if (!iterator.next(&this.cursor)) {
this.cursor.i += this.cursor.width;
this.cursor.width = 1;
this.cursor.c = CodepointIterator.ZeroValue;
}
// this.cp_idx += 1;
}
inline fn manualBumpAscii(this: *CursorState, i: u32, nextCp: Codepoint) void {
this.cursor.i += i;
this.cursor.c = nextCp;
this.cursor.width = 1;
}
inline fn manualPeekAscii(this: *CursorState, i: u32, nextCp: Codepoint) CursorState {
return .{
.cursor = CodepointIterator.Cursor{
.i = this.cursor.i + i,
.c = @truncate(nextCp),
.width = 1,
},
};
}
};
pub const BunGlobWalker = GlobWalker_(null);
fn dummyFilterTrue(val: []const u8) bool {
_ = val;
return true;
}
fn dummyFilterFalse(val: []const u8) bool {
_ = val;
return false;
}
pub fn GlobWalker_(
comptime ignore_filter_fn: ?*const fn ([]const u8) bool,
) type {
const is_ignored: *const fn ([]const u8) bool = if (comptime ignore_filter_fn) |func| func else dummyFilterFalse;
return struct {
const GlobWalker = @This();
pub const Result = Maybe(void);
arena: Arena = undefined,
/// not owned by this struct
pattern: []const u8 = "",
pattern_codepoints: []u32 = &[_]u32{},
cp_len: u32 = 0,
/// If the pattern contains "./" or "../"
has_relative_components: bool = false,
patternComponents: ArrayList(Component) = .{},
matchedPaths: ArrayList(BunString) = .{},
i: u32 = 0,
dot: bool = false,
absolute: bool = false,
cwd: []const u8 = "",
follow_symlinks: bool = false,
error_on_broken_symlinks: bool = false,
only_files: bool = true,
pathBuf: [bun.MAX_PATH_BYTES]u8 = undefined,
// iteration state
workbuf: ArrayList(WorkItem) = ArrayList(WorkItem){},
/// The glob walker references the .directory.path so its not safe to
/// copy/move this
const IterState = union(enum) {
/// Pops the next item off the work stack
get_next,
/// Currently iterating over a directory
directory: Directory,
const Directory = struct {
fd: bun.FileDescriptor,
iter: DirIterator.WrappedIterator,
path: [bun.MAX_PATH_BYTES]u8,
dir_path: [:0]const u8,
component_idx: u32,
pattern: *Component,
next_pattern: ?*Component,
is_last: bool,
iter_closed: bool = false,
at_cwd: bool = false,
};
};
pub const Iterator = struct {
walker: *GlobWalker,
iter_state: IterState = .get_next,
cwd_fd: bun.FileDescriptor = .zero,
empty_dir_path: [0:0]u8 = [0:0]u8{},
/// This is to make sure in debug/tests that we are closing file descriptors
/// We should only have max 2 open at a time. One for the cwd, and one for the
/// directory being iterated on.
fds_open: if (bun.Environment.allow_assert) usize else u0 = 0,
pub fn init(this: *Iterator) !Maybe(void) {
var path_buf: *[bun.MAX_PATH_BYTES]u8 = &this.walker.pathBuf;
const root_path = this.walker.cwd;
@memcpy(path_buf[0..root_path.len], root_path[0..root_path.len]);
path_buf[root_path.len] = 0;
const cwd_fd = switch (Syscall.open(@ptrCast(path_buf[0 .. root_path.len + 1]), std.os.O.DIRECTORY | std.os.O.RDONLY, 0)) {
.err => |err| return .{ .err = this.walker.handleSysErrWithPath(err, @ptrCast(path_buf[0 .. root_path.len + 1])) },
.result => |fd| fd,
};
if (bun.Environment.allow_assert) {
this.fds_open += 1;
}
this.cwd_fd = cwd_fd;
const root_work_item = WorkItem.new(this.walker.cwd, 0, .directory);
switch (try this.transitionToDirIterState(root_work_item, true)) {
.err => |err| return .{ .err = err },
else => {},
}
return Maybe(void).success;
}
pub fn deinit(this: *Iterator) void {
this.closeCwdFd();
switch (this.iter_state) {
.directory => |dir| {
if (!dir.iter_closed) {
this.closeDisallowingCwd(dir.fd);
}
},
else => {},
}
while (this.walker.workbuf.popOrNull()) |work_item| {
if (work_item.fd) |fd| {
this.closeDisallowingCwd(fd);
}
}
if (bun.Environment.allow_assert) {
std.debug.assert(this.fds_open == 0);
}
}
pub fn closeCwdFd(this: *Iterator) void {
if (this.cwd_fd == .zero) return;
_ = Syscall.close(this.cwd_fd);
if (bun.Environment.allow_assert) this.fds_open -= 1;
}
pub fn closeDisallowingCwd(this: *Iterator, fd: bun.FileDescriptor) void {
if (fd == this.cwd_fd) return;
_ = Syscall.close(fd);
if (bun.Environment.allow_assert) this.fds_open -= 1;
}
pub fn bumpOpenFds(this: *Iterator) void {
if (bun.Environment.allow_assert) {
this.fds_open += 1;
// If this is over 2 then this means that there is a bug in the iterator code
std.debug.assert(this.fds_open <= 2);
}
}
fn transitionToDirIterState(
this: *Iterator,
work_item: WorkItem,
comptime root: bool,
) !Maybe(void) {
this.iter_state = .{ .directory = .{
.fd = .zero,
.iter = undefined,
.path = undefined,
.dir_path = undefined,
.component_idx = 0,
.pattern = undefined,
.next_pattern = null,
.is_last = false,
.iter_closed = false,
.at_cwd = false,
} };
var dir_path: [:0]u8 = dir_path: {
if (comptime root) {
if (!this.walker.absolute) {
this.iter_state.directory.path[0] = 0;
break :dir_path this.iter_state.directory.path[0..0 :0];
}
}
// TODO Optimization: On posix systems filepaths are already null byte terminated so we can skip this if thats the case
@memcpy(this.iter_state.directory.path[0..work_item.path.len], work_item.path);
this.iter_state.directory.path[work_item.path.len] = 0;
break :dir_path this.iter_state.directory.path[0..work_item.path.len :0];
};
var had_dot_dot = false;
const component_idx = this.walker.skipSpecialComponents(work_item.idx, &dir_path, &this.iter_state.directory.path, &had_dot_dot);
this.iter_state.directory.dir_path = dir_path;
this.iter_state.directory.component_idx = component_idx;
this.iter_state.directory.pattern = &this.walker.patternComponents.items[component_idx];
this.iter_state.directory.next_pattern = if (component_idx + 1 < this.walker.patternComponents.items.len) &this.walker.patternComponents.items[component_idx + 1] else null;
this.iter_state.directory.is_last = component_idx == this.walker.patternComponents.items.len - 1;
this.iter_state.directory.at_cwd = false;
const fd: bun.FileDescriptor = fd: {
if (work_item.fd) |fd| break :fd fd;
if (comptime root) {
if (had_dot_dot) break :fd switch (Syscall.openat(this.cwd_fd, dir_path, std.os.O.DIRECTORY | std.os.O.RDONLY, 0)) {
.err => |err| return .{
.err = this.walker.handleSysErrWithPath(err, dir_path),
},
.result => |fd_| brk: {
this.bumpOpenFds();
break :brk fd_;
},
};
this.iter_state.directory.at_cwd = true;
break :fd this.cwd_fd;
}
break :fd switch (Syscall.openat(this.cwd_fd, dir_path, std.os.O.DIRECTORY | std.os.O.RDONLY, 0)) {
.err => |err| return .{
.err = this.walker.handleSysErrWithPath(err, dir_path),
},
.result => |fd_| brk: {
this.bumpOpenFds();
break :brk fd_;
},
};
};
this.iter_state.directory.fd = fd;
const dir = std.fs.Dir{ .fd = bun.fdcast(fd) };
const iterator = DirIterator.iterate(dir, .u8);
this.iter_state.directory.iter = iterator;
this.iter_state.directory.iter_closed = false;
return Maybe(void).success;
}
pub fn next(this: *Iterator) !Maybe(?[]const u8) {
while (true) {
switch (this.iter_state) {
.get_next => {
// Done
if (this.walker.workbuf.items.len == 0) return .{ .result = null };
const work_item = this.walker.workbuf.pop();
switch (work_item.kind) {
.directory => {
switch (try this.transitionToDirIterState(work_item, false)) {
.err => |err| return .{ .err = err },
else => {},
}
continue;
},
.symlink => {
var scratch_path_buf: *[bun.MAX_PATH_BYTES]u8 = &this.walker.pathBuf;
@memcpy(scratch_path_buf[0..work_item.path.len], work_item.path);
scratch_path_buf[work_item.path.len] = 0;
var symlink_full_path_z: [:0]u8 = scratch_path_buf[0..work_item.path.len :0];
const entry_name = symlink_full_path_z[work_item.entry_start..symlink_full_path_z.len];
var has_dot_dot = false;
const component_idx = this.walker.skipSpecialComponents(work_item.idx, &symlink_full_path_z, scratch_path_buf, &has_dot_dot);
var pattern = this.walker.patternComponents.items[component_idx];
const next_pattern = if (component_idx + 1 < this.walker.patternComponents.items.len) &this.walker.patternComponents.items[component_idx + 1] else null;
const is_last = component_idx == this.walker.patternComponents.items.len - 1;
this.iter_state = .get_next;
const maybe_dir_fd: ?bun.FileDescriptor = switch (Syscall.openat(this.cwd_fd, symlink_full_path_z, std.os.O.DIRECTORY | std.os.O.RDONLY, 0)) {
.err => |err| brk: {
if (@as(usize, @intCast(err.errno)) == @as(usize, @intFromEnum(bun.C.E.NOTDIR))) {
break :brk null;
}
if (this.walker.error_on_broken_symlinks) return .{ .err = this.walker.handleSysErrWithPath(err, symlink_full_path_z) };
// Broken symlink, but if `only_files` is false we still want to append
// it to the matched paths
if (!this.walker.only_files) {
// (See case A and B in the comment for `matchPatternFile()`)
// When we encounter a symlink we call the catch all
// matching function: `matchPatternImpl()` to see if we can avoid following the symlink.
// So for case A, we just need to check if the pattern is the last pattern.
if (is_last or
(pattern.syntax_hint == .Double and
component_idx + 1 == this.walker.patternComponents.items.len -| 1 and
next_pattern.?.syntax_hint != .Double and
this.walker.matchPatternImpl(next_pattern.?, entry_name)))
{
return .{ .result = try this.walker.prepareMatchedPathSymlink(symlink_full_path_z) };
}
}
continue;
},
.result => |fd| brk: {
this.bumpOpenFds();
break :brk fd;
},
};
const dir_fd = maybe_dir_fd orelse {
// No directory file descriptor, it's a file
if (is_last)
return .{ .result = try this.walker.prepareMatchedPathSymlink(symlink_full_path_z) };
if (pattern.syntax_hint == .Double and
component_idx + 1 == this.walker.patternComponents.items.len -| 1 and
next_pattern.?.syntax_hint != .Double and
this.walker.matchPatternImpl(next_pattern.?, entry_name))
{
return .{ .result = try this.walker.prepareMatchedPathSymlink(symlink_full_path_z) };
}
continue;
};
var add_dir: bool = false;
// TODO this function calls `matchPatternImpl(pattern,
// entry_name)` which is redundant because we already called
// that when we first encountered the symlink
const recursion_idx_bump_ = this.walker.matchPatternDir(&pattern, next_pattern, entry_name, component_idx, is_last, &add_dir);
if (recursion_idx_bump_) |recursion_idx_bump| {
try this.walker.workbuf.append(
this.walker.arena.allocator(),
WorkItem.newWithFd(work_item.path, component_idx + recursion_idx_bump, .directory, dir_fd),
);
}
if (add_dir and !this.walker.only_files) {
return .{ .result = try this.walker.prepareMatchedPathSymlink(symlink_full_path_z) };
}
continue;
},
}
},
.directory => |*dir| {
const entry = switch (dir.iter.next()) {
.err => |err| {
if (!dir.at_cwd) this.closeDisallowingCwd(dir.fd);
dir.iter_closed = true;
return .{ .err = this.walker.handleSysErrWithPath(err, dir.dir_path) };
},
.result => |ent| ent,
} orelse {
if (!dir.at_cwd) this.closeDisallowingCwd(dir.fd);
dir.iter_closed = true;
this.iter_state = .get_next;
continue;
};
const dir_iter_state: *const IterState.Directory = &this.iter_state.directory;
const entry_name = entry.name.slice();
switch (entry.kind) {
.file => {
const matches = this.walker.matchPatternFile(entry_name, dir_iter_state.component_idx, dir.is_last, dir_iter_state.pattern, dir_iter_state.next_pattern);
if (matches) {
const prepared = try this.walker.prepareMatchedPath(entry_name, dir.dir_path);
return .{ .result = prepared };
}
continue;
},
.directory => {
var add_dir: bool = false;
const recursion_idx_bump_ = this.walker.matchPatternDir(dir_iter_state.pattern, dir_iter_state.next_pattern, entry_name, dir_iter_state.component_idx, dir_iter_state.is_last, &add_dir);
if (recursion_idx_bump_) |recursion_idx_bump| {
const subdir_parts: []const []const u8 = &[_][]const u8{
dir.dir_path[0..dir.dir_path.len],
entry_name,
};
const subdir_entry_name = try this.walker.join(subdir_parts);
try this.walker.workbuf.append(
this.walker.arena.allocator(),
WorkItem.new(subdir_entry_name, dir_iter_state.component_idx + recursion_idx_bump, .directory),
);
}
if (add_dir and !this.walker.only_files) {
const prepared_path = try this.walker.prepareMatchedPath(entry_name, dir.dir_path);
return .{ .result = prepared_path };
}
continue;
},
.sym_link => {
if (this.walker.follow_symlinks) {
// Following a symlink requires additional syscalls, so
// we first try it against our "catch-all" pattern match
// function
const matches = this.walker.matchPatternImpl(dir_iter_state.pattern, entry_name);
if (!matches) continue;
const subdir_parts: []const []const u8 = &[_][]const u8{
dir.dir_path[0..dir.dir_path.len],
entry_name,
};
const entry_start: u32 = @intCast(if (dir.dir_path.len == 0) 0 else dir.dir_path.len + 1);
// const subdir_entry_name = try this.arena.allocator().dupe(u8, ResolvePath.join(subdir_parts, .auto));
const subdir_entry_name = try this.walker.join(subdir_parts);
try this.walker.workbuf.append(
this.walker.arena.allocator(),
WorkItem.newSymlink(subdir_entry_name, dir_iter_state.component_idx, entry_start),
);
continue;
}
if (this.walker.only_files) continue;
const matches = this.walker.matchPatternFile(entry_name, dir_iter_state.component_idx, dir_iter_state.is_last, dir_iter_state.pattern, dir_iter_state.next_pattern);
if (matches) {
const prepared_path = try this.walker.prepareMatchedPath(entry_name, dir.dir_path);
return .{ .result = prepared_path };
}
continue;
},
else => continue,
}
},
}
}
}
};
const WorkItem = struct {
path: []const u8,
idx: u32,
kind: Kind,
entry_start: u32 = 0,
fd: ?bun.FileDescriptor = null,
const Kind = enum {
directory,
symlink,
};
fn new(path: []const u8, idx: u32, kind: Kind) WorkItem {
return .{
.path = path,
.idx = idx,
.kind = kind,
};
}
fn newWithFd(path: []const u8, idx: u32, kind: Kind, fd: bun.FileDescriptor) WorkItem {
return .{
.path = path,
.idx = idx,
.kind = kind,
.fd = fd,
};
}
fn newSymlink(path: []const u8, idx: u32, entry_start: u32) WorkItem {
return .{
.path = path,
.idx = idx,
.kind = .symlink,
.entry_start = entry_start,
};
}
};
/// A component is each part of a glob pattern, separated by directory
/// separator:
/// `src/**/*.ts` -> `src`, `**`, `*.ts`
const Component = struct {
start: u32,
len: u32,
syntax_hint: SyntaxHint = .None,
is_ascii: bool = false,
/// Only used when component is not ascii
unicode_set: bool = false,
start_cp: u32 = 0,
end_cp: u32 = 0,
const SyntaxHint = enum {
None,
Single,
Double,
/// Uses special fast-path matching for components like: `*.ts`
WildcardFilepath,
/// Uses special fast-patch matching for literal components e.g.
/// "node_modules", becomes memcmp
Literal,
/// ./fixtures/*.ts
/// ^
Dot,
/// ../
DotBack,
};
};
/// The arena parameter is dereferenced and copied if all allocations go well and nothing goes wrong
pub fn init(
this: *GlobWalker,
arena: *Arena,
pattern: []const u8,
dot: bool,
absolute: bool,
follow_symlinks: bool,
error_on_broken_symlinks: bool,
only_files: bool,
) !Maybe(void) {
errdefer arena.deinit();
var cwd: []const u8 = undefined;
switch (Syscall.getcwd(&this.pathBuf)) {
.err => |err| {
return .{ .err = err };
},
.result => |result| {
const copiedCwd = try arena.allocator().alloc(u8, result.len);
@memcpy(copiedCwd, result);
cwd = copiedCwd;
},
}
return try this.initWithCwd(
arena,
pattern,
cwd,
dot,
absolute,
follow_symlinks,
error_on_broken_symlinks,
only_files,
);
}
pub fn convertUtf8ToCodepoints(codepoints: []u32, pattern: []const u8) void {
_ = bun.simdutf.convert.utf8.to.utf32.le(pattern, codepoints);
}
/// `cwd` should be allocated with the arena
/// The arena parameter is dereferenced and copied if all allocations go well and nothing goes wrong
pub fn initWithCwd(
this: *GlobWalker,
arena: *Arena,
pattern: []const u8,
cwd: []const u8,
dot: bool,
absolute: bool,
follow_symlinks: bool,
error_on_broken_symlinks: bool,
only_files: bool,
) !Maybe(void) {
var patternComponents = ArrayList(Component){};
try GlobWalker.buildPatternComponents(
arena,
&patternComponents,
pattern,
&this.cp_len,
&this.pattern_codepoints,
&this.has_relative_components,
);
this.cwd = cwd;
this.patternComponents = patternComponents;
this.pattern = pattern;
this.arena = arena.*;
this.dot = dot;
this.absolute = absolute;
this.follow_symlinks = follow_symlinks;
this.error_on_broken_symlinks = error_on_broken_symlinks;
this.only_files = only_files;
return Maybe(void).success;
}
/// NOTE This also calls deinit on the arena, if you don't want to do that then
pub fn deinit(this: *GlobWalker, comptime clear_arena: bool) void {
if (comptime clear_arena) {
this.arena.deinit();
}
}
pub fn handleSysErrWithPath(
this: *GlobWalker,
err: Syscall.Error,
path_buf: [:0]const u8,
) Syscall.Error {
std.mem.copyForwards(u8, this.pathBuf[0 .. path_buf.len + 1], @as([]const u8, @ptrCast(path_buf[0 .. path_buf.len + 1])));
return err.withPath(this.pathBuf[0 .. path_buf.len + 1]);
}
pub fn walk(this: *GlobWalker) !Maybe(void) {
if (this.patternComponents.items.len == 0) return Maybe(void).success;
var iter = GlobWalker.Iterator{ .walker = this };
defer iter.deinit();
switch (try iter.init()) {
.err => |err| return .{ .err = err },
else => {},
}
while (switch (try iter.next()) {
.err => |err| return .{ .err = err },
.result => |matched_path| matched_path,
}) |path| {
try this.matchedPaths.append(this.arena.allocator(), BunString.fromBytes(path));
}
return Maybe(void).success;
}
// NOTE you must check that the pattern at `idx` has `syntax_hint == .Dot` or
// `syntax_hint == .DotBack` first
fn collapseDots(
this: *GlobWalker,
idx: u32,
dir_path: *[:0]u8,
path_buf: *[bun.MAX_PATH_BYTES]u8,
encountered_dot_dot: *bool,
) u32 {
var component_idx = idx;
var len = dir_path.len;
while (component_idx < this.patternComponents.items.len) {
switch (this.patternComponents.items[component_idx].syntax_hint) {
.Dot => {
defer component_idx += 1;
if (len + 2 >= bun.MAX_PATH_BYTES) @panic("Invalid path");
if (len == 0) {
path_buf[len] = '.';
path_buf[len + 1] = 0;
len += 1;
} else {
path_buf[len] = '/';
path_buf[len + 1] = '.';
path_buf[len + 2] = 0;
len += 2;
}
},
.DotBack => {
defer component_idx += 1;
encountered_dot_dot.* = true;
if (dir_path.len + 3 >= bun.MAX_PATH_BYTES) @panic("Invalid path");
if (len == 0) {
path_buf[len] = '.';
path_buf[len + 1] = '.';
path_buf[len + 2] = 0;
len += 2;
} else {
path_buf[len] = '/';
path_buf[len + 1] = '.';
path_buf[len + 2] = '.';
path_buf[len + 3] = 0;
len += 3;
}
},
else => break,
}
}
dir_path.len = len;
return component_idx;
}
// NOTE you must check that the pattern at `idx` has `syntax_hint == .Double` first
fn collapseSuccessiveDoubleWildcards(this: *GlobWalker, idx: u32) u32 {
var component_idx = idx;
const pattern = this.patternComponents.items[idx];
_ = pattern;
// Collapse successive double wildcards
while (component_idx + 1 < this.patternComponents.items.len and
this.patternComponents.items[component_idx + 1].syntax_hint == .Double) : (component_idx += 1)
{}
return component_idx;
}
pub fn skipSpecialComponents(
this: *GlobWalker,
work_item_idx: u32,
dir_path: *[:0]u8,
scratch_path_buf: *[bun.MAX_PATH_BYTES]u8,
encountered_dot_dot: *bool,
) u32 {
var component_idx = work_item_idx;
// Skip `.` and `..` while also appending them to `dir_path`
component_idx = switch (this.patternComponents.items[component_idx].syntax_hint) {
.Dot => this.collapseDots(
component_idx,
dir_path,
scratch_path_buf,
encountered_dot_dot,
),
.DotBack => this.collapseDots(
component_idx,
dir_path,
scratch_path_buf,
encountered_dot_dot,
),
else => component_idx,
};
// Skip to the last `**` if there is a chain of them
component_idx = switch (this.patternComponents.items[component_idx].syntax_hint) {
.Double => this.collapseSuccessiveDoubleWildcards(component_idx),
else => component_idx,
};
return component_idx;
}
fn matchPatternDir(
this: *GlobWalker,
pattern: *Component,
next_pattern: ?*Component,
entry_name: []const u8,
component_idx: u32,
is_last: bool,
add: *bool,
) ?u32 {
if (!this.dot and GlobWalker.startsWithDot(entry_name)) return null;
if (is_ignored(entry_name)) return null;
// Handle double wildcard `**`, this could possibly
// propagate the `**` to the directory's children
if (pattern.syntax_hint == .Double) {
// Stop the double wildcard if it matches the pattern afer it
// Example: src/**/*.js
// - Matches: src/bun.js/
// src/bun.js/foo/bar/baz.js
if (!is_last and this.matchPatternImpl(next_pattern.?, entry_name)) {
// But if the next pattern is the last
// component, it should match and propagate the
// double wildcard recursion to the directory's
// children
if (component_idx + 1 == this.patternComponents.items.len - 1) {
add.* = true;
return 0;
}
// In the normal case skip over the next pattern
// since we matched it, example:
// BEFORE: src/**/node_modules/**/*.js
// ^
// AFTER: src/**/node_modules/**/*.js
// ^
return 2;
}
if (is_last) {
add.* = true;
}
return 0;
}
const matches = this.matchPatternImpl(pattern, entry_name);
if (matches) {
if (is_last) {
add.* = true;
return null;
}
return 1;
}
return null;
}
/// A file can only match if:
/// a) it matches against the the last pattern, or
/// b) it matches the next pattern, provided the current
/// pattern is a double wildcard and the next pattern is
/// not a double wildcard
///
/// Examples:
/// a -> `src/foo/index.ts` matches
/// b -> `src/**/*.ts` (on 2nd pattern) matches
fn matchPatternFile(
this: *GlobWalker,
entry_name: []const u8,
component_idx: u32,
is_last: bool,
pattern: *Component,
next_pattern: ?*Component,
) bool {
// Handle case b)
if (!is_last) return pattern.syntax_hint == .Double and
component_idx + 1 == this.patternComponents.items.len -| 1 and
next_pattern.?.syntax_hint != .Double and
this.matchPatternImpl(next_pattern.?, entry_name);
// Handle case a)
return this.matchPatternImpl(pattern, entry_name);
}
fn matchPatternImpl(
this: *GlobWalker,
pattern_component: *Component,
filepath: []const u8,
) bool {
if (!this.dot and GlobWalker.startsWithDot(filepath)) return false;
if (is_ignored(filepath)) return false;
return switch (pattern_component.syntax_hint) {
.Double, .Single => true,
.WildcardFilepath => if (comptime !isWindows)
matchWildcardFilepath(this.pattern[pattern_component.start .. pattern_component.start + pattern_component.len], filepath)
else
this.matchPatternSlow(pattern_component, filepath),
.Literal => if (comptime !isWindows)
matchWildcardLiteral(this.pattern[pattern_component.start .. pattern_component.start + pattern_component.len], filepath)
else
this.matchPatternSlow(pattern_component, filepath),
else => this.matchPatternSlow(pattern_component, filepath),
};
}
fn matchPatternSlow(this: *GlobWalker, pattern_component: *Component, filepath: []const u8) bool {
// windows filepaths are utf-16 so GlobAscii.match will never work
if (comptime !isWindows) {
if (pattern_component.is_ascii and isAllAscii(filepath))
return GlobAscii.match(
this.pattern[pattern_component.start .. pattern_component.start + pattern_component.len],
filepath,
);
}
const codepoints = this.componentStringUnicode(pattern_component);
return matchImpl(
codepoints,
filepath,
);
}
fn componentStringUnicode(this: *GlobWalker, pattern_component: *Component) []const u32 {
if (comptime isWindows) {
return this.componentStringUnicodeWindows(pattern_component);
} else {
return this.componentStringUnicodePosix(pattern_component);
}
}
fn componentStringUnicodeWindows(this: *GlobWalker, pattern_component: *Component) []const u32 {
return this.pattern_codepoints[pattern_component.start_cp..pattern_component.end_cp];
}
fn componentStringUnicodePosix(this: *GlobWalker, pattern_component: *Component) []const u32 {
if (pattern_component.unicode_set) return this.pattern_codepoints[pattern_component.start_cp..pattern_component.end_cp];
const codepoints = this.pattern_codepoints[pattern_component.start_cp..pattern_component.end_cp];
GlobWalker.convertUtf8ToCodepoints(
codepoints,
this.pattern[pattern_component.start .. pattern_component.start + pattern_component.len],
);
pattern_component.unicode_set = true;
return codepoints;
}
fn prepareMatchedPathSymlink(this: *GlobWalker, symlink_full_path: []const u8) ![]const u8 {
const name = try this.arena.allocator().dupe(u8, symlink_full_path);
return name;
}
fn prepareMatchedPath(this: *GlobWalker, entry_name: []const u8, dir_name: [:0]const u8) ![]const u8 {
const subdir_parts: []const []const u8 = &[_][]const u8{
dir_name[0..dir_name.len],
entry_name,
};
const name = try this.join(subdir_parts);
return name;
}
fn appendMatchedPath(
this: *GlobWalker,
entry_name: []const u8,
dir_name: [:0]const u8,
) !void {
const subdir_parts: []const []const u8 = &[_][]const u8{
dir_name[0..dir_name.len],
entry_name,
};
const name = try this.join(subdir_parts);
try this.matchedPaths.append(this.arena.allocator(), BunString.fromBytes(name));
}
fn appendMatchedPathSymlink(this: *GlobWalker, symlink_full_path: []const u8) !void {
const name = try this.arena.allocator().dupe(u8, symlink_full_path);
try this.matchedPaths.append(this.arena.allocator(), BunString.fromBytes(name));
}
inline fn join(this: *GlobWalker, subdir_parts: []const []const u8) ![]u8 {
return if (!this.absolute)
// If relative paths enabled, stdlib join is preferred over
// ResolvePath.joinBuf because it doesn't try to normalize the path
try std.fs.path.join(this.arena.allocator(), subdir_parts)
else
try this.arena.allocator().dupe(u8, ResolvePath.join(subdir_parts, .auto));
}
inline fn startsWithDot(filepath: []const u8) bool {