summaryrefslogtreecommitdiffstats
path: root/lib/Test/Lintian/Filter.pm
blob: 4b6ea8aa31573d88bc176da8e263698679a21ee0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# Copyright (C) 2020 Felix Lechner
#
# 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 2 of the License, 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, you can find it on the World Wide
# Web at https://www.gnu.org/copyleft/gpl.html, or write to the Free
# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
# MA 02110-1301, USA.

package Test::Lintian::Filter;

=head1 NAME

Test::Lintian::Filter -- Functions to select with tests to run

=head1 SYNOPSIS

  use Test::Lintian::Filter qw(find_selected_lintian_testpaths);
  my @testpaths = find_selected_lintian_testpaths('suite:changes');

=head1 DESCRIPTION

Functions that parse the optional argument 'only_run' to find the
tests that are supposed to run.

=cut

use v5.20;
use warnings;
use utf8;

use Exporter qw(import);

BEGIN {
    our @EXPORT_OK = qw(
      find_selected_scripts
      find_selected_lintian_testpaths
    );
}

use Carp;
use Const::Fast;
use File::Spec::Functions qw(rel2abs splitpath catpath);
use File::Find::Rule;
use List::SomeUtils qw(uniq none);
use List::Util qw(any all);
use Path::Tiny;
use Text::CSV;
use Unicode::UTF8 qw(encode_utf8);

use Lintian::Profile;
use Test::Lintian::ConfigFile qw(read_config);

my @LINTIAN_SUITES = qw(recipes);

const my $EMPTY => q{};
const my $SPACE => q{ };
const my $VERTICAL_BAR => q{|};
const my $DESC => 'desc';
const my $SEPARATED_BY_COLON => qr/([^:]+):([^:]+)/;

=head1 FUNCTIONS

=over 4

=item get_suitepath(TEST_SET, SUITE)

Returns a string containing all test belonging to suite SUITE relative
to path TEST_SET.

=cut

sub get_suitepath {
    my ($basepath, $suite) = @_;
    my $suitepath = rel2abs($suite, $basepath);

    croak encode_utf8("Cannot find suite $suite in $basepath")
      unless -d $suitepath;

    return $suitepath;
}

=item find_selected_scripts(SCRIPT_PATH, ONLY_RUN)

Find all test scripts in SCRIPT_PATH that are identified by the
user's selection string ONLY_RUN.

=cut

