Upgrade to File::Path 2.06_06. (a diff from David via http)
[p5sagit/p5-mst-13.2.git] / lib / File / Path.pm
1 package File::Path;
2
3 use 5.005_04;
4 use strict;
5
6 use Cwd 'getcwd';
7 use File::Basename ();
8 use File::Spec     ();
9
10 BEGIN {
11     if ($] < 5.006) {
12         # can't say 'opendir my $dh, $dirname'
13         # need to initialise $dh
14         eval "use Symbol";
15     }
16 }
17
18 use Exporter ();
19 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
20 $VERSION   = '2.06_06';
21 @ISA     = qw(Exporter);
22 @EXPORT  = qw(mkpath rmtree);
23 @EXPORT_OK = qw(make_path remove_tree);
24
25 my $Is_VMS   = $^O eq 'VMS';
26 my $Is_MacOS = $^O eq 'MacOS';
27
28 # These OSes complain if you want to remove a file that you have no
29 # write permission to:
30 my $Force_Writeable = grep {$^O eq $_} qw(amigaos dos epoc MSWin32 MacOS os2);
31
32 sub _carp {
33     require Carp;
34     goto &Carp::carp;
35 }
36
37 sub _croak {
38     require Carp;
39     goto &Carp::croak;
40 }
41
42 sub _error {
43     my $arg     = shift;
44     my $message = shift;
45     my $object  = shift;
46
47     if ($arg->{error}) {
48         $object = '' unless defined $object;
49         $message .= ": $!" if $!;
50         push @{${$arg->{error}}}, {$object => $message};
51     }
52     else {
53         _carp(defined($object) ? "$message for $object: $!" : "$message: $!");
54     }
55 }
56
57 sub make_path {
58     push @_, {} if !@_ or (@_ and !UNIVERSAL::isa($_[-1],'HASH'));
59     goto &mkpath;
60 }
61
62 sub mkpath {
63     my $old_style = !(@_ > 0 and UNIVERSAL::isa($_[-1],'HASH'));
64
65     my $arg;
66     my $paths;
67
68     if ($old_style) {
69         my ($verbose, $mode);
70         ($paths, $verbose, $mode) = @_;
71         $paths = [$paths] unless UNIVERSAL::isa($paths,'ARRAY');
72         $arg->{verbose} = defined $verbose ? $verbose : 0;
73         $arg->{mode}    = defined $mode    ? $mode    : 0777;
74     }
75     else {
76             $arg = pop @_;
77         $arg->{verbose} ||= 0;
78         $arg->{mode}      = delete $arg->{mask} if exists $arg->{mask};
79             $arg->{mode} = 0777 unless exists $arg->{mode};
80             ${$arg->{error}} = [] if exists $arg->{error};
81         $paths = [@_];
82     }
83     return _mkpath($arg, $paths);
84 }
85
86 sub _mkpath {
87     my $arg   = shift;
88     my $paths = shift;
89
90     my(@created,$path);
91     foreach $path (@$paths) {
92         next unless defined($path) and length($path);
93         $path .= '/' if $^O eq 'os2' and $path =~ /^\w:\z/s; # feature of CRT 
94         # Logic wants Unix paths, so go with the flow.
95         if ($Is_VMS) {
96             next if $path eq '/';
97             $path = VMS::Filespec::unixify($path);
98         }
99         next if -d $path;
100         my $parent = File::Basename::dirname($path);
101         unless (-d $parent or $path eq $parent) {
102             push(@created,_mkpath($arg, [$parent]));
103         }
104         print "mkdir $path\n" if $arg->{verbose};
105         if (mkdir($path,$arg->{mode})) {
106             push(@created, $path);
107         }
108         else {
109             my $save_bang = $!;
110             my ($e, $e1) = ($save_bang, $^E);
111             $e .= "; $e1" if $e ne $e1;
112             # allow for another process to have created it meanwhile
113             if (!-d $path) {
114                 $! = $save_bang;
115                 if ($arg->{error}) {
116                     push @{${$arg->{error}}}, {$path => $e};
117                 }
118                 else {
119                     _croak("mkdir $path: $e");
120                 }
121             }
122         }
123     }
124     return @created;
125 }
126
127 sub remove_tree {
128     push @_, {} if !@_ or (@_ and !UNIVERSAL::isa($_[-1],'HASH'));
129     goto &rmtree;
130 }
131
132 sub rmtree {
133     my $old_style = !(@_ > 0 and UNIVERSAL::isa($_[-1],'HASH'));
134
135     my $arg;
136     my $paths;
137
138     if ($old_style) {
139         my ($verbose, $safe);
140         ($paths, $verbose, $safe) = @_;
141         $arg->{verbose} = defined $verbose ? $verbose : 0;
142         $arg->{safe}    = defined $safe    ? $safe    : 0;
143
144         if (defined($paths) and length($paths)) {
145             $paths = [$paths] unless UNIVERSAL::isa($paths,'ARRAY');
146         }
147         else {
148             _carp ("No root path(s) specified\n");
149             return 0;
150         }
151     }
152     else {
153         if (@_ > 0 and UNIVERSAL::isa($_[-1],'HASH')) {
154             $arg = pop @_;
155             ${$arg->{error}}  = [] if exists $arg->{error};
156             ${$arg->{result}} = [] if exists $arg->{result};
157         }
158         else {
159             @{$arg}{qw(verbose safe)} = (0, 0);
160         }
161         $paths = [@_];
162     }
163
164     $arg->{prefix} = '';
165     $arg->{depth}  = 0;
166
167     my @clean_path;
168     $arg->{cwd} = getcwd() or do {
169         _error($arg, "cannot fetch initial working directory");
170         return 0;
171     };
172     for ($arg->{cwd}) { /\A(.*)\Z/; $_ = $1 } # untaint
173
174     for my $p (@$paths) {
175         # need to fixup case and map \ to / on Windows
176         my $ortho_root = $^O eq 'MSWin32' ? _slash_lc($p)          : $p;
177         my $ortho_cwd  = $^O eq 'MSWin32' ? _slash_lc($arg->{cwd}) : $arg->{cwd};
178         if ($ortho_root eq substr($ortho_cwd, 0, length($ortho_root))) {
179             local $! = 0;
180             _error($arg, "cannot remove path when cwd is $arg->{cwd}", $p);
181             next;
182         }
183
184         if ($Is_MacOS) {
185             $p  = ":$p" unless $p =~ /:/;
186             $p .= ":"   unless $p =~ /:\z/;
187         }
188         elsif ($^O eq 'MSWin32') {
189             $p =~ s{[/\\]\z}{};
190         }
191         else {
192             $p =~ s{/\z}{};
193         }
194         push @clean_path, $p;
195     }
196
197     @{$arg}{qw(device inode perm)} = (lstat $arg->{cwd})[0,1] or do {
198         _error($arg, "cannot stat initial working directory", $arg->{cwd});
199         return 0;
200     };
201
202     return _rmtree($arg, \@clean_path);
203 }
204
205 sub _rmtree {
206     my $arg   = shift;
207     my $paths = shift;
208
209     my $count  = 0;
210     my $curdir = File::Spec->curdir();
211     my $updir  = File::Spec->updir();
212
213     my (@files, $root);
214     ROOT_DIR:
215     foreach $root (@$paths) {
216         # since we chdir into each directory, it may not be obvious
217         # to figure out where we are if we generate a message about
218         # a file name. We therefore construct a semi-canonical
219         # filename, anchored from the directory being unlinked (as
220         # opposed to being truly canonical, anchored from the root (/).
221
222         my $canon = $arg->{prefix}
223             ? File::Spec->catfile($arg->{prefix}, $root)
224             : $root
225         ;
226
227         my ($ldev, $lino, $perm) = (lstat $root)[0,1,2] or next ROOT_DIR;
228
229         if ( -d _ ) {
230             $root = VMS::Filespec::pathify($root) if $Is_VMS;
231             if (!chdir($root)) {
232                 # see if we can escalate privileges to get in
233                 # (e.g. funny protection mask such as -w- instead of rwx)
234                 $perm &= 07777;
235                 my $nperm = $perm | 0700;
236                 if (!($arg->{safe} or $nperm == $perm or chmod($nperm, $root))) {
237                     _error($arg, "cannot make child directory read-write-exec", $canon);
238                     next ROOT_DIR;
239                 }
240                 elsif (!chdir($root)) {
241                     _error($arg, "cannot chdir to child", $canon);
242                     next ROOT_DIR;
243                 }
244             }
245
246             my ($cur_dev, $cur_inode, $perm) = (stat $curdir)[0,1,2] or do {
247                 _error($arg, "cannot stat current working directory", $canon);
248                 next ROOT_DIR;
249             };
250
251             ($ldev eq $cur_dev and $lino eq $cur_inode)
252                 or _croak("directory $canon changed before chdir, expected dev=$ldev ino=$lino, actual dev=$cur_dev ino=$cur_inode, aborting.");
253
254             $perm &= 07777; # don't forget setuid, setgid, sticky bits
255             my $nperm = $perm | 0700;
256
257             # notabene: 0700 is for making readable in the first place,
258             # it's also intended to change it to writable in case we have
259             # to recurse in which case we are better than rm -rf for 
260             # subtrees with strange permissions
261
262             if (!($arg->{safe} or $nperm == $perm or chmod($nperm, $curdir))) {
263                 _error($arg, "cannot make directory read+writeable", $canon);
264                 $nperm = $perm;
265             }
266
267             my $d;
268             $d = gensym() if $] < 5.006;
269             if (!opendir $d, $curdir) {
270                 _error($arg, "cannot opendir", $canon);
271                 @files = ();
272             }
273             else {
274                 no strict 'refs';
275                 if (!defined ${"\cTAINT"} or ${"\cTAINT"}) {
276                     # Blindly untaint dir names if taint mode is
277                     # active, or any perl < 5.006
278                     @files = map { /\A(.*)\z/s; $1 } readdir $d;
279                 }
280                 else {
281                     @files = readdir $d;
282                 }
283                 closedir $d;
284             }
285
286             if ($Is_VMS) {
287                 # Deleting large numbers of files from VMS Files-11
288                 # filesystems is faster if done in reverse ASCIIbetical order.
289                 # include '.' to '.;' from blead patch #31775
290                 @files = map {$_ eq '.' ? '.;' : $_} reverse @files;
291                 ($root = VMS::Filespec::unixify($root)) =~ s/\.dir\z//;
292             }
293             @files = grep {$_ ne $updir and $_ ne $curdir} @files;
294
295             if (@files) {
296                 # remove the contained files before the directory itself
297                 my $narg = {%$arg};
298                 @{$narg}{qw(device inode cwd prefix depth)}
299                     = ($cur_dev, $cur_inode, $updir, $canon, $arg->{depth}+1);
300                 $count += _rmtree($narg, \@files);
301             }
302
303             # restore directory permissions of required now (in case the rmdir
304             # below fails), while we are still in the directory and may do so
305             # without a race via '.'
306             if ($nperm != $perm and not chmod($perm, $curdir)) {
307                 _error($arg, "cannot reset chmod", $canon);
308             }
309
310             # don't leave the client code in an unexpected directory
311             chdir($arg->{cwd})
312                 or _croak("cannot chdir to $arg->{cwd} from $canon: $!, aborting.");
313
314             # ensure that a chdir upwards didn't take us somewhere other
315             # than we expected (see CVE-2002-0435)
316             ($cur_dev, $cur_inode) = (stat $curdir)[0,1]
317                 or _croak("cannot stat prior working directory $arg->{cwd}: $!, aborting.");
318
319             ($arg->{device} eq $cur_dev and $arg->{inode} eq $cur_inode)
320                 or _croak("previous directory $arg->{cwd} changed before entering $canon, expected dev=$ldev ino=$lino, actual dev=$cur_dev ino=$cur_inode, aborting.");
321
322             if ($arg->{depth} or !$arg->{keep_root}) {
323                 if ($arg->{safe} &&
324                     ($Is_VMS ? !&VMS::Filespec::candelete($root) : !-w $root)) {
325                     print "skipped $root\n" if $arg->{verbose};
326                     next ROOT_DIR;
327                 }
328                 if ($Force_Writeable and !chmod $perm | 0700, $root) {
329                         _error($arg, "cannot make directory writeable", $canon);
330                     }
331                 print "rmdir $root\n" if $arg->{verbose};
332                 if (rmdir $root) {
333                     push @{${$arg->{result}}}, $root if $arg->{result};
334                     ++$count;
335                 }
336                 else {
337                     _error($arg, "cannot remove directory", $canon);
338                     if (!chmod($perm, ($Is_VMS ? VMS::Filespec::fileify($root) : $root))
339                     ) {
340                         _error($arg, sprintf("cannot restore permissions to 0%o",$perm), $canon);
341                     }
342                 }
343             }
344         }
345         else {
346             # not a directory
347             $root = VMS::Filespec::vmsify("./$root")
348                 if $Is_VMS 
349                    && !File::Spec->file_name_is_absolute($root)
350                    && ($root !~ m/(?<!\^)[\]>]+/);  # not already in VMS syntax
351
352             if ($arg->{safe} &&
353                 ($Is_VMS ? !&VMS::Filespec::candelete($root)
354                          : !(-l $root || -w $root)))
355             {
356                 print "skipped $root\n" if $arg->{verbose};
357                 next ROOT_DIR;
358             }
359
360             my $nperm = $perm & 07777 | 0600;
361             if ($Force_Writeable and $nperm != $perm and not chmod $nperm, $root) {
362                     _error($arg, "cannot make file writeable", $canon);
363                 }
364             print "unlink $canon\n" if $arg->{verbose};
365             # delete all versions under VMS
366             for (;;) {
367                 if (unlink $root) {
368                     push @{${$arg->{result}}}, $root if $arg->{result};
369                 }
370                 else {
371                     _error($arg, "cannot unlink file", $canon);
372                     $Force_Writeable and chmod($perm, $root) or
373                         _error($arg, sprintf("cannot restore permissions to 0%o",$perm), $canon);
374                     last;
375                 }
376                 ++$count;
377                 last unless $Is_VMS && lstat $root;
378             }
379         }
380     }
381     return $count;
382 }
383
384 sub _slash_lc {
385     # fix up slashes and case on MSWin32 so that we can determine that
386     # c:\path\to\dir is underneath C:/Path/To
387     my $path = shift;
388     $path =~ tr{\\}{/};
389     return lc($path);
390 }
391
392 1;
393 __END__
394
395 =head1 NAME
396
397 File::Path - Create or remove directory trees
398
399 =head1 VERSION
400
401 This document describes version 2.06_06 of File::Path, released
402 2008-10-05.
403
404 =head1 SYNOPSIS
405
406     use File::Path;
407
408     # modern
409   make_path( 'foo/bar/baz', '/zug/zwang' );
410   # or
411     mkpath( 'foo/bar/baz', '/zug/zwang', {verbose => 1} );
412
413     rmtree(
414         'foo/bar/baz', '/zug/zwang',
415         { verbose => 1, error  => \my $err_list }
416     );
417   # or
418   remove_tree( 'foo/bar/baz', '/zug/zwang' );
419
420     # traditional
421     mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);
422     rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);
423
424 =head1 DESCRIPTION
425
426 The C<mkpath> function provides a convenient way to create directories
427 of arbitrary depth. Similarly, the C<rmtree> function provides a
428 convenient way to delete an entire directory subtree from the
429 filesystem, much like the Unix command C<rm -r> or C<del /s> on
430 Windows.
431
432 There are two further functions, C<make_path> and C<remove_tree>
433 that perform the same task and offer a more intuitive interface.
434
435 =head2 FUNCTIONS
436
437 The modern way of calling C<mkpath> and C<rmtree> is with a list
438 of directories to create, or remove, respectively, followed by a
439 hash reference containing keys to control the function's behaviour.
440
441 =head3 C<make_path>
442
443 The C<make_path> routine accepts a list of directories to be
444 created. Its behaviour may be tuned by an optional hashref
445 appearing as the last parameter on the call.
446
447   my @created = make_path(qw(/tmp /flub /home/nobody));
448   print "created $_\n" for @created;
449
450 The function returns the list of files actually created during the
451 call.
452
453 =head3 C<mkpath>
454
455 The C<mkpath> routine will recognise a final hashref in the
456 same manner as C<make_path>. If no hashref is present, the
457 parameters are interpreted according to the traditional interface
458 (see below).
459
460   my @created = mkpath(
461     qw(/tmp /flub /home/nobody),
462     {verbose => 1, mode => 0750},
463   );
464   print "created $_\n" for @created;
465
466 The function returns the list of directories actually created during
467 the call.
468
469 The following keys are recognised:
470
471 =over 4
472
473 =item mode
474
475 The numeric permissions mode to apply to each created directory
476 (defaults to 0777), to be modified by the current C<umask>. If the
477 directory already exists (and thus does not need to be created),
478 the permissions will not be modified.
479
480 C<mask> is recognised as an alias for this parameter.
481
482 =item verbose
483
484 If present, will cause C<mkpath> to print the name of each directory
485 as it is created. By default nothing is printed.
486
487 =item error
488
489 If present, will be interpreted as a reference to a list, and will
490 be used to store any errors that are encountered.  See the ERROR
491 HANDLING section for more information.
492
493 If this parameter is not used, certain error conditions may raise
494 a fatal error that will cause the program will halt, unless trapped
495 in an C<eval> block.
496
497 =back
498
499 =head3 C<remove_tree>
500
501 The C<remove_tree> routine accepts a list of directories to be
502 removed. Its behaviour may be tuned by an optional hashref
503 appearing as the last parameter on the call.
504
505   remove_tree( 'this/dir', 'that/dir' );
506
507 =head3 C<rmtree>
508
509 The C<rmtree> routine will recognise a final hashref in the
510 same manner as C<remove_tree>. If no hashref is present, the
511 parameters are interpreted according to the traditional interface.
512
513   rmtree( 'mydir', 1 );                 # traditional
514   rmtree( ['mydir'], 1 );               # traditional
515   rmtree( 'mydir', 1, {verbose => 0} ); # modern
516
517 =over 4
518
519 =item verbose
520
521 If present, will cause C<rmtree> to print the name of each file as
522 it is unlinked. By default nothing is printed.
523
524 =item safe
525
526 When set to a true value, will cause C<rmtree> to skip the files
527 for which the process lacks the required privileges needed to delete
528 files, such as delete privileges on VMS. In other words, the code
529 will make no attempt to alter file permissions. Thus, if the process
530 is interrupted, no filesystem object will be left in a more
531 permissive mode.
532
533 =item keep_root
534
535 When set to a true value, will cause all files and subdirectories
536 to be removed, except the initially specified directories. This comes
537 in handy when cleaning out an application's scratch directory.
538
539   remove_tree( '/tmp', {keep_root => 1} );
540
541 =item result
542
543 If present, will be interpreted as a reference to a list, and will
544 be used to store the list of all files and directories unlinked
545 during the call. If nothing is unlinked, a reference to an empty
546 list is returned (rather than C<undef>).
547
548   remove_tree( '/tmp', {result => \my $list} );
549   print "unlinked $_\n" for @$list;
550
551 This is a useful alternative to the C<verbose> key.
552
553 =item error
554
555 If present, will be interpreted as a reference to a list,
556 and will be used to store any errors that are encountered.
557 See the ERROR HANDLING section for more information.
558
559 Removing things is a much more dangerous proposition than
560 creating things. As such, there are certain conditions that
561 C<rmtree> may encounter that are so dangerous that the only
562 sane action left is to kill the program.
563
564 Use C<error> to trap all that is reasonable (problems with
565 permissions and the like), and let it die if things get out
566 of hand. This is the safest course of action.
567
568 =back
569
570 =head2 TRADITIONAL INTERFACE
571
572 The old interfaces of C<mkpath> and C<rmtree> take a reference to
573 a list of directories (to create or remove), followed by a series
574 of positional, numeric, modal parameters that control their behaviour.
575 If only one directory is being created or removed, a simple scalar
576 may be used instead of the reference.
577
578   rmtree( ['dir1', 'dir2'], 0, 1 );
579   rmtree( 'dir3', 1, 1 );
580
581 This design made it difficult to add additional functionality, as
582 well as posed the problem of what to do when the calling code only
583 needs to set the last parameter. Even though the code doesn't care
584 how the initial positional parameters are set, the programmer is
585 forced to learn what the defaults are, and specify them.
586
587 Worse, if it turns out in the future that it would make more sense
588 to change the default behaviour of the first parameter (for example,
589 to avoid a security vulnerability), all existing code will remain
590 hard-wired to the wrong defaults.
591
592 Finally, a series of numeric parameters are much less self-documenting
593 in terms of communicating to the reader what the code is doing. Named
594 parameters do not have this problem.
595
596 In the traditional API, C<mkpath> takes three arguments:
597
598 =over 4
599
600 =item *
601
602 The name of the path to create, or a reference to a list of paths
603 to create,
604
605 =item *
606
607 a boolean value, which if TRUE will cause C<mkpath> to print the
608 name of each directory as it is created (defaults to FALSE), and
609
610 =item *
611
612 the numeric mode to use when creating the directories (defaults to
613 0777), to be modified by the current umask.
614
615 =back
616
617 It returns a list of all directories (including intermediates,
618 determined using the Unix '/' separator) created. In scalar context
619 it returns the number of directories created.
620
621 If a system error prevents a directory from being created, then the
622 C<mkpath> function throws a fatal error with C<Carp::croak>. This
623 error can be trapped with an C<eval> block:
624
625   eval { mkpath($dir) };
626   if ($@) {
627     print "Couldn't create $dir: $@";
628   }
629
630 In the traditional API, C<rmtree> takes three arguments:
631
632 =over 4
633
634 =item *
635
636 the root of the subtree to delete, or a reference to a list of
637 roots. All of the files and directories below each root, as well
638 as the roots themselves, will be deleted. If you want to keep
639 the roots themselves, you must use the modern API.
640
641 =item *
642
643 a boolean value, which if TRUE will cause C<rmtree> to print a
644 message each time it examines a file, giving the name of the file,
645 and indicating whether it's using C<rmdir> or C<unlink> to remove
646 it, or that it's skipping it.  (defaults to FALSE)
647
648 =item *
649
650 a boolean value, which if TRUE will cause C<rmtree> to skip any
651 files to which you do not have delete access (if running under VMS)
652 or write access (if running under another OS). This will change
653 in the future when a criterion for 'delete permission' under OSs
654 other than VMS is settled.  (defaults to FALSE)
655
656 =back
657
658 C<rmtree> returns the number of files, directories and symlinks
659 successfully deleted. Symlinks are simply deleted and not followed.
660
661 Note also that the occurrence of errors in C<rmtree> using the
662 traditional interface can be determined I<only> by trapping diagnostic
663 messages using C<$SIG{__WARN__}>; it is not apparent from the return
664 value. (The modern interface may use the C<error> parameter to
665 record any problems encountered).
666
667 It is not possible to invoke the C<keep_root> functionality through
668 the traditional interface.
669
670 =head2 ERROR HANDLING
671
672 If C<mkpath> or C<rmtree> encounter an error, a diagnostic message
673 will be printed to C<STDERR> via C<carp> (for non-fatal errors),
674 or via C<croak> (for fatal errors).
675
676 If this behaviour is not desirable, the C<error> attribute may be
677 used to hold a reference to a variable, which will be used to store
678 the diagnostics. The result is a reference to a list of hash
679 references. For each hash reference, the key is the name of the
680 file, and the value is the error message (usually the contents of
681 C<$!>). An example usage looks like:
682
683   remove_tree( 'foo/bar', 'bar/rat', {error => \my $err} );
684   for my $diag (@$err) {
685     my ($file, $message) = each %$diag;
686     print "problem unlinking $file: $message\n";
687   }
688
689 If no errors are encountered, C<$err> will point to an empty list
690 (thus there is no need to test for C<undef>). If a general error
691 is encountered (for instance, C<rmtree> attempts to remove a directory
692 tree that does not exist), the diagnostic key will be empty, only
693 the value will be set:
694
695   remove_tree( '/no/such/path', {error => \my $err} );
696   for my $diag (@$err) {
697     my ($file, $message) = each %$diag;
698     if ($file eq '') {
699       print "general error: $message\n";
700     }
701   }
702
703 =head2 NOTES
704
705 C<File::Path> blindly exports C<mkpath> and C<rmtree> into the
706 current namespace. These days, this is considered bad style, but
707 to change it now would break too much code. Nonetheless, you are
708 invited to specify what it is you are expecting to use:
709
710   use File::Path 'rmtree';
711
712 The routines C<make_path> and C<remove_tree> are B<not> exported
713 by default. You must specify which ones you want to use.
714
715   use File::Path 'remove_tree';
716
717 Note that a side-effect of the above is that C<mkpath> and C<rmtree>
718 are no longer exported at all. This is due to the way the C<Exporter>
719 module works. If you are migrating a codebase to use the new
720 interface, you will have to list everything explicitly. But that's
721 just good practice anyway.
722
723   use File::Path qw(remove_tree rmtree);
724
725 =head3 SECURITY CONSIDERATIONS
726
727 There were race conditions 1.x implementations of File::Path's
728 C<rmtree> function (although sometimes patched depending on the OS
729 distribution or platform). The 2.0 version contains code to avoid the
730 problem mentioned in CVE-2002-0435.
731
732 See the following pages for more information:
733
734   http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=286905
735   http://www.nntp.perl.org/group/perl.perl5.porters/2005/01/msg97623.html
736   http://www.debian.org/security/2005/dsa-696
737
738 Additionally, unless the C<safe> parameter is set (or the
739 third parameter in the traditional interface is TRUE), should a
740 C<rmtree> be interrupted, files that were originally in read-only
741 mode may now have their permissions set to a read-write (or "delete
742 OK") mode.
743
744 =head1 DIAGNOSTICS
745
746 FATAL errors will cause the program to halt (C<croak>), since the
747 problem is so severe that it would be dangerous to continue. (This
748 can always be trapped with C<eval>, but it's not a good idea. Under
749 the circumstances, dying is the best thing to do).
750
751 SEVERE errors may be trapped using the modern interface. If the
752 they are not trapped, or the old interface is used, such an error
753 will cause the program will halt.
754
755 All other errors may be trapped using the modern interface, otherwise
756 they will be C<carp>ed about. Program execution will not be halted.
757
758 =over 4
759
760 =item mkdir [path]: [errmsg] (SEVERE)
761
762 C<mkpath> was unable to create the path. Probably some sort of
763 permissions error at the point of departure, or insufficient resources
764 (such as free inodes on Unix).
765
766 =item No root path(s) specified
767
768 C<mkpath> was not given any paths to create. This message is only
769 emitted if the routine is called with the traditional interface.
770 The modern interface will remain silent if given nothing to do.
771
772 =item No such file or directory
773
774 On Windows, if C<mkpath> gives you this warning, it may mean that
775 you have exceeded your filesystem's maximum path length.
776
777 =item cannot fetch initial working directory: [errmsg]
778
779 C<rmtree> attempted to determine the initial directory by calling
780 C<Cwd::getcwd>, but the call failed for some reason. No attempt
781 will be made to delete anything.
782
783 =item cannot stat initial working directory: [errmsg]
784
785 C<rmtree> attempted to stat the initial directory (after having
786 successfully obtained its name via C<getcwd>), however, the call
787 failed for some reason. No attempt will be made to delete anything.
788
789 =item cannot chdir to [dir]: [errmsg]
790
791 C<rmtree> attempted to set the working directory in order to
792 begin deleting the objects therein, but was unsuccessful. This is
793 usually a permissions issue. The routine will continue to delete
794 other things, but this directory will be left intact.
795
796 =item directory [dir] changed before chdir, expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)
797
798 C<rmtree> recorded the device and inode of a directory, and then
799 moved into it. It then performed a C<stat> on the current directory
800 and detected that the device and inode were no longer the same. As
801 this is at the heart of the race condition problem, the program
802 will die at this point.
803
804 =item cannot make directory [dir] read+writeable: [errmsg]
805
806 C<rmtree> attempted to change the permissions on the current directory
807 to ensure that subsequent unlinkings would not run into problems,
808 but was unable to do so. The permissions remain as they were, and
809 the program will carry on, doing the best it can.
810
811 =item cannot read [dir]: [errmsg]
812
813 C<rmtree> tried to read the contents of the directory in order
814 to acquire the names of the directory entries to be unlinked, but
815 was unsuccessful. This is usually a permissions issue. The
816 program will continue, but the files in this directory will remain
817 after the call.
818
819 =item cannot reset chmod [dir]: [errmsg]
820
821 C<rmtree>, after having deleted everything in a directory, attempted
822 to restore its permissions to the original state but failed. The
823 directory may wind up being left behind.
824
825 =item cannot remove [dir] when cwd is [dir]
826
827 The current working directory of the program is F</some/path/to/here>
828 and you are attempting to remove an ancestor, such as F</some/path>.
829 The directory tree is left untouched.
830
831 The solution is to C<chdir> out of the child directory to a place
832 outside the directory tree to be removed.
833
834 =item cannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting. (FATAL)
835
836 C<rmtree>, after having deleted everything and restored the permissions
837 of a directory, was unable to chdir back to the parent. The program
838 halts to avoid a race condition from occurring.
839
840 =item cannot stat prior working directory [dir]: [errmsg], aborting. (FATAL)
841
842 C<rmtree> was unable to stat the parent directory after have returned
843 from the child. Since there is no way of knowing if we returned to
844 where we think we should be (by comparing device and inode) the only
845 way out is to C<croak>.
846
847 =item previous directory [parent-dir] changed before entering [child-dir], expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)
848
849 When C<rmtree> returned from deleting files in a child directory, a
850 check revealed that the parent directory it returned to wasn't the one
851 it started out from. This is considered a sign of malicious activity.
852
853 =item cannot make directory [dir] writeable: [errmsg]
854
855 Just before removing a directory (after having successfully removed
856 everything it contained), C<rmtree> attempted to set the permissions
857 on the directory to ensure it could be removed and failed. Program
858 execution continues, but the directory may possibly not be deleted.
859
860 =item cannot remove directory [dir]: [errmsg]
861
862 C<rmtree> attempted to remove a directory, but failed. This may because
863 some objects that were unable to be removed remain in the directory, or
864 a permissions issue. The directory will be left behind.
865
866 =item cannot restore permissions of [dir] to [0nnn]: [errmsg]
867
868 After having failed to remove a directory, C<rmtree> was unable to
869 restore its permissions from a permissive state back to a possibly
870 more restrictive setting. (Permissions given in octal).
871
872 =item cannot make file [file] writeable: [errmsg]
873
874 C<rmtree> attempted to force the permissions of a file to ensure it
875 could be deleted, but failed to do so. It will, however, still attempt
876 to unlink the file.
877
878 =item cannot unlink file [file]: [errmsg]
879
880 C<rmtree> failed to remove a file. Probably a permissions issue.
881
882 =item cannot restore permissions of [file] to [0nnn]: [errmsg]
883
884 After having failed to remove a file, C<rmtree> was also unable
885 to restore the permissions on the file to a possibly less permissive
886 setting. (Permissions given in octal).
887
888 =back
889
890 =head1 SEE ALSO
891
892 =over 4
893
894 =item *
895
896 L<File::Remove>
897
898 Allows files and directories to be moved to the Trashcan/Recycle
899 Bin (where they may later be restored if necessary) if the operating
900 system supports such functionality. This feature may one day be
901 made available directly in C<File::Path>.
902
903 =item *
904
905 L<File::Find::Rule>
906
907 When removing directory trees, if you want to examine each file to
908 decide whether to delete it (and possibly leaving large swathes
909 alone), F<File::Find::Rule> offers a convenient and flexible approach
910 to examining directory trees.
911
912 =back
913
914 =head1 BUGS
915
916 Please report all bugs on the RT queue:
917
918 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Path>
919
920 =head1 ACKNOWLEDGEMENTS
921
922 Paul Szabo identified the race condition originally, and Brendan
923 O'Dea wrote an implementation for Debian that addressed the problem.
924 That code was used as a basis for the current code. Their efforts
925 are greatly appreciated.
926
927 =head1 AUTHORS
928
929 Tim Bunce and Charles Bailey. Currently maintained by David Landgren
930 <F<david@landgren.net>>.
931
932 =head1 COPYRIGHT
933
934 This module is copyright (C) Charles Bailey, Tim Bunce and
935 David Landgren 1995-2008. All rights reserved.
936
937 =head1 LICENSE
938
939 This library is free software; you can redistribute it and/or modify
940 it under the same terms as Perl itself.
941
942 =cut