interactive shell navigation and history
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385const 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);}