1 ### the gnu tar specification:
2 ### http://www.gnu.org/software/tar/manual/html_mono/tar.html
4 ### and the pax format spec, which tar derives from:
5 ### http://www.opengroup.org/onlinepubs/007904975/utilities/pax.html
11 use vars qw[$DEBUG $error $VERSION $WARN $FOLLOW_SYMLINK $CHOWN $CHMOD
12 $DO_NOT_USE_PREFIX $HAS_PERLIO $HAS_IO_STRING];
20 $DO_NOT_USE_PREFIX = 0;
24 $HAS_PERLIO = $Config::Config{useperlio};
26 ### try and load IO::String anyway, so you can dynamically
27 ### switch between perlio and IO::String
32 $HAS_IO_STRING = $@ ? 0 : 1;
38 use Carp qw(carp croak);
40 use File::Spec::Unix ();
43 use Archive::Tar::File;
44 use Archive::Tar::Constant;
48 Archive::Tar - module for manipulations of tar archives
53 my $tar = Archive::Tar->new;
55 $tar->read('origin.tgz',1);
58 $tar->add_files('file/foo.pl', 'docs/README');
59 $tar->add_data('file/baz.txt', 'This is the contents now');
61 $tar->rename('oldname', 'new/file/name');
63 $tar->write('files.tar');
67 Archive::Tar provides an object oriented mechanism for handling tar
68 files. It provides class methods for quick and easy files handling
69 while also allowing for the creation of tar file objects for custom
70 manipulation. If you have the IO::Zlib module installed,
71 Archive::Tar will also support compressed or gzipped tar files.
73 An object of class Archive::Tar represents a .tar(.gz) archive full
78 =head2 Archive::Tar->new( [$file, $compressed] )
80 Returns a new Tar object. If given any arguments, C<new()> calls the
81 C<read()> method automatically, passing on the arguments provided to
84 If C<new()> is invoked with arguments and the C<read()> method fails
85 for any reason, C<new()> returns undef.
94 ### install get/set accessors for this object.
95 for my $key ( keys %$tmpl ) {
97 *{__PACKAGE__."::$key"} = sub {
99 $self->{$key} = $_[0] if @_;
100 return $self->{$key};
106 $class = ref $class if ref $class;
108 ### copying $tmpl here since a shallow copy makes it use the
109 ### same aref, causing for files to remain in memory always.
110 my $obj = bless { _data => [ ], _file => 'Unknown' }, $class;
113 return unless $obj->read( @_ );
119 =head2 $tar->read ( $filename|$handle, $compressed, {opt => 'val'} )
121 Read the given tar file into memory.
122 The first argument can either be the name of a file or a reference to
123 an already open filehandle (or an IO::Zlib object if it's compressed)
124 The second argument indicates whether the file referenced by the first
125 argument is compressed.
127 The C<read> will I<replace> any previous content in C<$tar>!
129 The second argument may be considered optional if IO::Zlib is
130 installed, since it will transparently Do The Right Thing.
131 Archive::Tar will warn if you try to pass a compressed file if
132 IO::Zlib is not available and simply return.
134 The third argument can be a hash reference with options. Note that
135 all options are case-sensitive.
141 Do not read more than C<limit> files. This is useful if you have
142 very big archives, and are only interested in the first few files.
146 If set to true, immediately extract entries when reading them. This
147 gives you the same memory break as the C<extract_archive> function.
148 Note however that entries will not be read into memory, but written
153 All files are stored internally as C<Archive::Tar::File> objects.
154 Please consult the L<Archive::Tar::File> documentation for details.
156 Returns the number of files read in scalar context, and a list of
157 C<Archive::Tar::File> objects in list context.
164 my $gzip = shift || 0;
165 my $opts = shift || {};
167 unless( defined $file ) {
168 $self->_error( qq[No file to read from!] );
171 $self->_file( $file );
174 my $handle = $self->_get_handle($file, $gzip, READ_ONLY->( ZLIB ) )
177 my $data = $self->_read_tar( $handle, $opts ) or return;
179 $self->_data( $data );
181 return wantarray ? @$data : scalar @$data;
186 my $file = shift; return unless defined $file;
187 return $file if ref $file;
189 my $gzip = shift || 0;
190 my $mode = shift || READ_ONLY->( ZLIB ); # default to read only
194 ### only default to ZLIB if we're not trying to /write/ to a handle ###
195 if( ZLIB and $gzip || MODE_READ->( $mode ) ) {
197 ### IO::Zlib will Do The Right Thing, even when passed
203 $self->_error(qq[Compression not available - Install IO::Zlib!]);
212 unless( $fh->open( $file, $mode ) ) {
213 $self->_error( qq[Could not create filehandle for '$file': $!!] );
224 my $handle = shift or return;
225 my $opts = shift || {};
227 my $count = $opts->{limit} || 0;
228 my $extract = $opts->{extract} || 0;
230 ### set a cap on the amount of files to extract ###
232 $limit = 1 if $count > 0;
237 my $real_name; # to set the name of a file when
238 # we're encountering @longlink
242 while( $handle->read( $chunk, HEAD ) ) {
243 ### IO::Zlib doesn't support this yet
244 my $offset = eval { tell $handle } || 'unknown';
247 my $gzip = GZIP_MAGIC_NUM;
248 if( $chunk =~ /$gzip/ ) {
249 $self->_error( qq[Cannot read compressed format in tar-mode] );
254 ### if we can't read in all bytes... ###
255 last if length $chunk != HEAD;
257 ### Apparently this should really be two blocks of 512 zeroes,
258 ### but GNU tar sometimes gets it wrong. See comment in the
259 ### source code (tar.c) to GNU cpio.
260 next if $chunk eq TAR_END;
263 unless( $entry = Archive::Tar::File->new( chunk => $chunk ) ) {
264 $self->_error( qq[Couldn't read chunk at offset $offset] );
269 ### http://www.gnu.org/manual/tar/html_node/tar_139.html
270 next if $entry->is_label;
272 if( length $entry->type and ($entry->is_file || $entry->is_longlink) ) {
274 if ( $entry->is_file && !$entry->validate ) {
275 ### sometimes the chunk is rather fux0r3d and a whole 512
276 ### bytes ends p in the ->name area.
277 ### clean it up, if need be
278 my $name = $entry->name;
279 $name = substr($name, 0, 100) if length $name > 100;
282 $self->_error( $name . qq[: checksum error] );
286 my $block = BLOCK_SIZE->( $entry->size );
288 $data = $entry->get_content_by_ref;
290 ### just read everything into memory
291 ### can't do lazy loading since IO::Zlib doesn't support 'seek'
292 ### this is because Compress::Zlib doesn't support it =/
293 ### this reads in the whole data in one read() call.
294 if( $handle->read( $$data, $block ) < $block ) {
295 $self->_error( qq[Read error on tarfile (missing data) '].
296 $entry->full_path ."' at offset $offset" );
300 ### throw away trailing garbage ###
301 substr ($$data, $entry->size) = "";
303 ### part II of the @LongLink munging -- need to do /after/
304 ### the checksum check.
305 if( $entry->is_longlink ) {
306 ### weird thing in tarfiles -- if the file is actually a
307 ### @LongLink, the data part seems to have a trailing ^@
308 ### (unprintable) char. to display, pipe output through less.
309 ### but that doesn't *always* happen.. so check if the last
310 ### character is a control character, and if so remove it
311 ### at any rate, we better remove that character here, or tests
312 ### like 'eq' and hashlook ups based on names will SO not work
313 ### remove it by calculating the proper size, and then
314 ### tossing out everything that's longer than that size.
316 ### count number of nulls
317 my $nulls = $$data =~ tr/\0/\0/;
319 ### cut data + size by that many bytes
320 $entry->size( $entry->size - $nulls );
321 substr ($$data, $entry->size) = "";
325 ### clean up of the entries.. posix tar /apparently/ has some
326 ### weird 'feature' that allows for filenames > 255 characters
327 ### they'll put a header in with as name '././@LongLink' and the
328 ### contents will be the name of the /next/ file in the archive
329 ### pretty crappy and kludgy if you ask me
331 ### set the name for the next entry if this is a @LongLink;
332 ### this is one ugly hack =/ but needed for direct extraction
333 if( $entry->is_longlink ) {
336 } elsif ( defined $real_name ) {
337 $entry->name( $$real_name );
342 $self->_extract_file( $entry ) if $extract
343 && !$entry->is_longlink
344 && !$entry->is_unknown
345 && !$entry->is_label;
347 ### Guard against tarfiles with garbage at the end
348 last LOOP if $entry->name eq '';
350 ### push only the name on the rv if we're extracting
351 ### -- for extract_archive
352 push @$tarfile, ($extract ? $entry->name : $entry);
355 $count-- unless $entry->is_longlink || $entry->is_dir;
356 last LOOP unless $count;
365 =head2 $tar->contains_file( $filename )
367 Check if the archive contains a certain file.
368 It will return true if the file is in the archive, false otherwise.
370 Note however, that this function does an exact match using C<eq>
371 on the full path. So it cannot compensate for case-insensitive file-
372 systems or compare 2 paths to see if they would point to the same
379 my $full = shift or return;
381 return 1 if $self->_find_entry($full);
385 =head2 $tar->extract( [@filenames] )
387 Write files whose names are equivalent to any of the names in
388 C<@filenames> to disk, creating subdirectories as necessary. This
389 might not work too well under VMS.
390 Under MacPerl, the file's modification time will be converted to the
391 MacOS zero of time, and appropriate conversions will be done to the
392 path. However, the length of each element of the path is not
393 inspected to see whether it's longer than MacOS currently allows (32
396 If C<extract> is called without a list of file names, the entire
397 contents of the archive are extracted.
399 Returns a list of filenames extracted.
407 ### you requested the extraction of only certian files
411 for my $entry ( @{$self->_data} ) {
412 next unless $file eq $entry->full_path;
414 ### we found the file you're looking for
420 return $self->_error( qq[Could not find '$file' in archive] );
424 ### just grab all the file items
426 @files = $self->get_files;
429 ### nothing found? that's an error
430 unless( scalar @files ) {
431 $self->_error( qq[No files found for ] . $self->_file );
436 for my $entry ( @files ) {
437 unless( $self->_extract_file( $entry ) ) {
438 $self->_error(q[Could not extract ']. $entry->full_path .q['] );
446 =head2 $tar->extract_file( $file, [$extract_path] )
448 Write an entry, whose name is equivalent to the file name provided to
449 disk. Optionally takes a second parameter, which is the full (unix)
450 path (including filename) the entry will be written to.
454 $tar->extract_file( 'name/in/archive', 'name/i/want/to/give/it' );
456 Returns true on success, false on failure.
462 my $file = shift or return;
465 my $entry = $self->_find_entry( $file )
466 or $self->_error( qq[Could not find an entry for '$file'] ), return;
468 return $self->_extract_file( $entry, $alt );
473 my $entry = shift or return;
477 ### you wanted an alternate extraction location ###
478 my $name = defined $alt ? $alt : $entry->full_path;
480 ### splitpath takes a bool at the end to indicate
481 ### that it's splitting a dir
482 my ($vol,$dirs,$file) = File::Spec::Unix->splitpath( $name,
485 ### is $name an absolute path? ###
486 if( File::Spec->file_name_is_absolute( $dirs ) ) {
489 ### it's a relative path ###
491 my @dirs = File::Spec::Unix->splitdir( $dirs );
492 my @cwd = File::Spec->splitdir( $cwd );
493 $dir = File::Spec->catdir(@cwd, @dirs);
496 if( -e $dir && !-d _ ) {
497 $^W && $self->_error( qq['$dir' exists, but it's not a directory!\n] );
502 eval { File::Path::mkpath( $dir, 0, 0777 ) };
504 $self->_error( qq[Could not create directory '$dir': $@] );
509 ### we're done if we just needed to create a dir ###
510 return 1 if $entry->is_dir;
512 my $full = File::Spec->catfile( $dir, $file );
514 if( $entry->is_unknown ) {
515 $self->_error( qq[Unknown file type for file '$full'] );
519 if( length $entry->type && $entry->is_file ) {
520 my $fh = IO::File->new;
521 $fh->open( '>' . $full ) or (
522 $self->_error( qq[Could not open file '$full': $!] ),
528 syswrite $fh, $entry->data or (
529 $self->_error( qq[Could not write data to '$full'] ),
535 $self->_error( qq[Could not close file '$full'] ),
540 $self->_make_special_file( $entry, $full ) or return;
543 utime time, $entry->mtime - TIME_OFFSET, $full or
544 $self->_error( qq[Could not update timestamp] );
546 if( $CHOWN && CAN_CHOWN ) {
547 chown $entry->uid, $entry->gid, $full or
548 $self->_error( qq[Could not set uid/gid on '$full'] );
551 ### only chmod if we're allowed to, but never chmod symlinks, since they'll
552 ### change the perms on the file they're linking too...
553 if( $CHMOD and not -l $full ) {
554 chmod $entry->mode, $full or
555 $self->_error( qq[Could not chown '$full' to ] . $entry->mode );
561 sub _make_special_file {
563 my $entry = shift or return;
564 my $file = shift; return unless defined $file;
568 if( $entry->is_symlink ) {
571 symlink( $entry->linkname, $file ) or $fail++;
574 $self->_extract_special_file_as_plain_file( $entry, $file )
578 $err = qq[Making symbolink link from '] . $entry->linkname .
579 qq[' to '$file' failed] if $fail;
581 } elsif ( $entry->is_hardlink ) {
584 link( $entry->linkname, $file ) or $fail++;
587 $self->_extract_special_file_as_plain_file( $entry, $file )
591 $err = qq[Making hard link from '] . $entry->linkname .
592 qq[' to '$file' failed] if $fail;
594 } elsif ( $entry->is_fifo ) {
595 ON_UNIX && !system('mknod', $file, 'p') or
596 $err = qq[Making fifo ']. $entry->name .qq[' failed];
598 } elsif ( $entry->is_blockdev or $entry->is_chardev ) {
599 my $mode = $entry->is_blockdev ? 'b' : 'c';
601 ON_UNIX && !system('mknod', $file, $mode,
602 $entry->devmajor, $entry->devminor) or
603 $err = qq[Making block device ']. $entry->name .qq[' (maj=] .
604 $entry->devmajor . qq[ min=] . $entry->devminor .
607 } elsif ( $entry->is_socket ) {
608 ### the original doesn't do anything special for sockets.... ###
612 return $err ? $self->_error( $err ) : 1;
615 ### don't know how to make symlinks, let's just extract the file as
617 sub _extract_special_file_as_plain_file {
619 my $entry = shift or return;
620 my $file = shift; return unless defined $file;
624 my $orig = $self->_find_entry( $entry->linkname );
627 $err = qq[Could not find file '] . $entry->linkname .
632 ### clone the entry, make it appear as a normal file ###
633 my $clone = $entry->clone;
634 $clone->_downgrade_to_plainfile;
635 $self->_extract_file( $clone, $file ) or last TRY;
640 return $self->_error($err);
643 =head2 $tar->list_files( [\@properties] )
645 Returns a list of the names of all the files in the archive.
647 If C<list_files()> is passed an array reference as its first argument
648 it returns a list of hash references containing the requested
649 properties of each file. The following list of properties is
650 supported: name, size, mtime (last modified date), mode, uid, gid,
651 linkname, uname, gname, devmajor, devminor, prefix.
653 Passing an array reference containing only one element, 'name', is
654 special cased to return a list of names rather than a list of hash
655 references, making it equivalent to calling C<list_files> without
662 my $aref = shift || [ ];
664 unless( $self->_data ) {
665 $self->read() or return;
668 if( @$aref == 0 or ( @$aref == 1 and $aref->[0] eq 'name' ) ) {
669 return map { $_->full_path } @{$self->_data};
673 #for my $obj ( @{$self->_data} ) {
674 # push @rv, { map { $_ => $obj->$_() } @$aref };
678 ### this does the same as the above.. just needs a +{ }
679 ### to make sure perl doesn't confuse it for a block
680 return map { my $o=$_;
681 +{ map { $_ => $o->$_() } @$aref }
690 unless( defined $file ) {
691 $self->_error( qq[No file specified] );
695 for my $entry ( @{$self->_data} ) {
696 my $path = $entry->full_path;
697 return $entry if $path eq $file;
700 $self->_error( qq[No such file in archive: '$file'] );
704 =head2 $tar->get_files( [@filenames] )
706 Returns the C<Archive::Tar::File> objects matching the filenames
707 provided. If no filename list was passed, all C<Archive::Tar::File>
708 objects in the current Tar object are returned.
710 Please refer to the C<Archive::Tar::File> documentation on how to
711 handle these objects.
718 return @{ $self->_data } unless @_;
721 for my $file ( @_ ) {
722 push @list, grep { defined } $self->_find_entry( $file );
728 =head2 $tar->get_content( $file )
730 Return the content of the named file.
736 my $entry = $self->_find_entry( shift ) or return;
741 =head2 $tar->replace_content( $file, $content )
743 Make the string $content be the content for the file named $file.
747 sub replace_content {
749 my $entry = $self->_find_entry( shift ) or return;
751 return $entry->replace_content( shift );
754 =head2 $tar->rename( $file, $new_name )
756 Rename the file of the in-memory archive to $new_name.
758 Note that you must specify a Unix path for $new_name, since per tar
759 standard, all files in the archive must be Unix paths.
761 Returns true on success and false on failure.
767 my $file = shift; return unless defined $file;
768 my $new = shift; return unless defined $new;
770 my $entry = $self->_find_entry( $file ) or return;
772 return $entry->rename( $new );
775 =head2 $tar->remove (@filenamelist)
777 Removes any entries with names matching any of the given filenames
778 from the in-memory archive. Returns a list of C<Archive::Tar::File>
787 my %seen = map { $_->full_path => $_ } @{$self->_data};
788 delete $seen{ $_ } for @list;
790 $self->_data( [values %seen] );
797 C<clear> clears the current in-memory archive. This effectively gives
798 you a 'blank' object, ready to be filled again. Note that C<clear>
799 only has effect on the object, not the underlying tarfile.
804 my $self = shift or return;
813 =head2 $tar->write ( [$file, $compressed, $prefix] )
815 Write the in-memory archive to disk. The first argument can either
816 be the name of a file or a reference to an already open filehandle (a
817 GLOB reference). If the second argument is true, the module will use
818 IO::Zlib to write the file in a compressed format. If IO::Zlib is
819 not available, the C<write> method will fail and return.
821 Note that when you pass in a filehandle, the compression argument
822 is ignored, as all files are printed verbatim to your filehandle.
823 If you wish to enable compression with filehandles, use an
824 C<IO::Zlib> filehandle instead.
826 Specific levels of compression can be chosen by passing the values 2
827 through 9 as the second parameter.
829 The third argument is an optional prefix. All files will be tucked
830 away in the directory you specify as prefix. So if you have files
831 'a' and 'b' in your archive, and you specify 'foo' as prefix, they
832 will be written to the archive as 'foo/a' and 'foo/b'.
834 If no arguments are given, C<write> returns the entire formatted
835 archive as a string, which could be useful if you'd like to stuff the
836 archive into a socket or a pipe to gzip or something.
842 my $file = shift; $file = '' unless defined $file;
843 my $gzip = shift || 0;
844 my $ext_prefix = shift; $ext_prefix = '' unless defined $ext_prefix;
847 ### only need a handle if we have a file to print to ###
848 my $handle = length($file)
849 ? ( $self->_get_handle($file, $gzip, WRITE_ONLY->($gzip) )
851 : $HAS_PERLIO ? do { open my $h, '>', \$dummy; $h }
852 : $HAS_IO_STRING ? IO::String->new
853 : __PACKAGE__->no_string_support();
857 for my $entry ( @{$self->_data} ) {
858 ### entries to be written to the tarfile ###
861 ### only now will we change the object to reflect the current state
862 ### of the name and prefix fields -- this needs to be limited to
864 my $clone = $entry->clone;
867 ### so, if you don't want use to use the prefix, we'll stuff
868 ### everything in the name field instead
869 if( $DO_NOT_USE_PREFIX ) {
871 ### you might have an extended prefix, if so, set it in the clone
872 ### XXX is ::Unix right?
873 $clone->name( length $ext_prefix
874 ? File::Spec::Unix->catdir( $ext_prefix,
876 : $clone->full_path );
877 $clone->prefix( '' );
879 ### otherwise, we'll have to set it properly -- prefix part in the
880 ### prefix and name part in the name field.
883 ### split them here, not before!
884 my ($prefix,$name) = $clone->_prefix_and_file( $clone->full_path );
886 ### you might have an extended prefix, if so, set it in the clone
887 ### XXX is ::Unix right?
888 $prefix = File::Spec::Unix->catdir( $ext_prefix, $prefix )
889 if length $ext_prefix;
891 $clone->prefix( $prefix );
892 $clone->name( $name );
895 ### names are too long, and will get truncated if we don't add a
896 ### '@LongLink' file...
897 my $make_longlink = ( length($clone->name) > NAME_LENGTH or
898 length($clone->prefix) > PREFIX_LENGTH
901 ### perhaps we need to make a longlink file?
902 if( $make_longlink ) {
903 my $longlink = Archive::Tar::File->new(
904 data => LONGLINK_NAME,
909 unless( $longlink ) {
910 $self->_error( qq[Could not create 'LongLink' entry for ] .
911 qq[oversize file '] . $clone->full_path ."'" );
915 push @write_me, $longlink;
918 push @write_me, $clone;
920 ### write the one, optionally 2 a::t::file objects to the handle
921 for my $clone (@write_me) {
923 ### if the file is a symlink, there are 2 options:
924 ### either we leave the symlink intact, but then we don't write any
925 ### data OR we follow the symlink, which means we actually make a
926 ### copy. if we do the latter, we have to change the TYPE of the
928 my $link_ok = $clone->is_symlink && $Archive::Tar::FOLLOW_SYMLINK;
929 my $data_ok = !$clone->is_symlink && $clone->has_content;
931 ### downgrade to a 'normal' file if it's a symlink we're going to
932 ### treat as a regular file
933 $clone->_downgrade_to_plainfile if $link_ok;
935 ### get the header for this block
936 my $header = $self->_format_tar_entry( $clone );
938 $self->_error(q[Could not format header for: ] .
943 unless( print $handle $header ) {
944 $self->_error(q[Could not write header for: ] .
949 if( $link_ok or $data_ok ) {
950 unless( print $handle $clone->data ) {
951 $self->_error(q[Could not write data for: ] .
956 ### pad the end of the clone if required ###
957 print $handle TAR_PAD->( $clone->size ) if $clone->size % BLOCK
960 } ### done writing these entries
963 ### write the end markers ###
964 print $handle TAR_END x 2 or
965 return $self->_error( qq[Could not write tar end markers] );
966 ### did you want it written to a file, or returned as a string? ###
967 return length($file) ? 1
968 : $HAS_PERLIO ? $dummy
969 : do { seek $handle, 0, 0; local $/; <$handle> }
972 sub _format_tar_entry {
974 my $entry = shift or return;
975 my $ext_prefix = shift; $ext_prefix = '' unless defined $ext_prefix;
976 my $no_prefix = shift || 0;
978 my $file = $entry->name;
979 my $prefix = $entry->prefix; $prefix = '' unless defined $prefix;
981 ### remove the prefix from the file name
982 ### not sure if this is still neeeded --kane
983 ### no it's not -- Archive::Tar::File->_new_from_file will take care of
984 ### this for us. Even worse, this would break if we tried to add a file
986 #if( length $prefix ) {
987 # $file =~ s/^$match//;
990 $prefix = File::Spec::Unix->catdir($ext_prefix, $prefix)
991 if length $ext_prefix;
993 ### not sure why this is... ###
994 my $l = PREFIX_LENGTH; # is ambiguous otherwise...
995 substr ($prefix, 0, -$l) = "" if length $prefix >= PREFIX_LENGTH;
997 my $f1 = "%06o"; my $f2 = "%11o";
999 ### this might be optimizable with a 'changed' flag in the file objects ###
1004 (map { sprintf( $f1, $entry->$_() ) } qw[mode uid gid]),
1005 (map { sprintf( $f2, $entry->$_() ) } qw[size mtime]),
1007 "", # checksum field - space padded a bit down
1009 (map { $entry->$_() } qw[type linkname magic]),
1011 $entry->version || TAR_VERSION,
1013 (map { $entry->$_() } qw[uname gname]),
1014 (map { sprintf( $f1, $entry->$_() ) } qw[devmajor devminor]),
1016 ($no_prefix ? '' : $prefix)
1019 ### add the checksum ###
1020 substr($tar,148,7) = sprintf("%6o\0", unpack("%16C*",$tar));
1025 =head2 $tar->add_files( @filenamelist )
1027 Takes a list of filenames and adds them to the in-memory archive.
1029 The path to the file is automatically converted to a Unix like
1030 equivalent for use in the archive, and, if on MacOS, the file's
1031 modification time is converted from the MacOS epoch to the Unix epoch.
1032 So tar archives created on MacOS with B<Archive::Tar> can be read
1033 both with I<tar> on Unix and applications like I<suntar> or
1034 I<Stuffit Expander> on MacOS.
1036 Be aware that the file's type/creator and resource fork will be lost,
1037 which is usually what you want in cross-platform archives.
1039 Returns a list of C<Archive::Tar::File> objects that were just added.
1045 my @files = @_ or return;
1048 for my $file ( @files ) {
1049 unless( -e $file ) {
1050 $self->_error( qq[No such file: '$file'] );
1054 my $obj = Archive::Tar::File->new( file => $file );
1056 $self->_error( qq[Unable to add file: '$file'] );
1063 push @{$self->{_data}}, @rv;
1068 =head2 $tar->add_data ( $filename, $data, [$opthashref] )
1070 Takes a filename, a scalar full of data and optionally a reference to
1071 a hash with specific options.
1073 Will add a file to the in-memory archive, with name C<$filename> and
1074 content C<$data>. Specific properties can be set using C<$opthashref>.
1075 The following list of properties is supported: name, size, mtime
1076 (last modified date), mode, uid, gid, linkname, uname, gname,
1077 devmajor, devminor, prefix. (On MacOS, the file's path and
1078 modification times are converted to Unix equivalents.)
1080 Returns the C<Archive::Tar::File> object that was just added, or
1081 C<undef> on failure.
1087 my ($file, $data, $opt) = @_;
1089 my $obj = Archive::Tar::File->new( data => $file, $data, $opt );
1091 $self->_error( qq[Unable to add file: '$file'] );
1095 push @{$self->{_data}}, $obj;
1100 =head2 $tar->error( [$BOOL] )
1102 Returns the current errorstring (usually, the last error reported).
1103 If a true value was specified, it will give the C<Carp::longmess>
1104 equivalent of the error, in effect giving you a stacktrace.
1106 For backwards compatibility, this error is also available as
1107 C<$Archive::Tar::error> although it is much recommended you use the
1108 method call instead.
1118 my $msg = $error = shift;
1119 $longmess = Carp::longmess($error);
1121 ### set Archive::Tar::WARN to 0 to disable printing
1124 carp $DEBUG ? $longmess : $msg;
1132 return shift() ? $longmess : $error;
1137 =head2 $bool = $tar->has_io_string
1139 Returns true if we currently have C<IO::String> support loaded.
1141 Either C<IO::String> or C<perlio> support is needed to support writing
1142 stringified archives. Currently, C<perlio> is the preffered method, if
1145 See the C<GLOBAL VARIABLES> section to see how to change this preference.
1149 sub has_io_string { return $HAS_IO_STRING; }
1151 =head2 $bool = $tar->has_perlio
1153 Returns true if we currently have C<perlio> support loaded.
1155 This requires C<perl-5.8> or higher, compiled with C<perlio>
1157 Either C<IO::String> or C<perlio> support is needed to support writing
1158 stringified archives. Currently, C<perlio> is the preffered method, if
1161 See the C<GLOBAL VARIABLES> section to see how to change this preference.
1165 sub has_perlio { return $HAS_PERLIO; }
1168 =head1 Class Methods
1170 =head2 Archive::Tar->create_archive($file, $compression, @filelist)
1172 Creates a tar file from the list of files provided. The first
1173 argument can either be the name of the tar file to create or a
1174 reference to an open file handle (e.g. a GLOB reference).
1176 The second argument specifies the level of compression to be used, if
1177 any. Compression of tar files requires the installation of the
1178 IO::Zlib module. Specific levels of compression may be
1179 requested by passing a value between 2 and 9 as the second argument.
1180 Any other value evaluating as true will result in the default
1181 compression level being used.
1183 Note that when you pass in a filehandle, the compression argument
1184 is ignored, as all files are printed verbatim to your filehandle.
1185 If you wish to enable compression with filehandles, use an
1186 C<IO::Zlib> filehandle instead.
1188 The remaining arguments list the files to be included in the tar file.
1189 These files must all exist. Any files which don't exist or can't be
1190 read are silently ignored.
1192 If the archive creation fails for any reason, C<create_archive> will
1193 return false. Please use the C<error> method to find the cause of the
1196 Note that this method does not write C<on the fly> as it were; it
1197 still reads all the files into memory before writing out the archive.
1198 Consult the FAQ below if this is a problem.
1202 sub create_archive {
1205 my $file = shift; return unless defined $file;
1206 my $gzip = shift || 0;
1210 return $class->_error( qq[Cowardly refusing to create empty archive!] );
1213 my $tar = $class->new;
1214 $tar->add_files( @files );
1215 return $tar->write( $file, $gzip );
1218 =head2 Archive::Tar->list_archive ($file, $compressed, [\@properties])
1220 Returns a list of the names of all the files in the archive. The
1221 first argument can either be the name of the tar file to list or a
1222 reference to an open file handle (e.g. a GLOB reference).
1224 If C<list_archive()> is passed an array reference as its third
1225 argument it returns a list of hash references containing the requested
1226 properties of each file. The following list of properties is
1227 supported: name, size, mtime (last modified date), mode, uid, gid,
1228 linkname, uname, gname, devmajor, devminor, prefix.
1230 Passing an array reference containing only one element, 'name', is
1231 special cased to return a list of names rather than a list of hash
1238 my $file = shift; return unless defined $file;
1239 my $gzip = shift || 0;
1241 my $tar = $class->new($file, $gzip);
1244 return $tar->list_files( @_ );
1247 =head2 Archive::Tar->extract_archive ($file, $gzip)
1249 Extracts the contents of the tar file. The first argument can either
1250 be the name of the tar file to create or a reference to an open file
1251 handle (e.g. a GLOB reference). All relative paths in the tar file will
1252 be created underneath the current working directory.
1254 C<extract_archive> will return a list of files it extracted.
1255 If the archive extraction fails for any reason, C<extract_archive>
1256 will return false. Please use the C<error> method to find the cause
1261 sub extract_archive {
1263 my $file = shift; return unless defined $file;
1264 my $gzip = shift || 0;
1266 my $tar = $class->new( ) or return;
1268 return $tar->read( $file, $gzip, { extract => 1 } );
1271 =head2 Archive::Tar->can_handle_compressed_files
1273 A simple checking routine, which will return true if C<Archive::Tar>
1274 is able to uncompress compressed archives on the fly with C<IO::Zlib>,
1275 or false if C<IO::Zlib> is not installed.
1277 You can use this as a shortcut to determine whether C<Archive::Tar>
1278 will do what you think before passing compressed archives to its
1283 sub can_handle_compressed_files { return ZLIB ? 1 : 0 }
1285 sub no_string_support {
1286 croak("You have to install IO::String to support writing archives to strings");
1293 =head1 GLOBAL VARIABLES
1295 =head2 $Archive::Tar::FOLLOW_SYMLINK
1297 Set this variable to C<1> to make C<Archive::Tar> effectively make a
1298 copy of the file when extracting. Default is C<0>, which
1299 means the symlink stays intact. Of course, you will have to pack the
1300 file linked to as well.
1302 This option is checked when you write out the tarfile using C<write>
1303 or C<create_archive>.
1305 This works just like C</bin/tar>'s C<-h> option.
1307 =head2 $Archive::Tar::CHOWN
1309 By default, C<Archive::Tar> will try to C<chown> your files if it is
1310 able to. In some cases, this may not be desired. In that case, set
1311 this variable to C<0> to disable C<chown>-ing, even if it were
1314 The default is C<1>.
1316 =head2 $Archive::Tar::CHMOD
1318 By default, C<Archive::Tar> will try to C<chmod> your files to
1319 whatever mode was specified for the particular file in the archive.
1320 In some cases, this may not be desired. In that case, set this
1321 variable to C<0> to disable C<chmod>-ing.
1323 The default is C<1>.
1325 =head2 $Archive::Tar::DO_NOT_USE_PREFIX
1327 By default, C<Archive::Tar> will try to put paths that are over
1328 100 characters in the C<prefix> field of your tar header. However,
1329 some older tar programs do not implement this spec. To retain
1330 compatibility with these older versions, you can set the
1331 C<$DO_NOT_USE_PREFIX> variable to a true value, and C<Archive::Tar>
1332 will use an alternate way of dealing with paths over 100 characters
1333 by using the C<GNU Extended Header> feature.
1335 The default is C<0>.
1337 =head2 $Archive::Tar::DEBUG
1339 Set this variable to C<1> to always get the C<Carp::longmess> output
1340 of the warnings, instead of the regular C<carp>. This is the same
1341 message you would get by doing:
1347 =head2 $Archive::Tar::WARN
1349 Set this variable to C<0> if you do not want any warnings printed.
1350 Personally I recommend against doing this, but people asked for the
1351 option. Also, be advised that this is of course not threadsafe.
1355 =head2 $Archive::Tar::error
1357 Holds the last reported error. Kept for historical reasons, but its
1358 use is very much discouraged. Use the C<error()> method instead:
1360 warn $tar->error unless $tar->extract;
1362 =head2 $Archive::Tar::HAS_PERLIO
1364 This variable holds a boolean indicating if we currently have
1365 C<perlio> support loaded. This will be enabled for any perl
1366 greater than C<5.8> compiled with C<perlio>.
1368 If you feel strongly about disabling it, set this variable to
1369 C<false>. Note that you will then need C<IO::String> installed
1370 to support writing stringified archives.
1372 Don't change this variable unless you B<really> know what you're
1375 =head2 $Archive::Tar::HAS_IO_STRING
1377 This variable holds a boolean indicating if we currently have
1378 C<IO::String> support loaded. This will be enabled for any perl
1379 that has a loadable C<IO::String> module.
1381 If you feel strongly about disabling it, set this variable to
1382 C<false>. Note that you will then need C<perlio> support from
1383 your perl to be able to write stringified archives.
1385 Don't change this variable unless you B<really> know what you're
1392 =item What's the minimum perl version required to run Archive::Tar?
1394 You will need perl version 5.005_03 or newer.
1396 =item Isn't Archive::Tar slow?
1398 Yes it is. It's pure perl, so it's a lot slower then your C</bin/tar>
1399 However, it's very portable. If speed is an issue, consider using
1400 C</bin/tar> instead.
1402 =item Isn't Archive::Tar heavier on memory than /bin/tar?
1404 Yes it is, see previous answer. Since C<Compress::Zlib> and therefore
1405 C<IO::Zlib> doesn't support C<seek> on their filehandles, there is little
1406 choice but to read the archive into memory.
1407 This is ok if you want to do in-memory manipulation of the archive.
1408 If you just want to extract, use the C<extract_archive> class method
1409 instead. It will optimize and write to disk immediately.
1411 =item Can't you lazy-load data instead?
1413 No, not easily. See previous question.
1415 =item How much memory will an X kb tar file need?
1417 Probably more than X kb, since it will all be read into memory. If
1418 this is a problem, and you don't need to do in memory manipulation
1419 of the archive, consider using C</bin/tar> instead.
1421 =item What do you do with unsupported filetypes in an archive?
1423 C<Unix> has a few filetypes that aren't supported on other platforms,
1424 like C<Win32>. If we encounter a C<hardlink> or C<symlink> we'll just
1425 try to make a copy of the original file, rather than throwing an error.
1427 This does require you to read the entire archive in to memory first,
1428 since otherwise we wouldn't know what data to fill the copy with.
1429 (This means that you cannot use the class methods on archives that
1430 have incompatible filetypes and still expect things to work).
1432 For other filetypes, like C<chardevs> and C<blockdevs> we'll warn that
1433 the extraction of this particular item didn't work.
1441 =item Check if passed in handles are open for read/write
1443 Currently I don't know of any portable pure perl way to do this.
1444 Suggestions welcome.
1451 Jos Boumans E<lt>kane@cpan.orgE<gt>.
1453 =head1 ACKNOWLEDGEMENTS
1455 Thanks to Sean Burke, Chris Nandor, Chip Salzenberg, Tim Heaney and
1456 especially Andrew Savige for their help and suggestions.
1461 copyright (c) 2002 Jos Boumans E<lt>kane@cpan.orgE<gt>.
1462 All rights reserved.
1464 This library is free software;
1465 you may redistribute and/or modify it under the same
1466 terms as Perl itself.