Commit | Line | Data |
---|---|---|
bd910290 AC |
1 | #! /usr/bin/env perl |
2 | ||
3 | use v5.16; | |
4 | use warnings; | |
5 | ||
6 | # Take a unified diff (perhaps from "git diff" or similar) on stdin, and | |
7 | # delete hunks where (a) every "ins" line in the hunk also appears in a | |
8 | # "del" line somewhere in the diff, and (b) every "del" line in the hunk | |
9 | # also appears in an "ins" line somewhere in the diff. | |
10 | ||
11 | die "Usage: diff ... | nontrivdiff\n" if @ARGV; | |
12 | ||
13 | sub break_before (&@) { | |
14 | my $predicate = shift; | |
15 | my (@curr, @groups); | |
16 | for (@_) { | |
17 | push @groups, [splice @curr] | |
18 | if @curr && $predicate->($_); | |
19 | push @curr, $_; | |
20 | } | |
21 | push @groups, \@curr if @curr; | |
22 | return @groups; | |
23 | } | |
24 | ||
25 | my @all_lines = <>; | |
26 | ||
27 | my @head; | |
28 | push @head, shift @all_lines | |
29 | while @all_lines && $all_lines[0] =~ /^diff |^index |^--- |^\+\+\+ /; | |
30 | ||
31 | die "Can't handle multi-file diffs\n" | |
32 | if grep /^--- |^\+\+\+ /, @all_lines; | |
33 | ||
34 | my (%ins, %del); | |
35 | for (@all_lines) { | |
36 | next if /^\@\@ |^ /; | |
37 | my ($c, $line) = /([-+])(.*)/s or die "can't parse: $_"; | |
38 | $line =~ s/[ \t]+/ /g; | |
39 | my $h = $c eq '-' ? \%del : \%ins; | |
40 | $h->{$line}++; | |
41 | } | |
42 | ||
43 | my @out; | |
44 | for my $hunk (break_before { /^\@\@ / } @all_lines) { | |
45 | push @out, @$hunk if any_changes_missing($hunk); | |
46 | } | |
47 | ||
48 | print @head, @out if @out; | |
49 | ||
50 | sub any_changes_missing { | |
51 | my ($hunk) = @_; | |
52 | ||
53 | my %lins = %ins; | |
54 | my %ldel = %del; | |
55 | ||
56 | for (@$hunk) { | |
57 | next if /^\@\@ |^ /; | |
58 | my ($c, $line) = /([-+])(.*)/s or die "can't parse: $_"; | |
59 | $line =~ s/[ \t]+/ /g; | |
60 | my $h = $c eq '-' ? \%lins : \%ldel; | |
61 | return 1 if !$h->{$line}; | |
62 | $h->{$line}--; | |
63 | } | |
64 | ||
65 | %ins = %lins; | |
66 | %del = %ldel; | |
67 | return 0; | |
68 | } |