This file is indexed.

/usr/share/perl5/Dpkg/Copyright/Scanner.pm is in libconfig-model-dpkg-perl 2.105.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
package Dpkg::Copyright::Scanner ;

use strict;
use warnings;

use 5.20.0;
use IO::Pipe;
use Exporter::Lite;
use Array::IntSpan;
use Path::Tiny;
use Carp;
use YAML::Tiny;

use feature qw/postderef signatures/;
no warnings qw/experimental::postderef experimental::signatures/;

binmode STDOUT, ':utf8';

our @EXPORT = qw(scan_files print_copyright);

my $whitespace_list_delimiter = $ENV{'whitespace_list_delimiter'} || "\n ";

# license and copyright sanitisation pilfered from Jonas's
# licensecheck2dep5 Originally GPL-2+, permission to license this
# derivative work to LGPL-2.1+ was given by Jonas.
# see https://lists.alioth.debian.org/pipermail/pkg-perl-maintainers/2015-March/084900.html

# Copyright 2014 Dominique Dumont <dod@debian.org>
# Copyright © 2005-2012 Jonas Smedegaard <dr@jones.dk>
# Description: Reformat licencecheck output to copyright file format
#
# 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, 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, see <http://www.gnu.org/licenses/>.

sub print_copyright ( %args ) {
    my ($files, $copyrights_by_id) = scan_files(%args);

    # split file path and fill recursive hash, leaf is id
    my $split_files = {};
    foreach my $path (sort keys %$files) {
        __create_tree_leaf_from_paths ($split_files,$path,$files->{$path});
    }

    # regroup %files hash: all leaves have same id -> wild card
    __squash($split_files);

    # pack files by copyright id
    my @packed = __pack_files($split_files);

    my @out ;

    foreach my $p (@packed) {
        my ($id, @paths) = $p->@*;
        my ($c,$l) = $copyrights_by_id->[$id]->@*;

        next if $id == 0;

        # don't print directory info covered by same info in directory above
        next if $paths[0] =~ /\.$/;

        $c = "UNKNOWN" unless $c;
        push @out,
            "Files: ", join($whitespace_list_delimiter, @paths )."\n",
            "Copyright: $c\n",
            "License: $l\n", "\n";
    }

    if ($args{out}) {
        $args{out}->spew_utf8( @out);
    }
    else {
        binmode(STDOUT, ":utf8");
        print @out;
    }
}

my $quiet;

sub _warn ($msg) {
    warn $msg unless $quiet;
}

my %default ;
# from licensecheck.pl
$default{ignore}= << 'EOR';
# Ignore general backup files
~$|
# Ignore emacs recovery files
(?:^|/)\.#|
# Ignore vi swap files
(?:^|/)\..*\.swp$|
# Ignore baz-style junk files or directories
(?:^|/),,.*(?:$|/.*$)|
# File-names that should be ignored (never directories)
(?:^|/)(?:DEADJOE|\.cvsignore|\.arch-inventory|\.bzrignore|\.gitignore)$|
# File or directory names that should be ignored
(?:^|/)(?:CVS|RCS|\.pc|\.deps|\{arch\}|\.arch-ids|\.svn|\.hg|_darcs|\.git|
\.shelf|_MTN|\.bzr(?:\.backup|tags)?)(?:$|/.*$)|
# skip debian files that are too confusing or too short
(?:^|/)debian/((fix.scanned.)?copyright|changelog|NEWS|compat|.*yml|docs|source|patches/series)
EOR

# also from licensecheck
$default{check} = << 'EOR2' ;
    (^|/)\w+$                 # scripts, AUTHORS files
    |^README                   # README.* files
    |\.(                          # search for file suffix
        c(c|pp|xx)?              # c and c++
       |h(h|pp|xx)?              # header files for c and c++
       |S
       |css|less                 # HTML css and similar
       |f(77|90)?
       |go
       |groovy
       |in|am                    # file to pre-process
       |m4
       |\d                       # man pages
       |lisp
       |scala
       |clj
       |p(l|m)?6?|t|xs|pod6?     # perl5 or perl6
       |sh
       |php
       |py(|x)
       |rb
       |java
       |js
       |vala
       |el
       |sc(i|e)
       |cs
       |pas
       |inc
       |dtd|xsl
       |mod
       |m
       |md|markdown
       |tex
       |mli?
       |(c|l)?hs
     )
    $
