Document where to find maintainers of dual live modules
[p5sagit/p5-mst-13.2.git] / lib / Archive / Tar.pm
CommitLineData
39713df4 1### the gnu tar specification:
2### http://www.gnu.org/software/tar/manual/html_mono/tar.html
3###
4### and the pax format spec, which tar derives from:
5### http://www.opengroup.org/onlinepubs/007904975/utilities/pax.html
6
7package Archive::Tar;
8require 5.005_03;
9
10use strict;
11use vars qw[$DEBUG $error $VERSION $WARN $FOLLOW_SYMLINK $CHOWN $CHMOD
12 $DO_NOT_USE_PREFIX $HAS_PERLIO $HAS_IO_STRING];
13
14$DEBUG = 0;
15$WARN = 1;
16$FOLLOW_SYMLINK = 0;
d2f9954d 17$VERSION = "1.24_02";
39713df4 18$CHOWN = 1;
19$CHMOD = 1;
20$DO_NOT_USE_PREFIX = 0;
21
22BEGIN {
23 use Config;
24 $HAS_PERLIO = $Config::Config{useperlio};
25
26 ### try and load IO::String anyway, so you can dynamically
27 ### switch between perlio and IO::String
28 eval {
29 require IO::String;
30 import IO::String;
31 };
32 $HAS_IO_STRING = $@ ? 0 : 1;
33
34}
35
36use Cwd;
37use IO::File;
38use Carp qw(carp croak);
39use File::Spec ();
40use File::Spec::Unix ();
41use File::Path ();
42
43use Archive::Tar::File;
44use Archive::Tar::Constant;
45
46=head1 NAME
47
48Archive::Tar - module for manipulations of tar archives
49
50=head1 SYNOPSIS
51
52 use Archive::Tar;
53 my $tar = Archive::Tar->new;
54
55 $tar->read('origin.tgz',1);
56 $tar->extract();
57
58 $tar->add_files('file/foo.pl', 'docs/README');
59 $tar->add_data('file/baz.txt', 'This is the contents now');
60
61 $tar->rename('oldname', 'new/file/name');
62
63 $tar->write('files.tar');
64
65=head1 DESCRIPTION
66
67Archive::Tar provides an object oriented mechanism for handling tar
68files. It provides class methods for quick and easy files handling
69while also allowing for the creation of tar file objects for custom
70manipulation. If you have the IO::Zlib module installed,
71Archive::Tar will also support compressed or gzipped tar files.
72
73An object of class Archive::Tar represents a .tar(.gz) archive full
74of files and things.
75
76=head1 Object Methods
77
78=head2 Archive::Tar->new( [$file, $compressed] )
79
80Returns a new Tar object. If given any arguments, C<new()> calls the
81C<read()> method automatically, passing on the arguments provided to
82the C<read()> method.
83
84If C<new()> is invoked with arguments and the C<read()> method fails
85for any reason, C<new()> returns undef.
86
87=cut
88
89my $tmpl = {
90 _data => [ ],
91 _file => 'Unknown',
92};
93
94### install get/set accessors for this object.
95for my $key ( keys %$tmpl ) {
96 no strict 'refs';
97 *{__PACKAGE__."::$key"} = sub {
98 my $self = shift;
99 $self->{$key} = $_[0] if @_;
100 return $self->{$key};
101 }
102}
103
104sub new {
105 my $class = shift;
106 $class = ref $class if ref $class;
107
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;
111
112 if (@_) {
113 return unless $obj->read( @_ );
114 }
115
116 return $obj;
117}
118
119=head2 $tar->read ( $filename|$handle, $compressed, {opt => 'val'} )
120
121Read the given tar file into memory.
122The first argument can either be the name of a file or a reference to
123an already open filehandle (or an IO::Zlib object if it's compressed)
124The second argument indicates whether the file referenced by the first
125argument is compressed.
126
127The C<read> will I<replace> any previous content in C<$tar>!
128
129The second argument may be considered optional if IO::Zlib is
130installed, since it will transparently Do The Right Thing.
131Archive::Tar will warn if you try to pass a compressed file if
132IO::Zlib is not available and simply return.
133
134The third argument can be a hash reference with options. Note that
135all options are case-sensitive.
136
137=over 4
138
139=item limit
140
141Do not read more than C<limit> files. This is useful if you have
142very big archives, and are only interested in the first few files.
143
144=item extract
145
146If set to true, immediately extract entries when reading them. This
147gives you the same memory break as the C<extract_archive> function.
148Note however that entries will not be read into memory, but written
149straight to disk.
150
151=back
152
153All files are stored internally as C<Archive::Tar::File> objects.
154Please consult the L<Archive::Tar::File> documentation for details.
155
156Returns the number of files read in scalar context, and a list of
157C<Archive::Tar::File> objects in list context.
158
159=cut
160
161sub read {
162 my $self = shift;
163 my $file = shift;
164 my $gzip = shift || 0;
165 my $opts = shift || {};
166
167 unless( defined $file ) {
168 $self->_error( qq[No file to read from!] );
169 return;
170 } else {
171 $self->_file( $file );
172 }
173
174 my $handle = $self->_get_handle($file, $gzip, READ_ONLY->( ZLIB ) )
175 or return;
176
177 my $data = $self->_read_tar( $handle, $opts ) or return;
178
179 $self->_data( $data );
180
181 return wantarray ? @$data : scalar @$data;
182}
183
184sub _get_handle {
185 my $self = shift;
186 my $file = shift; return unless defined $file;
187 return $file if ref $file;
188
189 my $gzip = shift || 0;
190 my $mode = shift || READ_ONLY->( ZLIB ); # default to read only
191
192 my $fh; my $bin;
193
194 ### only default to ZLIB if we're not trying to /write/ to a handle ###
195 if( ZLIB and $gzip || MODE_READ->( $mode ) ) {
196
197 ### IO::Zlib will Do The Right Thing, even when passed
198 ### a plain file ###
199 $fh = new IO::Zlib;
200
201 } else {
202 if( $gzip ) {
203 $self->_error(qq[Compression not available - Install IO::Zlib!]);
204 return;
205
206 } else {
207 $fh = new IO::File;
208 $bin++;
209 }
210 }
211
212 unless( $fh->open( $file, $mode ) ) {
213 $self->_error( qq[Could not create filehandle for '$file': $!!] );
214 return;
215 }
216
217 binmode $fh if $bin;
218
219 return $fh;
220}
221
222sub _read_tar {
223 my $self = shift;
224 my $handle = shift or return;
225 my $opts = shift || {};
226
227 my $count = $opts->{limit} || 0;
228 my $extract = $opts->{extract} || 0;
229
230 ### set a cap on the amount of files to extract ###
231 my $limit = 0;
232 $limit = 1 if $count > 0;
233
234 my $tarfile = [ ];
235 my $chunk;
236 my $read = 0;
237 my $real_name; # to set the name of a file when
238 # we're encountering @longlink
239 my $data;
240
241 LOOP:
242 while( $handle->read( $chunk, HEAD ) ) {
243 ### IO::Zlib doesn't support this yet
244 my $offset = eval { tell $handle } || 'unknown';
245
246 unless( $read++ ) {
247 my $gzip = GZIP_MAGIC_NUM;
248 if( $chunk =~ /$gzip/ ) {
249 $self->_error( qq[Cannot read compressed format in tar-mode] );
250 return;
251 }
252 }
253
254 ### if we can't read in all bytes... ###
255 last if length $chunk != HEAD;
256
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;
261
262 my $entry;
263 unless( $entry = Archive::Tar::File->new( chunk => $chunk ) ) {
264 $self->_error( qq[Couldn't read chunk at offset $offset] );
265 next;
266 }
267
268 ### ignore labels:
269 ### http://www.gnu.org/manual/tar/html_node/tar_139.html
270 next if $entry->is_label;
271
272 if( length $entry->type and ($entry->is_file || $entry->is_longlink) ) {
273
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;
280 $name =~ s/\n/ /g;
281
282 $self->_error( $name . qq[: checksum error] );
283 next LOOP;
284 }
285
286 my $block = BLOCK_SIZE->( $entry->size );
287
288 $data = $entry->get_content_by_ref;
289
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" );
297 next;
298 }
299
300 ### throw away trailing garbage ###
301 substr ($$data, $entry->size) = "";
302
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.
315
316 ### count number of nulls
317 my $nulls = $$data =~ tr/\0/\0/;
318
319 ### cut data + size by that many bytes
320 $entry->size( $entry->size - $nulls );
321 substr ($$data, $entry->size) = "";
322 }
323 }
324
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
330
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 ) {
334 $real_name = $data;
335 next;
336 } elsif ( defined $real_name ) {
337 $entry->name( $$real_name );
338 $entry->prefix('');
339 undef $real_name;
340 }
341
342 $self->_extract_file( $entry ) if $extract
343 && !$entry->is_longlink
344 && !$entry->is_unknown
345 && !$entry->is_label;
346
347 ### Guard against tarfiles with garbage at the end
348 last LOOP if $entry->name eq '';
349
350 ### push only the name on the rv if we're extracting
351 ### -- for extract_archive
352 push @$tarfile, ($extract ? $entry->name : $entry);
353
354 if( $limit ) {
355 $count-- unless $entry->is_longlink || $entry->is_dir;
356 last LOOP unless $count;
357 }
358 } continue {
359 undef $data;
360 }
361
362 return $tarfile;
363}
364
365=head2 $tar->contains_file( $filename )
366
367Check if the archive contains a certain file.
368It will return true if the file is in the archive, false otherwise.
369
370Note however, that this function does an exact match using C<eq>
371on the full path. So it cannot compensate for case-insensitive file-
372systems or compare 2 paths to see if they would point to the same
373underlying file.
374
375=cut
376
377sub contains_file {
378 my $self = shift;
379 my $full = shift or return;
380
381 return 1 if $self->_find_entry($full);
382 return;
383}
384
385=head2 $tar->extract( [@filenames] )
386
387Write files whose names are equivalent to any of the names in
388C<@filenames> to disk, creating subdirectories as necessary. This
389might not work too well under VMS.
390Under MacPerl, the file's modification time will be converted to the
391MacOS zero of time, and appropriate conversions will be done to the
392path. However, the length of each element of the path is not
393inspected to see whether it's longer than MacOS currently allows (32
394characters).
395
396If C<extract> is called without a list of file names, the entire
397contents of the archive are extracted.
398
399Returns a list of filenames extracted.
400
401=cut
402
403sub extract {
404 my $self = shift;
405 my @files;
406
407 ### you requested the extraction of only certian files
408 if( @_ ) {
409 for my $file (@_) {
410 my $found;
411 for my $entry ( @{$self->_data} ) {
412 next unless $file eq $entry->full_path;
413
414 ### we found the file you're looking for
415 push @files, $entry;
416 $found++;
417 }
418
419 unless( $found ) {
420 return $self->_error( qq[Could not find '$file' in archive] );
421 }
422 }
423
424 ### just grab all the file items
425 } else {
426 @files = $self->get_files;
427 }
428
429 ### nothing found? that's an error
430 unless( scalar @files ) {
431 $self->_error( qq[No files found for ] . $self->_file );
432 return;
433 }
434
435 ### now extract them
436 for my $entry ( @files ) {
437 unless( $self->_extract_file( $entry ) ) {
438 $self->_error(q[Could not extract ']. $entry->full_path .q['] );
439 return;
440 }
441 }
442
443 return @files;
444}
445
446=head2 $tar->extract_file( $file, [$extract_path] )
447
448Write an entry, whose name is equivalent to the file name provided to
449disk. Optionally takes a second parameter, which is the full (unix)
450path (including filename) the entry will be written to.
451
452For example:
453
454 $tar->extract_file( 'name/in/archive', 'name/i/want/to/give/it' );
455
456Returns true on success, false on failure.
457
458=cut
459
460sub extract_file {
461 my $self = shift;
462 my $file = shift or return;
463 my $alt = shift;
464
465 my $entry = $self->_find_entry( $file )
466 or $self->_error( qq[Could not find an entry for '$file'] ), return;
467
468 return $self->_extract_file( $entry, $alt );
469}
470
471sub _extract_file {
472 my $self = shift;
473 my $entry = shift or return;
474 my $alt = shift;
475 my $cwd = cwd();
476
477 ### you wanted an alternate extraction location ###
478 my $name = defined $alt ? $alt : $entry->full_path;
479
480 ### splitpath takes a bool at the end to indicate
481 ### that it's splitting a dir
7f10f74b 482 my ($vol,$dirs,$file);
483 if ( defined $alt ) { # It's a local-OS path
484 ($vol,$dirs,$file) = File::Spec->splitpath( $alt,
485 $entry->is_dir );
486 } else {
487 ($vol,$dirs,$file) = File::Spec::Unix->splitpath( $name,
488 $entry->is_dir );
489 }
490
39713df4 491 my $dir;
492 ### is $name an absolute path? ###
493 if( File::Spec->file_name_is_absolute( $dirs ) ) {
494 $dir = $dirs;
495
496 ### it's a relative path ###
497 } else {
498 my @dirs = File::Spec::Unix->splitdir( $dirs );
499 my @cwd = File::Spec->splitdir( $cwd );
500 $dir = File::Spec->catdir(@cwd, @dirs);
501 }
502
503 if( -e $dir && !-d _ ) {
504 $^W && $self->_error( qq['$dir' exists, but it's not a directory!\n] );
505 return;
506 }
507
508 unless ( -d _ ) {
509 eval { File::Path::mkpath( $dir, 0, 0777 ) };
510 if( $@ ) {
511 $self->_error( qq[Could not create directory '$dir': $@] );
512 return;
513 }
514 }
515
516 ### we're done if we just needed to create a dir ###
517 return 1 if $entry->is_dir;
518
519 my $full = File::Spec->catfile( $dir, $file );
520
521 if( $entry->is_unknown ) {
522 $self->_error( qq[Unknown file type for file '$full'] );
523 return;
524 }
525
526 if( length $entry->type && $entry->is_file ) {
527 my $fh = IO::File->new;
528 $fh->open( '>' . $full ) or (
529 $self->_error( qq[Could not open file '$full': $!] ),
530 return
531 );
532
533 if( $entry->size ) {
534 binmode $fh;
535 syswrite $fh, $entry->data or (
536 $self->_error( qq[Could not write data to '$full'] ),
537 return
538 );
539 }
540
541 close $fh or (
542 $self->_error( qq[Could not close file '$full'] ),
543 return
544 );
545
546 } else {
547 $self->_make_special_file( $entry, $full ) or return;
548 }
549
550 utime time, $entry->mtime - TIME_OFFSET, $full or
551 $self->_error( qq[Could not update timestamp] );
552
553 if( $CHOWN && CAN_CHOWN ) {
554 chown $entry->uid, $entry->gid, $full or
555 $self->_error( qq[Could not set uid/gid on '$full'] );
556 }
557
558 ### only chmod if we're allowed to, but never chmod symlinks, since they'll
559 ### change the perms on the file they're linking too...
560 if( $CHMOD and not -l $full ) {
561 chmod $entry->mode, $full or
562 $self->_error( qq[Could not chown '$full' to ] . $entry->mode );
563 }
564
565 return 1;
566}
567
568sub _make_special_file {
569 my $self = shift;
570 my $entry = shift or return;
571 my $file = shift; return unless defined $file;
572
573 my $err;
574
575 if( $entry->is_symlink ) {
576 my $fail;
577 if( ON_UNIX ) {
578 symlink( $entry->linkname, $file ) or $fail++;
579
580 } else {
581 $self->_extract_special_file_as_plain_file( $entry, $file )
582 or $fail++;
583 }
584
585 $err = qq[Making symbolink link from '] . $entry->linkname .
586 qq[' to '$file' failed] if $fail;
587
588 } elsif ( $entry->is_hardlink ) {
589 my $fail;
590 if( ON_UNIX ) {
591 link( $entry->linkname, $file ) or $fail++;
592
593 } else {
594 $self->_extract_special_file_as_plain_file( $entry, $file )
595 or $fail++;
596 }
597
598 $err = qq[Making hard link from '] . $entry->linkname .
599 qq[' to '$file' failed] if $fail;
600
601 } elsif ( $entry->is_fifo ) {
602 ON_UNIX && !system('mknod', $file, 'p') or
603 $err = qq[Making fifo ']. $entry->name .qq[' failed];
604
605 } elsif ( $entry->is_blockdev or $entry->is_chardev ) {
606 my $mode = $entry->is_blockdev ? 'b' : 'c';
607
608 ON_UNIX && !system('mknod', $file, $mode,
609 $entry->devmajor, $entry->devminor) or
610 $err = qq[Making block device ']. $entry->name .qq[' (maj=] .
611 $entry->devmajor . qq[ min=] . $entry->devminor .
612 qq[) failed.];
613
614 } elsif ( $entry->is_socket ) {
615 ### the original doesn't do anything special for sockets.... ###
616 1;
617 }
618
619 return $err ? $self->_error( $err ) : 1;
620}
621
622### don't know how to make symlinks, let's just extract the file as
623### a plain file
624sub _extract_special_file_as_plain_file {
625 my $self = shift;
626 my $entry = shift or return;
627 my $file = shift; return unless defined $file;
628
629 my $err;
630 TRY: {
631 my $orig = $self->_find_entry( $entry->linkname );
632
633 unless( $orig ) {
634 $err = qq[Could not find file '] . $entry->linkname .
635 qq[' in memory.];
636 last TRY;
637 }
638
639 ### clone the entry, make it appear as a normal file ###
640 my $clone = $entry->clone;
641 $clone->_downgrade_to_plainfile;
642 $self->_extract_file( $clone, $file ) or last TRY;
643
644 return 1;
645 }
646
647 return $self->_error($err);
648}
649
650=head2 $tar->list_files( [\@properties] )
651
652Returns a list of the names of all the files in the archive.
653
654If C<list_files()> is passed an array reference as its first argument
655it returns a list of hash references containing the requested
656properties of each file. The following list of properties is
657supported: name, size, mtime (last modified date), mode, uid, gid,
658linkname, uname, gname, devmajor, devminor, prefix.
659
660Passing an array reference containing only one element, 'name', is
661special cased to return a list of names rather than a list of hash
662references, making it equivalent to calling C<list_files> without
663arguments.
664
665=cut
666
667sub list_files {
668 my $self = shift;
669 my $aref = shift || [ ];
670
671 unless( $self->_data ) {
672 $self->read() or return;
673 }
674
675 if( @$aref == 0 or ( @$aref == 1 and $aref->[0] eq 'name' ) ) {
676 return map { $_->full_path } @{$self->_data};
677 } else {
678
679 #my @rv;
680 #for my $obj ( @{$self->_data} ) {
681 # push @rv, { map { $_ => $obj->$_() } @$aref };
682 #}
683 #return @rv;
684
685 ### this does the same as the above.. just needs a +{ }
686 ### to make sure perl doesn't confuse it for a block
687 return map { my $o=$_;
688 +{ map { $_ => $o->$_() } @$aref }
689 } @{$self->_data};
690 }
691}
692
693sub _find_entry {
694 my $self = shift;
695 my $file = shift;
696
697 unless( defined $file ) {
698 $self->_error( qq[No file specified] );
699 return;
700 }
701
702 for my $entry ( @{$self->_data} ) {
703 my $path = $entry->full_path;
704 return $entry if $path eq $file;
705 }
706
707 $self->_error( qq[No such file in archive: '$file'] );
708 return;
709}
710
711=head2 $tar->get_files( [@filenames] )
712
713Returns the C<Archive::Tar::File> objects matching the filenames
714provided. If no filename list was passed, all C<Archive::Tar::File>
715objects in the current Tar object are returned.
716
717Please refer to the C<Archive::Tar::File> documentation on how to
718handle these objects.
719
720=cut
721
722sub get_files {
723 my $self = shift;
724
725 return @{ $self->_data } unless @_;
726
727 my @list;
728 for my $file ( @_ ) {
729 push @list, grep { defined } $self->_find_entry( $file );
730 }
731
732 return @list;
733}
734
735=head2 $tar->get_content( $file )
736
737Return the content of the named file.
738
739=cut
740
741sub get_content {
742 my $self = shift;
743 my $entry = $self->_find_entry( shift ) or return;
744
745 return $entry->data;
746}
747
748=head2 $tar->replace_content( $file, $content )
749
750Make the string $content be the content for the file named $file.
751
752=cut
753
754sub replace_content {
755 my $self = shift;
756 my $entry = $self->_find_entry( shift ) or return;
757
758 return $entry->replace_content( shift );
759}
760
761=head2 $tar->rename( $file, $new_name )
762
763Rename the file of the in-memory archive to $new_name.
764
765Note that you must specify a Unix path for $new_name, since per tar
766standard, all files in the archive must be Unix paths.
767
768Returns true on success and false on failure.
769
770=cut
771
772sub rename {
773 my $self = shift;
774 my $file = shift; return unless defined $file;
775 my $new = shift; return unless defined $new;
776
777 my $entry = $self->_find_entry( $file ) or return;
778
779 return $entry->rename( $new );
780}
781
782=head2 $tar->remove (@filenamelist)
783
784Removes any entries with names matching any of the given filenames
785from the in-memory archive. Returns a list of C<Archive::Tar::File>
786objects that remain.
787
788=cut
789
790sub remove {
791 my $self = shift;
792 my @list = @_;
793
794 my %seen = map { $_->full_path => $_ } @{$self->_data};
795 delete $seen{ $_ } for @list;
796
797 $self->_data( [values %seen] );
798
799 return values %seen;
800}
801
802=head2 $tar->clear
803
804C<clear> clears the current in-memory archive. This effectively gives
805you a 'blank' object, ready to be filled again. Note that C<clear>
806only has effect on the object, not the underlying tarfile.
807
808=cut
809
810sub clear {
811 my $self = shift or return;
812
813 $self->_data( [] );
814 $self->_file( '' );
815
816 return 1;
817}
818
819
820=head2 $tar->write ( [$file, $compressed, $prefix] )
821
822Write the in-memory archive to disk. The first argument can either
823be the name of a file or a reference to an already open filehandle (a
824GLOB reference). If the second argument is true, the module will use
825IO::Zlib to write the file in a compressed format. If IO::Zlib is
826not available, the C<write> method will fail and return.
827
828Note that when you pass in a filehandle, the compression argument
829is ignored, as all files are printed verbatim to your filehandle.
830If you wish to enable compression with filehandles, use an
831C<IO::Zlib> filehandle instead.
832
833Specific levels of compression can be chosen by passing the values 2
834through 9 as the second parameter.
835
836The third argument is an optional prefix. All files will be tucked
837away in the directory you specify as prefix. So if you have files
838'a' and 'b' in your archive, and you specify 'foo' as prefix, they
839will be written to the archive as 'foo/a' and 'foo/b'.
840
841If no arguments are given, C<write> returns the entire formatted
842archive as a string, which could be useful if you'd like to stuff the
843archive into a socket or a pipe to gzip or something.
844
845=cut
846
847sub write {
848 my $self = shift;
849 my $file = shift; $file = '' unless defined $file;
850 my $gzip = shift || 0;
851 my $ext_prefix = shift; $ext_prefix = '' unless defined $ext_prefix;
852 my $dummy = '';
853
854 ### only need a handle if we have a file to print to ###
855 my $handle = length($file)
856 ? ( $self->_get_handle($file, $gzip, WRITE_ONLY->($gzip) )
857 or return )
858 : $HAS_PERLIO ? do { open my $h, '>', \$dummy; $h }
859 : $HAS_IO_STRING ? IO::String->new
860 : __PACKAGE__->no_string_support();
861
862
863
864 for my $entry ( @{$self->_data} ) {
865 ### entries to be written to the tarfile ###
866 my @write_me;
867
868 ### only now will we change the object to reflect the current state
869 ### of the name and prefix fields -- this needs to be limited to
870 ### write() only!
871 my $clone = $entry->clone;
872
873
874 ### so, if you don't want use to use the prefix, we'll stuff
875 ### everything in the name field instead
876 if( $DO_NOT_USE_PREFIX ) {
877
878 ### you might have an extended prefix, if so, set it in the clone
879 ### XXX is ::Unix right?
880 $clone->name( length $ext_prefix
881 ? File::Spec::Unix->catdir( $ext_prefix,
882 $clone->full_path)
883 : $clone->full_path );
884 $clone->prefix( '' );
885
886 ### otherwise, we'll have to set it properly -- prefix part in the
887 ### prefix and name part in the name field.
888 } else {
889
890 ### split them here, not before!
891 my ($prefix,$name) = $clone->_prefix_and_file( $clone->full_path );
892
893 ### you might have an extended prefix, if so, set it in the clone
894 ### XXX is ::Unix right?
895 $prefix = File::Spec::Unix->catdir( $ext_prefix, $prefix )
896 if length $ext_prefix;
897
898 $clone->prefix( $prefix );
899 $clone->name( $name );
900 }
901
902 ### names are too long, and will get truncated if we don't add a
903 ### '@LongLink' file...
904 my $make_longlink = ( length($clone->name) > NAME_LENGTH or
905 length($clone->prefix) > PREFIX_LENGTH
906 ) || 0;
907
908 ### perhaps we need to make a longlink file?
909 if( $make_longlink ) {
910 my $longlink = Archive::Tar::File->new(
911 data => LONGLINK_NAME,
912 $clone->full_path,
913 { type => LONGLINK }
914 );
915
916 unless( $longlink ) {
917 $self->_error( qq[Could not create 'LongLink' entry for ] .
918 qq[oversize file '] . $clone->full_path ."'" );
919 return;
920 };
921
922 push @write_me, $longlink;
923 }
924
925 push @write_me, $clone;
926
927 ### write the one, optionally 2 a::t::file objects to the handle
928 for my $clone (@write_me) {
929
930 ### if the file is a symlink, there are 2 options:
931 ### either we leave the symlink intact, but then we don't write any
932 ### data OR we follow the symlink, which means we actually make a
933 ### copy. if we do the latter, we have to change the TYPE of the
934 ### clone to 'FILE'
935 my $link_ok = $clone->is_symlink && $Archive::Tar::FOLLOW_SYMLINK;
936 my $data_ok = !$clone->is_symlink && $clone->has_content;
937
938 ### downgrade to a 'normal' file if it's a symlink we're going to
939 ### treat as a regular file
940 $clone->_downgrade_to_plainfile if $link_ok;
941
942 ### get the header for this block
943 my $header = $self->_format_tar_entry( $clone );
944 unless( $header ) {
945 $self->_error(q[Could not format header for: ] .
946 $clone->full_path );
947 return;
948 }
949
950 unless( print $handle $header ) {
951 $self->_error(q[Could not write header for: ] .
952 $clone->full_path);
953 return;
954 }
955
956 if( $link_ok or $data_ok ) {
957 unless( print $handle $clone->data ) {
958 $self->_error(q[Could not write data for: ] .
959 $clone->full_path);
960 return;
961 }
962
963 ### pad the end of the clone if required ###
964 print $handle TAR_PAD->( $clone->size ) if $clone->size % BLOCK
965 }
966
967 } ### done writing these entries
968 }
969
970 ### write the end markers ###
971 print $handle TAR_END x 2 or
972 return $self->_error( qq[Could not write tar end markers] );
973 ### did you want it written to a file, or returned as a string? ###
974 return length($file) ? 1
975 : $HAS_PERLIO ? $dummy
976 : do { seek $handle, 0, 0; local $/; <$handle> }
977}
978
979sub _format_tar_entry {
980 my $self = shift;
981 my $entry = shift or return;
982 my $ext_prefix = shift; $ext_prefix = '' unless defined $ext_prefix;
983 my $no_prefix = shift || 0;
984
985 my $file = $entry->name;
986 my $prefix = $entry->prefix; $prefix = '' unless defined $prefix;
987
988 ### remove the prefix from the file name
989 ### not sure if this is still neeeded --kane
990 ### no it's not -- Archive::Tar::File->_new_from_file will take care of
991 ### this for us. Even worse, this would break if we tried to add a file
992 ### like x/x.
993 #if( length $prefix ) {
994 # $file =~ s/^$match//;
995 #}
996
997 $prefix = File::Spec::Unix->catdir($ext_prefix, $prefix)
998 if length $ext_prefix;
999
1000 ### not sure why this is... ###
1001 my $l = PREFIX_LENGTH; # is ambiguous otherwise...
1002 substr ($prefix, 0, -$l) = "" if length $prefix >= PREFIX_LENGTH;
1003
1004 my $f1 = "%06o"; my $f2 = "%11o";
1005
1006 ### this might be optimizable with a 'changed' flag in the file objects ###
1007 my $tar = pack (
1008 PACK,
1009 $file,
1010
1011 (map { sprintf( $f1, $entry->$_() ) } qw[mode uid gid]),
1012 (map { sprintf( $f2, $entry->$_() ) } qw[size mtime]),
1013
1014 "", # checksum field - space padded a bit down
1015
1016 (map { $entry->$_() } qw[type linkname magic]),
1017
1018 $entry->version || TAR_VERSION,
1019
1020 (map { $entry->$_() } qw[uname gname]),
1021 (map { sprintf( $f1, $entry->$_() ) } qw[devmajor devminor]),
1022
1023 ($no_prefix ? '' : $prefix)
1024 );
1025
1026 ### add the checksum ###
1027 substr($tar,148,7) = sprintf("%6o\0", unpack("%16C*",$tar));
1028
1029 return $tar;
1030}
1031
1032=head2 $tar->add_files( @filenamelist )
1033
1034Takes a list of filenames and adds them to the in-memory archive.
1035
1036The path to the file is automatically converted to a Unix like
1037equivalent for use in the archive, and, if on MacOS, the file's
1038modification time is converted from the MacOS epoch to the Unix epoch.
1039So tar archives created on MacOS with B<Archive::Tar> can be read
1040both with I<tar> on Unix and applications like I<suntar> or
1041I<Stuffit Expander> on MacOS.
1042
1043Be aware that the file's type/creator and resource fork will be lost,
1044which is usually what you want in cross-platform archives.
1045
1046Returns a list of C<Archive::Tar::File> objects that were just added.
1047
1048=cut
1049
1050sub add_files {
1051 my $self = shift;
1052 my @files = @_ or return;
1053
1054 my @rv;
1055 for my $file ( @files ) {
1056 unless( -e $file ) {
1057 $self->_error( qq[No such file: '$file'] );
1058 next;
1059 }
1060
1061 my $obj = Archive::Tar::File->new( file => $file );
1062 unless( $obj ) {
1063 $self->_error( qq[Unable to add file: '$file'] );
1064 next;
1065 }
1066
1067 push @rv, $obj;
1068 }
1069
1070 push @{$self->{_data}}, @rv;
1071
1072 return @rv;
1073}
1074
1075=head2 $tar->add_data ( $filename, $data, [$opthashref] )
1076
1077Takes a filename, a scalar full of data and optionally a reference to
1078a hash with specific options.
1079
1080Will add a file to the in-memory archive, with name C<$filename> and
1081content C<$data>. Specific properties can be set using C<$opthashref>.
1082The following list of properties is supported: name, size, mtime
1083(last modified date), mode, uid, gid, linkname, uname, gname,
1084devmajor, devminor, prefix. (On MacOS, the file's path and
1085modification times are converted to Unix equivalents.)
1086
1087Returns the C<Archive::Tar::File> object that was just added, or
1088C<undef> on failure.
1089
1090=cut
1091
1092sub add_data {
1093 my $self = shift;
1094 my ($file, $data, $opt) = @_;
1095
1096 my $obj = Archive::Tar::File->new( data => $file, $data, $opt );
1097 unless( $obj ) {
1098 $self->_error( qq[Unable to add file: '$file'] );
1099 return;
1100 }
1101
1102 push @{$self->{_data}}, $obj;
1103
1104 return $obj;
1105}
1106
1107=head2 $tar->error( [$BOOL] )
1108
1109Returns the current errorstring (usually, the last error reported).
1110If a true value was specified, it will give the C<Carp::longmess>
1111equivalent of the error, in effect giving you a stacktrace.
1112
1113For backwards compatibility, this error is also available as
1114C<$Archive::Tar::error> although it is much recommended you use the
1115method call instead.
1116
1117=cut
1118
1119{
1120 $error = '';
1121 my $longmess;
1122
1123 sub _error {
1124 my $self = shift;
1125 my $msg = $error = shift;
1126 $longmess = Carp::longmess($error);
1127
1128 ### set Archive::Tar::WARN to 0 to disable printing
1129 ### of errors
1130 if( $WARN ) {
1131 carp $DEBUG ? $longmess : $msg;
1132 }
1133
1134 return;
1135 }
1136
1137 sub error {
1138 my $self = shift;
1139 return shift() ? $longmess : $error;
1140 }
1141}
1142
1143
1144=head2 $bool = $tar->has_io_string
1145
1146Returns true if we currently have C<IO::String> support loaded.
1147
1148Either C<IO::String> or C<perlio> support is needed to support writing
1149stringified archives. Currently, C<perlio> is the preffered method, if
1150available.
1151
1152See the C<GLOBAL VARIABLES> section to see how to change this preference.
1153
1154=cut
1155
1156sub has_io_string { return $HAS_IO_STRING; }
1157
1158=head2 $bool = $tar->has_perlio
1159
1160Returns true if we currently have C<perlio> support loaded.
1161
1162This requires C<perl-5.8> or higher, compiled with C<perlio>
1163
1164Either C<IO::String> or C<perlio> support is needed to support writing
1165stringified archives. Currently, C<perlio> is the preffered method, if
1166available.
1167
1168See the C<GLOBAL VARIABLES> section to see how to change this preference.
1169
1170=cut
1171
1172sub has_perlio { return $HAS_PERLIO; }
1173
1174
1175=head1 Class Methods
1176
1177=head2 Archive::Tar->create_archive($file, $compression, @filelist)
1178
1179Creates a tar file from the list of files provided. The first
1180argument can either be the name of the tar file to create or a
1181reference to an open file handle (e.g. a GLOB reference).
1182
1183The second argument specifies the level of compression to be used, if
1184any. Compression of tar files requires the installation of the
1185IO::Zlib module. Specific levels of compression may be
1186requested by passing a value between 2 and 9 as the second argument.
1187Any other value evaluating as true will result in the default
1188compression level being used.
1189
1190Note that when you pass in a filehandle, the compression argument
1191is ignored, as all files are printed verbatim to your filehandle.
1192If you wish to enable compression with filehandles, use an
1193C<IO::Zlib> filehandle instead.
1194
1195The remaining arguments list the files to be included in the tar file.
1196These files must all exist. Any files which don't exist or can't be
1197read are silently ignored.
1198
1199If the archive creation fails for any reason, C<create_archive> will
1200return false. Please use the C<error> method to find the cause of the
1201failure.
1202
1203Note that this method does not write C<on the fly> as it were; it
1204still reads all the files into memory before writing out the archive.
1205Consult the FAQ below if this is a problem.
1206
1207=cut
1208
1209sub create_archive {
1210 my $class = shift;
1211
1212 my $file = shift; return unless defined $file;
1213 my $gzip = shift || 0;
1214 my @files = @_;
1215
1216 unless( @files ) {
1217 return $class->_error( qq[Cowardly refusing to create empty archive!] );
1218 }
1219
1220 my $tar = $class->new;
1221 $tar->add_files( @files );
1222 return $tar->write( $file, $gzip );
1223}
1224
1225=head2 Archive::Tar->list_archive ($file, $compressed, [\@properties])
1226
1227Returns a list of the names of all the files in the archive. The
1228first argument can either be the name of the tar file to list or a
1229reference to an open file handle (e.g. a GLOB reference).
1230
1231If C<list_archive()> is passed an array reference as its third
1232argument it returns a list of hash references containing the requested
1233properties of each file. The following list of properties is
1234supported: name, size, mtime (last modified date), mode, uid, gid,
1235linkname, uname, gname, devmajor, devminor, prefix.
1236
1237Passing an array reference containing only one element, 'name', is
1238special cased to return a list of names rather than a list of hash
1239references.
1240
1241=cut
1242
1243sub list_archive {
1244 my $class = shift;
1245 my $file = shift; return unless defined $file;
1246 my $gzip = shift || 0;
1247
1248 my $tar = $class->new($file, $gzip);
1249 return unless $tar;
1250
1251 return $tar->list_files( @_ );
1252}
1253
1254=head2 Archive::Tar->extract_archive ($file, $gzip)
1255
1256Extracts the contents of the tar file. The first argument can either
1257be the name of the tar file to create or a reference to an open file
1258handle (e.g. a GLOB reference). All relative paths in the tar file will
1259be created underneath the current working directory.
1260
1261C<extract_archive> will return a list of files it extracted.
1262If the archive extraction fails for any reason, C<extract_archive>
1263will return false. Please use the C<error> method to find the cause
1264of the failure.
1265
1266=cut
1267
1268sub extract_archive {
1269 my $class = shift;
1270 my $file = shift; return unless defined $file;
1271 my $gzip = shift || 0;
1272
1273 my $tar = $class->new( ) or return;
1274
1275 return $tar->read( $file, $gzip, { extract => 1 } );
1276}
1277
1278=head2 Archive::Tar->can_handle_compressed_files
1279
1280A simple checking routine, which will return true if C<Archive::Tar>
1281is able to uncompress compressed archives on the fly with C<IO::Zlib>,
1282or false if C<IO::Zlib> is not installed.
1283
1284You can use this as a shortcut to determine whether C<Archive::Tar>
1285will do what you think before passing compressed archives to its
1286C<read> method.
1287
1288=cut
1289
1290sub can_handle_compressed_files { return ZLIB ? 1 : 0 }
1291
1292sub no_string_support {
1293 croak("You have to install IO::String to support writing archives to strings");
1294}
1295
12961;
1297
1298__END__
1299
1300=head1 GLOBAL VARIABLES
1301
1302=head2 $Archive::Tar::FOLLOW_SYMLINK
1303
1304Set this variable to C<1> to make C<Archive::Tar> effectively make a
1305copy of the file when extracting. Default is C<0>, which
1306means the symlink stays intact. Of course, you will have to pack the
1307file linked to as well.
1308
1309This option is checked when you write out the tarfile using C<write>
1310or C<create_archive>.
1311
1312This works just like C</bin/tar>'s C<-h> option.
1313
1314=head2 $Archive::Tar::CHOWN
1315
1316By default, C<Archive::Tar> will try to C<chown> your files if it is
1317able to. In some cases, this may not be desired. In that case, set
1318this variable to C<0> to disable C<chown>-ing, even if it were
1319possible.
1320
1321The default is C<1>.
1322
1323=head2 $Archive::Tar::CHMOD
1324
1325By default, C<Archive::Tar> will try to C<chmod> your files to
1326whatever mode was specified for the particular file in the archive.
1327In some cases, this may not be desired. In that case, set this
1328variable to C<0> to disable C<chmod>-ing.
1329
1330The default is C<1>.
1331
1332=head2 $Archive::Tar::DO_NOT_USE_PREFIX
1333
1334By default, C<Archive::Tar> will try to put paths that are over
1335100 characters in the C<prefix> field of your tar header. However,
1336some older tar programs do not implement this spec. To retain
1337compatibility with these older versions, you can set the
1338C<$DO_NOT_USE_PREFIX> variable to a true value, and C<Archive::Tar>
1339will use an alternate way of dealing with paths over 100 characters
1340by using the C<GNU Extended Header> feature.
1341
1342The default is C<0>.
1343
1344=head2 $Archive::Tar::DEBUG
1345
1346Set this variable to C<1> to always get the C<Carp::longmess> output
1347of the warnings, instead of the regular C<carp>. This is the same
1348message you would get by doing:
1349
1350 $tar->error(1);
1351
1352Defaults to C<0>.
1353
1354=head2 $Archive::Tar::WARN
1355
1356Set this variable to C<0> if you do not want any warnings printed.
1357Personally I recommend against doing this, but people asked for the
1358option. Also, be advised that this is of course not threadsafe.
1359
1360Defaults to C<1>.
1361
1362=head2 $Archive::Tar::error
1363
1364Holds the last reported error. Kept for historical reasons, but its
1365use is very much discouraged. Use the C<error()> method instead:
1366
1367 warn $tar->error unless $tar->extract;
1368
1369=head2 $Archive::Tar::HAS_PERLIO
1370
1371This variable holds a boolean indicating if we currently have
1372C<perlio> support loaded. This will be enabled for any perl
1373greater than C<5.8> compiled with C<perlio>.
1374
1375If you feel strongly about disabling it, set this variable to
1376C<false>. Note that you will then need C<IO::String> installed
1377to support writing stringified archives.
1378
1379Don't change this variable unless you B<really> know what you're
1380doing.
1381
1382=head2 $Archive::Tar::HAS_IO_STRING
1383
1384This variable holds a boolean indicating if we currently have
1385C<IO::String> support loaded. This will be enabled for any perl
1386that has a loadable C<IO::String> module.
1387
1388If you feel strongly about disabling it, set this variable to
1389C<false>. Note that you will then need C<perlio> support from
1390your perl to be able to write stringified archives.
1391
1392Don't change this variable unless you B<really> know what you're
1393doing.
1394
1395=head1 FAQ
1396
1397=over 4
1398
1399=item What's the minimum perl version required to run Archive::Tar?
1400
1401You will need perl version 5.005_03 or newer.
1402
1403=item Isn't Archive::Tar slow?
1404
1405Yes it is. It's pure perl, so it's a lot slower then your C</bin/tar>
1406However, it's very portable. If speed is an issue, consider using
1407C</bin/tar> instead.
1408
1409=item Isn't Archive::Tar heavier on memory than /bin/tar?
1410
1411Yes it is, see previous answer. Since C<Compress::Zlib> and therefore
1412C<IO::Zlib> doesn't support C<seek> on their filehandles, there is little
1413choice but to read the archive into memory.
1414This is ok if you want to do in-memory manipulation of the archive.
1415If you just want to extract, use the C<extract_archive> class method
1416instead. It will optimize and write to disk immediately.
1417
1418=item Can't you lazy-load data instead?
1419
1420No, not easily. See previous question.
1421
1422=item How much memory will an X kb tar file need?
1423
1424Probably more than X kb, since it will all be read into memory. If
1425this is a problem, and you don't need to do in memory manipulation
1426of the archive, consider using C</bin/tar> instead.
1427
1428=item What do you do with unsupported filetypes in an archive?
1429
1430C<Unix> has a few filetypes that aren't supported on other platforms,
1431like C<Win32>. If we encounter a C<hardlink> or C<symlink> we'll just
1432try to make a copy of the original file, rather than throwing an error.
1433
1434This does require you to read the entire archive in to memory first,
1435since otherwise we wouldn't know what data to fill the copy with.
1436(This means that you cannot use the class methods on archives that
1437have incompatible filetypes and still expect things to work).
1438
1439For other filetypes, like C<chardevs> and C<blockdevs> we'll warn that
1440the extraction of this particular item didn't work.
1441
1442=back
1443
1444=head1 TODO
1445
1446=over 4
1447
1448=item Check if passed in handles are open for read/write
1449
1450Currently I don't know of any portable pure perl way to do this.
1451Suggestions welcome.
1452
1453=back
1454
1455=head1 AUTHOR
1456
1457This module by
1458Jos Boumans E<lt>kane@cpan.orgE<gt>.
1459
1460=head1 ACKNOWLEDGEMENTS
1461
1462Thanks to Sean Burke, Chris Nandor, Chip Salzenberg, Tim Heaney and
1463especially Andrew Savige for their help and suggestions.
1464
1465=head1 COPYRIGHT
1466
1467This module is
1468copyright (c) 2002 Jos Boumans E<lt>kane@cpan.orgE<gt>.
1469All rights reserved.
1470
1471This library is free software;
1472you may redistribute and/or modify it under the same
1473terms as Perl itself.
1474
1475=cut