1use 5.008001; 2use strict; 3use warnings; 4 5package Path::Tiny; 6# ABSTRACT: File path utility 7 8our $VERSION = '0.120'; 9 10# Dependencies 11use Config; 12use Exporter 5.57 (qw/import/); 13use File::Spec 0.86 (); # shipped with 5.8.1 14use Carp (); 15 16our @EXPORT = qw/path/; 17our @EXPORT_OK = qw/cwd rootdir tempfile tempdir/; 18 19use constant { 20 PATH => 0, 21 CANON => 1, 22 VOL => 2, 23 DIR => 3, 24 FILE => 4, 25 TEMP => 5, 26 IS_WIN32 => ( $^O eq 'MSWin32' ), 27}; 28 29use overload ( 30 q{""} => sub { $_[0]->[PATH] }, 31 bool => sub () { 1 }, 32 fallback => 1, 33); 34 35# FREEZE/THAW per Sereal/CBOR/Types::Serialiser protocol 36sub FREEZE { return $_[0]->[PATH] } 37sub THAW { return path( $_[2] ) } 38{ no warnings 'once'; *TO_JSON = *FREEZE }; 39 40my $HAS_UU; # has Unicode::UTF8; lazily populated 41 42sub _check_UU { 43 local $SIG{__DIE__}; # prevent outer handler from being called 44 !!eval { 45 require Unicode::UTF8; 46 Unicode::UTF8->VERSION(0.58); 47 1; 48 }; 49} 50 51my $HAS_PU; # has PerlIO::utf8_strict; lazily populated 52 53sub _check_PU { 54 local $SIG{__DIE__}; # prevent outer handler from being called 55 !!eval { 56 # MUST preload Encode or $SIG{__DIE__} localization fails 57 # on some Perl 5.8.8 (maybe other 5.8.*) compiled with -O2. 58 require Encode; 59 require PerlIO::utf8_strict; 60 PerlIO::utf8_strict->VERSION(0.003); 61 1; 62 }; 63} 64 65my $HAS_FLOCK = $Config{d_flock} || $Config{d_fcntl_can_lock} || $Config{d_lockf}; 66 67# notions of "root" directories differ on Win32: \\server\dir\ or C:\ or \ 68my $SLASH = qr{[\\/]}; 69my $NOTSLASH = qr{[^\\/]}; 70my $DRV_VOL = qr{[a-z]:}i; 71my $UNC_VOL = qr{$SLASH $SLASH $NOTSLASH+ $SLASH $NOTSLASH+}x; 72my $WIN32_ROOT = qr{(?: $UNC_VOL $SLASH | $DRV_VOL $SLASH | $SLASH )}x; 73 74sub _win32_vol { 75 my ( $path, $drv ) = @_; 76 require Cwd; 77 my $dcwd = eval { Cwd::getdcwd($drv) }; # C: -> C:\some\cwd 78 # getdcwd on non-existent drive returns empty string 79 # so just use the original drive Z: -> Z: 80 $dcwd = "$drv" unless defined $dcwd && length $dcwd; 81 # normalize dwcd to end with a slash: might be C:\some\cwd or D:\ or Z: 82 $dcwd =~ s{$SLASH?\z}{/}; 83 # make the path absolute with dcwd 84 $path =~ s{^$DRV_VOL}{$dcwd}; 85 return $path; 86} 87 88# This is a string test for before we have the object; see is_rootdir for well-formed 89# object test 90sub _is_root { 91 return IS_WIN32() ? ( $_[0] =~ /^$WIN32_ROOT\z/ ) : ( $_[0] eq '/' ); 92} 93 94BEGIN { 95 *_same = IS_WIN32() ? sub { lc( $_[0] ) eq lc( $_[1] ) } : sub { $_[0] eq $_[1] }; 96} 97 98# mode bits encoded for chmod in symbolic mode 99my %MODEBITS = ( om => 0007, gm => 0070, um => 0700 ); ## no critic 100{ my $m = 0; $MODEBITS{$_} = ( 1 << $m++ ) for qw/ox ow or gx gw gr ux uw ur/ }; 101 102sub _symbolic_chmod { 103 my ( $mode, $symbolic ) = @_; 104 for my $clause ( split /,\s*/, $symbolic ) { 105 if ( $clause =~ m{\A([augo]+)([=+-])([rwx]+)\z} ) { 106 my ( $who, $action, $perms ) = ( $1, $2, $3 ); 107 $who =~ s/a/ugo/g; 108 for my $w ( split //, $who ) { 109 my $p = 0; 110 $p |= $MODEBITS{"$w$_"} for split //, $perms; 111 if ( $action eq '=' ) { 112 $mode = ( $mode & ~$MODEBITS{"${w}m"} ) | $p; 113 } 114 else { 115 $mode = $action eq "+" ? ( $mode | $p ) : ( $mode & ~$p ); 116 } 117 } 118 } 119 else { 120 Carp::croak("Invalid mode clause '$clause' for chmod()"); 121 } 122 } 123 return $mode; 124} 125 126# flock doesn't work on NFS on BSD or on some filesystems like lustre. 127# Since program authors often can't control or detect that, we warn once 128# instead of being fatal if we can detect it and people who need it strict 129# can fatalize the 'flock' category 130 131#<<< No perltidy 132{ package flock; use warnings::register } 133#>>> 134 135my $WARNED_NO_FLOCK = 0; 136 137sub _throw { 138 my ( $self, $function, $file, $msg ) = @_; 139 if ( $function =~ /^flock/ 140 && $! =~ /operation not supported|function not implemented/i 141 && !warnings::fatal_enabled('flock') ) 142 { 143 if ( !$WARNED_NO_FLOCK ) { 144 warnings::warn( flock => "Flock not available: '$!': continuing in unsafe mode" ); 145 $WARNED_NO_FLOCK++; 146 } 147 } 148 else { 149 $msg = $! unless defined $msg; 150 Path::Tiny::Error->throw( $function, ( defined $file ? $file : $self->[PATH] ), 151 $msg ); 152 } 153 return; 154} 155 156# cheapo option validation 157sub _get_args { 158 my ( $raw, @valid ) = @_; 159 if ( defined($raw) && ref($raw) ne 'HASH' ) { 160 my ( undef, undef, undef, $called_as ) = caller(1); 161 $called_as =~ s{^.*::}{}; 162 Carp::croak("Options for $called_as must be a hash reference"); 163 } 164 my $cooked = {}; 165 for my $k (@valid) { 166 $cooked->{$k} = delete $raw->{$k} if exists $raw->{$k}; 167 } 168 if ( keys %$raw ) { 169 my ( undef, undef, undef, $called_as ) = caller(1); 170 $called_as =~ s{^.*::}{}; 171 Carp::croak( "Invalid option(s) for $called_as: " . join( ", ", keys %$raw ) ); 172 } 173 return $cooked; 174} 175 176#--------------------------------------------------------------------------# 177# Constructors 178#--------------------------------------------------------------------------# 179 180#pod =construct path 181#pod 182#pod $path = path("foo/bar"); 183#pod $path = path("/tmp", "file.txt"); # list 184#pod $path = path("."); # cwd 185#pod $path = path("~user/file.txt"); # tilde processing 186#pod 187#pod Constructs a C<Path::Tiny> object. It doesn't matter if you give a file or 188#pod directory path. It's still up to you to call directory-like methods only on 189#pod directories and file-like methods only on files. This function is exported 190#pod automatically by default. 191#pod 192#pod The first argument must be defined and have non-zero length or an exception 193#pod will be thrown. This prevents subtle, dangerous errors with code like 194#pod C<< path( maybe_undef() )->remove_tree >>. 195#pod 196#pod If the first component of the path is a tilde ('~') then the component will be 197#pod replaced with the output of C<glob('~')>. If the first component of the path 198#pod is a tilde followed by a user name then the component will be replaced with 199#pod output of C<glob('~username')>. Behaviour for non-existent users depends on 200#pod the output of C<glob> on the system. 201#pod 202#pod On Windows, if the path consists of a drive identifier without a path component 203#pod (C<C:> or C<D:>), it will be expanded to the absolute path of the current 204#pod directory on that volume using C<Cwd::getdcwd()>. 205#pod 206#pod If called with a single C<Path::Tiny> argument, the original is returned unless 207#pod the original is holding a temporary file or directory reference in which case a 208#pod stringified copy is made. 209#pod 210#pod $path = path("foo/bar"); 211#pod $temp = Path::Tiny->tempfile; 212#pod 213#pod $p2 = path($path); # like $p2 = $path 214#pod $t2 = path($temp); # like $t2 = path( "$temp" ) 215#pod 216#pod This optimizes copies without proliferating references unexpectedly if a copy is 217#pod made by code outside your control. 218#pod 219#pod Current API available since 0.017. 220#pod 221#pod =cut 222 223sub path { 224 my $path = shift; 225 Carp::croak("Path::Tiny paths require defined, positive-length parts") 226 unless 1 + @_ == grep { defined && length } $path, @_; 227 228 # non-temp Path::Tiny objects are effectively immutable and can be reused 229 if ( !@_ && ref($path) eq __PACKAGE__ && !$path->[TEMP] ) { 230 return $path; 231 } 232 233 # stringify objects 234 $path = "$path"; 235 236 # expand relative volume paths on windows; put trailing slash on UNC root 237 if ( IS_WIN32() ) { 238 $path = _win32_vol( $path, $1 ) if $path =~ m{^($DRV_VOL)(?:$NOTSLASH|\z)}; 239 $path .= "/" if $path =~ m{^$UNC_VOL\z}; 240 } 241 242 # concatenations stringifies objects, too 243 if (@_) { 244 $path .= ( _is_root($path) ? "" : "/" ) . join( "/", @_ ); 245 } 246 247 # canonicalize, but with unix slashes and put back trailing volume slash 248 my $cpath = $path = File::Spec->canonpath($path); 249 $path =~ tr[\\][/] if IS_WIN32(); 250 $path = "/" if $path eq '/..'; # for old File::Spec 251 $path .= "/" if IS_WIN32() && $path =~ m{^$UNC_VOL\z}; 252 253 # root paths must always have a trailing slash, but other paths must not 254 if ( _is_root($path) ) { 255 $path =~ s{/?\z}{/}; 256 } 257 else { 258 $path =~ s{/\z}{}; 259 } 260 261 # do any tilde expansions 262 if ( $path =~ m{^(~[^/]*).*} ) { 263 require File::Glob; 264 my ($homedir) = File::Glob::bsd_glob($1); 265 $homedir =~ tr[\\][/] if IS_WIN32(); 266 $path =~ s{^(~[^/]*)}{$homedir}; 267 } 268 269 bless [ $path, $cpath ], __PACKAGE__; 270} 271 272#pod =construct new 273#pod 274#pod $path = Path::Tiny->new("foo/bar"); 275#pod 276#pod This is just like C<path>, but with method call overhead. (Why would you 277#pod do that?) 278#pod 279#pod Current API available since 0.001. 280#pod 281#pod =cut 282 283sub new { shift; path(@_) } 284 285#pod =construct cwd 286#pod 287#pod $path = Path::Tiny->cwd; # path( Cwd::getcwd ) 288#pod $path = cwd; # optional export 289#pod 290#pod Gives you the absolute path to the current directory as a C<Path::Tiny> object. 291#pod This is slightly faster than C<< path(".")->absolute >>. 292#pod 293#pod C<cwd> may be exported on request and used as a function instead of as a 294#pod method. 295#pod 296#pod Current API available since 0.018. 297#pod 298#pod =cut 299 300sub cwd { 301 require Cwd; 302 return path( Cwd::getcwd() ); 303} 304 305#pod =construct rootdir 306#pod 307#pod $path = Path::Tiny->rootdir; # / 308#pod $path = rootdir; # optional export 309#pod 310#pod Gives you C<< File::Spec->rootdir >> as a C<Path::Tiny> object if you're too 311#pod picky for C<path("/")>. 312#pod 313#pod C<rootdir> may be exported on request and used as a function instead of as a 314#pod method. 315#pod 316#pod Current API available since 0.018. 317#pod 318#pod =cut 319 320sub rootdir { path( File::Spec->rootdir ) } 321 322#pod =construct tempfile, tempdir 323#pod 324#pod $temp = Path::Tiny->tempfile( @options ); 325#pod $temp = Path::Tiny->tempdir( @options ); 326#pod $temp = $dirpath->tempfile( @options ); 327#pod $temp = $dirpath->tempdir( @options ); 328#pod $temp = tempfile( @options ); # optional export 329#pod $temp = tempdir( @options ); # optional export 330#pod 331#pod C<tempfile> passes the options to C<< File::Temp->new >> and returns a C<Path::Tiny> 332#pod object with the file name. The C<TMPDIR> option is enabled by default. 333#pod 334#pod The resulting C<File::Temp> object is cached. When the C<Path::Tiny> object is 335#pod destroyed, the C<File::Temp> object will be as well. 336#pod 337#pod C<File::Temp> annoyingly requires you to specify a custom template in slightly 338#pod different ways depending on which function or method you call, but 339#pod C<Path::Tiny> lets you ignore that and can take either a leading template or a 340#pod C<TEMPLATE> option and does the right thing. 341#pod 342#pod $temp = Path::Tiny->tempfile( "customXXXXXXXX" ); # ok 343#pod $temp = Path::Tiny->tempfile( TEMPLATE => "customXXXXXXXX" ); # ok 344#pod 345#pod The tempfile path object will be normalized to have an absolute path, even if 346#pod created in a relative directory using C<DIR>. If you want it to have 347#pod the C<realpath> instead, pass a leading options hash like this: 348#pod 349#pod $real_temp = tempfile({realpath => 1}, @options); 350#pod 351#pod C<tempdir> is just like C<tempfile>, except it calls 352#pod C<< File::Temp->newdir >> instead. 353#pod 354#pod Both C<tempfile> and C<tempdir> may be exported on request and used as 355#pod functions instead of as methods. 356#pod 357#pod The methods can be called on an instances representing a 358#pod directory. In this case, the directory is used as the base to create the 359#pod temporary file/directory, setting the C<DIR> option in File::Temp. 360#pod 361#pod my $target_dir = path('/to/destination'); 362#pod my $tempfile = $target_dir->tempfile('foobarXXXXXX'); 363#pod $tempfile->spew('A lot of data...'); # not atomic 364#pod $tempfile->rename($target_dir->child('foobar')); # hopefully atomic 365#pod 366#pod In this case, any value set for option C<DIR> is ignored. 367#pod 368#pod B<Note>: for tempfiles, the filehandles from File::Temp are closed and not 369#pod reused. This is not as secure as using File::Temp handles directly, but is 370#pod less prone to deadlocks or access problems on some platforms. Think of what 371#pod C<Path::Tiny> gives you to be just a temporary file B<name> that gets cleaned 372#pod up. 373#pod 374#pod B<Note 2>: if you don't want these cleaned up automatically when the object 375#pod is destroyed, File::Temp requires different options for directories and 376#pod files. Use C<< CLEANUP => 0 >> for directories and C<< UNLINK => 0 >> for 377#pod files. 378#pod 379#pod B<Note 3>: Don't lose the temporary object by chaining a method call instead 380#pod of storing it: 381#pod 382#pod my $lost = tempdir()->child("foo"); # tempdir cleaned up right away 383#pod 384#pod B<Note 4>: The cached object may be accessed with the L</cached_temp> method. 385#pod Keeping a reference to, or modifying the cached object may break the 386#pod behavior documented above and is not supported. Use at your own risk. 387#pod 388#pod Current API available since 0.119. 389#pod 390#pod =cut 391 392sub tempfile { 393 my ( $opts, $maybe_template, $args ) 394 = _parse_file_temp_args(tempfile => @_); 395 396 # File::Temp->new demands TEMPLATE 397 $args->{TEMPLATE} = $maybe_template->[0] if @$maybe_template; 398 399 require File::Temp; 400 my $temp = File::Temp->new( TMPDIR => 1, %$args ); 401 close $temp; 402 my $self = $opts->{realpath} ? path($temp)->realpath : path($temp)->absolute; 403 $self->[TEMP] = $temp; # keep object alive while we are 404 return $self; 405} 406 407sub tempdir { 408 my ( $opts, $maybe_template, $args ) 409 = _parse_file_temp_args(tempdir => @_); 410 411 require File::Temp; 412 my $temp = File::Temp->newdir( @$maybe_template, TMPDIR => 1, %$args ); 413 my $self = $opts->{realpath} ? path($temp)->realpath : path($temp)->absolute; 414 $self->[TEMP] = $temp; # keep object alive while we are 415 # Some ActiveState Perls for Windows break Cwd in ways that lead 416 # File::Temp to get confused about what path to remove; this 417 # monkey-patches the object with our own view of the absolute path 418 $temp->{REALNAME} = $self->[CANON] if IS_WIN32; 419 return $self; 420} 421 422# normalize the various ways File::Temp does templates 423sub _parse_file_temp_args { 424 my $called_as = shift; 425 if ( @_ && $_[0] eq 'Path::Tiny' ) { shift } # class method 426 elsif ( @_ && eval{$_[0]->isa('Path::Tiny')} ) { 427 my $dir = shift; 428 if (! $dir->is_dir) { 429 $dir->_throw( $called_as, $dir, "is not a directory object" ); 430 } 431 push @_, DIR => $dir->stringify; # no overriding 432 } 433 my $opts = ( @_ && ref $_[0] eq 'HASH' ) ? shift @_ : {}; 434 $opts = _get_args( $opts, qw/realpath/ ); 435 436 my $leading_template = ( scalar(@_) % 2 == 1 ? shift(@_) : '' ); 437 my %args = @_; 438 %args = map { uc($_), $args{$_} } keys %args; 439 my @template = ( 440 exists $args{TEMPLATE} ? delete $args{TEMPLATE} 441 : $leading_template ? $leading_template 442 : () 443 ); 444 445 return ( $opts, \@template, \%args ); 446} 447 448#--------------------------------------------------------------------------# 449# Private methods 450#--------------------------------------------------------------------------# 451 452sub _splitpath { 453 my ($self) = @_; 454 @{$self}[ VOL, DIR, FILE ] = File::Spec->splitpath( $self->[PATH] ); 455} 456 457sub _resolve_symlinks { 458 my ($self) = @_; 459 my $new = $self; 460 my ( $count, %seen ) = 0; 461 while ( -l $new->[PATH] ) { 462 if ( $seen{ $new->[PATH] }++ ) { 463 $self->_throw( 'readlink', $self->[PATH], "symlink loop detected" ); 464 } 465 if ( ++$count > 100 ) { 466 $self->_throw( 'readlink', $self->[PATH], "maximum symlink depth exceeded" ); 467 } 468 my $resolved = readlink $new->[PATH] or $new->_throw( 'readlink', $new->[PATH] ); 469 $resolved = path($resolved); 470 $new = $resolved->is_absolute ? $resolved : $new->sibling($resolved); 471 } 472 return $new; 473} 474 475#--------------------------------------------------------------------------# 476# Public methods 477#--------------------------------------------------------------------------# 478 479#pod =method absolute 480#pod 481#pod $abs = path("foo/bar")->absolute; 482#pod $abs = path("foo/bar")->absolute("/tmp"); 483#pod 484#pod Returns a new C<Path::Tiny> object with an absolute path (or itself if already 485#pod absolute). If no argument is given, the current directory is used as the 486#pod absolute base path. If an argument is given, it will be converted to an 487#pod absolute path (if it is not already) and used as the absolute base path. 488#pod 489#pod This will not resolve upward directories ("foo/../bar") unless C<canonpath> 490#pod in L<File::Spec> would normally do so on your platform. If you need them 491#pod resolved, you must call the more expensive C<realpath> method instead. 492#pod 493#pod On Windows, an absolute path without a volume component will have it added 494#pod based on the current drive. 495#pod 496#pod Current API available since 0.101. 497#pod 498#pod =cut 499 500sub absolute { 501 my ( $self, $base ) = @_; 502 503 # absolute paths handled differently by OS 504 if (IS_WIN32) { 505 return $self if length $self->volume; 506 # add missing volume 507 if ( $self->is_absolute ) { 508 require Cwd; 509 # use Win32::GetCwd not Cwd::getdcwd because we're sure 510 # to have the former but not necessarily the latter 511 my ($drv) = Win32::GetCwd() =~ /^($DRV_VOL | $UNC_VOL)/x; 512 return path( $drv . $self->[PATH] ); 513 } 514 } 515 else { 516 return $self if $self->is_absolute; 517 } 518 519 # no base means use current directory as base 520 require Cwd; 521 return path( Cwd::getcwd(), $_[0]->[PATH] ) unless defined $base; 522 523 # relative base should be made absolute; we check is_absolute rather 524 # than unconditionally make base absolute so that "/foo" doesn't become 525 # "C:/foo" on Windows. 526 $base = path($base); 527 return path( ( $base->is_absolute ? $base : $base->absolute ), $_[0]->[PATH] ); 528} 529 530#pod =method append, append_raw, append_utf8 531#pod 532#pod path("foo.txt")->append(@data); 533#pod path("foo.txt")->append(\@data); 534#pod path("foo.txt")->append({binmode => ":raw"}, @data); 535#pod path("foo.txt")->append_raw(@data); 536#pod path("foo.txt")->append_utf8(@data); 537#pod 538#pod Appends data to a file. The file is locked with C<flock> prior to writing 539#pod and closed afterwards. An optional hash reference may be used to pass 540#pod options. Valid options are: 541#pod 542#pod =for :list 543#pod * C<binmode>: passed to C<binmode()> on the handle used for writing. 544#pod * C<truncate>: truncates the file after locking and before appending 545#pod 546#pod The C<truncate> option is a way to replace the contents of a file 547#pod B<in place>, unlike L</spew> which writes to a temporary file and then 548#pod replaces the original (if it exists). 549#pod 550#pod C<append_raw> is like C<append> with a C<binmode> of C<:unix> for fast, 551#pod unbuffered, raw write. 552#pod 553#pod C<append_utf8> is like C<append> with a C<binmode> of 554#pod C<:unix:encoding(UTF-8)> (or L<PerlIO::utf8_strict>). If L<Unicode::UTF8> 555#pod 0.58+ is installed, a raw append will be done instead on the data encoded 556#pod with C<Unicode::UTF8>. 557#pod 558#pod Current API available since 0.060. 559#pod 560#pod =cut 561 562sub append { 563 my ( $self, @data ) = @_; 564 my $args = ( @data && ref $data[0] eq 'HASH' ) ? shift @data : {}; 565 $args = _get_args( $args, qw/binmode truncate/ ); 566 my $binmode = $args->{binmode}; 567 $binmode = ( ( caller(0) )[10] || {} )->{'open>'} unless defined $binmode; 568 my $mode = $args->{truncate} ? ">" : ">>"; 569 my $fh = $self->filehandle( { locked => 1 }, $mode, $binmode ); 570 print {$fh} map { ref eq 'ARRAY' ? @$_ : $_ } @data; 571 close $fh or $self->_throw('close'); 572} 573 574sub append_raw { 575 my ( $self, @data ) = @_; 576 my $args = ( @data && ref $data[0] eq 'HASH' ) ? shift @data : {}; 577 $args = _get_args( $args, qw/binmode truncate/ ); 578 $args->{binmode} = ':unix'; 579 append( $self, $args, @data ); 580} 581 582sub append_utf8 { 583 my ( $self, @data ) = @_; 584 my $args = ( @data && ref $data[0] eq 'HASH' ) ? shift @data : {}; 585 $args = _get_args( $args, qw/binmode truncate/ ); 586 if ( defined($HAS_UU) ? $HAS_UU : ( $HAS_UU = _check_UU() ) ) { 587 $args->{binmode} = ":unix"; 588 append( $self, $args, map { Unicode::UTF8::encode_utf8($_) } @data ); 589 } 590 elsif ( defined($HAS_PU) ? $HAS_PU : ( $HAS_PU = _check_PU() ) ) { 591 $args->{binmode} = ":unix:utf8_strict"; 592 append( $self, $args, @data ); 593 } 594 else { 595 $args->{binmode} = ":unix:encoding(UTF-8)"; 596 append( $self, $args, @data ); 597 } 598} 599 600#pod =method assert 601#pod 602#pod $path = path("foo.txt")->assert( sub { $_->exists } ); 603#pod 604#pod Returns the invocant after asserting that a code reference argument returns 605#pod true. When the assertion code reference runs, it will have the invocant 606#pod object in the C<$_> variable. If it returns false, an exception will be 607#pod thrown. The assertion code reference may also throw its own exception. 608#pod 609#pod If no assertion is provided, the invocant is returned without error. 610#pod 611#pod Current API available since 0.062. 612#pod 613#pod =cut 614 615sub assert { 616 my ( $self, $assertion ) = @_; 617 return $self unless $assertion; 618 if ( ref $assertion eq 'CODE' ) { 619 local $_ = $self; 620 $assertion->() 621 or Path::Tiny::Error->throw( "assert", $self->[PATH], "failed assertion" ); 622 } 623 else { 624 Carp::croak("argument to assert must be a code reference argument"); 625 } 626 return $self; 627} 628 629#pod =method basename 630#pod 631#pod $name = path("foo/bar.txt")->basename; # bar.txt 632#pod $name = path("foo.txt")->basename('.txt'); # foo 633#pod $name = path("foo.txt")->basename(qr/.txt/); # foo 634#pod $name = path("foo.txt")->basename(@suffixes); 635#pod 636#pod Returns the file portion or last directory portion of a path. 637#pod 638#pod Given a list of suffixes as strings or regular expressions, any that match at 639#pod the end of the file portion or last directory portion will be removed before 640#pod the result is returned. 641#pod 642#pod Current API available since 0.054. 643#pod 644#pod =cut 645 646sub basename { 647 my ( $self, @suffixes ) = @_; 648 $self->_splitpath unless defined $self->[FILE]; 649 my $file = $self->[FILE]; 650 for my $s (@suffixes) { 651 my $re = ref($s) eq 'Regexp' ? qr/$s\z/ : qr/\Q$s\E\z/; 652 last if $file =~ s/$re//; 653 } 654 return $file; 655} 656 657#pod =method canonpath 658#pod 659#pod $canonical = path("foo/bar")->canonpath; # foo\bar on Windows 660#pod 661#pod Returns a string with the canonical format of the path name for 662#pod the platform. In particular, this means directory separators 663#pod will be C<\> on Windows. 664#pod 665#pod Current API available since 0.001. 666#pod 667#pod =cut 668 669sub canonpath { $_[0]->[CANON] } 670 671#pod =method cached_temp 672#pod 673#pod Returns the cached C<File::Temp> or C<File::Temp::Dir> object if the 674#pod C<Path::Tiny> object was created with C</tempfile> or C</tempdir>. 675#pod If there is no such object, this method throws. 676#pod 677#pod B<WARNING>: Keeping a reference to, or modifying the cached object may 678#pod break the behavior documented for temporary files and directories created 679#pod with C<Path::Tiny> and is not supported. Use at your own risk. 680#pod 681#pod Current API available since 0.101. 682#pod 683#pod =cut 684 685sub cached_temp { 686 my $self = shift; 687 $self->_throw( "cached_temp", $self, "has no cached File::Temp object" ) 688 unless defined $self->[TEMP]; 689 return $self->[TEMP]; 690} 691 692#pod =method child 693#pod 694#pod $file = path("/tmp")->child("foo.txt"); # "/tmp/foo.txt" 695#pod $file = path("/tmp")->child(@parts); 696#pod 697#pod Returns a new C<Path::Tiny> object relative to the original. Works 698#pod like C<catfile> or C<catdir> from File::Spec, but without caring about 699#pod file or directories. 700#pod 701#pod B<WARNING>: because the argument could contain C<..> or refer to symlinks, 702#pod there is no guarantee that the new path refers to an actual descendent of 703#pod the original. If this is important to you, transform parent and child with 704#pod L</realpath> and check them with L</subsumes>. 705#pod 706#pod Current API available since 0.001. 707#pod 708#pod =cut 709 710sub child { 711 my ( $self, @parts ) = @_; 712 return path( $self->[PATH], @parts ); 713} 714 715#pod =method children 716#pod 717#pod @paths = path("/tmp")->children; 718#pod @paths = path("/tmp")->children( qr/\.txt\z/ ); 719#pod 720#pod Returns a list of C<Path::Tiny> objects for all files and directories 721#pod within a directory. Excludes "." and ".." automatically. 722#pod 723#pod If an optional C<qr//> argument is provided, it only returns objects for child 724#pod names that match the given regular expression. Only the base name is used 725#pod for matching: 726#pod 727#pod @paths = path("/tmp")->children( qr/^foo/ ); 728#pod # matches children like the glob foo* 729#pod 730#pod Current API available since 0.028. 731#pod 732#pod =cut 733 734sub children { 735 my ( $self, $filter ) = @_; 736 my $dh; 737 opendir $dh, $self->[PATH] or $self->_throw('opendir'); 738 my @children = readdir $dh; 739 closedir $dh or $self->_throw('closedir'); 740 741 if ( not defined $filter ) { 742 @children = grep { $_ ne '.' && $_ ne '..' } @children; 743 } 744 elsif ( $filter && ref($filter) eq 'Regexp' ) { 745 @children = grep { $_ ne '.' && $_ ne '..' && $_ =~ $filter } @children; 746 } 747 else { 748 Carp::croak("Invalid argument '$filter' for children()"); 749 } 750 751 return map { path( $self->[PATH], $_ ) } @children; 752} 753 754#pod =method chmod 755#pod 756#pod path("foo.txt")->chmod(0777); 757#pod path("foo.txt")->chmod("0755"); 758#pod path("foo.txt")->chmod("go-w"); 759#pod path("foo.txt")->chmod("a=r,u+wx"); 760#pod 761#pod Sets file or directory permissions. The argument can be a numeric mode, a 762#pod octal string beginning with a "0" or a limited subset of the symbolic mode use 763#pod by F</bin/chmod>. 764#pod 765#pod The symbolic mode must be a comma-delimited list of mode clauses. Clauses must 766#pod match C<< qr/\A([augo]+)([=+-])([rwx]+)\z/ >>, which defines "who", "op" and 767#pod "perms" parameters for each clause. Unlike F</bin/chmod>, all three parameters 768#pod are required for each clause, multiple ops are not allowed and permissions 769#pod C<stugoX> are not supported. (See L<File::chmod> for more complex needs.) 770#pod 771#pod Current API available since 0.053. 772#pod 773#pod =cut 774 775sub chmod { 776 my ( $self, $new_mode ) = @_; 777 778 my $mode; 779 if ( $new_mode =~ /\d/ ) { 780 $mode = ( $new_mode =~ /^0/ ? oct($new_mode) : $new_mode ); 781 } 782 elsif ( $new_mode =~ /[=+-]/ ) { 783 $mode = _symbolic_chmod( $self->stat->mode & 07777, $new_mode ); ## no critic 784 } 785 else { 786 Carp::croak("Invalid mode argument '$new_mode' for chmod()"); 787 } 788 789 CORE::chmod( $mode, $self->[PATH] ) or $self->_throw("chmod"); 790 791 return 1; 792} 793 794#pod =method copy 795#pod 796#pod path("/tmp/foo.txt")->copy("/tmp/bar.txt"); 797#pod 798#pod Copies the current path to the given destination using L<File::Copy>'s 799#pod C<copy> function. Upon success, returns the C<Path::Tiny> object for the 800#pod newly copied file. 801#pod 802#pod Current API available since 0.070. 803#pod 804#pod =cut 805 806# XXX do recursively for directories? 807sub copy { 808 my ( $self, $dest ) = @_; 809 require File::Copy; 810 File::Copy::copy( $self->[PATH], $dest ) 811 or Carp::croak("copy failed for $self to $dest: $!"); 812 813 return -d $dest ? path( $dest, $self->basename ) : path($dest); 814} 815 816#pod =method digest 817#pod 818#pod $obj = path("/tmp/foo.txt")->digest; # SHA-256 819#pod $obj = path("/tmp/foo.txt")->digest("MD5"); # user-selected 820#pod $obj = path("/tmp/foo.txt")->digest( { chunk_size => 1e6 }, "MD5" ); 821#pod 822#pod Returns a hexadecimal digest for a file. An optional hash reference of options may 823#pod be given. The only option is C<chunk_size>. If C<chunk_size> is given, that many 824#pod bytes will be read at a time. If not provided, the entire file will be slurped 825#pod into memory to compute the digest. 826#pod 827#pod Any subsequent arguments are passed to the constructor for L<Digest> to select 828#pod an algorithm. If no arguments are given, the default is SHA-256. 829#pod 830#pod Current API available since 0.056. 831#pod 832#pod =cut 833 834sub digest { 835 my ( $self, @opts ) = @_; 836 my $args = ( @opts && ref $opts[0] eq 'HASH' ) ? shift @opts : {}; 837 $args = _get_args( $args, qw/chunk_size/ ); 838 unshift @opts, 'SHA-256' unless @opts; 839 require Digest; 840 my $digest = Digest->new(@opts); 841 if ( $args->{chunk_size} ) { 842 my $fh = $self->filehandle( { locked => 1 }, "<", ":unix" ); 843 my $buf; 844 $digest->add($buf) while read $fh, $buf, $args->{chunk_size}; 845 } 846 else { 847 $digest->add( $self->slurp_raw ); 848 } 849 return $digest->hexdigest; 850} 851 852#pod =method dirname (deprecated) 853#pod 854#pod $name = path("/tmp/foo.txt")->dirname; # "/tmp/" 855#pod 856#pod Returns the directory portion you would get from calling 857#pod C<< File::Spec->splitpath( $path->stringify ) >> or C<"."> for a path without a 858#pod parent directory portion. Because L<File::Spec> is inconsistent, the result 859#pod might or might not have a trailing slash. Because of this, this method is 860#pod B<deprecated>. 861#pod 862#pod A better, more consistently approach is likely C<< $path->parent->stringify >>, 863#pod which will not have a trailing slash except for a root directory. 864#pod 865#pod Deprecated in 0.056. 866#pod 867#pod =cut 868 869sub dirname { 870 my ($self) = @_; 871 $self->_splitpath unless defined $self->[DIR]; 872 return length $self->[DIR] ? $self->[DIR] : "."; 873} 874 875#pod =method edit, edit_raw, edit_utf8 876#pod 877#pod path("foo.txt")->edit( \&callback, $options ); 878#pod path("foo.txt")->edit_utf8( \&callback ); 879#pod path("foo.txt")->edit_raw( \&callback ); 880#pod 881#pod These are convenience methods that allow "editing" a file using a single 882#pod callback argument. They slurp the file using C<slurp>, place the contents 883#pod inside a localized C<$_> variable, call the callback function (without 884#pod arguments), and then write C<$_> (presumably mutated) back to the 885#pod file with C<spew>. 886#pod 887#pod An optional hash reference may be used to pass options. The only option is 888#pod C<binmode>, which is passed to C<slurp> and C<spew>. 889#pod 890#pod C<edit_utf8> and C<edit_raw> act like their respective C<slurp_*> and 891#pod C<spew_*> methods. 892#pod 893#pod Current API available since 0.077. 894#pod 895#pod =cut 896 897sub edit { 898 my $self = shift; 899 my $cb = shift; 900 my $args = _get_args( shift, qw/binmode/ ); 901 Carp::croak("Callback for edit() must be a code reference") 902 unless defined($cb) && ref($cb) eq 'CODE'; 903 904 local $_ = 905 $self->slurp( exists( $args->{binmode} ) ? { binmode => $args->{binmode} } : () ); 906 $cb->(); 907 $self->spew( $args, $_ ); 908 909 return; 910} 911 912# this is done long-hand to benefit from slurp_utf8 optimizations 913sub edit_utf8 { 914 my ( $self, $cb ) = @_; 915 Carp::croak("Callback for edit_utf8() must be a code reference") 916 unless defined($cb) && ref($cb) eq 'CODE'; 917 918 local $_ = $self->slurp_utf8; 919 $cb->(); 920 $self->spew_utf8($_); 921 922 return; 923} 924 925sub edit_raw { $_[2] = { binmode => ":unix" }; goto &edit } 926 927#pod =method edit_lines, edit_lines_utf8, edit_lines_raw 928#pod 929#pod path("foo.txt")->edit_lines( \&callback, $options ); 930#pod path("foo.txt")->edit_lines_utf8( \&callback ); 931#pod path("foo.txt")->edit_lines_raw( \&callback ); 932#pod 933#pod These are convenience methods that allow "editing" a file's lines using a 934#pod single callback argument. They iterate over the file: for each line, the 935#pod line is put into a localized C<$_> variable, the callback function is 936#pod executed (without arguments) and then C<$_> is written to a temporary file. 937#pod When iteration is finished, the temporary file is atomically renamed over 938#pod the original. 939#pod 940#pod An optional hash reference may be used to pass options. The only option is 941#pod C<binmode>, which is passed to the method that open handles for reading and 942#pod writing. 943#pod 944#pod C<edit_lines_utf8> and C<edit_lines_raw> act like their respective 945#pod C<slurp_*> and C<spew_*> methods. 946#pod 947#pod Current API available since 0.077. 948#pod 949#pod =cut 950 951sub edit_lines { 952 my $self = shift; 953 my $cb = shift; 954 my $args = _get_args( shift, qw/binmode/ ); 955 Carp::croak("Callback for edit_lines() must be a code reference") 956 unless defined($cb) && ref($cb) eq 'CODE'; 957 958 my $binmode = $args->{binmode}; 959 # get default binmode from caller's lexical scope (see "perldoc open") 960 $binmode = ( ( caller(0) )[10] || {} )->{'open>'} unless defined $binmode; 961 962 # writing need to follow the link and create the tempfile in the same 963 # dir for later atomic rename 964 my $resolved_path = $self->_resolve_symlinks; 965 my $temp = path( $resolved_path . $$ . int( rand( 2**31 ) ) ); 966 967 my $temp_fh = $temp->filehandle( { exclusive => 1, locked => 1 }, ">", $binmode ); 968 my $in_fh = $self->filehandle( { locked => 1 }, '<', $binmode ); 969 970 local $_; 971 while (<$in_fh>) { 972 $cb->(); 973 $temp_fh->print($_); 974 } 975 976 close $temp_fh or $self->_throw( 'close', $temp ); 977 close $in_fh or $self->_throw('close'); 978 979 return $temp->move($resolved_path); 980} 981 982sub edit_lines_raw { $_[2] = { binmode => ":unix" }; goto &edit_lines } 983 984sub edit_lines_utf8 { 985 $_[2] = { binmode => ":raw:encoding(UTF-8)" }; 986 goto &edit_lines; 987} 988 989#pod =method exists, is_file, is_dir 990#pod 991#pod if ( path("/tmp")->exists ) { ... } # -e 992#pod if ( path("/tmp")->is_dir ) { ... } # -d 993#pod if ( path("/tmp")->is_file ) { ... } # -e && ! -d 994#pod 995#pod Implements file test operations, this means the file or directory actually has 996#pod to exist on the filesystem. Until then, it's just a path. 997#pod 998#pod B<Note>: C<is_file> is not C<-f> because C<-f> is not the opposite of C<-d>. 999#pod C<-f> means "plain file", excluding symlinks, devices, etc. that often can be 1000#pod read just like files. 1001#pod 1002#pod Use C<-f> instead if you really mean to check for a plain file. 1003#pod 1004#pod Current API available since 0.053. 1005#pod 1006#pod =cut 1007 1008sub exists { -e $_[0]->[PATH] } 1009 1010sub is_file { -e $_[0]->[PATH] && !-d _ } 1011 1012sub is_dir { -d $_[0]->[PATH] } 1013 1014#pod =method filehandle 1015#pod 1016#pod $fh = path("/tmp/foo.txt")->filehandle($mode, $binmode); 1017#pod $fh = path("/tmp/foo.txt")->filehandle({ locked => 1 }, $mode, $binmode); 1018#pod $fh = path("/tmp/foo.txt")->filehandle({ exclusive => 1 }, $mode, $binmode); 1019#pod 1020#pod Returns an open file handle. The C<$mode> argument must be a Perl-style 1021#pod read/write mode string ("<" ,">", ">>", etc.). If a C<$binmode> 1022#pod is given, it is set during the C<open> call. 1023#pod 1024#pod An optional hash reference may be used to pass options. 1025#pod 1026#pod The C<locked> option governs file locking; if true, handles opened for writing, 1027#pod appending or read-write are locked with C<LOCK_EX>; otherwise, they are 1028#pod locked with C<LOCK_SH>. When using C<locked>, ">" or "+>" modes will delay 1029#pod truncation until after the lock is acquired. 1030#pod 1031#pod The C<exclusive> option causes the open() call to fail if the file already 1032#pod exists. This corresponds to the O_EXCL flag to sysopen / open(2). 1033#pod C<exclusive> implies C<locked> and will set it for you if you forget it. 1034#pod 1035#pod See C<openr>, C<openw>, C<openrw>, and C<opena> for sugar. 1036#pod 1037#pod Current API available since 0.066. 1038#pod 1039#pod =cut 1040 1041# Note: must put binmode on open line, not subsequent binmode() call, so things 1042# like ":unix" actually stop perlio/crlf from being added 1043 1044sub filehandle { 1045 my ( $self, @args ) = @_; 1046 my $args = ( @args && ref $args[0] eq 'HASH' ) ? shift @args : {}; 1047 $args = _get_args( $args, qw/locked exclusive/ ); 1048 $args->{locked} = 1 if $args->{exclusive}; 1049 my ( $opentype, $binmode ) = @args; 1050 1051 $opentype = "<" unless defined $opentype; 1052 Carp::croak("Invalid file mode '$opentype'") 1053 unless grep { $opentype eq $_ } qw/< +< > +> >> +>>/; 1054 1055 $binmode = ( ( caller(0) )[10] || {} )->{ 'open' . substr( $opentype, -1, 1 ) } 1056 unless defined $binmode; 1057 $binmode = "" unless defined $binmode; 1058 1059 my ( $fh, $lock, $trunc ); 1060 if ( $HAS_FLOCK && $args->{locked} && !$ENV{PERL_PATH_TINY_NO_FLOCK} ) { 1061 require Fcntl; 1062 # truncating file modes shouldn't truncate until lock acquired 1063 if ( grep { $opentype eq $_ } qw( > +> ) ) { 1064 # sysopen in write mode without truncation 1065 my $flags = $opentype eq ">" ? Fcntl::O_WRONLY() : Fcntl::O_RDWR(); 1066 $flags |= Fcntl::O_CREAT(); 1067 $flags |= Fcntl::O_EXCL() if $args->{exclusive}; 1068 sysopen( $fh, $self->[PATH], $flags ) or $self->_throw("sysopen"); 1069 1070 # fix up the binmode since sysopen() can't specify layers like 1071 # open() and binmode() can't start with just :unix like open() 1072 if ( $binmode =~ s/^:unix// ) { 1073 # eliminate pseudo-layers 1074 binmode( $fh, ":raw" ) or $self->_throw("binmode (:raw)"); 1075 # strip off real layers until only :unix is left 1076 while ( 1 < ( my $layers =()= PerlIO::get_layers( $fh, output => 1 ) ) ) { 1077 binmode( $fh, ":pop" ) or $self->_throw("binmode (:pop)"); 1078 } 1079 } 1080 1081 # apply any remaining binmode layers 1082 if ( length $binmode ) { 1083 binmode( $fh, $binmode ) or $self->_throw("binmode ($binmode)"); 1084 } 1085 1086 # ask for lock and truncation 1087 $lock = Fcntl::LOCK_EX(); 1088 $trunc = 1; 1089 } 1090 elsif ( $^O eq 'aix' && $opentype eq "<" ) { 1091 # AIX can only lock write handles, so upgrade to RW and LOCK_EX if 1092 # the file is writable; otherwise give up on locking. N.B. 1093 # checking -w before open to determine the open mode is an 1094 # unavoidable race condition 1095 if ( -w $self->[PATH] ) { 1096 $opentype = "+<"; 1097 $lock = Fcntl::LOCK_EX(); 1098 } 1099 } 1100 else { 1101 $lock = $opentype eq "<" ? Fcntl::LOCK_SH() : Fcntl::LOCK_EX(); 1102 } 1103 } 1104 1105 unless ($fh) { 1106 my $mode = $opentype . $binmode; 1107 open $fh, $mode, $self->[PATH] or $self->_throw("open ($mode)"); 1108 } 1109 1110 do { flock( $fh, $lock ) or $self->_throw("flock ($lock)") } if $lock; 1111 do { truncate( $fh, 0 ) or $self->_throw("truncate") } if $trunc; 1112 1113 return $fh; 1114} 1115 1116#pod =method is_absolute, is_relative 1117#pod 1118#pod if ( path("/tmp")->is_absolute ) { ... } 1119#pod if ( path("/tmp")->is_relative ) { ... } 1120#pod 1121#pod Booleans for whether the path appears absolute or relative. 1122#pod 1123#pod Current API available since 0.001. 1124#pod 1125#pod =cut 1126 1127sub is_absolute { substr( $_[0]->dirname, 0, 1 ) eq '/' } 1128 1129sub is_relative { substr( $_[0]->dirname, 0, 1 ) ne '/' } 1130 1131#pod =method is_rootdir 1132#pod 1133#pod while ( ! $path->is_rootdir ) { 1134#pod $path = $path->parent; 1135#pod ... 1136#pod } 1137#pod 1138#pod Boolean for whether the path is the root directory of the volume. I.e. the 1139#pod C<dirname> is C<q[/]> and the C<basename> is C<q[]>. 1140#pod 1141#pod This works even on C<MSWin32> with drives and UNC volumes: 1142#pod 1143#pod path("C:/")->is_rootdir; # true 1144#pod path("//server/share/")->is_rootdir; #true 1145#pod 1146#pod Current API available since 0.038. 1147#pod 1148#pod =cut 1149 1150sub is_rootdir { 1151 my ($self) = @_; 1152 $self->_splitpath unless defined $self->[DIR]; 1153 return $self->[DIR] eq '/' && $self->[FILE] eq ''; 1154} 1155 1156#pod =method iterator 1157#pod 1158#pod $iter = path("/tmp")->iterator( \%options ); 1159#pod 1160#pod Returns a code reference that walks a directory lazily. Each invocation 1161#pod returns a C<Path::Tiny> object or undef when the iterator is exhausted. 1162#pod 1163#pod $iter = path("/tmp")->iterator; 1164#pod while ( $path = $iter->() ) { 1165#pod ... 1166#pod } 1167#pod 1168#pod The current and parent directory entries ("." and "..") will not 1169#pod be included. 1170#pod 1171#pod If the C<recurse> option is true, the iterator will walk the directory 1172#pod recursively, breadth-first. If the C<follow_symlinks> option is also true, 1173#pod directory links will be followed recursively. There is no protection against 1174#pod loops when following links. If a directory is not readable, it will not be 1175#pod followed. 1176#pod 1177#pod The default is the same as: 1178#pod 1179#pod $iter = path("/tmp")->iterator( { 1180#pod recurse => 0, 1181#pod follow_symlinks => 0, 1182#pod } ); 1183#pod 1184#pod For a more powerful, recursive iterator with built-in loop avoidance, see 1185#pod L<Path::Iterator::Rule>. 1186#pod 1187#pod See also L</visit>. 1188#pod 1189#pod Current API available since 0.016. 1190#pod 1191#pod =cut 1192 1193sub iterator { 1194 my $self = shift; 1195 my $args = _get_args( shift, qw/recurse follow_symlinks/ ); 1196 my @dirs = $self; 1197 my $current; 1198 return sub { 1199 my $next; 1200 while (@dirs) { 1201 if ( ref $dirs[0] eq 'Path::Tiny' ) { 1202 if ( !-r $dirs[0] ) { 1203 # Directory is missing or not readable, so skip it. There 1204 # is still a race condition possible between the check and 1205 # the opendir, but we can't easily differentiate between 1206 # error cases that are OK to skip and those that we want 1207 # to be exceptions, so we live with the race and let opendir 1208 # be fatal. 1209 shift @dirs and next; 1210 } 1211 $current = $dirs[0]; 1212 my $dh; 1213 opendir( $dh, $current->[PATH] ) 1214 or $self->_throw( 'opendir', $current->[PATH] ); 1215 $dirs[0] = $dh; 1216 if ( -l $current->[PATH] && !$args->{follow_symlinks} ) { 1217 # Symlink attack! It was a real dir, but is now a symlink! 1218 # N.B. we check *after* opendir so the attacker has to win 1219 # two races: replace dir with symlink before opendir and 1220 # replace symlink with dir before -l check above 1221 shift @dirs and next; 1222 } 1223 } 1224 while ( defined( $next = readdir $dirs[0] ) ) { 1225 next if $next eq '.' || $next eq '..'; 1226 my $path = $current->child($next); 1227 push @dirs, $path 1228 if $args->{recurse} && -d $path && !( !$args->{follow_symlinks} && -l $path ); 1229 return $path; 1230 } 1231 shift @dirs; 1232 } 1233 return; 1234 }; 1235} 1236 1237#pod =method lines, lines_raw, lines_utf8 1238#pod 1239#pod @contents = path("/tmp/foo.txt")->lines; 1240#pod @contents = path("/tmp/foo.txt")->lines(\%options); 1241#pod @contents = path("/tmp/foo.txt")->lines_raw; 1242#pod @contents = path("/tmp/foo.txt")->lines_utf8; 1243#pod 1244#pod @contents = path("/tmp/foo.txt")->lines( { chomp => 1, count => 4 } ); 1245#pod 1246#pod Returns a list of lines from a file. Optionally takes a hash-reference of 1247#pod options. Valid options are C<binmode>, C<count> and C<chomp>. 1248#pod 1249#pod If C<binmode> is provided, it will be set on the handle prior to reading. 1250#pod 1251#pod If a positive C<count> is provided, that many lines will be returned from the 1252#pod start of the file. If a negative C<count> is provided, the entire file will be 1253#pod read, but only C<abs(count)> will be kept and returned. If C<abs(count)> 1254#pod exceeds the number of lines in the file, all lines will be returned. 1255#pod 1256#pod If C<chomp> is set, any end-of-line character sequences (C<CR>, C<CRLF>, or 1257#pod C<LF>) will be removed from the lines returned. 1258#pod 1259#pod Because the return is a list, C<lines> in scalar context will return the number 1260#pod of lines (and throw away the data). 1261#pod 1262#pod $number_of_lines = path("/tmp/foo.txt")->lines; 1263#pod 1264#pod C<lines_raw> is like C<lines> with a C<binmode> of C<:raw>. We use C<:raw> 1265#pod instead of C<:unix> so PerlIO buffering can manage reading by line. 1266#pod 1267#pod C<lines_utf8> is like C<lines> with a C<binmode> of C<:raw:encoding(UTF-8)> 1268#pod (or L<PerlIO::utf8_strict>). If L<Unicode::UTF8> 0.58+ is installed, a raw 1269#pod UTF-8 slurp will be done and then the lines will be split. This is 1270#pod actually faster than relying on C<:encoding(UTF-8)>, though a bit memory 1271#pod intensive. If memory use is a concern, consider C<openr_utf8> and 1272#pod iterating directly on the handle. 1273#pod 1274#pod Current API available since 0.065. 1275#pod 1276#pod =cut 1277 1278sub lines { 1279 my $self = shift; 1280 my $args = _get_args( shift, qw/binmode chomp count/ ); 1281 my $binmode = $args->{binmode}; 1282 $binmode = ( ( caller(0) )[10] || {} )->{'open<'} unless defined $binmode; 1283 my $fh = $self->filehandle( { locked => 1 }, "<", $binmode ); 1284 my $chomp = $args->{chomp}; 1285 # XXX more efficient to read @lines then chomp(@lines) vs map? 1286 if ( $args->{count} ) { 1287 my ( $counter, $mod, @result ) = ( 0, abs( $args->{count} ) ); 1288 while ( my $line = <$fh> ) { 1289 $line =~ s/(?:\x{0d}?\x{0a}|\x{0d})\z// if $chomp; 1290 $result[ $counter++ ] = $line; 1291 # for positive count, terminate after right number of lines 1292 last if $counter == $args->{count}; 1293 # for negative count, eventually wrap around in the result array 1294 $counter %= $mod; 1295 } 1296 # reorder results if full and wrapped somewhere in the middle 1297 splice( @result, 0, 0, splice( @result, $counter ) ) 1298 if @result == $mod && $counter % $mod; 1299 return @result; 1300 } 1301 elsif ($chomp) { 1302 return map { s/(?:\x{0d}?\x{0a}|\x{0d})\z//; $_ } <$fh>; ## no critic 1303 } 1304 else { 1305 return wantarray ? <$fh> : ( my $count =()= <$fh> ); 1306 } 1307} 1308 1309sub lines_raw { 1310 my $self = shift; 1311 my $args = _get_args( shift, qw/binmode chomp count/ ); 1312 if ( $args->{chomp} && !$args->{count} ) { 1313 return split /\n/, slurp_raw($self); ## no critic 1314 } 1315 else { 1316 $args->{binmode} = ":raw"; 1317 return lines( $self, $args ); 1318 } 1319} 1320 1321my $CRLF = qr/(?:\x{0d}?\x{0a}|\x{0d})/; 1322 1323sub lines_utf8 { 1324 my $self = shift; 1325 my $args = _get_args( shift, qw/binmode chomp count/ ); 1326 if ( ( defined($HAS_UU) ? $HAS_UU : ( $HAS_UU = _check_UU() ) ) 1327 && $args->{chomp} 1328 && !$args->{count} ) 1329 { 1330 my $slurp = slurp_utf8($self); 1331 $slurp =~ s/$CRLF\z//; # like chomp, but full CR?LF|CR 1332 return split $CRLF, $slurp, -1; ## no critic 1333 } 1334 elsif ( defined($HAS_PU) ? $HAS_PU : ( $HAS_PU = _check_PU() ) ) { 1335 $args->{binmode} = ":unix:utf8_strict"; 1336 return lines( $self, $args ); 1337 } 1338 else { 1339 $args->{binmode} = ":raw:encoding(UTF-8)"; 1340 return lines( $self, $args ); 1341 } 1342} 1343 1344#pod =method mkpath 1345#pod 1346#pod path("foo/bar/baz")->mkpath; 1347#pod path("foo/bar/baz")->mkpath( \%options ); 1348#pod 1349#pod Like calling C<make_path> from L<File::Path>. An optional hash reference 1350#pod is passed through to C<make_path>. Errors will be trapped and an exception 1351#pod thrown. Returns the list of directories created or an empty list if 1352#pod the directories already exist, just like C<make_path>. 1353#pod 1354#pod Current API available since 0.001. 1355#pod 1356#pod =cut 1357 1358sub mkpath { 1359 my ( $self, $args ) = @_; 1360 $args = {} unless ref $args eq 'HASH'; 1361 my $err; 1362 $args->{error} = \$err unless defined $args->{error}; 1363 require File::Path; 1364 my @dirs = File::Path::make_path( $self->[PATH], $args ); 1365 if ( $err && @$err ) { 1366 my ( $file, $message ) = %{ $err->[0] }; 1367 Carp::croak("mkpath failed for $file: $message"); 1368 } 1369 return @dirs; 1370} 1371 1372#pod =method move 1373#pod 1374#pod path("foo.txt")->move("bar.txt"); 1375#pod 1376#pod Move the current path to the given destination path using Perl's 1377#pod built-in L<rename|perlfunc/rename> function. Returns the result 1378#pod of the C<rename> function (except it throws an exception if it fails). 1379#pod 1380#pod Current API available since 0.001. 1381#pod 1382#pod =cut 1383 1384sub move { 1385 my ( $self, $dst ) = @_; 1386 1387 return rename( $self->[PATH], $dst ) 1388 || $self->_throw( 'rename', $self->[PATH] . "' -> '$dst" ); 1389} 1390 1391#pod =method openr, openw, openrw, opena 1392#pod 1393#pod $fh = path("foo.txt")->openr($binmode); # read 1394#pod $fh = path("foo.txt")->openr_raw; 1395#pod $fh = path("foo.txt")->openr_utf8; 1396#pod 1397#pod $fh = path("foo.txt")->openw($binmode); # write 1398#pod $fh = path("foo.txt")->openw_raw; 1399#pod $fh = path("foo.txt")->openw_utf8; 1400#pod 1401#pod $fh = path("foo.txt")->opena($binmode); # append 1402#pod $fh = path("foo.txt")->opena_raw; 1403#pod $fh = path("foo.txt")->opena_utf8; 1404#pod 1405#pod $fh = path("foo.txt")->openrw($binmode); # read/write 1406#pod $fh = path("foo.txt")->openrw_raw; 1407#pod $fh = path("foo.txt")->openrw_utf8; 1408#pod 1409#pod Returns a file handle opened in the specified mode. The C<openr> style methods 1410#pod take a single C<binmode> argument. All of the C<open*> methods have 1411#pod C<open*_raw> and C<open*_utf8> equivalents that use C<:raw> and 1412#pod C<:raw:encoding(UTF-8)>, respectively. 1413#pod 1414#pod An optional hash reference may be used to pass options. The only option is 1415#pod C<locked>. If true, handles opened for writing, appending or read-write are 1416#pod locked with C<LOCK_EX>; otherwise, they are locked for C<LOCK_SH>. 1417#pod 1418#pod $fh = path("foo.txt")->openrw_utf8( { locked => 1 } ); 1419#pod 1420#pod See L</filehandle> for more on locking. 1421#pod 1422#pod Current API available since 0.011. 1423#pod 1424#pod =cut 1425 1426# map method names to corresponding open mode 1427my %opens = ( 1428 opena => ">>", 1429 openr => "<", 1430 openw => ">", 1431 openrw => "+<" 1432); 1433 1434while ( my ( $k, $v ) = each %opens ) { 1435 no strict 'refs'; 1436 # must check for lexical IO mode hint 1437 *{$k} = sub { 1438 my ( $self, @args ) = @_; 1439 my $args = ( @args && ref $args[0] eq 'HASH' ) ? shift @args : {}; 1440 $args = _get_args( $args, qw/locked/ ); 1441 my ($binmode) = @args; 1442 $binmode = ( ( caller(0) )[10] || {} )->{ 'open' . substr( $v, -1, 1 ) } 1443 unless defined $binmode; 1444 $self->filehandle( $args, $v, $binmode ); 1445 }; 1446 *{ $k . "_raw" } = sub { 1447 my ( $self, @args ) = @_; 1448 my $args = ( @args && ref $args[0] eq 'HASH' ) ? shift @args : {}; 1449 $args = _get_args( $args, qw/locked/ ); 1450 $self->filehandle( $args, $v, ":raw" ); 1451 }; 1452 *{ $k . "_utf8" } = sub { 1453 my ( $self, @args ) = @_; 1454 my $args = ( @args && ref $args[0] eq 'HASH' ) ? shift @args : {}; 1455 $args = _get_args( $args, qw/locked/ ); 1456 $self->filehandle( $args, $v, ":raw:encoding(UTF-8)" ); 1457 }; 1458} 1459 1460#pod =method parent 1461#pod 1462#pod $parent = path("foo/bar/baz")->parent; # foo/bar 1463#pod $parent = path("foo/wibble.txt")->parent; # foo 1464#pod 1465#pod $parent = path("foo/bar/baz")->parent(2); # foo 1466#pod 1467#pod Returns a C<Path::Tiny> object corresponding to the parent directory of the 1468#pod original directory or file. An optional positive integer argument is the number 1469#pod of parent directories upwards to return. C<parent> by itself is equivalent to 1470#pod C<parent(1)>. 1471#pod 1472#pod Current API available since 0.014. 1473#pod 1474#pod =cut 1475 1476# XXX this is ugly and coverage is incomplete. I think it's there for windows 1477# so need to check coverage there and compare 1478sub parent { 1479 my ( $self, $level ) = @_; 1480 $level = 1 unless defined $level && $level > 0; 1481 $self->_splitpath unless defined $self->[FILE]; 1482 my $parent; 1483 if ( length $self->[FILE] ) { 1484 if ( $self->[FILE] eq '.' || $self->[FILE] eq ".." ) { 1485 $parent = path( $self->[PATH] . "/.." ); 1486 } 1487 else { 1488 $parent = path( _non_empty( $self->[VOL] . $self->[DIR] ) ); 1489 } 1490 } 1491 elsif ( length $self->[DIR] ) { 1492 # because of symlinks, any internal updir requires us to 1493 # just add more updirs at the end 1494 if ( $self->[DIR] =~ m{(?:^\.\./|/\.\./|/\.\.\z)} ) { 1495 $parent = path( $self->[VOL] . $self->[DIR] . "/.." ); 1496 } 1497 else { 1498 ( my $dir = $self->[DIR] ) =~ s{/[^\/]+/\z}{/}; 1499 $parent = path( $self->[VOL] . $dir ); 1500 } 1501 } 1502 else { 1503 $parent = path( _non_empty( $self->[VOL] ) ); 1504 } 1505 return $level == 1 ? $parent : $parent->parent( $level - 1 ); 1506} 1507 1508sub _non_empty { 1509 my ($string) = shift; 1510 return ( ( defined($string) && length($string) ) ? $string : "." ); 1511} 1512 1513#pod =method realpath 1514#pod 1515#pod $real = path("/baz/foo/../bar")->realpath; 1516#pod $real = path("foo/../bar")->realpath; 1517#pod 1518#pod Returns a new C<Path::Tiny> object with all symbolic links and upward directory 1519#pod parts resolved using L<Cwd>'s C<realpath>. Compared to C<absolute>, this is 1520#pod more expensive as it must actually consult the filesystem. 1521#pod 1522#pod If the parent path can't be resolved (e.g. if it includes directories that 1523#pod don't exist), an exception will be thrown: 1524#pod 1525#pod $real = path("doesnt_exist/foo")->realpath; # dies 1526#pod 1527#pod However, if the parent path exists and only the last component (e.g. filename) 1528#pod doesn't exist, the realpath will be the realpath of the parent plus the 1529#pod non-existent last component: 1530#pod 1531#pod $real = path("./aasdlfasdlf")->realpath; # works 1532#pod 1533#pod The underlying L<Cwd> module usually worked this way on Unix, but died on 1534#pod Windows (and some Unixes) if the full path didn't exist. As of version 0.064, 1535#pod it's safe to use anywhere. 1536#pod 1537#pod Current API available since 0.001. 1538#pod 1539#pod =cut 1540 1541# Win32 and some Unixes need parent path resolved separately so realpath 1542# doesn't throw an error resolving non-existent basename 1543sub realpath { 1544 my $self = shift; 1545 $self = $self->_resolve_symlinks; 1546 require Cwd; 1547 $self->_splitpath if !defined $self->[FILE]; 1548 my $check_parent = 1549 length $self->[FILE] && $self->[FILE] ne '.' && $self->[FILE] ne '..'; 1550 my $realpath = eval { 1551 # pure-perl Cwd can carp 1552 local $SIG{__WARN__} = sub { }; 1553 Cwd::realpath( $check_parent ? $self->parent->[PATH] : $self->[PATH] ); 1554 }; 1555 # parent realpath must exist; not all Cwd::realpath will error if it doesn't 1556 $self->_throw("resolving realpath") 1557 unless defined $realpath && length $realpath && -e $realpath; 1558 return ( $check_parent ? path( $realpath, $self->[FILE] ) : path($realpath) ); 1559} 1560 1561#pod =method relative 1562#pod 1563#pod $rel = path("/tmp/foo/bar")->relative("/tmp"); # foo/bar 1564#pod 1565#pod Returns a C<Path::Tiny> object with a path relative to a new base path 1566#pod given as an argument. If no argument is given, the current directory will 1567#pod be used as the new base path. 1568#pod 1569#pod If either path is already relative, it will be made absolute based on the 1570#pod current directly before determining the new relative path. 1571#pod 1572#pod The algorithm is roughly as follows: 1573#pod 1574#pod =for :list 1575#pod * If the original and new base path are on different volumes, an exception 1576#pod will be thrown. 1577#pod * If the original and new base are identical, the relative path is C<".">. 1578#pod * If the new base subsumes the original, the relative path is the original 1579#pod path with the new base chopped off the front 1580#pod * If the new base does not subsume the original, a common prefix path is 1581#pod determined (possibly the root directory) and the relative path will 1582#pod consist of updirs (C<"..">) to reach the common prefix, followed by the 1583#pod original path less the common prefix. 1584#pod 1585#pod Unlike C<File::Spec::abs2rel>, in the last case above, the calculation based 1586#pod on a common prefix takes into account symlinks that could affect the updir 1587#pod process. Given an original path "/A/B" and a new base "/A/C", 1588#pod (where "A", "B" and "C" could each have multiple path components): 1589#pod 1590#pod =for :list 1591#pod * Symlinks in "A" don't change the result unless the last component of A is 1592#pod a symlink and the first component of "C" is an updir. 1593#pod * Symlinks in "B" don't change the result and will exist in the result as 1594#pod given. 1595#pod * Symlinks and updirs in "C" must be resolved to actual paths, taking into 1596#pod account the possibility that not all path components might exist on the 1597#pod filesystem. 1598#pod 1599#pod Current API available since 0.001. New algorithm (that accounts for 1600#pod symlinks) available since 0.079. 1601#pod 1602#pod =cut 1603 1604sub relative { 1605 my ( $self, $base ) = @_; 1606 $base = path( defined $base && length $base ? $base : '.' ); 1607 1608 # relative paths must be converted to absolute first 1609 $self = $self->absolute if $self->is_relative; 1610 $base = $base->absolute if $base->is_relative; 1611 1612 # normalize volumes if they exist 1613 $self = $self->absolute if !length $self->volume && length $base->volume; 1614 $base = $base->absolute if length $self->volume && !length $base->volume; 1615 1616 # can't make paths relative across volumes 1617 if ( !_same( $self->volume, $base->volume ) ) { 1618 Carp::croak("relative() can't cross volumes: '$self' vs '$base'"); 1619 } 1620 1621 # if same absolute path, relative is current directory 1622 return path(".") if _same( $self->[PATH], $base->[PATH] ); 1623 1624 # if base is a prefix of self, chop prefix off self 1625 if ( $base->subsumes($self) ) { 1626 $base = "" if $base->is_rootdir; 1627 my $relative = "$self"; 1628 $relative =~ s{\A\Q$base/}{}; 1629 return path($relative); 1630 } 1631 1632 # base is not a prefix, so must find a common prefix (even if root) 1633 my ( @common, @self_parts, @base_parts ); 1634 @base_parts = split /\//, $base->_just_filepath; 1635 1636 # if self is rootdir, then common directory is root (shown as empty 1637 # string for later joins); otherwise, must be computed from path parts. 1638 if ( $self->is_rootdir ) { 1639 @common = (""); 1640 shift @base_parts; 1641 } 1642 else { 1643 @self_parts = split /\//, $self->_just_filepath; 1644 1645 while ( @self_parts && @base_parts && _same( $self_parts[0], $base_parts[0] ) ) { 1646 push @common, shift @base_parts; 1647 shift @self_parts; 1648 } 1649 } 1650 1651 # if there are any symlinks from common to base, we have a problem, as 1652 # you can't guarantee that updir from base reaches the common prefix; 1653 # we must resolve symlinks and try again; likewise, any updirs are 1654 # a problem as it throws off calculation of updirs needed to get from 1655 # self's path to the common prefix. 1656 if ( my $new_base = $self->_resolve_between( \@common, \@base_parts ) ) { 1657 return $self->relative($new_base); 1658 } 1659 1660 # otherwise, symlinks in common or from common to A don't matter as 1661 # those don't involve updirs 1662 my @new_path = ( ("..") x ( 0+ @base_parts ), @self_parts ); 1663 return path(@new_path); 1664} 1665 1666sub _just_filepath { 1667 my $self = shift; 1668 my $self_vol = $self->volume; 1669 return "$self" if !length $self_vol; 1670 1671 ( my $self_path = "$self" ) =~ s{\A\Q$self_vol}{}; 1672 1673 return $self_path; 1674} 1675 1676sub _resolve_between { 1677 my ( $self, $common, $base ) = @_; 1678 my $path = $self->volume . join( "/", @$common ); 1679 my $changed = 0; 1680 for my $p (@$base) { 1681 $path .= "/$p"; 1682 if ( $p eq '..' ) { 1683 $changed = 1; 1684 if ( -e $path ) { 1685 $path = path($path)->realpath->[PATH]; 1686 } 1687 else { 1688 $path =~ s{/[^/]+/..\z}{/}; 1689 } 1690 } 1691 if ( -l $path ) { 1692 $changed = 1; 1693 $path = path($path)->realpath->[PATH]; 1694 } 1695 } 1696 return $changed ? path($path) : undef; 1697} 1698 1699#pod =method remove 1700#pod 1701#pod path("foo.txt")->remove; 1702#pod 1703#pod This is just like C<unlink>, except for its error handling: if the path does 1704#pod not exist, it returns false; if deleting the file fails, it throws an 1705#pod exception. 1706#pod 1707#pod Current API available since 0.012. 1708#pod 1709#pod =cut 1710 1711sub remove { 1712 my $self = shift; 1713 1714 return 0 if !-e $self->[PATH] && !-l $self->[PATH]; 1715 1716 return unlink( $self->[PATH] ) || $self->_throw('unlink'); 1717} 1718 1719#pod =method remove_tree 1720#pod 1721#pod # directory 1722#pod path("foo/bar/baz")->remove_tree; 1723#pod path("foo/bar/baz")->remove_tree( \%options ); 1724#pod path("foo/bar/baz")->remove_tree( { safe => 0 } ); # force remove 1725#pod 1726#pod Like calling C<remove_tree> from L<File::Path>, but defaults to C<safe> mode. 1727#pod An optional hash reference is passed through to C<remove_tree>. Errors will be 1728#pod trapped and an exception thrown. Returns the number of directories deleted, 1729#pod just like C<remove_tree>. 1730#pod 1731#pod If you want to remove a directory only if it is empty, use the built-in 1732#pod C<rmdir> function instead. 1733#pod 1734#pod rmdir path("foo/bar/baz/"); 1735#pod 1736#pod Current API available since 0.013. 1737#pod 1738#pod =cut 1739 1740sub remove_tree { 1741 my ( $self, $args ) = @_; 1742 return 0 if !-e $self->[PATH] && !-l $self->[PATH]; 1743 $args = {} unless ref $args eq 'HASH'; 1744 my $err; 1745 $args->{error} = \$err unless defined $args->{error}; 1746 $args->{safe} = 1 unless defined $args->{safe}; 1747 require File::Path; 1748 my $count = File::Path::remove_tree( $self->[PATH], $args ); 1749 1750 if ( $err && @$err ) { 1751 my ( $file, $message ) = %{ $err->[0] }; 1752 Carp::croak("remove_tree failed for $file: $message"); 1753 } 1754 return $count; 1755} 1756 1757#pod =method sibling 1758#pod 1759#pod $foo = path("/tmp/foo.txt"); 1760#pod $sib = $foo->sibling("bar.txt"); # /tmp/bar.txt 1761#pod $sib = $foo->sibling("baz", "bam.txt"); # /tmp/baz/bam.txt 1762#pod 1763#pod Returns a new C<Path::Tiny> object relative to the parent of the original. 1764#pod This is slightly more efficient than C<< $path->parent->child(...) >>. 1765#pod 1766#pod Current API available since 0.058. 1767#pod 1768#pod =cut 1769 1770sub sibling { 1771 my $self = shift; 1772 return path( $self->parent->[PATH], @_ ); 1773} 1774 1775#pod =method slurp, slurp_raw, slurp_utf8 1776#pod 1777#pod $data = path("foo.txt")->slurp; 1778#pod $data = path("foo.txt")->slurp( {binmode => ":raw"} ); 1779#pod $data = path("foo.txt")->slurp_raw; 1780#pod $data = path("foo.txt")->slurp_utf8; 1781#pod 1782#pod Reads file contents into a scalar. Takes an optional hash reference which may 1783#pod be used to pass options. The only available option is C<binmode>, which is 1784#pod passed to C<binmode()> on the handle used for reading. 1785#pod 1786#pod C<slurp_raw> is like C<slurp> with a C<binmode> of C<:unix> for 1787#pod a fast, unbuffered, raw read. 1788#pod 1789#pod C<slurp_utf8> is like C<slurp> with a C<binmode> of 1790#pod C<:unix:encoding(UTF-8)> (or L<PerlIO::utf8_strict>). If L<Unicode::UTF8> 1791#pod 0.58+ is installed, a raw slurp will be done instead and the result decoded 1792#pod with C<Unicode::UTF8>. This is just as strict and is roughly an order of 1793#pod magnitude faster than using C<:encoding(UTF-8)>. 1794#pod 1795#pod B<Note>: C<slurp> and friends lock the filehandle before slurping. If 1796#pod you plan to slurp from a file created with L<File::Temp>, be sure to 1797#pod close other handles or open without locking to avoid a deadlock: 1798#pod 1799#pod my $tempfile = File::Temp->new(EXLOCK => 0); 1800#pod my $guts = path($tempfile)->slurp; 1801#pod 1802#pod Current API available since 0.004. 1803#pod 1804#pod =cut 1805 1806sub slurp { 1807 my $self = shift; 1808 my $args = _get_args( shift, qw/binmode/ ); 1809 my $binmode = $args->{binmode}; 1810 $binmode = ( ( caller(0) )[10] || {} )->{'open<'} unless defined $binmode; 1811 my $fh = $self->filehandle( { locked => 1 }, "<", $binmode ); 1812 if ( ( defined($binmode) ? $binmode : "" ) eq ":unix" 1813 and my $size = -s $fh ) 1814 { 1815 my $buf; 1816 read $fh, $buf, $size; # File::Slurp in a nutshell 1817 return $buf; 1818 } 1819 else { 1820 local $/; 1821 return scalar <$fh>; 1822 } 1823} 1824 1825sub slurp_raw { $_[1] = { binmode => ":unix" }; goto &slurp } 1826 1827sub slurp_utf8 { 1828 if ( defined($HAS_UU) ? $HAS_UU : ( $HAS_UU = _check_UU() ) ) { 1829 return Unicode::UTF8::decode_utf8( slurp( $_[0], { binmode => ":unix" } ) ); 1830 } 1831 elsif ( defined($HAS_PU) ? $HAS_PU : ( $HAS_PU = _check_PU() ) ) { 1832 $_[1] = { binmode => ":unix:utf8_strict" }; 1833 goto &slurp; 1834 } 1835 else { 1836 $_[1] = { binmode => ":raw:encoding(UTF-8)" }; 1837 goto &slurp; 1838 } 1839} 1840 1841#pod =method spew, spew_raw, spew_utf8 1842#pod 1843#pod path("foo.txt")->spew(@data); 1844#pod path("foo.txt")->spew(\@data); 1845#pod path("foo.txt")->spew({binmode => ":raw"}, @data); 1846#pod path("foo.txt")->spew_raw(@data); 1847#pod path("foo.txt")->spew_utf8(@data); 1848#pod 1849#pod Writes data to a file atomically. The file is written to a temporary file in 1850#pod the same directory, then renamed over the original. An optional hash reference 1851#pod may be used to pass options. The only option is C<binmode>, which is passed to 1852#pod C<binmode()> on the handle used for writing. 1853#pod 1854#pod C<spew_raw> is like C<spew> with a C<binmode> of C<:unix> for a fast, 1855#pod unbuffered, raw write. 1856#pod 1857#pod C<spew_utf8> is like C<spew> with a C<binmode> of C<:unix:encoding(UTF-8)> 1858#pod (or L<PerlIO::utf8_strict>). If L<Unicode::UTF8> 0.58+ is installed, a raw 1859#pod spew will be done instead on the data encoded with C<Unicode::UTF8>. 1860#pod 1861#pod B<NOTE>: because the file is written to a temporary file and then renamed, the 1862#pod new file will wind up with permissions based on your current umask. This is a 1863#pod feature to protect you from a race condition that would otherwise give 1864#pod different permissions than you might expect. If you really want to keep the 1865#pod original mode flags, use L</append> with the C<truncate> option. 1866#pod 1867#pod Current API available since 0.011. 1868#pod 1869#pod =cut 1870 1871# XXX add "unsafe" option to disable flocking and atomic? Check benchmarks on append() first. 1872sub spew { 1873 my ( $self, @data ) = @_; 1874 my $args = ( @data && ref $data[0] eq 'HASH' ) ? shift @data : {}; 1875 $args = _get_args( $args, qw/binmode/ ); 1876 my $binmode = $args->{binmode}; 1877 # get default binmode from caller's lexical scope (see "perldoc open") 1878 $binmode = ( ( caller(0) )[10] || {} )->{'open>'} unless defined $binmode; 1879 1880 # spewing need to follow the link 1881 # and create the tempfile in the same dir 1882 my $resolved_path = $self->_resolve_symlinks; 1883 1884 my $temp = path( $resolved_path . $$ . int( rand( 2**31 ) ) ); 1885 my $fh = $temp->filehandle( { exclusive => 1, locked => 1 }, ">", $binmode ); 1886 print {$fh} map { ref eq 'ARRAY' ? @$_ : $_ } @data; 1887 close $fh or $self->_throw( 'close', $temp->[PATH] ); 1888 1889 return $temp->move($resolved_path); 1890} 1891 1892sub spew_raw { splice @_, 1, 0, { binmode => ":unix" }; goto &spew } 1893 1894sub spew_utf8 { 1895 if ( defined($HAS_UU) ? $HAS_UU : ( $HAS_UU = _check_UU() ) ) { 1896 my $self = shift; 1897 spew( 1898 $self, 1899 { binmode => ":unix" }, 1900 map { Unicode::UTF8::encode_utf8($_) } map { ref eq 'ARRAY' ? @$_ : $_ } @_ 1901 ); 1902 } 1903 elsif ( defined($HAS_PU) ? $HAS_PU : ( $HAS_PU = _check_PU() ) ) { 1904 splice @_, 1, 0, { binmode => ":unix:utf8_strict" }; 1905 goto &spew; 1906 } 1907 else { 1908 splice @_, 1, 0, { binmode => ":unix:encoding(UTF-8)" }; 1909 goto &spew; 1910 } 1911} 1912 1913#pod =method stat, lstat 1914#pod 1915#pod $stat = path("foo.txt")->stat; 1916#pod $stat = path("/some/symlink")->lstat; 1917#pod 1918#pod Like calling C<stat> or C<lstat> from L<File::stat>. 1919#pod 1920#pod Current API available since 0.001. 1921#pod 1922#pod =cut 1923 1924# XXX break out individual stat() components as subs? 1925sub stat { 1926 my $self = shift; 1927 require File::stat; 1928 return File::stat::stat( $self->[PATH] ) || $self->_throw('stat'); 1929} 1930 1931sub lstat { 1932 my $self = shift; 1933 require File::stat; 1934 return File::stat::lstat( $self->[PATH] ) || $self->_throw('lstat'); 1935} 1936 1937#pod =method stringify 1938#pod 1939#pod $path = path("foo.txt"); 1940#pod say $path->stringify; # same as "$path" 1941#pod 1942#pod Returns a string representation of the path. Unlike C<canonpath>, this method 1943#pod returns the path standardized with Unix-style C</> directory separators. 1944#pod 1945#pod Current API available since 0.001. 1946#pod 1947#pod =cut 1948 1949sub stringify { $_[0]->[PATH] } 1950 1951#pod =method subsumes 1952#pod 1953#pod path("foo/bar")->subsumes("foo/bar/baz"); # true 1954#pod path("/foo/bar")->subsumes("/foo/baz"); # false 1955#pod 1956#pod Returns true if the first path is a prefix of the second path at a directory 1957#pod boundary. 1958#pod 1959#pod This B<does not> resolve parent directory entries (C<..>) or symlinks: 1960#pod 1961#pod path("foo/bar")->subsumes("foo/bar/../baz"); # true 1962#pod 1963#pod If such things are important to you, ensure that both paths are resolved to 1964#pod the filesystem with C<realpath>: 1965#pod 1966#pod my $p1 = path("foo/bar")->realpath; 1967#pod my $p2 = path("foo/bar/../baz")->realpath; 1968#pod if ( $p1->subsumes($p2) ) { ... } 1969#pod 1970#pod Current API available since 0.048. 1971#pod 1972#pod =cut 1973 1974sub subsumes { 1975 my $self = shift; 1976 Carp::croak("subsumes() requires a defined, positive-length argument") 1977 unless defined $_[0]; 1978 my $other = path(shift); 1979 1980 # normalize absolute vs relative 1981 if ( $self->is_absolute && !$other->is_absolute ) { 1982 $other = $other->absolute; 1983 } 1984 elsif ( $other->is_absolute && !$self->is_absolute ) { 1985 $self = $self->absolute; 1986 } 1987 1988 # normalize volume vs non-volume; do this after absolute path 1989 # adjustments above since that might add volumes already 1990 if ( length $self->volume && !length $other->volume ) { 1991 $other = $other->absolute; 1992 } 1993 elsif ( length $other->volume && !length $self->volume ) { 1994 $self = $self->absolute; 1995 } 1996 1997 if ( $self->[PATH] eq '.' ) { 1998 return !!1; # cwd subsumes everything relative 1999 } 2000 elsif ( $self->is_rootdir ) { 2001 # a root directory ("/", "c:/") already ends with a separator 2002 return $other->[PATH] =~ m{^\Q$self->[PATH]\E}; 2003 } 2004 else { 2005 # exact match or prefix breaking at a separator 2006 return $other->[PATH] =~ m{^\Q$self->[PATH]\E(?:/|\z)}; 2007 } 2008} 2009 2010#pod =method touch 2011#pod 2012#pod path("foo.txt")->touch; 2013#pod path("foo.txt")->touch($epoch_secs); 2014#pod 2015#pod Like the Unix C<touch> utility. Creates the file if it doesn't exist, or else 2016#pod changes the modification and access times to the current time. If the first 2017#pod argument is the epoch seconds then it will be used. 2018#pod 2019#pod Returns the path object so it can be easily chained with other methods: 2020#pod 2021#pod # won't die if foo.txt doesn't exist 2022#pod $content = path("foo.txt")->touch->slurp; 2023#pod 2024#pod Current API available since 0.015. 2025#pod 2026#pod =cut 2027 2028sub touch { 2029 my ( $self, $epoch ) = @_; 2030 if ( !-e $self->[PATH] ) { 2031 my $fh = $self->openw; 2032 close $fh or $self->_throw('close'); 2033 } 2034 if ( defined $epoch ) { 2035 utime $epoch, $epoch, $self->[PATH] 2036 or $self->_throw("utime ($epoch)"); 2037 } 2038 else { 2039 # literal undef prevents warnings :-( 2040 utime undef, undef, $self->[PATH] 2041 or $self->_throw("utime ()"); 2042 } 2043 return $self; 2044} 2045 2046#pod =method touchpath 2047#pod 2048#pod path("bar/baz/foo.txt")->touchpath; 2049#pod 2050#pod Combines C<mkpath> and C<touch>. Creates the parent directory if it doesn't exist, 2051#pod before touching the file. Returns the path object like C<touch> does. 2052#pod 2053#pod Current API available since 0.022. 2054#pod 2055#pod =cut 2056 2057sub touchpath { 2058 my ($self) = @_; 2059 my $parent = $self->parent; 2060 $parent->mkpath unless $parent->exists; 2061 $self->touch; 2062} 2063 2064#pod =method visit 2065#pod 2066#pod path("/tmp")->visit( \&callback, \%options ); 2067#pod 2068#pod Executes a callback for each child of a directory. It returns a hash 2069#pod reference with any state accumulated during iteration. 2070#pod 2071#pod The options are the same as for L</iterator> (which it uses internally): 2072#pod C<recurse> and C<follow_symlinks>. Both default to false. 2073#pod 2074#pod The callback function will receive a C<Path::Tiny> object as the first argument 2075#pod and a hash reference to accumulate state as the second argument. For example: 2076#pod 2077#pod # collect files sizes 2078#pod my $sizes = path("/tmp")->visit( 2079#pod sub { 2080#pod my ($path, $state) = @_; 2081#pod return if $path->is_dir; 2082#pod $state->{$path} = -s $path; 2083#pod }, 2084#pod { recurse => 1 } 2085#pod ); 2086#pod 2087#pod For convenience, the C<Path::Tiny> object will also be locally aliased as the 2088#pod C<$_> global variable: 2089#pod 2090#pod # print paths matching /foo/ 2091#pod path("/tmp")->visit( sub { say if /foo/ }, { recurse => 1} ); 2092#pod 2093#pod If the callback returns a B<reference> to a false scalar value, iteration will 2094#pod terminate. This is not the same as "pruning" a directory search; this just 2095#pod stops all iteration and returns the state hash reference. 2096#pod 2097#pod # find up to 10 files larger than 100K 2098#pod my $files = path("/tmp")->visit( 2099#pod sub { 2100#pod my ($path, $state) = @_; 2101#pod $state->{$path}++ if -s $path > 102400 2102#pod return \0 if keys %$state == 10; 2103#pod }, 2104#pod { recurse => 1 } 2105#pod ); 2106#pod 2107#pod If you want more flexible iteration, use a module like L<Path::Iterator::Rule>. 2108#pod 2109#pod Current API available since 0.062. 2110#pod 2111#pod =cut 2112 2113sub visit { 2114 my $self = shift; 2115 my $cb = shift; 2116 my $args = _get_args( shift, qw/recurse follow_symlinks/ ); 2117 Carp::croak("Callback for visit() must be a code reference") 2118 unless defined($cb) && ref($cb) eq 'CODE'; 2119 my $next = $self->iterator($args); 2120 my $state = {}; 2121 while ( my $file = $next->() ) { 2122 local $_ = $file; 2123 my $r = $cb->( $file, $state ); 2124 last if ref($r) eq 'SCALAR' && !$$r; 2125 } 2126 return $state; 2127} 2128 2129#pod =method volume 2130#pod 2131#pod $vol = path("/tmp/foo.txt")->volume; # "" 2132#pod $vol = path("C:/tmp/foo.txt")->volume; # "C:" 2133#pod 2134#pod Returns the volume portion of the path. This is equivalent 2135#pod to what L<File::Spec> would give from C<splitpath> and thus 2136#pod usually is the empty string on Unix-like operating systems or the 2137#pod drive letter for an absolute path on C<MSWin32>. 2138#pod 2139#pod Current API available since 0.001. 2140#pod 2141#pod =cut 2142 2143sub volume { 2144 my ($self) = @_; 2145 $self->_splitpath unless defined $self->[VOL]; 2146 return $self->[VOL]; 2147} 2148 2149package Path::Tiny::Error; 2150 2151our @CARP_NOT = qw/Path::Tiny/; 2152 2153use overload ( q{""} => sub { (shift)->{msg} }, fallback => 1 ); 2154 2155sub throw { 2156 my ( $class, $op, $file, $err ) = @_; 2157 chomp( my $trace = Carp::shortmess ); 2158 my $msg = "Error $op on '$file': $err$trace\n"; 2159 die bless { op => $op, file => $file, err => $err, msg => $msg }, $class; 2160} 2161 21621; 2163 2164 2165# vim: ts=4 sts=4 sw=4 et: 2166 2167__END__ 2168 2169=pod 2170 2171=encoding UTF-8 2172 2173=head1 NAME 2174 2175Path::Tiny - File path utility 2176 2177=head1 VERSION 2178 2179version 0.120 2180 2181=head1 SYNOPSIS 2182 2183 use Path::Tiny; 2184 2185 # creating Path::Tiny objects 2186 2187 $dir = path("/tmp"); 2188 $foo = path("foo.txt"); 2189 2190 $subdir = $dir->child("foo"); 2191 $bar = $subdir->child("bar.txt"); 2192 2193 # stringifies as cleaned up path 2194 2195 $file = path("./foo.txt"); 2196 print $file; # "foo.txt" 2197 2198 # reading files 2199 2200 $guts = $file->slurp; 2201 $guts = $file->slurp_utf8; 2202 2203 @lines = $file->lines; 2204 @lines = $file->lines_utf8; 2205 2206 ($head) = $file->lines( {count => 1} ); 2207 ($tail) = $file->lines( {count => -1} ); 2208 2209 # writing files 2210 2211 $bar->spew( @data ); 2212 $bar->spew_utf8( @data ); 2213 2214 # reading directories 2215 2216 for ( $dir->children ) { ... } 2217 2218 $iter = $dir->iterator; 2219 while ( my $next = $iter->() ) { ... } 2220 2221=head1 DESCRIPTION 2222 2223This module provides a small, fast utility for working with file paths. It is 2224friendlier to use than L<File::Spec> and provides easy access to functions from 2225several other core file handling modules. It aims to be smaller and faster 2226than many alternatives on CPAN, while helping people do many common things in 2227consistent and less error-prone ways. 2228 2229Path::Tiny does not try to work for anything except Unix-like and Win32 2230platforms. Even then, it might break if you try something particularly obscure 2231or tortuous. (Quick! What does this mean: 2232C<< ///../../..//./././a//b/.././c/././ >>? And how does it differ on Win32?) 2233 2234All paths are forced to have Unix-style forward slashes. Stringifying 2235the object gives you back the path (after some clean up). 2236 2237File input/output methods C<flock> handles before reading or writing, 2238as appropriate (if supported by the platform and/or filesystem). 2239 2240The C<*_utf8> methods (C<slurp_utf8>, C<lines_utf8>, etc.) operate in raw 2241mode. On Windows, that means they will not have CRLF translation from the 2242C<:crlf> IO layer. Installing L<Unicode::UTF8> 0.58 or later will speed up 2243C<*_utf8> situations in many cases and is highly recommended. 2244Alternatively, installing L<PerlIO::utf8_strict> 0.003 or later will be 2245used in place of the default C<:encoding(UTF-8)>. 2246 2247This module depends heavily on PerlIO layers for correct operation and thus 2248requires Perl 5.008001 or later. 2249 2250=head1 CONSTRUCTORS 2251 2252=head2 path 2253 2254 $path = path("foo/bar"); 2255 $path = path("/tmp", "file.txt"); # list 2256 $path = path("."); # cwd 2257 $path = path("~user/file.txt"); # tilde processing 2258 2259Constructs a C<Path::Tiny> object. It doesn't matter if you give a file or 2260directory path. It's still up to you to call directory-like methods only on 2261directories and file-like methods only on files. This function is exported 2262automatically by default. 2263 2264The first argument must be defined and have non-zero length or an exception 2265will be thrown. This prevents subtle, dangerous errors with code like 2266C<< path( maybe_undef() )->remove_tree >>. 2267 2268If the first component of the path is a tilde ('~') then the component will be 2269replaced with the output of C<glob('~')>. If the first component of the path 2270is a tilde followed by a user name then the component will be replaced with 2271output of C<glob('~username')>. Behaviour for non-existent users depends on 2272the output of C<glob> on the system. 2273 2274On Windows, if the path consists of a drive identifier without a path component 2275(C<C:> or C<D:>), it will be expanded to the absolute path of the current 2276directory on that volume using C<Cwd::getdcwd()>. 2277 2278If called with a single C<Path::Tiny> argument, the original is returned unless 2279the original is holding a temporary file or directory reference in which case a 2280stringified copy is made. 2281 2282 $path = path("foo/bar"); 2283 $temp = Path::Tiny->tempfile; 2284 2285 $p2 = path($path); # like $p2 = $path 2286 $t2 = path($temp); # like $t2 = path( "$temp" ) 2287 2288This optimizes copies without proliferating references unexpectedly if a copy is 2289made by code outside your control. 2290 2291Current API available since 0.017. 2292 2293=head2 new 2294 2295 $path = Path::Tiny->new("foo/bar"); 2296 2297This is just like C<path>, but with method call overhead. (Why would you 2298do that?) 2299 2300Current API available since 0.001. 2301 2302=head2 cwd 2303 2304 $path = Path::Tiny->cwd; # path( Cwd::getcwd ) 2305 $path = cwd; # optional export 2306 2307Gives you the absolute path to the current directory as a C<Path::Tiny> object. 2308This is slightly faster than C<< path(".")->absolute >>. 2309 2310C<cwd> may be exported on request and used as a function instead of as a 2311method. 2312 2313Current API available since 0.018. 2314 2315=head2 rootdir 2316 2317 $path = Path::Tiny->rootdir; # / 2318 $path = rootdir; # optional export 2319 2320Gives you C<< File::Spec->rootdir >> as a C<Path::Tiny> object if you're too 2321picky for C<path("/")>. 2322 2323C<rootdir> may be exported on request and used as a function instead of as a 2324method. 2325 2326Current API available since 0.018. 2327 2328=head2 tempfile, tempdir 2329 2330 $temp = Path::Tiny->tempfile( @options ); 2331 $temp = Path::Tiny->tempdir( @options ); 2332 $temp = $dirpath->tempfile( @options ); 2333 $temp = $dirpath->tempdir( @options ); 2334 $temp = tempfile( @options ); # optional export 2335 $temp = tempdir( @options ); # optional export 2336 2337C<tempfile> passes the options to C<< File::Temp->new >> and returns a C<Path::Tiny> 2338object with the file name. The C<TMPDIR> option is enabled by default. 2339 2340The resulting C<File::Temp> object is cached. When the C<Path::Tiny> object is 2341destroyed, the C<File::Temp> object will be as well. 2342 2343C<File::Temp> annoyingly requires you to specify a custom template in slightly 2344different ways depending on which function or method you call, but 2345C<Path::Tiny> lets you ignore that and can take either a leading template or a 2346C<TEMPLATE> option and does the right thing. 2347 2348 $temp = Path::Tiny->tempfile( "customXXXXXXXX" ); # ok 2349 $temp = Path::Tiny->tempfile( TEMPLATE => "customXXXXXXXX" ); # ok 2350 2351The tempfile path object will be normalized to have an absolute path, even if 2352created in a relative directory using C<DIR>. If you want it to have 2353the C<realpath> instead, pass a leading options hash like this: 2354 2355 $real_temp = tempfile({realpath => 1}, @options); 2356 2357C<tempdir> is just like C<tempfile>, except it calls 2358C<< File::Temp->newdir >> instead. 2359 2360Both C<tempfile> and C<tempdir> may be exported on request and used as 2361functions instead of as methods. 2362 2363The methods can be called on an instances representing a 2364directory. In this case, the directory is used as the base to create the 2365temporary file/directory, setting the C<DIR> option in File::Temp. 2366 2367 my $target_dir = path('/to/destination'); 2368 my $tempfile = $target_dir->tempfile('foobarXXXXXX'); 2369 $tempfile->spew('A lot of data...'); # not atomic 2370 $tempfile->rename($target_dir->child('foobar')); # hopefully atomic 2371 2372In this case, any value set for option C<DIR> is ignored. 2373 2374B<Note>: for tempfiles, the filehandles from File::Temp are closed and not 2375reused. This is not as secure as using File::Temp handles directly, but is 2376less prone to deadlocks or access problems on some platforms. Think of what 2377C<Path::Tiny> gives you to be just a temporary file B<name> that gets cleaned 2378up. 2379 2380B<Note 2>: if you don't want these cleaned up automatically when the object 2381is destroyed, File::Temp requires different options for directories and 2382files. Use C<< CLEANUP => 0 >> for directories and C<< UNLINK => 0 >> for 2383files. 2384 2385B<Note 3>: Don't lose the temporary object by chaining a method call instead 2386of storing it: 2387 2388 my $lost = tempdir()->child("foo"); # tempdir cleaned up right away 2389 2390B<Note 4>: The cached object may be accessed with the L</cached_temp> method. 2391Keeping a reference to, or modifying the cached object may break the 2392behavior documented above and is not supported. Use at your own risk. 2393 2394Current API available since 0.119. 2395 2396=head1 METHODS 2397 2398=head2 absolute 2399 2400 $abs = path("foo/bar")->absolute; 2401 $abs = path("foo/bar")->absolute("/tmp"); 2402 2403Returns a new C<Path::Tiny> object with an absolute path (or itself if already 2404absolute). If no argument is given, the current directory is used as the 2405absolute base path. If an argument is given, it will be converted to an 2406absolute path (if it is not already) and used as the absolute base path. 2407 2408This will not resolve upward directories ("foo/../bar") unless C<canonpath> 2409in L<File::Spec> would normally do so on your platform. If you need them 2410resolved, you must call the more expensive C<realpath> method instead. 2411 2412On Windows, an absolute path without a volume component will have it added 2413based on the current drive. 2414 2415Current API available since 0.101. 2416 2417=head2 append, append_raw, append_utf8 2418 2419 path("foo.txt")->append(@data); 2420 path("foo.txt")->append(\@data); 2421 path("foo.txt")->append({binmode => ":raw"}, @data); 2422 path("foo.txt")->append_raw(@data); 2423 path("foo.txt")->append_utf8(@data); 2424 2425Appends data to a file. The file is locked with C<flock> prior to writing 2426and closed afterwards. An optional hash reference may be used to pass 2427options. Valid options are: 2428 2429=over 4 2430 2431=item * 2432 2433C<binmode>: passed to C<binmode()> on the handle used for writing. 2434 2435=item * 2436 2437C<truncate>: truncates the file after locking and before appending 2438 2439=back 2440 2441The C<truncate> option is a way to replace the contents of a file 2442B<in place>, unlike L</spew> which writes to a temporary file and then 2443replaces the original (if it exists). 2444 2445C<append_raw> is like C<append> with a C<binmode> of C<:unix> for fast, 2446unbuffered, raw write. 2447 2448C<append_utf8> is like C<append> with a C<binmode> of 2449C<:unix:encoding(UTF-8)> (or L<PerlIO::utf8_strict>). If L<Unicode::UTF8> 24500.58+ is installed, a raw append will be done instead on the data encoded 2451with C<Unicode::UTF8>. 2452 2453Current API available since 0.060. 2454 2455=head2 assert 2456 2457 $path = path("foo.txt")->assert( sub { $_->exists } ); 2458 2459Returns the invocant after asserting that a code reference argument returns 2460true. When the assertion code reference runs, it will have the invocant 2461object in the C<$_> variable. If it returns false, an exception will be 2462thrown. The assertion code reference may also throw its own exception. 2463 2464If no assertion is provided, the invocant is returned without error. 2465 2466Current API available since 0.062. 2467 2468=head2 basename 2469 2470 $name = path("foo/bar.txt")->basename; # bar.txt 2471 $name = path("foo.txt")->basename('.txt'); # foo 2472 $name = path("foo.txt")->basename(qr/.txt/); # foo 2473 $name = path("foo.txt")->basename(@suffixes); 2474 2475Returns the file portion or last directory portion of a path. 2476 2477Given a list of suffixes as strings or regular expressions, any that match at 2478the end of the file portion or last directory portion will be removed before 2479the result is returned. 2480 2481Current API available since 0.054. 2482 2483=head2 canonpath 2484 2485 $canonical = path("foo/bar")->canonpath; # foo\bar on Windows 2486 2487Returns a string with the canonical format of the path name for 2488the platform. In particular, this means directory separators 2489will be C<\> on Windows. 2490 2491Current API available since 0.001. 2492 2493=head2 cached_temp 2494 2495Returns the cached C<File::Temp> or C<File::Temp::Dir> object if the 2496C<Path::Tiny> object was created with C</tempfile> or C</tempdir>. 2497If there is no such object, this method throws. 2498 2499B<WARNING>: Keeping a reference to, or modifying the cached object may 2500break the behavior documented for temporary files and directories created 2501with C<Path::Tiny> and is not supported. Use at your own risk. 2502 2503Current API available since 0.101. 2504 2505=head2 child 2506 2507 $file = path("/tmp")->child("foo.txt"); # "/tmp/foo.txt" 2508 $file = path("/tmp")->child(@parts); 2509 2510Returns a new C<Path::Tiny> object relative to the original. Works 2511like C<catfile> or C<catdir> from File::Spec, but without caring about 2512file or directories. 2513 2514B<WARNING>: because the argument could contain C<..> or refer to symlinks, 2515there is no guarantee that the new path refers to an actual descendent of 2516the original. If this is important to you, transform parent and child with 2517L</realpath> and check them with L</subsumes>. 2518 2519Current API available since 0.001. 2520 2521=head2 children 2522 2523 @paths = path("/tmp")->children; 2524 @paths = path("/tmp")->children( qr/\.txt\z/ ); 2525 2526Returns a list of C<Path::Tiny> objects for all files and directories 2527within a directory. Excludes "." and ".." automatically. 2528 2529If an optional C<qr//> argument is provided, it only returns objects for child 2530names that match the given regular expression. Only the base name is used 2531for matching: 2532 2533 @paths = path("/tmp")->children( qr/^foo/ ); 2534 # matches children like the glob foo* 2535 2536Current API available since 0.028. 2537 2538=head2 chmod 2539 2540 path("foo.txt")->chmod(0777); 2541 path("foo.txt")->chmod("0755"); 2542 path("foo.txt")->chmod("go-w"); 2543 path("foo.txt")->chmod("a=r,u+wx"); 2544 2545Sets file or directory permissions. The argument can be a numeric mode, a 2546octal string beginning with a "0" or a limited subset of the symbolic mode use 2547by F</bin/chmod>. 2548 2549The symbolic mode must be a comma-delimited list of mode clauses. Clauses must 2550match C<< qr/\A([augo]+)([=+-])([rwx]+)\z/ >>, which defines "who", "op" and 2551"perms" parameters for each clause. Unlike F</bin/chmod>, all three parameters 2552are required for each clause, multiple ops are not allowed and permissions 2553C<stugoX> are not supported. (See L<File::chmod> for more complex needs.) 2554 2555Current API available since 0.053. 2556 2557=head2 copy 2558 2559 path("/tmp/foo.txt")->copy("/tmp/bar.txt"); 2560 2561Copies the current path to the given destination using L<File::Copy>'s 2562C<copy> function. Upon success, returns the C<Path::Tiny> object for the 2563newly copied file. 2564 2565Current API available since 0.070. 2566 2567=head2 digest 2568 2569 $obj = path("/tmp/foo.txt")->digest; # SHA-256 2570 $obj = path("/tmp/foo.txt")->digest("MD5"); # user-selected 2571 $obj = path("/tmp/foo.txt")->digest( { chunk_size => 1e6 }, "MD5" ); 2572 2573Returns a hexadecimal digest for a file. An optional hash reference of options may 2574be given. The only option is C<chunk_size>. If C<chunk_size> is given, that many 2575bytes will be read at a time. If not provided, the entire file will be slurped 2576into memory to compute the digest. 2577 2578Any subsequent arguments are passed to the constructor for L<Digest> to select 2579an algorithm. If no arguments are given, the default is SHA-256. 2580 2581Current API available since 0.056. 2582 2583=head2 dirname (deprecated) 2584 2585 $name = path("/tmp/foo.txt")->dirname; # "/tmp/" 2586 2587Returns the directory portion you would get from calling 2588C<< File::Spec->splitpath( $path->stringify ) >> or C<"."> for a path without a 2589parent directory portion. Because L<File::Spec> is inconsistent, the result 2590might or might not have a trailing slash. Because of this, this method is 2591B<deprecated>. 2592 2593A better, more consistently approach is likely C<< $path->parent->stringify >>, 2594which will not have a trailing slash except for a root directory. 2595 2596Deprecated in 0.056. 2597 2598=head2 edit, edit_raw, edit_utf8 2599 2600 path("foo.txt")->edit( \&callback, $options ); 2601 path("foo.txt")->edit_utf8( \&callback ); 2602 path("foo.txt")->edit_raw( \&callback ); 2603 2604These are convenience methods that allow "editing" a file using a single 2605callback argument. They slurp the file using C<slurp>, place the contents 2606inside a localized C<$_> variable, call the callback function (without 2607arguments), and then write C<$_> (presumably mutated) back to the 2608file with C<spew>. 2609 2610An optional hash reference may be used to pass options. The only option is 2611C<binmode>, which is passed to C<slurp> and C<spew>. 2612 2613C<edit_utf8> and C<edit_raw> act like their respective C<slurp_*> and 2614C<spew_*> methods. 2615 2616Current API available since 0.077. 2617 2618=head2 edit_lines, edit_lines_utf8, edit_lines_raw 2619 2620 path("foo.txt")->edit_lines( \&callback, $options ); 2621 path("foo.txt")->edit_lines_utf8( \&callback ); 2622 path("foo.txt")->edit_lines_raw( \&callback ); 2623 2624These are convenience methods that allow "editing" a file's lines using a 2625single callback argument. They iterate over the file: for each line, the 2626line is put into a localized C<$_> variable, the callback function is 2627executed (without arguments) and then C<$_> is written to a temporary file. 2628When iteration is finished, the temporary file is atomically renamed over 2629the original. 2630 2631An optional hash reference may be used to pass options. The only option is 2632C<binmode>, which is passed to the method that open handles for reading and 2633writing. 2634 2635C<edit_lines_utf8> and C<edit_lines_raw> act like their respective 2636C<slurp_*> and C<spew_*> methods. 2637 2638Current API available since 0.077. 2639 2640=head2 exists, is_file, is_dir 2641 2642 if ( path("/tmp")->exists ) { ... } # -e 2643 if ( path("/tmp")->is_dir ) { ... } # -d 2644 if ( path("/tmp")->is_file ) { ... } # -e && ! -d 2645 2646Implements file test operations, this means the file or directory actually has 2647to exist on the filesystem. Until then, it's just a path. 2648 2649B<Note>: C<is_file> is not C<-f> because C<-f> is not the opposite of C<-d>. 2650C<-f> means "plain file", excluding symlinks, devices, etc. that often can be 2651read just like files. 2652 2653Use C<-f> instead if you really mean to check for a plain file. 2654 2655Current API available since 0.053. 2656 2657=head2 filehandle 2658 2659 $fh = path("/tmp/foo.txt")->filehandle($mode, $binmode); 2660 $fh = path("/tmp/foo.txt")->filehandle({ locked => 1 }, $mode, $binmode); 2661 $fh = path("/tmp/foo.txt")->filehandle({ exclusive => 1 }, $mode, $binmode); 2662 2663Returns an open file handle. The C<$mode> argument must be a Perl-style 2664read/write mode string ("<" ,">", ">>", etc.). If a C<$binmode> 2665is given, it is set during the C<open> call. 2666 2667An optional hash reference may be used to pass options. 2668 2669The C<locked> option governs file locking; if true, handles opened for writing, 2670appending or read-write are locked with C<LOCK_EX>; otherwise, they are 2671locked with C<LOCK_SH>. When using C<locked>, ">" or "+>" modes will delay 2672truncation until after the lock is acquired. 2673 2674The C<exclusive> option causes the open() call to fail if the file already 2675exists. This corresponds to the O_EXCL flag to sysopen / open(2). 2676C<exclusive> implies C<locked> and will set it for you if you forget it. 2677 2678See C<openr>, C<openw>, C<openrw>, and C<opena> for sugar. 2679 2680Current API available since 0.066. 2681 2682=head2 is_absolute, is_relative 2683 2684 if ( path("/tmp")->is_absolute ) { ... } 2685 if ( path("/tmp")->is_relative ) { ... } 2686 2687Booleans for whether the path appears absolute or relative. 2688 2689Current API available since 0.001. 2690 2691=head2 is_rootdir 2692 2693 while ( ! $path->is_rootdir ) { 2694 $path = $path->parent; 2695 ... 2696 } 2697 2698Boolean for whether the path is the root directory of the volume. I.e. the 2699C<dirname> is C<q[/]> and the C<basename> is C<q[]>. 2700 2701This works even on C<MSWin32> with drives and UNC volumes: 2702 2703 path("C:/")->is_rootdir; # true 2704 path("//server/share/")->is_rootdir; #true 2705 2706Current API available since 0.038. 2707 2708=head2 iterator 2709 2710 $iter = path("/tmp")->iterator( \%options ); 2711 2712Returns a code reference that walks a directory lazily. Each invocation 2713returns a C<Path::Tiny> object or undef when the iterator is exhausted. 2714 2715 $iter = path("/tmp")->iterator; 2716 while ( $path = $iter->() ) { 2717 ... 2718 } 2719 2720The current and parent directory entries ("." and "..") will not 2721be included. 2722 2723If the C<recurse> option is true, the iterator will walk the directory 2724recursively, breadth-first. If the C<follow_symlinks> option is also true, 2725directory links will be followed recursively. There is no protection against 2726loops when following links. If a directory is not readable, it will not be 2727followed. 2728 2729The default is the same as: 2730 2731 $iter = path("/tmp")->iterator( { 2732 recurse => 0, 2733 follow_symlinks => 0, 2734 } ); 2735 2736For a more powerful, recursive iterator with built-in loop avoidance, see 2737L<Path::Iterator::Rule>. 2738 2739See also L</visit>. 2740 2741Current API available since 0.016. 2742 2743=head2 lines, lines_raw, lines_utf8 2744 2745 @contents = path("/tmp/foo.txt")->lines; 2746 @contents = path("/tmp/foo.txt")->lines(\%options); 2747 @contents = path("/tmp/foo.txt")->lines_raw; 2748 @contents = path("/tmp/foo.txt")->lines_utf8; 2749 2750 @contents = path("/tmp/foo.txt")->lines( { chomp => 1, count => 4 } ); 2751 2752Returns a list of lines from a file. Optionally takes a hash-reference of 2753options. Valid options are C<binmode>, C<count> and C<chomp>. 2754 2755If C<binmode> is provided, it will be set on the handle prior to reading. 2756 2757If a positive C<count> is provided, that many lines will be returned from the 2758start of the file. If a negative C<count> is provided, the entire file will be 2759read, but only C<abs(count)> will be kept and returned. If C<abs(count)> 2760exceeds the number of lines in the file, all lines will be returned. 2761 2762If C<chomp> is set, any end-of-line character sequences (C<CR>, C<CRLF>, or 2763C<LF>) will be removed from the lines returned. 2764 2765Because the return is a list, C<lines> in scalar context will return the number 2766of lines (and throw away the data). 2767 2768 $number_of_lines = path("/tmp/foo.txt")->lines; 2769 2770C<lines_raw> is like C<lines> with a C<binmode> of C<:raw>. We use C<:raw> 2771instead of C<:unix> so PerlIO buffering can manage reading by line. 2772 2773C<lines_utf8> is like C<lines> with a C<binmode> of C<:raw:encoding(UTF-8)> 2774(or L<PerlIO::utf8_strict>). If L<Unicode::UTF8> 0.58+ is installed, a raw 2775UTF-8 slurp will be done and then the lines will be split. This is 2776actually faster than relying on C<:encoding(UTF-8)>, though a bit memory 2777intensive. If memory use is a concern, consider C<openr_utf8> and 2778iterating directly on the handle. 2779 2780Current API available since 0.065. 2781 2782=head2 mkpath 2783 2784 path("foo/bar/baz")->mkpath; 2785 path("foo/bar/baz")->mkpath( \%options ); 2786 2787Like calling C<make_path> from L<File::Path>. An optional hash reference 2788is passed through to C<make_path>. Errors will be trapped and an exception 2789thrown. Returns the list of directories created or an empty list if 2790the directories already exist, just like C<make_path>. 2791 2792Current API available since 0.001. 2793 2794=head2 move 2795 2796 path("foo.txt")->move("bar.txt"); 2797 2798Move the current path to the given destination path using Perl's 2799built-in L<rename|perlfunc/rename> function. Returns the result 2800of the C<rename> function (except it throws an exception if it fails). 2801 2802Current API available since 0.001. 2803 2804=head2 openr, openw, openrw, opena 2805 2806 $fh = path("foo.txt")->openr($binmode); # read 2807 $fh = path("foo.txt")->openr_raw; 2808 $fh = path("foo.txt")->openr_utf8; 2809 2810 $fh = path("foo.txt")->openw($binmode); # write 2811 $fh = path("foo.txt")->openw_raw; 2812 $fh = path("foo.txt")->openw_utf8; 2813 2814 $fh = path("foo.txt")->opena($binmode); # append 2815 $fh = path("foo.txt")->opena_raw; 2816 $fh = path("foo.txt")->opena_utf8; 2817 2818 $fh = path("foo.txt")->openrw($binmode); # read/write 2819 $fh = path("foo.txt")->openrw_raw; 2820 $fh = path("foo.txt")->openrw_utf8; 2821 2822Returns a file handle opened in the specified mode. The C<openr> style methods 2823take a single C<binmode> argument. All of the C<open*> methods have 2824C<open*_raw> and C<open*_utf8> equivalents that use C<:raw> and 2825C<:raw:encoding(UTF-8)>, respectively. 2826 2827An optional hash reference may be used to pass options. The only option is 2828C<locked>. If true, handles opened for writing, appending or read-write are 2829locked with C<LOCK_EX>; otherwise, they are locked for C<LOCK_SH>. 2830 2831 $fh = path("foo.txt")->openrw_utf8( { locked => 1 } ); 2832 2833See L</filehandle> for more on locking. 2834 2835Current API available since 0.011. 2836 2837=head2 parent 2838 2839 $parent = path("foo/bar/baz")->parent; # foo/bar 2840 $parent = path("foo/wibble.txt")->parent; # foo 2841 2842 $parent = path("foo/bar/baz")->parent(2); # foo 2843 2844Returns a C<Path::Tiny> object corresponding to the parent directory of the 2845original directory or file. An optional positive integer argument is the number 2846of parent directories upwards to return. C<parent> by itself is equivalent to 2847C<parent(1)>. 2848 2849Current API available since 0.014. 2850 2851=head2 realpath 2852 2853 $real = path("/baz/foo/../bar")->realpath; 2854 $real = path("foo/../bar")->realpath; 2855 2856Returns a new C<Path::Tiny> object with all symbolic links and upward directory 2857parts resolved using L<Cwd>'s C<realpath>. Compared to C<absolute>, this is 2858more expensive as it must actually consult the filesystem. 2859 2860If the parent path can't be resolved (e.g. if it includes directories that 2861don't exist), an exception will be thrown: 2862 2863 $real = path("doesnt_exist/foo")->realpath; # dies 2864 2865However, if the parent path exists and only the last component (e.g. filename) 2866doesn't exist, the realpath will be the realpath of the parent plus the 2867non-existent last component: 2868 2869 $real = path("./aasdlfasdlf")->realpath; # works 2870 2871The underlying L<Cwd> module usually worked this way on Unix, but died on 2872Windows (and some Unixes) if the full path didn't exist. As of version 0.064, 2873it's safe to use anywhere. 2874 2875Current API available since 0.001. 2876 2877=head2 relative 2878 2879 $rel = path("/tmp/foo/bar")->relative("/tmp"); # foo/bar 2880 2881Returns a C<Path::Tiny> object with a path relative to a new base path 2882given as an argument. If no argument is given, the current directory will 2883be used as the new base path. 2884 2885If either path is already relative, it will be made absolute based on the 2886current directly before determining the new relative path. 2887 2888The algorithm is roughly as follows: 2889 2890=over 4 2891 2892=item * 2893 2894If the original and new base path are on different volumes, an exception will be thrown. 2895 2896=item * 2897 2898If the original and new base are identical, the relative path is C<".">. 2899 2900=item * 2901 2902If the new base subsumes the original, the relative path is the original path with the new base chopped off the front 2903 2904=item * 2905 2906If the new base does not subsume the original, a common prefix path is determined (possibly the root directory) and the relative path will consist of updirs (C<"..">) to reach the common prefix, followed by the original path less the common prefix. 2907 2908=back 2909 2910Unlike C<File::Spec::abs2rel>, in the last case above, the calculation based 2911on a common prefix takes into account symlinks that could affect the updir 2912process. Given an original path "/A/B" and a new base "/A/C", 2913(where "A", "B" and "C" could each have multiple path components): 2914 2915=over 4 2916 2917=item * 2918 2919Symlinks in "A" don't change the result unless the last component of A is a symlink and the first component of "C" is an updir. 2920 2921=item * 2922 2923Symlinks in "B" don't change the result and will exist in the result as given. 2924 2925=item * 2926 2927Symlinks and updirs in "C" must be resolved to actual paths, taking into account the possibility that not all path components might exist on the filesystem. 2928 2929=back 2930 2931Current API available since 0.001. New algorithm (that accounts for 2932symlinks) available since 0.079. 2933 2934=head2 remove 2935 2936 path("foo.txt")->remove; 2937 2938This is just like C<unlink>, except for its error handling: if the path does 2939not exist, it returns false; if deleting the file fails, it throws an 2940exception. 2941 2942Current API available since 0.012. 2943 2944=head2 remove_tree 2945 2946 # directory 2947 path("foo/bar/baz")->remove_tree; 2948 path("foo/bar/baz")->remove_tree( \%options ); 2949 path("foo/bar/baz")->remove_tree( { safe => 0 } ); # force remove 2950 2951Like calling C<remove_tree> from L<File::Path>, but defaults to C<safe> mode. 2952An optional hash reference is passed through to C<remove_tree>. Errors will be 2953trapped and an exception thrown. Returns the number of directories deleted, 2954just like C<remove_tree>. 2955 2956If you want to remove a directory only if it is empty, use the built-in 2957C<rmdir> function instead. 2958 2959 rmdir path("foo/bar/baz/"); 2960 2961Current API available since 0.013. 2962 2963=head2 sibling 2964 2965 $foo = path("/tmp/foo.txt"); 2966 $sib = $foo->sibling("bar.txt"); # /tmp/bar.txt 2967 $sib = $foo->sibling("baz", "bam.txt"); # /tmp/baz/bam.txt 2968 2969Returns a new C<Path::Tiny> object relative to the parent of the original. 2970This is slightly more efficient than C<< $path->parent->child(...) >>. 2971 2972Current API available since 0.058. 2973 2974=head2 slurp, slurp_raw, slurp_utf8 2975 2976 $data = path("foo.txt")->slurp; 2977 $data = path("foo.txt")->slurp( {binmode => ":raw"} ); 2978 $data = path("foo.txt")->slurp_raw; 2979 $data = path("foo.txt")->slurp_utf8; 2980 2981Reads file contents into a scalar. Takes an optional hash reference which may 2982be used to pass options. The only available option is C<binmode>, which is 2983passed to C<binmode()> on the handle used for reading. 2984 2985C<slurp_raw> is like C<slurp> with a C<binmode> of C<:unix> for 2986a fast, unbuffered, raw read. 2987 2988C<slurp_utf8> is like C<slurp> with a C<binmode> of 2989C<:unix:encoding(UTF-8)> (or L<PerlIO::utf8_strict>). If L<Unicode::UTF8> 29900.58+ is installed, a raw slurp will be done instead and the result decoded 2991with C<Unicode::UTF8>. This is just as strict and is roughly an order of 2992magnitude faster than using C<:encoding(UTF-8)>. 2993 2994B<Note>: C<slurp> and friends lock the filehandle before slurping. If 2995you plan to slurp from a file created with L<File::Temp>, be sure to 2996close other handles or open without locking to avoid a deadlock: 2997 2998 my $tempfile = File::Temp->new(EXLOCK => 0); 2999 my $guts = path($tempfile)->slurp; 3000 3001Current API available since 0.004. 3002 3003=head2 spew, spew_raw, spew_utf8 3004 3005 path("foo.txt")->spew(@data); 3006 path("foo.txt")->spew(\@data); 3007 path("foo.txt")->spew({binmode => ":raw"}, @data); 3008 path("foo.txt")->spew_raw(@data); 3009 path("foo.txt")->spew_utf8(@data); 3010 3011Writes data to a file atomically. The file is written to a temporary file in 3012the same directory, then renamed over the original. An optional hash reference 3013may be used to pass options. The only option is C<binmode>, which is passed to 3014C<binmode()> on the handle used for writing. 3015 3016C<spew_raw> is like C<spew> with a C<binmode> of C<:unix> for a fast, 3017unbuffered, raw write. 3018 3019C<spew_utf8> is like C<spew> with a C<binmode> of C<:unix:encoding(UTF-8)> 3020(or L<PerlIO::utf8_strict>). If L<Unicode::UTF8> 0.58+ is installed, a raw 3021spew will be done instead on the data encoded with C<Unicode::UTF8>. 3022 3023B<NOTE>: because the file is written to a temporary file and then renamed, the 3024new file will wind up with permissions based on your current umask. This is a 3025feature to protect you from a race condition that would otherwise give 3026different permissions than you might expect. If you really want to keep the 3027original mode flags, use L</append> with the C<truncate> option. 3028 3029Current API available since 0.011. 3030 3031=head2 stat, lstat 3032 3033 $stat = path("foo.txt")->stat; 3034 $stat = path("/some/symlink")->lstat; 3035 3036Like calling C<stat> or C<lstat> from L<File::stat>. 3037 3038Current API available since 0.001. 3039 3040=head2 stringify 3041 3042 $path = path("foo.txt"); 3043 say $path->stringify; # same as "$path" 3044 3045Returns a string representation of the path. Unlike C<canonpath>, this method 3046returns the path standardized with Unix-style C</> directory separators. 3047 3048Current API available since 0.001. 3049 3050=head2 subsumes 3051 3052 path("foo/bar")->subsumes("foo/bar/baz"); # true 3053 path("/foo/bar")->subsumes("/foo/baz"); # false 3054 3055Returns true if the first path is a prefix of the second path at a directory 3056boundary. 3057 3058This B<does not> resolve parent directory entries (C<..>) or symlinks: 3059 3060 path("foo/bar")->subsumes("foo/bar/../baz"); # true 3061 3062If such things are important to you, ensure that both paths are resolved to 3063the filesystem with C<realpath>: 3064 3065 my $p1 = path("foo/bar")->realpath; 3066 my $p2 = path("foo/bar/../baz")->realpath; 3067 if ( $p1->subsumes($p2) ) { ... } 3068 3069Current API available since 0.048. 3070 3071=head2 touch 3072 3073 path("foo.txt")->touch; 3074 path("foo.txt")->touch($epoch_secs); 3075 3076Like the Unix C<touch> utility. Creates the file if it doesn't exist, or else 3077changes the modification and access times to the current time. If the first 3078argument is the epoch seconds then it will be used. 3079 3080Returns the path object so it can be easily chained with other methods: 3081 3082 # won't die if foo.txt doesn't exist 3083 $content = path("foo.txt")->touch->slurp; 3084 3085Current API available since 0.015. 3086 3087=head2 touchpath 3088 3089 path("bar/baz/foo.txt")->touchpath; 3090 3091Combines C<mkpath> and C<touch>. Creates the parent directory if it doesn't exist, 3092before touching the file. Returns the path object like C<touch> does. 3093 3094Current API available since 0.022. 3095 3096=head2 visit 3097 3098 path("/tmp")->visit( \&callback, \%options ); 3099 3100Executes a callback for each child of a directory. It returns a hash 3101reference with any state accumulated during iteration. 3102 3103The options are the same as for L</iterator> (which it uses internally): 3104C<recurse> and C<follow_symlinks>. Both default to false. 3105 3106The callback function will receive a C<Path::Tiny> object as the first argument 3107and a hash reference to accumulate state as the second argument. For example: 3108 3109 # collect files sizes 3110 my $sizes = path("/tmp")->visit( 3111 sub { 3112 my ($path, $state) = @_; 3113 return if $path->is_dir; 3114 $state->{$path} = -s $path; 3115 }, 3116 { recurse => 1 } 3117 ); 3118 3119For convenience, the C<Path::Tiny> object will also be locally aliased as the 3120C<$_> global variable: 3121 3122 # print paths matching /foo/ 3123 path("/tmp")->visit( sub { say if /foo/ }, { recurse => 1} ); 3124 3125If the callback returns a B<reference> to a false scalar value, iteration will 3126terminate. This is not the same as "pruning" a directory search; this just 3127stops all iteration and returns the state hash reference. 3128 3129 # find up to 10 files larger than 100K 3130 my $files = path("/tmp")->visit( 3131 sub { 3132 my ($path, $state) = @_; 3133 $state->{$path}++ if -s $path > 102400 3134 return \0 if keys %$state == 10; 3135 }, 3136 { recurse => 1 } 3137 ); 3138 3139If you want more flexible iteration, use a module like L<Path::Iterator::Rule>. 3140 3141Current API available since 0.062. 3142 3143=head2 volume 3144 3145 $vol = path("/tmp/foo.txt")->volume; # "" 3146 $vol = path("C:/tmp/foo.txt")->volume; # "C:" 3147 3148Returns the volume portion of the path. This is equivalent 3149to what L<File::Spec> would give from C<splitpath> and thus 3150usually is the empty string on Unix-like operating systems or the 3151drive letter for an absolute path on C<MSWin32>. 3152 3153Current API available since 0.001. 3154 3155=for Pod::Coverage openr_utf8 opena_utf8 openw_utf8 openrw_utf8 3156openr_raw opena_raw openw_raw openrw_raw 3157IS_WIN32 FREEZE THAW TO_JSON abs2rel 3158 3159=head1 EXCEPTION HANDLING 3160 3161Simple usage errors will generally croak. Failures of underlying Perl 3162functions will be thrown as exceptions in the class 3163C<Path::Tiny::Error>. 3164 3165A C<Path::Tiny::Error> object will be a hash reference with the following fields: 3166 3167=over 4 3168 3169=item * 3170 3171C<op> — a description of the operation, usually function call and any extra info 3172 3173=item * 3174 3175C<file> — the file or directory relating to the error 3176 3177=item * 3178 3179C<err> — hold C<$!> at the time the error was thrown 3180 3181=item * 3182 3183C<msg> — a string combining the above data and a Carp-like short stack trace 3184 3185=back 3186 3187Exception objects will stringify as the C<msg> field. 3188 3189=head1 ENVIRONMENT 3190 3191=head2 PERL_PATH_TINY_NO_FLOCK 3192 3193If the environment variable C<PERL_PATH_TINY_NO_FLOCK> is set to a true 3194value then flock will NOT be used when accessing files (this is not 3195recommended). 3196 3197=head1 CAVEATS 3198 3199=head2 Subclassing not supported 3200 3201For speed, this class is implemented as an array based object and uses many 3202direct function calls internally. You must not subclass it and expect 3203things to work properly. 3204 3205=head2 File locking 3206 3207If flock is not supported on a platform, it will not be used, even if 3208locking is requested. 3209 3210In situations where a platform normally would support locking, but the 3211flock fails due to a filesystem limitation, Path::Tiny has some heuristics 3212to detect this and will warn once and continue in an unsafe mode. If you 3213want this failure to be fatal, you can fatalize the 'flock' warnings 3214category: 3215 3216 use warnings FATAL => 'flock'; 3217 3218See additional caveats below. 3219 3220=head3 NFS and BSD 3221 3222On BSD, Perl's flock implementation may not work to lock files on an 3223NFS filesystem. If detected, this situation will warn once, as described 3224above. 3225 3226=head3 Lustre 3227 3228The Lustre filesystem does not support flock. If detected, this situation 3229will warn once, as described above. 3230 3231=head3 AIX and locking 3232 3233AIX requires a write handle for locking. Therefore, calls that normally 3234open a read handle and take a shared lock instead will open a read-write 3235handle and take an exclusive lock. If the user does not have write 3236permission, no lock will be used. 3237 3238=head2 utf8 vs UTF-8 3239 3240All the C<*_utf8> methods by default use C<:encoding(UTF-8)> -- either as 3241C<:unix:encoding(UTF-8)> (unbuffered) or C<:raw:encoding(UTF-8)> (buffered) -- 3242which is strict against the Unicode spec and disallows illegal Unicode 3243codepoints or UTF-8 sequences. 3244 3245Unfortunately, C<:encoding(UTF-8)> is very, very slow. If you install 3246L<Unicode::UTF8> 0.58 or later, that module will be used by some C<*_utf8> 3247methods to encode or decode data after a raw, binary input/output operation, 3248which is much faster. Alternatively, if you install L<PerlIO::utf8_strict>, 3249that will be used instead of C<:encoding(UTF-8)> and is also very fast. 3250 3251If you need the performance and can accept the security risk, 3252C<< slurp({binmode => ":unix:utf8"}) >> will be faster than C<:unix:encoding(UTF-8)> 3253(but not as fast as C<Unicode::UTF8>). 3254 3255Note that the C<*_utf8> methods read in B<raw> mode. There is no CRLF 3256translation on Windows. If you must have CRLF translation, use the regular 3257input/output methods with an appropriate binmode: 3258 3259 $path->spew_utf8($data); # raw 3260 $path->spew({binmode => ":encoding(UTF-8)"}, $data; # LF -> CRLF 3261 3262=head2 Default IO layers and the open pragma 3263 3264If you have Perl 5.10 or later, file input/output methods (C<slurp>, C<spew>, 3265etc.) and high-level handle opening methods ( C<filehandle>, C<openr>, 3266C<openw>, etc. ) respect default encodings set by the C<-C> switch or lexical 3267L<open> settings of the caller. For UTF-8, this is almost certainly slower 3268than using the dedicated C<_utf8> methods if you have L<Unicode::UTF8>. 3269 3270=head1 TYPE CONSTRAINTS AND COERCION 3271 3272A standard L<MooseX::Types> library is available at 3273L<MooseX::Types::Path::Tiny>. A L<Type::Tiny> equivalent is available as 3274L<Types::Path::Tiny>. 3275 3276=head1 SEE ALSO 3277 3278These are other file/path utilities, which may offer a different feature 3279set than C<Path::Tiny>. 3280 3281=over 4 3282 3283=item * 3284 3285L<File::chmod> 3286 3287=item * 3288 3289L<File::Fu> 3290 3291=item * 3292 3293L<IO::All> 3294 3295=item * 3296 3297L<Path::Class> 3298 3299=back 3300 3301These iterators may be slightly faster than the recursive iterator in 3302C<Path::Tiny>: 3303 3304=over 4 3305 3306=item * 3307 3308L<Path::Iterator::Rule> 3309 3310=item * 3311 3312L<File::Next> 3313 3314=back 3315 3316There are probably comparable, non-Tiny tools. Let me know if you want me to 3317add a module to the list. 3318 3319This module was featured in the L<2013 Perl Advent Calendar|http://www.perladvent.org/2013/2013-12-18.html>. 3320 3321=for :stopwords cpan testmatrix url bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan 3322 3323=head1 SUPPORT 3324 3325=head2 Bugs / Feature Requests 3326 3327Please report any bugs or feature requests through the issue tracker 3328at L<https://github.com/dagolden/Path-Tiny/issues>. 3329You will be notified automatically of any progress on your issue. 3330 3331=head2 Source Code 3332 3333This is open source software. The code repository is available for 3334public review and contribution under the terms of the license. 3335 3336L<https://github.com/dagolden/Path-Tiny> 3337 3338 git clone https://github.com/dagolden/Path-Tiny.git 3339 3340=head1 AUTHOR 3341 3342David Golden <dagolden@cpan.org> 3343 3344=head1 CONTRIBUTORS 3345 3346=for stopwords Alex Efros Aristotle Pagaltzis Chris Williams Dan Book Dave Rolsky David Steinbrunner Doug Bell Flavio Poletti Gabor Szabo Gabriel Andrade George Hartzell Geraud Continsouzas Goro Fuji Graham Knop Ollis Ian Sillitoe James Hunt John Karr Karen Etheridge Mark Ellis Martin H. Sluka Kjeldsen Michael G. Schwern Nigel Gregoire Philippe Bruhat (BooK) regina-verbae Roy Ivy III Shlomi Fish Smylers Tatsuhiko Miyagawa Toby Inkster Yanick Champoux 김도형 - Keedi Kim 3347 3348=over 4 3349 3350=item * 3351 3352Alex Efros <powerman@powerman.name> 3353 3354=item * 3355 3356Aristotle Pagaltzis <pagaltzis@gmx.de> 3357 3358=item * 3359 3360Chris Williams <bingos@cpan.org> 3361 3362=item * 3363 3364Dan Book <grinnz@grinnz.com> 3365 3366=item * 3367 3368Dave Rolsky <autarch@urth.org> 3369 3370=item * 3371 3372David Steinbrunner <dsteinbrunner@pobox.com> 3373 3374=item * 3375 3376Doug Bell <madcityzen@gmail.com> 3377 3378=item * 3379 3380Flavio Poletti <flavio@polettix.it> 3381 3382=item * 3383 3384Gabor Szabo <szabgab@cpan.org> 3385 3386=item * 3387 3388Gabriel Andrade <gabiruh@gmail.com> 3389 3390=item * 3391 3392George Hartzell <hartzell@cpan.org> 3393 3394=item * 3395 3396Geraud Continsouzas <geraud@scsi.nc> 3397 3398=item * 3399 3400Goro Fuji <gfuji@cpan.org> 3401 3402=item * 3403 3404Graham Knop <haarg@haarg.org> 3405 3406=item * 3407 3408Graham Ollis <plicease@cpan.org> 3409 3410=item * 3411 3412Ian Sillitoe <ian@sillit.com> 3413 3414=item * 3415 3416James Hunt <james@niftylogic.com> 3417 3418=item * 3419 3420John Karr <brainbuz@brainbuz.org> 3421 3422=item * 3423 3424Karen Etheridge <ether@cpan.org> 3425 3426=item * 3427 3428Mark Ellis <mark.ellis@cartridgesave.co.uk> 3429 3430=item * 3431 3432Martin H. Sluka <fany@cpan.org> 3433 3434=item * 3435 3436Martin Kjeldsen <mk@bluepipe.dk> 3437 3438=item * 3439 3440Michael G. Schwern <mschwern@cpan.org> 3441 3442=item * 3443 3444Nigel Gregoire <nigelgregoire@gmail.com> 3445 3446=item * 3447 3448Philippe Bruhat (BooK) <book@cpan.org> 3449 3450=item * 3451 3452regina-verbae <regina-verbae@users.noreply.github.com> 3453 3454=item * 3455 3456Roy Ivy III <rivy@cpan.org> 3457 3458=item * 3459 3460Shlomi Fish <shlomif@shlomifish.org> 3461 3462=item * 3463 3464Smylers <Smylers@stripey.com> 3465 3466=item * 3467 3468Tatsuhiko Miyagawa <miyagawa@bulknews.net> 3469 3470=item * 3471 3472Toby Inkster <tobyink@cpan.org> 3473 3474=item * 3475 3476Yanick Champoux <yanick@babyl.dyndns.org> 3477 3478=item * 3479 3480김도형 - Keedi Kim <keedi@cpan.org> 3481 3482=back 3483 3484=head1 COPYRIGHT AND LICENSE 3485 3486This software is Copyright (c) 2014 by David Golden. 3487 3488This is free software, licensed under: 3489 3490 The Apache License, Version 2.0, January 2004 3491 3492=cut 3493