lib/App/SlimPacker.pm

filter: Statementstmt 100% 89 / 89 Branchbran 92.1% 35 / 38 Conditioncond 90.0% 9 / 10 MC/DCmcdc 83.3% 5 / 6 Subroutinesub 100% 10 / 10 Podpod 100% 4 / 4 totaltotal 96.8% 152 / 157 CC 31 SCAR 18.4
CC
31
Cov
97%
plugin_search_paths
9.0
perl_switches
8.0
_use_line
7.0
CRAP 6.3
« lib/App/SlimPacker/Minify.pm ↑ Summary bin/minify »
1 package App::SlimPacker;
2 34 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 34 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 34 ▶use App::SlimPacker::Minify qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
5 process process_deps minify_file name_gen needs_space
6 module_deps collect_bundle_globals
7 rename_module_name rename_module_path
8 34 );
9 34 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 34 our $VERSION = '0.08';
11 34 our @EXPORT_OK = qw(
12 process process_deps minify_file name_gen needs_space
13 pack_string perl_switches plugin_search_paths inline_plugins
14 module_deps collect_bundle_globals
15 rename_module_name rename_module_path
16 );
17  
18 # Build a perl program from -m/-M/-e/-E switch arguments, perl-binary style.
19 # perl_switches(\@m, \@M, \@e, \@E) -> program text
20 # -m Foo -> use Foo ();
21 # -M Foo -> use Foo;
22 # -M Foo=bar,baz -> use Foo qw(bar baz);
23 # -M Foo=5.010 -> use Foo 5.010;
24 # -M 5.010 -> use 5.010;
25 # -E CODE -> use feature qw(:all); CODE
26 21 ▶sub perl_switches {
Subroutine perl_switches: called CC=8 SCAR=20.8
Pod documented
27 21 my ($m, $M, $e, $E) = @_;
28 21 ▶ $_ ||= [] for ($m, $M, $e, $E);
Condition100%2/2
$_ ||= []
l!l
7113
MC/DC100%1/1
$_ ||= []
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
29 21 my @out;
30 21 for my $arg (@$m) { push @out, _use_line($arg, 0) }
31 21 for my $arg (@$M) { push @out, _use_line($arg, 1) }
32 # perl -E enables all features; the ':all' bundle only exists from perl
33 # 5.16, so fall back to ':5.10' (say/state/switch) on older perls.
34 21 ▶ if (@$E) { push @out, q{BEGIN{require feature;eval{feature->import(':all');1}or feature->import(':5.10')}} }
Branch: 1 branch
BranchTrueFalseTotal
if (@$E) 1 20 21
35 21 ▶ if (@$e || @$E) { push @out, join("\n", @$e, @$E) }
Branch: 1 branch
BranchTrueFalseTotal
if (@$e or @$E) 3 18 21
Condition100%3/3
@$e or @$E
l!l&&r!l&&!r
2118
MC/DC100%2/2
@$e or @$E
@$e @$E
Truth table100%3/3
A or B
A= @$eB= @$E
ABresult
1X1
011
000
36 21 return join("\n", @out) . "\n";
37 }
38  
39 6 ▶sub _use_line {
Subroutine _use_line: called CC=7 SCAR=19.5
40 6 my ($arg, $with_imports) = @_;
41 6 my ($mod, $terms) = $arg =~ /^([^=\s]+)(?:=(.*))?$/;
42 6 ▶ die "bad -m/-M argument: '$arg'\n" unless defined $mod;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mod 0 6 6
43 6 ▶ $terms = '' unless defined $terms;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $terms 3 3 6
44 6 ▶ return "use $mod ();" unless $with_imports;
Branch: 1 branch
BranchTrueFalseTotal
unless $with_imports 1 5 6
45 5 ▶ return "use $mod;" unless length $terms;
Branch: 1 branch
BranchTrueFalseTotal
unless length $terms 2 3 5
46 3 my @t = split /,/, $terms;
47 3 ▶ if (@t == 1 && $t[0] =~ /^(?:\d[\d.]*|v[\d.]+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if (@t == 1 and $t[0] =~ /^(?:\d[\d.]*|v[\d.]+)$/) 1 2 3
Condition100%3/3
@t == 1 and $t[0] =~ /^(?:\d[\d.]*|v[\d.]+)$/
!ll&&!rl&&r
111
MC/DC100%2/2
@t == 1 and $t[0] =~ /^(?:\d[\d.]*|v[\d.]+)$/
@t == 1 $t[0] =~ /^(?:\d[\d.]*|v[\d.]+)$/
Truth table100%3/3
A and B
A= @t == 1B= $t[0] =~ /^(?:\d[\d.]*|v[\d.]+)$/
ABresult
0X0
100
111
48 1 return "use $mod $t[0];";
49 }
50 2 return "use $mod qw(@t);";
51 }
52  
53 # Extract the Module::Pluggable search_path(s) from a program's
54 # 'use Module::Pluggable (...)' statement. Returns a hashref of namespace => 1.
55 48 ▶sub plugin_search_paths {
Subroutine plugin_search_paths: called CC=9 SCAR=22.0
Pod documented
56 48 my ($program) = @_;
57 48 my %searched;
58 48 ▶ if ($program =~ m{\buse\s+Module::Pluggable\s*\((.*?)\)\s*;}s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($program =~ /\buse\s+Module::Pluggable\s*\((.*?)\)\s*;/s) 8 40 48
59 8 my $args = $1;
60 8 ▶ while ($args =~ m~search_path\s*=>\s*(?:(\[[^\]]*\])|("[^"]*")|('[^']*')|(q\{[^}]*\}|q\([^)]*\)|q\[[^\]]*\]|q<[^>]*>))~g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args =~ /search_path\s*=>\s*(?:(\[[^\]]*\])|("[^"]*")|('[^']*')|(q\{[^}]*\}|q\([^)]*\)|q\[[^\]]*\]|q<[^>]*>))/g) 6 8 14
61 6 my ($array, $double, $single, $q) = ($1, $2, $3, $4);
62 6 ▶ my $spec = defined $array ? $array : defined $double ? $double
Branch: 3 branches
BranchTrueFalseTotal
defined $array ? : 3 3 6
defined $double ? : 1 2 3
defined $single ? : 0 2 2
63 : defined $single ? $single : $q;
64 6 ▶ if (defined $array) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $array) { } 3 3 6
65 3 $searched{$_} = 1 for _quoted_values($array);
66 } else {
67 3 my ($v) = _quoted_values($spec);
68 3 ▶ $searched{$v} = 1 if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 3 0 3
69 }
70 }
71 }
72 48 return \%searched;
73 }
74  
75 # Pull the string contents out of any common Perl quote form.
76 6 ▶sub _quoted_values {
Subroutine _quoted_values: called CC=2 SCAR=6.9
77 6 my ($s) = @_;
78 6 my @v;
79 6 ▶ while ($s =~ m~(?:'([^']*)'|"([^"]*)"|q\{([^}]*)\}|q\(([^)]*)\)|q\[([^\]]*)\]|q<([^>]*)>)~g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ /(?:'([^']*)'|"([^"]*)"|q\{([^}]*)\}|q\(([^)]*)\)|q\[([^\]]*)\]|q<([^>]*)>)/g) 10 6 16
80 10 my @m = grep { defined } ($1, $2, $3, $4, $5, $6);
81 10 push @v, $m[0];
82 }
83 6 return @v;
84 }
85  
86 # ── Bundle / packing helpers ────────────────────────────────────────
87  
88 # Quotes that must never be run through B::perlstring()'s blunt double-quoted
89 # form. Candidate q<delim> delimiters — any punctuation would do, so we use the
90 # ones least likely to occur in code. ' and " are excluded (they re-enable
91 # escaping), \ is excluded (never a delimiter), = is excluded (q= literals
92 # break on >= => <= inside the content), and the paired brackets ( ) [ ] { } < >
93 # are excluded because Perl closes them with the *partner* (q<...> closes on >,
94 # never on <). All remaining candidates are validated safe with delimiter
95 # escaping against an adversarial corpus; see pack_string() for the cost rules.
96 # q-literal delimiter candidates. `;` is excluded: q;...; is a syntax error
97 # on perl <= 5.16 (allowed from 5.18), and bundles should run on old perls.
98 34 my @_QDELIM = ('^', '~', '|', '?', ',', '!', '#', '&', '-', '+', '*', '/', '%', ':');
99  
100 # pack_string LITERAL — shortest exact Perl string literal for arbitrary bytes.
101 # B::perlstring always emits double quotes and escapes every sigil ("\$x"),
102 # inflating the bundler's module table by ~15%. pack_string never uses
103 # perlstring; content is escaped in place inside quote literals, keeping every
104 # $ @ % " raw. Two literal families, priced per byte so the cheaper wins:
105 # '...' cost = 2 (delimiters) + \ occurrences + ' occurrences
106 # q<d>... cost = 3 (q + 2 delimiters) + \ occurrences + <d> occurrences
107 # because both families must double backslashes (q<d> collapses \\ to \ in
108 # perl — the same as single quotes do), and each must escape its own delimiter
109 # character. ' occurring in code is far more common than ^ (or any other
110 # candidate), so the q<delim> form wins once the content holds a quote, and on
111 # a tie the q form is preferred for the same reason. The delimiter with
112 # the fewest occurrences is picked — no candidate needs to be absent at all.
113 # Every form round-trips byte-for-byte; validated against a seeded random
114 # differential corpus.
115 1027 ▶sub pack_string {
Subroutine pack_string: called CC=5 SCAR=16.1
Pod documented
116 1027 my ($s) = @_;
117 1027 ▶ return "''" if $s eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $s eq "" 7 1020 1027
118 1020 my $bs = () = $s =~ /\\/g;
119 1020 my $q = () = $s =~ /'/g;
120 1020 my ($best_d, $best_occ) = (undef, length($s) + 1);
121 1020 for my $d (@_QDELIM) {
122 14280 my $occ = () = $s =~ /\Q$d\E/g;
123 14280 ▶ ($best_d, $best_occ) = ($d, $occ) if $occ < $best_occ;
Branch: 1 branch
BranchTrueFalseTotal
if $occ < $best_occ 1844 12436 14280
124 }
125 1020 ▶ if (3 + $bs + $best_occ <= 2 + $bs + $q) {
Branch: 1 branch
BranchTrueFalseTotal
if (3 + $bs + $best_occ <= 2 + $bs + $q) 642 378 1020
126 642 (my $e = $s) =~ s/\\/\\\\/g;
127 642 $e =~ s/\Q$best_d\E/\\$best_d/g;
128 642 return 'q' . $best_d . $e . $best_d;
129 }
130 378 (my $e = $s) =~ s/([\\'])/\\$1/g;
131 378 return "'$e'";
132 }
133  
134 # Inline a plugin class list into plugins() based on the Module::Pluggable
135 # search_path(s) in $program and the available $classes (Class::Name => 1).
136 # Classes are matched one level deep (Module::Pluggable's default), sorted.
137 # The 'use Module::Pluggable' statement is removed so it never loads. Programs
138 # without Module::Pluggable (or without a search_path) are returned unchanged.
139 17 ▶sub inline_plugins {
Subroutine inline_plugins: called CC=5 SCAR=16.1
Pod documented
140 17 my ($program, $classes) = @_;
141 17 ▶ $classes ||= {};
Condition50%1/2
$classes ||= {}
l!l
170
MC/DC0%0/1
$classes ||= {}
$classes
Truth table50%1/2
A
A= $classes
Aresult
11
00
142 17 my $searched = plugin_search_paths($program);
143 17 ▶ return $program unless %$searched;
Branch: 1 branch
BranchTrueFalseTotal
unless %$searched 15 2 17
144  
145 2 my @plugins;
146 2 for my $ns (sort keys %$searched) {
147 3 for my $cp (sort grep { m{^\Q$ns\E::[^:]+$} } keys %$classes) {
148 5 push @plugins, $cp;
149 }
150 }
151  
152 2 my $list = join(',', map { "\"$_\"" } @plugins);
153 my $requires = join '', map {
154 2 (my $path = $_) =~ s{::}{/}g; $path .= '.pm'; "require \"$path\";"
155 } @plugins;
156 2 $program =~ s{\buse\s+Module::Pluggable\s*\(.*?\)\s*;}{$requires}gs;
157 2 $program =~ s{plugins\(\)}{($list)}gs;
158 2 return $program;
159 }
160  
161 =head1 NAME
162  
163 App::SlimPacker - fatpack-style bundling helpers with PPI-based minification for standalone Perl scripts
164  
165 =head1 VERSION
166  
167 Version 0.08
168  
169 =head1 SYNOPSIS
170  
171 use App::SlimPacker qw(minify_file pack_string);
172  
173 # minify a module and turn it into a Perl string literal for embedding
174 my $min = minify_file('lib/My/Module.pm');
175 my $literal = pack_string($min); # 'package My::Module;...' or q^...^
176  
177 =head1 DESCRIPTION
178  
179 App::SlimPacker packs a Perl script and the non-core
180 modules it uses into a single file that runs on a plain perl, with nothing to
181 install. It minifies what it packs: comments, POD
182 and whitespace are removed, variables, subs and package names are shortened
183 consistently across the whole bundle, and the result is compressed.
184  
185 It finds the modules by compiling the script to see what it loads, and by
186 following the C<use> and C<require> statements in what it finds. It leaves
187 out core modules and copies the rest from their installed locations. Modules found with L<Module::Pluggable> are listed in
188 the bundle directly, since there is no directory to scan at runtime.
189  
190 Most users want the L<slimpack> command. This module holds the helpers it is
191 built from, and re-exports the minifier from L<App::SlimPacker::Minify>.
192  
193 =head1 EXPORTS
194  
195 Nothing by default. Import what you need:
196  
197 use App::SlimPacker qw(pack_string inline_plugins);
198  
199 =head1 FUNCTIONS
200  
201 =head2 pack_string($literal)
202  
203 Returns the shortest exact Perl string literal for an arbitrary byte string.
204 Used by the bundler to embed minified module sources, where
205 L<B::perlstring> would double-quote and escape every sigil (C<"\$x">,
206 C<"\@_">), inflating the bundle by ~15%. pack_string never uses perlstring;
207 content is escaped in place inside quote literals, keeping C<$ @ % "> raw.
208  
209 Two literal families are priced so the cheaper wins:
210  
211 =over 4
212  
213 =item *
214  
215 C<'...'> -- cost 2 (delimiters) + backslash occurrences + single-quote
216 occurrences, since both C<'> and C<\> must be escaped;
217  
218 =item *
219  
220 a C<q<delim>> literal -- delimiter chosen from C<^ ~ | ? , ! # & - + * / % :>,
221 the candidate occurring fewest times in the content. Cost 3 + backslash
222 occurrences + delimiter occurrences, since backslashes and the delimiter
223 character must be escaped. C<=> is excluded (a C<q=...=> literal breaks when
224 the content contains a comparison like C< >= >), as are C<< < >> and C<< > >>
225 (paired delimiters already close on C<< > >>, so C<q<< ... >> > cannot nest);
226 every candidate above is validated safe with escaping.
227  
228 =back
229  
230 C<'> occurs far more often in code than C<^> or any other candidate, so the
231 q<delim> form wins as soon as the content holds a quote, and wins ties for the
232 same reason. No candidate needs to be absent: its occurrences are simply
233 escaped (C<\^>). The returned literal always C<eval>s back to the exact
234 input bytes.
235  
236 =head2 plugin_search_paths($program)
237  
238 Extracts C<Module::Pluggable> search paths from a program's
239 C<use Module::Pluggable (...)> statement. Returns a hashref of
240 C<< namespace => 1 >>.
241  
242 =head2 inline_plugins($program, \%classes)
243  
244 Inlines a plugin class list into C<plugins()> calls based on the
245 C<Module::Pluggable> search paths in C<$program> and the available classes
246 (hashref of C<< Class::Name => 1 >>). Classes are matched one level deep
247 (Module::Pluggable's default), sorted. The C<use Module::Pluggable> statement
248 is removed so it never loads at runtime.
249  
250 Returns the modified program text. Programs without C<Module::Pluggable> or
251 without a C<search_path> are returned unchanged.
252  
253 =head2 perl_switches(\@m, \@M, \@e, \@E)
254  
255 Builds a Perl program string from C<-m>/C<-M>/C<-e>/C<-E> switch arguments
256 (perl-binary style). Returns the program text with appropriate C<use>
257 statements prepended.
258  
259 =head1 AUTHOR
260  
261 Nicolas Mendoza, C<< <mendoza at pvv.ntnu.no> >>
262  
263 =head1 LICENSE AND COPYRIGHT
264  
265 This software is licensed under the Artistic License 2.0. See the F<LICENSE>
266 file in this distribution for the full text.
267  
268 =head1 SEE ALSO
269  
270 L<App::SlimPacker::Minify>, L<slimpack>, L<PPI>, L<App::FatPacker>
271  
272 =cut
273  
274 34 1;
« lib/App/SlimPacker/Minify.pm ↑ Summary bin/minify »