Patch.pm 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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;
  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 base '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))*1000000000);
  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))*1000000000);
  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_regexp"}) {
  143. $diff_ignore = sub { return $_[0] =~ /$opts{"diff_ignore_regexp"}/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. defined(my $n = readlink("$new/$fn")) ||
  162. syserr(_g("cannot read link %s"), "$new/$fn");
  163. defined(my $n2 = readlink("$old/$fn")) ||
  164. syserr(_g("cannot read link %s"), "$old/$fn");
  165. unless ($n eq $n2) {
  166. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  167. }
  168. } elsif (-f _) {
  169. my $old_file = "$old/$fn";
  170. if (not lstat("$old/$fn")) {
  171. $! == ENOENT ||
  172. syserr(_g("cannot stat file %s"), "$old/$fn");
  173. $old_file = '/dev/null';
  174. } elsif (not -f _) {
  175. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  176. return;
  177. }
  178. my $label_old = "$basedir.orig/$fn";
  179. if ($opts{'use_dev_null'}) {
  180. $label_old = $old_file if $old_file eq '/dev/null';
  181. }
  182. push @diff_files, [$fn, $mode, $size, $old_file, "$new/$fn",
  183. $label_old, "$basedir/$fn"];
  184. } elsif (-p _) {
  185. unless (-p "$old/$fn") {
  186. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  187. }
  188. } elsif (-b _ || -c _ || -S _) {
  189. $self->_fail_with_msg("$new/$fn",
  190. _g("device or socket is not allowed"));
  191. } elsif (-d _) {
  192. if (not lstat("$old/$fn")) {
  193. $! == ENOENT ||
  194. syserr(_g("cannot stat file %s"), "$old/$fn");
  195. } elsif (not -d _) {
  196. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  197. }
  198. } else {
  199. $self->_fail_with_msg("$new/$fn", _g("unknown file type"));
  200. }
  201. };
  202. my $scan_old = sub {
  203. my $fn = (length > length($old)) ? substr($_, length($old) + 1) : '.';
  204. return if &$diff_ignore($fn);
  205. return if $files_in_new{$fn};
  206. lstat("$old/$fn") || syserr(_g("cannot stat file %s"), "$old/$fn");
  207. if (-f _) {
  208. if ($inc_removal) {
  209. push @diff_files, [$fn, 0, 0, "$old/$fn", "/dev/null",
  210. "$basedir.orig/$fn", "/dev/null"];
  211. } else {
  212. warning(_g("ignoring deletion of file %s"), $fn);
  213. }
  214. } elsif (-d _) {
  215. warning(_g("ignoring deletion of directory %s"), $fn);
  216. } elsif (-l _) {
  217. warning(_g("ignoring deletion of symlink %s"), $fn);
  218. } else {
  219. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  220. }
  221. };
  222. find({ wanted => $scan_new, no_chdir => 1 }, $new);
  223. find({ wanted => $scan_old, no_chdir => 1 }, $old);
  224. if ($opts{"order_from"} and -e $opts{"order_from"}) {
  225. my $order_from = Dpkg::Source::Patch->new(
  226. filename => $opts{"order_from"});
  227. my $analysis = $order_from->analyze($basedir, verbose => 0);
  228. my %patchorder;
  229. my $i = 0;
  230. foreach my $fn (@{$analysis->{"patchorder"}}) {
  231. $fn =~ s{^[^/]+/}{};
  232. $patchorder{$fn} = $i++;
  233. }
  234. # 'quilt refresh' sorts files as follows:
  235. # - Any files in the existing patch come first, in the order in
  236. # which they appear in the existing patch.
  237. # - New files follow, sorted lexicographically.
  238. # This seems a reasonable policy to follow, and avoids autopatches
  239. # being shuffled when they are regenerated.
  240. foreach my $diff_file (sort { $a->[0] cmp $b->[0] } @diff_files) {
  241. my $fn = $diff_file->[0];
  242. $patchorder{$fn} = $i++ unless exists $patchorder{$fn};
  243. }
  244. @diff_files = sort { $patchorder{$a->[0]} <=> $patchorder{$b->[0]} }
  245. @diff_files;
  246. }
  247. foreach my $diff_file (@diff_files) {
  248. my ($fn, $mode, $size,
  249. $old_file, $new_file, $label_old, $label_new) = @$diff_file;
  250. my $success = $self->add_diff_file($old_file, $new_file,
  251. label_old => $label_old,
  252. label_new => $label_new, %opts);
  253. if ($success and
  254. $old_file eq "/dev/null" and $new_file ne "/dev/null") {
  255. if (not $size) {
  256. warning(_g("newly created empty file '%s' will not " .
  257. "be represented in diff"), $fn);
  258. } else {
  259. if ($mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
  260. warning(_g("executable mode %04o of '%s' will " .
  261. "not be represented in diff"), $mode, $fn)
  262. unless $fn eq 'debian/rules';
  263. }
  264. if ($mode & (S_ISUID | S_ISGID | S_ISVTX)) {
  265. warning(_g("special mode %04o of '%s' will not " .
  266. "be represented in diff"), $mode, $fn);
  267. }
  268. }
  269. }
  270. }
  271. }
  272. sub finish {
  273. my ($self) = @_;
  274. close($self) || syserr(_g("cannot close %s"), $self->get_filename());
  275. return not *$self->{'errors'};
  276. }
  277. sub register_error {
  278. my ($self) = @_;
  279. *$self->{'errors'}++;
  280. }
  281. sub _fail_with_msg {
  282. my ($self, $file, $msg) = @_;
  283. errormsg(_g("cannot represent change to %s: %s"), $file, $msg);
  284. $self->register_error();
  285. }
  286. sub _fail_not_same_type {
  287. my ($self, $old, $new) = @_;
  288. my $old_type = get_type($old);
  289. my $new_type = get_type($new);
  290. errormsg(_g("cannot represent change to %s:"), $new);
  291. errormsg(_g(" new version is %s"), $new_type);
  292. errormsg(_g(" old version is %s"), $old_type);
  293. $self->register_error();
  294. }
  295. # check diff for sanity, find directories to create as a side effect
  296. sub analyze {
  297. my ($self, $destdir, %opts) = @_;
  298. $opts{"verbose"} = 1 if not defined $opts{"verbose"};
  299. my $diff = $self->get_filename();
  300. my %filepatched;
  301. my %dirtocreate;
  302. my @patchorder;
  303. my $patch_header = '';
  304. my $diff_count = 0;
  305. sub getline {
  306. my $handle = shift;
  307. my $line = <$handle>;
  308. if (defined $line) {
  309. # Strip end-of-line chars
  310. chomp($line);
  311. $line =~ s/\r$//;
  312. }
  313. return $line;
  314. }
  315. sub strip_ts { # Strip timestamp
  316. my $header = shift;
  317. # Tab is the official separator, it's always used when
  318. # filename contain spaces. Try it first, otherwise strip on space
  319. # if there's no tab
  320. $header =~ s/\s.*// unless ($header =~ s/\t.*//);
  321. return $header;
  322. }
  323. sub intuit_file_patched {
  324. my ($old, $new) = @_;
  325. return $new unless defined $old;
  326. return $old unless defined $new;
  327. return $new if -e $new and not -e $old;
  328. return $old if -e $old and not -e $new;
  329. # We don't consider the case where both files are non-existent and
  330. # where patch picks the one with the fewest directories to create
  331. # since dpkg-source will pre-create the required directories
  332. #
  333. # Precalculate metrics used by patch
  334. my ($tmp_o, $tmp_n) = ($old, $new);
  335. my ($len_o, $len_n) = (length($old), length($new));
  336. $tmp_o =~ s{[/\\]+}{/}g;
  337. $tmp_n =~ s{[/\\]+}{/}g;
  338. my $nb_comp_o = ($tmp_o =~ tr{/}{/});
  339. my $nb_comp_n = ($tmp_n =~ tr{/}{/});
  340. $tmp_o =~ s{^.*/}{};
  341. $tmp_n =~ s{^.*/}{};
  342. my ($blen_o, $blen_n) = (length($tmp_o), length($tmp_n));
  343. # Decide like patch would
  344. if ($nb_comp_o != $nb_comp_n) {
  345. return ($nb_comp_o < $nb_comp_n) ? $old : $new;
  346. } elsif ($blen_o != $blen_n) {
  347. return ($blen_o < $blen_n) ? $old : $new;
  348. } elsif ($len_o != $len_n) {
  349. return ($len_o < $len_n) ? $old : $new;
  350. }
  351. return $old;
  352. }
  353. $_ = getline($self);
  354. HUNK:
  355. while (defined($_) || not eof($self)) {
  356. my (%path, %fn);
  357. # skip comments leading up to patch (if any)
  358. while (1) {
  359. if (/^--- /) {
  360. last;
  361. } else {
  362. $patch_header .= "$_\n";
  363. }
  364. last HUNK if not defined($_ = getline($self));
  365. }
  366. $diff_count++;
  367. # read file header (---/+++ pair)
  368. unless(s/^--- //) {
  369. error(_g("expected ^--- in line %d of diff `%s'"), $., $diff);
  370. }
  371. $path{'old'} = $_ = strip_ts($_);
  372. $fn{'old'} = $_ if $_ ne '/dev/null' and s{^[^/]*/+}{$destdir/};
  373. if (/\.dpkg-orig$/) {
  374. error(_g("diff `%s' patches file with name ending .dpkg-orig"), $diff);
  375. }
  376. unless (defined($_ = getline($self))) {
  377. error(_g("diff `%s' finishes in middle of ---/+++ (line %d)"), $diff, $.);
  378. }
  379. unless (s/^\+\+\+ //) {
  380. error(_g("line after --- isn't as expected in diff `%s' (line %d)"), $diff, $.);
  381. }
  382. $path{'new'} = $_ = strip_ts($_);
  383. $fn{'new'} = $_ if $_ ne '/dev/null' and s{^[^/]*/+}{$destdir/};
  384. unless (defined $fn{'old'} or defined $fn{'new'}) {
  385. error(_g("none of the filenames in ---/+++ are valid in diff '%s' (line %d)"),
  386. $diff, $.);
  387. }
  388. # Safety checks on both filenames that patch could use
  389. foreach my $key ("old", "new") {
  390. next unless defined $fn{$key};
  391. if ($path{$key} =~ m{/\.\./}) {
  392. error(_g("%s contains an insecure path: %s"), $diff, $path{$key});
  393. }
  394. my $path = $fn{$key};
  395. while (1) {
  396. if (-l $path) {
  397. error(_g("diff %s modifies file %s through a symlink: %s"),
  398. $diff, $fn{$key}, $path);
  399. }
  400. last unless $path =~ s{/+[^/]*$}{};
  401. last if length($path) <= length($destdir); # $destdir is assumed safe
  402. }
  403. }
  404. if ($path{'old'} eq '/dev/null' and $path{'new'} eq '/dev/null') {
  405. error(_g("original and modified files are /dev/null in diff `%s' (line %d)"),
  406. $diff, $.);
  407. } elsif ($path{'new'} eq '/dev/null') {
  408. error(_g("file removal without proper filename in diff `%s' (line %d)"),
  409. $diff, $. - 1) unless defined $fn{'old'};
  410. if ($opts{"verbose"}) {
  411. warning(_g("diff %s removes a non-existing file %s (line %d)"),
  412. $diff, $fn{'old'}, $.) unless -e $fn{'old'};
  413. }
  414. }
  415. my $fn = intuit_file_patched($fn{'old'}, $fn{'new'});
  416. my $dirname = $fn;
  417. if ($dirname =~ s{/[^/]+$}{} && not -d $dirname) {
  418. $dirtocreate{$dirname} = 1;
  419. }
  420. if (-e $fn and not -f _) {
  421. error(_g("diff `%s' patches something which is not a plain file"), $diff);
  422. }
  423. if ($filepatched{$fn}) {
  424. warning(_g("diff `%s' patches file %s twice"), $diff, $fn)
  425. if $opts{"verbose"};
  426. } else {
  427. $filepatched{$fn} = 1;
  428. push @patchorder, $fn;
  429. }
  430. # read hunks
  431. my $hunk = 0;
  432. while (defined($_ = getline($self))) {
  433. # read hunk header (@@)
  434. next if /^\\ /;
  435. last unless (/^@@ -\d+(,(\d+))? \+\d+(,(\d+))? @\@( .*)?$/);
  436. my ($olines, $nlines) = ($1 ? $2 : 1, $3 ? $4 : 1);
  437. # read hunk
  438. while ($olines || $nlines) {
  439. unless (defined($_ = getline($self))) {
  440. if (($olines == $nlines) and ($olines < 3)) {
  441. warning(_g("unexpected end of diff `%s'"), $diff)
  442. if $opts{"verbose"};
  443. last;
  444. } else {
  445. error(_g("unexpected end of diff `%s'"), $diff);
  446. }
  447. }
  448. next if /^\\ /;
  449. # Check stats
  450. if (/^ / || /^$/) { --$olines; --$nlines; }
  451. elsif (/^-/) { --$olines; }
  452. elsif (/^\+/) { --$nlines; }
  453. else {
  454. error(_g("expected [ +-] at start of line %d of diff `%s'"),
  455. $., $diff);
  456. }
  457. }
  458. $hunk++;
  459. }
  460. unless($hunk) {
  461. error(_g("expected ^\@\@ at line %d of diff `%s'"), $., $diff);
  462. }
  463. }
  464. close($self);
  465. unless ($diff_count) {
  466. warning(_g("diff `%s' doesn't contain any patch"), $diff)
  467. if $opts{"verbose"};
  468. }
  469. *$self->{'analysis'}{$destdir}{"dirtocreate"} = \%dirtocreate;
  470. *$self->{'analysis'}{$destdir}{"filepatched"} = \%filepatched;
  471. *$self->{'analysis'}{$destdir}{"patchorder"} = \@patchorder;
  472. *$self->{'analysis'}{$destdir}{"patchheader"} = $patch_header;
  473. return *$self->{'analysis'}{$destdir};
  474. }
  475. sub prepare_apply {
  476. my ($self, $analysis, %opts) = @_;
  477. if ($opts{"create_dirs"}) {
  478. foreach my $dir (keys %{$analysis->{'dirtocreate'}}) {
  479. eval { mkpath($dir, 0, 0777); };
  480. syserr(_g("cannot create directory %s"), $dir) if $@;
  481. }
  482. }
  483. }
  484. sub apply {
  485. my ($self, $destdir, %opts) = @_;
  486. # Set default values to options
  487. $opts{"force_timestamp"} = 1 unless exists $opts{"force_timestamp"};
  488. $opts{"remove_backup"} = 1 unless exists $opts{"remove_backup"};
  489. $opts{"create_dirs"} = 1 unless exists $opts{"create_dirs"};
  490. $opts{"options"} ||= [ '-t', '-F', '0', '-N', '-p1', '-u',
  491. '-V', 'never', '-g0', '-b', '-z', '.dpkg-orig'];
  492. $opts{"add_options"} ||= [];
  493. push @{$opts{"options"}}, @{$opts{"add_options"}};
  494. # Check the diff and create missing directories
  495. my $analysis = $self->analyze($destdir, %opts);
  496. $self->prepare_apply($analysis, %opts);
  497. # Apply the patch
  498. $self->ensure_open("r");
  499. my ($stdout, $stderr) = ('', '');
  500. spawn(
  501. 'exec' => [ 'patch', @{$opts{"options"}} ],
  502. 'chdir' => $destdir,
  503. 'env' => { LC_ALL => 'C', LANG => 'C' },
  504. 'delete_env' => [ 'POSIXLY_CORRECT' ], # ensure expected patch behaviour
  505. 'wait_child' => 1,
  506. 'nocheck' => 1,
  507. 'from_handle' => $self->get_filehandle(),
  508. 'to_string' => \$stdout,
  509. 'error_to_string' => \$stderr,
  510. );
  511. if ($?) {
  512. print STDOUT $stdout;
  513. print STDERR $stderr;
  514. subprocerr("LC_ALL=C patch " . join(" ", @{$opts{"options"}}) .
  515. " < " . $self->get_filename());
  516. }
  517. $self->close();
  518. # Reset the timestamp of all the patched files
  519. # and remove .dpkg-orig files
  520. my @files = keys %{$analysis->{'filepatched'}};
  521. my $now = $opts{"timestamp"};
  522. $now ||= fs_time($files[0]) if $opts{"force_timestamp"} and scalar @files;
  523. foreach my $fn (@files) {
  524. if ($opts{"force_timestamp"}) {
  525. utime($now, $now, $fn) || $! == ENOENT ||
  526. syserr(_g("cannot change timestamp for %s"), $fn);
  527. }
  528. if ($opts{"remove_backup"}) {
  529. $fn .= ".dpkg-orig";
  530. unlink($fn) || syserr(_g("remove patch backup file %s"), $fn);
  531. }
  532. }
  533. return $analysis;
  534. }
  535. # Verify if check will work...
  536. sub check_apply {
  537. my ($self, $destdir, %opts) = @_;
  538. # Set default values to options
  539. $opts{"create_dirs"} = 1 unless exists $opts{"create_dirs"};
  540. $opts{"options"} ||= [ '--dry-run', '-s', '-t', '-F', '0', '-N', '-p1', '-u',
  541. '-V', 'never', '-g0', '-b', '-z', '.dpkg-orig'];
  542. $opts{"add_options"} ||= [];
  543. push @{$opts{"options"}}, @{$opts{"add_options"}};
  544. # Check the diff and create missing directories
  545. my $analysis = $self->analyze($destdir, %opts);
  546. $self->prepare_apply($analysis, %opts);
  547. # Apply the patch
  548. $self->ensure_open("r");
  549. my $error;
  550. my $patch_pid = spawn(
  551. 'exec' => [ 'patch', @{$opts{"options"}} ],
  552. 'chdir' => $destdir,
  553. 'env' => { LC_ALL => 'C', LANG => 'C' },
  554. 'delete_env' => [ 'POSIXLY_CORRECT' ], # ensure expected patch behaviour
  555. 'from_handle' => $self->get_filehandle(),
  556. 'to_file' => '/dev/null',
  557. 'error_to_file' => '/dev/null',
  558. );
  559. wait_child($patch_pid, nocheck => 1);
  560. my $exit = WEXITSTATUS($?);
  561. subprocerr("patch --dry-run") unless WIFEXITED($?);
  562. $self->close();
  563. return ($exit == 0);
  564. }
  565. # Helper functions
  566. sub get_type {
  567. my $file = shift;
  568. if (not lstat($file)) {
  569. return _g("nonexistent") if $! == ENOENT;
  570. syserr(_g("cannot stat %s"), $file);
  571. } else {
  572. -f _ && return _g("plain file");
  573. -d _ && return _g("directory");
  574. -l _ && return sprintf(_g("symlink to %s"), readlink($file));
  575. -b _ && return _g("block device");
  576. -c _ && return _g("character device");
  577. -p _ && return _g("named pipe");
  578. -S _ && return _g("named socket");
  579. }
  580. }
  581. 1;