File Coverage

blib/lib/Dpkg/Source/Patch.pm
Criterion Covered Total %
statement 181 406 44.5
branch 59 256 23.0
condition 26 117 22.2
subroutine 22 37 59.4
pod 0 11 0.0
total 288 827 34.8


line stmt bran cond sub pod time code
1             # Copyright © 2008 Raphaël Hertzog
2             # Copyright © 2008-2010, 2012-2015 Guillem Jover
3             #
4             # This program is free software; you can redistribute it and/or modify
5             # it under the terms of the GNU General Public License as published by
6             # the Free Software Foundation; either version 2 of the License, or
7             # (at your option) any later version.
8             #
9             # This program is distributed in the hope that it will be useful,
10             # but WITHOUT ANY WARRANTY; without even the implied warranty of
11             # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12             # GNU General Public License for more details.
13             #
14             # You should have received a copy of the GNU General Public License
15             # along with this program. If not, see .
16              
17             package Dpkg::Source::Patch;
18              
19 4     4   3325 use strict;
  4         9  
  4         125  
20 4     4   23 use warnings;
  4         7  
  4         166  
21              
22             our $VERSION = '0.01';
23              
24 4     4   21 use POSIX qw(:errno_h :sys_wait_h);
  4         8  
  4         26  
25 4     4   2989 use File::Find;
  4         8  
  4         224  
26 4     4   30 use File::Basename;
  4         5  
  4         230  
27 4     4   24 use File::Spec;
  4         8  
  4         119  
28 4     4   22 use File::Path qw(make_path);
  4         5  
  4         215  
29 4     4   2099 use File::Compare;
  4         3933  
  4         235  
30 4     4   28 use Fcntl ':mode';
  4         11  
  4         813  
31 4     4   25 use Time::HiRes qw(stat);
  4         11  
  4         32  
32              
33 4     4   2023 use Dpkg;
  4         11  
  4         152  
34 4     4   1295 use Dpkg::Gettext;
  4         11  
  4         231  
35 4     4   1246 use Dpkg::ErrorHandling;
  4         10  
  4         311  
36 4     4   1755 use Dpkg::IPC;
  4         9  
  4         232  
37 4     4   1712 use Dpkg::Source::Functions qw(fs_time);
  4         9  
  4         236  
38              
39 4     4   1989 use parent qw(Dpkg::Compression::FileHandle);
  4         1177  
  4         21  
