<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package Test2::Formatter::TAP;
use strict;
use warnings;

our $VERSION = '1.302194';

use Test2::Util qw/clone_io/;

use Test2::Util::HashBase qw{
    no_numbers handles _encoding _last_fh
    -made_assertion
};

sub OUT_STD() { 0 }
sub OUT_ERR() { 1 }

BEGIN { require Test2::Formatter; our @ISA = qw(Test2::Formatter) }

my $supports_tables;
sub supports_tables {
    if (!defined $supports_tables) {
        local $SIG{__DIE__} = 'DEFAULT';
        local $@;
        $supports_tables
            = ($INC{'Term/Table.pm'} &amp;&amp; $INC{'Term/Table/Util.pm'})
            || eval { require Term::Table; require Term::Table::Util; 1 }
            || 0;
    }
    return $supports_tables;
}

sub _autoflush {
    my($fh) = pop;
    my $old_fh = select $fh;
    $| = 1;
    select $old_fh;
}

_autoflush(\*STDOUT);
_autoflush(\*STDERR);

sub hide_buffered { 1 }

sub init {
    my $self = shift;

    $self-&gt;{+HANDLES} ||= $self-&gt;_open_handles;
    if(my $enc = delete $self-&gt;{encoding}) {
        $self-&gt;encoding($enc);
    }
}

sub _open_handles {
    my $self = shift;

    require Test2::API;
    my $out = clone_io(Test2::API::test2_stdout());
    my $err = clone_io(Test2::API::test2_stderr());

    _autoflush($out);
    _autoflush($err);

    return [$out, $err];
}

sub encoding {
    my $self = shift;

    if ($] ge "5.007003" and @_) {
        my ($enc) = @_;
        my $handles = $self-&gt;{+HANDLES};

        # https://rt.perl.org/Public/Bug/Display.html?id=31923
        # If utf8 is requested we use ':utf8' instead of ':encoding(utf8)' in
        # order to avoid the thread segfault.
        if ($enc =~ m/^utf-?8$/i) {
            binmode($_, ":utf8") for @$handles;
        }
        else {
            binmode($_, ":encoding($enc)") for @$handles;
        }
        $self-&gt;{+_ENCODING} = $enc;
    }

    return $self-&gt;{+_ENCODING};
}

if ($^C) {
    no warnings 'redefine';
    *write = sub {};
}
sub write {
    my ($self, $e, $num, $f) = @_;

    # The most common case, a pass event with no amnesty and a normal name.
    return if $self-&gt;print_optimal_pass($e, $num);

    $f ||= $e-&gt;facet_data;

    $self-&gt;encoding($f-&gt;{control}-&gt;{encoding}) if $f-&gt;{control}-&gt;{encoding};

    my @tap = $self-&gt;event_tap($f, $num) or return;

    $self-&gt;{+MADE_ASSERTION} = 1 if $f-&gt;{assert};

    my $nesting = $f-&gt;{trace}-&gt;{nested} || 0;
    my $handles = $self-&gt;{+HANDLES};
    my $indent = '    ' x $nesting;

    # Local is expensive! Only do it if we really need to.
    local($\, $,) = (undef, '') if $\ || $,;
    for my $set (@tap) {
        no warnings 'uninitialized';
        my ($hid, $msg) = @$set;
        next unless $msg;
        my $io = $handles-&gt;[$hid] or next;

        print $io "\n"
            if $ENV{HARNESS_ACTIVE}
            &amp;&amp; $hid == OUT_ERR
            &amp;&amp; $self-&gt;{+_LAST_FH} != $io
            &amp;&amp; $msg =~ m/^#\s*Failed( \(TODO\))? test /;

        $msg =~ s/^/$indent/mg if $nesting;
        print $io $msg;
        $self-&gt;{+_LAST_FH} = $io;
    }
}

