Cn-Util

 view release on metacpan or  search on metacpan

lib/Cn/Util.pm  view on Meta::CPAN

	# goto then called the stub itself, forever.
	return if $DDP_LOADED{$pkg};
	require DDP;
	no strict 'refs';
	# DDP->import() exports both p() and np(), but a stub was installed only
	# for a name the caller had no sub under, so the other -- or one the caller
	# defined over a stub after its `use` line -- is the caller's own.  Its
	# glob is localised for the import, so DDP writes into a temporary that is
	# discarded, and the caller's sub comes back untouched.
	my %own = map {
		my $glob = "${pkg}::$_";
		$_ => (defined &{$glob} && \&{$glob} != ($DDP_STUB{$pkg}{$_} // 0));
	} 'p', 'np';
	local *{"${pkg}::p"}  if $own{p};
	local *{"${pkg}::np"} if $own{np};
	local $SIG{__WARN__} = sub {
		warn @_ unless $_[0] =~ m{\ASubroutine \Q$pkg\E::n?p redefined};
	};
	# show_memsize needs Devel::Size, which is not a prerequisite; asked for
	# without it, DDP warned "Devel::Size not found" on every first p() or np().
	my $memsize = eval { require Devel::Size; 1 } ? 1 : 0;
	my $ok = eval qq{package $pkg;\nDDP->import({output => 'STDOUT', array_max => 10, show_memsize => $memsize, show_dualvar => 'off'}); 1};
	die "Cn::Util: could not load DDP into $pkg: $@" unless $ok;
	$DDP_LOADED{$pkg} = 1;
	return;
}

sub dir {
	my %args = (
	  tests     => 'f',
	  dir       => '.',
	  regex     => '.',
	  recursive => 0,
	  on_match  => undef,   # optional callback: streams results, keeps RAM flat
	  cpu       => 1,       # worker processes for a recursive walk; 1 = no forking
	  @_,
	);

	my %allowed = map { $_ => 1 } qw(tests dir regex recursive on_match cpu);
	if (my @bad = grep { !$allowed{$_} } keys %args) {
	  die "Unrecognized arguments: @bad\nAccepted args: "
		 . join(', ', sort keys %allowed);
	}
	# Added 's' (non-zero size), removed 't' (tty test - meaningless on a path)
	# Checked here so that an undef gets this message rather than "Use of
	# uninitialized value" from the first line that reads it.  recursive is
	# left out: undef is as false there as 0.
	for my $name (qw(tests dir regex cpu)) {
		die "$name must be defined" unless defined $args{$name};
	}
	die "on_match must be a code reference"
		if defined $args{on_match} && ref $args{on_match} ne 'CODE';
	die "Unrecognized characters in tests: $args{tests}"
	  if $args{tests} =~ /[^rwxoRWXOezsfdlpSbcugkTB]/;
	die "cpu must be a positive integer, got '$args{cpu}'"
	  unless $args{cpu} =~ /\A[1-9][0-9]*\z/;
	my $re = eval { qr/$args{regex}/ }
	  or die "Invalid regex '$args{regex}': $@";
# Compile the tests once. The first test stats the path; every later test
# reuses the stat buffer via the special '_' filehandle, so N tests cost
# one stat(2) syscall instead of N (~2.4x faster for 4 tests).
# -l needs lstat, so it is hoisted to the front, and the test after it
# must re-stat the real path (otherwise '_' holds lstat data, or -l _
# would be a fatal error).
	my @t = split //, $args{tests};
	@t = ((grep { $_ eq 'l' } @t), (grep { $_ ne 'l' } @t));
	my @parts;
	my $fresh = 1;   # 1 = the next test must stat the path itself rather than reuse '_'
	for my $t (@t) {
	  if    ($t eq 'l') { push @parts, '-l $_[0]';   $fresh = 1 }
	  elsif ($fresh)    { push @parts, "-$t \$_[0]"; $fresh = 0 }
	  else              { push @parts, "-$t _" }
	}
	my $tester = @parts
	  ? (eval 'sub { ' . join(' && ', @parts) . ' }'
		   or die "Failed to compile tests: $@")
	  : sub { 1 };   # empty tests string now means "no filtering", not "nothing matches"

	my $target_dir = $args{dir};
	# On Windows every "\" in dir becomes "/", so that every path dir() returns
	# there uses "/" alone.  This began as matching File::Find, which did the
	# same to its starting path (the "canonicalize directory separators" step
	# of _find_opt in 1.44, on the Strawberry Perl 5.42 smoker) while the
	# recursive walk used it, and mixed separators made that walk report its
	# own root.  Only on MSWin32: elsewhere "\" is an ordinary character in a
	# file name.
	my $is_win32 = $^O eq 'MSWin32';
	$target_dir =~ tr{\\}{/} if $is_win32;
	# Strip trailing slashes, but keep a root intact: "/", and on Windows "C:/",
	# because "C:" alone is the current directory on drive C, not its root.
	# Collapsing first is what turns "///" into "/"; it used to be left as it
	# was, to be joined as "////etc".
	$target_dir =~ s{/+\z}{/}s;
	$target_dir =~ s{/\z}{}s
		unless $target_dir =~ ($is_win32 ? qr{\A(?:[A-Za-z]:)?/\z}s : qr{\A/\z}s);
	# "." is left off the front of results; a root, the only $d that still
	# ends in "/", must not become "//etc" or "C://etc".
	my $join = sub {
		my ($d, $item) = @_;
		$d eq '.' ? $item : $d =~ m{/\z} ? "$d$item" : "$d/$item"
	};

	my $cb = $args{on_match};
	my @items;
	my $emit = $cb // sub { push @items, $_[0] };

	if ($args{recursive}) {
		# Walk everything strictly below $start, depth first, handing each
		# match to $sink.  _dir_level returns a directory's subdirectories
		# without the symlinks among them, so the walk does not follow links;
		# but opendir follows $start itself, so a dir that is a symlink to a
		# directory is listed through the link.
		#
		# File::Find did this walk up to 0.024.  Over ~/perl5 (279,000
		# entries, warm cache, 2026-11-09) it took 1.06 s of user CPU to this
		# loop's 0.43 s, for the same system time: the two make the same stat
		# and lstat calls.  It also lstat()ed its starting path, so a symlinked
		# dir needed listing by hand before it, and on Windows it rewrote the
		# separators of that path, which the "\" conversion above is for.
		my $find = sub {
			my ($start, $sink) = @_;
			my @todo = ($start);
			push @todo, _dir_level(pop @todo, $re, $tester, $join, $sink) while @todo;
			return;
		};
		if ($args{cpu} == 1) {
			$find->($target_dir, $emit);
		} else {
			_dir_parallel($target_dir, $args{cpu}, $re, $tester, $join, $find, $emit);
		}
	} else {
		# cpu is ignored here on purpose: one readdir plus one stat per entry
		# is ~6 us warm, far below the cost of forking and shipping results back.
		opendir my $dh, $target_dir
			or die "Cannot open directory $target_dir: $!";
		while (defined(my $item = readdir $dh)) {   # defined(): a file named "0" is falsy
			next if $item =~ /\A\.\.?\z/;           # \A..\z: "$" would match before a trailing \n
			next if $item !~ $re;
			my $path = $join->($target_dir, $item);
			$emit->($path) if $tester->($path);
		}
		closedir $dh;
	}
	return $cb ? () : @items;
}

# Jobs handed out per worker.  Parallel::ForkManager starts a new job whenever
# a worker finishes, so more jobs than workers is what evens out a tree whose
# subdirectories differ wildly in size; each job costs one fork plus one
# Storable round-trip through a temp file, so too many jobs loses again.
# Measured 2026-09-23, 20-core NVMe box, warm cache, best of 3, seconds:
#
#   tree (files)                 serial   k=1    k=2    k=4    k=8    k=16
#   ~/perl5 (150k), cpu=8         1.23    0.95   0.25   0.29   0.36   0.47
#   ~/perl5 (150k), cpu=4         1.23    1.03   0.82   0.39   0.45   0.61
#   perlbrew/build (120k), cpu=8  0.75    0.19   0.24   0.25   0.33   0.44
#
# k=1 and k=2 collapse on the skewed tree; 4 is the smallest value that does
# not.  Re-run: edit the value below, then time
#   perl -Ilib -MCn::Util -e 'dir(dir => $ARGV[0], recursive => 1, cpu => 8)' TREE
my $DIR_JOBS_PER_CPU = 4;

# Hand each entry of directory $d that matches $re and $tester to $emit, and
# return its subdirectories, leaving out symlinks to directories so that a
# recursive walk does not follow them.  One level of a recursive dir(): the
# serial walk is a loop over it, and so are the parallel walk's breadth-first
# levels and each of its workers.
sub _dir_level {
	my ($d, $re, $tester, $join, $emit) = @_;
	opendir my $dh, $d or die "Cannot open directory $d: $!";
	my @sub;
	while (defined(my $item = readdir $dh)) {
		next if $item =~ /\A\.\.?\z/;
		my $path = $join->($d, $item);
		$emit->($path) if $item =~ $re && $tester->($path);
		push @sub, $path if !-l $path && -d _;   # -l: lstat, so -d _ is the entry itself, not its target
	}



( run in 1.106 second using v1.01-cache-2.11-cpan-eb134014566 )