File: Patch.pm

package info (click to toggle)
libtext-patch-perl 1.8-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch, wheezy
  • size: 104 kB
  • ctags: 11
  • sloc: perl: 191; makefile: 2
file content (340 lines) | stat: -rw-r--r-- 8,965 bytes parent folder | download | duplicates (2)
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
package Text::Patch;
use Exporter;
our @ISA = qw( Exporter );
our @EXPORT = qw( patch );
our $VERSION = '1.8';
use strict;
use warnings;
use Carp;

use constant NO_NEWLINE => '\\ No newline at end of file';

sub patch
{
  my $text = shift;
  my $diff = shift;
  my %options = ref $_[0] eq 'HASH' ? %{ $_[0] } : @_;

  my %handler = ('unified'  => \&patch_unified,
                 'context'  => \&patch_context,
                 'oldstyle' => \&patch_oldstyle,
                 );
  my $style = $options{STYLE};
  croak "required STYLE option is missing" unless $style;
  croak "source required" unless defined $text;
  croak "diff required" unless defined $diff;
  my $code = $handler{lc($style)} || croak "unrecognised STYLE '$style'";

  my @text = split /^/m, $text;
  my @diff = split /^/m, $diff;

  # analyse source/diff to determine line ending used.
  # (if source is only 1 line, can't use it to determine line endings)
  my $line1 = @text > 1 ? $text[0] : $diff[0];
  my($line1c, $sep) = _chomp($line1);
  $sep ||= "\n";  # default to unix line ending

  # apply patch
  DUMP("got patch", \@diff);
  my $out = $code->(\@text, \@diff, $sep);

  my $lastline = _chomp($diff[-1], $sep);
  $out = _chomp($out, $sep) if $lastline eq NO_NEWLINE;
  return $out;
}

sub patch_unified
{
  my($text, $diff, $sep) = @_;
  my @hunks;
  my %hunk;

  for( @$diff )
    {
    #print STDERR ">>> ... [$_]";
    if( /^\@\@\s*-([\d,]+)/ )
      {
      #print STDERR ">>> *** HUNK!\n";
      my($pos1, $count1) = split /,/, $1;
      push @hunks, { %hunk };
      %hunk = ();
      $hunk{ FROM } = $pos1 - 1; # diff is 1-based
      # Modification by Ben L., patches may have @@ -0,0 if the source is empty.
      $hunk{ FROM } = 0 if $hunk{ FROM } < 0;
      $hunk{ LEN  } = defined $count1 ? $count1 : $pos1 == 0 ? 0 : 1;
      $hunk{ DATA } = [];
      }
    push @{ $hunk{ DATA } }, $_;
    }
  push @hunks, { %hunk }; # push last hunk
  shift @hunks; # first is always empty

  return _patch($text, \@hunks, $sep);
}

sub patch_oldstyle {
    my($text, $diff, $sep) = @_;
    my @hunks;
    my $i = 0;

    my $hunk_head = qr/^([\d,]+)([acd])([\d,]+)$/;
    while($i < @$diff) {
        my $l = $diff->[$i];
        my($r1, $type, $r2) = $l =~ $hunk_head;
        die "Malformed patch at line ".($i + 1)."\n"
            unless defined $r1 && $type && defined $r2;
        my($pos1, $count1) = _range($r1);
        my($pos2, $count2) = _range($r2);

        # parse chunk data
        my @data;
        my $j = $i + 1;
        for(; $j < @$diff; $j++) {
            $l = $diff->[$j];
            last if $l =~ $hunk_head;
            next if $l =~ /^---/;  # separator
            push @data, $l;
        }
        my $datalen = $j - $i - 1;

        if($type eq 'a') { # add
            $count1 = 0;   # don't remove any lines
            $pos1++;       # add to line after pos1
        }

        # convert data to a format _patch() will understand
        for(@data) {
            $_ =~ s/^< /-/;
            $_ =~ s/^> /+/;
        }

        push @hunks, { FROM => $pos1 - 1,
                       LEN  => $count1,
                       DATA => \@data,
                     };
        $i += $datalen + 1;
    }
    return _patch($text, \@hunks, $sep);
}

