lib/App/makefilepl2cpanfile.pm

filter: Statementstmt 100% 273 / 273 Branchbran 100% 112 / 112 Conditioncond 96.4% 81 / 84 MC/DCmcdc 85.1% 40 / 47 Subroutinesub 100% 27 / 27 Podpod 100% 3 / 3 totaltotal 98.1% 536 / 546 CC 103 SCAR 23.3
CC
103
Cov
99%
generate
19.0
_load_develop_config
17.0
parse_prereqs
16.0
CRAP 10.3
↑ Summary bin/makefilepl2cpanfile »
1 package App::makefilepl2cpanfile;
2  
3 89 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 89 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 # Nothing is imported: every external function is called by its full name,
6 # so the only subroutines in this package are its own. (Importing put
7 # Load, Dump, home, path, croak, carp and Readonly into the namespace.)
8 89 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 89 ▶use Readonly ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 89 ▶use Path::Tiny ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 89 ▶use Params::Get ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 88 ▶use YAML::Tiny ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 87 ▶use File::HomeDir ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 86 ▶use Fcntl ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 =head1 NAME
17  
18 App::makefilepl2cpanfile - Convert Makefile.PL to a cpanfile automatically
19  
20 =head1 VERSION
21  
22 This document describes App::makefilepl2cpanfile version 0.07.
23  
24 =cut
25  
26 86 our $VERSION = '0.07';
27  
28 # -----------------------------------------------------------------------
29 # Constants
30 # -----------------------------------------------------------------------
31  
32 # Default author/developer tools added to the 'develop' phase when
33 # with_develop is true and no user config file overrides them.
34 154 Readonly::Hash my %DEFAULT_DEVELOP => (
35 'Devel::Cover' => 0,
36 'Perl::Critic' => 0,
37 'Test::Pod' => 0,
38 'Test::Pod::Coverage' => 0,
39 );
40  
41 # Maps each Makefile.PL simple-dependency key to its cpanfile phase name.
42 # All of these are treated as 'requires' relationships.
43 86 Readonly::Hash my %PHASE_MAP => (
44 BUILD_REQUIRES => 'build',
45 CONFIGURE_REQUIRES => 'configure',
46 PREREQ_PM => 'runtime',
47 TEST_REQUIRES => 'test',
48 );
49  
50 # Valid cpanfile phase names recognised inside 'prereqs => { ... }' blocks.
51 137 Readonly::Hash my %VALID_PHASE => map { $_ => 1 }
52 qw(runtime configure build test develop);
53  
54 # Valid cpanfile relationship keywords inside each phase block.
55 86 Readonly::Hash my %VALID_REL => map { $_ => 1 }
56 qw(requires recommends suggests conflicts);
57  
58 # Canonical emit order for non-runtime phases (runtime is special-cased at
59 # the top level per cpanfile convention).
60 86 Readonly::Array my @PHASE_ORDER => qw(configure build test develop);
61  
62 # Within each phase block, emit relationships in this order.
63 86 Readonly::Array my @REL_ORDER => qw(requires recommends suggests conflicts);
64  
65 # META spec 1.x top-level keys (e.g. directly under META_MERGE) and the
66 # phase and relationship each one stands for.
67 86 Readonly::Hash my %LEGACY_KEY => (
68 requires => [ 'runtime', 'requires' ],
69 build_requires => [ 'build', 'requires' ],
70 configure_requires => [ 'configure', 'requires' ],
71 recommends => [ 'runtime', 'recommends' ],
72 suggests => [ 'runtime', 'suggests' ],
73 conflicts => [ 'runtime', 'conflicts' ],
74 );
75  
76 # First line of every generated cpanfile.
77 86 Readonly::Scalar my $HEADER => '# Generated from Makefile.PL using makefilepl2cpanfile';
78  
79 # A CPAN module name: ASCII only (as PAUSE requires), so look-alike
80 # characters from other scripts cannot smuggle in a different module.
81 # Possessive quantifiers: no backtracking on hostile input.
82 86 Readonly::Scalar my $MODULE_NAME_RE => qr/
83 \A
84 [A-Za-z_] \w*+ # first part: letter or '_', then word characters
85 (?: :: \w++ )*+ # further parts, each after '::'
86 \z
87 /xa;
88  
89 # The whole value after '=>': a single- or double-quoted string, or a bare
90 # token. The complete token is captured so that it is validated as a
91 # unit - capturing only a numeric prefix would turn '1e3' into '1'.
92 86 Readonly::Scalar my $VALUE_TOKEN_RE => qr/
93 (?:
94 ' ([^'\n]*+) ' # $1: single-quoted
95 | " ([^"\n]*+) " # $2: double-quoted
96 | ([^\s,}\#'"]++) # $3: bare token, up to a separator
97 )
98 /x;
99  
100 # One dependency entry: a quoted module name (quotes must match), '=>',
101 # then an optional value token. Compiled once here: interpolating
102 # $VALUE_TOKEN_RE inside the per-line loop made Perl re-check the pattern
103 # on every line.
104 86 Readonly::Scalar my $PAIR_RE => qr/
105 (?:
106 ' ([^'\n]++) ' # $1: single-quoted name
107 | " ([^"\n]++) " # $2: double-quoted name (quotes must match)
108 )
109 \s* => \s*
110 $VALUE_TOKEN_RE? # $3-$5: the value, if any
111 /x;
112  
113 # A version number: optional 'v', ASCII digits, '.' and '_', at least one
114 # digit. The lookahead finds a digit lazily and the main match is
115 # possessive, so the check is linear even on long hostile strings.
116 86 Readonly::Scalar my $VERSION_RE => qr/
117 \A
118 v?+ # optional leading 'v'
119 (?= [0-9._]*? [0-9] ) # at least one digit (found lazily: linear)
120 [0-9._]++ # nothing but digits, '.' and '_'
121 \z
122 /x;
123  
124 # A version requirement: a single version (as above), or a CPAN::Meta
125 # version range - comma-separated versions each with a comparison operator,
126 # e.g. '>= 1.2, < 2.0'. Only digits, '.', '_', 'v', the operators, ',' and
127 # spaces can match, so a requirement can never close the quoted literal it
128 # is written into. Every quantifier is possessive: linear on any input.
129 86 Readonly::Scalar my $REQUIREMENT_RE => qr/
130 \A
131 (?: (?: >= | <= | == | != | > | < ) \s*+ )?+ # optional operator
132 v?+ (?= [0-9._]*? [0-9] ) [0-9._]++ # a version
133 (?:
134 \s*+ , \s*+
135 (?: >= | <= | == | != | > | < ) \s*+ # further parts need an operator
136 v?+ (?= [0-9._]*? [0-9] ) [0-9._]++
137 )*+
138 \z # no space before or after the whole value
139 /x;
140  
141 # Everything on a line up to and including its first '#' that is not
142 # inside a quoted string. A quote with no partner is taken as a plain
143 # character, exactly as a left-to-right scan for quoted strings would.
144 86 Readonly::Scalar my $TO_COMMENT_RE => qr/
145 \A
146 (?:
147 [^'"\#]++ # ordinary text
148 | ' [^']*+ ' # a single-quoted string (may contain '#')
149 | " [^"]*+ " # a double-quoted string (may contain '#')
150 | ['"] # a quote with no partner: an ordinary character
151 )*+
152 \# # the first '#' outside quotes
153 /x;
154  
155 # The four simple keys, for a single pass over the content.
156 86 Readonly::Scalar my $SIMPLE_KEY_RE => qr/
157 (?: BUILD_REQUIRES | CONFIGURE_REQUIRES | PREREQ_PM | TEST_REQUIRES )
158 /x;
159  
160 # Openers of dependency blocks: each captures its key in $1 and ends with
161 # the '{', whose block _blocks() then takes from the matching-brace table.
162 86 Readonly::Scalar my $SIMPLE_OPEN_RE => qr/ \b ($SIMPLE_KEY_RE) ['"]? \s*+ => \s*+ \{ /x;
163 86 Readonly::Scalar my $PREREQS_OPEN_RE => qr/ \b (prereqs) ['"]? \s*+ => \s*+ \{ /x;
164 # A child of a prereqs or phase block: a phase or relationship name.
165 86 Readonly::Scalar my $CHILD_OPEN_RE => qr/ \b (\w++) ['"]? \s*+ => \s*+ \{ /x;
166 # The META spec 1.x top-level keys of %LEGACY_KEY, optionally quoted.
167 86 Readonly::Scalar my $LEGACY_OPEN_RE => qr/
168 \b ( requires | build_requires | configure_requires | recommends | suggests | conflicts )
169 ['"]? \s*+ => \s*+ \{
170 /x;
171  
172 # The text of a comment without its outer whitespace: runs of whitespace
173 # each followed by non-whitespace, taken possessively, so trailing
174 # whitespace is left out without being rescanned. (The usual
175 # s{\s+\z}{} and (.*\S) forms retry from every position inside a long
176 # whitespace run and are quadratic in its length.)
177 86 Readonly::Scalar my $TRIMMED_RE => qr/
178 \s*+ # leading whitespace, skipped
179 ( (?: \s*+ \S++ )++ ) # $1: from the first to the last non-space
180 /x;
181  
182 # The opening of a develop block in an existing cpanfile.
183 86 Readonly::Scalar my $DEVELOP_OPEN_RE => qr/
184 on \s+ ["']develop["'] \s* => \s* sub \s* \{
185 /x;
186  
187 # One entry of a develop block: relationship keyword, quoted module name,
188 # optional quoted version. Quotes must match on both.
189 69 Readonly::Scalar my $DEVELOP_ENTRY_RE => qr/
190 \b (requires|recommends|suggests|conflicts) \s+ # $1: relationship
191 (?: ' ([^'\n]++) ' | " ([^"\n]++) " ) # $2 or $3: module name
192 (?:
193 \s* , \s*
194 (?: ' ([^'\n]*+) ' | " ([^"\n]*+) " ) # $4 or $5: version
195 )?
196 /x;
197  
198 # Characters stripped from comments before they are written out: C0/C1
199 # controls other than TAB (a CR can visually overwrite a line) and the
200 # Unicode bidirectional controls used by "Trojan Source" (CVE-2021-42574)
201 # to make text display differently from how it is read.
202 69 Readonly::Scalar my $UNSAFE_COMMENT_CHARS_RE =>
203 qr/[\x00-\x08\x0A-\x1F\x7F-\x9F\x{061C}\x{200E}\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}]/x;
204  
205 =head1 SYNOPSIS
206  
207 Create or refresh the F<cpanfile> of the project in the current directory:
208  
209 use App::makefilepl2cpanfile;
210 use Path::Tiny;
211  
212 my $text = App::makefilepl2cpanfile::generate();
213 path('cpanfile')->spew_utf8($text);
214  
215 Keep the hand-written C<develop> section of an existing F<cpanfile>:
216  
217 my $old = path('cpanfile')->slurp_utf8;
218 my $text = App::makefilepl2cpanfile::generate(existing => $old);
219 path('cpanfile')->spew_utf8($text);
220  
221 Make a F<cpanfile> for another project, with no developer tools added.
222 The result is the same on every computer, which is useful in CI:
223  
224 my $text = App::makefilepl2cpanfile::generate({
225 makefile => '/path/to/other/project/Makefile.PL',
226 with_develop => 0,
227 });
228  
229 List every dependency without making a F<cpanfile>:
230  
231 my $deps = App::makefilepl2cpanfile::parse_prereqs(
232 path('Makefile.PL')->slurp_utf8
233 );
234 for my $phase (sort keys %{$deps}) {
235 for my $rel (sort keys %{ $deps->{$phase} }) {
236 for my $module (sort keys %{ $deps->{$phase}{$rel} }) {
237 print "$phase $rel $module\n";
238 }
239 }
240 }
241  
242 Check in a test that the committed F<cpanfile> is up to date:
243  
244 use Test::More;
245 is(
246 App::makefilepl2cpanfile::generate(existing => path('cpanfile')->slurp_utf8),
247 path('cpanfile')->slurp_utf8,
248 'cpanfile matches Makefile.PL',
249 );
250  
251 From the command line (see L<makefilepl2cpanfile>):
252  
253 makefilepl2cpanfile # write ./cpanfile
254 makefilepl2cpanfile --dry-run # print it instead
255 makefilepl2cpanfile --diff # show what would change
256  
257 =head1 DESCRIPTION
258  
259 A Perl distribution lists the modules it needs in its F<Makefile.PL>.
260 Many tools (for example C<cpanm --installdeps .> and CI systems) prefer
261 a F<cpanfile> instead. This module reads a F<Makefile.PL> and writes the
262 same list in F<cpanfile> form, so you only keep the list in one place.
263  
264 The F<Makefile.PL> is B<never run>. It is read as plain text and
265 searched for the parts that list dependencies. This makes the tool safe
266 to use on code you do not trust, but it also means that it cannot see
267 dependencies that are computed while the program runs (see
268 L</COMMON PITFALLS>).
269  
270 Reading takes time in proportion to the size of the input, however it is
271 written, so a hostile F<Makefile.PL> or F<cpanfile> (for example one with
272 thousands of unclosed braces) cannot make the tool hang.
273  
274 =head2 What it reads
275  
276 =over 4
277  
278 =item * C<PREREQ_PM>, C<BUILD_REQUIRES>, C<TEST_REQUIRES> and
279 C<CONFIGURE_REQUIRES>. The key may be bare or in single or double quotes
280 (C<'PREREQ_PM' =E<gt> { ... }>), and the same goes for C<prereqs>, its
281 phase and relationship names, and C<MIN_PERL_VERSION>. These become C<requires> lines in the C<runtime>,
282 C<build>, C<test> and C<configure> phases.
283  
284 =item * C<prereqs =E<gt> { PHASE =E<gt> { RELATIONSHIP =E<gt> { ... } } }>
285 blocks (the CPAN::Meta::Spec version 2 layout), wherever they appear -
286 also inside C<META_MERGE>.
287  
288 =item * The older version 1 layout, directly inside C<META_MERGE>:
289 C<requires>, C<recommends>, C<suggests> and C<conflicts> become lines of
290 that kind in the C<runtime> phase; C<build_requires> and
291 C<configure_requires> become C<requires> lines in the C<build> and
292 C<configure> phases.
293  
294 =item * C<MIN_PERL_VERSION>, which becomes C<requires 'perl', 'VERSION';>.
295  
296 =item * A C<#> comment after an entry. It is copied to the F<cpanfile>.
297  
298 =back
299  
300 =head2 What it writes
301  
302 # Generated from Makefile.PL using makefilepl2cpanfile
303  
304 requires 'perl', '5.010';
305  
306 requires 'Moo', '2.000'; # object system
307 requires 'Try::Tiny';
308 recommends 'JSON::MaybeXS';
309  
310 on 'test' => sub {
311 requires 'Test::More', '0.98';
312 };
313  
314 on 'develop' => sub {
315 requires 'Perl::Critic';
316 };
317  
318 Runtime dependencies come first, without an C<on> block. The other
319 phases follow in this order: C<configure>, C<build>, C<test>, C<develop>.
320 Inside each phase, C<requires> lines come first, then C<recommends>, then
321 C<suggests>, and the modules are in alphabetical order. The same input
322 always gives exactly the same output.
323  
324 =head1 CONFIGURATION
325  
326 When C<with_develop> is true (the default), some developer tools are
327 added to the C<develop> phase. By default these are L<Devel::Cover>,
328 L<Perl::Critic>, L<Test::Pod> and L<Test::Pod::Coverage>.
329  
330 To choose your own list, create the file
331 F<~/.config/makefilepl2cpanfile.yml>:
332  
333 develop:
334 Perl::Critic: 0
335 Devel::Cover: 0
336 My::Extra::Tool: '1.00'
337  
338 The number after each name is the minimum version; C<0> means "any
339 version". Your list B<replaces> the default list; it is not added to it.
340 Names that are not valid module names, and versions that are not version
341 numbers, are ignored with a warning, so a mistake in this file can never
342 put unexpected code into your F<cpanfile>.
343  
344 =head1 DATA STRUCTURE
345  
346 C<parse_prereqs()> returns a hash reference with three levels:
347  
348 {
349 PHASE => {
350 RELATIONSHIP => {
351 'Module::Name' => { version => '1.0', comment => 'why it is needed' },
352 },
353 },
354 }
355  
356 =over 4
357  
358 =item * PHASE is one of C<runtime>, C<configure>, C<build>, C<test> or
359 C<develop>.
360  
361 =item * RELATIONSHIP is one of C<requires>, C<recommends>, C<suggests> or
362 C<conflicts>.
363  
364 =item * C<version> is the version requirement exactly as it was written:
365 a single version (C<'1.60'> stays C<'1.60'>) or a version range such as
366 C<'E<gt>= 1.2, E<lt> 2.0'>. It is C<0> when there is no requirement.
367  
368 =item * C<comment> is the text of the C<#> comment after the entry, or
369 C<undef> when there is none.
370  
371 =back
372  
373 A phase or relationship with no modules is not present at all.
374  
375 =head1 ENCODING
376  
377 =over 4
378  
379 =item * B<The Makefile.PL file> is read as UTF-8. Comments may contain
380 any printable Unicode text, including accented letters, emoji and
381 combining marks; they are copied to the output unchanged. Control
382 characters (other than TAB) and Unicode direction-override characters
383 are removed from comments, so that the generated file cannot be made to
384 look different from what it really contains. If the file is not valid UTF-8 you get a
385 warning and processing continues (see L</generate(%args)>).
386  
387 =item * B<The returned cpanfile text> is a Perl character string. Write
388 it with a UTF-8 output layer, for example C<path(...)-E<gt>spew_utf8> or
389 C<binmode $fh, ':encoding(UTF-8)'>. Otherwise Perl warns
390 "Wide character in print" when a comment contains non-ASCII text.
391  
392 =item * B<The existing argument> and B<the content argument of
393 parse_prereqs()> must be character strings: decode them first (for
394 example with C<slurp_utf8>). Raw bytes work for plain ASCII, but a
395 non-ASCII comment would come back as separate bytes.
396  
397 =item * B<Module names> must be plain ASCII (A-Z, a-z, 0-9, C<_> and
398 C<::>), as CPAN requires. A name with any other character is ignored.
399 This also stops look-alike names, such as C<Test::More> written with a
400 Cyrillic letter.
401  
402 =item * B<Version numbers> may use only the ASCII digits 0-9, C<.>,
403 C<_> and a leading C<v>, and must contain at least one digit. A version
404 range joins such numbers, each after one of the operators C<E<gt>=>,
405 C<E<lt>=>, C<==>, C<!=>, C<E<gt>> or C<E<lt>>, with commas. The whole
406 value is checked: C<'1.0-TRIAL'> is not shortened to C<'1.0'>. Anything
407 else is treated as "no minimum version".
408  
409 =item * B<The YAML configuration file> is read as UTF-8; the same rules
410 for names and versions apply.
411  
412 =item * B<File names> are passed to the operating system unchanged.
413 Names with spaces, non-ASCII letters or shell characters such as C<;>
414 and C<|> are safe: no shell is ever used.
415  
416 =back
417  
418 =head1 METHODS
419  
420 =head2 generate(%args)
421  
422 =head3 PURPOSE
423  
424 Reads a F<Makefile.PL> and returns the text of a matching F<cpanfile>.
425 The F<Makefile.PL> is read as text and is never run.
426  
427 =head3 ARGUMENTS
428  
429 Give the arguments as a list of name/value pairs, or as one hash
430 reference. All of them are optional.
431  
432 =over 4
433  
434 =item * C<content> - the text of a F<Makefile.PL>, for example from
435 L</read_makefile($path)>. When it is given it is used as it is, and
436 C<makefile> is ignored and nothing is read. Use it to read the file once
437 and use the same text for more than one purpose.
438  
439 =item * C<makefile> - the path of the F<Makefile.PL> to read. Default:
440 C<'Makefile.PL'> in the current directory. Anything that turns into a
441 path when used as a string is accepted, such as a L<Path::Tiny> object.
442 A filehandle or another kind of reference is refused with
443 C<Cannot read>.
444  
445 =item * C<existing> - the text of your current F<cpanfile>. Default:
446 C<''> (none). Only its C<on 'develop' =E<gt> sub { ... }> section is
447 used. Every C<requires>, C<recommends>, C<suggests> and C<conflicts>
448 line in that section is copied to the new text, so your hand-written developer
449 dependencies are kept. Lines that are commented out are not copied.
450 An entry whose name is not a valid module name is dropped. An entry
451 whose version is not a version number or version range is kept without a
452 version, and you get a warning.
453  
454 =item * C<with_develop> - true or false. Default: true. When true, the
455 developer tools from the configuration file (see L</CONFIGURATION>), or
456 the default tools, are added to the C<develop> phase as C<requires>. A
457 tool that is already in the develop phase, from the F<Makefile.PL> or
458 from C<existing>, is left exactly as it is.
459  
460 =back
461  
462 =head3 RETURNS
463  
464 A string: the complete F<cpanfile>. It always starts with the line
465 C<# Generated from Makefile.PL using makefilepl2cpanfile> and always ends
466 with exactly one newline. The layout is described in
467 L</What it writes>. A F<Makefile.PL> with no dependencies gives just
468 the first line.
469  
470 =head3 SIDE EFFECTS
471  
472 =over 4
473  
474 =item * Reads the C<makefile> file.
475  
476 =item * When C<with_develop> is true, reads
477 F<~/.config/makefilepl2cpanfile.yml> if it exists.
478  
479 =item * Never writes, creates or deletes any file.
480  
481 =item * May print warnings (see MESSAGES below).
482  
483 =item * Does not change the caller's C<$@>, C<$!> or C<$_>.
484  
485 =back
486  
487 =head3 USAGE EXAMPLE
488  
489 use App::makefilepl2cpanfile;
490 use Path::Tiny;
491  
492 my $cpanfile = path('cpanfile');
493 my $text = App::makefilepl2cpanfile::generate(
494 makefile => 'Makefile.PL',
495 existing => $cpanfile->exists ? $cpanfile->slurp_utf8 : '',
496 with_develop => 1,
497 );
498 $cpanfile->spew_utf8($text);
499  
500 =head3 HOW IT WORKS
501  
502 =over 4
503  
504 =item 1. Check that C<makefile> is a readable, regular file.
505  
506 =item 2. Read it as UTF-8. If that fails because of bad UTF-8, warn and
507 read the raw bytes instead. Any other read error is passed on.
508  
509 =item 3. Find C<MIN_PERL_VERSION> and call L</parse_prereqs($content)>.
510  
511 =item 4. Copy the develop entries from C<existing>, without replacing
512 entries that came from the F<Makefile.PL>.
513  
514 =item 5. If C<with_develop> is true, add each configured tool that is
515 not already in the develop phase.
516  
517 =item 6. Format and return the text.
518  
519 =back
520  
521 =head3 API SPECIFICATION
522  
523 =head4 Input
524  
525 {
526 content => {
527 type => 'string',
528 optional => 1,
529 },
530 makefile => {
531 type => 'string',
532 optional => 1,
533 min => 1,
534 default => 'Makefile.PL',
535 },
536 existing => {
537 type => 'string',
538 optional => 1,
539 default => '',
540 },
541 with_develop => {
542 type => 'boolean',
543 optional => 1,
544 default => 1,
545 },
546 }
547  
548 =head4 Output
549  
550 {
551 type => 'string',
552 matches => qr/\A# Generated from Makefile\.PL using makefilepl2cpanfile\n.*(?<!\n)\n\z/s,
553 }
554  
555 =head4 Domains
556  
557 Each argument, split into groups of values that behave the same way.
558 "Refused" means the call dies with C<Cannot read '...'>.
559  
560 makefile
561 valid: a readable regular file, given as a relative path, an
562 absolute path, or an object that stringifies to one
563 (e.g. Path::Tiny). Any characters the file system allows,
564 including spaces, non-ASCII letters and shell characters.
565 default: undef or not given -> 'Makefile.PL'
566 refused: '' and '0' (unless such a file exists), a missing file,
567 a directory, a device, a FIFO, a symlink loop, a file
568 without read permission, any reference (filehandle, glob,
569 array, hash, code)
570 limits: a file name component up to the file system's NAME_MAX
571 (usually 255 bytes) is accepted; one byte more is refused.
572 File size: 0 bytes gives just the header line; there is
573 no upper limit other than memory.
574  
575 content
576 given: used as the Makefile.PL text; makefile is then ignored
577 and no file is read (so no "Cannot read" is possible)
578 default: undef or not given -> the makefile file is read
579  
580 existing
581 valid: any string. Only the first on 'develop' => sub { ... };
582 block is used; its closing "};" must start a line (after
583 optional spaces or tabs). 'develop' or "develop".
584 default: undef or not given -> ''
585 ignored: a string without a develop block, a block that is never
586 closed, a reference (its "HASH(0x...)" text has no block)
587 entries: 0 or more; each needs a valid module name; a version, if
588 given, must be a version or version range (see
589 parse_prereqs)
590  
591 with_develop
592 true: any true Perl value, including 'yes' and '0.0'
593 false: 0, '0', ''
594 default: undef or not given -> true
595  
596 combinations
597 - with_develop false does not stop the existing develop block from
598 being kept; it only stops tools being added.
599 - An empty Makefile.PL with an existing develop block gives the
600 header plus that develop block.
601 - A configuration file with an empty "develop: {}" adds no tools.
602  
603 =head3 MESSAGES
604  
605 Values taken from files or the environment (paths, module names,
606 versions, parser errors) are shown with control characters and Unicode
607 direction-override characters replaced by C<\x{..}> escapes, so a
608 hostile file cannot use a message to send escape sequences to your
609 terminal.
610  
611 Errors (the call dies):
612  
613 Cannot read '$makefile'
614 The path does not exist, is not a regular file (for example a
615 directory, a device or a FIFO), cannot be read, or is not a path
616 at all (for example a filehandle).
617 What to do: check the path and its permissions.
618  
619 Failed to parse $cfg_file: $error
620 The configuration file exists but contains invalid YAML, cannot be
621 read, or its location cannot be checked (for example "Permission
622 denied"). A missing file, or something that is not a regular
623 file, is simply treated as "no configuration".
624 What to do: fix the YAML or the permissions, or delete the file.
625  
626 (any other error while reading the Makefile.PL)
627 A real read error, such as a disk failure, is passed on unchanged.
628  
629 Warnings (processing continues):
630  
631 Warning: '$makefile' contains invalid UTF-8; reading as raw bytes: $error
632 The file is not valid UTF-8. Its raw bytes are used instead.
633 Note: depending on which optional UTF-8 modules are installed
634 (Unicode::UTF8, PerlIO::utf8_strict), Path::Tiny may instead
635 decode the file leniently and print its own warning. Either way
636 you get a warning, not an error.
637 What to do: save the Makefile.PL as UTF-8.
638  
639 Ignoring invalid version for '$module' in existing cpanfile: '$version'
640 A develop entry in the existing cpanfile has a version that is
641 not a version number. The entry is kept with no version, so the
642 bad value cannot change the meaning of the new cpanfile.
643  
644 No 'develop' key found in $cfg_file; using defaults
645 The configuration file has no develop: section.
646 What to do: add one, or delete the file.
647  
648 Skipping invalid module name in $cfg_file: '$module'
649 A name in the develop: section is not a valid module name. It is
650 ignored.
651  
652 Skipping invalid version for '$module' in $cfg_file: '$version'
653 A version in the develop: section is not a version number. The
654 module is kept with no minimum version.
655  
656 =cut
657  
658 617 ▶sub generate {
Subroutine generate: called CC=19 SCAR=29.4
Pod documented
659 # Accept both flat hash and single-hashref calling styles.
660 615 my $args = Params::Get::get_params(undef, \@_);
661  
662 # File tests and the reads below (including the config file) change
663 # errno; restore the caller's $! on every exit path.
664 615 local $! = 0;
665  
666 513 ▶ my $existing = $args->{existing} // '';
Condition100%2/2
$args->{"existing"} // ""
l!l
190425
MC/DC100%1/1
$args->{"existing"} // ""
$args->{"existing"}
Truth table100%2/2
A
A= $args->{"existing"}
Aresult
11
00
667 513 ▶ my $with_dev = $args->{with_develop} // 1;
Condition100%2/2
$args->{"with_develop"} // 1
l!l
401214
MC/DC100%1/1
$args->{"with_develop"} // 1
$args->{"with_develop"}
Truth table100%2/2
A
A= $args->{"with_develop"}
Aresult
11
00
668  
669 # Text supplied directly is used as it is; otherwise read the file.
670 513 ▶ my $content = defined $args->{content} ? $args->{content} : read_makefile($args->{makefile});
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'content'} ? : 62 553 615
671 148 my $min_perl = _parse_min_perl($content);
672 148 my $deps = parse_prereqs($content);
673  
674 # Merge the develop block from a pre-existing cpanfile so that
675 # hand-curated entries (all relationship types) survive regeneration.
676 #
677 # Two linear steps instead of one /(.*?)^};/ms match: that lazy match
678 # re-scanned to the end of the string from every unclosed opener, which
679 # is quadratic. Premise: any closing line after a later opener is also
680 # after the first. Conclusion: only the first opener needs trying.
681 # The closing '};' must start a line, so a '};' inside an inline
682 # comment does not end the block early.
683 143 ▶ if ($existing =~ /$DEVELOP_OPEN_RE/gx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($existing =~ /$DEVELOP_OPEN_RE/gx) 97 416 513
684 92 my $open_end = pos $existing;
685 92 ▶ if ($existing =~ /^[ \t]*\};/mgx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($existing =~ /^[ \t]*\};/gmx) 92 5 97
686 2142 my $dev_block = substr $existing, $open_end, $-[0] - $open_end;
687  
688 # A commented-out line is not an entry. '#' cannot occur in a
689 # valid module name or version, so stripping to end of line is safe.
690 2142 $dev_block =~ s/\#[^\n]*+//gx;
691  
692 2134 ▶ while ($dev_block =~ /$DEVELOP_ENTRY_RE/gx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dev_block =~ /$DEVELOP_ENTRY_RE/gx) 2161 92 2253
693 # Save immediately: the validation regexes below would reset
694 # the capture variables.
695 66 ▶ my ($rel, $mod, $ver) = ($1, $2 // $3, $4 // $5);
Condition100%6/6
$2 // $3
l!l&&r!l&&!r
215821
$4 // $5
l!l&&r!l&&!r
94422025
MC/DC100%2/2
$2 // $3
$2 $3
MC/DC100%2/2
$4 // $5
$4 $5
Truth table100%3/3
A // B
A= $2B= $3
ABresult
1X1
011
000
Truth table100%3/3
A // B
A= $4B= $5
ABresult
1X1
011
000
696 66 ▶ next unless $mod =~ $MODULE_NAME_RE;
Branch: 1 branch
BranchTrueFalseTotal
unless $mod =~ /$MODULE_NAME_RE/ 8 2153 2161
697 # SECURITY: the version is written back inside a single-quoted
698 # literal; a value such as '\' would escape the closing quote and
699 # turn following entries into executable code.
700 # length(undef) is undef, so one test covers "absent" and "empty":
701 # only a non-empty version can be invalid.
702 2153 ▶ if (length($ver // q{}) && !_valid_requirement($ver)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length($ver // "") and not _valid_requirement($ver)) 37 2116 2153
Condition100%5/5
length($ver // "") and not _valid_requirement($ver)
!ll&&!rl&&r
20655137
$ver // ""
l!l
922061
MC/DC100%2/2
length($ver // "") and not _valid_requirement($ver)
$ver not _valid_requirement($ver)
Truth table100%3/3
A and not(B)
A= $verB= not _valid_requirement($ver)
ABresult
0X0
100
111
703 452 Carp::carp "Ignoring invalid version for '$mod' in existing cpanfile: '" . _printable($ver) . q{'};
704 230 $ver = 0;
705 }
706 218 ▶ $deps->{develop}{$rel}{$mod} //= { version => $ver || 0, comment => undef };
Condition100%4/4
$deps->{"develop"}{$rel}{$mod} //= {"version", $ver || 0, "comment", undef}
l!l
82145
$ver || 0
l!l
422103
MC/DC100%1/1
$deps->{"develop"}{$rel}{$mod} //= {"version", $ver || 0, "comment", undef}
$deps->{"develop"}{$rel}{$mod}
MC/DC100%1/1
$ver || 0
$ver
Truth table100%2/2
A
A= $deps->{"develop"}{$rel}{$mod}
Aresult
11
00
Truth table100%2/2
A
A= $ver
Aresult
11
00
707 }
708 }
709 }
710  
711 250 ▶ if ($with_dev) {
Branch: 1 branch
BranchTrueFalseTotal
if ($with_dev) 251 262 513
712 1140 my $config = _load_develop_config();
713  
714 # Premise 1: a listed tool must never be added again or overwritten.
715 # Premise 2: "listed" means present under any relationship.
716 # Conclusion: build that set once, then add every tool outside it.
717 # ($dev is a copy of the reference or a fresh {}, so reading it
718 # cannot autovivify $deps->{develop} or its relationship hashes.)
719 776 ▶ my $dev = $deps->{develop} || {};
Condition100%2/2
$deps->{'develop'} || {}
l!l
11792
MC/DC100%1/1
$deps->{'develop'} || {}
$deps->{'develop'}
Truth table100%2/2
A
A= $deps->{'develop'}
Aresult
11
00
720 776 ▶ my %listed = map { $_ => 1 } map { keys %{ $dev->{$_} || {} } } @REL_ORDER;
Condition100%2/2
$dev->{$_} || {}
l!l
129707
MC/DC100%1/1
$dev->{$_} || {}
$dev->{$_}
Truth table100%2/2
A
A= $dev->{$_}
Aresult
11
00
721 536 for my $mod (grep { !$listed{$_} } keys %{$config}) {
722 579 $deps->{develop}{requires}{$mod} = { version => $config->{$mod}, comment => undef };
723 }
724 }
725  
726 616 return _emit($deps, $min_perl);
727 }
728  
729 =head2 read_makefile($path)
730  
731 =head3 PURPOSE
732  
733 Reads the text of a F<Makefile.PL>, exactly as L</generate(%args)> does
734 when it is given a C<makefile> argument. Use it together with the
735 C<content> argument of C<generate()> when you need the same text for
736 more than one call, so that the file is read only once.
737  
738 =head3 ARGUMENTS
739  
740 =over 4
741  
742 =item * C<$path> - as the C<makefile> argument of L</generate(%args)>:
743 optional, default C<'Makefile.PL'>, used as a string.
744  
745 =back
746  
747 =head3 RETURNS
748  
749 The file's text as a character string. If the file is not valid UTF-8
750 you get a warning and its raw bytes instead (see L</generate(%args)>).
751  
752 =head3 SIDE EFFECTS
753  
754 Reads the file. May warn. Does not change the caller's C<$@>, C<$!>
755 or C<$_>.
756  
757 =head3 USAGE EXAMPLE
758  
759 my $text = App::makefilepl2cpanfile::read_makefile('Makefile.PL');
760 my $deps = App::makefilepl2cpanfile::parse_prereqs($text);
761 my $out = App::makefilepl2cpanfile::generate(content => $text);
762  
763 =head3 API SPECIFICATION
764  
765 =head4 Input
766  
767 {
768 path => {
769 type => 'string',
770 optional => 1,
771 min => 1,
772 default => 'Makefile.PL',
773 position => 0,
774 },
775 }
776  
777 =head4 Output
778  
779 {
780 type => 'string',
781 }
782  
783 =head3 MESSAGES
784  
785 The same as the file-reading messages of L</generate(%args)>:
786 C<Cannot read '$path'> (croak), the invalid-UTF-8 warning, and any
787 other read error passed on unchanged.
788  
789 =cut
790  
791 793 ▶sub read_makefile {
Subroutine read_makefile: called CC=7 SCAR=19.5
Pod documented
792 # Stringify so a filehandle, glob or other reference is judged by the
793 # same "Cannot read" guard as a bad path, rather than being accepted by
794 # -f (which also tests open handles) and then misread as a path.
795 618 ▶ my $makefile = "@{[ $_[0] // 'Makefile.PL' ]}";
Condition100%2/2
$_[0] // "Makefile.PL"
l!l
6108
MC/DC100%1/1
$_[0] // "Makefile.PL"
$_[0]
Truth table100%2/2
A
A= $_[0]
Aresult
11
00
796  
797 # File tests and reads change errno; restore the caller's $! and $@.
798 533 local $! = 0;
799 533 local $@ = q{};
800  
801 533 ▶ Carp::croak "Cannot read '" . _printable($makefile) . q{'} unless -f $makefile && -r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $makefile and -r _ 85 533 618
Condition100%3/3
-f $makefile and -r _
!ll&&!rl&&r
796533
MC/DC100%2/2
-f $makefile and -r _
-f $makefile -r _
Truth table100%3/3
A and B
A= -f $makefileB= -r _
ABresult
0X0
100
111
802  
803 505 my $content;
804 90 ▶ if (!eval { $content = Path::Tiny::path($makefile)->slurp_utf8; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $content = Path::Tiny::path($makefile)->slurp_utf8; 1 } }) 30 503 533
805 # Only degrade gracefully for encoding errors; re-throw true I/O
806 # failures so callers can distinguish a corrupt file from an
807 # unreadable one. Path::Tiny reports I/O failures as
808 # Path::Tiny::Error objects, whose text includes the file's path:
809 # matching keywords against that would misread an I/O error in,
810 # say, ~/src/utf8-tools/ as a decoding problem. So objects are
811 # always rethrown, and only plain decoder messages are matched.
812 455 ▶ die $@ if ref $@ || $@ !~ /decode|ill-formed|utf/ix; ## no critic (RequireCarping) re-thrown unchanged, as documented; croak would append a location
Branch: 1 branch
BranchTrueFalseTotal
if ref $@ or not $@ =~ /decode|ill-formed|utf/xi 18 12 30
Condition100%3/3
ref $@ or not $@ =~ /decode|ill-formed|utf/xi
l!l&&r!l&&!r
31512
MC/DC100%2/2
ref $@ or not $@ =~ /decode|ill-formed|utf/xi
ref $@ not $@ =~ /decode|ill-formed|utf/xi
Truth table100%3/3
A or not(B)
A= ref $@B= not $@ =~ /decode|ill-formed|utf/xi
ABresult
1X1
011
000
813 732 Carp::carp "Warning: '" . _printable($makefile) . "' contains invalid UTF-8; reading as raw bytes: "
814 . _printable($@ =~ s/\n\z//rx);
815 732 $content = Path::Tiny::path($makefile)->slurp_raw;
816 }
817 767 return $content;
818 }
819  
820 =head2 parse_prereqs($content)
821  
822 =head3 PURPOSE
823  
824 Finds every dependency listed in the text of a F<Makefile.PL> and returns
825 them grouped by phase and relationship. This is the parser that
826 L</generate(%args)> uses; call it directly when you want the data rather
827 than a F<cpanfile>. The text is never run.
828  
829 =head3 ARGUMENTS
830  
831 =over 4
832  
833 =item * C<$content> - the text of a F<Makefile.PL>, as a character string
834 (see L</ENCODING>). C<undef> or a reference is treated as text with no
835 dependencies.
836  
837 =back
838  
839 The forms that are recognised are listed in L</What it reads>. These
840 rules also apply:
841  
842 =over 4
843  
844 =item * Only entries whose name is in quotes and is a valid module name
845 are used. Several entries may be on one line; a C<#> comment at the end
846 of a line belongs to the last entry on that line.
847  
848 =item * Commented-out code is ignored, including a whole dependency list
849 written on one line after a C<#>.
850  
851 =item * A version must contain at least one digit and use only C<0-9>,
852 C<.>, C<_> and a leading C<v>; a version range joins such versions, each
853 after a comparison operator, with commas. Anything else (for example
854 C<'.'> or C<$VERSION>) means "no minimum version".
855  
856 =item * When a module appears twice in the same phase and relationship,
857 the first one wins. The simple keys are read before C<prereqs> blocks.
858  
859 =item * Relationship hashes inside a C<prereqs> block belong to that
860 block's phase; only the version 1 keys directly inside C<META_MERGE> are
861 mapped as described in L</What it reads>.
862  
863 =item * A comment at the end of a line belongs to the last entry on the
864 line that is actually kept; an entry dropped for an invalid name does not
865 take the comment with it.
866  
867 =back
868  
869 =head3 RETURNS
870  
871 A hash reference as described in L</DATA STRUCTURE>. It is empty when
872 nothing is found.
873  
874 =head3 USAGE EXAMPLE
875  
876 use App::makefilepl2cpanfile;
877 use Path::Tiny;
878  
879 my $deps = App::makefilepl2cpanfile::parse_prereqs(
880 path('Makefile.PL')->slurp_utf8
881 );
882  
883 # Which test modules are needed, and which minimum versions?
884 my $test = $deps->{test}{requires} || {};
885 for my $module (sort keys %{$test}) {
886 printf "%-30s %s\n", $module, $test->{$module}{version} || 'any';
887 }
888  
889 =head3 API SPECIFICATION
890  
891 =head4 Input
892  
893 {
894 content => {
895 type => 'string',
896 optional => 1,
897 position => 0,
898 },
899 }
900  
901 =head4 Output
902  
903 {
904 type => 'hashref',
905 }
906  
907 =head4 Domains
908  
909 content
910 valid: any string (decoded characters; see ENCODING)
911 empty: '', undef, any reference, text with no dependency lists
912 -> {} (no warning)
913  
914 module name (the quoted key of an entry)
915 valid: ASCII letter or '_' first, then ASCII letters, digits and
916 '_', in parts joined by '::'. Shortest: one character
917 ('A', '_'). No maximum length.
918 ignored: '' ; leading digit ('1A') ; '::' at either end ; ':::' ;
919 '-', space, ';' or the old "'" package separator ;
920 any non-ASCII character ; a bareword (unquoted) key
921  
922 version (the value of an entry, and MIN_PERL_VERSION)
923 valid: the whole value is an optional 'v' followed by ASCII
924 digits, '.' and '_', with at least one digit:
925 '1', 1.60, 'v1.2.3', '1.23_01', '5.010001'
926 range: (entries only, not MIN_PERL_VERSION) such versions, each
927 after one of >= <= == != > <, joined by commas:
928 '>= 1.2, < 2.0', '== 1.5', '< 2'. '>= 0' means "any".
929 zero: '0', 0, '0.0', '0.000', 'v0', 'v0.0.0' -> "no minimum"
930 (nothing is written)
931 invalid: -> "no minimum": '.', '_', 'v', '1e3', '1.0-TRIAL',
932 '1 0', non-ASCII digits, $VERSION, version->parse(...),
933 spaces around the whole value, and ranges with a missing
934 comma or operator ('>= 1.2 < 2.0', '1.2, 2.0')
935 limits: no maximum length
936  
937 phase / relationship (inside prereqs blocks)
938 valid: exactly runtime, configure, build, test, develop /
939 requires, recommends, suggests, conflicts (lower case)
940 ignored: anything else, including 'Runtime', 'recommend', 'x_foo'
941  
942 comment (text after '#' on an entry's line)
943 kept: any printable Unicode: accents, 'ss'-type letters, emoji,
944 combining marks, right-to-left scripts
945 removed: control characters other than TAB (for example CR) and
946 the bidirectional control characters U+061C, U+200E,
947 U+200F, U+202A-U+202E, U+2066-U+2069, which could make the
948 generated file display differently from its real content
949 empty: a comment that is empty after this -> undef
950  
951 =head3 MESSAGES
952  
953 None. Text that is not recognised is ignored without a warning.
954  
955 =cut
956  
957 783 ▶sub parse_prereqs {
Subroutine parse_prereqs: called CC=16 SCAR=27.7
Pod documented
958 775 my $content = $_[0];
959  
960 # The POD contract is "no errors or warnings - unrecognised content is
961 # silently ignored." Undef and references are not valid Str inputs; return
962 # {} immediately to avoid "uninitialized value" and "reference used as
963 # string" warnings from the pattern-match operators below.
964 775 ▶ return {} if !defined $content || ref $content;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $content or ref $content 25 775 800
Condition100%3/3
not defined $content or ref $content
l!l&&r!l&&!r
916775
MC/DC100%2/2
not defined $content or ref $content
not defined $content ref $content
Truth table100%3/3
not(A) or B
A= not defined $contentB= ref $content
ABresult
1X1
011
000
965  
966 775 my %deps;
967 775 my $comments = _comment_spans($content);
968  
969 # Every block is found through the matching-brace table, so a block may
970 # nest to any depth and each scan below is linear: no pattern has to
971 # match balanced braces, which is what made unclosed openers quadratic.
972 20842 my $pairs = _brace_pairs($content);
973  
974 # ---- Simple dependency keys (PREREQ_PM, BUILD_REQUIRES, etc.) ----
975 # These always map to the 'requires' relationship in their phase. All
976 # four are found in one pass: each key has its own phase, so the order
977 # in which blocks are met cannot change which entry wins.
978 20842 for my $found (@{ _blocks($content, 0, $pairs, $SIMPLE_OPEN_RE) }) {
979 20924 my ($key, $at, undef, $block) = @{$found};
980 872 ▶ next if _in_comment($comments, $at);
Branch: 1 branch
BranchTrueFalseTotal
if _in_comment($comments, $at) 15 20924 20939
981 872 _extract_pairs($block, \%deps, $PHASE_MAP{$key}, 'requires');
982 }
983  
984 # ---- Structured 'prereqs' blocks (CPAN Meta Spec style) ----
985 # These can appear at the top level of WriteMakefile() or nested inside
986 # META_MERGE; both are covered by searching the full content for 'prereqs'.
987 # The [start, end) offset of each block is recorded so that the legacy
988 # scan below can skip relationship blocks nested inside it.
989 20280 my @prereqs_spans;
990 20280 for my $prereqs (@{ _blocks($content, 0, $pairs, $PREREQS_OPEN_RE) }) {
991 20229 my (undef, $at, $prereqs_base, $prereqs_block, $end) = @{$prereqs};
992 20229 ▶ next if _in_comment($comments, $at);
Branch: 1 branch
BranchTrueFalseTotal
if _in_comment($comments, $at) 3 20229 20232
993 20370 push @prereqs_spans, [ $at, $end ];
994  
995 # Each direct child is a phase name mapping to a relationship hash.
996 20370 for my $phase (@{ _blocks($prereqs_block, $prereqs_base, $pairs, $CHILD_OPEN_RE) }) {
997 20382 my ($phase_name, $phase_at, $phase_base, $phase_block) = @{$phase};
998 20380 ▶ next unless $VALID_PHASE{$phase_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_PHASE{$phase_name} 8 20382 20390
999 20393 ▶ next if _in_comment($comments, $phase_at);
Branch: 1 branch
BranchTrueFalseTotal
if _in_comment($comments, $phase_at) 2 20380 20382
1000  
1001 # Each child of the phase block is a relationship name.
1002 20393 for my $relationship (@{ _blocks($phase_block, $phase_base, $pairs, $CHILD_OPEN_RE) }) {
1003 20385 my ($rel, $rel_at, undef, $rel_block) = @{$relationship};
1004 747 ▶ next unless $VALID_REL{$rel};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_REL{$rel} 8 20385 20393
1005 747 ▶ next if _in_comment($comments, $rel_at);
Branch: 1 branch
BranchTrueFalseTotal
if _in_comment($comments, $rel_at) 3 20382 20385
1006  
1007 60452 _extract_pairs($rel_block, \%deps, $phase_name, $rel);
1008 }
1009 }
1010 }
1011  
1012 # ---- Legacy top-level keys (META spec 1.x) ----
1013 # e.g. META_MERGE => { recommends => { 'Mod' => 0 } }, mapped through
1014 # %LEGACY_KEY. Occurrences inside a 'prereqs' block are phase-scoped and
1015 # have already been handled above, so skip them.
1016 60480 for my $found (@{ _blocks($content, 0, $pairs, $LEGACY_OPEN_RE) }) {
1017 40103 my ($key, $at, undef, $block) = @{$found};
1018 # The spans come from a scan that resumes after each block, so they
1019 # are sorted and do not overlap: the same binary search as for
1020 # comments applies, O(log P) per block instead of a linear scan
1021 # (which made many legacy blocks times many prereqs blocks quadratic).
1022 40095 ▶ next if _in_comment(\@prereqs_spans, $at);
Branch: 1 branch
BranchTrueFalseTotal
if _in_comment(\@prereqs_spans, $at) 20394 40062 60456
1023 710 ▶ next if _in_comment($comments, $at);
Branch: 1 branch
BranchTrueFalseTotal
if _in_comment($comments, $at) 8 40054 40062
1024 718 _extract_pairs($block, \%deps, @{ $LEGACY_KEY{$key} });
1025 }
1026  
1027 783 return \%deps;
1028 }
1029  
1030 # -----------------------------------------------------------------------
1031  
1032 # _brace_pairs
1033 #
1034 # Purpose: Pair every '{' in the content with its matching '}', in one
1035 # left-to-right pass with a stack.
1036 # Entry: $_[0] - the content (a defined string).
1037 # Exit: Returns a hashref { offset of '{' => offset of its '}' }. A '{'
1038 # that is never closed has no entry; a '}' with no '{' before it
1039 # is ignored.
1040 # Effects: None.
1041 #
1042 # Braces are counted wherever they appear, including inside quoted strings
1043 # and comments, as the balanced-brace patterns this replaced did.
1044 42738 ▶sub _brace_pairs {
Subroutine _brace_pairs: called CC=4 SCAR=13.9
1045 794519 my $content = $_[0];
1046 672296 my (%close_of, @open);
1047 122290 ▶ while ($content =~ /[{}]/gx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content =~ /[{}]/gx) 795078 783 795861
1048 1342 ▶ if (substr($content, $-[0], 1) eq '{') {
Branch: 2 branches
BranchTrueFalseTotal
if (substr($content, $-[0], 1) eq '{') { } 672541 122537 795078
elsif (@open) { } 122535 2 122537
1049 42983 push @open, $-[0];
1050 } elsif (@open) {
1051 42983 $close_of{ pop @open } = $-[0];
1052 }
1053 }
1054 42738 return \%close_of;
1055 }
1056  
1057 # -----------------------------------------------------------------------
1058  
1059 # _blocks
1060 #
1061 # Purpose: Find each "KEY => {" whose '{' is closed, with the text of its
1062 # block.
1063 # Entry: $_[0] - text to scan: a substring of the content.
1064 # $_[1] - offset of that substring in the content.
1065 # $_[2] - _brace_pairs() of the whole content.
1066 # $_[3] - opener pattern: captures the key in $1, ends with '{'.
1067 # Exit: Returns an arrayref of [ key, offset of the key, offset of the
1068 # block's text, the block's text, offset just past its '}' ].
1069 # Offsets are in the whole content.
1070 # Effects: None.
1071 #
1072 # Like a /g match of a balanced-brace pattern, the scan resumes after each
1073 # block, so a key inside a block that was found is not reported
1074 # separately. An unclosed '{' is passed over and the scan continues
1075 # inside it.
1076 81439 ▶sub _blocks {
Subroutine _blocks: called CC=3 SCAR=11.0
1077 492373 my ($text, $base, $pairs, $opener_re) = @_;
1078 492373 my @blocks;
1079 142369 ▶ while ($text =~ /$opener_re/gx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /$opener_re/gx) 492418 42938 535356
1080 142414 my ($key, $at, $opening) = ($1, $base + $-[0], $base + $+[0] - 1);
1081 42983 ▶ my $closing = $pairs->{$opening} // next;
Condition100%2/2
$pairs->{$opening} // (next)
l!l
142414350004
MC/DC100%1/1
$pairs->{$opening} // (next)
$pairs->{$opening}
Truth table100%2/2
A
A= $pairs->{$opening}
Aresult
11
00
1082 81484 push @blocks, [ $key, $at, $opening + 1, substr($text, $opening + 1 - $base, $closing - $opening - 1), $closing + 1 ];
1083 81484 pos($text) = $closing + 1 - $base;
1084 }
1085 83271 return \@blocks;
1086 }
1087  
1088 # -----------------------------------------------------------------------
1089 # Private helpers
1090 # -----------------------------------------------------------------------
1091  
1092 # _extract_pairs
1093 #
1094 # Purpose: Parse a raw block of text (the content between the outermost
1095 # braces of a dependency hash) into module/version/comment triples
1096 # and store them in the deps structure. Processes line-by-line
1097 # so that trailing inline comments can be captured before the
1098 # comment text is discarded.
1099 # Entry: $_[0] - raw block text (between the outer braces).
1100 # $_[1] - hashref to populate (the top-level %deps).
1101 # $_[2] - phase name string (e.g. 'runtime').
1102 # $_[3] - relationship string (e.g. 'requires').
1103 # Exit: Returns nothing - mutates $_[1] in place.
1104 # Effects: Modifies the deps hashref; no I/O.
1105 #
1106 # First-occurrence-wins: if the same module appears multiple times (e.g.
1107 # once in PREREQ_PM and once in a prereqs block), the first parsed entry
1108 # is kept.
1109 678 ▶sub _extract_pairs {
Subroutine _extract_pairs: called CC=12 SCAR=24.9
1110 83213 my ($block, $deps, $phase, $rel) = @_;
1111  
1112 460 for my $line (split /\n/x, $block) {
1113 # Capture any trailing inline comment before stripping it.
1114 # (.*\S) is O(N): greedy .* scans to end, then gives back trailing
1115 # spaces one by one until \S anchors on the last non-space char.
1116 # Avoids the super-linear behaviour of (.+?)\s*$ which re-evaluates
1117 # \s*$ at every expanded position of the lazy quantifier.
1118 572 my $comment;
1119 # Most lines have no '#': index() is far cheaper than the regexes.
1120 572 ▶ if (index($line, '#') >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($line, "#") != -1) 284 83041 83325
1121 # Text after the first '#', then again after removing unsafe
1122 # characters (which can expose new outer whitespace). Both use
1123 # $TRIMMED_RE, which is linear; see its definition.
1124 274 my $after = substr $line, index($line, '#') + 1;
1125 274 ($comment) = $after =~ /\A$TRIMMED_RE/x;
1126 284 ▶ if (defined $comment) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $comment) 274 10 284
1127 83037 $comment =~ s/$UNSAFE_COMMENT_CHARS_RE//gx;
1128 83037 ($comment) = $comment =~ /\A$TRIMMED_RE/x;
1129 }
1130 82558 $line = substr $line, 0, index($line, '#');
1131 }
1132  
1133 # A line may hold several entries ('A' => 0, 'B' => 0); take them all.
1134 83325 my @pairs;
1135 # Opening and closing quotes must match: with ['"]...['"] the key
1136 # "A'B" was read as 'B" and recorded as a different module, B.
1137 82846 ▶ while ($line =~ /$PAIR_RE/gx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /$PAIR_RE/gx) 82825 83325 166150
1138 83304 ▶ push @pairs, [ $1 // $2, $3 // $4 // $5 ];
Condition88%8/9
$1 // $2
l!l&&r!l&&!r
8282230
($3 // $4) // $5
l!l&&r!l&&!r
95181762112
$3 // $4
l!l&&r!l&&!r
9493781839
MC/DC0%0/2
$1 // $2
$1 $2
MC/DC66%2/3
($3 // $4) // $5
$3 $4 $5
Truth table66%2/3
A // B
A= $1B= $2
ABresult
1X1
011
000
Truth table75%3/4
A // B // C
A= $3B= $4C= $5
ABCresult
1XX1
01X1
0011
0000
1139 }
1140  
1141 # Defense-in-depth: [^'"]+ already excludes quote characters, but it
1142 # would accept spaces, ';' and non-ASCII look-alikes. Only a real
1143 # module name may reach the generated cpanfile. Invalid names are
1144 # dropped first, so that the line's comment goes to the last entry
1145 # that is actually kept.
1146 82817 @pairs = grep { $_->[0] =~ $MODULE_NAME_RE } @pairs;
1147  
1148 82817 for my $i (0 .. $#pairs) {
1149 82796 my ($mod, $ver) = @{ $pairs[$i] };
1150 # Anything that is not a version or version range ('.', '_',
1151 # $VERSION, ...) means "no minimum"; emitting it would produce a
1152 # cpanfile that CPAN::Meta::Requirements rejects.
1153 769 ▶ $ver = 0 unless _valid_requirement($ver);
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_requirement($ver) 52 82744 82796
1154 # First occurrence wins - do not overwrite already-parsed entries.
1155 # A trailing comment belongs to the entry it follows: the last.
1156 769 ▶ $deps->{$phase}{$rel}{$mod} //= {
Branch: 1 branch
BranchTrueFalseTotal
$i == $#pairs ? : 82490 53 82543
Condition100%2/2
$deps->{$phase}{$rel}{$mod} //= {"version", $ver, "comment", $i == $#pairs ? $comment : undef}
l!l
25382543
MC/DC100%1/1
$deps->{$phase}{$rel}{$mod} //= {"version", $ver, "comment", $i == $#pairs ? $comment : undef}
$deps->{$phase}{$rel}{$mod}
Truth table100%2/2
A
A= $deps->{$phase}{$rel}{$mod}
Aresult
11
00
1157 version => $ver,
1158 comment => $i == $#pairs ? $comment : undef,
1159 };
1160 }
1161 }
1162  
1163 674 return;
1164 }
1165  
1166 # _parse_min_perl
1167 #
1168 # Purpose: Extract the MIN_PERL_VERSION value from Makefile.PL text.
1169 # Entry: $_[0] - raw Makefile.PL content string.
1170 # Exit: The version string (e.g. '5.010'), or undef if not declared.
1171 773 ▶sub _parse_min_perl {
Subroutine _parse_min_perl: called CC=7 SCAR=19.5
1172 235 my $content = $_[0];
1173 235 ▶ return undef if !defined $content || ref $content; ## no critic (ProhibitExplicitReturnUndef)
Branch: 1 branch
BranchTrueFalseTotal
if not defined $content or ref $content 4 524 528
Condition66%2/3
not defined $content or ref $content
l!l&&r!l&&!r
40524
MC/DC50%1/2
not defined $content or ref $content
not defined $content ref $content
Truth table66%2/3
not(A) or B
A= not defined $contentB= ref $content
ABresult
1X1
011
000
1174 773 ▶ return undef unless $content =~ /\bMIN_PERL_VERSION\b['"]?\s*=>\s*$VALUE_TOKEN_RE/x; ## no critic (ProhibitExplicitReturnUndef)
Branch: 1 branch
BranchTrueFalseTotal
unless $content =~ /\bMIN_PERL_VERSION\b['"]?\s*=>\s*$VALUE_TOKEN_RE/x 301 223 524
1175 761 ▶ my $ver = $1 // $2 // $3;
Condition83%5/6
($1 // $2) // $3
l!l&&r!l&&!r
21913
$1 // $2
l!l&&r!l&&!r
21670
MC/DC0%0/3
($1 // $2) // $3
$1 $2 $3
Truth table50%2/4
A // B // C
A= $1B= $2C= $3
ABCresult
1XX1
01X1
0011
0000
1176 761 ▶ return _valid_version($ver) ? $ver : undef;
Branch: 1 branch
BranchTrueFalseTotal
_valid_version($ver) ? : 213 10 223
1177 }
1178  
1179 # _comment_spans
1180 #
1181 # Purpose: Find every '#' comment in the content, so that a commented-out
1182 # one-line dependency hash is not parsed as live. One linear pass;
1183 # the result is queried with _in_comment for each candidate block.
1184 # Entry: $_[0] - content string.
1185 # Exit: ArrayRef of [start, end) offsets, ascending and non-overlapping,
1186 # each running from an unquoted '#' to the end of its line.
1187 182221 ▶sub _comment_spans {
Subroutine _comment_spans: called CC=4 SCAR=13.9
1188 781 my $content = $_[0];
1189 44977 my @spans;
1190 345 my $offset = 0;
1191 44977 for my $line (split /\n/x, $content, -1) {
1192 # Most lines have no '#' at all; only the rest need the quote-aware
1193 # scan, which finds the first '#' outside quoted strings (so that
1194 # e.g. 'C#' is not mistaken for a comment) without building a copy.
1195 1455 ▶ if (index($line, '#') >= 0 && $line =~ $TO_COMMENT_RE) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($line, "#") != -1 and $line =~ /$TO_COMMENT_RE/) 327 45324 45651
Condition100%3/3
index($line, "#") != -1 and $line =~ /$TO_COMMENT_RE/
!ll&&!rl&&r
453213327
MC/DC100%2/2
index($line, "#") != -1 and $line =~ /$TO_COMMENT_RE/
index($line, "#") != -1 $line =~ /$TO_COMMENT_RE/
Truth table100%3/3
A and B
A= index($line, "#") != -1B= $line =~ /$TO_COMMENT_RE/
ABresult
0X0
100
111
1196 182203 push @spans, [ $offset + $+[0] - 1, $offset + length $line ];
1197 }
1198 182895 $offset += length($line) + 1;
1199 }
1200 182221 return \@spans;
1201 }
1202  
1203 # _in_comment
1204 #
1205 # Purpose: Decide whether an offset lies inside one of the comment spans.
1206 # Entry: $_[0] - ArrayRef from _comment_spans; $_[1] - offset.
1207 # Exit: Boolean. Binary search, so O(log n) per query.
1208 507 ▶sub _in_comment {
Subroutine _in_comment: called CC=4 SCAR=13.9
1209 182470 my ($spans, $pos) = @_;
1210 556492 my ($lo, $hi) = (0, $#{$spans});
1211 556492 ▶ while ($lo <= $hi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lo <= $hi) 556437 162040 718477
1212 556437 my $mid = int(($lo + $hi) / 2);
1213 259015 my ($start, $end) = @{ $spans->[$mid] };
1214 20652 ▶ if ($pos < $start) { $hi = $mid - 1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($pos < $start) { } 258858 297579 556437
elsif ($pos >= $end) { } 277149 20430 297579
1215 305 elsif ($pos >= $end) { $lo = $mid + 1 }
1216 230 else { return 1 }
1217 }
1218 82991 return 0;
1219 }
1220  
1221 # _valid_version
1222 #
1223 # Purpose: Decide whether a string is a plausible version number that is
1224 # safe to write inside a single-quoted cpanfile literal.
1225 # Entry: $_[0] - candidate version string.
1226 # Exit: Boolean: an optional leading 'v' followed only by ASCII digits,
1227 # dots and underscores, with at least one digit.
1228 82763 ▶sub _valid_version {
Subroutine _valid_version: called CC=3 SCAR=11.0
1229 82763 my $ver = $_[0];
1230 533 ▶ return defined $ver && $ver =~ $VERSION_RE ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $ver && $ver =~ /$VERSION_RE/ ? : 218 20 238
Condition100%3/3
defined $ver and $ver =~ /$VERSION_RE/
!ll&&!rl&&r
218218
MC/DC100%2/2
defined $ver and $ver =~ /$VERSION_RE/
defined $ver $ver =~ /$VERSION_RE/
Truth table100%3/3
A and B
A= defined $verB= $ver =~ /$VERSION_RE/
ABresult
0X0
100
111
1231 }
1232  
1233 # _valid_requirement
1234 #
1235 # Purpose: Decide whether a string is a module version requirement that is
1236 # safe to write inside a single-quoted cpanfile literal: a single
1237 # version (see _valid_version) or a CPAN::Meta version range.
1238 # Entry: $_[0] - candidate string.
1239 # Exit: Boolean.
1240 807 ▶sub _valid_requirement {
Subroutine _valid_requirement: called CC=3 SCAR=11.0
1241 807 my $req = $_[0];
1242 337 ▶ return defined $req && $req =~ $REQUIREMENT_RE ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $req && $req =~ /$REQUIREMENT_RE/ ? : 82925 112 83037
Condition100%3/3
defined $req and $req =~ /$REQUIREMENT_RE/
!ll&&!rl&&r
211082925
MC/DC100%2/2
defined $req and $req =~ /$REQUIREMENT_RE/
defined $req $req =~ /$REQUIREMENT_RE/
Truth table100%3/3
A and B
A= defined $reqB= $req =~ /$REQUIREMENT_RE/
ABresult
0X0
100
111
1243 }
1244  
1245 # _printable
1246 #
1247 # Purpose: Make text from a file or the environment safe to put in an
1248 # error or warning. SECURITY: such text is printed to the user's
1249 # terminal, where escape sequences (e.g. ESC ] 0 ; ... to retitle
1250 # the window, or CR and ESC [ 2 K to erase the line and print
1251 # something else) could hide or forge messages.
1252 # Entry: $_[0] - any value (stringified).
1253 # Exit: The string with control characters and bidirectional-override
1254 # characters replaced by \x{..} escapes; everything else as is.
1255 296 ▶sub _printable {
Subroutine _printable: called CC=1 SCAR=0.0
1256 508 my $text = "$_[0]";
1257 296 $text =~ s/($UNSAFE_COMMENT_CHARS_RE)/sprintf '\\x{%X}', ord $1/gex;
1258 296 return $text;
1259 }
1260  
1261 # _load_develop_config
1262 #
1263 # Return the develop-tools hash from the user's YAML config file,
1264 # or %DEFAULT_DEVELOP when no config file exists.
1265 # Entry: None - reads from the filesystem at a well-known path.
1266 # Exit: HashRef { Module::Name => minimum_version_or_0 }.
1267 # Effects: Reads from disk. Croaks on YAML parse failure. Carps when the
1268 # config file lacks a 'develop' key.
1269 453 ▶sub _load_develop_config {
Subroutine _load_develop_config: called CC=17 SCAR=28.3
1270 # Path::Tiny and YAML::Tiny use eval internally, which resets $@; keep the
1271 # caller's value intact so an enclosing eval/$@ check is not disturbed.
1272 284 local $@ = q{};
1273  
1274 # Guard: no usable home directory (containers, chroots, CI). length()
1275 # of undef is undef, so one test rejects both undef and ''.
1276 284 my $home = File::HomeDir->my_home;
1277 284 ▶ return {%DEFAULT_DEVELOP} unless length($home // q{});
Branch: 1 branch
BranchTrueFalseTotal
unless length($home // "") 9 284 293
Condition100%2/2
$home // ""
l!l
2876
MC/DC100%1/1
$home // ""
$home
Truth table100%2/2
A
A= $home
Aresult
11
00
1278  
1279 284 my $cfg_path = Path::Tiny::path($home)->child('.config', 'makefilepl2cpanfile.yml');
1280 98 my $cfg_shown = _printable($cfg_path);
1281  
1282 # Guard: the path cannot be examined. A missing file means "use the
1283 # defaults"; any other stat failure (EACCES, ELOOP, stale NFS...) must not
1284 # silently change the output.
1285 95 my @stat = stat "$cfg_path";
1286 207 ▶ unless (@stat) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@stat) 85 199 284
1287 623 ▶ Carp::croak "Failed to parse $cfg_shown: $!" unless $!{ENOENT} || $!{ENOTDIR};
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless $!{"ENOENT"} or $!{"ENOTDIR"} 3 82 85
Condition100%3/3
$!{"ENOENT"} or $!{"ENOTDIR"}
l!l&&r!l&&!r
8113
MC/DC100%2/2
$!{"ENOENT"} or $!{"ENOTDIR"}
$!{"ENOENT"} $!{"ENOTDIR"}
Truth table100%3/3
A or B
A= $!{"ENOENT"}B= $!{"ENOTDIR"}
ABresult
1X1
011
000
1288 187 return {%DEFAULT_DEVELOP};
1289 }
1290  
1291 # Guard: not a regular file. A FIFO would block the read forever and a
1292 # device could stream without end. The mode bits come from @stat, not
1293 # from Perl's implicit '_' buffer, which another stat could replace.
1294 192 ▶ return {%DEFAULT_DEVELOP} unless Fcntl::S_ISREG($stat[2]);
Branch: 1 branch
BranchTrueFalseTotal
unless Fcntl::S_ISREG($stat[2]) 7 192 199
1295  
1296 # Guard: unreadable or invalid YAML. YAML::Tiny reports failure by dying
1297 # (current versions) or by returning false with errstr set (older ones);
1298 # both become the single documented message, without YAML::Tiny's own
1299 # location.
1300 57 my $yaml = eval { YAML::Tiny->read("$cfg_path") };
1301 57 ▶ unless ($yaml) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($yaml) 45 147 192
1302 136 ▶ my $err = $@ || YAML::Tiny->errstr() // q{};
Condition100%5/5
($@ || "YAML::Tiny"->errstr) // ""
l!l
441
$@ or "YAML::Tiny"->errstr
l!l&&r!l&&!r
3564
MC/DC100%2/2
($@ || "YAML::Tiny"->errstr) // ""
$@ "YAML::Tiny"->errstr
Truth table100%3/3
A or B
A= $@B= "YAML::Tiny"->errstr
ABresult
1X1
011
000
1303 136 $err =~ s/[ ]at[ ]\S++[ ]line[ ]\d++\.?\n?\z//x;
1304 136 Carp::croak "Failed to parse $cfg_shown: " . _printable($err);
1305 }
1306  
1307 # Guard: no develop hash. Checking the document's type first means a
1308 # document that is not a hash is never dereferenced.
1309 53 my $doc = $yaml->[0];
1310 53 ▶ my $develop = ref $doc eq 'HASH' ? $doc->{develop} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $doc eq 'HASH' ? : 143 4 147
1311 106 ▶ unless (ref $develop eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $develop eq "HASH") 41 106 147
1312 94 Carp::carp "No 'develop' key found in $cfg_shown; using defaults";
1313 94 return {%DEFAULT_DEVELOP};
1314 }
1315  
1316 # SECURITY: validate every key (module name) and value (version) before
1317 # use. Keys are arbitrary strings: without this guard a key such as
1318 # "Safe'; system('evil'); requires 'X" would close the quoted literal in
1319 # _fmt_dep and inject code into the generated cpanfile, which cpanm runs.
1320 142 my %clean;
1321 22 for my $mod (keys %{$develop}) {
1322 132 ▶ unless ($mod =~ $MODULE_NAME_RE) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($mod =~ /$MODULE_NAME_RE/) 10 132 142
1323 120 Carp::carp "Skipping invalid module name in $cfg_shown: '" . _printable($mod) . q{'};
1324 23 next;
1325 }
1326 # Premise 1: a null value means "any version", i.e. 0.
1327 # Premise 2: _valid_requirement accepts '0' (it contains a digit).
1328 # Conclusion: '' is the only extra value that needs allowing.
1329 35 ▶ my $v = $develop->{$mod} // 0;
Condition100%2/2
$develop->{$mod} // 0
l!l
1266
MC/DC100%1/1
$develop->{$mod} // 0
$develop->{$mod}
Truth table100%2/2
A
A= $develop->{$mod}
Aresult
11
00
1330 132 ▶ unless ($v eq q{} || _valid_requirement($v)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($v eq "" or _valid_requirement($v)) 23 109 132
Condition100%3/3
$v eq "" or _valid_requirement($v)
l!l&&r!l&&!r
710223
MC/DC100%2/2
$v eq "" or _valid_requirement($v)
$v eq "" _valid_requirement($v)
Truth table100%3/3
A or B
A= $v eq ""B= _valid_requirement($v)
ABresult
1X1
011
000
1331 94 Carp::carp "Skipping invalid version for '$mod' in $cfg_shown: '" . _printable($v) . q{'};
1332 432 $v = 0;
1333 }
1334 444 $clean{$mod} = $v;
1335 }
1336 444 return \%clean;
1337 }
1338  
1339 # _emit
1340 #
1341 # Purpose: Pure formatter - converts the structured dependency hash and an
1342 # optional minimum Perl version into a valid cpanfile string.
1343 # Entry: $_[0] - HashRef (see DATA STRUCTURE section in POD)
1344 # $_[1] - optional Str minimum Perl version (e.g. '5.010')
1345 # Exit: Scalar string; always terminated with exactly one newline.
1346 # Never returns undef.
1347 #
1348 # Runtime deps are emitted at the top level (no 'on' block) per cpanfile
1349 # convention. All other phases get 'on phase => sub { ... }' blocks.
1350 # Within each phase, relationships are emitted in @REL_ORDER order;
1351 # modules within each relationship are sorted alphabetically.
1352 # Inline comments are re-emitted after the semicolon on the same line.
1353 # A version of 0 or '' means "any version" and is omitted.
1354 2224 ▶sub _emit {
Subroutine _emit: called CC=6 SCAR=17.9
1355 491 my ($deps, $min_perl) = @_;
1356  
1357 # Build the output as a list of sections joined by blank lines.
1358 2219 my @sections = ($HEADER);
1359 2219 ▶ push @sections, "requires 'perl', '$min_perl';" if _has_version($min_perl);
Branch: 1 branch
BranchTrueFalseTotal
if _has_version($min_perl) 175 316 491
1360  
1361 # Runtime is emitted at the top level; every other phase in an 'on'
1362 # block, in @PHASE_ORDER. Both use the same line builder.
1363 4450 for my $phase ('runtime', @PHASE_ORDER) {
1364 4686 ▶ my $indent = $phase eq 'runtime' ? q{} : "\t";
Branch: 1 branch
BranchTrueFalseTotal
$phase eq 'runtime' ? : 491 1964 2455
1365 2455 my $body = join q{}, map { _fmt_dep(@{$_}, $indent) } @{ _phase_entries($deps->{$phase}) };
1366 # Premise: an absent phase, or one whose relationships are all
1367 # empty, yields no entries. Conclusion: it yields no section.
1368 2460 ▶ next if $body eq q{};
Branch: 1 branch
BranchTrueFalseTotal
if $body eq "" 1547 908 2455
1369 2325 ▶ push @sections, $phase eq 'runtime'
Branch: 1 branch
BranchTrueFalseTotal
$phase eq 'runtime' ? : 424 484 908
1370 ? $body =~ s/\n\z//rx # the blank-line separator is added by join
1371 : "on '$phase' => sub {\n$body};";
1372 }
1373  
1374 2224 return join("\n\n", @sections) . "\n";
1375 }
1376  
1377 # _phase_entries
1378 #
1379 # Purpose: List one phase's entries in output order: relationships in
1380 # @REL_ORDER, modules alphabetically within each.
1381 # Entry: $_[0] - the phase's hashref ({ rel => { module => entry } }),
1382 # or undef when the phase is absent.
1383 # Exit: ArrayRef of [ rel, module, entry ] triples; empty when none.
1384 4704 ▶sub _phase_entries {
Subroutine _phase_entries: called CC=5 SCAR=16.1
1385 8955 ▶ my $phase = $_[0] || {};
Condition100%2/2
$_[0] || {}
l!l
9151545
MC/DC100%1/1
$_[0] || {}
$_[0]
Truth table100%2/2
A
A= $_[0]
Aresult
11
00
1386 8955 my @entries;
1387 8955 for my $rel (@REL_ORDER) {
1388 3345 ▶ my $mods = $phase->{$rel} || {};
Condition100%2/2
$phase->{$rel} || {}
l!l
10048836
MC/DC100%1/1
$phase->{$rel} || {}
$phase->{$rel}
Truth table100%2/2
A
A= $phase->{$rel}
Aresult
11
00
1389 5589 push @entries, [ $rel, $_, $mods->{$_} ] for sort keys %{$mods};
1390 }
1391 4704 return \@entries;
1392 }
1393  
1394 # _fmt_dep
1395 #
1396 # Purpose: Format a single dependency line for cpanfile output, including
1397 # the optional version constraint and inline comment.
1398 # Entry: $_[0] - relationship keyword (e.g. 'requires', 'recommends').
1399 # $_[1] - module name string.
1400 # $_[2] - entry hashref { version => ..., comment => ... }.
1401 # $_[3] - indentation prefix ('' for runtime, "\t" for phase blocks).
1402 # Exit: A complete formatted line, including trailing newline.
1403 5192 ▶sub _fmt_dep {
Subroutine _fmt_dep: called CC=3 SCAR=11.0
1404 4718 my ($rel, $mod, $entry, $indent) = @_;
1405  
1406 445 my $line = "${indent}$rel '$mod'";
1407 4582 ▶ $line .= ", '$entry->{version}'" if _has_version($entry->{version});
Branch: 1 branch
BranchTrueFalseTotal
if _has_version($entry->{"version"}) 535 4183 4718
1408  
1409 # Premise 1: every producer of entries stores a comment that is undef
1410 # or non-empty (_extract_pairs turns an empty comment into undef; merged
1411 # and configured entries have none). Premise 2: _fmt_dep is only called
1412 # by _emit on such entries. Conclusion: defined() is sufficient.
1413 4718 ▶ if (defined $entry->{comment}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry->{'comment'}) { } 163 4555 4718
1414 4910 $line .= "; # $entry->{comment}\n";
1415 } else {
1416 5165 $line .= ";\n";
1417 }
1418  
1419 4891 return $line;
1420 }
1421  
1422 # _has_version
1423 #
1424 # Decide whether a version value represents a real minimum version
1425 # constraint that should be written into the cpanfile output.
1426 # Entry: $_[0] - version value (scalar, possibly undef or numeric '0').
1427 # Exit: Boolean: true if the version should be emitted; false if it
1428 # means "any version" (undef, empty string, or numeric zero).
1429 368 ▶sub _has_version {
Subroutine _has_version: called CC=5 SCAR=16.1
1430 4945 my $ver = $_[0];
1431  
1432 # Premise 1: every version that reaches here is undef, 0, '' or a string
1433 # accepted by _valid_requirement: a single version (ASCII digits, '.',
1434 # '_', optional 'v') or a range, which always contains an operator.
1435 # Premise 2: a single version is zero exactly when none of its digits is
1436 # 1-9 ('0', '0.000', 'v0.0.0', '0_0'); a range means "any version" only
1437 # when it is '>=' a zero version.
1438 # Conclusion: two tests decide it.
1439 385 ▶ return 0 unless defined $ver;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ver 313 4938 5251
1440 373 ▶ return $ver =~ /\A \s* >= \s* v? [0._]* \s* \z/x ? 0 : 1 if $ver =~ /[<>=!]/x;
Branch: 2 branches
BranchTrueFalseTotal
if $ver =~ /[<>=!]/x 5 4933 4938
$ver =~ /\A \s* >= \s* v? [0._]* \s* \z/x ? : 1 4 5
1441 373 ▶ return $ver =~ /[1-9]/x ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ver =~ /[1-9]/x ? : 729 4204 4933
1442 }
1443  
1444  
1445 # -----------------------------------------------------------------------
1446 # Post-release roadmap (from the 0.05 gap analysis)
1447 # -----------------------------------------------------------------------
1448 #
1449 # Features
1450 # TODO: Write CPAN::Meta optional_features as cpanfile 'feature' blocks,
1451 # and carry x_* custom phases through instead of dropping them.
1452 # TODO: Command line: --diff should exit non-zero when the cpanfile would
1453 # change (like 'git diff --exit-code'); add --makefile FILE,
1454 # --output FILE, --quiet, and '-' to read Makefile.PL from stdin.
1455 # TODO: Read other build files: Build.PL (Module::Build requires,
1456 # build_requires, test_requires, configure_requires, recommends) and
1457 # possibly dist.ini; consider the reverse direction (cpanfile to a
1458 # PREREQ_PM snippet).
1459 # TODO: Keep more of a hand-written cpanfile than its develop block:
1460 # feature blocks, extra 'on test' entries, and comments inside the
1461 # develop block.
1462 # TODO: Optional, never default, mode that runs Makefile.PL in an isolated
1463 # sandbox to capture dependencies computed by code.
1464 # TODO: Translatable messages (e.g. Locale::TextDomain); all messages are
1465 # English only.
1466 #
1467 # Technical debt
1468 # TODO: Replace the brace matching with PPI: parses Perl without running
1469 # it, understands quoting, comments and heredocs (so a brace inside
1470 # a string would no longer count), and could flag conditional
1471 # dependencies instead of making them unconditional.
1472 # TODO: Move bin/makefilepl2cpanfile's logic into a module
1473 # (e.g. App::makefilepl2cpanfile::CLI->run(\@ARGV) returning an exit
1474 # code) for in-process tests, real coverage, and fewer subprocess
1475 # tests (slow, and fragile on Windows).
1476 # TODO: Consolidate the test suite: move duplicated helpers (empty_home,
1477 # make_mf, use_home, run_cli) into t/lib, and merge the overlap
1478 # between function.t, unit.t and extended_tests.t.
1479 # TODO: Readonly hashes and arrays (%PHASE_MAP, %VALID_PHASE, %VALID_REL,
1480 # %LEGACY_KEY, @REL_ORDER, @PHASE_ORDER, %DEFAULT_DEVELOP) are tied,
1481 # adding overhead to every access; use plain lexicals or constant
1482 # lists.
1483 # TODO: In the command-line tool, rename the temporary file directly
1484 # instead of Path::Tiny's move (File::Copy::move moves INTO a
1485 # directory; only the non-regular-file guard prevents that today),
1486 # and close the small race between the symlink check and the write.
1487 # TODO: Consider a size limit for Makefile.PL and the existing cpanfile, so
1488 # a huge hostile file cannot exhaust memory.
1489 # TODO: CI: Devel::Cover for the command-line tool's subprocesses (via
1490 # PERL5OPT).
1491  
1492 69 1;
1493  
1494 __END__
↑ Summary bin/makefilepl2cpanfile »