EOR2

# cleanup the regexp
map { s/#.*\n//g;  s/[\s\n]+//g; } values %default;

# option to skip UNKNOWN ?
# load a file to override some entries ?
sub scan_files ( %args ) {

    $quiet = $args{quiet} // 0;

    my $current_dir = $args{from_dir} || path('.');

    my %regexps = %default; # default is needed during tests 
    my @lines ;
    if (my $file = $ENV{COPYRIGHT_SCANNER_INPUT}) {
        @lines = path($file)->lines_utf8 ; # for tests
    }
    elsif ($args{in}) {
        @lines = $args{in}->lines_utf8; # for other tests
    }
    else {
        my $scan_data = {};
        my $debian = $current_dir->child('debian');
        my $scan_patterns = $debian->child("copyright-scan-patterns.yml");

        if ($debian->is_dir and $scan_patterns->is_file) {
            my $yaml = $scan_patterns->slurp_utf8;
            # { check => { suffixes => [ js pl ], pattern => '[A-Z]*'}, ignore => { suffixes => [ jpg png ], pattern => 'foo.*'} }
            $scan_data = Load $yaml;
        }

        # licensecheck --check is broken ( #842368 ), so --skipped option is useless.
        # let's scan everything and skip later
        foreach my $what (qw/check ignore/) {
            my $data = $scan_data->{$what} or next;
            my $reg = join(
                '|' ,
                (map { '\.'.$_.'$'} @{$data->{suffixes} || []}),
                @{ $data->{pattern} || []},
                $default{$what}
            );
            $regexps{$what} = qr/$reg/;
        }

        my $pipe = IO::Pipe->new();
        my @cmd = (qw/licensecheck --encoding utf8 --copyright --machine --deb-fmt --recursive/,
                   '--ignore='.$regexps{ignore}, '.');
        $pipe->reader(@cmd);
        binmode($pipe, ":encoding(UTF-8)");
        @lines = $pipe->getlines;
        $pipe->close;
    }

    my $fill_blank_data = __load_fill_blank_data($current_dir);

    my %copyrights ;
    my $files = {};
    my $id = 1;
    my @no_info_list;
    my @skipped;

    foreach my $line (sort @lines) {
        chomp $line;
        # say "found: $line";
        my ($f,$l,$c) = split /\t/, $line;
        $f =~ s!\./!!;
        next if $files->{$f}; # file already parsed

        # skip copyright because there's no need to have recursive copyrights
        # skip changelog because it's often contains log entries beginning with copyright
        # and it's a collective work by nature.
        next if $f =~  m!debian/(copyright|changelog)!;

        # filter out files user does not want checked
        if ( $f !~ $regexps{check} ) {
            # the ignore test should not be usefull as the files are ignored by licensecheck
            push @skipped, $f unless $f =~ $regexps{ignore};
            next;
        }

        # $l =~ s/([*?\\])/\\$1/g;
        # $l =~ s/\s*\(unversioned\/unknown version\)//g;
        # $l =~ s/\s*\(with incorrect FSF address\)//g;
        # $l =~ s/(\w+)\s+\(v([^)]+) or v([^)]+)\)/uc($1)."-$2 or ".uc($1)."-$3"/eg;
        # $l =~ s/\s+\(v([^)]+) or later\)/-$1+/g;
        # $l =~ s/\s+\(v([^)]+)\)/-$1/g;
        # $l =~ s/^\s*(GENERATED FILE)/UNKNOWN/g;
        # $l =~ s/\s+(GENERATED FILE)//g;
        # $l =~ s/\bzlib\/libpng\b/Zlib/g;
        # $l =~ s/\bMIT\/X11 \(BSD like\)/Expat/g;
        # $l =~ s/\bBSD \((\d) clause\)/BSD-$1-clause/g;
        # $l =~ s/\bpublic domain\b/public-domain/ig;


        # # deduplicate license keywords and add 'or' keyword where missing
        # # this is fragile. may need to change license-check to output license keyword
        # my %tmp_l = map { ( $_ => 1) ;} grep { $_ ne 'or' } split(/ /,$l);
        # $l = join(' or ', sort keys %tmp_l) ;

        # Handle license like "under the same term as Perl"
        # $l =~ s/perl/Artistic or GPL-1+/i;

        $c =~ s/'//g;
        $c =~ s/^&copy;\s*//g;
        $c =~ s/\(c\)\s*//g;
        $c =~ s/(?<=\b\d{4})\s*-\s*\d{4}(?=\s*-\s*(\d{4})\b)//g;
        $c =~ s/(\d+)\s*-\s*(\d+)/$1-$2/g;
        $c =~ s/\b(\d{4}),?\s+([\S^\d])/$1, $2/g;
        $c =~ s/\s+by\s+//g;
        $c =~ s/(\\n)*all\s+rights?\s+reserved\.?(\\n)*\s*//gi; # yes there are literal \n
        $c = 'no-info-found' if $c =~ /^\*No/;
        $c =~ s/\(r\)//g;
        $c =~ s!^[\s,/*]|[\s,#/*-]+$!!g;
        $c =~ s/--/-/g;
        $c =~ s!\s+\*/\s+! !;

        $c = __pack_copyright($c);

        # this data overrides what's found in current files. This is done before
        # the code that merge and coaslesce entries
        my $fill_blank = __get_fill_blank($fill_blank_data, $f);

        next if $fill_blank->{skip};

        if ( $c =~ /no-info-found/ and $fill_blank->{copyright} ) {
            $c = $fill_blank->{copyright};
        }
        if ($fill_blank->{'override-copyright'}) {
            _warn "Overriding path $f copyright info\n";
            $c = $fill_blank->{'override-copyright'};
        }
        if ( $l =~/unknown/i and $fill_blank->{license} ) {
            $l = $fill_blank->{license};
        }
        if ($fill_blank->{'override-license'}) {
            _warn "Overriding path $f license info\n";
            $l = $fill_blank->{'override-license'};
        }

        my @no_info_found;
        if ( $c =~ /no-info-found/ ) {
            push @no_info_found, 'copyright';
        }
        if ( $l =~/unknown/i ) {
            push @no_info_found, 'license';
        }

        push @no_info_list , [$f , @no_info_found ] if @no_info_found;

        my $has_info = @no_info_found < 2 ? 1 : 0;
        $files->{$f} = $copyrights{$c}{$l} //= ($has_info ? $id++ : 0);
        # say "Storing '$f' : '$c' '$l' has_info: $has_info id ".$files->{$f};
    }

    if (@skipped) {
        my $msg= "The following files were skipped:\n";
        map {
             $msg .= "- $_\n";
         } @skipped;
        $msg .= "You may want to add a line in debian/copyright-scan-patterns.yml\n"
            ."or ask the author to add more default patterns to scan\n\n";
        _warn $msg;
    }

    if (@no_info_list) {
        my $msg= "The following paths are missing information:\n";
        map {my ($p,@i) = $_->@*;
             $msg .= "- $p: missing ".join(' and ', @i)."\n";
         } @no_info_list;
        $msg .= "You may want to add a line in debian/fill.copyright.blanks.yml\n\n";
        _warn $msg;
    }

    my @notused = grep { ! $fill_blank_data->{$_}{used} and $_; } sort keys %$fill_blank_data ;
    if (@notused) {
        _warn "Warning: the following entries from fill.copyright.blanks.yml were not used\n- '"
            .join("'\n- '",@notused)."'\n";
    }

    my @copyrights_by_id ;
    foreach my $c (sort keys %copyrights) {
        foreach my $l (sort keys $copyrights{$c}->%* ) {
            my $id = $copyrights{$c}{$l};
            $copyrights_by_id[$id] = [ $c, $l ] ;
        }
    }

    warn "No copyright information found" unless keys %$files;

    my $merged_c_info = __squash_copyrights_years (\@copyrights_by_id) ;

    # replace the old ids with news ids
    __swap_merged_ids($files, $merged_c_info);

    # stop here for update ...
    return ($files, \@copyrights_by_id) ;
}

sub __split_copyright ($c) {
    my ($years,$owner) = $c =~ /^(\d\d[\s,\d-]+)(.*)/;
    # say "undef year in $c" unless defined $years;
    return unless defined $years;
    my @data = split /(?<=\d)[,\s]+/, $years;
    return unless defined $owner;
    $owner =~ s/^[\s.,-]+|[\s,*-]+$//g;
    return ($owner,@data);
}

sub __create_tree_leaf_from_paths ($h,$path,$value) {
    # explode path in subpaths
    my @subpaths = split '/', $path;
    my $last = pop @subpaths;
    map { $h = $h->{$_} ||= {} } @subpaths ;
    $h->{$last} = $value;
}

sub __pack_copyright ($r) {

    return $r if $r eq 'no-info-found';
    my %cop;
    $r =~ /^[\s\W]+|[\s\W]+$/g;
    # split licensescheck output or debfmt data
    foreach my $c ( split( m!(?:\s+/\s+)|(?:\s*\n\s*)!, $r) ) {
        my ($owner, @data) = __split_copyright($c);
        return $r unless defined $owner;
        $cop{$owner} ||= [] ;
        push $cop{$owner}->@*, @data ;
    }
    my @res ;
    foreach my $owner (sort keys %cop) {
        my $span = Array::IntSpan->new();
        my $data = $cop{$owner};
        foreach my $year ($data->@*) {
            return $r if $year =~ /[^\d-]/; # bail-out
            # take care of ranges written like 2002-3
            $year =~ s/^(\d\d\d)(\d)-(\d)$/$1$2-$1$3/;
            # take care of ranges written like 2014-15
            $year =~ s/^(\d\d)(\d\d)-(\d\d)$/$1$2-$1$3/;
            eval {
                $span->set_range_as_string($year, $owner);
            };
            if ($@) {
                warn "Invalid year range in copyright: $r";
                return $r;
            }
        }
        $span->consolidate();
        push @res, $span->get_range_list. ($owner ? ', '. $owner : '');
    }
    return join("\n ",reverse sort @res);
}

#in each directory, pack files that have the same copyright/license information
# traverse recursively %h (whose structure matches the scanned directory)
# @path keeps track of the recursion depth to provide the file path
sub __pack_files ($h) {

    my @res ;
    __pack_dir($h,\@res) ;

    # sort by first path listed in there
    my $sort_path = sub {
        $a->[1] cmp $b->[1];
    };

    return sort $sort_path @res ;
}

sub __pack_dir ($h, $pack, @path) {
    my %pack_by_id;
    foreach my $file (sort keys %$h) {
        my $id = $h->{$file};
        if (ref($id)) {
            __pack_dir($id, $pack, @path, $file) ;
        }
        elsif (defined $pack_by_id{$id} ) {
            push $pack_by_id{$id}->@*, join('/',@path,$file);
        }
        else {
            $pack_by_id{$id} = [ join('/',@path,$file) ] ;
        }
    }

    push $pack->@*, map { [ $_, $pack_by_id{$_}->@* ];  } keys %pack_by_id ;
}

# find ids that can be merged together
# I.e. merge entries with same license and same set of owners. In this
# case the years are merged together.
sub __squash_copyrights_years ($copyrights_by_id) {

    my %id_year_by_same_owner_license;
    for (my $id = 1; $id < $copyrights_by_id->@* ; $id++ ) {
        my ($c,$l) = $copyrights_by_id->[$id]->@* ;
        #say "id $id: c $c l $l";
        my @owners ;
        my @years ;
        foreach my $line (split(/\n\s+/,$c)) {
            my ($owner, @year) = __split_copyright($line);
            next unless defined $owner;
            push @owners, $owner;
            push @years, join(',',@year);
        }
        my $k = join('|', $l, @owners);
        $id_year_by_same_owner_license{$k} //= [];
        push $id_year_by_same_owner_license{$k}->@*, [ $id, @years ];
    }

    my @merged_c_info;
    # now detect where %id_year_by_same_owner_license references more
    # than one id this means that several entries can be merged in a
    # *new* id (new id to avoid cloberring data of other directories)
    foreach my $owner_license (sort keys %id_year_by_same_owner_license) {
        my @entries =  $id_year_by_same_owner_license{$owner_license}->@* ;
        next unless @entries > 1;

        my ($l,@owners) = split /\|/, $owner_license;

        # create new copyright info with coalesced years
        my @squashed_c = __coalesce_copyright_years(\@entries,\@owners) ;
        next unless @squashed_c ; # give up this entry when problem

        # store (c) info with coalesced years in new item of $copyrights_by_id
        my $new_id = $copyrights_by_id->@* ;
        my $new_cop = join("\n ",@squashed_c) ;
        $copyrights_by_id->[$new_id] = [ $new_cop , $l ];
        #say "created id $new_id with c $new_cop l $l";
        # fill the swap table entry-id -> coaslesces entry-id
        foreach my $id ( map { $_->[0]} @entries) {
            $merged_c_info[$id] = $new_id;
        }
    }

    return \@merged_c_info;
}

sub __swap_merged_ids ($files, $merged_c_info) {
    foreach my $name (sort keys %$files) {
        my $item = $files->{$name};
        if (ref($item)) {
            __swap_merged_ids($item,$merged_c_info);
        }
        elsif (my $new_id = $merged_c_info->[$item]) {
            $files->{$name} = "$new_id"  ;
        }
    }
}

sub __coalesce_copyright_years($entries, $owners) {
    my @ranges_of_years ;
    # $entries and $owners always have the same size

    foreach my $entry (@$entries) {
        my ($id, @years) = $entry->@* ;

        for (my $i = 0; $i < @years; $i++) {
            return () unless $years[$i] =~ /^[0-9,\s-]+$/; # detect empty year range
            my $span = $ranges_of_years[$i] //= Array::IntSpan->new();
            return () unless $span; # bail out in case of problems
            eval {
                $span->set_range_as_string($years[$i], 1);
            };
            if ($@) {
                warn "Invalid year range: ",$years[$i];
                return ();
            }
        }
    }

    my @squashed_c;
    for (my $i=0; $i < @$owners ; $i++) {
        $ranges_of_years[$i]->consolidate();
        $squashed_c[$i] = $ranges_of_years[$i]->get_range_list.', '.$owners->[$i];
    }

    return @squashed_c;
}

# $h is a tree of hash matching the directory structure. Each leaf is a
# copyright id. Each key is a file name in a directory (not the full path)
sub __squash ($h, $p = '') {
    my %count ;

    # find main license info found in LICENCE or COPYING or README
    # file
    foreach my $info_name (qw/readme copying license/) {
        my $re = qr!$info_name[.\w]*$!i;
        foreach my $name (sort keys %$h) {
            if ($name =~ $re) {
                my $id = delete $h->{$name};
                next unless $id; # skip files without info
                # say "del global lic info $p/$name with $id";
                # using 1 means that info from this file is not easy to override
                $count{$id} = 1;
            };
        }
    }

    # count the number of times each (c) info is used in this directory.
    # (including the main (c) info of each subdirectory)
    foreach my $name (sort keys %$h) {
        my $item = $h->{$name};
        if (ref($item)) {
            # squash may return a plain id, or a hash with '*' => id ,
            # or a non squashable hash
            $h->{$name} = __squash($item, $p.'/'.$name);
        }
        my $id = (ref($item) and defined $item->{'*'}) ? $item->{'*'} : $item ;

        # do not count non squashable hashes (i.e. there's no main (c) info)
        # do not count ids containing no information (id 0)
        if (not ref ($id) and $id != 0) {
            $count{$id}//=0;
            $count{$id} ++;
        }
    }

    # find the most used (c) info in this directory (or the existing '*' entry)
    # unless info was already found in LICENSE or README content
    my $max = 0;
    my $main_license_id = $h->{'*'};
    if (not defined $main_license_id) {
        foreach my $id (sort keys %count) {
            if ($count{$id} > $max) {
                $max = $count{$id};
                $main_license_id = $id ;
            }
        }
    }

    # all files associated to the most used (c) info are deleted to
    # be represented by '*' entry
    if (defined $main_license_id) {
        foreach my $name (sort keys %$h) {
            my $item = $h->{$name};
            if (ref($item) and defined $item->{'*'} and $item->{'*'} == $main_license_id) {
                # rename item/* to item/. when covered by ./*
                # this is a "weak" directory info which is handled specially
                $item->{'.'} = delete $item->{'*'};
            }
            if (not ref ($item)) {
                # delete file that is represented by '*' entry
                delete $h->{$name} if $item == $main_license_id;
            }
        }

        # here's the '*' file representing the most used (c) info
        $h->{'*'} //= $main_license_id;
    }

    return $h;
}

sub __load_fill_blank_data ($current_dir) {
    my %fill_blanks ;
    my $debian = $current_dir->child('debian'); # may be missing in test environment

    if ($debian->is_dir) {
        my @fills = $debian->children(qr/fill\.copyright\.blanks\.yml$/);

        warn "Note: loading @fills fixes" if @fills and not $quiet;
        foreach my $file ( @fills) {
            my $yaml = $file->slurp_utf8;
            my $data = Load $yaml;
            foreach my $path (sort keys %$data) {
                if ($fill_blanks{$path}) {
                    warn "Warning: skipping duplicated fill blank path $path from file $file";
                }
                else {
                    $fill_blanks{$path} = $data->{$path};
                }

                foreach my $k (keys $fill_blanks{$path}->%*) {
                    die "Error in file $file: Unexpected key '$k' in path '$path'\n"
                        unless $k =~/^(comment|skip|(override-)?(license|copyright))$/;
                }
            }
        }
    }

    return \%fill_blanks;
}

sub __get_fill_blank ($fbd,$file) {

    foreach my $path (reverse sort keys %$fbd) {
        if ($file =~ m(^$path)) {
            $fbd->{$path}{used} = 1;
            return $fbd->{$path};
        }
    }
    return {};
}

1;

__END__

=encoding utf8

=head1 NAME

 Dpkg::Copyright::Scanner - Scan files to provide copyright data

=head1 SYNOPSIS

 use Dpkg::Copyright::Scanner qw/print_copyright scan_files/;

 # print copyright data on STDOUT
 print_copyright;

 # return a data structure containing copyright information
 my @copyright_data = scan_files();


=head1 DESCRIPTION

This modules scans current package directory to extract copyright and
license information. Information are packed in a way to ease review and
maintenance. Files information is grouped with wildcards ('*') to reduce
the list of files.

=head1 Selecting or ignoring files to scan

By default, scanner scans source files with known suffixes (like .c
.pl ...), README, scripts and skip backup files.

You can change this behavior in file
C<debian/copyright-scan-patterns.yml>. This YAML file can contain a
list of suffixes or patterns to scan or to ignore that are added to
the default list. Any file that is not scanned or ignored will be
shown as "skipped".

The file must have the following structure (all fields are optional
and order does not matter):

 ---
 check :
   suffixes :
     - PL       # check .PL$
     - asm
   pattern:
     - /README$
 ignore :
   suffixes :
     - yml
   pattern :
     - /t/
     - /models/
     - /debian/
     - /Changes

Do not specify the dot with the suffixes. This will be added by the scanner.

Note that a file that match both "check" and "ignore" pattern is ignored.

=head1 Filling the blanks

Sometimes, upstream coders are not perfect: some source files cannot
be parsed correctly or some legal information is missing.

All scanned files, even without copyright or license will be used. A
warning will be shown for each file with missing information.

Instead of patching upstream source files to fill the blank, you can
specify the missing information in a special file. This file is
C<debian/fill.copyright.blanks.yml>. It should contain a "mapping"
YAML structure (i.e. a hash), where the key is a Perl pattern used to
match a path. 

If the source of the package contains a lot of files without legal
information, you may need to specify there information for a whole
directory (See the C</src> dir in the example below).

For instance:

 ---
 debian:
   copyright: 2015, Marcel
   license: Expat
 src/:
   copyright: 2016. Joe
   license: Expat
 share/pkgs/openSUSE/systemd/onedsetup:
   copyright: 2015, Marcel
 share/vendor/ruby/gems/rbvmomi/lib/rbvmomi.*\.rb:
   license: Expat
 .*/NOTICE:
   skip: 1
 share/websockify/:
   license: LGPL-2
 src/sunstone/:
   license: Apache-2.0
 src/garbled/:
   'override-copyright': 2016 Marcel Mézigue

Patterns are matched from the beginning a
path. I.e. C<share/websockify/> pattern will match
C<share/websockify/foo.rb> but will not match
C<web/share/websockify/foo.rb>.

Patterns are tried in reversed sorted order. I.e. the data attached to
more specific path (e.g. C<3rdparty/foo/blah.c>) are applied before
more generic patterns (e.g. C<3rdparty/foo/>

The C<license> key must contain a license short name as returned by
C<license_check>.

When C<skip> is true, the file is skipped like a file without any
information.

The C<override-copyright> and C<override-license> keys can be used to
ignore the copyright information coming from the source and provide
the correct information. Use this as last resort for instance when the
encoding of the owner is not ascii or utf-8 or when the license data
is corrupted. Note that a warning will be shown each time an override
key is used.

=head1 METHODS

=head2 print_copyright

Print copyright information on STDOUT like L<scan-copyrights>.

=head2 scan_files ( %args )

Return a data structure with copyright and license information.

The structure is a list of list:

 [
   [
     [ path1 ,path2, ...],
     copyright,
     license_short_name
   ],
   ...
 ]

Example:

 [
  [
    [ '*' ],
    '1994-2001, by Frank Pilhofer.',
    'GPL-2+'
  ],
  [
    [ 'pan/*' ],
    '2002-2006, Charles Kerr <charles@rebelbase.com>',
    'GPL-2'
  ],
  [
    [
      'pan/data/parts.cc',
      'pan/data/parts.h'
    ],
    '2002-2007, Charles Kerr <charles@rebelbase.com>',
    'GPL-2'
  ],
 ]

Parameters in C<%args>:

=over

=item quiet

set to 1 to suppress progress messages. Should be used only in tests.

=back


=head1 Encoding

The output of L<licensecheck> is expected to be utf-8. Which means
that the source files scanned by L<licensecheck> should also be
encoded in utf-8. In practice, this will impact only copyright owner
name which may be garbled if comments are not encoded in utf-8.

=head1 BUGS

Extracting license and copyright data from unstructured comments is not reliable.
User must check manually the files when no copyright info is found or when the
license is unknown.

Source files are assumed to be utf8 (or ascii). Using files with other encoding
will lead to garbled names of copyright owner. In this case, you can:

=over

=item *

Path source files to use utf-8 encoding.

=item *

Use the "fill copyright blank" mechanism described above with
C<copyright-override> to provide an owner name with the correct
encoding.

=item *

File a bug against licensecheck of devscript package to find a better solution.

=back

=head1 SEE ALSO

L<licensecheck>, C<licensecheck2dep5> from C<cdbs> package

=head1 AUTHOR

Dominique Dumont <dod@debian.org>

=cut