File Coverage

File:blib/lib/App/Test/Generator/PodExampleExtractor.pm
Coverage:94.9%

linestmtbrancondsubtimecode
1package App::Test::Generator::PodExampleExtractor;
2
3
8
8
68460
16
use 5.036;
4
8
8
8
17
22
258
use Carp qw(croak);
5
8
8
8
911
15050
187
use File::Slurp qw(read_file);
6
8
8
8
338
2391
4439
use Readonly;
7
8our $VERSION = '0.52';
9
10Readonly my $ANNOTATION_RE => qr/\#\s*(?:=>|returns?)\s*(.+?)\s*$/;
11Readonly my $VERBATIM_RE   => qr/^[ \t]/;
12
13=encoding utf8
14
15 - 143
=head1 NAME

App::Test::Generator::PodExampleExtractor - Extract runnable code examples from a Perl module's POD

=head1 VERSION

Version 0.52

=head1 SYNOPSIS

Pattern 1: list every example found in a module.

    use App::Test::Generator::PodExampleExtractor;

    my $ex = App::Test::Generator::PodExampleExtractor->new(
        file => 'lib/My/Module.pm',
    );
    my $examples = $ex->extract();

    for my $e (@$examples) {
        printf "%-30s  %s\n", $e->{label}, $e->{code};
    }

Pattern 2: keep only the examples that say what they return.
These are the ones that can be checked automatically.

    my @checkable = grep { defined $_->{expected} } @{ $ex->extract() };

    for my $e (@checkable) {
        print "Run:    $e->{annotated_line}\n";
        print "Expect: $e->{expected}\n";
    }

Pattern 3: count the examples in each documentation section.

    my %count;
    $count{ $_->{section} }++ for @{ $ex->extract() };
    printf "%-20s %d\n", $_, $count{$_} for sort keys %count;

Pattern 4: handle a missing file without stopping the program.

    my $ex2 = eval {
        App::Test::Generator::PodExampleExtractor->new(file => $path);
    };
    warn "Skipping $path: $@" unless $ex2;

=head1 DESCRIPTION

Parses the POD of a Perl module and returns a structured list of
runnable code examples.  Three sources are collected:

=over 4

=item * Verbatim blocks inside C<=head1 SYNOPSIS> and C<=head2 SYNOPSIS>

=item * C<=for example begin> ... C<=for example end> blocks