sub print_optimal_pass {
    my ($self, $e, $num) = @_;

    my $type = ref($e);

    # Only optimal if this is a Pass or a passing Ok
    return unless $type eq 'Test2::Event::Pass' || ($type eq 'Test2::Event::Ok' &amp;&amp; $e-&gt;{pass});

    # Amnesty requires further processing (todo is a form of amnesty)
    return if ($e-&gt;{amnesty} &amp;&amp; @{$e-&gt;{amnesty}}) || defined($e-&gt;{todo});

    # A name with a newline or hash symbol needs extra processing
    return if defined($e-&gt;{name}) &amp;&amp; (-1 != index($e-&gt;{name}, "\n") || -1 != index($e-&gt;{name}, '#'));

    my $ok = 'ok';
    $ok .= " $num" if $num &amp;&amp; !$self-&gt;{+NO_NUMBERS};
    $ok .= defined($e-&gt;{name}) ? " - $e-&gt;{name}\n" : "\n";

    if (my $nesting = $e-&gt;{trace}-&gt;{nested}) {
        my $indent = '    ' x $nesting;
        $ok = "$indent$ok";
    }

    my $io = $self-&gt;{+HANDLES}-&gt;[OUT_STD];

    local($\, $,) = (undef, '') if $\ || $,;
    print $io $ok;
    $self-&gt;{+_LAST_FH} = $io;

    return 1;
}

sub event_tap {
    my ($self, $f, $num) = @_;

    my @tap;

    # If this IS the first event the plan should come first
    # (plan must be before or after assertions, not in the middle)
    push @tap =&gt; $self-&gt;plan_tap($f) if $f-&gt;{plan} &amp;&amp; !$self-&gt;{+MADE_ASSERTION};

    # The assertion is most important, if present.
    if ($f-&gt;{assert}) {
        push @tap =&gt; $self-&gt;assert_tap($f, $num);
        push @tap =&gt; $self-&gt;debug_tap($f, $num) unless $f-&gt;{assert}-&gt;{no_debug} || $f-&gt;{assert}-&gt;{pass};
    }

    # Almost as important as an assertion
    push @tap =&gt; $self-&gt;error_tap($f) if $f-&gt;{errors};

    # Now lets see the diagnostics messages
    push @tap =&gt; $self-&gt;info_tap($f) if $f-&gt;{info};

    # If this IS NOT the first event the plan should come last
    # (plan must be before or after assertions, not in the middle)
    push @tap =&gt; $self-&gt;plan_tap($f) if $self-&gt;{+MADE_ASSERTION} &amp;&amp; $f-&gt;{plan};

    # Bail out
    push @tap =&gt; $self-&gt;halt_tap($f) if $f-&gt;{control}-&gt;{halt};

    return @tap if @tap;
    return @tap if $f-&gt;{control}-&gt;{halt};
    return @tap if grep { $f-&gt;{$_} } qw/assert plan info errors/;

    # Use the summary as a fallback if nothing else is usable.
    return $self-&gt;summary_tap($f, $num);
}

sub error_tap {
    my $self = shift;
    my ($f) = @_;

    my $IO = ($f-&gt;{amnesty} &amp;&amp; @{$f-&gt;{amnesty}}) ? OUT_STD : OUT_ERR;

    return map {
        my $details = $_-&gt;{details};

        my $msg;
        if (ref($details)) {
            require Data::Dumper;
            my $dumper = Data::Dumper-&gt;new([$details])-&gt;Indent(2)-&gt;Terse(1)-&gt;Pad('# ')-&gt;Useqq(1)-&gt;Sortkeys(1);
            chomp($msg = $dumper-&gt;Dump);
        }
        else {
            chomp($msg = $details);
            $msg =~ s/^/# /;
            $msg =~ s/\n/\n# /g;
        }

        [$IO, "$msg\n"];
    } @{$f-&gt;{errors}};
}

sub plan_tap {
    my $self = shift;
    my ($f) = @_;
    my $plan = $f-&gt;{plan} or return;

    return if $plan-&gt;{none};

    if ($plan-&gt;{skip}) {
        my $reason = $plan-&gt;{details} or return [OUT_STD, "1..0 # SKIP\n"];
        chomp($reason);
        return [OUT_STD, '1..0 # SKIP ' . $reason . "\n"];
    }

    return [OUT_STD, "1.." . $plan-&gt;{count} . "\n"];
}

