chiark / gitweb /
Dgit.pm: Split here doc for reflog cache commit message (nfc)
[dgit.git] / i18n-diff-auditor
1 #!/usr/bin/perl -w
2 #
3 # i18n-diff-auditor
4 # Copyright (C)2018 Ian Jackson
5 # GPLv3+, NO WARRANTY, see below.
6 #
7 #
8 # Usage:
9 #  something like this
10 #  git-log -n1 -p | ./i18n-diff-auditor -D 2>&1 |less -j10 +/'^!.*'
11 #
12 # -D is for debug.  Currently only one level.
13 #
14 # Output is the relevant diff hunks, with each line prepended with
15 # space for ok lines and ! for questionable ones, and with relevant
16 # diff lines prepended with lines starting !! (and lines starting #
17 # for debug output), so ovrall:
18 #
19 #   !! <message>   reasoning for subsequent questionable diff line(s)
20 #   !+             diff line found to be questionable
21 #   !-             diff line found to be questionable
22 #    @@@ etc.      diff furniture
23 #    +             diff line checked and ok
24 #    -             diff line checked and ok
25 #   # <stuff>      debug output (normally precedes relevant output)
26 #
27 # Changes are generally marked as ok if they correspond to a known
28 # intended code change pattern.  (That includes changing error calls
29 # to different error calls.)  If they don't correspond to any known
30 # pattern, they are "questionable" and the first thing that doesn't
31 # match the most common pattern is reported.
32 #
33 # Might be useful for projects other than dgit, provided it uses
34 # the same gettext aliases (__ f_ i_) and similar error calls
35 # (die, confess, fail).
36 #
37 #
38 # This program is free software: you can redistribute it and/or modify
39 # it under the terms of the GNU General Public License as published by
40 # the Free Software Foundation, either version 3 of the License, or
41 # (at your option) any later version.
42 #
43 # This program is distributed in the hope that it will be useful,
44 # but WITHOUT ANY WARRANTY; without even the implied warranty of
45 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
46 # GNU General Public License for more details.
47 #
48 # You should have received a copy of the GNU General Public License
49 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
50
51 use strict;
52 use Carp;
53 use Data::Dumper;
54 use Getopt::Long;
55
56 our $debug = 0;
57 GetOptions("debug|D+" => \$debug
58            );
59
60 our @debug;
61 sub debug ($$) {
62     my ($i,$s) = @_;
63     push @{ $debug[$i] }, $s if $debug;
64 }
65
66 my @d = <>;
67 unshift @d, "# dummy line to make line 1 index 1 in \@d\n";
68
69 our $i_last_l_ok = -1;
70 our $count_i_last_l_ok;
71
72 sub l_ok ($) {
73     my ($i) = @_;
74
75     if ($i == $i_last_l_ok) {
76         confess $i if $count_i_last_l_ok++ > 50;
77     } else {
78         $count_i_last_l_ok = 0;
79         $i_last_l_ok = $i;
80     }
81
82     return unless $i < @d;
83     $_ = $d[$i];
84     #print STDERR "L $i\n";
85     1;
86 }
87
88 sub l ($) {
89     my ($i) = @_;
90     confess $i unless l_ok $i;
91 };
92
93 our $perlop_text = <<'END'; # c&p from man perlop
94            left        terms and list operators (leftward)
95            left        ->
96            nonassoc    ++ --
97            right       **
98            right       ! ~ \ and unary + and -
99            left        =~ !~
100            left        * / % x
101            left        + - .
102            left        << >>
103            nonassoc    named unary operators
104            nonassoc    < > <= >= lt gt le ge
105            nonassoc    == != <=> eq ne cmp ~~
106            left        &
107            left        | ^
108            left        &&
109            left        || //
110            nonassoc    ..  ...
111            right       ?:
112            right       = += -= *= etc. goto last next redo dump
113            left        , =>
114            nonassoc    list operators (rightward)
115            right       not
116            left        and
117            left        or xor
118
119            **=    +=    *=    &=    &.=    <<=    &&=
120                   -=    /=    |=    |.=    >>=    ||=
121                   .=    %=    ^=    ^.=           //=
122                         x=
123 END
124
125 our $perlop_re;
126
127 sub prep_perlop () {
128     my @ops;
129     foreach (split /\n/, $perlop_text) {
130         next unless m{\S};
131         s{\s+$}{};
132         s{^\s+}{};
133         s{^(?: left | right | nonassoc ) \s+}{}x;
134         next if m{^terms and list operators};
135         next if m{^named unary};
136         next if m{^list operators};
137         s{ and unary.*}{};
138         s{ etc\. }{ };
139         s{\?\:}{ ? : };
140         foreach my $op (split /\s+/) {
141             next unless length $op;
142             next if $op =~ m{^\w+$};
143             $op =~ s/\W/\\$&/g;
144             push @ops, $op;
145         }
146     }
147     $perlop_re = '(?: '.(join ' | ', @ops).' )';
148     $perlop_re = qr{$perlop_re}x;
149     #print STDERR "$perlop_re\n";
150 }
151
152 prep_perlop();
153
154 our ($ifilehead, $ifirsthunkhead);
155 our ($ihunkhead, $ihunkend);
156 our ($ichunkstart, $ichunkend);
157 our ($before, $after);
158
159 sub is_string ($) { $_[0]{T} =~ m/heredoc|string/; }
160 sub is_trans ($) { grep { $_[0]{E} eq $_ } qw(__ f_ i_); }
161
162 sub qp ($) {
163     my ($p) = @_;
164     $p =~ s{\\}{\\\\}g;
165     $p =~ s{\'}{\\'}g;
166     $p =~ s{\n}{\\n}g;
167     $p =~ s{\t}{\\t}g;
168     return "'$p'";
169 };
170
171 sub semiparse ($) {
172     ($_) = @_;
173     my @o;
174     #my $in = $_;
175     # entries contain
176     #   T     type
177     #   E     exact input text (does not contain here doc contents)
178     #   P     something to print in messages
179     #   V     value, only for: heredoc string
180     #   Q     quote characcter, only for: heredoc string
181     for (;;) {
182         s{^\s+}{};
183         if (s{^[\$\@\%]?[_0-9a-zA-Z]+}{}) {
184             push @o, { T => 'ident', E => $&, P => $& };
185         } elsif (s{^\<\<(['"]?)([A-Z_]+)\1}{}) {
186             my ($q,$d) = ($1,$2);
187             $q ||= '"';
188             push @o, { T => 'heredoc', Q => $q, Delim => $d,
189                        E => $&, P => "<<$q$d$q" };
190             if (s{^
191                     (                 .* \n     )
192                     ( (?: (?! $d \n ) .* \n )*? )
193                               $d         \n
194                  }{ $1 }xe) {
195                 $o[$#o]{V} = $2;
196             } else {
197                 m{^.*\n} or confess;
198                 $_ = $&;
199                 $o[$#o]{V} = $';
200                 $o[$#o]{Invented} = 1;
201             }
202         } elsif (s{^ (["'])( (?: [^\\'"]
203                                | \\ [^"']
204                                | (?! \1 ) [^"]
205                               )*
206                        ) \1 }{}x) {
207             my ($q,$v) = ($1,$2);
208             push @o, { T => 'string', E => $&, P => "$q$q",
209                        Q => $q, V => $v};
210         } elsif (s{^$perlop_re|^\;}{}) {
211             push @o, { T => 'op', E => $&, P => $& };
212         } elsif (s/^[[{(]//) {
213             push @o, { T => 'bra', E => $&, P => $& };
214         } elsif (s/^[]})]//) {
215             push @o, { T => 'ket', E => $&, P => $& };
216         } elsif (s/^( [\$\@\%] )( \{ )//x) {
217             push @o, { T => 'deref', E => $1, P => $1 },
218                      { T => 'bra',   E => $2, P => $2 };
219         } elsif (s/^ [\$\@\%] [^[^{] //x) {
220             push @o, { T => 'specvar', E => $&, P => $& };
221         } elsif (!length) {
222             last;
223         } else {
224             m{^.{0,10}};
225             die "cannot tokenise \`$&'";
226         }
227     }
228     for (my $i=0; $i+2 < @o; $i++) {
229         next unless $o[$i+1]{E} eq '.';
230         my @inputs = @o[$i, $i+2];
231         #print STDERR Dumper(\@inputs);
232         next if grep { !is_string($_) } @inputs;
233         my $q = $inputs[0]{Q};
234         next if grep { $_->{Q} ne $q } @inputs;
235         next if grep { $_->{Invented} } @inputs;
236         my $new = { T => 'joinedstrings',
237                     E => (join '.', map { $_->{E} } @inputs),
238                     P => (join '.', map { $_->{P} } @inputs),
239                     V => (join '',  map { $_->{V} } @inputs),
240                     Q => $q,
241                   };
242         @o = (@o[0..$i-1], $new, @o[$i+3..$#o]);
243         $i--; # counteracts $i++
244     }
245     debug $ichunkstart, "semiparsed: ".join ' ', map { $_->{P} } @o;
246     # debug $ichunkstart, "semiparsed V: ".join ' ', map { defined $_->{V} ? ">$_->{V}<" : '-' } @o;
247     return @o;
248 }           
249
250 our @analysed_x;
251 our @analysed_y;
252
253 sub analyse_chunk_core () {
254     die "plain deletion\n" unless defined $after;
255     die "plain insertion\n" unless defined $before;
256     my @xs = semiparse $before;
257     my @ys = semiparse $after;
258     @analysed_x = @analysed_y = ();
259     my $next_something = sub {
260         my ($ary,$anal,$var,$what) = @_;
261         die "ran out of $what\n" unless @$ary;
262         my $r = shift @$ary;
263         push @$anal, $r->{P};
264         $$var = $r;
265     };
266     my ($x,$y);
267     my $next_x = sub { $next_something->(\@xs, \@analysed_x, \$x, 'before'); };
268     my $next_y = sub { $next_something->(\@ys, \@analysed_y, \$y, 'after' ); };
269     our @y_expect_suffix = ();
270     for (;;) {
271         while (my $e = shift @y_expect_suffix) {
272             $next_y->();
273             $y->{E} eq $e
274                 or die "suffix mismatch, expected $e got $y->{E}\n";
275         }
276         last unless @xs or @ys;
277         $next_x->();
278         $next_y->();
279         next if $x->{E} eq $y->{E};
280         next if $x->{E} eq 'sprintf' and $y->{E} eq 'f_';
281         next if $x->{E} eq 'die'     and $y->{E} eq 'confess';
282         next if $x->{E} eq 'die'     and $y->{E} eq 'fail';
283         if ($y->{E} eq '+'
284             and @ys >= 3
285             and $ys[0]{E} eq '('
286             and is_trans($ys[1])) {
287             $next_y->(); # (
288             $next_y->(); # __ f_ i_
289             @y_expect_suffix = ')';
290         } elsif ($y->{E} eq '('
291             and @ys > 2
292             and is_trans($ys[0])
293             and @analysed_y
294             and (grep { $_ eq $analysed_y[-1] } (qw( => [ { ? : . ),
295                                                  '(', ',') )) {
296             $next_y->(); # __ f_ i_
297             @y_expect_suffix = ')';
298         }
299         my $string_changed;
300         my $ye = $y->{E};
301         if (is_trans($y)) {
302             $next_y->();
303             die "__ on non-string $y->{P}\n"     unless is_string($y);
304             die "__ on was non-string $x->{P}\n" unless is_string($x);
305             if ($y->{Q} ne "'") {
306                 die "var subst in new string\n"
307                     if $y->{V} =~ m{(?<!\\) [\$\@]};
308             }
309             eval {
310                 die "__ string changed\n"       unless $y->{V} eq $x->{V};
311                 die "__ string quote changed\n" unless $y->{Q} eq $x->{Q};
312             };
313             $string_changed = $@;
314         }
315         if ($ye eq '__') {
316             $_ = $y->{V};
317             die "percent $& in __ ' string\n" if m{\%};
318             die $string_changed if length $string_changed;
319             next;
320         }
321         if ($ye eq 'i_') {
322             die $string_changed if length $string_changed;
323             next;
324         }
325         if ($ye eq 'f_') {
326             my $fmt = $y->{V};
327             die "no percent in f_ string\n" unless $fmt =~ m{\%};
328             next unless $string_changed;
329             die "f_ old string '-quoted\n" if $x->{Q} ne '"';
330             my $xs = $x->{V};
331             my $exactly = sub {
332                 my ($lit, $what) = @_;
333                 my $xl = substr($xs, 0, length($lit));
334                 if ($xl ne $lit) {
335                     debug $ichunkstart, "not exactly x: ..".qp($xs);
336                     debug $ichunkstart, "not exactly y:   ".qp($lit);
337                     my $next = @ys ? $ys[0]{P} : '(end)';
338                     die "string contents mismatch near $what before $next\n";
339                 }
340                 $xs = substr($xs, length($lit));
341             };
342             for (;;) {
343                 #print STDERR Dumper($fmt, $xs, \@xs, @ys);
344                 if ($fmt !~ m{\%[^\%]}) {
345                     $exactly->($fmt, '(tail)');
346                     $fmt = '';
347                     die "text deleted from end of string: ".qp($xs)."\n"
348                         if length $xs;
349                     last;
350                 }
351                 $exactly->($`, '(literal)');
352                 $fmt = $';
353                 if ($& eq '%%') { $exactly->('%', '%%'); next; }
354                 elsif ($& ne '%s') { die "unhandled %-subst $&\n"; }
355                 $next_y->();
356                 die "expected comma, got $y->{P}\n" unless $y->{E} eq ',';
357                 if (!length $fmt and
358                     !length $xs and
359                     @xs and
360                     $xs[0]{E} eq '.') {
361                     # X has   "<earlier>" .                <something>
362                     # Y has   "<earlier>%s" [other args] , <something>
363                     $next_x->(); # eat the '.'
364                     next;
365                 }
366                 if ($xs =~ m{^\@}) {
367                     $next_y->();
368                     die "\@... => not string" unless is_string($y);
369                     die "\@... => $y->{P}" if $y->{Q} ne '"';
370                     $exactly->($y->{V}, $y->{P});
371                     next;
372                 }
373                 my $bras = 0;
374                 for (;;) {
375                     if (!$bras and !@ys) {
376                         last;
377                     }
378                     $next_y->();
379                     if (!$bras and
380                         (grep { $y->{E} eq $_ } qw( or xor and not ; :
381                                                     if unless while when )
382                          or $y->{E} eq ','
383                          or $y->{T} eq 'ket'
384                         )) {
385                         # lookahead shows close of containing scope
386                         # or lower precedence operator
387                         unshift @ys, $y;
388                         pop @analysed_y;
389                         last;
390                     }
391                     $xs =~ s{^\s+}{} if $bras;
392                     if (is_string($y) and $y->{Q} eq '"') {
393                         $exactly->($y->{V}, $y->{P});
394                         next;
395                     }
396                     $exactly->($y->{E}, $y->{P});
397                     if ($y->{T} eq 'bra' or $y->{E} eq '?') {
398                         $bras++;
399                     } elsif ($y->{T} eq 'ket' or $y->{E} eq ':') {
400                         die "too many kets at $y->{E}\n" unless $bras;
401                         $bras--;
402                     }
403                 }
404             }
405             next;
406         }
407         die "mismatch $x->{P} => $y->{P}\n";
408     }
409 }
410
411 sub analyse_chunk () {
412     for (;;) {
413         eval { analyse_chunk_core(); };
414         return unless length $@;
415         if ($@ =~ m{^missing end of here doc (\S+)\n}) {
416             # fudge this
417             # (this never happens now, but in the future we might
418             # want this code again eg to try adding to the chunk)
419             $before .= "\n$1\n";
420             $after .= "\n$1\n";
421             next;
422         } else {
423             die $@;
424         }
425     }
426 }
427
428 our @report;
429 our $last_filehead = -1;
430
431 sub report_on_hunk () {
432     return unless @report;
433     if ($last_filehead != $ifilehead) {
434         foreach (my $i=$ifilehead; $i<$ifirsthunkhead; $i++) {
435             print $d[$i];
436         }
437         $last_filehead = $ifilehead;
438     }
439     my $dummy_r = { S => (scalar @d)+1, E => (scalar @d)+1 };
440     my $r;
441     for (my $i=$ihunkhead; ; $i++) {
442         for (;;) {
443             $r //= shift @report;
444             $r //= $dummy_r;
445             last if $i < $r->{E};
446             confess unless $r->{Done} == 03;
447             $r = undef;
448         }
449
450         last unless $i<$ihunkend;
451
452         foreach my $ds (@{ $debug[$i] }) {
453             print "# $ds\n";
454         }
455
456         if ($i == $r->{S}) {
457             print "!! $r->{M}";
458             $r->{Done} |= 01;
459         }
460         if ($i >= $r->{S}) {
461             print "!";
462             $r->{Done} |= 02;
463         } else {
464             print " ";
465         }
466         print $d[$i];
467     }
468     confess unless $r = $dummy_r;
469 }
470
471 for ($ifilehead = 0; l_ok $ifilehead; $ifilehead++) {
472     m{^diff} or next;
473     $ifirsthunkhead = $ifilehead;
474     while (l_ok $ifirsthunkhead and
475            m{^diff|^index|^---|^\Q+++\E}) {
476         $ifirsthunkhead++
477     }
478     $ihunkhead = $ifirsthunkhead;
479     while (l_ok $ihunkhead) {
480         m{^\@\@} or confess "$ihunkhead $_ ?";
481         my $i = $ihunkhead + 1;
482         for (; ; $i++) {
483             if (!l_ok $i or m{^ } or m{^\@\@}) {
484                 if (defined $ichunkstart) {
485                     $ichunkend = $i;
486                     eval { analyse_chunk(); 1; };
487                     if (length $@) {
488                         debug $ichunkstart, "done x: @analysed_x";
489                         debug $ichunkstart, "done y: @analysed_y";
490                         push @report, { M => $@,
491                                         S => $ichunkstart,
492                                         E => $ichunkend };
493                     }
494                     $ichunkstart = $ichunkend = $before = $after = undef;
495                 }
496                 l_ok $i or last;
497                 m{^\@\@} and last;
498             } elsif (m{^[-+]}) {
499                 my $which = $& eq '-' ? \$before : \$after;
500                 $ichunkstart //= $i;
501                 $$which //= '';
502                 $$which .= $';
503             } else {
504                 confess "$i $_ ?";
505             }
506         }
507         $ihunkend = $i;
508         report_on_hunk();
509         $ichunkend = $i;
510         $ihunkhead = $i;
511     }
512 }