Patch.pm 22 KB

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