const std = @import("std"); const assert = std.debug.assert; const input_output = @import("input_output.zig"); pub const max_supported_depth: usize = 128; comptime { assert(max_supported_depth > 0); } pub const Entry = struct { path: []const u8, mtime_ns: i128, }; pub fn shouldSkip(path: []const u8, ignored_patterns: []const []const u8) bool { assert(path.len > 0); var components = std.mem.splitScalar(u8, path, std.fs.path.sep); while (components.next()) |component| { for (ignored_patterns) |pattern| { if (std.mem.eql(u8, component, pattern)) { return true; } } } return false; } pub fn openWalkRoot() !std.Io.Dir { return openWalkDir(input_output.runtime(), std.Io.Dir.cwd()); } /// Opens directory again with the access that TreeWalker needs. pub fn openWalkDir(input_output_handle: std.Io, directory: std.Io.Dir) !std.Io.Dir { return directory.openDir(input_output_handle, ".", .{ .access_sub_paths = true, .iterate = true, .follow_symlinks = true, }); } pub fn freeEntries(allocator: std.mem.Allocator, entries: *std.ArrayListUnmanaged(Entry)) void { for (entries.items) |entry| { allocator.free(entry.path); } entries.deinit(allocator); } pub const WalkItem = struct { path: []const u8, kind: std.Io.File.Kind, /// Kind reported by stat. For a symlink this is the target's kind. stat_kind: std.Io.File.Kind, mtime_ns: i128, /// Size reported by the stat call. Both 64-bit and wasi sizes fit. size_bytes: u64 = 0, }; pub const TreeWalker = struct { input_output_handle: std.Io, allocator: std.mem.Allocator, ignored_patterns: []const []const u8, max_depth: usize, /// When true, recoverable walk failures are skipped silently. The /// grep picker walks while its terminal UI is on screen, so an error /// printed mid-walk would garble the drawing. Callers that walk before /// showing any UI pass false and keep the warnings. quiet: bool, stack: std.ArrayListUnmanaged(Frame) = .empty, const Frame = struct { directory: std.Io.Dir, prefix: ?[]const u8, depth: usize, iterator: std.Io.Dir.Iterator, }; pub fn init( input_output_handle: std.Io, allocator: std.mem.Allocator, root: std.Io.Dir, ignored_patterns: []const []const u8, max_depth: usize, quiet: bool, ) !TreeWalker { assert(max_depth <= max_supported_depth); var self = TreeWalker{ .input_output_handle = input_output_handle, .allocator = allocator, .ignored_patterns = ignored_patterns, .max_depth = max_depth, .quiet = quiet, }; errdefer self.deinit(); errdefer root.close(input_output_handle); try self.stack.append(allocator, .{ .directory = root, .prefix = null, .depth = 0, .iterator = root.iterate(), }); assert(self.stack.items.len == 1); assert(self.stack.capacity >= 1); return self; } pub fn deinit(self: *TreeWalker) void { while (self.stack.items.len > 0) { self.popFrame(); } assert(self.stack.items.len == 0); self.stack.deinit(self.allocator); } fn popFrame(self: *TreeWalker) void { const frame = self.stack.pop() orelse unreachable; frame.directory.close(self.input_output_handle); if (frame.prefix) |prefix| { self.allocator.free(prefix); } } pub fn next(self: *TreeWalker) !?WalkItem { while (self.stack.items.len > 0) { assert(self.stack.items.len <= self.max_depth + 1); const top_index = self.stack.items.len - 1; const maybe_entry = try self.stack.items[top_index].iterator.next( self.input_output_handle, ); if (maybe_entry == null) { self.popFrame(); continue; } const entry = maybe_entry.?; assert(entry.name.len > 0); if (try self.descendOrEmit(top_index, entry)) |item| { return item; } } return null; } fn descendOrEmit(self: *TreeWalker, top_index: usize, entry: std.Io.Dir.Entry) !?WalkItem { assert(top_index < self.stack.items.len); assert(entry.name.len > 0); const parent = &self.stack.items[top_index]; const entry_path = if (parent.prefix) |prefix| try std.fs.path.join(self.allocator, &.{ prefix, entry.name }) else try self.allocator.dupe(u8, entry.name); errdefer self.allocator.free(entry_path); if (shouldSkip(entry_path, self.ignored_patterns)) { self.allocator.free(entry_path); return null; } const stat = parent.directory.statFile( self.input_output_handle, entry.name, .{ .follow_symlinks = true }, ) catch |err| { self.allocator.free(entry_path); if (err == error.FileNotFound) { return null; } if (err == error.AccessDenied) { return null; } if (!self.quiet) { input_output.warn("failed to stat {s}: {}\n", .{ entry.name, err }); } return null; }; if (entry.kind == .directory) { if (parent.depth + 1 < self.max_depth) { self.pushFrame(top_index, entry.name, entry_path) catch |err| { if (!self.quiet) { input_output.warn( "failed to open directory {s}: {}\n", .{ entry.name, err }, ); } }; } } assert(self.stack.items.len <= self.max_depth + 1); return .{ .path = entry_path, .kind = entry.kind, .stat_kind = stat.kind, .mtime_ns = stat.mtime.nanoseconds, .size_bytes = stat.size, }; } fn pushFrame( self: *TreeWalker, parent_index: usize, name: []const u8, prefix_source: []const u8, ) !void { assert(parent_index < self.stack.items.len); assert(name.len > 0); const parent = &self.stack.items[parent_index]; assert(parent.depth + 1 < self.max_depth); var sub_dir = try parent.directory.openDir(self.input_output_handle, name, .{ .access_sub_paths = true, .iterate = true, .follow_symlinks = true, }); errdefer sub_dir.close(self.input_output_handle); const owned_prefix = try self.allocator.dupe(u8, prefix_source); errdefer self.allocator.free(owned_prefix); try self.stack.append(self.allocator, .{ .directory = sub_dir, .prefix = owned_prefix, .depth = parent.depth + 1, .iterator = sub_dir.iterate(), }); assert(self.stack.items.len <= self.max_depth + 1); } }; pub fn collectWalkEntries( input_output_handle: std.Io, allocator: std.mem.Allocator, root: std.Io.Dir, kind: std.Io.File.Kind, ignored_patterns: []const []const u8, max_depth: usize, entries: *std.ArrayListUnmanaged(Entry), ) !void { assert(max_depth <= max_supported_depth); assert(entries.items.len == 0); var walker = try TreeWalker.init( input_output_handle, allocator, root, ignored_patterns, max_depth, false, ); defer walker.deinit(); while (try walker.next()) |item| { defer allocator.free(item.path); assert(item.path.len > 0); // A symlink counts when its target has the wanted kind. const effective_kind = if (item.kind == .sym_link) item.stat_kind else item.kind; if (effective_kind == kind) { try appendWalkEntry(allocator, entries, item); } } } fn appendWalkEntry( allocator: std.mem.Allocator, entries: *std.ArrayListUnmanaged(Entry), item: WalkItem, ) !void { assert(item.path.len > 0); const owned_path = try allocator.dupe(u8, item.path); try entries.append(allocator, .{ .path = owned_path, .mtime_ns = item.mtime_ns, }); } const testing = std.testing; test "shouldSkip: matches an exact path component" { const ignored = [_][]const u8{ "node_modules", ".git" }; try testing.expect(shouldSkip("src/node_modules/pkg/x.js", &ignored)); try testing.expect(shouldSkip(".git/config", &ignored)); try testing.expect(shouldSkip("a/b/.git", &ignored)); } test "shouldSkip: partial component is not a match" { const ignored = [_][]const u8{"node_modules"}; try testing.expect(!shouldSkip("src/lib/main.zig", &ignored)); try testing.expect(!shouldSkip("src/node_modules_old/x", &ignored)); } test "shouldSkip: empty pattern set never skips" { try testing.expect(!shouldSkip("a/b/c", &.{})); } test "TreeWalker: collects nested entries without recursion" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; try temp_directory.dir.createDir(test_input_output, "sub", .fromMode(0o755)); try temp_directory.dir.createDir(test_input_output, "sub/deep", .fromMode(0o755)); try input_output.writeFile(test_input_output, temp_directory.dir, "top.txt", "top", 0o644); try input_output.writeFile(test_input_output, temp_directory.dir, "sub/mid.txt", "mid", 0o644); try input_output.writeFile( test_input_output, temp_directory.dir, "sub/deep/bottom.txt", "bottom", 0o644, ); const root = try openWalkDir(test_input_output, temp_directory.dir); var entries = std.ArrayListUnmanaged(Entry).empty; defer freeEntries(testing.allocator, &entries); try collectWalkEntries(test_input_output, testing.allocator, root, .file, &.{}, 10, &entries); try testing.expectEqual(@as(usize, 3), entries.items.len); var found_top = false; var found_mid = false; var found_bottom = false; for (entries.items) |entry| { if (std.mem.eql(u8, entry.path, "top.txt")) found_top = true; if (std.mem.eql(u8, entry.path, "sub/mid.txt")) found_mid = true; if (std.mem.eql(u8, entry.path, "sub/deep/bottom.txt")) found_bottom = true; } try testing.expect(found_top); try testing.expect(found_mid); try testing.expect(found_bottom); } test "TreeWalker: ignored components are pruned, not descended" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; try temp_directory.dir.createDir(test_input_output, "node_modules", .fromMode(0o755)); try input_output.writeFile(test_input_output, temp_directory.dir, "keep.txt", "keep", 0o644); try input_output.writeFile( test_input_output, temp_directory.dir, "node_modules/hidden.txt", "hidden", 0o644, ); const ignored = [_][]const u8{"node_modules"}; const root = try openWalkDir(test_input_output, temp_directory.dir); var entries = std.ArrayListUnmanaged(Entry).empty; defer freeEntries(testing.allocator, &entries); try collectWalkEntries( test_input_output, testing.allocator, root, .file, &ignored, 10, &entries, ); try testing.expectEqual(@as(usize, 1), entries.items.len); try testing.expectEqualStrings("keep.txt", entries.items[0].path); } test "TreeWalker: max depth bounds descent" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; try temp_directory.dir.createDir(test_input_output, "sub", .fromMode(0o755)); try input_output.writeFile(test_input_output, temp_directory.dir, "top.txt", "top", 0o644); try input_output.writeFile(test_input_output, temp_directory.dir, "sub/mid.txt", "mid", 0o644); const root = try openWalkDir(test_input_output, temp_directory.dir); var entries = std.ArrayListUnmanaged(Entry).empty; defer freeEntries(testing.allocator, &entries); try collectWalkEntries(test_input_output, testing.allocator, root, .file, &.{}, 1, &entries); try testing.expectEqual(@as(usize, 1), entries.items.len); try testing.expectEqualStrings("top.txt", entries.items[0].path); } test "TreeWalker: empty directories yield no entries" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; const root = try openWalkDir(test_input_output, temp_directory.dir); var entries = std.ArrayListUnmanaged(Entry).empty; defer entries.deinit(testing.allocator); try collectWalkEntries(test_input_output, testing.allocator, root, .file, &.{}, 10, &entries); try testing.expectEqual(@as(usize, 0), entries.items.len); }