use 5.006;
use strict;
use warnings;
use warnings::register;
our $VERSION = '1.07';
require Exporter;
require Cwd;
#
# Modified to ensure sub-directory traversal order is not inverded by stack
# push and pops. That is remains in the same order as in the directory file,
# or user pre-processing (EG:sorted).
#
=head1 NAME
File::Find - Traverse a directory tree.
=head1 SYNOPSIS
use File::Find;
find(\&wanted, @directories_to_search);
sub wanted { ... }
use File::Find;
finddepth(\&wanted, @directories_to_search);
sub wanted { ... }
use File::Find;
find({ wanted => \&process, follow => 1 }, '.');
=head1 DESCRIPTION
These are functions for searching through directory trees doing work
on each file found similar to the Unix I<find> command. File::Find
exports two functions, C<find> and C<finddepth>. They work similarly
but have subtle differences.
=over 4
=item B<find>
find(\&wanted, @directories);
find(\%options, @directories);
C<find()> does a depth-first search over the given C<@directories> in
the order they are given. For each file or directory found, it calls
the C<&wanted> subroutine. (See below for details on how to use the
C<&wanted> function). Additionally, for each directory found, it will
C<chdir()> into that directory and continue the search, invoking the
C<&wanted> function on each file or subdirectory in the directory.
=item B<finddepth>
finddepth(\&wanted, @directories);
finddepth(\%options, @directories);
C<finddepth()> works just like C<find()> except that is invokes the
C<&wanted> function for a directory I<after> invoking it for the
directory's contents. It does a postorder traversal instead of a
preorder traversal, working from the bottom of the directory tree up
where C<find()> works from the top of the tree down.
=back
=head2 %options
The first argument to C<find()> is either a code reference to your
C<&wanted> function, or a hash reference describing the operations
to be performed for each file. The
code reference is described in L<The wanted function> below.
Here are the possible keys for the hash:
=over 3
=item C<wanted>
The value should be a code reference. This code reference is
described in L<The wanted function> below.
=item C<bydepth>
Reports the name of a directory only AFTER all its entries
have been reported. Entry point C<finddepth()> is a shortcut for
specifying C<<{ bydepth => 1 }>> in the first argument of C<find()>.
=item C<preprocess>
The value should be a code reference. This code reference is used to
preprocess the current directory. The name of the currently processed
directory is in C<$File::Find::dir>. Your preprocessing function is
called after C<readdir()>, but before the loop that calls the C<wanted()>
names) and is expected to return a list of strings. The code can be
or to filter out directory entries based on their name alone. When
I<follow> or I<follow_fast> are in effect, C<preprocess> is a no-op.
=item C<postprocess>
The value should be a code reference. It is invoked just before leaving
the currently processed directory. It is called in void context with no
arguments. The name of the current directory is in C<$File::Find::dir>. This
hook is handy for summarizing a directory, such as calculating its disk
usage. When I<follow> or I<follow_fast> are in effect, C<postprocess> is a
no-op.
=item C<follow>
Causes symbolic links to be followed. Since directory trees with symbolic
links (followed) may contain files more than once and may even have
cycles, a hash has to be built up with an entry for each file.
This might be expensive both in space and time for a large
directory tree. See I<follow_fast> and I<follow_skip> below.
If either I<follow> or I<follow_fast> is in effect:
=over 6
=item *
It is guaranteed that an I<lstat> has been called before the user's
C<wanted()> function is called. This enables fast file checks involving S< _>.
=item *
There is a variable C<$File::Find::fullname> which holds the absolute
pathname of the file with all symbolic links resolved
=back
=item C<follow_fast>
This is similar to I<follow> except that it may report some files more
than once. It does detect cycles, however. Since only symbolic links
have to be hashed, this is much cheaper both in space and time. If
processing a file more than once (by the user's C<wanted()> function)
is worse than just taking time, the option I<follow> should be used.
=item C<follow_skip>
C<follow_skip==1>, which is the default, causes all files which are
neither directories nor symbolic links to be ignored if they are about
to be processed a second time. If a directory or a symbolic link
are about to be processed a second time, File::Find dies.
C<follow_skip==0> causes File::Find to die if any file is about to be
processed a second time.
C<follow_skip==2> causes File::Find to ignore any duplicate files and
directories but to proceed normally otherwise.
=item C<dangling_symlinks>
If true and a code reference, will be called with the symbolic link
name and the directory it lives in as arguments. Otherwise, if true
and warnings are on, warning "symbolic_link_name is a dangling
symbolic link\n" will be issued. If false, the dangling symbolic link
will be silently ignored.
=item C<no_chdir>
Does not C<chdir()> to each directory as it recurses. The C<wanted()>
function will need to be aware of this, of course. In this case,
C<$_> will be the same as C<$File::Find::name>.
=item C<untaint>
If find is used in taint-mode (-T command line switch or if EUID != UID
or if EGID != GID) then internally directory names have to be untainted
before they can be chdir'ed to. Therefore they are checked against a regular
expression I<untaint_pattern>. Note that all names passed to the user's
I<wanted()> function are still tainted. If this option is used while
not in taint-mode, C<untaint> is a no-op.
=item C<untaint_pattern>
See above. This should be set using the C<qr> quoting operator.
The default is set to C<qr|^([-+@\w./]+)$|>.
Note that the parentheses are vital.
=item C<untaint_skip>
If set, a directory which fails the I<untaint_pattern> is skipped,
including all its sub-directories. The default is to 'die' in such a case.
=back
=head2 The wanted function
The C<wanted()> function does whatever verifications you want on
each file and directory. Note that despite its name, the C<wanted()>
function is a generic callback function, and does B<not> tell
File::Find if a file is "wanted" or not. In fact, its return value
is ignored.
The wanted function takes no arguments but rather does its work
through a collection of variables.
=over 4
=item C<$File::Find::dir> is the current directory name,
=item C<$_> is the current filename within that directory
=item C<$File::Find::name> is the complete pathname to the file.
=back
Don't modify these variables.
$_ = foo.ext
You are chdir()'d toC<$File::Find::dir> when the function is called,
unless C<no_chdir> was specified. Note that when changing to
directories is in effect the root directory (F</>) is a somewhat
special case inasmuch as the concatenation of C<$File::Find::dir>,
C<'/'> and C<$_> is not literally equal to C<$File::Find::name>. The
table below summarizes all variants:
$File::Find::name $File::Find::dir $_
default / / .
no_chdir=>0 /etc / etc
/etc/x /etc x
no_chdir=>1 / / /
/etc / /etc
/etc/x /etc /etc/x
When <follow> or <follow_fast> are in effect, there is
also a C<$File::Find::fullname>. The function may set
C<$File::Find::prune> to prune the tree unless C<bydepth> was
specified. Unless C<follow> or C<follow_fast> is specified, for
compatibility reasons (find.pl, find2perl) there are in addition the
following globals available: C<$File::Find::topdir>,
C<$File::Find::topdev>, C<$File::Find::topino>,
C<$File::Find::topmode> and C<$File::Find::topnlink>.
This library is useful for the C<find2perl> tool, which when fed,
find2perl / -name .nfs\* -mtime +7 \
-exec rm -f {} \; -o -fstype nfs -prune
produces something like:
sub wanted {
/^\.nfs.*\z/s &&
(($dev, $ino, $mode, $nlink, $uid, $gid) = lstat($_)) &&
int(-M _) > 7 &&
unlink($_)
||
($nlink || (($dev, $ino, $mode, $nlink, $uid, $gid) = lstat($_))) &&
$dev < 0 &&
($File::Find::prune = 1);
}
Notice the C<_> in the above C<int(-M _)>: the C<_> is a magical
filehandle that caches the information from the preceding
C<stat()>, C<lstat()>, or filetest.
Here's another interesting wanted function. It will find all symbolic
links that don't resolve:
sub wanted {
-l && !-e && print "bogus link: $File::Find::name\n";
}
See also the script C<pfind> on CPAN for a nice application of this
module.
=head1 WARNINGS
If you run your program with the C<-w> switch, or if you use the
C<warnings> pragma, File::Find will report warnings for several weird
situations. You can disable these warnings by putting the statement
no warnings 'File::Find';
in the appropriate scope. See L<perllexwarn> for more info about lexical
warnings.
=head1 CAVEAT
=over 2
=item $dont_use_nlink
You can set the variable C<$File::Find::dont_use_nlink> to 1, if you want to
force File::Find to always stat directories. This was used for file systems
that do not have an C<nlink> count matching the number of sub-directories.
Examples are ISO-9660 (CD-ROM), AFS, HPFS (OS/2 file system), FAT (DOS file
system) and a couple of others.
You shouldn't need to set this variable, since File::Find should now detect
such file systems on-the-fly and switch itself to using stat. This works even
for parts of your file system, like a mounted CD-ROM.
If you do set C<$File::Find::dont_use_nlink> to 1, you will notice slow-downs.
=item symlinks
Be aware that the option to follow symbolic links can be dangerous.
Depending on the structure of the directory tree (including symbolic
links to directories) you might traverse a given (physical) directory
more than once (only if C<follow_fast> is in effect).
Furthermore, deleting or changing files in a symbolically linked directory
might cause very unpleasant surprises, since you delete or change files
in an unknown directory.
=back
=head1 NOTES
=over 4
=item *
Mac OS (Classic) users should note a few differences:
=over 4
=item *
The path separator is ':', not '/', and the current directory is denoted
as ':', not '.'. You should be careful about specifying relative pathnames.
While a full path always begins with a volume name, a relative pathname
should always begin with a ':'. If specifying a volume name only, a
trailing ':' is required.
=item *
C<$File::Find::dir> is guaranteed to end with a ':'. If C<$_>
contains the name of a directory, that name may or may not end with a
':'. Likewise, C<$File::Find::name>, which contains the complete
pathname to that directory, and C<$File::Find::fullname>, which holds
the absolute pathname of that directory with all symbolic links resolved,
may or may not end with a ':'.
=item *
The default C<untaint_pattern> (see above) on Mac OS is set to
C<qr|^(.+)$|>. Note that the parentheses are vital.
=item *
The invisible system file "Icon\015" is ignored. While this file may
appear in every directory, there are some more invisible system files
on every volume, which are all located at the volume root level (i.e.
"MacintoshHD:"). These system files are B<not> excluded automatically.
Your filter may use the following code to recognize invisible files or
directories (requires Mac::Files):
use Mac::Files;
# 0 if it's visible or undef if an error occurred
sub invisible($) {
my $file = shift;
my ($fileCat, $fileInfo);
my $invisible_flag = 1 << 14;
if ( $fileCat = FSpGetCatInfo($file) ) {
if ($fileInfo = $fileCat->ioFlFndrInfo() ) {
return (($fileInfo->fdFlags & $invisible_flag) && 1);
}
}
return undef;
}
Generally, invisible files are system files, unless an odd application
decides to use invisible files for its own purposes. To distinguish
such files from system files, you have to look at the B<type> and B<creator>
file attributes. The MacPerl built-in functions C<GetFileInfo(FILE)> and
C<SetFileInfo(CREATOR, TYPE, FILES)> offer access to these attributes
(see MacPerl.pm for details).
Files that appear on the desktop actually reside in an (hidden) directory
named "Desktop Folder" on the particular disk volume. Note that, although
all desktop files appear to be on the same "virtual" desktop, each disk
volume actually maintains its own "Desktop Folder" directory.
=back
=back
=head1 BUGS AND CAVEATS
Despite the name of the C<finddepth()> function, both C<find()> and
C<finddepth()> perform a depth-first search of the directory
hierarchy.
=head1 HISTORY
File::Find used to produce incorrect results if called recursively.
During the development of perl 5.8 this bug was fixed.
The first fixed version of File::Find was 1.01.
=cut
use strict;
my $Is_VMS;
my $Is_MacOS;
# Should ideally be my() not our() but local() currently
# refuses to operate on lexicals
our %SLnkSeen;
sub contract_name {
$fn =~ s|^\./||;
1 while $abs_name =~ s!/[^/]*/\.\./!/!;
}
return $abs_name;
}
# return the absolute name of a directory or file
sub contract_name_Mac {
my $abs_name;
if ($fn =~ /^(:+)(.*)$/) { # valid pathname starting with a ':'
my $colon_count = length ($1);
if ($colon_count == 1) {
return $abs_name;
}
else {
# need to move up the tree, but
# only if it's not a volume name
for (my $i=1; $i<$colon_count; $i++) {
unless ($cdir =~ /^[^:]+:$/) { # volume name
$cdir =~ s/[^:]+:$//;
}
else {
return undef;
}
}
return $abs_name;
}
}
else {
# $fn may be a valid path to a directory or file or (dangling)
# symlink, without a leading ':'
if ($fn =~ /^[^:]+:/) { # a volume name like DataHD:*
return $fn; # $fn is already an absolute path
}
else {
return $abs_name;
}
}
return undef;
}
}
}
sub PathCombine($$) {
my $AbsName;
if ($Is_MacOS) {
# $Name is the resolved symlink (always a full path on MacOS),
# i.e. there's no need to call contract_name_Mac()
# (simple) check for recursion
return undef;
}
}
else {
}
else {
}
# (simple) check for recursion
{
return undef;
}
}
}
return $AbsName;
}
sub Follow_SymLink($) {
my ($AbsName) = @_;
while (-l _) {
if ($follow_skip < 2) {
die "$AbsName is encountered a second time";
}
else {
return undef;
}
}
unless(defined $NewName) {
if ($follow_skip < 2) {
die "$AbsName is a recursive symbolic link";
}
else {
return undef;
}
}
else {
}
return undef unless defined $DEV; # dangling symbolic link
}
die "$AbsName encountered a second time";
}
else {
return undef;
}
}
return $AbsName;
}
sub _find_dir_symlnk($$$);
sub _find_dir($$$);
# check whether or not a scalar variable is tainted
# (code straight from the Camel, 3rd ed., page 561)
sub is_tainted_pp {
my $arg = shift;
local $@;
eval { eval "# $nada" };
return length($@) != 0;
}
sub _find_opt {
my $wanted = shift;
die "invalid top directory" unless defined $_[0];
# This function must local()ize everything because callbacks may
# call find() or finddepth()
local %SLnkSeen;
local *_ = \my $a;
my $cwd_untainted = $cwd;
my $check_t_cwd = 1;
# for compatibility reasons (find.pl, find2perl)
# a symbolic link to a directory doesn't increase the link count
foreach my $TOP (@_) {
if ($Is_MacOS) {
$top_item = ":$top_item"
if ( (-d _) && ( $top_item !~ /:/ ) );
}
else {
}
$Is_Dir= 0;
if ($follow) {
if ($Is_MacOS) {
}
else {
unless (defined $abs_dir) {
warnings::warnif "Can't determine absolute path for $top_item (No such file or directory)\n";
next Proc_Top_Item;
}
}
}
else {
}
}
else { # care about any ../
}
}
unless (defined $abs_dir) {
if ($dangling_symlinks) {
if (ref $dangling_symlinks eq 'CODE') {
} else {
warnings::warnif "$top_item is a dangling symbolic link\n";
}
}
next Proc_Top_Item;
}
if (-d _) {
$Is_Dir= 1;
}
}
else { # no follow
unless (defined $topnlink) {
warnings::warnif "Can't stat $top_item: $!\n";
next Proc_Top_Item;
}
if (-d _) {
$Is_Dir= 1;
}
else {
}
}
unless ($Is_Dir) {
if ($Is_MacOS) {
}
else {
}
}
unless (defined $abs_dir) {
if ($untaint_skip == 0) {
die "directory $dir is still tainted";
}
else {
next Proc_Top_Item;
}
}
}
warnings::warnif "Couldn't chdir $abs_dir: $!\n";
next Proc_Top_Item;
}
{ $wanted_callback->() }; # protect against wild "next"
}
unless ( $no_chdir ) {
unless (defined $cwd_untainted) {
die "insecure cwd in find(depth)";
}
$check_t_cwd = 0;
}
unless (chdir $cwd_untainted) {
die "Can't cd to $cwd: $!\n";
}
}
}
}
# API:
# $wanted
# $p_dir : "parent directory"
# $nlink : what came back from the stat
# preconditions:
# chdir (if not no_chdir) to dir
sub _find_dir($$$) {
my @Stack;
my @filenames;
my $SE= [];
my $dir_pref;
my $tainted = 0;
my $no_nlink;
if ($Is_MacOS) {
}
else {
}
unless (defined $udir) {
if ($untaint_skip == 0) {
die "directory $p_dir is still tainted";
}
else {
return;
}
}
}
warnings::warnif "Can't cd to $udir: $!\n";
return;
}
}
# push the starting directory
if ($Is_MacOS) {
}
while (defined $SE) {
unless ($bydepth) {
# prune may happen here
$prune= 0;
{ $wanted_callback->() }; # protect against wild "next"
next if $prune;
}
# change to that directory
unless (defined $udir) {
if ($untaint_skip == 0) {
if ($Is_MacOS) {
die "directory ($p_dir) $dir_rel is still tainted";
}
else {
}
} else { # $untaint_skip == 1
next;
}
}
}
if ($Is_MacOS) {
warnings::warnif "Can't cd to ($p_dir) $udir: $!\n";
}
else {
warnings::warnif "Can't cd to (" .
}
next;
}
$CdLvl++;
}
if ($Is_MacOS) {
}
# Get the list of files in the current directory.
warnings::warnif "Can't opendir($dir_name): $!\n";
next;
}
closedir(DIR);
# default: use whatever was specifid
# (if $nlink >= 2, and $avoid_nlink == 0, this will switch back)
$no_nlink = $avoid_nlink;
# if dir has wrong nlink count, force switch to slower stat method
# This dir has no subdirectories.
{ $wanted_callback->() }; # protect against wild "next"
}
}
else {
# This dir has subdirectories.
# HACK: insert directories at this position. so as to preserve
# the user pre-processed ordering of files.
# EG: directory traversal is in user sorted order, not at random.
# Seen all the subdirs?
# check for directoriness.
# stat is faster for a file in the current directory
if (-d _) {
--$subcount;
# HACK: replace push to preserve dir traversal order
#push @Stack,[$CdLvl,$dir_name,$FN,$sub_nlink];
}
else {
{ $wanted_callback->() }; # protect against wild "next"
}
}
else {
{ $wanted_callback->() }; # protect against wild "next"
}
}
}
}
continue {
my $tmp;
if ($Is_MacOS) {
}
else {
}
die "Can't cd to $dir_name" . $tmp
unless chdir ($tmp);
}
if ($Is_MacOS) {
# $pdir always has a trailing ':', except for the starting dir,
# where $dir_rel eq ':'
$dir_name = "$p_dir$dir_rel";
$dir_pref = "$dir_name:";
}
else {
$dir_pref = "$dir_name/";
}
if ( $nlink == -2 ) {
$post_process->(); # End-of-directory processing
}
if ($Is_MacOS) {
$name =~ s|:$||; # $File::Find::name
}
}
else {
}
if ( substr($_,-2) eq '/.' ) {
substr($_, length($_) == 2 ? -1 : -2) = '';
}
}
{ $wanted_callback->() }; # protect against wild "next"
}
else {
last;
}
}
}
}
# API:
# $wanted
# $dir_loc : absolute location of a dir
# $p_dir : "parent directory"
# preconditions:
# chdir (if not no_chdir) to dir
sub _find_dir_symlnk($$$) {
my @Stack;
my @filenames;
my $new_loc;
my $SE = [];
my $dir_pref;
my $loc_pref;
my $byd_flag; # flag for pending stack entry if $bydepth
my $tainted = 0;
my $ok = 1;
if ($Is_MacOS) {
} else {
}
unless ($no_chdir) {
# untaint the topdir
# once untainted, $updir_loc is pushed on the stack (as parent directory);
# hence, we don't need to untaint the parent directory every time we chdir
# to it later
unless (defined $updir_loc) {
if ($untaint_skip == 0) {
die "directory $dir_loc is still tainted";
}
else {
return;
}
}
}
unless ($ok) {
warnings::warnif "Can't cd to $updir_loc: $!\n";
return;
}
}
if ($Is_MacOS) {
}
while (defined $SE) {
unless ($bydepth) {
# change (back) to parent directory (always untainted)
unless ($no_chdir) {
unless (chdir $updir_loc) {
warnings::warnif "Can't cd to $updir_loc: $!\n";
next;
}
}
# prune may happen here
$prune= 0;
lstat($_); # make sure file tests with '_' work
{ $wanted_callback->() }; # protect against wild "next"
next if $prune;
}
# change to that directory
# untaint $dir_loc, what will be pushed on the stack as (untainted) parent dir
unless (defined $updir_loc) {
if ($untaint_skip == 0) {
die "directory $dir_loc is still tainted";
}
else {
next;
}
}
}
unless (chdir $updir_loc) {
warnings::warnif "Can't cd to $updir_loc: $!\n";
next;
}
}
if ($Is_MacOS) {
}
# Get the list of files in the current directory.
warnings::warnif "Can't opendir($dir_loc): $!\n";
next;
}
closedir(DIR);
# follow symbolic links / do an lstat
# ignore if invalid symlink
next unless defined $new_loc;
if (-d _) {
}
else {
{ $wanted_callback->() }; # protect against wild "next"
}
}
}
continue {
if ($Is_MacOS) {
# $p_dir always has a trailing ':', except for the starting dir,
# where $dir_rel eq ':'
$dir_name = "$p_dir$dir_rel";
$dir_pref = "$dir_name:";
}
else {
$dir_pref = "$dir_name/";
$loc_pref = "$dir_loc/";
}
unless (chdir $updir_loc) { # $updir_loc (parent dir) is always untainted
warnings::warnif "Can't cd to $updir_loc: $!\n";
next;
}
}
if ($Is_MacOS) {
$name =~ s|:$||; # $File::Find::name
}
}
else {
}
if ( substr($_,-2) eq '/.' ) {
substr($_, length($_) == 2 ? -1 : -2) = '';
}
}
lstat($_); # make sure file tests with '_' work
{ $wanted_callback->() }; # protect against wild "next"
}
else {
last;
}
}
}
}
sub wrap_wanted {
my $wanted = shift;
if ( ref($wanted) eq 'HASH' ) {
}
unless defined $wanted->{untaint_pattern};
}
return $wanted;
}
else {
}
}
sub find {
my $wanted = shift;
}
sub finddepth {
my $wanted = wrap_wanted(shift);
}
# default
# These are hard-coded for now, but may move to hint files.
if ($^O eq 'VMS') {
$Is_VMS = 1;
}
elsif ($^O eq 'MacOS') {
$Is_MacOS = 1;
}
# this _should_ work properly on all platforms
# where File::Find can be expected to work
if $^O eq 'os2' || $^O eq 'dos' || $^O eq 'amigaos' || $^O eq 'MSWin32' ||
$^O eq 'cygwin' || $^O eq 'epoc' || $^O eq 'qnx' ||
$^O eq 'nto';
# Set dont_use_nlink in your hint file if your system's stat doesn't
# report the number of links in a directory as an indication
# of the number of files.
# See, e.g. hints/machten.sh for MachTen 2.2.
require Config;
}
# We need a function that checks if a scalar is tainted. Either use the
# Scalar::Util module's tainted() function or our (slower) pure Perl
# fallback is_tainted_pp()
{
local $@;
}
1;