# frozen_string_literal: true

# Run with the patched lib/find.rb first on the load path:
#   ruby --disable-gems -I patch/b/lib bench_ticket.rb DIR [RUNS]

require "find"
require "set"

abort "patched find.rb not loaded" unless Find.method(:find).parameters.include?([:key, :lstat])

ERRS = [Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG, Errno::EINVAL].freeze

def tally(path, stat, acc)
  if stat.directory? || (stat.symlink? && File.directory?(path))
    acc[1] += stat.size
  else
    acc[0] += 1 if File.basename(path) != ".DS_Store"
    acc[1] += stat.size if acc[2].add?([stat.dev, stat.ino])
  end
end

# Today: Find.find lstats each entry, then the block lstats it again.
def find_then_lstat(root)
  acc = [0, 0, Set.new]
  Find.find(root) do |path|
    stat = begin
      File.lstat(path)
    rescue *ERRS
      next
    end
    tally(path, stat, acc)
  end
  acc.first(2)
end

# Proposed: Find.find hands over the lstat it already made.
def find_lstat_keyword(root)
  acc = [0, 0, Set.new]
  Find.find(root, lstat: true) do |path, stat|
    tally(path, stat, acc) if stat
  end
  acc.first(2)
end

# Stock alternative: Dir.glob walks the tree; one lstat per result.
def glob_then_lstat(root)
  acc = [0, 0, Set.new]
  Dir.glob("**/*", File::FNM_DOTMATCH, base: root, sort: false) do |rel|
    path = rel == "." ? root : File.join(root, rel)
    stat = begin
      File.lstat(path)
    rescue *ERRS
      next
    end
    tally(path, stat, acc)
  end
  acc.first(2)
end

# What Homebrew/brew#24629 does instead: its own traversal.
def hand_written_walk(root)
  acc = [0, 0, Set.new]
  entries = [root]
  while (entry = entries.pop)
    begin
      stat = File.lstat(entry)
    rescue *ERRS
      next
    end
    tally(entry, stat, acc)
    next unless stat.directory?

    begin
      Dir.children(entry, encoding: entry.encoding).each { |child| entries << File.join(entry, child) }
    rescue *ERRS
      nil
    end
  end
  acc.first(2)
end

root = ARGV.fetch(0)
runs = Integer(ARGV.fetch(1, "21"))
variants = %i[find_then_lstat find_lstat_keyword glob_then_lstat hand_written_walk]

expected = find_then_lstat(root)
entries = Find.find(root).count
puts "#{RUBY_DESCRIPTION}\n#{root}: #{entries} entries"
variants.each { |v| abort "MISMATCH #{v}" unless send(v, root) == expected }

times = variants.to_h { |v| [v, []] }
runs.times do
  variants.shuffle.each do |v|
    GC.start
    t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    send(v, root)
    times[v] << (Process.clock_gettime(Process::CLOCK_MONOTONIC) - t)
  end
end

med = ->(a) { a.sort[a.size / 2] }
base = med.(times[:find_then_lstat])
variants.each do |v|
  puts format("%-20s median %6.0f ms  min %6.0f ms  %5.2fx", v, med.(times[v]) * 1000, times[v].min * 1000,
              base / med.(times[v]))
end
