Patch.pm 21 KB

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