convert non-utf8; avoid buffering; debug unmatched values
[git-grep-footer.git] / git-grep-footer
1 #!/usr/bin/perl -0 -CO
2 use 5.010;
3 use strict;
4 use warnings;
5 use Encode 'decode';
6 use Data::Dump 'pp';
7 use Getopt::Long;
8
9 GetOptions(\my %opt,
10         'debug!',
11 ) or die;
12
13 local $| = 1;
14
15 my $HEADERMATCH = qr/ [a-z]+ (?: (?:-\w+)+ | \ by ) /ix;
16
17 while (readline) {
18         s/(.+)\n//m;
19         my $hash = $1;
20
21         # strip commit seperator
22         chomp;
23         # skip expensive checks without potential identifier
24         m/:/ or next;
25         # try to parse as UTF-8
26         eval { $_ = decode(utf8   => $_, Encode::FB_CROAK()) };
27         # if invalid, assume it's latin1
28                $_ = decode(cp1252 => $_) if $@;
29
30         my $prefix = 0;
31         my %attr;
32
33         BLOCK:
34         for (reverse split /\n\n/) {
35                 my @headers;
36
37                 LINE:
38                 for (split /\n/) {
39                         next if not /\S/;
40                         my @header = m{
41                                 ^
42                                 (?<key> $HEADERMATCH)
43                                 : \s*
44                                 (?<val> \S .+)
45                                 $
46                         }imx or do {
47                                 $prefix++;
48                                 next LINE;
49                         };
50
51                         push @headers, \@header;
52                 }
53
54                 next BLOCK if not @headers;
55
56                 if ($opt{debug} and $prefix) {
57                         say "infix junk in commit $hash";
58                 }
59
60                 for (@headers) {
61                         say join ': ', @$_;
62                 }
63
64                 last BLOCK;
65         }
66 }