# NB: this works by converting hunks into a kind of unified format
sub patch_context {
    my($text, $diff, $sep) = @_;
    my $i = 0;
    my @hunks;

    # skip past header
    for(@$diff) {
        $i++;
        last if /^\Q***************\E$/;  # end header marker
    }

    # this sub reads one half of a hunk (from/to part)
    my $read_part = sub {
        my $l = $diff->[$i++];
        TRACE("got line: $l");
        die "Malformed patch at line $i\n"
            unless $l =~ /^(?:\*\*\*|---)\s+([\d,]+)\s+(?:\*\*\*|---)/;
        my($pos, $count) = _range($1);
        my @part;
        while($i < @$diff) {
            my $l = $diff->[$i];
            last if $l =~ /^(\*\*\*|---)/;
            push @part, $l;
            $i++;
        }
        DUMP("got part", \@part);
        return (\@part, $pos, $count);
    };

    while($i < @$diff) {
        # read the from and to part of this hunk
        my($part1, $pos1, $count1) = $read_part->();
        my($part2, $pos2, $count2) = $read_part->();
        $i++;  # skip chunk separator

        # convert operations to unified style ones
        $_ =~ s/^(.)\s/$1/ for @$part1, @$part2;
        $_ =~ s/^\!/-/ for @$part1;  # remove
        $_ =~ s/^\!/+/ for @$part2;  # add

        # merge the parts to create a unified style chunk
        my @data;
        for(;;) {
            my $c1 = $part1->[0];
            my $c2 = $part2->[0];
            last unless defined $c1 || defined $c2;

            if(defined $c1 && $c1 =~ /^-/) {
                push @data, shift @$part1;  # remove line
            } elsif(defined $c2 && $c2 =~ /^\+/) {
                push @data, shift @$part2;  # add line
            } else {                        # context
                my($x1, $x2) = (shift @$part1, shift @$part2);
                push @data, defined $x1 ? $x1 : $x2;
            }
        }
        push @hunks, { FROM => $pos1 - 1,
                       LEN  => $count1,
                       DATA => \@data,
                     };
        DUMP("merged data", \@data);
    }
    return _patch($text, \@hunks, $sep);
}

######################################################################
# private

# returns (start line, line count)
sub _range {
    my($range) = @_;
    my($pos1, $pos2) = split /,/, $range;
    return ($pos1, defined $pos2 ? $pos2 - $pos1 + 1 : 1);
}

sub _patch {
  my($text, $hunks, $sep) = @_;
  my $hunknum = scalar @$hunks + 1;
  die "No hunks found\n" unless @$hunks;
  for my $hunk ( reverse @$hunks )
    {
    $hunknum--;
    DUMP("hunk", $hunk);
    my @pdata;
    my $num = $hunk->{FROM};
    for( @{ $hunk->{ DATA } } )
      {
      next unless s/^([ \-\+])//;
      #print STDERR ">>> ($1) $_";
      if($1 ne '+') {
          # not an addition, check line for match against existing text.
          # ignore line endings for comparison
          my $orig   = _chomp($text->[$num++], $sep); # num 0 based here
          my $expect = _chomp($_, $sep);
          TRACE("checking >>$orig<<");
          TRACE(" against >>$expect<<");
          die "Hunk #$hunknum failed at line $num.\n" # actual line number
              unless $orig eq $expect;
      }
      next if $1 eq '-';  # removals
      push @pdata, $_;    # add/replace line
      }
    splice @$text, $hunk->{ FROM }, $hunk->{ LEN }, @pdata;
    }

  return join '', @$text;
}

# chomp $sep from the end of line
# if $sep is not given, chomp unix or dos line ending
sub _chomp {
    my($text, $sep) = @_;
    if($sep) {
        $text =~ s/($sep)$//;
    } else {
        $text =~ s/(\r\n|\n)$//;
    }
    return wantarray ? ($text, $1) : $text;
}

sub DUMP {}
sub TRACE {}

#sub DUMP {
#use Data::Dumper;
#print STDERR Dumper(@_);
#}
#sub TRACE {
#use Data::Dumper;
#print STDERR Dumper(@_);
#}


=pod

=head1 NAME

Text::Patch - Patches text with given patch

=head1 SYNOPSIS

    use Text::Patch;

    $output = patch( $source, $diff, STYLE => "Unified" );

    use Text::Diff;

    $src  = ...
    $dst  = ...

    $diff = diff( \$src, \$dst, { STYLE => 'Unified' } );

    $out  = patch( $src, $diff, { STYLE => 'Unified' } );

    print "Patch successful" if $out eq $dst;

=head1 DESCRIPTION

Text::Patch combines source text with given diff (difference) data.
Diff data is produced by Text::Diff module or by the standard diff
utility (man diff, see -u option).

=over 4

=item patch( $source, $diff, options... )

First argument is source (original) text. Second is the diff data.
Third argument can be either hash reference with options or all the
rest arguments will be considered patch options:

    $output = patch( $source, $diff, STYLE => "Unified", ... );

    $output = patch( $source, $diff, { STYLE => "Unified", ... } );

Options are:

  STYLE => 'Unified'

STYLE can be "Unified", "Context" or "OldStyle".

The 'Unified' diff format looks like this:

  @@ -1,7 +1,6 @@
  -The Way that can be told of is not the eternal Way;
  -The name that can be named is not the eternal name.
   The Nameless is the origin of Heaven and Earth;
  -The Named is the mother of all things.
  +The named is the mother of all things.
  +
   Therefore let there always be non-being,
     so we may see their subtlety,
   And let there always be being,
  @@ -9,3 +8,6 @@
   The two are the same,
   But after they are produced,
     they have different names.
  +They both may be called deep and profound.
  +Deeper and more profound,
  +The door of all subtleties!


=back

=head1 TODO

  Interfaces with files, arrays, etc.

=head1 AUTHOR

  Vladi Belperchinov-Shabanski "Cade"

  <cade@biscom.net> <cade@datamax.bg> <cade@cpan.org>

  http://cade.datamax.bg

=head1 VERSION

  $Id: Patch.pm,v 1.6 2007/04/07 19:57:41 cade Exp $

=cut