| 1 | package Silki::Role::Web::CombinedStaticFiles; | ||
| 2 | { | ||
| 3 | $Silki::Role::Web::CombinedStaticFiles::VERSION = '0.29'; | ||
| 4 | } | ||
| 5 | |||
| 6 | use strict; | ||
| 7 | use warnings; | ||
| 8 | use namespace::autoclean; | ||
| 9 | |||
| 10 | use autodie; | ||
| 11 | use DateTime; | ||
| 12 | use File::Copy qw( move ); | ||
| 13 | use File::Slurp qw( read_file ); | ||
| 14 | use File::Temp qw( tempfile ); | ||
| 15 | use JSAN::ServerSide 0.04; | ||
| 16 | use List::AllUtils qw( all ); | ||
| 17 | use Path::Class; | ||
| 18 | use Silki::Config; | ||
| 19 | use Silki::Util qw( string_is_empty ); | ||
| 20 | use Time::HiRes; | ||
| 21 | |||
| 22 | use Moose::Role; | ||
| 23 | |||
| 24 | has files => ( | ||
| 25 | is => 'ro', | ||
| 26 | isa => 'ArrayRef[Path::Class::File]', | ||
| 27 | lazy => 1, | ||
| 28 | builder => '_build_files', | ||
| 29 | ); | ||
| 30 | |||
| 31 | has target_file => ( | ||
| 32 | is => 'ro', | ||
| 33 | isa => 'Path::Class::File', | ||
| 34 | lazy => 1, | ||
| 35 | builder => '_build_target_file', | ||
| 36 | ); | ||
| 37 | |||
| 38 | has header => ( | ||
| 39 | is => 'ro', | ||
| 40 | isa => 'Str', | ||
| 41 | builder => '_build_header', | ||
| 42 | ); | ||
| 43 | |||
| 44 | requires qw( _squish ); | ||
| 45 | |||
| 46 | sub _build_header { | ||
| 47 | return q{}; | ||
| 48 | } | ||
| 49 | |||
| 50 | sub create_single_file { | ||
| 51 | my $self = shift; | ||
| 52 | |||
| 53 | my $target = $self->target_file(); | ||
| 54 | |||
| 55 | my $target_mod = -f $target ? $target->stat()->mtime() : 0; | ||
| 56 | |||
| 57 | return | ||
| 58 | unless grep { $_->stat()->mtime() >= $target_mod } | ||
| 59 | @{ $self->files() }; | ||
| 60 | |||
| 61 | my ( $fh, $tempfile ) = tempfile( UNLINK => 0 ); | ||
| 62 | |||
| 63 | print {$fh} $self->create_content(); | ||
| 64 | |||
| 65 | move( $tempfile => $target ) | ||
| 66 | or die "Cannot move $tempfile => $target: $!"; | ||
| 67 | } | ||
| 68 | |||
| 69 | sub create_content { | ||
| 70 | my $self = shift; | ||
| 71 | |||
| 72 | my $now = DateTime->now( | ||
| 73 | time_zone => 'local', | ||
| 74 | )->strftime('%Y-%m-%d %H:%M:%S.%{nanosecond} %{time_zone_long_name}'); | ||
| 75 | |||
| 76 | my $content = "/* Generated at $now */\n\n"; | ||
| 77 | |||
| 78 | my $header = $self->header(); | ||
| 79 | $content .= $header | ||
| 80 | unless string_is_empty($header); | ||
| 81 | |||
| 82 | for my $file ( @{ $self->files() } ) { | ||
| 83 | $content .= "\n\n/* $file */\n\n"; | ||
| 84 | $content .= $self->_squish( $self->_process($file) ); | ||
| 85 | } | ||
| 86 | |||
| 87 | return $content; | ||
| 88 | } | ||
| 89 | |||
| 90 | sub _process { | ||
| 91 | my $self = shift; | ||
| 92 | my $file = shift; | ||
| 93 | |||
| 94 | return scalar read_file( $file->stringify() ); | ||
| 95 | } | ||
| 96 | |||
| 97 | 1; | ||
| 98 | |||
| 99 | # ABSTRACT: Provides common behavior for combining and minifying JS or CSS | ||
| 100 | |||
| 101 | __END__ |