sub find_selected_scripts {
    my ($scriptpath, $onlyrun) = @_;

    my @found;

    my @selectors = split(m/\s*,\s*/, $onlyrun//$EMPTY);

    if ((any { $_ eq 'suite:scripts' } @selectors) || !length $onlyrun) {
        @found = File::Find::Rule->file()->name('*.t')->in($scriptpath);
    } else {
        foreach my $selector (@selectors) {
            my ($prefix, $lookfor) = ($selector =~ /$SEPARATED_BY_COLON/);

            next if defined $prefix && $prefix ne 'script';
            $lookfor = $selector unless defined $prefix;

            # look for files with the standard suffix
            my $withsuffix = rel2abs("$lookfor.t", $scriptpath);
            push(@found, $withsuffix) if -e $withsuffix;

            # look for script with exact name
            my $exactpath = rel2abs($lookfor, $scriptpath);
            push(@found, $exactpath) if -e $exactpath;

            # also add entire directory if name matches
            push(@found, File::Find::Rule->file()->name('*.t')->in($exactpath))
              if -d $exactpath;
        }
    }

    my @sorted = sort +uniq @found;

    return @sorted;
}

=item find_selected_lintian_testpaths(TEST_SET, ONLY_RUN)

Find all those test paths with Lintian tests located in the directory
TEST_SET and identified by the user's selection string ONLY_RUN.

=cut

sub find_selected_lintian_testpaths {

    my ($testset, $onlyrun) = @_;

    my $filter = {
        'tag' => [],
        'suite' => [],
        'test' => [],
        'check' => [],
        'skeleton' => [],
    };
    my @filter_no_prefix;

    if (!length $onlyrun) {
        $filter->{suite} = [@LINTIAN_SUITES];
    } else {

        my @selectors = split(m/\s*,\s*/, $onlyrun);

        foreach my $selector (@selectors) {

            foreach my $wanted (keys %{$filter}) {
                my ($prefix, $lookfor) = ($selector =~ /$SEPARATED_BY_COLON/);

                next if defined $prefix && $prefix ne $wanted;

                push(@{$filter->{$wanted}}, $lookfor) if length $lookfor;
                push(@filter_no_prefix, $selector) unless length $lookfor;
            }
        }
    }

    my $profile = Lintian::Profile->new;
    $profile->load(undef, undef, 0);

    my @found;
    foreach my $suite (sort @LINTIAN_SUITES) {

        my @insuite;
        my $suitepath = get_suitepath($testset, $suite);

        # find all tests for selected suites
        if (any { $_ eq $suite } @{$filter->{suite}}) {
            push(@insuite, find_all_testpaths($suitepath));
        }

        # find explicitly selected tests
        foreach my $testname (@{$filter->{test}}) {
            my @withtests = find_testpaths_by_name($suitepath, $testname);
            push(@insuite, @withtests);
        }

        # find tests for selected checks and tags
        if (scalar @{$filter->{check}} || scalar @{$filter->{tag}}) {

            my %wanted = map { $_ => 1 } @{$filter->{check}};

            for my $tag_name (@{$filter->{tag}}) {

                my $tag = $profile->get_tag($tag_name);
                unless ($tag) {
                    say encode_utf8("Tag $tag_name not found");
                    return ();
                }

                if (none { $tag_name eq $_ } $profile->enabled_tags) {
                    say encode_utf8("Tag $tag_name not enabled");
                    return ();
                }

                $wanted{$tag->check} = 1;
            }

            for my $testpath (find_all_testpaths($suitepath)) {
                my $desc = read_config("$testpath/eval/" . $DESC);

                next
                  unless $desc->declares('Check');

                for my $check ($desc->trimmed_list('Check')) {
                    push(@insuite, $testpath)
                      if exists $wanted{$check};
                }
            }
        }

        # find tests for selected skeleton
        if (scalar @{$filter->{skeleton}}) {

            my %wanted = map { $_ => 1 } @{$filter->{skeleton}};

            for my $testpath (find_all_testpaths($suitepath)) {
                my $desc = read_config("$testpath/build-spec/fill-values");

                next
                  unless $desc->declares('Skeleton');

                my $skeleton = $desc->unfolded_value('Skeleton');
                push(@insuite, $testpath)
                  if exists $wanted{$skeleton};
            }
        }

        # guess what was meant by selection without prefix
        for my $parameter (@filter_no_prefix) {
            push(@insuite,find_testpaths_by_name($suitepath, $parameter));

            if ($parameter eq 'legacy'
                || exists $profile->check_module_by_name->{$parameter}) {

                push(@insuite,
                    find_testpaths_by_name($suitepath, "$parameter-*"));
            }
        }

        push(@found, sort +uniq @insuite);
    }

    return @found;
}

=item find_all_testpaths(PATH)

Returns an array containing all test paths located under PATH. They
are identified as test paths by a specially named file containing
the test description (presently 'desc').

=cut

sub find_all_testpaths {
    my ($directory) = @_;
    my @descfiles = File::Find::Rule->file()->name($DESC)->in($directory);

    my @testpaths= map { path($_)->parent->parent->stringify }@descfiles;

    return @testpaths;
}

=item find_testpaths_by_name(PATH, NAME)

Returns an array containing all test paths with the name NAME
located under PATH. The test paths are identified as such
by a specially named file containing the test description
(presently 'desc').

=cut

sub find_testpaths_by_name {
    my ($path, $name) = @_;

    my @named = File::Find::Rule->directory()->name($name)->in($path);
    my @testpaths= grep { defined }
      map { -e rel2abs('eval/' . $DESC, $_) ? $_ : undef } @named;

    return @testpaths;
}

=item find_all_tags(TEST_PATH)

Returns an array containing all tags that somehow concern the test
located in TEST_PATH.

=cut

sub find_all_tags {
    my ($testpath) = @_;

    my $desc = read_config("$testpath/eval/" . $DESC);

    return $EMPTY
      unless $desc->declares('Check');

    my $profile = Lintian::Profile->new;
    $profile->load(undef, undef, 0);

    my @check_names = $desc->trimmed_list('Check');
    my @unknown
      = grep { !exists $profile->check_module_by_name->{$_} } @check_names;

    die encode_utf8('Unknown Lintian checks: ' . join($SPACE, @unknown))
      if @unknown;

    my %tags;
    for my $name (@check_names) {
        $tags{$_} = 1 for @{$profile->tag_names_for_check->{$name}};
    }

    return keys %tags
      unless $desc->declares('Test-Against');

    # read hints from specification
    my $temp = Path::Tiny->tempfile;
    die encode_utf8("hintextract failed: $!")
      if system('private/hintextract', '-f', 'EWI', "$testpath/hints",
        $temp->stringify);
    my @lines = $temp->lines_utf8({ chomp => 1 });

    my $csv = Text::CSV->new({ sep_char => $VERTICAL_BAR });

    my %expected;
    foreach my $line (@lines) {

        my $status = $csv->parse($line);
        die encode_utf8("Cannot parse line $line: " . $csv->error_diag)
          unless $status;

        my ($type, $package, $name, $details) = $csv->fields;

        die encode_utf8("Cannot parse line $line")
          unless all { length } ($type, $package, $name);

        $expected{$name} = 1;
    }

    # remove tags not appearing in specification
    foreach my $name (keys %tags) {
        delete $tags{$name}
          unless $expected{$name};
    }

    # add tags listed in Test-Against
    my @test_against = $desc->trimmed_list('Test-Against');
    $tags{$_} = 1 for @test_against;

    return keys %tags;
}

=back

=cut

1;

# Local Variables:
# indent-tabs-mode: nil
# cperl-indent-level: 4
# End:
# vim: syntax=perl sw=4 sts=4 sr et