| 1 | #!/usr/bin/perl |
| 2 | use v5.14; |
| 3 | use warnings; |
| 4 | |
| 5 | use CSS::Minifier::XS qw/minify/; |
| 6 | use Digest::SHA qw/sha256_base64/; |
| 7 | use IO::Compress::Gzip qw/gzip/; |
| 8 | use File::Slurp qw/read_file write_file edit_file_lines/; |
| 9 | use List::Util qw/first/; |
| 10 | |
| 11 | mkdir 'static'; |
| 12 | mkdir 'static/css'; |
| 13 | mkdir 'static/js'; |
| 14 | |
| 15 | sub gzip_file { |
| 16 | my ($file) = @_; |
| 17 | gzip $file => "$file.gz", -Level => 9, Minimal => 1; |
| 18 | } |
| 19 | |
| 20 | sub read_css_into_blocks { |
| 21 | my ($file) = @_; |
| 22 | my (@blocks, $block); |
| 23 | for (read_file $file) { |
| 24 | $block .= $_; |
| 25 | if (/^}/) { |
| 26 | push @blocks, $block; |
| 27 | $block = ''; |
| 28 | } |
| 29 | } |
| 30 | \@blocks |
| 31 | } |
| 32 | |
| 33 | sub make_css { |
| 34 | my %css; |
| 35 | $css{common} .= read_file $_ for <css/*.css>; |
| 36 | |
| 37 | my (%themes, $rndtheme); |
| 38 | for (<css/themes/*>) { |
| 39 | ($rndtheme) = m,themes/(.*)\.css,; |
| 40 | $themes{$rndtheme} = read_css_into_blocks $_; |
| 41 | } |
| 42 | |
| 43 | while (grep { scalar @$_ } values %themes) { |
| 44 | my %blocks = map { $_ => (shift @{$themes{$_}}) // '' } keys %themes; |
| 45 | if (grep { $_ ne $blocks{$rndtheme} } values %blocks) { |
| 46 | $css{$_} .= $blocks{$_} for keys %themes; |
| 47 | } else { |
| 48 | $css{common} .= $blocks{$rndtheme}; |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | for my $name (keys %css) { |
| 53 | write_file "static/css/$name.css", minify $css{$name}; |
| 54 | gzip_file "static/css/$name.css" |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | sub make_js { |
| 59 | system java => -jar => 'compiler.jar', qw,-O SIMPLE --create_source_map static/js/js.map --js_output_file static/js/all.js --language_in ECMASCRIPT6_STRICT --language_out ECMASCRIPT5_STRICT --source_map_location_mapping js/|/static/js/,, <js/*>; |
| 60 | my $js = read_file 'static/js/all.js'; |
| 61 | write_file 'static/js/all.js', '//# sourceMappingURL=/static/js/js.map', "\n", $js; |
| 62 | system 'cp', '-rp', 'js', 'static/'; |
| 63 | gzip_file 'static/js/all.js'; |
| 64 | } |
| 65 | |
| 66 | my $css_mtime = -M 'static/css/slate.css' // 0; |
| 67 | for (<css/*>, <css/themes/*>) { |
| 68 | if (!$css_mtime || $css_mtime > -M) { |
| 69 | make_css; |
| 70 | last |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | my $js_mtime = -M 'static/js/all.js' // 0; |
| 75 | for (<js/*>) { |
| 76 | if (!$js_mtime || $js_mtime > -M) { |
| 77 | make_js; |
| 78 | last |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | edit_file_lines { |
| 83 | my ($file) = m,(static.*\.(?:css|js)),; |
| 84 | return unless $file; |
| 85 | my $hash = sha256_base64 scalar read_file $file; |
| 86 | s/integrity=".*"/integrity="sha256-$hash="/; |
| 87 | } 'tmpl/skel.en' |