| 1 | #!/usr/bin/env perl | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use v5.16; | ||
| 6 | use Perl::Minify qw(minify minify_sub minify_error); | ||
| 7 | use Getopt::Long; | ||
| 8 | |||
| 9 | my $width = 0; | ||
| 10 | my $sub_name; | ||
| 11 | GetOptions( | ||
| 12 | 'width=i' => \$width, | ||
| 13 | 'sub=s' => \$sub_name, | ||
| 14 | ) or die(usage()); | ||
| 15 | |||
| 16 | ############################################################################### | ||
| 17 | ############################################################################### | ||
| 18 | |||
| 19 | # Read the sample source file | ||
| 20 | my $source_file = $ARGV[0] || ""; | ||
| 21 | |||
| 22 | if (!-r $source_file) { | ||
| 23 | die(usage()); | ||
| 24 | } | ||
| 25 | |||
| 26 | my $source = file_get_contents($source_file); | ||
| 27 | |||
| 28 | # Minify the file (or just one sub, if --sub was given) | ||
| 29 | my $opts = { shorten_vars => 1, wrap => $width }; | ||
| 30 | my $min; | ||
| 31 | if (defined $sub_name) { | ||
| 32 | $min = minify_sub($source, $sub_name, $opts); | ||
| 33 | } else { | ||
| 34 | $min = minify($source, $opts); | ||
| 35 | } | ||
| 36 | |||
| 37 | if (!defined $min) { | ||
| 38 | print STDERR minify_error(), "\n"; | ||
| 39 | exit 1; | ||
| 40 | } | ||
| 41 | |||
| 42 | print $min; | ||
| 43 | |||
| 44 | ############################################################################### | ||
| 45 | ############################################################################### | ||
| 46 | |||
| 47 | sub usage { | ||
| 48 | my $ret = "Usage: $0 script.pl [--width 80] [--sub NAME]\n"; | ||
| 49 | |||
| 50 | return $ret; | ||
| 51 | } | ||
| 52 | |||
| 53 | sub file_get_contents { | ||
| 54 | my ($file) = @_; | ||
| 55 | |||
| 56 | open(my $fh, "<", $file) or return undef; | ||
| 57 | binmode($fh, ":encoding(UTF-8)"); | ||
| 58 | |||
| 59 | local $/ = undef; # Slurp | ||
| 60 | my $ret = readline($fh); | ||
| 61 | close($fh); | ||
| 62 | |||
| 63 | return $ret; | ||
| 64 | } | ||
| 65 | |||
| 66 | # vim: tabstop=4 shiftwidth=4 noexpandtab autoindent softtabstop=4 |