forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglob.zig
2200 lines (1943 loc) · 92.9 KB
/
glob.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
// 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 bun = @import("root").bun;
const eqlComptime = @import("./string_immutable.zig").eqlComptime;
const expect = std.testing.expect;
const isAllAscii = @import("./string_immutable.zig").isAllASCII;
const math = std.math;
const mem = std.mem;
const isWindows = @import("builtin").os.tag == .windows;
const Allocator = std.mem.Allocator;
const Arena = std.heap.ArenaAllocator;
const ArrayList = std.ArrayListUnmanaged;
const ArrayListManaged = std.ArrayList;
const BunString = bun.String;
const C = @import("./c.zig");
const CodepointIterator = @import("./string_immutable.zig").PackedCodepointIterator;
const Codepoint = CodepointIterator.Cursor.CodePointType;
const Dirent = @import("./bun.js/node/types.zig").Dirent;
const DirIterator = @import("./bun.js/node/dir_iterator.zig");
const EntryKind = @import("./bun.js/node/types.zig").Dirent.Kind;
const GlobAscii = @import("./glob_ascii.zig");
const JSC = bun.JSC;
const Maybe = JSC.Maybe;
const PathLike = @import("./bun.js/node/types.zig").PathLike;
const PathString = @import("./string_types.zig").PathString;
const ResolvePath = @import("./resolver/resolve_path.zig");
const Syscall = bun.sys;
const ZigString = @import("./bun.js/bindings/bindings.zig").ZigString;
// const Codepoint = u32;
const Cursor = CodepointIterator.Cursor;
const log = bun.Output.scoped(.Glob, false);
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, SyscallAccessor, false);
fn dummyFilterTrue(val: []const u8) bool {
_ = val;
return true;
}
fn dummyFilterFalse(val: []const u8) bool {
_ = val;
return false;
}
pub fn statatWindows(fd: bun.FileDescriptor, path: [:0]const u8) Maybe(bun.Stat) {
if (comptime !bun.Environment.isWindows) @compileError("oi don't use this");
var buf: bun.PathBuffer = undefined;
const dir = switch (Syscall.getFdPath(fd, &buf)) {
.err => |e| return .{ .err = e },
.result => |s| s,
};
const parts: []const []const u8 = &.{
dir[0..dir.len],
path,
};
const statpath = ResolvePath.joinZBuf(&buf, parts, .auto);
return Syscall.stat(statpath);
}
pub const SyscallAccessor = struct {
const count_fds = true;
const Handle = struct {
value: bun.FileDescriptor,
const zero = Handle{ .value = bun.FileDescriptor.zero };
pub fn isZero(this: Handle) bool {
return this.value == bun.FileDescriptor.zero;
}
pub fn eql(this: Handle, other: Handle) bool {
return this.value == other.value;
}
};
const DirIter = struct {
value: DirIterator.WrappedIterator,
pub inline fn next(self: *DirIter) Maybe(?DirIterator.IteratorResult) {
return self.value.next();
}
pub inline fn iterate(dir: Handle) DirIter {
return .{ .value = DirIterator.WrappedIterator.init(dir.value.asDir()) };
}
};
pub fn open(path: [:0]const u8) !Maybe(Handle) {
return switch (Syscall.open(path, bun.O.DIRECTORY | bun.O.RDONLY, 0)) {
.err => |err| .{ .err = err },
.result => |fd| .{ .result = Handle{ .value = fd } },
};
}
pub fn statat(handle: Handle, path: [:0]const u8) Maybe(bun.Stat) {
if (comptime bun.Environment.isWindows) return statatWindows(handle.value, path);
return switch (Syscall.fstatat(handle.value, path)) {
.err => |err| .{ .err = err },
.result => |s| .{ .result = s },
};
}
pub fn openat(handle: Handle, path: [:0]const u8) !Maybe(Handle) {
return switch (Syscall.openat(handle.value, path, bun.O.DIRECTORY | bun.O.RDONLY, 0)) {
.err => |err| .{ .err = err },
.result => |fd| .{ .result = Handle{ .value = fd } },
};
}
pub fn close(handle: Handle) ?Syscall.Error {
return Syscall.close(handle.value);
}
pub fn getcwd(path_buf: *bun.PathBuffer) Maybe([]const u8) {
return Syscall.getcwd(path_buf);
}
};
pub const DirEntryAccessor = struct {
const FS = bun.fs.FileSystem;
const count_fds = false;
const Handle = struct {
value: ?*FS.DirEntry,
const zero = Handle{ .value = null };
pub fn isZero(this: Handle) bool {
return this.value == null;
}
pub fn eql(this: Handle, other: Handle) bool {
// TODO this might not be quite right, we're comparing pointers, not the underlying directory
// On the other hand, DirEntries are only ever created once (per generation), so this should be fine?
// Realistically, as closing the handle is a no-op, this should be fine either way.
return this.value == other.value;
}
};
const DirIter = struct {
value: ?FS.DirEntry.EntryMap.Iterator,
const IterResult = struct {
name: NameWrapper,
kind: std.fs.File.Kind,
const NameWrapper = struct {
value: []const u8,
pub fn slice(this: NameWrapper) []const u8 {
return this.value;
}
};
};
pub inline fn next(self: *DirIter) Maybe(?IterResult) {
if (self.value) |*value| {
const nextval = value.next() orelse return .{ .result = null };
const name = nextval.key_ptr.*;
const kind = nextval.value_ptr.*.kind(&FS.instance.fs, true);
const fskind = switch (kind) {
.file => std.fs.File.Kind.file,
.dir => std.fs.File.Kind.directory,
};
return .{
.result = .{
.name = IterResult.NameWrapper{ .value = name },
.kind = fskind,
},
};
} else {
return .{ .result = null };
}
}
pub inline fn iterate(dir: Handle) DirIter {
const entry = dir.value orelse return DirIter{ .value = null };
return .{ .value = entry.data.iterator() };
}
};
pub fn statat(handle: Handle, path_: [:0]const u8) Maybe(bun.Stat) {
var path: [:0]const u8 = path_;
var buf: bun.PathBuffer = undefined;
if (!bun.path.Platform.auto.isAbsolute(path)) {
if (handle.value) |entry| {
const slice = bun.path.joinStringBuf(&buf, [_][]const u8{ entry.dir, path }, .auto);
buf[slice.len] = 0;
path = buf[0..slice.len :0];
}
}
return Syscall.stat(path);
}
pub fn open(path: [:0]const u8) !Maybe(Handle) {
return openat(Handle.zero, path);
}
pub fn openat(handle: Handle, path_: [:0]const u8) !Maybe(Handle) {
var path: []const u8 = path_;
var buf: bun.PathBuffer = undefined;
if (!bun.path.Platform.auto.isAbsolute(path)) {
if (handle.value) |entry| {
path = bun.path.joinStringBuf(&buf, [_][]const u8{ entry.dir, path }, .auto);
}
}
// TODO do we want to propagate ENOTDIR through the 'Maybe' to match the SyscallAccessor?
// The glob implementation specifically checks for this error when dealing with symlinks
// return .{ .err = Syscall.Error.fromCode(bun.C.E.NOTDIR, Syscall.Tag.open) };
const res = FS.instance.fs.readDirectory(path, null, 0, false) catch |err| {
return err;
};
switch (res.*) {
.entries => |entry| {
return .{ .result = Handle{ .value = entry } };
},
.err => |err| {
return err.original_err;
},
}
}
pub inline fn close(handle: Handle) ?Syscall.Error {
// TODO is this a noop?
_ = handle;
return null;
}
pub fn getcwd(path_buf: *bun.PathBuffer) Maybe([]const u8) {
@memcpy(path_buf, bun.fs.FileSystem.instance.fs.cwd);
}
};
pub fn GlobWalker_(
comptime ignore_filter_fn: ?*const fn ([]const u8) bool,
comptime Accessor: type,
comptime sentinel: bool,
) type {
const is_ignored: *const fn ([]const u8) bool = if (comptime ignore_filter_fn) |func| func else dummyFilterFalse;
const count_fds = Accessor.count_fds and bun.Environment.isDebug;
const stdJoin = comptime if (!sentinel) std.fs.path.join else std.fs.path.joinZ;
const bunJoin = comptime if (!sentinel) ResolvePath.join else ResolvePath.joinZ;
const MatchedPath = comptime if (!sentinel) []const u8 else [:0]const u8;
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,
end_byte_of_basename_excluding_special_syntax: u32 = 0,
basename_excluding_special_syntax_component_idx: u32 = 0,
patternComponents: ArrayList(Component) = .{},
matchedPaths: MatchedMap = .{},
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.PathBuffer = undefined,
// iteration state
workbuf: ArrayList(WorkItem) = ArrayList(WorkItem){},
/// Array hashmap used as a set (values are the keys)
/// to store matched paths and prevent duplicates
///
/// BunString is used so that we can call BunString.toJSArray()
/// on the result of `.keys()` to give the result back to JS
///
/// The only type of string impl we use is ZigString since
/// all matched paths are UTF-8 (DirIterator converts them on
/// windows) and allocated on the arnea
///
/// Multiple patterns are not supported so right now this is
/// only possible when running a pattern like:
///
/// `foo/**/*`
///
/// Use `.keys()` to get the matched paths
const MatchedMap = std.ArrayHashMapUnmanaged(BunString, void, struct {
pub fn hash(_: @This(), this: BunString) u32 {
bun.assert(this.tag == .ZigString);
const slice = this.byteSlice();
if (comptime sentinel) {
const slicez = slice[0 .. slice.len - 1 :0];
return std.array_hash_map.hashString(slicez);
}
return std.array_hash_map.hashString(slice);
}
pub fn eql(_: @This(), this: BunString, other: BunString, _: usize) bool {
return this.eql(other);
}
}, true);
/// 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,
/// Two particular cases where this is used:
///
/// 1. A pattern with no special glob syntax was supplied, for example: `/Users/zackradisic/foo/bar`
///
/// In that case, the mere existence of the file/dir counts as a match, so we can eschew directory
/// iterating and walking for a simple stat call to the path.
///
/// 2. Pattern ending in literal optimization
///
/// With a pattern like: `packages/**/package.json`, once the iteration component index reaches
/// the final component, which is a literal string ("package.json"), we can similarly make a
/// single stat call to complete the pattern.
matched: MatchedPath,
const Directory = struct {
fd: Accessor.Handle,
iter: Accessor.DirIter,
path: bun.PathBuffer,
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: Accessor.Handle = Accessor.Handle.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 (count_fds) usize else u0 = 0,
pub fn init(this: *Iterator) !Maybe(void) {
log("Iterator init pattern={s}", .{this.walker.pattern});
var was_absolute = false;
const root_work_item = brk: {
var use_posix = bun.Environment.isPosix;
const is_absolute = if (bun.Environment.isPosix) std.fs.path.isAbsolute(this.walker.pattern) else std.fs.path.isAbsolute(this.walker.pattern) or is_absolute: {
use_posix = true;
break :is_absolute std.fs.path.isAbsolutePosix(this.walker.pattern);
};
if (!is_absolute) break :brk WorkItem.new(this.walker.cwd, 0, .directory);
was_absolute = true;
var path_without_special_syntax = this.walker.pattern[0..this.walker.end_byte_of_basename_excluding_special_syntax];
var starting_component_idx = this.walker.basename_excluding_special_syntax_component_idx;
if (path_without_special_syntax.len == 0) {
path_without_special_syntax = if (!bun.Environment.isWindows) "/" else ResolvePath.windowsFilesystemRoot(this.walker.cwd);
} else {
// Skip the components associated with the literal path
starting_component_idx += 1;
// This means we got a pattern without any special glob syntax, for example:
// `/Users/zackradisic/foo/bar`
//
// In that case we don't need to do any walking and can just open up the FS entry
if (starting_component_idx >= this.walker.patternComponents.items.len) {
const path = try this.walker.arena.allocator().dupeZ(u8, path_without_special_syntax);
const fd = switch (try Accessor.open(path)) {
.err => |e| {
if (e.getErrno() == bun.C.E.NOTDIR) {
this.iter_state = .{ .matched = path };
return Maybe(void).success;
}
// Doesn't exist
if (e.getErrno() == bun.C.E.NOENT) {
this.iter_state = .get_next;
return Maybe(void).success;
}
const errpath = try this.walker.arena.allocator().dupeZ(u8, path);
return .{ .err = e.withPath(errpath) };
},
.result => |fd| fd,
};
_ = Accessor.close(fd);
this.iter_state = .{ .matched = path };
return Maybe(void).success;
}
// In the above branch, if `starting_compoennt_dix >= pattern_components.len` then
// it should also mean that `end_byte_of_basename_excluding_special_syntax >= pattern.len`
//
// So if we see that `end_byte_of_basename_excluding_special_syntax < this.walker.pattern.len` we
// miscalculated the values
bun.assert(this.walker.end_byte_of_basename_excluding_special_syntax < this.walker.pattern.len);
}
break :brk WorkItem.new(
path_without_special_syntax,
starting_component_idx,
.directory,
);
};
var path_buf: *bun.PathBuffer = &this.walker.pathBuf;
const root_path = root_work_item.path;
@memcpy(path_buf[0..root_path.len], root_path[0..root_path.len]);
path_buf[root_path.len] = 0;
const cwd_fd = switch (try Accessor.open(path_buf[0..root_path.len :0])) {
.err => |err| return .{ .err = this.walker.handleSysErrWithPath(err, @ptrCast(path_buf[0 .. root_path.len + 1])) },
.result => |fd| fd,
};
if (comptime count_fds) {
this.fds_open += 1;
}
this.cwd_fd = cwd_fd;
switch (if (was_absolute) try this.transitionToDirIterState(
root_work_item,
false,
) else try this.transitionToDirIterState(
root_work_item,
true,
)) {
.err => |err| return .{ .err = err },
else => {},
}
return Maybe(void).success;
}
pub fn deinit(this: *Iterator) void {
defer {
bun.debugAssert(this.fds_open == 0);
}
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 (comptime count_fds) {
bun.debugAssert(this.fds_open == 0);
}
}
pub fn closeCwdFd(this: *Iterator) void {
if (this.cwd_fd.isZero()) return;
_ = Accessor.close(this.cwd_fd);
if (comptime count_fds) this.fds_open -= 1;
}
pub fn closeDisallowingCwd(this: *Iterator, fd: Accessor.Handle) void {
if (fd.isZero() or fd.eql(this.cwd_fd)) return;
_ = Accessor.close(fd);
if (comptime count_fds) this.fds_open -= 1;
}
pub fn bumpOpenFds(this: *Iterator) void {
if (comptime count_fds) {
this.fds_open += 1;
// If this is over 2 then this means that there is a bug in the iterator code
bun.debugAssert(this.fds_open <= 2);
}
}
fn transitionToDirIterState(
this: *Iterator,
work_item: WorkItem,
comptime root: bool,
) !Maybe(void) {
log("transition => {s}", .{work_item.path});
this.iter_state = .{ .directory = .{
.fd = Accessor.Handle.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);
const fd: Accessor.Handle = fd: {
if (work_item.fd) |fd| break :fd fd;
if (comptime root) {
if (had_dot_dot) break :fd switch (try Accessor.openat(this.cwd_fd, dir_path)) {
.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 (try Accessor.openat(this.cwd_fd, dir_path)) {
.err => |err| return .{
.err = this.walker.handleSysErrWithPath(err, dir_path),
},
.result => |fd_| brk: {
this.bumpOpenFds();
break :brk fd_;
},
};
};
// Optimization:
// If we have a pattern like:
// `packages/*/package.json`
// ^ and we are at this component, with let's say
// a directory named: `packages/frontend/`
//
// Then we can just open `packages/frontend/package.json` without
// doing any iteration on the current directory.
//
// More generally, we can apply this optimization if we are on the
// last component and it is a literal with no special syntax.
if (component_idx == this.walker.patternComponents.items.len -| 1 and
this.walker.patternComponents.items[component_idx].syntax_hint == .Literal)
{
defer {
this.closeDisallowingCwd(fd);
}
const stackbuf_size = 256;
var stfb = std.heap.stackFallback(stackbuf_size, this.walker.arena.allocator());
const pathz = try stfb.get().dupeZ(u8, this.walker.patternComponents.items[component_idx].patternSlice(this.walker.pattern));
const stat_result: bun.Stat = switch (Accessor.statat(fd, pathz)) {
.err => |e_| {
var e: bun.sys.Error = e_;
if (e.getErrno() == bun.C.E.NOENT) {
this.iter_state = .get_next;
return Maybe(void).success;
}
return .{ .err = e.withPath(this.walker.patternComponents.items[component_idx].patternSlice(this.walker.pattern)) };
},
.result => |stat| stat,
};
const matches = (bun.S.ISDIR(@intCast(stat_result.mode)) and !this.walker.only_files) or bun.S.ISREG(@intCast(stat_result.mode)) or !this.walker.only_files;
if (matches) {
if (try this.walker.prepareMatchedPath(pathz, dir_path)) |path| {
this.iter_state = .{ .matched = path };
} else {
this.iter_state = .get_next;
}
} else {
this.iter_state = .get_next;
}
return Maybe(void).success;
}
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;
this.iter_state.directory.fd = Accessor.Handle.zero;
log("Transition(dirpath={s}, fd={}, component_idx={d})", .{ dir_path, fd, component_idx });
this.iter_state.directory.fd = fd;
const iterator = Accessor.DirIter.iterate(fd);
this.iter_state.directory.iter = iterator;
this.iter_state.directory.iter_closed = false;
return Maybe(void).success;
}
pub fn next(this: *Iterator) !Maybe(?MatchedPath) {
while (true) {
switch (this.iter_state) {
.matched => |path| {
this.iter_state = .get_next;
return .{ .result = path };
},
.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.PathBuffer = &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: ?Accessor.Handle = switch (try Accessor.openat(this.cwd_fd, symlink_full_path_z)) {
.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) orelse continue };
}
}
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) orelse continue };
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) orelse continue };
}
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| {
if (recursion_idx_bump == 2) {
try this.walker.workbuf.append(
this.walker.arena.allocator(),
WorkItem.newWithFd(work_item.path, component_idx + recursion_idx_bump, .directory, dir_fd),
);
try this.walker.workbuf.append(
this.walker.arena.allocator(),
WorkItem.newWithFd(work_item.path, component_idx, .directory, dir_fd),
);
} else {
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) orelse continue };
}
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;
};
log("dir: {s} entry: {s}", .{ dir.dir_path, entry.name.slice() });
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) orelse continue;
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);
if (recursion_idx_bump == 2) {
try this.walker.workbuf.append(
this.walker.arena.allocator(),
WorkItem.new(subdir_entry_name, dir_iter_state.component_idx + recursion_idx_bump, .directory),
);
try this.walker.workbuf.append(
this.walker.arena.allocator(),
WorkItem.new(subdir_entry_name, dir_iter_state.component_idx, .directory),
);
} else {
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) orelse continue;
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) orelse continue;
return .{ .result = prepared_path };
}
continue;
},
else => continue,
}
},
}
}
}
};
const WorkItem = struct {
path: []const u8,
idx: u32,
kind: Kind,
entry_start: u32 = 0,
fd: ?Accessor.Handle = 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: Accessor.Handle) 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,
trailing_sep: bool = false,
is_ascii: bool = false,
/// Only used when component is not ascii
unicode_set: bool = false,
start_cp: u32 = 0,
end_cp: u32 = 0,
pub fn patternSlice(this: *const Component, pattern: []const u8) []const u8 {
return pattern[this.start .. this.start + this.len - @as(u1, @bitCast(this.trailing_sep))];
}
pub fn patternSliceCp(this: *const Component, pattern: []u32) []u32 {
return pattern[this.start_cp .. this.end_cp - @as(u1, @bitCast(this.trailing_sep))];
}
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.