| 1 | # ABSTRACT: Embed a self-extracting tarball in a Perl module. | ||
| 2 | package App::FilePacker; | ||
| 3 | use Moo; | ||
| 4 | use Archive::Tar; | ||
| 5 | use File::Find; | ||
| 6 | use Cwd; | ||
| 7 | |||
| 8 | our $VERSION = '0.001'; | ||
| 9 | |||
| 10 | # Name of the module to create, | ||
| 11 | # used in the package declaration. | ||
| 12 | # ex: Foo::Bar | ||
| 13 | has name => ( | ||
| 14 | is => 'ro', | ||
| 15 | ); | ||
| 16 | |||
| 17 | # Name of the file to output to. | ||
| 18 | # ex: Bar.pm | ||
| 19 | has out => ( | ||
| 20 | is => 'ro', | ||
| 21 | ); | ||
| 22 | |||
| 23 | # Directory to package | ||
| 24 | has dir => ( | ||
| 25 | is => 'ro', | ||
| 26 | isa => sub { | ||
| 27 | die "$_[0] is not a directory" unless -d $_[0]; | ||
| 28 | }, | ||
| 29 | ); | ||
| 30 | |||
| 31 | has tarball => ( | ||
| 32 | is => 'lazy', | ||
| 33 | init_arg => undef, | ||
| 34 | ); | ||
| 35 | |||
| 36 | sub _build_tarball { | ||
| 37 | my ( $self ) = @_; | ||
| 38 | |||
| 39 | my $tarball = Archive::Tar->new; | ||
| 40 | |||
| 41 | |||
| 42 | my $orig = getcwd; | ||
| 43 | chdir $self->dir | ||
| 44 | or die "Failed to chdir to " . $self->dir . ": $!"; | ||
| 45 | |||
| 46 | find({ | ||
| 47 | wanted => sub { | ||
| 48 | return if $_ =~ m|/\.\.?$|; # Skip . and .. | ||
| 49 | $tarball->add_files( $_ ); | ||
| 50 | }, | ||
| 51 | no_chdir => 1, | ||
| 52 | }, '.' ); | ||
| 53 | |||
| 54 | chdir $orig | ||
| 55 | or die "Failed to chdir to $orig after tarball creation: $!"; | ||
| 56 | |||
| 57 | return $tarball; | ||
| 58 | } | ||
| 59 | |||
| 60 | # Body of module to extract embedded tar file. | ||
| 61 | has module_body => ( | ||
| 62 | is => 'ro', | ||
| 63 | default => sub { return join "\n", | ||
| 64 | 'use warnings;', | ||
| 65 | 'use strict;', | ||
| 66 | 'use Archive::Tar;', | ||
| 67 | 'use File::Path qw( make_path );', | ||
| 68 | '', | ||
| 69 | 'sub extract {', | ||
| 70 | ' my ( $path ) = @_;', | ||
| 71 | '', | ||
| 72 | ' make_path( $path );', | ||
| 73 | '', | ||
| 74 | ' chdir $path', | ||
| 75 | ' or die "Failed to move into path $path to extract files.\n";', | ||
| 76 | '', | ||
| 77 | ' Archive::Tar->new( \*DATA, 0, { extract => 1 } );', | ||
| 78 | '}'; | ||
| 79 | }, | ||
| 80 | ); | ||
| 81 | |||
| 82 | sub write { | ||
| 83 | my ( $self ) = @_; | ||
| 84 | |||
| 85 | open my $sf, ">", $self->out | ||
| 86 | or die "Failed to open " . $self->out . " for writing: $!"; | ||
| 87 | |||
| 88 | print $sf "package " . $self->name . ";\n"; | ||
| 89 | print $sf $self->module_body; | ||
| 90 | print $sf "\n1;\n"; | ||
| 91 | print $sf "__DATA__\n"; | ||
| 92 | $self->tarball->write( $sf ); | ||
| 93 | close $sf; | ||
| 94 | |||
| 95 | } | ||
| 96 | |||
| 97 | 1; | ||
| 98 | |||
| 99 | __END__ |