=item * Annotated single-line call examples inside per-method docstrings
(lines matching C<$obj-E<gt>method(...)  # returns value> or
C<method(...)  # => value>)

=back

Return-value annotations of the form C<# returns value> or C<< # => value >>
are parsed and exposed as C<expected> in the result hashref, enabling
downstream test generators to emit C<is()> assertions.

=head2 new

Construct a new extractor for the given source file.

    my $ex = App::Test::Generator::PodExampleExtractor->new(
        file => 'lib/My/Module.pm',
    );

=head3 Arguments

=over 4

=item * C<file>

Path to the Perl module to extract examples from.  Required.
The file must exist on disk.

=back

=head3 Returns

A blessed C<App::Test::Generator::PodExampleExtractor> object.
Croaks if C<file> is missing or does not exist.

The file is not opened by C<new>.  It is read each time you call C<extract>.

=head3 EXAMPLE

    use App::Test::Generator::PodExampleExtractor;

    my $ex = App::Test::Generator::PodExampleExtractor->new(
        file => 'lib/Acme/Widget.pm',
    );
    printf "Extracting examples from %s\n", 'lib/Acme/Widget.pm';

=head3 MESSAGES

=over 4

=item C<file is required>

C<file> was not supplied.

=item C<File not found: $path>

C<file> was supplied but the path does not exist on disk.

=back

=head3 API SPECIFICATION

=head4 input

    { file => { type => SCALAR } }

=head4 output

    { type => OBJECT, isa => 'App::Test::Generator::PodExampleExtractor' }

The mathematical description is in L</FORMAL SPECIFICATION>.

=cut
144
145sub new {
146
74
401580
        my ($class, %args) = @_;
147
74
129
        croak 'file is required'          unless defined $args{file};
148
69
385
        croak "File not found: $args{file}" unless -f $args{file};
149
63
99
        return bless { file => $args{file} }, $class;
150}
151
152 - 219
=head2 extract

Extract all runnable examples from the module's POD.

    my $examples = $ex->extract();

=head3 Arguments

None beyond C<$self>.

=head3 Returns

An arrayref of example hashrefs, deduplicated by C<code> text.  Each hashref
has the following keys:

=over 4

=item * C<label> - human-readable name for use as a test label (e.g. C<"SYNOPSIS example 1">)

=item * C<section> - the POD section heading (C<=head1>/C<=head2> text) where the example was found

=item * C<code> - the raw code text, dedented.  May be multi-line for verbatim blocks.

=item * C<expected> - the expected return value string from a C<# returns value> or C<< # => value >> annotation; C<undef> if not annotated.

=item * C<annotated_line> - for annotated single-line examples, the bare expression with the annotation stripped; C<undef> for verbatim blocks.

=back

=head3 EXAMPLE

    my $examples = $ex->extract();
    for my $e (@{$examples}) {
        printf "[%s] %s\n", $e->{label}, $e->{code};
        if(defined $e->{expected}) {
            printf "  expects: %s\n", $e->{expected};
        }
    }

    # Count examples without a declared return value
    my @unannotated = grep { !defined $_->{expected} } @{$examples};
    printf "%d unannotated examples\n", scalar @unannotated;

=head3 MESSAGES

=over 4

=item C<read_file 'PATH' - ...> (raised by C<File::Slurp::read_file>)

The source file was removed, or became unreadable, between the call to
C<new> and the call to C<extract>.  The rest of the message is the reason
given by the operating system.

=back

=head3 API SPECIFICATION

=head4 input

    { self => { type => OBJECT, isa => 'App::Test::Generator::PodExampleExtractor' } }

=head4 output

    { type => ARRAYREF }

The mathematical description is in L</FORMAL SPECIFICATION>.

=cut
220
221sub extract {
222
61
505
        my $self = $_[0];
223
224
61
102
        my $text = read_file($self->{file}, err_mode => 'croak');
225
226
61
2697
        my @raw;
227
61
61
        push @raw, _extract_synopsis_blocks($text);
228
61
59
        push @raw, _extract_for_example_blocks($text);
229
61
56
        push @raw, _extract_annotated_lines($text);
230
231        # deduplicate by code text
232
61
35
        my %seen;
233
61
98
55
134
        my @unique = grep { !$seen{ $_->{code} }++ } @raw;
234
235        # assign numbered labels within each section
236
61
40
        my %section_count;
237
61
44
        for my $e (@unique) {
238
96
84
                my $n = ++$section_count{ $e->{section} };
239
96
83
                $e->{label} = "$e->{section} example $n";
240        }
241
242
61
133
        return \@unique;
243}
244
245# --------------------------------------------------
246# _extract_synopsis_blocks
247#
248# Purpose:    Extract verbatim (indented) paragraphs from
249#             =head1 SYNOPSIS and =head2 SYNOPSIS sections.
250#
251# Entry:      $text - full module source including POD
252#
253# Exit:       Returns a list of example hashrefs.
254# --------------------------------------------------
255sub _extract_synopsis_blocks {
256
61
38
        my $text = $_[0];
257
258
61
42
        my @examples;
259
61
1449
        while($text =~ /=head[12]\s+SYNOPSIS\s*\n(.*?)(?=\n=head|\n=cut|\z)/sg) {
260
31
38
                my $block = $1;
261
31
39
                push @examples, _verbatim_paragraphs($block, 'SYNOPSIS');
262        }
263
61
51
        return @examples;
264}
265
266# --------------------------------------------------
267# _extract_for_example_blocks
268#
269# Purpose:    Extract code inside =for example begin / =for example end pairs.
270#
271# Entry:      $text - full module source including POD
272#
273# Exit:       Returns a list of example hashrefs.
274# --------------------------------------------------
275sub _extract_for_example_blocks {
276
61
47
        my $text = $_[0];
277
278
61
35
        my @examples;
279
61
35
        my $n = 0;
280
61
961
        while($text =~ /=for\s+example\s+begin\s*\n(.*?)=for\s+example\s+end/sg) {
281
4
6
                my $block = $1;
282
4
6
                push @examples, _verbatim_paragraphs($block, '=for example ' . ++$n);
283        }
284
61
44
        return @examples;
285}
286
287# --------------------------------------------------
288# _extract_annotated_lines
289#
290# Purpose:    Find individual lines inside per-method docstrings that
291#             carry a # returns / # => annotation.  These are single-
292#             call examples where the expected value is documented inline.
293#
294# Entry:      $text - full module source including POD
295#
296# Exit:       Returns a list of example hashrefs (each wrapping the
297#             annotated line plus the leading context, if any).
298# --------------------------------------------------
299sub _extract_annotated_lines {
300
61
40
        my $text = $_[0];
301
302
61
28
        my @examples;
303
61
47
        my $section = 'UNKNOWN';
304
305
61
2598
        for my $line (split /\n/, $text) {
306                # Track current POD section heading
307
36379
56974
                if($line =~ /^=head\d+\s+(.+)/) {
308
1166
681
                        $section = $1;
309
1166
641
                        $section =~ s/\s+$//;
310
1166
600
                        next;
311                }
312
313                # Annotated verbatim line inside POD
314
35213
21597
                next unless $line =~ $VERBATIM_RE;
315
18072
29321
                next unless $line =~ $ANNOTATION_RE;
316
317
42
132
                my $expected = $1;
318
42
38
                $expected    =~ s/\s+$//;
319
320                # Strip leading whitespace from code text
321
42
48
                (my $code = $line) =~ s/^[ \t]+//;
322
323                # Strip the annotation comment from the code
324
42
81
                (my $code_only = $code) =~ s/\s*\#\s*(?:=>|returns?)\s*.+$//;
325
42
37
                $code_only =~ s/\s+$//;
326
327
42
38
                next unless length $code_only;
328
329
25
44
                push @examples, {
330                        section        => $section,
331                        code           => $code_only,
332                        expected       => $expected,
333                        annotated_line => $code_only,
334                };
335        }
336
337
61
1058
        return @examples;
338}
339
340# --------------------------------------------------
341# _verbatim_paragraphs
342#
343# Purpose:    Split a POD text block into its indented
344#             (verbatim) paragraphs and return example hashrefs.
345#             Paragraphs that contain no Perl-looking syntax
346#             (e.g. shell commands like "prove -l t/foo.t") are
347#             silently dropped — they would cause compile errors
348#             under "use strict" in the generated test file.
349#
350# Entry:      $block   - text block to scan
351#             $section - label string for the containing section
352#
353# Exit:       Returns a list of example hashrefs with no expected value.
354# --------------------------------------------------
355sub _verbatim_paragraphs {
356
35
37
        my ($block, $section) = @_;
357
358
35
23
        my @examples;
359        my @current;
360
361
35
127
        for my $line (split /\n/, $block) {
362
1362
854
                if($line =~ $VERBATIM_RE || ($line =~ /\S/ && @current)) {
363
1232
2239
                        push @current, $line;
364                } else {
365
130
324
                        if(@current) {
366
51
51
                                my $code = _dedent(join("\n", @current));
367
51
63
                                push @examples, {
368                                        section        => $section,
369                                        code           => $code,
370                                        expected       => undef,
371                                        annotated_line => undef,
372                                } if length($code) && _looks_like_perl($code);
373
51
42
                                @current = ();
374                        }
375                }
376        }
377
378
35
58
        if(@current) {
379
33
58
                my $code = _dedent(join("\n", @current));
380
33
57
                push @examples, {
381                        section        => $section,
382                        code           => $code,
383                        expected       => undef,
384                        annotated_line => undef,
385                } if length($code) && _looks_like_perl($code);
386        }
387
388
35
287
        return @examples;
389}
390
391# --------------------------------------------------
392# _dedent
393#
394# Purpose:    Remove the common leading whitespace from every line
395#             of a verbatim block so relative indentation is kept
396#             (like Python's textwrap.dedent).
397#
398# Entry:      $text - multi-line string
399#
400# Exit:       Returns the dedented string with trailing whitespace removed.
401# --------------------------------------------------
402sub _dedent {
403
84
53
        my $text = $_[0];
404
84
114
        my @lines = split /\n/, $text;
405
84
1232
54
802
        my @non_empty = grep { /\S/ } @lines;
406
84
71
        return '' unless @non_empty;
407
1288
586
        my ($min) = sort { $a <=> $b }
408
84
1232
74
933
                    map  { /^([ \t]*)/ ? length($1) : 0 } @non_empty;
409
84
692
        s/^[ \t]{0,$min}// for @lines;
410
84
86
        my $out = join("\n", @lines);
411
84
288
        $out =~ s/\s+$//;
412
84
129
        return $out;
413}
414
415# --------------------------------------------------
416# _looks_like_perl
417#
418# Purpose:    Return true when a verbatim block contains at least one
419#             line that is recognisably Perl syntax.  Used to skip
420#             blocks of shell commands (e.g. "prove -l t/foo.t") that
421#             would cause compile errors under "use strict".
422#
423# Entry:      $code - dedented block text
424#
425# Exit:       Returns 1 (Perl) or '' (not Perl).
426# --------------------------------------------------
427sub _looks_like_perl {
428
84
52
        my $code = $_[0];
429
84
110
        for my $line (split /\n/, $code) {
430
102
105
                next unless $line =~ /\S/;    # skip blank lines
431
102
80
                next if $line =~ /^\s*#/;     # skip comment-only lines
432                # Perl sigils
433
85
176
                return 1 if $line =~ /[\$\@\%]/;
434                # Perl keywords at start of statement
435
32
75
                return 1 if $line =~ /^\s*(?:my|our|local|use|require|no|package|sub|for(?:each)?|if|unless|while|until|return|die|croak|warn|print|say|eval|BEGIN|END|push|pop|shift|unshift|keys|values|grep|map|sort)\b/;
436                # Method call or package separator
437
15
30
                return 1 if $line =~ /(?:->|::)/;
438                # Fat comma — a hash or argument list
439
12
13
                return 1 if $line =~ /=>/;
440        }
441
11
13
        return '';
442}
443
444 - 706
=head1 COMMON PITFALLS

=over 4

=item Shell-command blocks are silently dropped

Verbatim paragraphs that contain only shell commands (e.g. C<prove -l t/> or
C<extract-schemas lib/My/Module.pm>) are filtered out by C<_looks_like_perl>.
They would cause compile errors under C<use strict> in a generated test file.
If you want a shell command to appear as an example, put it in a POD comment
block, not a verbatim paragraph.

=item Annotations must be on the B<same line> as the call expression

The C<# returns> / C<< # => >> annotation is parsed as a line-level suffix.
Multi-line calls spread across multiple lines will not pick up an annotation on
the last line.  Only the last line is examined, and the call expression on
earlier lines is lost.

=item C<expected> is always a raw string

The C<expected> field is the literal text captured after C<# returns> or
C<< # => >>.  It is not evaluated or type-converted.  Downstream code that
emits C<is($result, $expected)> must handle quoting appropriately.

=item SYNOPSIS blocks from C<=head3> and deeper are not collected

Only C<=head1 SYNOPSIS> and C<=head2 SYNOPSIS> sections are scanned for
verbatim blocks.  Deeper heading levels are ignored.

=item C<new> takes a list of pairs, not a hashref

Write C<< new(file => $path) >>.  If you write C<< new({ file => $path }) >>
the file name is not seen, and C<new> croaks with C<file is required>.
Any argument other than C<file> is ignored without a warning.

=item How C<undef> is handled

=over 4

=item * C<< file => undef >> makes C<new> croak with C<file is required>.

=item * C<expected> and C<annotated_line> are C<undef> for every example
that came from a whole block.  Always test them with C<defined> before
you use them.

=item * C<label>, C<section> and C<code> are never C<undef>.

=item * A file with no examples gives an empty arrayref (C<[]>), never
C<undef>.

=back

=item Annotated lines are searched for in the whole file, not only in POD

Every indented line of the file is checked for a C<# returns ...> or
C<< # => ... >> comment.  This includes indented lines of ordinary Perl
code.  A code line such as

        return $total;    # returns the sum

is reported as an example with C<expected> set to C<the sum>.  The
C<section> of such an example is the last POD heading seen above it, or
C<UNKNOWN> if there was none.  Use a different wording in code comments
if you do not want this.

=item An annotated line inside a block is reported twice

A line with an annotation that sits inside a SYNOPSIS block appears once
as part of the whole block and once more by itself.  The two entries have
different C<code> text, so the duplicate check does not join them.

=item Each call to C<extract> reads the file again

The result is not stored in the object.  Two calls give two separate
arrayrefs.  Changing one result does not change the other.  If the file
changed on disk between the calls, the results can be different.

=back

=head1 ENCODING

The file is read as raw bytes.  Nothing is decoded.

=over 4

=item * The C<file> argument

The path is passed to the operating system unchanged.  ASCII paths
always work.  For a path with non-ASCII characters, pass it as bytes in
the encoding your file system uses (normally UTF-8).

=item * File contents

Any byte values are accepted.  UTF-8 text, other non-ASCII text and
emojis do not cause errors and are not damaged.  All the markers this
module looks for (C<=head1>, C<=for example>, C<#>, C<< => >>,
C<returns>) are ASCII, so they are found correctly in a UTF-8 file.

=item * Returned strings

C<section>, C<label>, C<code>, C<expected> and C<annotated_line> are
B<byte> strings.  If the file is UTF-8, each non-ASCII character or emoji
is still several separate bytes in the result.  Call
C<Encode::decode('UTF-8', $string)> if you need Perl character strings,
for example before you measure a length or print through a UTF-8 handle.

=item * The C<=encoding> line

It is ignored.  The module does not use it to convert anything.

=item * Line endings

Only C<\n> ends a line.  A file with Windows line endings keeps a C<\r>
inside multi-line C<code> values.

=back

=head1 LIMITATIONS

=over 4

=item No evaluation of verbatim blocks

Verbatim blocks are returned as raw code strings.  The module does not evaluate
them or check that they are syntactically valid Perl.  Blocks that are
syntactically broken will cause the downstream test file to fail to compile.

=item Deduplication is by exact C<code> text

Two examples with identical C<code> strings are deduplicated even if they come
from different sections.  If the same one-liner appears in both SYNOPSIS and a
method docstring, only the first occurrence is kept.

=back

=head1 SEE ALSO

=over 4

=item C<bin/pod-example-tester>

=item L<App::Test::Generator>

=item L<Pod::Simple>

=back

=head1 AUTHOR

Nigel Horne, C<< <njh at nigelhorne.com> >>

=head1 FORMAL SPECIFICATION

This section describes each method in Z notation.  It is for readers who
want an exact, mathematical statement.  You do not need it to use the module.

How to read it: a name ending in C<?> is an input, a name ending in C<!> is
an output, and a name ending in C<'> is the value after the call.
The symbol E<0x039E> before the state name means "this call does not change
the object".

The state of an object is one value, the path given to C<new>:

    â”Œâ”€ PodExampleExtractor ─────────────────────────────
    â”‚ file : PATH
    â”œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    â”‚ file ≠ undef
    â””───────────────────────────────────────────────────

    â”Œâ”€ Example ─────────────────────────────────────────
    â”‚ section, label, code : STRING
    â”‚ expected, annotated_line : STRING ∪ { undef }
    â”œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    â”‚ code ≠ ''
    â”‚ expected = undef ⇔ annotated_line = undef
    â”‚ annotated_line ≠ undef ⇒ annotated_line = code
    â””───────────────────────────────────────────────────

=head2 new

    â”Œâ”€ New ─────────────────────────────────────────────
    â”‚ PodExampleExtractor′
    â”‚ file? : VALUE
    â”‚ result! : PodExampleExtractor
    â”œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    â”‚ pre   file? ≠ undef ∧ file? names an existing plain file
    â”‚ post  file′ = file?
    â”‚       result! = θ PodExampleExtractor′
    â””───────────────────────────────────────────────────

    file? = undef                  â‡’ croak 'file is required'
    file? is not an existing file  â‡’ croak 'File not found: ' ⁀ file?

=head2 extract

    â”Œâ”€ Extract ─────────────────────────────────────────
    â”‚ Ξ PodExampleExtractor
    â”‚ result! : seq Example
    â”œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    â”‚ pre   file can be read
    â”‚ post  result! = synopsis blocks ⁀ 'for example' blocks
    â”‚                 â€ annotated lines, with later copies of
    â”‚                 the same code removed
    â”‚       âˆ€ i, j : dom result! •
    â”‚           i ≠ j ⇒ result!(i).code ≠ result!(j).code
    â”‚       âˆ€ e : ran result! • ∃ n : ℕ₁ •
    â”‚           e.label = e.section ⁀ ' example ' ⁀ n
    â”‚       âˆ€ i, j : dom result! •
    â”‚           i ≠ j ⇒ result!(i).label ≠ result!(j).label
    â””───────────────────────────────────────────────────

    file cannot be read  â‡’ croak (message from File::Slurp)

=head1 STATE DIAGRAM

An object of this class has only one working state.  It is created ready
to use and it never changes afterwards.

                         new(file => undef)
                         new(file => path that does not exist)
                       +------------------------------+
                       |  action: croak, no object    |
                       v                              |
                +-------------+                       |
                |  NO OBJECT  |-----------------------+
                +-------------+
                       |
                       | new(file => existing file)
                       | action: remember the path (file is not read)
                       v
                +-------------+   extract()  [file can be read]
                |             |---------------------------------+
                |    READY    |   action: read the file,        |
                |             |   return a new list of examples |
                |             |<--------------------------------+
                |             |
                |             |   extract()  [file removed or
                |             |               not readable]
                |             |---------------------------------+
                |             |   action: croak, nothing changes|
                |             |<--------------------------------+
                +-------------+
                       |
                       | last reference goes away
                       | action: Perl frees the object
                       v
                +-------------+
                |    GONE     |
                +-------------+

Side effects: C<extract> opens the file for reading and closes it again
before it returns.  No method writes to disk or prints anything.

=head1 LICENCE AND COPYRIGHT

Copyright 2026 Nigel Horne.

Usage is subject to the terms of GPL2.
If you use it,
please let me know.

=cut
707
7081;