From f4aef8215e7a441ecd4a1d2b90d29bcca2335424 Mon Sep 17 00:00:00 2001 From: Daniel Berger <78529+djberg96@users.noreply.github.com> Date: Sun, 4 Jan 2026 21:27:13 -0500 Subject: [PATCH] Short circuit if we're already at maxdepth. --- lib/file/find.rb | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/lib/file/find.rb b/lib/file/find.rb index 97d120c..ffb478d 100644 --- a/lib/file/find.rb +++ b/lib/file/find.rb @@ -249,33 +249,30 @@ def find next if @mount && stat_info.dev != @filesystem next if @links && stat_info.nlink != @links + # Calculate depth early if needed for maxdepth/mindepth checks if @maxdepth || @mindepth file_depth = file.split(File::SEPARATOR).reject(&:empty?).length current_base_path = [@path].flatten.find{ |tpath| file.include?(tpath) } path_depth = current_base_path.split(File::SEPARATOR).length - depth = file_depth - path_depth + end - if @maxdepth && depth > @maxdepth - if stat_info.directory? && !paths.include?(file) - queue << file - end - next + # Early termination: don't even add directories to queue if beyond maxdepth + if stat_info.directory? && !paths.include?(file) + if @maxdepth && depth && depth >= @maxdepth + # At maxdepth, don't traverse into this directory + else + queue << file end + end - if @mindepth && depth < @mindepth - if stat_info.directory? && !paths.include?(file) - queue << file - end - next - end + # Skip files that are beyond maxdepth or before mindepth + if @maxdepth && depth && depth > @maxdepth + next end - # Add directories back onto the list of paths to search unless - # they've already been added - # - if stat_info.directory? && !paths.include?(file) - queue << file + if @mindepth && depth && depth < @mindepth + next end next unless File.fnmatch?(@name, File.basename(file))