40              
41             sub create {
42 0     0 0 0 my ($self, %opts) = @_;
43 0         0 $self->ensure_open('w'); # Creates the file
44 0         0 *$self->{errors} = 0;
45 0         0 *$self->{empty} = 1;
46 0 0 0     0 if ($opts{old} and $opts{new} and $opts{filename}) {
      0        
47 0 0       0 $opts{old} = '/dev/null' unless -e $opts{old};
48 0 0       0 $opts{new} = '/dev/null' unless -e $opts{new};
49 0 0 0     0 if (-d $opts{old} and -d $opts{new}) {
    0 0        
50 0         0 $self->add_diff_directory($opts{old}, $opts{new}, %opts);
51             } elsif (-f $opts{old} and -f $opts{new}) {
52 0         0 $self->add_diff_file($opts{old}, $opts{new}, %opts);
53             } else {
54 0         0 $self->_fail_not_same_type($opts{old}, $opts{new}, $opts{filename});
55             }
56 0 0       0 $self->finish() unless $opts{nofinish};
57             }
58             }
59              
60             sub set_header {
61 0     0 0 0 my ($self, $header) = @_;
62 0         0 *$self->{header} = $header;
63             }
64              
65             sub add_diff_file {
66 0     0 0 0 my ($self, $old, $new, %opts) = @_;
67 0   0     0 $opts{include_timestamp} //= 0;
68             my $handle_binary = $opts{handle_binary_func} // sub {
69 0     0   0 my ($self, $old, $new, %opts) = @_;
70 0         0 my $file = $opts{filename};
71 0         0 $self->_fail_with_msg($file, g_('binary file contents changed'));
72 0   0     0 };
73             # Optimization to avoid forking diff if unnecessary
74 0 0       0 return 1 if compare($old, $new, 4096) == 0;
75             # Default diff options
76 0         0 my @options;
77 0 0       0 if ($opts{options}) {
78 0         0 push @options, @{$opts{options}};
  0         0  
79             } else {
80 0         0 push @options, '-p';
81             }
82             # Add labels
83 0 0 0     0 if ($opts{label_old} and $opts{label_new}) {
84 0 0       0 if ($opts{include_timestamp}) {
85 0         0 my $ts = (stat($old))[9];
86 0         0 my $t = POSIX::strftime('%Y-%m-%d %H:%M:%S', gmtime($ts));
87 0         0 $opts{label_old} .= sprintf("\t%s.%09d +0000", $t,
88             ($ts - int($ts)) * 1_000_000_000);
89 0         0 $ts = (stat($new))[9];
90 0         0 $t = POSIX::strftime('%Y-%m-%d %H:%M:%S', gmtime($ts));
91 0         0 $opts{label_new} .= sprintf("\t%s.%09d +0000", $t,
92             ($ts - int($ts)) * 1_000_000_000);
93             } else {
94             # Space in filenames need special treatment
95 0 0       0 $opts{label_old} .= "\t" if $opts{label_old} =~ / /;
96 0 0       0 $opts{label_new} .= "\t" if $opts{label_new} =~ / /;
97             }
98             push @options, '-L', $opts{label_old},
99 0         0 '-L', $opts{label_new};
100             }
101             # Generate diff
102 0         0 my $diffgen;
103 0         0 my $diff_pid = spawn(
104             exec => [ 'diff', '-u', @options, '--', $old, $new ],
105             env => { LC_ALL => 'C', LANG => 'C', TZ => 'UTC0' },
106             to_pipe => \$diffgen,
107             );
108             # Check diff and write it in patch file
109 0         0 my $difflinefound = 0;
110 0         0 my $binary = 0;
111 0         0 local $_;
112              
113 0         0 while (<$diffgen>) {
114 0 0       0 if (m/^(?:binary|[^-+\@ ].*\bdiffer\b)/i) {
    0          
    0          
115 0         0 $binary = 1;
116 0         0 $handle_binary->($self, $old, $new, %opts);
117 0         0 last;
118             } elsif (m/^[-+\@ ]/) {
119 0         0 $difflinefound++;
120             } elsif (m/^\\ /) {
121 0         0 warning(g_('file %s has no final newline (either ' .
122             'original or modified version)'), $new);
123             } else {
124 0         0 chomp;
125 0         0 error(g_("unknown line from diff -u on %s: '%s'"), $new, $_);
126             }
127 0 0 0     0 if (*$self->{empty} and defined(*$self->{header})) {
128 0 0       0 $self->print(*$self->{header}) or syserr(g_('failed to write'));
129 0         0 *$self->{empty} = 0;
130             }
131 0 0       0 print { $self } $_ or syserr(g_('failed to write'));
  0         0  
132             }
133 0 0       0 close($diffgen) or syserr('close on diff pipe');
134 0         0 wait_child($diff_pid, nocheck => 1,
135             cmdline => "diff -u @options -- $old $new");
136             # Verify diff process ended successfully
137             # Exit code of diff: 0 => no difference, 1 => diff ok, 2 => error
138             # Ignore error if binary content detected
139 0         0 my $exit = WEXITSTATUS($?);
140 0 0 0     0 unless (WIFEXITED($?) && ($exit == 0 || $exit == 1 || $binary)) {
      0        
141 0         0 subprocerr(g_('diff on %s'), $new);
142             }
143 0   0     0 return ($exit == 0 || $exit == 1);
144             }
145              
146             sub add_diff_directory {
147 0     0 0 0 my ($self, $old, $new, %opts) = @_;
148             # TODO: make this function more configurable
149             # - offer to disable some checks
150 0   0     0 my $basedir = $opts{basedirname} || basename($new);
151 0         0 my $diff_ignore;
152 0 0       0 if ($opts{diff_ignore_func}) {
    0          
153 0         0 $diff_ignore = $opts{diff_ignore_func};
154             } elsif ($opts{diff_ignore_regex}) {
155 0     0   0 $diff_ignore = sub { return $_[0] =~ /$opts{diff_ignore_regex}/o };
  0         0  
156             } else {
157 0     0   0 $diff_ignore = sub { return 0 };
  0         0  
158             }
159              
160 0         0 my @diff_files;
161             my %files_in_new;
162             my $scan_new = sub {
163 0 0   0   0 my $fn = (length > length($new)) ? substr($_, length($new) + 1) : '.';
164 0 0       0 return if $diff_ignore->($fn);
165 0         0 $files_in_new{$fn} = 1;
166 0 0       0 lstat("$new/$fn") or syserr(g_('cannot stat file %s'), "$new/$fn");
167 0         0 my $mode = S_IMODE((lstat(_))[2]);
168 0         0 my $size = (lstat(_))[7];
169 0 0 0     0 if (-l _) {
    0 0        
    0          
    0          
    0          
170 0 0       0 unless (-l "$old/$fn") {
171 0         0 $self->_fail_not_same_type("$old/$fn", "$new/$fn", $fn);
172 0         0 return;
173             }
174 0         0 my $n = readlink("$new/$fn");
175 0 0       0 unless (defined $n) {
176 0         0 syserr(g_('cannot read link %s'), "$new/$fn");
177             }
178 0         0 my $n2 = readlink("$old/$fn");
179 0 0       0 unless (defined $n2) {
180 0         0 syserr(g_('cannot read link %s'), "$old/$fn");
181             }
182 0 0       0 unless ($n eq $n2) {
183 0         0 $self->_fail_not_same_type("$old/$fn", "$new/$fn", $fn);
184             }
185             } elsif (-f _) {
186 0         0 my $old_file = "$old/$fn";
187 0 0       0 if (not lstat("$old/$fn")) {
    0          
188 0 0       0 if ($! != ENOENT) {
189 0         0 syserr(g_('cannot stat file %s'), "$old/$fn");
190             }
191 0         0 $old_file = '/dev/null';
192             } elsif (not -f _) {
193 0         0 $self->_fail_not_same_type("$old/$fn", "$new/$fn", $fn);
194 0         0 return;
195             }
196              
197 0         0 my $label_old = "$basedir.orig/$fn";
198 0 0       0 if ($opts{use_dev_null}) {
199 0 0       0 $label_old = $old_file if $old_file eq '/dev/null';
200             }
201 0         0 push @diff_files, [$fn, $mode, $size, $old_file, "$new/$fn",
202             $label_old, "$basedir/$fn"];
203             } elsif (-p _) {
204 0 0       0 unless (-p "$old/$fn") {
205 0         0 $self->_fail_not_same_type("$old/$fn", "$new/$fn", $fn);
206             }
207             } elsif (-b _ || -c _ || -S _) {
208 0         0 $self->_fail_with_msg("$new/$fn",
209             g_('device or socket is not allowed'));
210             } elsif (-d _) {
211 0 0       0 if (not lstat("$old/$fn")) {
    0          
212 0 0       0 if ($! != ENOENT) {
213 0         0 syserr(g_('cannot stat file %s'), "$old/$fn");
214             }
215             } elsif (not -d _) {
216 0         0 $self->_fail_not_same_type("$old/$fn", "$new/$fn", $fn);
217             }
218             } else {
219 0         0 $self->_fail_with_msg("$new/$fn", g_('unknown file type'));
220             }
221 0         0 };
222             my $scan_old = sub {
223 0 0   0   0 my $fn = (length > length($old)) ? substr($_, length($old) + 1) : '.';
224 0 0       0 return if $diff_ignore->($fn);
225 0 0       0 return if $files_in_new{$fn};
226 0 0       0 lstat("$old/$fn") or syserr(g_('cannot stat file %s'), "$old/$fn");
227 0 0       0 if (-f _) {
    0          
    0          
228 0 0       0 if (not defined $opts{include_removal}) {
    0          
229 0         0 warning(g_('ignoring deletion of file %s'), $fn);
230             } elsif (not $opts{include_removal}) {
231 0         0 warning(g_('ignoring deletion of file %s, use --include-removal to override'), $fn);
232             } else {
233 0         0 push @diff_files, [$fn, 0, 0, "$old/$fn", '/dev/null',
234             "$basedir.orig/$fn", '/dev/null'];
235             }
236             } elsif (-d _) {
237 0         0 warning(g_('ignoring deletion of directory %s'), $fn);
238             } elsif (-l _) {
239 0         0 warning(g_('ignoring deletion of symlink %s'), $fn);
240             } else {
241 0         0 $self->_fail_not_same_type("$old/$fn", "$new/$fn", $fn);
242             }
243 0         0 };
244              
245 0         0 find({ wanted => $scan_new, no_chdir => 1 }, $new);
246 0         0 find({ wanted => $scan_old, no_chdir => 1 }, $old);
247              
248 0 0 0     0 if ($opts{order_from} and -e $opts{order_from}) {
249             my $order_from = Dpkg::Source::Patch->new(
250 0         0 filename => $opts{order_from});
251 0         0 my $analysis = $order_from->analyze($basedir, verbose => 0);
252 0         0 my %patchorder;
253 0         0 my $i = 0;
254 0         0 foreach my $fn (@{$analysis->{patchorder}}) {
  0         0  
255 0         0 $fn =~ s{^[^/]+/}{};
256 0         0 $patchorder{$fn} = $i++;
257             }
258             # 'quilt refresh' sorts files as follows:
259             # - Any files in the existing patch come first, in the order in
260             # which they appear in the existing patch.
261             # - New files follow, sorted lexicographically.
262             # This seems a reasonable policy to follow, and avoids autopatches
263             # being shuffled when they are regenerated.
264 0         0 foreach my $diff_file (sort { $a->[0] cmp $b->[0] } @diff_files) {
  0         0  
265 0         0 my $fn = $diff_file->[0];
266 0   0     0 $patchorder{$fn} //= $i++;
267             }
268 0         0 @diff_files = sort { $patchorder{$a->[0]} <=> $patchorder{$b->[0]} }
  0         0  
269             @diff_files;
270             } else {
271 0         0 @diff_files = sort { $a->[0] cmp $b->[0] } @diff_files;
  0         0  
272             }
273              
274 0         0 foreach my $diff_file (@diff_files) {
275 0         0 my ($fn, $mode, $size,
276             $old_file, $new_file, $label_old, $label_new) = @$diff_file;
277 0         0 my $success = $self->add_diff_file($old_file, $new_file,
278             filename => $fn,
279             label_old => $label_old,
280             label_new => $label_new, %opts);
281 0 0 0     0 if ($success and
      0        
282             $old_file eq '/dev/null' and $new_file ne '/dev/null') {
283 0 0       0 if (not $size) {
284 0         0 warning(g_("newly created empty file '%s' will not " .
285             'be represented in diff'), $fn);
286             } else {
287 0 0       0 if ($mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
288 0 0       0 warning(g_("executable mode %04o of '%s' will " .
289             'not be represented in diff'), $mode, $fn)
290             unless $fn eq 'debian/rules';
291             }
292 0 0       0 if ($mode & (S_ISUID | S_ISGID | S_ISVTX)) {
293 0         0 warning(g_("special mode %04o of '%s' will not " .
294             'be represented in diff'), $mode, $fn);
295             }
296             }
297             }
298             }
299             }
300              
301             sub finish {
302 0     0 0 0 my $self = shift;
303 0 0       0 close($self) or syserr(g_('cannot close %s'), $self->get_filename());
304 0         0 return not *$self->{errors};
305             }
306              
307             sub register_error {
308 0     0 0 0 my $self = shift;
309 0         0 *$self->{errors}++;
310             }
311             sub _fail_with_msg {
312 0     0   0 my ($self, $file, $msg) = @_;
313 0         0 errormsg(g_('cannot represent change to %s: %s'), $file, $msg);
314 0         0 $self->register_error();
315             }
316             sub _fail_not_same_type {
317 0     0   0 my ($self, $old, $new, $file) = @_;
318 0         0 my $old_type = get_type($old);
319 0         0 my $new_type = get_type($new);
320 0         0 errormsg(g_('cannot represent change to %s:'), $file);
321 0         0 errormsg(g_(' new version is %s'), $new_type);
322 0         0 errormsg(g_(' old version is %s'), $old_type);
323 0         0 $self->register_error();
324             }
325              
326             sub _getline {
327 79     79   118 my $handle = shift;
328              
329 79         248 my $line = <$handle>;
330 79 100       2213 if (defined $line) {
331             # Strip end-of-line chars
332 74         129 chomp($line);
333 74         138 $line =~ s/\r$//;
334             }
335 79         188 return $line;
336             }
337              
338             # Fetch the header filename ignoring the optional timestamp
339             sub _fetch_filename {
340 26     26   55 my ($diff, $header) = @_;
341              
342             # Strip any leading spaces.
343 26         69 $header =~ s/^\s+//;
344              
345             # Is it a C-style string?
346 26 100       62 if ($header =~ m/^"/) {
347 6         165 error(g_('diff %s patches file with C-style encoded filename'), $diff);
348             } else {
349             # Tab is the official separator, it's always used when
350             # filename contain spaces. Try it first, otherwise strip on space
351             # if there's no tab
352 20 50       92 $header =~ s/\s.*// unless $header =~ s/\t.*//;
353             }
354              
355 20         68 return $header;
356             }
357              
358             sub _intuit_file_patched {
359 7     7   34 my ($old, $new) = @_;
360              
361 7 100       29 return $new unless defined $old;
362 2 50       10 return $old unless defined $new;
363 2 50 33     24 return $new if -e $new and not -e $old;
364 2 50 33     26 return $old if -e $old and not -e $new;
365              
366             # We don't consider the case where both files are non-existent and
367             # where patch picks the one with the fewest directories to create
368             # since dpkg-source will pre-create the required directories
369              
370             # Precalculate metrics used by patch
371 2         20 my ($tmp_o, $tmp_n) = ($old, $new);
372 2         6 my ($len_o, $len_n) = (length($old), length($new));
373 2         18 $tmp_o =~ s{[/\\]+}{/}g;
374 2         12 $tmp_n =~ s{[/\\]+}{/}g;
375 2         6 my $nb_comp_o = ($tmp_o =~ tr{/}{/});
376 2         6 my $nb_comp_n = ($tmp_n =~ tr{/}{/});
377 2         8 $tmp_o =~ s{^.*/}{};
378 2         8 $tmp_n =~ s{^.*/}{};
379 2         6 my ($blen_o, $blen_n) = (length($tmp_o), length($tmp_n));
380              
381             # Decide like patch would
382 2 50       16 if ($nb_comp_o != $nb_comp_n) {
    50          
    50          
383 0 0       0 return ($nb_comp_o < $nb_comp_n) ? $old : $new;
384             } elsif ($blen_o != $blen_n) {
385 0 0       0 return ($blen_o < $blen_n) ? $old : $new;
386             } elsif ($len_o != $len_n) {
387 0 0       0 return ($len_o < $len_n) ? $old : $new;
388             }
389 2         6 return $old;
390             }
391              
392             # check diff for sanity, find directories to create as a side effect
393             sub analyze {
394 21     21 0 78 my ($self, $destdir, %opts) = @_;
395              
396 21   50     52 $opts{verbose} //= 1;
397 21         73 my $diff = $self->get_filename();
398 21         56 my %filepatched;
399             my %dirtocreate;
400 21         0 my @patchorder;
401 21         38 my $patch_header = '';
402 21         32 my $diff_count = 0;
403              
404 21         48 my $line = _getline($self);
405              
406             HUNK:
407 21   66     56 while (defined $line or not eof $self) {
408 21         36 my (%path, %fn);
409              
410             # Skip comments leading up to the patch (if any). Although we do not
411             # look for an Index: pseudo-header in the comments, because we would
412             # not use it anyway, as we require both ---/+++ filename headers.
413 21         26 while (1) {
414 49 100       175 if ($line =~ /^(?:--- |\+\+\+ |@@ -)/) {
415 21         49 last;
416             } else {
417 28         97 $patch_header .= "$line\n";
418             }
419 28         57 $line = _getline($self);
420 28 50       80 last HUNK if not defined $line;
421             }
422 21         24 $diff_count++;
423             # read file header (---/+++ pair)
424 21 100       95 unless ($line =~ s/^--- //) {
425 8         51 error(g_("expected ^--- in line %d of diff '%s'"), $., $diff);
426             }
427 13         39 $path{old} = $line = _fetch_filename($diff, $line);
428 13 100 66     86 if ($line ne '/dev/null' and $line =~ s{^[^/]*/+}{$destdir/}) {
429 2         10 $fn{old} = $line;
430             }
431 13 50       54 if ($line =~ /\.dpkg-orig$/) {
432 0         0 error(g_("diff '%s' patches file with name ending in .dpkg-orig"),
433             $diff);
434             }
435              
436 13         24 $line = _getline($self);
437 13 50       31 unless (defined $line) {
438 0         0 error(g_("diff '%s' finishes in middle of ---/+++ (line %d)"),
439             $diff, $.);
440             }
441 13 50       81 unless ($line =~ s/^\+\+\+ //) {
442 0         0 error(g_("line after --- isn't as expected in diff '%s' (line %d)"),
443             $diff, $.);
444             }
445 13         36 $path{new} = $line = _fetch_filename($diff, $line);
446 7 50 33     99 if ($line ne '/dev/null' and $line =~ s{^[^/]*/+}{$destdir/}) {
447 7         19 $fn{new} = $line;
448             }
449              
450 7 50 66     39 unless (defined $fn{old} or defined $fn{new}) {
451 0         0 error(g_("none of the filenames in ---/+++ are valid in diff '%s' (line %d)"),
452             $diff, $.);
453             }
454              
455             # Safety checks on both filenames that patch could use
456 7         24 foreach my $key ('old', 'new') {
457 14 100       45 next unless defined $fn{$key};
458 9 50       31 if ($path{$key} =~ m{/\.\./}) {
459 0         0 error(g_('%s contains an insecure path: %s'), $diff, $path{$key});
460             }
461 9         19 my $path = $fn{$key};
462 9         16 while (1) {
463 13 50       201 if (-l $path) {
464             error(g_('diff %s modifies file %s through a symlink: %s'),
465 0         0 $diff, $fn{$key}, $path);
466             }
467 13 50       141 last unless $path =~ s{/+[^/]*$}{};
468 13 100       55 last if length($path) <= length($destdir); # $destdir is assumed safe
469             }
470             }
471              
472 7 50 66     62 if ($path{old} eq '/dev/null' and $path{new} eq '/dev/null') {
    50          
473 0         0 error(g_("original and modified files are /dev/null in diff '%s' (line %d)"),
474             $diff, $.);
475             } elsif ($path{new} eq '/dev/null') {
476             error(g_("file removal without proper filename in diff '%s' (line %d)"),
477 0 0       0 $diff, $. - 1) unless defined $fn{old};
478 0 0       0 if ($opts{verbose}) {
479             warning(g_('diff %s removes a non-existing file %s (line %d)'),
480 0 0       0 $diff, $fn{old}, $.) unless -e $fn{old};
481             }
482             }
483 7         36 my $fn = _intuit_file_patched($fn{old}, $fn{new});
484              
485 7         20 my $dirname = $fn;
486 7 100 66     179 if ($dirname =~ s{/[^/]+$}{} and not -d $dirname) {
487 2         10 $dirtocreate{$dirname} = 1;
488             }
489              
490 7 50 33     81 if (-e $fn and not -f _) {
491 0         0 error(g_("diff '%s' patches something which is not a plain file"),
492             $diff);
493             }
494              
495 7 50       29 if ($filepatched{$fn}) {
496 0         0 $filepatched{$fn}++;
497              
498 0 0 0     0 if ($opts{fatal_dupes}) {
    0          
499 0         0 error(g_("diff '%s' patches files multiple times; split the " .
500             'diff in multiple files or merge the hunks into a ' .
501             'single one'), $diff);
502             } elsif ($opts{verbose} and $filepatched{$fn} == 2) {
503 0         0 warning(g_("diff '%s' patches file %s more than once"), $diff, $fn)
504             }
505             } else {
506 7         54 $filepatched{$fn} = 1;
507 7         19 push @patchorder, $fn;
508             }
509              
510             # read hunks
511 7         14 my $hunk = 0;
512 7         21 while (defined($line = _getline($self))) {
513             # read hunk header (@@)
514 7 50       24 next if $line =~ /^\\ /;
515 7 100       45 last unless $line =~ /^@@ -\d+(,(\d+))? \+\d+(,(\d+))? @\@(?: .*)?$/;
516 5 50       70 my ($olines, $nlines) = ($1 ? $2 : 1, $3 ? $4 : 1);
    50          
517             # read hunk
518 5   66     40 while ($olines || $nlines) {
519 5 50       17 unless (defined($line = _getline($self))) {
520 0 0 0     0 if (($olines == $nlines) and ($olines < 3)) {
521             warning(g_("unexpected end of diff '%s'"), $diff)
522 0 0       0 if $opts{verbose};
523 0         0 last;
524             } else {
525 0         0 error(g_("unexpected end of diff '%s'"), $diff);
526             }
527             }
528 5 50       20 next if $line =~ /^\\ /;
529             # Check stats
530 5 50 33     110 if ($line =~ /^ / or length $line == 0) {
    50          
    50          
531 0         0 --$olines;
532 0         0 --$nlines;
533             } elsif ($line =~ /^-/) {
534 0         0 --$olines;
535             } elsif ($line =~ /^\+/) {
536 5         30 --$nlines;
537             } else {
538 0         0 error(g_("expected [ +-] at start of line %d of diff '%s'"),
539             $., $diff);
540             }
541             }
542 5         15 $hunk++;
543             }
544 7 100       74 unless ($hunk) {
545 2         6 error(g_("expected ^\@\@ at line %d of diff '%s'"), $., $diff);
546             }
547             }
548 5         110 close($self);
549 5 50       17 unless ($diff_count) {
550             warning(g_("diff '%s' doesn't contain any patch"), $diff)
551 0 0       0 if $opts{verbose};
552             }
553 5         27 *$self->{analysis}{$destdir}{dirtocreate} = \%dirtocreate;
554 5         10 *$self->{analysis}{$destdir}{filepatched} = \%filepatched;
555 5         15 *$self->{analysis}{$destdir}{patchorder} = \@patchorder;
556 5         20 *$self->{analysis}{$destdir}{patchheader} = $patch_header;
557 5         20 return *$self->{analysis}{$destdir};
558             }
559              
560             sub prepare_apply {
561 5     5 0 28 my ($self, $analysis, %opts) = @_;
562 5 50       18 if ($opts{create_dirs}) {
563 5         10 foreach my $dir (keys %{$analysis->{dirtocreate}}) {
  5         66  
564 0         0 eval { make_path($dir, { mode => 0777 }) };
  0         0  
565 0 0       0 syserr(g_('cannot create directory %s'), $dir) if $@;
566             }
567             }
568             }
569              
570             sub apply {
571 21     21 0 167 my ($self, $destdir, %opts) = @_;
572             # Set default values to options
573 21   50     95 $opts{force_timestamp} //= 1;
574 21   50     76 $opts{remove_backup} //= 1;
575 21   50     82 $opts{create_dirs} //= 1;
576 21   50     131 $opts{options} ||= [ '-t', '-F', '0', '-N', '-p1', '-u',
577             '-V', 'never', '-b', '-z', '.dpkg-orig'];
578 21   50     90 $opts{add_options} //= [];
579 21         37 push @{$opts{options}}, @{$opts{add_options}};
  21         41  
  21         47  
580             # Check the diff and create missing directories
581 21         98 my $analysis = $self->analyze($destdir, %opts);
582 5         33 $self->prepare_apply($analysis, %opts);
583             # Apply the patch
584 5         23 $self->ensure_open('r');
585 5         20 my ($stdout, $stderr) = ('', '');
586             spawn(
587 5         10 exec => [ $Dpkg::PROGPATCH, @{$opts{options}} ],
  5         90  
588             chdir => $destdir,
589             env => { LC_ALL => 'C', LANG => 'C', PATCH_GET => '0' },
590             delete_env => [ 'POSIXLY_CORRECT' ], # ensure expected patch behaviour
591             wait_child => 1,
592             nocheck => 1,
593             from_handle => $self->get_filehandle(),
594             to_string => \$stdout,
595             error_to_string => \$stderr,
596             );
597 3 100       88 if ($?) {
598 1         18 print { *STDOUT } $stdout;
  1         62  
599 1         14 print { *STDERR } $stderr;
  1         34  
600 1         13 subprocerr("LC_ALL=C $Dpkg::PROGPATCH " . join(' ', @{$opts{options}}) .
  1         84  
601             ' < ' . $self->get_filename());
602             }
603 2         118 $self->close();
604             # Reset the timestamp of all the patched files
605             # and remove .dpkg-orig files
606 2         4 my @files = keys %{$analysis->{filepatched}};
  2         40  
607 2         8 my $now = $opts{timestamp};
608 2 50 33     60 $now //= fs_time($files[0]) if $opts{force_timestamp} && scalar @files;
      50        
609 2         18 foreach my $fn (@files) {
610 2 50       10 if ($opts{force_timestamp}) {
611 2 50 33     36 utime($now, $now, $fn) or $! == ENOENT
612             or syserr(g_('cannot change timestamp for %s'), $fn);
613             }
614 2 50       10 if ($opts{remove_backup}) {
615 2         18 $fn .= '.dpkg-orig';
616 2 50       118 unlink($fn) or syserr(g_('remove patch backup file %s'), $fn);
617             }
618             }
619 2         52 return $analysis;
620             }
621              
622             # Verify if check will work...
623             sub check_apply {
624 0     0 0   my ($self, $destdir, %opts) = @_;
625             # Set default values to options
626 0   0       $opts{create_dirs} //= 1;
627 0   0       $opts{options} ||= [ '--dry-run', '-s', '-t', '-F', '0', '-N', '-p1', '-u',
628             '-V', 'never', '-b', '-z', '.dpkg-orig'];
629 0   0       $opts{add_options} //= [];
630 0           push @{$opts{options}}, @{$opts{add_options}};
  0            
  0            
631             # Check the diff and create missing directories
632 0           my $analysis = $self->analyze($destdir, %opts);
633 0           $self->prepare_apply($analysis, %opts);
634             # Apply the patch
635 0           $self->ensure_open('r');
636             my $patch_pid = spawn(
637 0           exec => [ $Dpkg::PROGPATCH, @{$opts{options}} ],
  0            
638             chdir => $destdir,
639             env => { LC_ALL => 'C', LANG => 'C', PATCH_GET => '0' },
640             delete_env => [ 'POSIXLY_CORRECT' ], # ensure expected patch behaviour
641             from_handle => $self->get_filehandle(),
642             to_file => '/dev/null',
643             error_to_file => '/dev/null',
644             );
645 0           wait_child($patch_pid, nocheck => 1);
646 0           my $exit = WEXITSTATUS($?);
647 0 0         subprocerr("$Dpkg::PROGPATCH --dry-run") unless WIFEXITED($?);
648 0           $self->close();
649 0           return ($exit == 0);
650             }
651              
652             # Helper functions
653             sub get_type {
654 0     0 0   my $file = shift;
655 0 0         if (not lstat($file)) {
656 0 0         return g_('nonexistent') if $! == ENOENT;
657 0           syserr(g_('cannot stat %s'), $file);
658             } else {
659 0 0         -f _ && return g_('plain file');
660 0 0         -d _ && return g_('directory');
661 0 0         -l _ && return sprintf(g_('symlink to %s'), readlink($file));
662 0 0         -b _ && return g_('block device');
663 0 0         -c _ && return g_('character device');
664 0 0         -p _ && return g_('named pipe');
665 0 0         -S _ && return g_('named socket');
666             }
667             }
668              
669             1;