#!/usr/bin/perl

use v5.10;
use utf8;
use strict;
use warnings;

use TAP::Parser;

=head1 NAME

tap-todo - TAP filter to tolerate select failures

=head1 VERSION

Version v0.1.0

=cut

our $VERSION = version->declare("v0.1.0");

=head1 SYNOPSIS

B<prove --lib> | B<tap-todo> "B<is a foo>" "B<does.* do bar::reason: baz.*>"

Feed the origina TAP data as STDIN,
and apply skip strings for failing tests that should be demoted to TODOs.

Each skip string contains a regular expression for the description,
and optionally, delimited by "::", a regular expression for YAML content.

=head1 DESCRIPTION

B<tap-todo> filters the output of TAP tests
and flags select (otherwise) failing tests as TODO.

=cut

#my %skip = map { split( /\b::\b/, $_, 2 ) } @ARGV;
my %skip = map { my ( $desc, $yaml ) = split /\b::\b/; $desc => $yaml } @ARGV;
open my $fh, "<&STDIN";
my $parser = TAP::Parser->new( { source => $fh } );

my $yaml;
my $todo = 0;
while ( my $res = $parser->next ) {
	if ( $res->is_test ) {
		$yaml = undef;
		unless ( $res->is_ok ) {
			while ( grep { $res->as_string =~ /$_/ } keys %skip ) {
				if ( $skip{$_} ) {
					$yaml = $skip{$_};
				}
				else {
					$todo++;
					print "# TODO: ";
				}
				last;
			}
		}
	}
	if ( $res->is_yaml and $yaml and $res->as_string =~ /$yaml/s ) {
		$todo++;
		print "# TODO: ";
	}
	say $res->as_string;
}
say "# skipped $todo/", 0 + @ARGV;

exit( $parser->tests_run - $parser->passed - $todo );

=head1 AUTHOR

Jonas Smedegaard C<< <dr@jones.dk> >>

=head1 COPYRIGHT AND LICENSE

  Copyright © 2020 Jonas Smedegaard

  Copyright © 2020 Purism SPC

This program is free software:
you can redistribute it and/or modify it
under the terms of the GNU General Public License
as published by the Free Software Foundation,
either version 3, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY;
without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.

You should have received a copy
of the GNU General Public License along with this program.
If not, see <https://www.gnu.org/licenses/>.

=cut