sub no_subtest_space { 0 }
sub assert_tap {
    my $self = shift;
    my ($f, $num) = @_;

    my $assert = $f-&gt;{assert} or return;
    my $pass = $assert-&gt;{pass};
    my $name = $assert-&gt;{details};

    my $ok = $pass ? 'ok' : 'not ok';
    $ok .= " $num" if $num &amp;&amp; !$self-&gt;{+NO_NUMBERS};

    # The regex form is ~250ms, the index form is ~50ms
    my @extra;
    defined($name) &amp;&amp; (
        (index($name, "\n") != -1 &amp;&amp; (($name, @extra) = split(/\n\r?/, $name, -1))),
        ((index($name, "#" ) != -1  || substr($name, -1) eq '\\') &amp;&amp; (($name =~ s|\\|\\\\|g), ($name =~ s|#|\\#|g)))
    );

    my $extra_space = @extra ? ' ' x (length($ok) + 2) : '';
    my $extra_indent = '';

    my ($directives, $reason, $is_skip);
    if ($f-&gt;{amnesty}) {
        my %directives;

        for my $am (@{$f-&gt;{amnesty}}) {
            next if $am-&gt;{inherited};
            my $tag = $am-&gt;{tag} or next;
            $is_skip = 1 if $tag eq 'skip';

            $directives{$tag} ||= $am-&gt;{details};
        }

        my %seen;

        # Sort so that TODO comes before skip even on systems where lc sorts
        # before uc, as other code depends on that ordering.
        my @order = grep { !$seen{$_}++ } sort { lc $b cmp lc $a } keys %directives;

        $directives = ' # ' . join ' &amp; ' =&gt; @order;

        for my $tag ('skip', @order) {
            next unless defined($directives{$tag}) &amp;&amp; length($directives{$tag});
            $reason = $directives{$tag};
            last;
        }
    }

    $ok .= " - $name" if defined $name &amp;&amp; !($is_skip &amp;&amp; !$name);

    my @subtap;
    if ($f-&gt;{parent} &amp;&amp; $f-&gt;{parent}-&gt;{buffered}) {
        $ok .= ' {';

        # In a verbose harness we indent the extra since they will appear
        # inside the subtest braces. This helps readability. In a non-verbose
        # harness we do not do this because it is less readable.
        if ($ENV{HARNESS_IS_VERBOSE} || !$ENV{HARNESS_ACTIVE}) {
            $extra_indent = "    ";
            $extra_space = ' ';
        }

        # Render the sub-events, we use our own counter for these.
        my $count = 0;
        @subtap = map {
            my $f2 = $_;

            # Bump the count for any event that should bump it.
            $count++ if $f2-&gt;{assert};

            # This indents all output lines generated for the sub-events.
            # index 0 is the filehandle, index 1 is the message we want to indent.
            map { $_-&gt;[1] =~ s/^(.*\S.*)$/    $1/mg; $_ } $self-&gt;event_tap($f2, $count);
        } @{$f-&gt;{parent}-&gt;{children}};

        push @subtap =&gt; [OUT_STD, "}\n"];
    }

    if ($directives) {
        $directives = ' # TODO &amp; SKIP' if $directives eq ' # TODO &amp; skip';
        $ok .= $directives;
        $ok .= " $reason" if defined($reason);
    }

    $extra_space = ' ' if $self-&gt;no_subtest_space;

    my @out = ([OUT_STD, "$ok\n"]);
    push @out =&gt; map {[OUT_STD, "${extra_indent}#${extra_space}$_\n"]} @extra if @extra;
    push @out =&gt; @subtap;

    return @out;
}

sub debug_tap {
    my ($self, $f, $num) = @_;

    # Figure out the debug info, this is typically the file name and line
    # number, but can also be a custom message. If no trace object is provided
    # then we have nothing useful to display.
    my $name  = $f-&gt;{assert}-&gt;{details};
    my $trace = $f-&gt;{trace};

    my $debug = "[No trace info available]";
    if ($trace-&gt;{details}) {
        $debug = $trace-&gt;{details};
    }
    elsif ($trace-&gt;{frame}) {
        my ($pkg, $file, $line) = @{$trace-&gt;{frame}};
        $debug = "at $file line $line." if $file &amp;&amp; $line;
    }

    my $amnesty = $f-&gt;{amnesty} &amp;&amp; @{$f-&gt;{amnesty}}
        ? ' (with amnesty)'
        : '';

    # Create the initial diagnostics. If the test has a name we put the debug
    # info on a second line, this behavior is inherited from Test::Builder.
    my $msg = defined($name)
        ? qq[# Failed test${amnesty} '$name'\n# $debug\n]
        : qq[# Failed test${amnesty} $debug\n];

    my $IO = $f-&gt;{amnesty} &amp;&amp; @{$f-&gt;{amnesty}} ? OUT_STD : OUT_ERR;

    return [$IO, $msg];
}

sub halt_tap {
    my ($self, $f) = @_;

    return if $f-&gt;{trace}-&gt;{nested} &amp;&amp; !$f-&gt;{trace}-&gt;{buffered};
    my $details = $f-&gt;{control}-&gt;{details};

    return [OUT_STD, "Bail out!\n"] unless defined($details) &amp;&amp; length($details);
    return [OUT_STD, "Bail out!  $details\n"];
}

sub info_tap {
    my ($self, $f) = @_;

    return map {
        my $details = $_-&gt;{details};
        my $table   = $_-&gt;{table};

        my $IO = $_-&gt;{debug} &amp;&amp; !($f-&gt;{amnesty} &amp;&amp; @{$f-&gt;{amnesty}}) ? OUT_ERR : OUT_STD;

        my $msg;
        if ($table &amp;&amp; $self-&gt;supports_tables) {
            $msg = join "\n" =&gt; map { "# $_" } Term::Table-&gt;new(
                header      =&gt; $table-&gt;{header},
                rows        =&gt; $table-&gt;{rows},
                collapse    =&gt; $table-&gt;{collapse},
                no_collapse =&gt; $table-&gt;{no_collapse},
                sanitize    =&gt; 1,
                mark_tail   =&gt; 1,
                max_width   =&gt; $self-&gt;calc_table_size($f),
            )-&gt;render();
        }
        elsif (ref($details)) {
            require Data::Dumper;
            my $dumper = Data::Dumper-&gt;new([$details])-&gt;Indent(2)-&gt;Terse(1)-&gt;Pad('# ')-&gt;Useqq(1)-&gt;Sortkeys(1);
            chomp($msg = $dumper-&gt;Dump);
        }
        else {
            chomp($msg = $details);
            $msg =~ s/^/# /;
            $msg =~ s/\n/\n# /g;
        }

        [$IO, "$msg\n"];
    } @{$f-&gt;{info}};
}

sub summary_tap {
    my ($self, $f, $num) = @_;

    return if $f-&gt;{about}-&gt;{no_display};

    my $summary = $f-&gt;{about}-&gt;{details} or return;
    chomp($summary);
    $summary =~ s/^/# /smg;

    return [OUT_STD, "$summary\n"];
}

sub calc_table_size {
    my $self = shift;
    my ($f) = @_;

    my $term = Term::Table::Util::term_size();
    my $nesting = 2 + (($f-&gt;{trace}-&gt;{nested} || 0) * 4); # 4 spaces per level, also '# ' prefix
    my $total = $term - $nesting;

    # Sane minimum width, any smaller and we are asking for pain
    return 50 if $total &lt; 50;

    return $total;
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Test2::Formatter::TAP - Standard TAP formatter

=head1 DESCRIPTION

This is what takes events and turns them into TAP.

=head1 SYNOPSIS

    use Test2::Formatter::TAP;
    my $tap = Test2::Formatter::TAP-&gt;new();

    # Switch to utf8
    $tap-&gt;encoding('utf8');

    $tap-&gt;write($event, $number); # Output an event

=head1 METHODS

=over 4

=item $bool = $tap-&gt;no_numbers

=item $tap-&gt;set_no_numbers($bool)

Use to turn numbers on and off.

=item $arrayref = $tap-&gt;handles

=item $tap-&gt;set_handles(\@handles);

Can be used to get/set the filehandles. Indexes are identified by the
C&lt;OUT_STD&gt; and C&lt;OUT_ERR&gt; constants.

=item $encoding = $tap-&gt;encoding

=item $tap-&gt;encoding($encoding)

Get or set the encoding. By default no encoding is set, the original settings
of STDOUT and STDERR are used.

This directly modifies the stored filehandles, it does not create new ones.

=item $tap-&gt;write($e, $num)

Write an event to the console.

=back

=head1 SOURCE

The source code repository for Test2 can be found at
F&lt;http://github.com/Test-More/test-more/&gt;.

=head1 MAINTAINERS

=over 4

=item Chad Granum E&lt;lt&gt;exodist@cpan.orgE&lt;gt&gt;

=back

=head1 AUTHORS

=over 4

=item Chad Granum E&lt;lt&gt;exodist@cpan.orgE&lt;gt&gt;

=item Kent Fredric E&lt;lt&gt;kentnl@cpan.orgE&lt;gt&gt;

=back

=head1 COPYRIGHT

Copyright 2020 Chad Granum E&lt;lt&gt;exodist@cpan.orgE&lt;gt&gt;.

This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

See F&lt;http://dev.perl.org/licenses/&gt;

=cut
</pre></body></html>