home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _4f077812db9f42a08ebaf43e24d0d6fd < prev    next >
Encoding:
Text File  |  2004-06-01  |  35.9 KB  |  1,188 lines

  1. ### the gnu tar specification:
  2. ### http://www.gnu.org/manual/tar/html_node/tar_toc.html
  3. ###
  4. ### and the pax format spec, which tar derives from:
  5. ### http://www.opengroup.org/onlinepubs/007904975/utilities/pax.html
  6.  
  7. package Archive::Tar;
  8. require 5.005_03;
  9.  
  10. use strict;
  11. use vars qw[$DEBUG $error $VERSION $WARN $FOLLOW_SYMLINK $CHOWN $CHMOD];
  12. $DEBUG          = 0;
  13. $WARN           = 1;
  14. $FOLLOW_SYMLINK = 0;
  15. $VERSION        = "1.08";
  16. $CHOWN          = 1;
  17. $CHMOD          = 1;
  18.  
  19. use IO::File;
  20. use Cwd;
  21. use Carp qw(carp);
  22. use File::Spec ();
  23. use File::Spec::Unix ();
  24. use File::Path ();
  25.  
  26. use Archive::Tar::File;
  27. use Archive::Tar::Constant;
  28.  
  29. =head1 NAME
  30.  
  31. Archive::Tar - module for manipulations of tar archives
  32.  
  33. =head1 SYNOPSIS
  34.  
  35.     use Archive::Tar;
  36.     my $tar = Archive::Tar->new;
  37.     
  38.     $tar->read('origin.tgz',1); 
  39.     $tar->extract();
  40.     
  41.     $tar->add_files('file/foo.pl', 'docs/README');
  42.     $tar->add_data('file/baz.txt', 'This is the contents now');
  43.     
  44.     $tar->rename('oldname', 'new/file/name');
  45.     
  46.     $tar->write('files.tar');
  47.     
  48. =head1 DESCRIPTION
  49.     
  50. Archive::Tar provides an object oriented mechanism for handling tar
  51. files.  It provides class methods for quick and easy files handling
  52. while also allowing for the creation of tar file objects for custom
  53. manipulation.  If you have the IO::Zlib module installed,
  54. Archive::Tar will also support compressed or gzipped tar files.
  55.  
  56. An object of class Archive::Tar represents a .tar(.gz) archive full 
  57. of files and things.
  58.  
  59. =head1 Object Methods
  60.  
  61. =head2 Archive::Tar->new( [$file, $compressed] )
  62.  
  63. Returns a new Tar object. If given any arguments, C<new()> calls the
  64. C<read()> method automatically, passing on the arguments provided to 
  65. the C<read()> method.
  66.  
  67. If C<new()> is invoked with arguments and the C<read()> method fails 
  68. for any reason, C<new()> returns undef.
  69.  
  70. =cut
  71.  
  72. my $tmpl = {
  73.     _data   => [ ],
  74.     _file   => 'Unknown',
  75. };    
  76.  
  77. ### install get/set accessors for this object.
  78. for my $key ( keys %$tmpl ) {
  79.     no strict 'refs';
  80.     *{__PACKAGE__."::$key"} = sub {
  81.         my $self = shift;
  82.         $self->{$key} = $_[0] if @_;
  83.         return $self->{$key};
  84.     }
  85. }
  86.  
  87. sub new {
  88.  
  89.     ### copying $tmpl here since a shallow copy makes it use the
  90.     ### same aref, causing for files to remain in memory always.
  91.     my $obj = bless { _data => [ ], _file => 'Unknown' }, shift;
  92.  
  93.     $obj->read( @_ ) if @_;
  94.     
  95.     return $obj;
  96. }
  97.  
  98. =head2 $tar->read ( $filename|$handle, $compressed, {opt => 'val'} )
  99.  
  100. Read the given tar file into memory. 
  101. The first argument can either be the name of a file or a reference to
  102. an already open filehandle (or an IO::Zlib object if it's compressed)  
  103. The second argument indicates whether the file referenced by the first 
  104. argument is compressed.
  105.  
  106. The C<read> will I<replace> any previous content in C<$tar>!
  107.  
  108. The second argument may be considered optional if IO::Zlib is
  109. installed, since it will transparently Do The Right Thing. 
  110. Archive::Tar will warn if you try to pass a compressed file if 
  111. IO::Zlib is not available and simply return.
  112.  
  113. The third argument can be a hash reference with options. Note that 
  114. all options are case-sensitive.
  115.  
  116. =over 4
  117.  
  118. =item limit
  119.  
  120. Do not read more than C<limit> files. This is usefull if you have 
  121. very big archives, and are only interested in the first few files.
  122.  
  123. =item extract
  124.  
  125. If set to true, immediately extract entries when reading them. This
  126. gives you the same memory break as the C<extract_archive> function.
  127. Note however that entries will not be read into memory, but written 
  128. straight to disk.
  129.  
  130. =back
  131.  
  132. All files are stored internally as C<Archive::Tar::File> objects.
  133. Please consult the L<Archive::Tar::File> documentation for details.
  134.  
  135. Returns the number of files read in scalar context, and a list of
  136. C<Archive::Tar::File> objects in list context.
  137.  
  138. =cut
  139.  
  140. sub read {
  141.     my $self = shift;    
  142.     my $file = shift; $file = $self->_file unless defined $file;
  143.     my $gzip = shift || 0;
  144.     my $opts = shift || {};
  145.     
  146.     unless( defined $file ) {
  147.         $self->_error( qq[No file to read from!] );
  148.         return;
  149.     } else {
  150.         $self->_file( $file );
  151.     }     
  152.     
  153.     my $handle = $self->_get_handle($file, $gzip, READ_ONLY->( ZLIB ) ) 
  154.                     or return;
  155.  
  156.     my $data = $self->_read_tar( $handle, $opts ) or return;
  157.  
  158.     $self->_data( $data );    
  159.  
  160.     return wantarray ? @$data : scalar @$data;
  161. }
  162.  
  163. sub _get_handle {
  164.     my $self = shift;
  165.     my $file = shift;   return unless defined $file;
  166.                         return $file if ref $file;
  167.                         
  168.     my $gzip = shift || 0;
  169.     my $mode = shift || READ_ONLY->( ZLIB ); # default to read only
  170.     
  171.     my $fh; my $bin;
  172.     
  173.     ### only default to ZLIB if we're not trying to /write/ to a handle ###
  174.     if( ZLIB and $gzip || MODE_READ->( $mode ) ) {
  175.         
  176.         ### IO::Zlib will Do The Right Thing, even when passed a plain file ###
  177.         $fh = new IO::Zlib;
  178.     
  179.     } else {    
  180.         if( $gzip ) {
  181.             $self->_error( qq[Compression not available - Install IO::Zlib!] );
  182.             return;
  183.         
  184.         } else {
  185.             $fh = new IO::File;
  186.             $bin++;
  187.         }
  188.     }
  189.         
  190.     unless( $fh->open( $file, $mode ) ) {
  191.         $self->_error( qq[Could not create filehandle for '$file': $!!] );
  192.         return;
  193.     }
  194.     
  195.     binmode $fh if $bin;
  196.     
  197.     return $fh;
  198. }
  199.  
  200. sub _read_tar {
  201.     my $self    = shift;
  202.     my $handle  = shift or return;
  203.     my $opts    = shift || {};
  204.  
  205.     my $count   = $opts->{limit}    || 0;
  206.     my $extract = $opts->{extract}  || 0;
  207.     
  208.     ### set a cap on the amount of files to extract ###
  209.     my $limit   = 0;
  210.     $limit = 1 if $count > 0;
  211.  
  212.     my $tarfile = [ ];
  213.     my $chunk;
  214.     my $read = 0;
  215.     my $real_name;  # to set the name of a file when we're encountering @longlink
  216.     my $data;
  217.          
  218.     LOOP: 
  219.     while( $handle->read( $chunk, HEAD ) ) {        
  220.         
  221.         unless( $read++ ) {
  222.             my $gzip = GZIP_MAGIC_NUM;
  223.             if( $chunk =~ /$gzip/ ) {
  224.                 $self->_error( qq[Can not read compressed format in tar-mode] );
  225.                 return;
  226.             }
  227.         }
  228.               
  229.         ### if we can't read in all bytes... ###
  230.         last if length $chunk != HEAD;
  231.         
  232.         # Apparently this should really be two blocks of 512 zeroes,
  233.         # but GNU tar sometimes gets it wrong. See comment in the
  234.         # source code (tar.c) to GNU cpio.
  235.         last if $chunk eq TAR_END; 
  236.         
  237.         my $entry; 
  238.         unless( $entry = Archive::Tar::File->new( chunk => $chunk ) ) {
  239.             $self->_error( qq[Couldn't read chunk '$chunk'] );
  240.             next;
  241.         }
  242.         
  243.         ### ignore labels:
  244.         ### http://www.gnu.org/manual/tar/html_node/tar_139.html
  245.         next if $entry->is_label;
  246.         
  247.         if( length $entry->type and ($entry->is_file || $entry->is_longlink) ) {
  248.             
  249.             if ( $entry->is_file && !$entry->validate ) {
  250.                 $self->_error( $entry->name . qq[: checksum error] );
  251.                 next LOOP;
  252.             }
  253.           
  254.             ### part II of the @LongLink munging -- need to do /after/
  255.             ### the checksum check.
  256.  
  257.             
  258.             my $block = BLOCK_SIZE->( $entry->size );
  259.  
  260.             $data = $entry->get_content_by_ref;
  261. #            while( $block ) {
  262. #                $handle->read( $data, $block ) or (
  263. #                    $self->_error( qq[Could not read block for ] . $entry->name ),
  264. #                    return
  265. #                );
  266. #                $block > BUFFER 
  267. #                    ? $block -= BUFFER
  268. #                    : last;   
  269. #                last if $block eq TAR_END;             
  270. #            }
  271.             
  272.             ### just read everything into memory 
  273.             ### can't do lazy loading since IO::Zlib doesn't support 'seek'
  274.             ### this is because Compress::Zlib doesn't support it =/            
  275.             if( $handle->read( $$data, $block ) < $block ) {
  276.                 $self->_error( qq[Read error on tarfile ']. $entry->name ."'" );
  277.                 return;
  278.             }
  279.  
  280.             ### throw away trailing garbage ###
  281.             substr ($$data, $entry->size) = "";
  282.         }
  283.         
  284.         
  285.         ### clean up of the entries.. posix tar /apparently/ has some
  286.         ### weird 'feature' that allows for filenames > 255 characters
  287.         ### they'll put a header in with as name '././@LongLink' and the
  288.         ### contents will be the name of the /next/ file in the archive
  289.         ### pretty crappy and kludgy if you ask me
  290.         
  291.         ### set the name for the next entry if this is a @LongLink;
  292.         ### this is one ugly hack =/ but needed for direct extraction
  293.         if( $entry->is_longlink ) {
  294.             $real_name = $data;
  295.             next;
  296.         } elsif ( defined $real_name ) {
  297.             $entry->name( $$real_name );
  298.             undef $real_name;      
  299.         }
  300.  
  301.         $self->_extract_file( $entry )  if $extract && !$entry->is_longlink
  302.                                         && !$entry->is_unknown && !$entry->is_label;
  303.         
  304.         ### Guard against tarfiles with garbage at the end
  305.         last LOOP if $entry->name eq ''; 
  306.     
  307.         ### push only the name on the rv if we're extracting -- for extract_archive
  308.         push @$tarfile, ($extract ? $entry->name : $entry);
  309.     
  310.         if( $limit ) {
  311.             $count-- unless $entry->is_longlink || $entry->is_dir;    
  312.             last LOOP unless $count;
  313.         }
  314.     } continue {
  315.         undef $data;
  316.     }      
  317.     
  318.     return $tarfile;
  319. }    
  320.  
  321. =head2 $tar->contains_file( $filename )
  322.  
  323. Check if the archive contains a certain file.
  324. It will return true if the file is in the archive, false otherwise.
  325.  
  326. Note however, that this function does an exact match using C<eq>
  327. on the full path. So it can not compensate for case-insensitive file-
  328. systems or compare 2 paths to see if they would point to the same
  329. underlying file.
  330.  
  331. =cut
  332.  
  333. sub contains_file {
  334.     my $self = shift;
  335.     my $full = shift or return;
  336.     
  337.     my @parts = File::Spec->splitdir($full);
  338.     my $file  = pop @parts;
  339.     my $path  = File::Spec::Unix->catdir( @parts );
  340.     
  341.     for my $obj ( $self->get_files ) {
  342.         next unless $file eq $obj->name;
  343.         next unless $path eq $obj->prefix;
  344.     
  345.         return 1;       
  346.     }      
  347.     return;
  348. }    
  349.  
  350. =head2 $tar->extract( [@filenames] )
  351.  
  352. Write files whose names are equivalent to any of the names in
  353. C<@filenames> to disk, creating subdirectories as necessary. This
  354. might not work too well under VMS.  
  355. Under MacPerl, the file's modification time will be converted to the
  356. MacOS zero of time, and appropriate conversions will be done to the 
  357. path.  However, the length of each element of the path is not 
  358. inspected to see whether it's longer than MacOS currently allows (32
  359. characters).
  360.  
  361. If C<extract> is called without a list of file names, the entire
  362. contents of the archive are extracted.
  363.  
  364. Returns a list of filenames extracted.
  365.  
  366. =cut
  367.  
  368. sub extract {
  369.     my $self    = shift;
  370.     my @files   = @_ ? @_ : $self->list_files;
  371.  
  372.     unless( scalar @files ) {
  373.         $self->_error( qq[No files found for ] . $self->_file );
  374.         return;
  375.     }
  376.     
  377.     for my $file ( @files ) {
  378.         for my $entry ( @{$self->_data} ) {
  379.             next unless $file eq $entry->name;
  380.     
  381.             unless( $self->_extract_file( $entry ) ) {
  382.                 $self->_error( qq[Could not extract '$file'] );
  383.                 return;
  384.             }        
  385.         }
  386.     }
  387.          
  388.     return @files;        
  389. }
  390.  
  391. sub _extract_file {
  392.     my $self    = shift;
  393.     my $entry   = shift or return;
  394.     my $cwd     = cwd();
  395.     
  396.                             ### splitpath takes a bool at the end to indicate that it's splitting a dir    
  397.     my ($vol,$dirs,$file)   = File::Spec::Unix->splitpath( $entry->name, $entry->is_dir );
  398.     my @dirs                = File::Spec::Unix->splitdir( $dirs );
  399.     my @cwd                 = File::Spec->splitdir( $cwd );
  400.     my $dir                 = File::Spec->catdir(@cwd, @dirs);               
  401.     
  402.     if( -e $dir && !-d _ ) {
  403.         $^W && $self->_error( qq['$dir' exists, but it's not a directory!\n] );
  404.         return;
  405.     }
  406.     
  407.     unless ( -d _ ) {
  408.         eval { File::Path::mkpath( $dir, 0, 0777 ) };
  409.         if( $@ ) {
  410.             $self->_error( qq[Could not create directory '$dir': $@] );
  411.             return;
  412.         }
  413.     }
  414.     
  415.     ### we're done if we just needed to create a dir ###
  416.     return 1 if $entry->is_dir;
  417.     
  418.     my $full = File::Spec->catfile( $dir, $file );
  419.     
  420.     if( $entry->is_unknown ) {
  421.         $self->_error( qq[Unknown file type for file '$full'] );
  422.         return;
  423.     }
  424.     
  425.     if( length $entry->type && $entry->is_file ) {
  426.         my $fh = IO::File->new;
  427.         $fh->open( '>' . $full ) or (
  428.             $self->_error( qq[Could not open file '$full': $!] ),
  429.             return
  430.         );
  431.     
  432.         if( $entry->size ) {
  433.             binmode $fh;
  434.             syswrite $fh, $entry->data or (
  435.                 $self->_error( qq[Could not write data to '$full'] ),
  436.                 return
  437.             );
  438.         }
  439.         
  440.         close $fh or (
  441.             $self->_error( qq[Could not close file '$full'] ),
  442.             return
  443.         );     
  444.     
  445.     } else {
  446.         $self->_make_special_file( $entry, $full ) or return;
  447.     } 
  448.  
  449.     utime time, $entry->mtime - TIME_OFFSET, $full or
  450.         $self->_error( qq[Could not update timestamp] );
  451.  
  452.     if( $CHOWN && CAN_CHOWN ) {
  453.         chown $entry->uid, $entry->gid, $full or
  454.             $self->_error( qq[Could not set uid/gid on '$full'] );
  455.     }
  456.     
  457.     if( $CHMOD ) {
  458.         chmod $entry->mode, $full or
  459.             $self->_error( qq[Could not chown '$full' to ] . $entry->mode );
  460.     }            
  461.     
  462.     return 1;
  463. }
  464.  
  465. sub _make_special_file {
  466.     my $self    = shift;
  467.     my $entry   = shift     or return;
  468.     my $file    = shift;    return unless defined $file;
  469.     
  470.     my $err;
  471.     
  472.     if( $entry->is_symlink ) {
  473.         ON_UNIX && symlink( $entry->linkname, $file ) or 
  474.             $err =  qq[Making symbolink link from '] . $entry->linkname .
  475.                     qq[' to '$file' failed]; 
  476.     
  477.     } elsif ( $entry->is_hardlink ) {
  478.         ON_UNIX && link( $entry->linkname, $file ) or 
  479.             $err =  qq[Making hard link from '] . $entry->linkname .
  480.                     qq[' to '$file' failed];     
  481.     
  482.     } elsif ( $entry->is_fifo ) {
  483.         ON_UNIX && !system('mknod', $file, 'p') or 
  484.             $err = qq[Making fifo ']. $entry->name .qq[' failed];
  485.  
  486.     } elsif ( $entry->is_blockdev or $entry->is_chardev ) {
  487.         my $mode = $entry->is_blockdev ? 'b' : 'c';
  488.             
  489.         ON_UNIX && !system('mknod', $file, $mode, $entry->devmajor, $entry->devminor ) or
  490.             $err =  qq[Making block device ']. $entry->name .qq[' (maj=] .
  491.                     $entry->devmajor . qq[ min=] . $entry->devminor .qq[) failed.];          
  492.  
  493.     } elsif ( $entry->is_socket ) {
  494.         ### the original doesn't do anything special for sockets.... ###     
  495.         1;
  496.     }
  497.     
  498.     return $err ? $self->_error( $err ) : 1;
  499. }
  500.  
  501. =head2 $tar->list_files( [\@properties] )
  502.  
  503. Returns a list of the names of all the files in the archive.
  504.  
  505. If C<list_files()> is passed an array reference as its first argument
  506. it returns a list of hash references containing the requested
  507. properties of each file.  The following list of properties is
  508. supported: name, size, mtime (last modified date), mode, uid, gid,
  509. linkname, uname, gname, devmajor, devminor, prefix.
  510.  
  511. Passing an array reference containing only one element, 'name', is
  512. special cased to return a list of names rather than a list of hash
  513. references, making it equivalent to calling C<list_files> without 
  514. arguments.
  515.  
  516. =cut
  517.  
  518. sub list_files {
  519.     my $self = shift;
  520.     my $aref = shift || [ ];
  521.     
  522.     unless( $self->_data ) {
  523.         $self->read() or return;
  524.     }
  525.     
  526.     if( @$aref == 0 or ( @$aref == 1 and $aref->[0] eq 'name' ) ) {
  527.         return map { $_->name } @{$self->_data};     
  528.     } else {
  529.     
  530.         #my @rv;
  531.         #for my $obj ( @{$self->_data} ) {
  532.         #    push @rv, { map { $_ => $obj->$_() } @$aref };
  533.         #}
  534.         #return @rv;
  535.         
  536.         ### this does the same as the above.. just needs a +{ }
  537.         ### to make sure perl doesn't confuse it for a block
  538.         return map { my $o=$_; +{ map { $_ => $o->$_() } @$aref } } @{$self->_data}; 
  539.     }    
  540. }
  541.  
  542. sub _find_entry {
  543.     my $self = shift;
  544.     my $file = shift;
  545.  
  546.     unless( defined $file ) {
  547.         $self->_error( qq[No file specified] );
  548.         return;
  549.     }
  550.     
  551.     for my $entry ( @{$self->_data} ) {
  552.         return $entry if $entry->name eq $file;      
  553.     }
  554.     
  555.     $self->_error( qq[No such file in archive: '$file'] );
  556.     return;
  557. }    
  558.  
  559. =head2 $tar->get_files( [@filenames] )
  560.  
  561. Returns the C<Archive::Tar::File> objects matching the filenames 
  562. provided. If no filename list was passed, all C<Archive::Tar::File>
  563. objects in the current Tar object are returned.
  564.  
  565. Please refer to the C<Archive::Tar::File> documentation on how to 
  566. handle these objects.
  567.  
  568. =cut
  569.  
  570. sub get_files {
  571.     my $self = shift;
  572.     
  573.     return @{ $self->_data } unless @_;
  574.     
  575.     my @list;
  576.     for my $file ( @_ ) {
  577.         push @list, grep { defined } $self->_find_entry( $file );
  578.     }
  579.     
  580.     return @list;
  581. }
  582.  
  583. =head2 $tar->get_content( $file )
  584.  
  585. Return the content of the named file.
  586.  
  587. =cut
  588.     
  589. sub get_content {
  590.     my $self = shift;
  591.     my $entry = $self->_find_entry( shift ) or return;
  592.     
  593.     return $entry->data;        
  594. }    
  595.  
  596. =head2 $tar->replace_content( $file, $content )
  597.  
  598. Make the string $content be the content for the file named $file.
  599.  
  600. =cut
  601.  
  602. sub replace_content {
  603.     my $self = shift;
  604.     my $entry = $self->_find_entry( shift ) or return;
  605.  
  606.     return $entry->replace_content( shift );
  607. }    
  608.  
  609. =head2 $tar->rename( $file, $new_name ) 
  610.  
  611. Rename the file of the in-memory archive to $new_name.
  612.  
  613. Note that you must specify a Unix path for $new_name, since per tar
  614. standard, all files in the archive must be Unix paths.
  615.  
  616. Returns true on success and false on failure.
  617.  
  618. =cut
  619.  
  620. sub rename {
  621.     my $self = shift;
  622.     my $file = shift; return unless defined $file;
  623.     my $new  = shift; return unless defined $new;
  624.     
  625.     my $entry = $self->_find_entry( $file ) or return;
  626.     
  627.     return $entry->rename( $new );
  628. }    
  629.  
  630. =head2 $tar->remove (@filenamelist)
  631.  
  632. Removes any entries with names matching any of the given filenames
  633. from the in-memory archive. Returns a list of C<Archive::Tar::File>
  634. objects that remain. 
  635.  
  636. =cut
  637.  
  638. sub remove {
  639.     my $self = shift;
  640.     my @list = @_;
  641.     
  642.     my %seen = map { $_->name => $_ } @{$self->_data};
  643.     delete $seen{ $_ } for @list;
  644.     
  645.     $self->_data( [values %seen] );
  646.     
  647.     return values %seen;   
  648. }
  649.  
  650. =head2 $tar->clear
  651.  
  652. C<clear> clears the current in-memory archive. This effectively gives
  653. you a 'blank' object, ready to be filled again. Note that C<clear> 
  654. only has effect on the object, not the underlying tarfile.
  655.  
  656. =cut
  657.  
  658. sub clear {
  659.     my $self = shift or return;
  660.     
  661.     $self->_data( [] );
  662.     $self->_file( '' );
  663.     
  664.     return 1;
  665. }    
  666.  
  667.  
  668. =head2 $tar->write ( [$file, $compressed, $prefix] )
  669.  
  670. Write the in-memory archive to disk.  The first argument can either 
  671. be the name of a file or a reference to an already open filehandle (a
  672. GLOB reference). If the second argument is true, the module will use
  673. IO::Zlib to write the file in a compressed format.  If IO::Zlib is 
  674. not available, the C<write> method will fail and return.
  675.  
  676. Specific levels of compression can be chosen by passing the values 2
  677. through 9 as the second parameter.
  678.  
  679. The third argument is an optional prefix. All files will be tucked
  680. away in the directory you specify as prefix. So if you have files
  681. 'a' and 'b' in your archive, and you specify 'foo' as prefix, they
  682. will be written to the archive as 'foo/a' and 'foo/b'.
  683.  
  684. If no arguments are given, C<write> returns the entire formatted
  685. archive as a string, which could be useful if you'd like to stuff the
  686. archive into a socket or a pipe to gzip or something.
  687.  
  688. =cut
  689.  
  690. sub write {
  691.     my $self    = shift;
  692.     my $file    = shift; $file   = '' unless defined $file;
  693.     my $gzip    = shift || 0;
  694.     my $prefix  = shift; $prefix = '' unless defined $prefix;
  695.  
  696.     ### only need a handle if we have a file to print to ###
  697.     my $handle = length($file)
  698.                     ? ( $self->_get_handle($file, $gzip, WRITE_ONLY->($gzip) ) 
  699.                         or return )
  700.                     : '';       
  701.  
  702.     my @rv;
  703.     for my $entry ( @{$self->_data} ) {
  704.     
  705.         ### names are too long, and will get truncated if we don't add a
  706.         ### '@LongLink' file...
  707.         if( length($entry->name)    > NAME_LENGTH or 
  708.             length($entry->prefix)  > PREFIX_LENGTH 
  709.         ) {
  710.             
  711.             my $longlink = Archive::Tar::File->new( 
  712.                             data => LONGLINK_NAME, 
  713.                             File::Spec::Unix->catfile( grep { length } $entry->prefix, $entry->name ),
  714.                             { type => LONGLINK }
  715.                         );
  716.             unless( $longlink ) {
  717.                 $self->_error( qq[Could not create 'LongLink' entry for oversize file '] . $entry->name ."'" );
  718.                 return;
  719.             };                      
  720.     
  721.     
  722.             if( length($file) ) {
  723.                 unless( $self->_write_to_handle( $handle, $longlink, $prefix ) ) {
  724.                     $self->_error( qq[Could not write 'LongLink' entry for oversize file '] .  $entry->name ."'" );
  725.                     return; 
  726.                 }
  727.             } else {
  728.                 push @rv, $self->_format_tar_entry( $longlink, $prefix );
  729.                 push @rv, $entry->data              if  $entry->has_content;
  730.                 push @rv, TAR_PAD->( $entry->size ) if  $entry->has_content &&
  731.                                                         $entry->size % BLOCK;
  732.             }     
  733.         }        
  734.  
  735.         if( length($file) ) {
  736.             unless( $self->_write_to_handle( $handle, $entry, $prefix ) ) {
  737.                 $self->_error( qq[Could not write entry '] . $entry->name . qq[' to archive] );
  738.                 return;          
  739.             }
  740.         } else {
  741.             push @rv, $self->_format_tar_entry( $entry, $prefix );
  742.             push @rv, $entry->data              if  $entry->has_content;
  743.             push @rv, TAR_PAD->( $entry->size ) if  $entry->has_content &&
  744.                                                         $entry->size % BLOCK;
  745.         }
  746.     }
  747.     
  748.     if( length($file) ) {    
  749.         print $handle TAR_END x 2 or (
  750.             $self->_error( qq[Could not write tar end markers] ),
  751.             return
  752.         );
  753.     } else {
  754.         push @rv, TAR_END x 2;
  755.     }
  756.     
  757.     return length($file) ? 1 : join '', @rv;
  758. }
  759.  
  760. sub _write_to_handle {
  761.     my $self    = shift;
  762.     my $handle  = shift or return;
  763.     my $entry   = shift or return;
  764.     my $prefix  = shift; $prefix = '' unless defined $prefix;
  765.     
  766.     ### if the file is a symlink, there are 2 options:
  767.     ### either we leave the symlink intact, but then we don't write any data
  768.     ### OR we follow the symlink, which means we actually make a copy.
  769.     ### if we do the latter, we have to change the TYPE of the entry to 'FILE'
  770.     my $symlink_ok =  $entry->is_symlink && $Archive::Tar::FOLLOW_SYMLINK;
  771.     my $content_ok = !$entry->is_symlink && $entry->has_content ;
  772.     
  773.     ### downgrade to a 'normal' file if it's a symlink we're going to treat
  774.     ### as a regular file
  775.     $entry->_downgrade_to_plainfile if $symlink_ok;
  776.     
  777.     my $header = $self->_format_tar_entry( $entry, $prefix );
  778.         
  779.     unless( $header ) {
  780.         $self->_error( qq[Could not format header for entry: ] . $entry->name );
  781.         return;
  782.     }      
  783.  
  784.     print $handle $header or (
  785.         $self->_error( qq[Could not write header for: ] . $entry->name ),
  786.         return
  787.     );
  788.     
  789.     if( $symlink_ok or $content_ok ) {
  790.         print $handle $entry->data or (
  791.             $self->_error( qq[Could not write data for: ] . $entry->name ),
  792.             return
  793.         );
  794.         ### pad the end of the entry if required ###
  795.         print $handle TAR_PAD->( $entry->size ) if $entry->size % BLOCK;
  796.     }         
  797.     
  798.     return 1;
  799. }
  800.  
  801.  
  802. sub _format_tar_entry {
  803.     my $self        = shift;
  804.     my $entry       = shift or return;
  805.     my $ext_prefix  = shift; $ext_prefix = '' unless defined $ext_prefix;
  806.  
  807.     my $file    = $entry->name;
  808.     my $prefix  = $entry->prefix; $prefix = '' unless defined $prefix;
  809.     my $match   = quotemeta $prefix;
  810.     
  811.     ### remove the prefix from the file name 
  812.     ### not sure if this is still neeeded --kane
  813.     ### no it's not -- Archive::Tar::File->_new_from_file will take care of
  814.     ### this for us. Even worse, this would break if we tried to add a file
  815.     ### like x/x. 
  816.     #if( length $prefix ) {
  817.     #    $file =~ s/^$match//;
  818.     #} 
  819.     
  820.     $prefix = File::Spec::Unix->catdir($ext_prefix, $prefix) if length $ext_prefix;
  821.     
  822.     ### not sure why this is... ###
  823.     my $l = PREFIX_LENGTH; # is ambiguous otherwise...
  824.     substr ($prefix, 0, -$l) = "" if length $prefix >= PREFIX_LENGTH;
  825.     
  826.     my $f1 = "%06o"; my $f2  = "%11o";
  827.     
  828.     ### this might be optimizable with a 'changed' flag in the file objects ###
  829.     my $tar = pack (
  830.                 PACK,
  831.                 $file,
  832.                 
  833.                 (map { sprintf( $f1, $entry->$_() ) } qw[mode uid gid]),
  834.                 (map { sprintf( $f2, $entry->$_() ) } qw[size mtime]),
  835.                 
  836.                 "",  # checksum filed - space padded a bit down 
  837.                 
  838.                 (map { $entry->$_() }                 qw[type linkname magic]),
  839.                 
  840.                 $entry->version || TAR_VERSION,
  841.                 
  842.                 (map { $entry->$_() }                 qw[uname gname]),
  843.                 (map { sprintf( $f1, $entry->$_() ) } qw[devmajor devminor]),
  844.                 
  845.                 $prefix
  846.     );
  847.     
  848.     ### add the checksum ###
  849.     substr($tar,148,7) = sprintf("%6o\0", unpack("%16C*",$tar));
  850.  
  851.     return $tar;
  852. }           
  853.  
  854. =head2 $tar->add_files( @filenamelist )
  855.  
  856. Takes a list of filenames and adds them to the in-memory archive.  
  857.  
  858. The path to the file is automatically converted to a Unix like
  859. equivalent for use in the archive, and, if on MacOS, the file's 
  860. modification time is converted from the MacOS epoch to the Unix epoch.
  861. So tar archives created on MacOS with B<Archive::Tar> can be read 
  862. both with I<tar> on Unix and applications like I<suntar> or 
  863. I<Stuffit Expander> on MacOS.
  864.  
  865. Be aware that the file's type/creator and resource fork will be lost,
  866. which is usually what you want in cross-platform archives.
  867.  
  868. Returns a list of C<Archive::Tar::File> objects that were just added.
  869.  
  870. =cut
  871.  
  872. sub add_files {
  873.     my $self    = shift;
  874.     my @files   = @_ or return ();
  875.     
  876.     my @rv;
  877.     for my $file ( @files ) {
  878.         unless( -e $file ) {
  879.             $self->_error( qq[No such file: '$file'] );
  880.             next;
  881.         }
  882.     
  883.         my $obj = Archive::Tar::File->new( file => $file );
  884.         unless( $obj ) {
  885.             $self->_error( qq[Unable to add file: '$file'] );
  886.             next;
  887.         }      
  888.  
  889.         push @rv, $obj;
  890.     }
  891.     
  892.     push @{$self->{_data}}, @rv;
  893.     
  894.     return @rv;
  895. }
  896.  
  897. =head2 $tar->add_data ( $filename, $data, [$opthashref] )
  898.  
  899. Takes a filename, a scalar full of data and optionally a reference to
  900. a hash with specific options. 
  901.  
  902. Will add a file to the in-memory archive, with name C<$filename> and 
  903. content C<$data>. Specific properties can be set using C<$opthashref>.
  904. The following list of properties is supported: name, size, mtime 
  905. (last modified date), mode, uid, gid, linkname, uname, gname, 
  906. devmajor, devminor, prefix.  (On MacOS, the file's path and 
  907. modification times are converted to Unix equivalents.)
  908.  
  909. Returns the C<Archive::Tar::File> object that was just added, or
  910. C<undef> on failure.
  911.  
  912. =cut
  913.  
  914. sub add_data {
  915.     my $self    = shift;
  916.     my ($file, $data, $opt) = @_; 
  917.  
  918.     my $obj = Archive::Tar::File->new( data => $file, $data, $opt );
  919.     unless( $obj ) {
  920.         $self->_error( qq[Unable to add file: '$file'] );
  921.         return;
  922.     }      
  923.  
  924.     push @{$self->{_data}}, $obj;
  925.  
  926.     return $obj;
  927. }
  928.  
  929. =head2 $tar->error( [$BOOL] )
  930.  
  931. Returns the current errorstring (usually, the last error reported).
  932. If a true value was specified, it will give the C<Carp::longmess> 
  933. equivalent of the error, in effect giving you a stacktrace.
  934.  
  935. For backwards compatibility, this error is also available as 
  936. C<$Archive::Tar::error> allthough it is much recommended you use the
  937. method call instead.
  938.  
  939. =cut
  940.  
  941. {
  942.     $error = '';
  943.     my $longmess;
  944.     
  945.     sub _error {
  946.         my $self    = shift;
  947.         my $msg     = $error = shift;
  948.         $longmess   = Carp::longmess($error);
  949.         
  950.         ### set Archive::Tar::WARN to 0 to disable printing
  951.         ### of errors
  952.         if( $WARN ) {
  953.             carp $DEBUG ? $longmess : $msg;
  954.         }
  955.         
  956.         return;
  957.     }
  958.     
  959.     sub error {
  960.         my $self = shift;
  961.         return shift() ? $longmess : $error;          
  962.     }
  963. }         
  964.  
  965.  
  966. =head1 Class Methods 
  967.  
  968. =head2 Archive::Tar->create_archive($file, $compression, @filelist)
  969.  
  970. Creates a tar file from the list of files provided.  The first
  971. argument can either be the name of the tar file to create or a
  972. reference to an open file handle (e.g. a GLOB reference).
  973.  
  974. The second argument specifies the level of compression to be used, if
  975. any.  Compression of tar files requires the installation of the
  976. IO::Zlib module.  Specific levels of compression may be
  977. requested by passing a value between 2 and 9 as the second argument.
  978. Any other value evaluating as true will result in the default
  979. compression level being used.
  980.  
  981. The remaining arguments list the files to be included in the tar file.
  982. These files must all exist.  Any files which don\'t exist or can\'t be
  983. read are silently ignored.
  984.  
  985. If the archive creation fails for any reason, C<create_archive> will
  986. return.  Please use the C<error> method to find the cause of the
  987. failure.
  988.  
  989. =cut
  990.  
  991. sub create_archive {
  992.     my $class = shift;
  993.     
  994.     my $file    = shift; return unless defined $file;
  995.     my $gzip    = shift || 0;
  996.     my @files   = @_;
  997.     
  998.     unless( @files ) {
  999.         return $class->_error( qq[Cowardly refusing to create empty archive!] );
  1000.     }        
  1001.     
  1002.     my $tar = $class->new;
  1003.     $tar->add_files( @files );
  1004.     return $tar->write( $file, $gzip );    
  1005. }
  1006.  
  1007. =head2 Archive::Tar->list_archive ($file, $compressed, [\@properties])
  1008.  
  1009. Returns a list of the names of all the files in the archive.  The
  1010. first argument can either be the name of the tar file to list or a
  1011. reference to an open file handle (e.g. a GLOB reference).
  1012.  
  1013. If C<list_archive()> is passed an array reference as its third
  1014. argument it returns a list of hash references containing the requested
  1015. properties of each file.  The following list of properties is
  1016. supported: name, size, mtime (last modified date), mode, uid, gid,
  1017. linkname, uname, gname, devmajor, devminor, prefix.
  1018.  
  1019. Passing an array reference containing only one element, 'name', is
  1020. special cased to return a list of names rather than a list of hash
  1021. references.
  1022.  
  1023. =cut
  1024.  
  1025. sub list_archive {
  1026.     my $class   = shift;
  1027.     my $file    = shift; return unless defined $file;
  1028.     my $gzip    = shift || 0;
  1029.  
  1030.     my $tar = $class->new($file, $gzip);
  1031.     return unless $tar;
  1032.     
  1033.     return $tar->list_files( @_ ); 
  1034. }
  1035.  
  1036. =head2 Archive::Tar->extract_archive ($file, $gzip)
  1037.  
  1038. Extracts the contents of the tar file.  The first argument can either
  1039. be the name of the tar file to create or a reference to an open file
  1040. handle (e.g. a GLOB reference).  All relative paths in the tar file will
  1041. be created underneath the current working directory.
  1042.  
  1043. C<extract_archive> will return a list of files it extract.
  1044. If the archive extraction fails for any reason, C<extract_archive>
  1045. will return.  Please use the C<error> method to find the cause
  1046. of the failure.
  1047.  
  1048. =cut
  1049.  
  1050. sub extract_archive {
  1051.     my $class   = shift;
  1052.     my $file    = shift; return unless defined $file;
  1053.     my $gzip    = shift || 0;
  1054.     
  1055.     my $tar = $class->new( ) or return;
  1056.     
  1057.     return $tar->read( $file, $gzip, { extract => 1 } );
  1058. }
  1059.  
  1060. 1;
  1061.  
  1062. __END__
  1063.  
  1064. =head1 GLOBAL VARIABLES
  1065.  
  1066. =head2 $Archive::Tar::FOLLOW_SYMLINK
  1067.  
  1068. Set this variable to C<1> to make C<Archive::Tar> effectively make a
  1069. copy of the file when extracting. Default is C<0>, which
  1070. means the symlink stays intact. Of course, you will have to pack the
  1071. file linked to as well.
  1072.  
  1073. This option is checked when you write out the tarfile using C<write> 
  1074. or C<create_archive>.
  1075.  
  1076. This works just like C</bin/tar>'s C<-h> option.
  1077.  
  1078. =head2 $Archive::Tar::CHOWN
  1079.  
  1080. By default, C<Archive::Tar> will try to C<chown> your files if it is
  1081. able to. In some cases, this may not be desired. In that case, set 
  1082. this variable to C<0> to disable C<chown>-ing, even if it were
  1083. possible.
  1084.  
  1085. The default is C<1>.
  1086.  
  1087. =head2 $Archive::Tar::CHMOD
  1088.  
  1089. By default, C<Archive::Tar> will try to C<chmod> your files to 
  1090. whatever mode was specified for the particular file in the archive. 
  1091. In some cases, this may not be desired. In that case, set this 
  1092. variable to C<0> to disable C<chmod>-ing.
  1093.  
  1094. The default is C<1>.
  1095.  
  1096. =head2 $Archive::Tar::DEBUG
  1097.  
  1098. Set this variable to C<1> to always get the C<Carp::longmess> output
  1099. of the warnings, instead of the regular C<carp>. This is the same 
  1100. message you would get by doing: 
  1101.     
  1102.     $tar->error(1);
  1103.  
  1104. Defaults to C<0>.
  1105.  
  1106. =head2 $Archive::Tar::WARN
  1107.  
  1108. Set this variable to C<0> if you do not want any warnings printed.
  1109. Personally I recommend against doing this, but people asked for the
  1110. option. Also, be advised that this is of course not threadsafe.
  1111.  
  1112. Defaults to C<1>.
  1113.  
  1114. =head2 $Archive::Tar::error
  1115.  
  1116. Holds the last reported error. Kept for historical reasons, but its
  1117. use is very much discouraged. Use the C<error()> method instead:
  1118.  
  1119.     warn $tar->error unless $tar->extract;
  1120.  
  1121. =head1 FAQ
  1122.  
  1123. =over 4
  1124.  
  1125. =item What's the minimum perl version required to run Archive::Tar?
  1126.  
  1127. You will need perl version 5.005_03 or newer. 
  1128.  
  1129. =item Isn't Archive::Tar slow?
  1130.  
  1131. Yes it is. It's pure perl, so it's a lot slower then your C</bin/tar>
  1132. However, it's very portable. If speed is an issue, consider using
  1133. C</bin/tar> instead.
  1134.  
  1135. =item Isn't Archive::Tar heavier on memory than /bin/tar?
  1136.  
  1137. Yes it is, see previous answer. Since C<Compress::Zlib> and therefore
  1138. C<IO::Zlib> doesn't support C<seek> on their filehandles, there is little
  1139. choice but to read the archive into memory. 
  1140. This is ok if you want to do in-memory manipulation of the archive.
  1141. If you just want to extract, use the C<extract_archive> class method
  1142. instead. It will optimize and write to disk immediately.
  1143.  
  1144. =item Can't you lazy-load data instead?
  1145.  
  1146. No, not easily. See previous question.
  1147.  
  1148. =item How much memory will an X kb tar file need?
  1149.  
  1150. Probably more than X kb, since it will all be read into memory. If 
  1151. this is a problem, and you don't need to do in memory manipulation 
  1152. of the archive, consider using C</bin/tar> instead.
  1153.  
  1154. =back
  1155.  
  1156. =head1 TODO
  1157.  
  1158. =over 4
  1159.  
  1160. =item Check if passed in handles are open for read/write
  1161.     
  1162. Currently I don't know of any portable pure perl way to do this.
  1163. Suggestions welcome.
  1164.  
  1165. =back
  1166.  
  1167. =head1 AUTHOR
  1168.  
  1169. This module by
  1170. Jos Boumans E<lt>kane@cpan.orgE<gt>.
  1171.  
  1172. =head1 ACKNOWLEDGEMENTS
  1173.  
  1174. Thanks to Sean Burke, Chris Nandor, Chip Salzenberg, Tim Heaney and
  1175. Andrew Savige for their help and suggestions.
  1176.  
  1177. =head1 COPYRIGHT
  1178.  
  1179. This module is
  1180. copyright (c) 2002 Jos Boumans E<lt>kane@cpan.orgE<gt>.
  1181. All rights reserved.
  1182.  
  1183. This library is free software;
  1184. you may redistribute and/or modify it under the same
  1185. terms as Perl itself.
  1186.  
  1187. =cut
  1188.