This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Update File-Path to CPAN version 2.11
[perl5.git] / cpan / File-Path / lib / File / Path.pm
CommitLineData
1fc4cb55 1package File::Path;
fed7345c 2
cac619e8
DL
3use 5.005_04;
4use strict;
5
6use Cwd 'getcwd';
7use File::Basename ();
8use File::Spec ();
9
10BEGIN {
139271cd
CBW
11 if ( $] < 5.006 ) {
12
cac619e8
DL
13 # can't say 'opendir my $dh, $dirname'
14 # need to initialise $dh
139271cd 15 eval 'use Symbol';
cac619e8
DL
16 }
17}
18
19use Exporter ();
3f083399 20use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
139271cd
CBW
21$VERSION = '2.11';
22$VERSION = eval $VERSION;
30cf951a
NC
23@ISA = qw(Exporter);
24@EXPORT = qw(mkpath rmtree);
3f083399 25@EXPORT_OK = qw(make_path remove_tree);
cac619e8 26
139271cd
CBW
27BEGIN {
28 for (qw(VMS MacOS MSWin32 os2)) {
29 no strict 'refs';
30 *{"_IS_\U$_"} = $^O eq $_ ? sub () { 1 } : sub () { 0 };
31 }
cac619e8 32
139271cd
CBW
33 # These OSes complain if you want to remove a file that you have no
34 # write permission to:
35 *_FORCE_WRITABLE = (
36 grep { $^O eq $_ } qw(amigaos dos epoc MSWin32 MacOS os2)
37 ) ? sub () { 1 } : sub () { 0 };
cac619e8 38
139271cd
CBW
39 # Unix-like systems need to stat each directory in order to detect
40 # race condition. MS-Windows is immune to this particular attack.
41 *_NEED_STAT_CHECK = !(_IS_MSWIN32()) ? sub () { 1 } : sub () { 0 };
42}
839bc55a 43
cac619e8
DL
44sub _carp {
45 require Carp;
46 goto &Carp::carp;
47}
48
49sub _croak {
50 require Carp;
51 goto &Carp::croak;
52}
53
54sub _error {
55 my $arg = shift;
56 my $message = shift;
57 my $object = shift;
58
139271cd 59 if ( $arg->{error} ) {
cac619e8 60 $object = '' unless defined $object;
3f083399 61 $message .= ": $!" if $!;
139271cd 62 push @{ ${ $arg->{error} } }, { $object => $message };
cac619e8
DL
63 }
64 else {
139271cd 65 _carp( defined($object) ? "$message for $object: $!" : "$message: $!" );
cac619e8
DL
66 }
67}
68
139271cd
CBW
69sub __is_arg {
70 my ($arg) = @_;
71
72 # If client code blessed an array ref to HASH, this will not work
73 # properly. We could have done $arg->isa() wrapped in eval, but
74 # that would be expensive. This implementation should suffice.
75 # We could have also used Scalar::Util:blessed, but we choose not
76 # to add this dependency
77 return ( ref $arg eq 'HASH' );
78}
79
3f083399 80sub make_path {
139271cd 81 push @_, {} unless @_ and __is_arg( $_[-1] );
3f083399
NC
82 goto &mkpath;
83}
84
cac619e8 85sub mkpath {
139271cd 86 my $old_style = !( @_ and __is_arg( $_[-1] ) );
cac619e8
DL
87
88 my $arg;
89 my $paths;
90
91 if ($old_style) {
139271cd
CBW
92 my ( $verbose, $mode );
93 ( $paths, $verbose, $mode ) = @_;
94 $paths = [$paths] unless UNIVERSAL::isa( $paths, 'ARRAY' );
2f9d49b4 95 $arg->{verbose} = $verbose;
139271cd 96 $arg->{mode} = defined $mode ? $mode : oct '777';
cac619e8
DL
97 }
98 else {
139271cd
CBW
99 my %args_permitted = map { $_ => 1 } ( qw|
100 chmod
101 error
102 group
103 mask
104 mode
105 owner
106 uid
107 user
108 verbose
109 | );
110 my @bad_args = ();
30cf951a 111 $arg = pop @_;
139271cd
CBW
112 for my $k (sort keys %{$arg}) {
113 push @bad_args, $k unless $args_permitted{$k};
114 }
115 _carp("Unrecognized option(s) passed to make_path(): @bad_args")
116 if @bad_args;
117 $arg->{mode} = delete $arg->{mask} if exists $arg->{mask};
118 $arg->{mode} = oct '777' unless exists $arg->{mode};
119 ${ $arg->{error} } = [] if exists $arg->{error};
120 $arg->{owner} = delete $arg->{user} if exists $arg->{user};
121 $arg->{owner} = delete $arg->{uid} if exists $arg->{uid};
122 if ( exists $arg->{owner} and $arg->{owner} =~ /\D/ ) {
123 my $uid = ( getpwnam $arg->{owner} )[2];
124 if ( defined $uid ) {
30eb83e1
RGS
125 $arg->{owner} = $uid;
126 }
127 else {
139271cd
CBW
128 _error( $arg,
129"unable to map $arg->{owner} to a uid, ownership not changed"
130 );
30eb83e1
RGS
131 delete $arg->{owner};
132 }
133 }
139271cd
CBW
134 if ( exists $arg->{group} and $arg->{group} =~ /\D/ ) {
135 my $gid = ( getgrnam $arg->{group} )[2];
136 if ( defined $gid ) {
30eb83e1
RGS
137 $arg->{group} = $gid;
138 }
139 else {
139271cd
CBW
140 _error( $arg,
141"unable to map $arg->{group} to a gid, group ownership not changed"
142 );
30eb83e1
RGS
143 delete $arg->{group};
144 }
145 }
139271cd
CBW
146 if ( exists $arg->{owner} and not exists $arg->{group} ) {
147 $arg->{group} = -1; # chown will leave group unchanged
30eb83e1 148 }
139271cd
CBW
149 if ( exists $arg->{group} and not exists $arg->{owner} ) {
150 $arg->{owner} = -1; # chown will leave owner unchanged
30eb83e1 151 }
cac619e8
DL
152 $paths = [@_];
153 }
139271cd 154 return _mkpath( $arg, $paths );
cac619e8
DL
155}
156
157sub _mkpath {
158 my $arg = shift;
159 my $paths = shift;
160
139271cd
CBW
161 my ( @created );
162 foreach my $path ( @{$paths} ) {
3f083399 163 next unless defined($path) and length($path);
139271cd
CBW
164 $path .= '/' if _IS_OS2 and $path =~ /^\w:\z/s; # feature of CRT
165
cac619e8 166 # Logic wants Unix paths, so go with the flow.
139271cd 167 if (_IS_VMS) {
cac619e8
DL
168 next if $path eq '/';
169 $path = VMS::Filespec::unixify($path);
170 }
171 next if -d $path;
172 my $parent = File::Basename::dirname($path);
139271cd
CBW
173 unless ( -d $parent or $path eq $parent ) {
174 push( @created, _mkpath( $arg, [$parent] ) );
cac619e8
DL
175 }
176 print "mkdir $path\n" if $arg->{verbose};
139271cd
CBW
177 if ( mkdir( $path, $arg->{mode} ) ) {
178 push( @created, $path );
179 if ( exists $arg->{owner} ) {
180
181 # NB: $arg->{group} guaranteed to be set during initialisation
182 if ( !chown $arg->{owner}, $arg->{group}, $path ) {
183 _error( $arg,
184"Cannot change ownership of $path to $arg->{owner}:$arg->{group}"
185 );
186 }
187 }
188 if ( exists $arg->{chmod} ) {
189 if ( !chmod $arg->{chmod}, $path ) {
190 _error( $arg,
191 "Cannot change permissions of $path to $arg->{chmod}" );
30eb83e1
RGS
192 }
193 }
cac619e8
DL
194 }
195 else {
196 my $save_bang = $!;
139271cd 197 my ( $e, $e1 ) = ( $save_bang, $^E );
cac619e8 198 $e .= "; $e1" if $e ne $e1;
139271cd 199
cac619e8 200 # allow for another process to have created it meanwhile
139271cd 201 if ( ! -d $path ) {
cac619e8 202 $! = $save_bang;
139271cd
CBW
203 if ( $arg->{error} ) {
204 push @{ ${ $arg->{error} } }, { $path => $e };
cac619e8
DL
205 }
206 else {
207 _croak("mkdir $path: $e");
208 }
209 }
210 }
211 }
212 return @created;
213}
214
3f083399 215sub remove_tree {
139271cd 216 push @_, {} unless @_ and __is_arg( $_[-1] );
3f083399
NC
217 goto &rmtree;
218}
219
0e5b5e32 220sub _is_subdir {
139271cd 221 my ( $dir, $test ) = @_;
0e5b5e32 222
139271cd
CBW
223 my ( $dv, $dd ) = File::Spec->splitpath( $dir, 1 );
224 my ( $tv, $td ) = File::Spec->splitpath( $test, 1 );
0e5b5e32
MHM
225
226 # not on same volume
227 return 0 if $dv ne $tv;
228
229 my @d = File::Spec->splitdir($dd);
230 my @t = File::Spec->splitdir($td);
231
232 # @t can't be a subdir if it's shorter than @d
233 return 0 if @t < @d;
234
139271cd 235 return join( '/', @d ) eq join( '/', splice @t, 0, +@d );
0e5b5e32
MHM
236}
237
cac619e8 238sub rmtree {
139271cd 239 my $old_style = !( @_ and __is_arg( $_[-1] ) );
cac619e8
DL
240
241 my $arg;
242 my $paths;
243
244 if ($old_style) {
139271cd
CBW
245 my ( $verbose, $safe );
246 ( $paths, $verbose, $safe ) = @_;
2f9d49b4 247 $arg->{verbose} = $verbose;
139271cd 248 $arg->{safe} = defined $safe ? $safe : 0;
cac619e8 249
139271cd
CBW
250 if ( defined($paths) and length($paths) ) {
251 $paths = [$paths] unless UNIVERSAL::isa( $paths, 'ARRAY' );
cac619e8
DL
252 }
253 else {
139271cd 254 _carp("No root path(s) specified\n");
cac619e8
DL
255 return 0;
256 }
257 }
258 else {
139271cd
CBW
259 my %args_permitted = map { $_ => 1 } ( qw|
260 error
261 keep_root
262 result
263 safe
264 verbose
265 | );
266 my @bad_args = ();
30cf951a 267 $arg = pop @_;
139271cd
CBW
268 for my $k (sort keys %{$arg}) {
269 push @bad_args, $k unless $args_permitted{$k};
270 }
271 _carp("Unrecognized option(s) passed to remove_tree(): @bad_args")
272 if @bad_args;
273 ${ $arg->{error} } = [] if exists $arg->{error};
274 ${ $arg->{result} } = [] if exists $arg->{result};
cac619e8
DL
275 $paths = [@_];
276 }
277
278 $arg->{prefix} = '';
279 $arg->{depth} = 0;
280
3f083399 281 my @clean_path;
cac619e8 282 $arg->{cwd} = getcwd() or do {
139271cd 283 _error( $arg, "cannot fetch initial working directory" );
cac619e8
DL
284 return 0;
285 };
139271cd 286 for ( $arg->{cwd} ) { /\A(.*)\Z/s; $_ = $1 } # untaint
cac619e8 287
3f083399 288 for my $p (@$paths) {
139271cd 289
c42ebacb 290 # need to fixup case and map \ to / on Windows
139271cd
CBW
291 my $ortho_root = _IS_MSWIN32 ? _slash_lc($p) : $p;
292 my $ortho_cwd =
293 _IS_MSWIN32 ? _slash_lc( $arg->{cwd} ) : $arg->{cwd};
c42ebacb 294 my $ortho_root_length = length($ortho_root);
139271cd
CBW
295 $ortho_root_length-- if _IS_VMS; # don't compare '.' with ']'
296 if ( $ortho_root_length && _is_subdir( $ortho_root, $ortho_cwd ) ) {
c42ebacb 297 local $! = 0;
139271cd 298 _error( $arg, "cannot remove path when cwd is $arg->{cwd}", $p );
c42ebacb
CB
299 next;
300 }
301
139271cd
CBW
302 if (_IS_MACOS) {
303 $p = ":$p" unless $p =~ /:/;
304 $p .= ":" unless $p =~ /:\z/;
3f083399 305 }
139271cd 306 elsif ( _IS_MSWIN32 ) {
3f083399
NC
307 $p =~ s{[/\\]\z}{};
308 }
309 else {
310 $p =~ s{/\z}{};
311 }
312 push @clean_path, $p;
313 }
314
139271cd
CBW
315 @{$arg}{qw(device inode perm)} = ( lstat $arg->{cwd} )[ 0, 1 ] or do {
316 _error( $arg, "cannot stat initial working directory", $arg->{cwd} );
cac619e8
DL
317 return 0;
318 };
319
139271cd 320 return _rmtree( $arg, \@clean_path );
cac619e8
DL
321}
322
323sub _rmtree {
324 my $arg = shift;
325 my $paths = shift;
326
327 my $count = 0;
328 my $curdir = File::Spec->curdir();
329 my $updir = File::Spec->updir();
330
139271cd
CBW
331 my ( @files, $root );
332 ROOT_DIR:
333 foreach my $root (@$paths) {
334
cac619e8
DL
335 # since we chdir into each directory, it may not be obvious
336 # to figure out where we are if we generate a message about
337 # a file name. We therefore construct a semi-canonical
338 # filename, anchored from the directory being unlinked (as
339 # opposed to being truly canonical, anchored from the root (/).
340
139271cd
CBW
341 my $canon =
342 $arg->{prefix}
343 ? File::Spec->catfile( $arg->{prefix}, $root )
344 : $root;
cac619e8 345
139271cd
CBW
346 my ( $ldev, $lino, $perm ) = ( lstat $root )[ 0, 1, 2 ]
347 or ( _error( $arg, "$root", $root ) and next ROOT_DIR );
cac619e8
DL
348
349 if ( -d _ ) {
139271cd
CBW
350 $root = VMS::Filespec::vmspath( VMS::Filespec::pathify($root) )
351 if _IS_VMS;
352
353 if ( !chdir($root) ) {
839bc55a 354
cac619e8
DL
355 # see if we can escalate privileges to get in
356 # (e.g. funny protection mask such as -w- instead of rwx)
139271cd
CBW
357 $perm &= oct '7777';
358 my $nperm = $perm | oct '700';
359 if (
360 !(
361 $arg->{safe}
362 or $nperm == $perm
363 or chmod( $nperm, $root )
364 )
365 )
366 {
367 _error( $arg,
368 "cannot make child directory read-write-exec", $canon );
cac619e8
DL
369 next ROOT_DIR;
370 }
139271cd
CBW
371 elsif ( !chdir($root) ) {
372 _error( $arg, "cannot chdir to child", $canon );
cac619e8
DL
373 next ROOT_DIR;
374 }
375 }
376
139271cd
CBW
377 my ( $cur_dev, $cur_inode, $perm ) = ( stat $curdir )[ 0, 1, 2 ]
378 or do {
379 _error( $arg, "cannot stat current working directory", $canon );
cac619e8 380 next ROOT_DIR;
139271cd 381 };
cac619e8 382
139271cd
CBW
383 if (_NEED_STAT_CHECK) {
384 ( $ldev eq $cur_dev and $lino eq $cur_inode )
385 or _croak(
386"directory $canon changed before chdir, expected dev=$ldev ino=$lino, actual dev=$cur_dev ino=$cur_inode, aborting."
387 );
839bc55a 388 }
cac619e8 389
139271cd
CBW
390 $perm &= oct '7777'; # don't forget setuid, setgid, sticky bits
391 my $nperm = $perm | oct '700';
cac619e8
DL
392
393 # notabene: 0700 is for making readable in the first place,
394 # it's also intended to change it to writable in case we have
139271cd 395 # to recurse in which case we are better than rm -rf for
cac619e8
DL
396 # subtrees with strange permissions
397
139271cd
CBW
398 if (
399 !(
400 $arg->{safe}
401 or $nperm == $perm
402 or chmod( $nperm, $curdir )
403 )
404 )
405 {
406 _error( $arg, "cannot make directory read+writeable", $canon );
cac619e8
DL
407 $nperm = $perm;
408 }
409
410 my $d;
411 $d = gensym() if $] < 5.006;
139271cd
CBW
412 if ( !opendir $d, $curdir ) {
413 _error( $arg, "cannot opendir", $canon );
cac619e8
DL
414 @files = ();
415 }
416 else {
139271cd
CBW
417 if ( !defined ${^TAINT} or ${^TAINT} ) {
418 # Blindly untaint dir names if taint mode is active
cac619e8
DL
419 @files = map { /\A(.*)\z/s; $1 } readdir $d;
420 }
421 else {
422 @files = readdir $d;
423 }
424 closedir $d;
425 }
426
139271cd
CBW
427 if (_IS_VMS) {
428
cac619e8
DL
429 # Deleting large numbers of files from VMS Files-11
430 # filesystems is faster if done in reverse ASCIIbetical order.
431 # include '.' to '.;' from blead patch #31775
139271cd 432 @files = map { $_ eq '.' ? '.;' : $_ } reverse @files;
cac619e8 433 }
839bc55a 434
139271cd 435 @files = grep { $_ ne $updir and $_ ne $curdir } @files;
cac619e8
DL
436
437 if (@files) {
139271cd 438
cac619e8
DL
439 # remove the contained files before the directory itself
440 my $narg = {%$arg};
139271cd
CBW
441 @{$narg}{qw(device inode cwd prefix depth)} =
442 ( $cur_dev, $cur_inode, $updir, $canon, $arg->{depth} + 1 );
443 $count += _rmtree( $narg, \@files );
cac619e8
DL
444 }
445
446 # restore directory permissions of required now (in case the rmdir
447 # below fails), while we are still in the directory and may do so
448 # without a race via '.'
139271cd
CBW
449 if ( $nperm != $perm and not chmod( $perm, $curdir ) ) {
450 _error( $arg, "cannot reset chmod", $canon );
cac619e8
DL
451 }
452
453 # don't leave the client code in an unexpected directory
139271cd
CBW
454 chdir( $arg->{cwd} )
455 or
456 _croak("cannot chdir to $arg->{cwd} from $canon: $!, aborting.");
cac619e8
DL
457
458 # ensure that a chdir upwards didn't take us somewhere other
459 # than we expected (see CVE-2002-0435)
139271cd
CBW
460 ( $cur_dev, $cur_inode ) = ( stat $curdir )[ 0, 1 ]
461 or _croak(
462 "cannot stat prior working directory $arg->{cwd}: $!, aborting."
463 );
464
465 if (_NEED_STAT_CHECK) {
466 ( $arg->{device} eq $cur_dev and $arg->{inode} eq $cur_inode )
467 or _croak( "previous directory $arg->{cwd} "
468 . "changed before entering $canon, "
469 . "expected dev=$ldev ino=$lino, "
470 . "actual dev=$cur_dev ino=$cur_inode, aborting."
471 );
839bc55a 472 }
cac619e8 473
139271cd
CBW
474 if ( $arg->{depth} or !$arg->{keep_root} ) {
475 if ( $arg->{safe}
476 && ( _IS_VMS
477 ? !&VMS::Filespec::candelete($root)
478 : !-w $root ) )
479 {
cac619e8
DL
480 print "skipped $root\n" if $arg->{verbose};
481 next ROOT_DIR;
482 }
139271cd
CBW
483 if ( _FORCE_WRITABLE and !chmod $perm | oct '700', $root ) {
484 _error( $arg, "cannot make directory writeable", $canon );
30cf951a 485 }
cac619e8 486 print "rmdir $root\n" if $arg->{verbose};
139271cd
CBW
487 if ( rmdir $root ) {
488 push @{ ${ $arg->{result} } }, $root if $arg->{result};
cac619e8
DL
489 ++$count;
490 }
491 else {
139271cd
CBW
492 _error( $arg, "cannot remove directory", $canon );
493 if (
494 _FORCE_WRITABLE
495 && !chmod( $perm,
496 ( _IS_VMS ? VMS::Filespec::fileify($root) : $root )
497 )
498 )
499 {
500 _error(
501 $arg,
502 sprintf( "cannot restore permissions to 0%o",
503 $perm ),
504 $canon
505 );
cac619e8
DL
506 }
507 }
508 }
509 }
510 else {
511 # not a directory
cac619e8 512 $root = VMS::Filespec::vmsify("./$root")
139271cd
CBW
513 if _IS_VMS
514 && !File::Spec->file_name_is_absolute($root)
515 && ( $root !~ m/(?<!\^)[\]>]+/ ); # not already in VMS syntax
516
517 if (
518 $arg->{safe}
519 && (
520 _IS_VMS
521 ? !&VMS::Filespec::candelete($root)
522 : !( -l $root || -w $root )
523 )
524 )
cac619e8
DL
525 {
526 print "skipped $root\n" if $arg->{verbose};
527 next ROOT_DIR;
528 }
529
139271cd
CBW
530 my $nperm = $perm & oct '7777' | oct '600';
531 if ( _FORCE_WRITABLE
532 and $nperm != $perm
533 and not chmod $nperm, $root )
534 {
535 _error( $arg, "cannot make file writeable", $canon );
30cf951a 536 }
cac619e8 537 print "unlink $canon\n" if $arg->{verbose};
139271cd 538
cac619e8 539 # delete all versions under VMS
139271cd
CBW
540 for ( ; ; ) {
541 if ( unlink $root ) {
542 push @{ ${ $arg->{result} } }, $root if $arg->{result};
cac619e8
DL
543 }
544 else {
139271cd
CBW
545 _error( $arg, "cannot unlink file", $canon );
546 _FORCE_WRITABLE and chmod( $perm, $root )
547 or _error( $arg,
548 sprintf( "cannot restore permissions to 0%o", $perm ),
549 $canon );
cac619e8
DL
550 last;
551 }
552 ++$count;
139271cd 553 last unless _IS_VMS && lstat $root;
cac619e8
DL
554 }
555 }
556 }
cac619e8
DL
557 return $count;
558}
559
3f083399 560sub _slash_lc {
139271cd 561
3f083399
NC
562 # fix up slashes and case on MSWin32 so that we can determine that
563 # c:\path\to\dir is underneath C:/Path/To
564 my $path = shift;
565 $path =~ tr{\\}{/};
566 return lc($path);
567}
568
cac619e8 5691;
139271cd 570
cac619e8
DL
571__END__
572
fed7345c
AD
573=head1 NAME
574
12c2e016
DL
575File::Path - Create or remove directory trees
576
577=head1 VERSION
578
8f65b4cd
CBW
579This document describes version 2.09 of File::Path, released
5802013-01-17.
fed7345c
AD
581
582=head1 SYNOPSIS
583
2f9d49b4 584 use File::Path qw(make_path remove_tree);
fed7345c 585
139271cd
CBW
586 @created = make_path('foo/bar/baz', '/zug/zwang');
587 @created = make_path('foo/bar/baz', '/zug/zwang', {
2f9d49b4
NC
588 verbose => 1,
589 mode => 0711,
590 });
139271cd
CBW
591 make_path('foo/bar/baz', '/zug/zwang', {
592 chmod => 0777,
593 });
12c2e016 594
139271cd
CBW
595 $removed_count = remove_tree('foo/bar/baz', '/zug/zwang');
596 $removed_count = remove_tree('foo/bar/baz', '/zug/zwang', {
2f9d49b4
NC
597 verbose => 1,
598 error => \my $err_list,
599 });
12c2e016 600
30cf951a 601 # legacy (interface promoted before v2.00)
139271cd
CBW
602 @created = mkpath('/foo/bar/baz');
603 @created = mkpath('/foo/bar/baz', 1, 0711);
604 @created = mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);
605 $removed_count = rmtree('foo/bar/baz', 1, 1);
606 $removed_count = rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);
fed7345c 607
30cf951a 608 # legacy (interface promoted before v2.06)
139271cd
CBW
609 @created = mkpath('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
610 $removed_count = rmtree('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
12c2e016 611
2f9d49b4 612=head1 DESCRIPTION
12c2e016 613
2f9d49b4
NC
614This module provide a convenient way to create directories of
615arbitrary depth and to delete an entire directory subtree from the
616filesystem.
3f083399 617
2f9d49b4 618The following functions are provided:
3f083399 619
2f9d49b4 620=over
12c2e016 621
2f9d49b4 622=item make_path( $dir1, $dir2, .... )
12c2e016 623
2f9d49b4 624=item make_path( $dir1, $dir2, ...., \%opts )
3f083399 625
2f9d49b4
NC
626The C<make_path> function creates the given directories if they don't
627exists before, much like the Unix command C<mkdir -p>.
3f083399 628
2f9d49b4
NC
629The function accepts a list of directories to be created. Its
630behaviour may be tuned by an optional hashref appearing as the last
631parameter on the call.
12c2e016 632
3f083399 633The function returns the list of directories actually created during
2f9d49b4 634the call; in scalar context the number of directories created.
3f083399 635
2f9d49b4 636The following keys are recognised in the option hash:
3f083399 637
2f9d49b4 638=over
12c2e016 639
2f9d49b4 640=item mode => $num
12c2e016 641
0b3d36bd
DL
642The numeric permissions mode to apply to each created directory
643(defaults to 0777), to be modified by the current C<umask>. If the
644directory already exists (and thus does not need to be created),
645the permissions will not be modified.
646
647C<mask> is recognised as an alias for this parameter.
12c2e016 648
139271cd
CBW
649=item chmod => $num
650
651Takes a numeric mode to apply to each created directory (not
652modified by the current C<umask>). If the directory already exists
653(and thus does not need to be created), the permissions will
654not be modified.
655
2f9d49b4 656=item verbose => $bool
12c2e016 657
30cf951a 658If present, will cause C<make_path> to print the name of each directory
12c2e016
DL
659as it is created. By default nothing is printed.
660
2f9d49b4 661=item error => \$err
12c2e016 662
2f9d49b4
NC
663If present, it should be a reference to a scalar.
664This scalar will be made to reference an array, which will
867b93c3
NC
665be used to store any errors that are encountered. See the L</"ERROR
666HANDLING"> section for more information.
12c2e016 667
0b3d36bd 668If this parameter is not used, certain error conditions may raise
139271cd 669a fatal error that will cause the program to halt, unless trapped
0b3d36bd 670in an C<eval> block.
12c2e016 671
30eb83e1
RGS
672=item owner => $owner
673
674=item user => $owner
675
676=item uid => $owner
677
678If present, will cause any created directory to be owned by C<$owner>.
679If the value is numeric, it will be interpreted as a uid, otherwise
680as username is assumed. An error will be issued if the username cannot be
681mapped to a uid, or the uid does not exist, or the process lacks the
682privileges to change ownership.
683
139271cd 684Ownership of directories that already exist will not be changed.
30eb83e1
RGS
685
686C<user> and C<uid> are aliases of C<owner>.
687
688=item group => $group
689
690If present, will cause any created directory to be owned by the group C<$group>.
691If the value is numeric, it will be interpreted as a gid, otherwise
692as group name is assumed. An error will be issued if the group name cannot be
693mapped to a gid, or the gid does not exist, or the process lacks the
694privileges to change group ownership.
695
139271cd 696Group ownership of directories that already exist will not be changed.
30eb83e1
RGS
697
698 make_path '/var/tmp/webcache', {owner=>'nobody', group=>'nogroup'};
699
12c2e016
DL
700=back
701
30cf951a
NC
702=item mkpath( $dir )
703
2f9d49b4 704=item mkpath( $dir, $verbose, $mode )
3f083399 705
2f9d49b4 706=item mkpath( [$dir1, $dir2,...], $verbose, $mode )
3f083399 707
2f9d49b4 708=item mkpath( $dir1, $dir2,..., \%opt )
3f083399 709
867b93c3
NC
710The mkpath() function provide the legacy interface of make_path() with
711a different interpretation of the arguments passed. The behaviour and
712return value of the function is otherwise identical to make_path().
12c2e016 713
2f9d49b4 714=item remove_tree( $dir1, $dir2, .... )
3f083399 715
2f9d49b4 716=item remove_tree( $dir1, $dir2, ...., \%opts )
3f083399 717
2f9d49b4
NC
718The C<remove_tree> function deletes the given directories and any
719files and subdirectories they might contain, much like the Unix
139271cd 720command C<rm -r> or the Windows commands C<rmdir /s> and C<rd /s>.
12c2e016 721
2f9d49b4
NC
722The function accepts a list of directories to be
723removed. Its behaviour may be tuned by an optional hashref
724appearing as the last parameter on the call.
725
726The functions returns the number of files successfully deleted.
727
728The following keys are recognised in the option hash:
729
730=over
731
732=item verbose => $bool
12c2e016 733
30cf951a 734If present, will cause C<remove_tree> to print the name of each file as
12c2e016
DL
735it is unlinked. By default nothing is printed.
736
2f9d49b4 737=item safe => $bool
12c2e016 738
30cf951a 739When set to a true value, will cause C<remove_tree> to skip the files
0b3d36bd 740for which the process lacks the required privileges needed to delete
5808899a
DL
741files, such as delete privileges on VMS. In other words, the code
742will make no attempt to alter file permissions. Thus, if the process
743is interrupted, no filesystem object will be left in a more
744permissive mode.
12c2e016 745
2f9d49b4 746=item keep_root => $bool
12c2e016 747
0b3d36bd
DL
748When set to a true value, will cause all files and subdirectories
749to be removed, except the initially specified directories. This comes
750in handy when cleaning out an application's scratch directory.
12c2e016 751
3f083399 752 remove_tree( '/tmp', {keep_root => 1} );
12c2e016 753
2f9d49b4 754=item result => \$res
12c2e016 755
2f9d49b4
NC
756If present, it should be a reference to a scalar.
757This scalar will be made to reference an array, which will
758be used to store all files and directories unlinked
867b93c3 759during the call. If nothing is unlinked, the array will be empty.
12c2e016 760
3f083399 761 remove_tree( '/tmp', {result => \my $list} );
12c2e016
DL
762 print "unlinked $_\n" for @$list;
763
0b3d36bd
DL
764This is a useful alternative to the C<verbose> key.
765
2f9d49b4 766=item error => \$err
12c2e016 767
2f9d49b4
NC
768If present, it should be a reference to a scalar.
769This scalar will be made to reference an array, which will
867b93c3
NC
770be used to store any errors that are encountered. See the L</"ERROR
771HANDLING"> section for more information.
12c2e016 772
0b3d36bd
DL
773Removing things is a much more dangerous proposition than
774creating things. As such, there are certain conditions that
30cf951a 775C<remove_tree> may encounter that are so dangerous that the only
0b3d36bd
DL
776sane action left is to kill the program.
777
778Use C<error> to trap all that is reasonable (problems with
779permissions and the like), and let it die if things get out
780of hand. This is the safest course of action.
12c2e016
DL
781
782=back
783
2f9d49b4 784=item rmtree( $dir )
fed7345c 785
2f9d49b4 786=item rmtree( $dir, $verbose, $safe )
fed7345c 787
2f9d49b4 788=item rmtree( [$dir1, $dir2,...], $verbose, $safe )
fed7345c 789
2f9d49b4 790=item rmtree( $dir1, $dir2,..., \%opt )
fed7345c 791
867b93c3
NC
792The rmtree() function provide the legacy interface of remove_tree()
793with a different interpretation of the arguments passed. The behaviour
794and return value of the function is otherwise identical to
795remove_tree().
fed7345c
AD
796
797=back
798
12c2e016
DL
799=head2 ERROR HANDLING
800
30cf951a
NC
801=over 4
802
803=item B<NOTE:>
804
805The following error handling mechanism is considered
806experimental and is subject to change pending feedback from
807users.
808
809=back
810
811If C<make_path> or C<remove_tree> encounter an error, a diagnostic
812message will be printed to C<STDERR> via C<carp> (for non-fatal
813errors), or via C<croak> (for fatal errors).
12c2e016
DL
814
815If this behaviour is not desirable, the C<error> attribute may be
816used to hold a reference to a variable, which will be used to store
867b93c3
NC
817the diagnostics. The variable is made a reference to an array of hash
818references. Each hash contain a single key/value pair where the key
819is the name of the file, and the value is the error message (including
820the contents of C<$!> when appropriate). If a general error is
821encountered the diagnostic key will be empty.
822
823An example usage looks like:
12c2e016 824
3f083399 825 remove_tree( 'foo/bar', 'bar/rat', {error => \my $err} );
867b93c3
NC
826 if (@$err) {
827 for my $diag (@$err) {
828 my ($file, $message) = %$diag;
829 if ($file eq '') {
830 print "general error: $message\n";
831 }
832 else {
833 print "problem unlinking $file: $message\n";
834 }
835 }
12c2e016 836 }
867b93c3
NC
837 else {
838 print "No error encountered\n";
12c2e016
DL
839 }
840
867b93c3
NC
841Note that if no errors are encountered, C<$err> will reference an
842empty array. This means that C<$err> will always end up TRUE; so you
139271cd 843need to test C<@$err> to determine if errors occurred.
867b93c3 844
12c2e016
DL
845=head2 NOTES
846
0b3d36bd
DL
847C<File::Path> blindly exports C<mkpath> and C<rmtree> into the
848current namespace. These days, this is considered bad style, but
849to change it now would break too much code. Nonetheless, you are
850invited to specify what it is you are expecting to use:
851
852 use File::Path 'rmtree';
853
3f083399
NC
854The routines C<make_path> and C<remove_tree> are B<not> exported
855by default. You must specify which ones you want to use.
e2ba98a1 856
3f083399 857 use File::Path 'remove_tree';
e2ba98a1 858
3f083399
NC
859Note that a side-effect of the above is that C<mkpath> and C<rmtree>
860are no longer exported at all. This is due to the way the C<Exporter>
861module works. If you are migrating a codebase to use the new
862interface, you will have to list everything explicitly. But that's
863just good practice anyway.
12c2e016 864
3f083399 865 use File::Path qw(remove_tree rmtree);
12c2e016 866
30eb83e1
RGS
867=head3 API CHANGES
868
869The API was changed in the 2.0 branch. For a time, C<mkpath> and
870C<rmtree> tried, unsuccessfully, to deal with the two different
871calling mechanisms. This approach was considered a failure.
872
873The new semantics are now only available with C<make_path> and
874C<remove_tree>. The old semantics are only available through
875C<mkpath> and C<rmtree>. Users are strongly encouraged to upgrade
876to at least 2.08 in order to avoid surprises.
877
0b3d36bd 878=head3 SECURITY CONSIDERATIONS
12c2e016 879
0b3d36bd
DL
880There were race conditions 1.x implementations of File::Path's
881C<rmtree> function (although sometimes patched depending on the OS
882distribution or platform). The 2.0 version contains code to avoid the
883problem mentioned in CVE-2002-0435.
12c2e016 884
0b3d36bd 885See the following pages for more information:
12c2e016 886
0b3d36bd
DL
887 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=286905
888 http://www.nntp.perl.org/group/perl.perl5.porters/2005/01/msg97623.html
889 http://www.debian.org/security/2005/dsa-696
12c2e016 890
5808899a 891Additionally, unless the C<safe> parameter is set (or the
37b1cd44 892third parameter in the traditional interface is TRUE), should a
30cf951a 893C<remove_tree> be interrupted, files that were originally in read-only
0b3d36bd
DL
894mode may now have their permissions set to a read-write (or "delete
895OK") mode.
96e4d5b1 896
b8d5f521
CW
897=head1 DIAGNOSTICS
898
0b3d36bd
DL
899FATAL errors will cause the program to halt (C<croak>), since the
900problem is so severe that it would be dangerous to continue. (This
901can always be trapped with C<eval>, but it's not a good idea. Under
902the circumstances, dying is the best thing to do).
903
904SEVERE errors may be trapped using the modern interface. If the
905they are not trapped, or the old interface is used, such an error
906will cause the program will halt.
907
908All other errors may be trapped using the modern interface, otherwise
909they will be C<carp>ed about. Program execution will not be halted.
910
b8d5f521
CW
911=over 4
912
37b1cd44 913=item mkdir [path]: [errmsg] (SEVERE)
0b3d36bd 914
867b93c3 915C<make_path> was unable to create the path. Probably some sort of
0b3d36bd
DL
916permissions error at the point of departure, or insufficient resources
917(such as free inodes on Unix).
918
919=item No root path(s) specified
920
867b93c3 921C<make_path> was not given any paths to create. This message is only
0b3d36bd
DL
922emitted if the routine is called with the traditional interface.
923The modern interface will remain silent if given nothing to do.
924
925=item No such file or directory
926
867b93c3 927On Windows, if C<make_path> gives you this warning, it may mean that
0b3d36bd
DL
928you have exceeded your filesystem's maximum path length.
929
930=item cannot fetch initial working directory: [errmsg]
931
30cf951a 932C<remove_tree> attempted to determine the initial directory by calling
0b3d36bd
DL
933C<Cwd::getcwd>, but the call failed for some reason. No attempt
934will be made to delete anything.
935
936=item cannot stat initial working directory: [errmsg]
937
30cf951a 938C<remove_tree> attempted to stat the initial directory (after having
0b3d36bd
DL
939successfully obtained its name via C<getcwd>), however, the call
940failed for some reason. No attempt will be made to delete anything.
941
942=item cannot chdir to [dir]: [errmsg]
943
30cf951a 944C<remove_tree> attempted to set the working directory in order to
0b3d36bd
DL
945begin deleting the objects therein, but was unsuccessful. This is
946usually a permissions issue. The routine will continue to delete
947other things, but this directory will be left intact.
948
3f083399 949=item directory [dir] changed before chdir, expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)
0b3d36bd 950
30cf951a 951C<remove_tree> recorded the device and inode of a directory, and then
0b3d36bd
DL
952moved into it. It then performed a C<stat> on the current directory
953and detected that the device and inode were no longer the same. As
954this is at the heart of the race condition problem, the program
955will die at this point.
956
957=item cannot make directory [dir] read+writeable: [errmsg]
958
30cf951a 959C<remove_tree> attempted to change the permissions on the current directory
0b3d36bd
DL
960to ensure that subsequent unlinkings would not run into problems,
961but was unable to do so. The permissions remain as they were, and
962the program will carry on, doing the best it can.
963
964=item cannot read [dir]: [errmsg]
965
30cf951a 966C<remove_tree> tried to read the contents of the directory in order
0b3d36bd
DL
967to acquire the names of the directory entries to be unlinked, but
968was unsuccessful. This is usually a permissions issue. The
969program will continue, but the files in this directory will remain
970after the call.
971
972=item cannot reset chmod [dir]: [errmsg]
973
30cf951a 974C<remove_tree>, after having deleted everything in a directory, attempted
cac619e8
DL
975to restore its permissions to the original state but failed. The
976directory may wind up being left behind.
12c2e016 977
c42ebacb
CB
978=item cannot remove [dir] when cwd is [dir]
979
980The current working directory of the program is F</some/path/to/here>
981and you are attempting to remove an ancestor, such as F</some/path>.
982The directory tree is left untouched.
983
984The solution is to C<chdir> out of the child directory to a place
985outside the directory tree to be removed.
986
cac619e8 987=item cannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting. (FATAL)
12c2e016 988
30cf951a 989C<remove_tree>, after having deleted everything and restored the permissions
3f083399
NC
990of a directory, was unable to chdir back to the parent. The program
991halts to avoid a race condition from occurring.
fed7345c 992
cac619e8 993=item cannot stat prior working directory [dir]: [errmsg], aborting. (FATAL)
0b3d36bd 994
30cf951a 995C<remove_tree> was unable to stat the parent directory after have returned
cac619e8
DL
996from the child. Since there is no way of knowing if we returned to
997where we think we should be (by comparing device and inode) the only
998way out is to C<croak>.
0b3d36bd 999
3f083399 1000=item previous directory [parent-dir] changed before entering [child-dir], expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)
0b3d36bd 1001
30cf951a 1002When C<remove_tree> returned from deleting files in a child directory, a
cac619e8
DL
1003check revealed that the parent directory it returned to wasn't the one
1004it started out from. This is considered a sign of malicious activity.
0b3d36bd 1005
cac619e8 1006=item cannot make directory [dir] writeable: [errmsg]
ee79a11f 1007
cac619e8 1008Just before removing a directory (after having successfully removed
30cf951a 1009everything it contained), C<remove_tree> attempted to set the permissions
cac619e8
DL
1010on the directory to ensure it could be removed and failed. Program
1011execution continues, but the directory may possibly not be deleted.
0b3d36bd 1012
cac619e8 1013=item cannot remove directory [dir]: [errmsg]
0b3d36bd 1014
30cf951a 1015C<remove_tree> attempted to remove a directory, but failed. This may because
cac619e8
DL
1016some objects that were unable to be removed remain in the directory, or
1017a permissions issue. The directory will be left behind.
0b3d36bd 1018
cac619e8 1019=item cannot restore permissions of [dir] to [0nnn]: [errmsg]
0b3d36bd 1020
30cf951a 1021After having failed to remove a directory, C<remove_tree> was unable to
cac619e8
DL
1022restore its permissions from a permissive state back to a possibly
1023more restrictive setting. (Permissions given in octal).
0b3d36bd 1024
cac619e8 1025=item cannot make file [file] writeable: [errmsg]
b5400373 1026
30cf951a 1027C<remove_tree> attempted to force the permissions of a file to ensure it
cac619e8
DL
1028could be deleted, but failed to do so. It will, however, still attempt
1029to unlink the file.
0b3d36bd 1030
cac619e8 1031=item cannot unlink file [file]: [errmsg]
0b3d36bd 1032
30cf951a 1033C<remove_tree> failed to remove a file. Probably a permissions issue.
0b3d36bd 1034
cac619e8 1035=item cannot restore permissions of [file] to [0nnn]: [errmsg]
0b3d36bd 1036
30cf951a 1037After having failed to remove a file, C<remove_tree> was also unable
cac619e8
DL
1038to restore the permissions on the file to a possibly less permissive
1039setting. (Permissions given in octal).
0b3d36bd 1040
30eb83e1
RGS
1041=item unable to map [owner] to a uid, ownership not changed");
1042
1043C<make_path> was instructed to give the ownership of created
1044directories to the symbolic name [owner], but C<getpwnam> did
1045not return the corresponding numeric uid. The directory will
1046be created, but ownership will not be changed.
1047
1048=item unable to map [group] to a gid, group ownership not changed
1049
1050C<make_path> was instructed to give the group ownership of created
1051directories to the symbolic name [group], but C<getgrnam> did
1052not return the corresponding numeric gid. The directory will
1053be created, but group ownership will not be changed.
1054
cac619e8 1055=back
12c2e016 1056
cac619e8 1057=head1 SEE ALSO
037c8c09 1058
cac619e8 1059=over 4
0b3d36bd 1060
cac619e8 1061=item *
0b3d36bd 1062
351a5cfe
DL
1063L<File::Remove>
1064
1065Allows files and directories to be moved to the Trashcan/Recycle
1066Bin (where they may later be restored if necessary) if the operating
1067system supports such functionality. This feature may one day be
1068made available directly in C<File::Path>.
1069
1070=item *
1071
cac619e8 1072L<File::Find::Rule>
0b3d36bd 1073
cac619e8
DL
1074When removing directory trees, if you want to examine each file to
1075decide whether to delete it (and possibly leaving large swathes
1076alone), F<File::Find::Rule> offers a convenient and flexible approach
1077to examining directory trees.
0b3d36bd 1078
cac619e8 1079=back
0b3d36bd 1080
139271cd
CBW
1081=head1 BUGS AND LIMITATIONS
1082
1083The following describes F<File::Path> limitations and how to report bugs.
1084
1085=head2 MULTITHREAD APPLICATIONS
1086
1087F<File::Path> B<rmtree> and B<remove_tree> will not work with multithreaded
1088applications due to its use of B<chdir>. At this time, no warning or error
1089results and you will certainly encounter unexpected results.
0b3d36bd 1090
139271cd
CBW
1091The implementation that surfaces this limitation may change in a future
1092release.
1093
1094=head2 NFS Mount Points
1095
1096F<File::Path> is not responsible for triggering the automounts, mirror mounts,
1097and the contents of network mounted filesystems. If your NFS implementation
1098requires an action to be performed on the filesystem in order for
1099F<File::Path> to perform operations, it is strongly suggested you assure
1100filesystem availability by reading the root of the mounted filesystem.
1101
1102=head2 REPORTING BUGS
1103
1104Please report all bugs on the RT queue, either via the web interface:
b5400373 1105
cac619e8 1106L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Path>
b5400373 1107
139271cd
CBW
1108or by email:
1109
1110 bug-File-Path@rt.cpan.org
1111
1112In either case, please B<attach> patches to the bug report rather than
1113including them inline in the web post or the body of the email.
1114
8f65b4cd
CBW
1115You can also send pull requests to the Github repository:
1116
139271cd 1117L<https://github.com/rpcme/File-Path>
8f65b4cd 1118
cac619e8 1119=head1 ACKNOWLEDGEMENTS
0b3d36bd 1120
cac619e8
DL
1121Paul Szabo identified the race condition originally, and Brendan
1122O'Dea wrote an implementation for Debian that addressed the problem.
1123That code was used as a basis for the current code. Their efforts
1124are greatly appreciated.
fed7345c 1125
867b93c3
NC
1126Gisle Aas made a number of improvements to the documentation for
11272.07 and his advice and assistance is also greatly appreciated.
1128
cac619e8 1129=head1 AUTHORS
fed7345c 1130
139271cd
CBW
1131Prior authors and maintainers: Tim Bunce, Charles Bailey, and
1132David Landgren <F<david@landgren.net>>.
1133
1134Current maintainers are Richard Elberger <F<riche@cpan.org>> and
1135James (Jim) Keenan <F<jkeenan@cpan.org>>.
1136
1137=head1 CONTRIBUTORS
1138
1139Contributors to File::Path, in alphabetical order.
1140
1141=over 1
1142
1143=item <F<bulkdd@cpan.org>>
1144
1145=item Richard Elberger <F<riche@cpan.org>>
1146
1147=item Ryan Yee <F<ryee@cpan.org>>
1148
1149=item Skye Shaw <F<shaw@cpan.org>>
1150
1151=item Tom Lutz <F<tommylutz@gmail.com>>
1152
1153=back
cac619e8
DL
1154
1155=head1 COPYRIGHT
1156
139271cd
CBW
1157This module is copyright (C) Charles Bailey, Tim Bunce, David Landgren,
1158James Keenan, and Richard Elberger 1995-2015. All rights reserved.
cac619e8
DL
1159
1160=head1 LICENSE
1161
1162This library is free software; you can redistribute it and/or modify
1163it under the same terms as Perl itself.
1164
1165=cut