svn-unapply 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. #!/usr/bin/perl -w
  2. # Copyright (C) 2005, 2006, 2007 Apple Inc. All rights reserved.
  3. # Copyright (C) 2009 Cameron McCormack <cam@mcc.id.au>
  4. # Copyright (C) 2010 Chris Jerdonek (chris.jerdonek@gmail.com)
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in the
  14. # documentation and/or other materials provided with the distribution.
  15. # 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
  16. # its contributors may be used to endorse or promote products derived
  17. # from this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
  20. # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  21. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. # DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
  23. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  24. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  25. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  26. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  28. # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. # "unpatch" script for WebKit Open Source Project, used to remove patches.
  30. # Differences from invoking "patch -p0 -R":
  31. #
  32. # Handles added files (does a svn revert with additional logic to handle local changes).
  33. # Handles added directories (does a svn revert and a rmdir).
  34. # Handles removed files (does a svn revert with additional logic to handle local changes).
  35. # Handles removed directories (does a svn revert).
  36. # Paths from Index: lines are used rather than the paths on the patch lines, which
  37. # makes patches generated by "cvs diff" work (increasingly unimportant since we
  38. # use Subversion now).
  39. # ChangeLog patches use --fuzz=3 to prevent rejects, and the entry date is reset in
  40. # the patch before it is applied (svn-apply sets it when applying a patch).
  41. # Handles binary files (requires patches made by svn-create-patch).
  42. # Handles copied and moved files (requires patches made by svn-create-patch).
  43. # Handles git-diff patches (without binary changes) created at the top-level directory
  44. #
  45. # Missing features:
  46. #
  47. # Handle property changes.
  48. # Handle copied and moved directories (would require patches made by svn-create-patch).
  49. # Use version numbers in the patch file and do a 3-way merge.
  50. # When reversing an addition, check that the file matches what's being removed.
  51. # Notice a patch that's being unapplied at the "wrong level" and make it work anyway.
  52. # Do a dry run on the whole patch and don't do anything if part of the patch is
  53. # going to fail (probably too strict unless we exclude ChangeLog).
  54. # Handle git-diff patches with binary changes
  55. use strict;
  56. use warnings;
  57. use Cwd;
  58. use Digest::MD5;
  59. use Fcntl qw(:DEFAULT :seek);
  60. use File::Basename;
  61. use File::Spec;
  62. use File::Temp qw(tempfile);
  63. use Getopt::Long;
  64. use FindBin;
  65. use lib $FindBin::Bin;
  66. use VCSUtils;
  67. sub checksum($);
  68. sub patch($);
  69. sub revertDirectories();
  70. sub unapplyPatch($$;$);
  71. sub unsetChangeLogDate($$);
  72. my $force = 0;
  73. my $showHelp = 0;
  74. my $optionParseSuccess = GetOptions(
  75. "force!" => \$force,
  76. "help!" => \$showHelp
  77. );
  78. if (!$optionParseSuccess || $showHelp) {
  79. print STDERR basename($0) . " [-h|--help] [--force] patch1 [patch2 ...]\n";
  80. exit 1;
  81. }
  82. my $globalExitStatus = 0;
  83. my $repositoryRootPath = determineVCSRoot();
  84. my @copiedFiles;
  85. my %directoriesToCheck;
  86. # Need to use a typeglob to pass the file handle as a parameter,
  87. # otherwise get a bareword error.
  88. my @diffHashRefs = parsePatch(*ARGV);
  89. print "Parsed " . @diffHashRefs . " diffs from patch file(s).\n";
  90. my $preparedPatchHash = prepareParsedPatch($force, @diffHashRefs);
  91. my @copyDiffHashRefs = @{$preparedPatchHash->{copyDiffHashRefs}};
  92. my @nonCopyDiffHashRefs = @{$preparedPatchHash->{nonCopyDiffHashRefs}};
  93. for my $diffHashRef (@nonCopyDiffHashRefs) {
  94. patch($diffHashRef);
  95. }
  96. # Handle copied and moved files last since they may have had post-copy changes that have now been unapplied
  97. for my $diffHashRef (@copyDiffHashRefs) {
  98. patch($diffHashRef);
  99. }
  100. if (isSVN()) {
  101. revertDirectories();
  102. }
  103. exit $globalExitStatus;
  104. sub checksum($)
  105. {
  106. my $file = shift;
  107. open(FILE, $file) or die "Can't open '$file': $!";
  108. binmode(FILE);
  109. my $checksum = Digest::MD5->new->addfile(*FILE)->hexdigest();
  110. close(FILE);
  111. return $checksum;
  112. }
  113. # Args:
  114. # $diffHashRef: a diff hash reference of the type returned by parsePatch().
  115. sub patch($)
  116. {
  117. my ($diffHashRef) = @_;
  118. # Make sure $patch is initialized to some value. There is no
  119. # svnConvertedText when reversing an svn copy/move.
  120. my $patch = $diffHashRef->{svnConvertedText} || "";
  121. my $fullPath = $diffHashRef->{indexPath};
  122. my $isSvnBinary = $diffHashRef->{isBinary} && $diffHashRef->{isSvn};
  123. my $hasTextChunks = $patch && $diffHashRef->{numTextChunks};
  124. $directoriesToCheck{dirname($fullPath)} = 1;
  125. my $deletion = 0;
  126. my $addition = 0;
  127. $addition = 1 if ($diffHashRef->{isNew} || $diffHashRef->{copiedFromPath} || $patch =~ /\n@@ -0,0 .* @@/);
  128. $deletion = 1 if ($diffHashRef->{isDeletion} || $patch =~ /\n@@ .* \+0,0 @@/);
  129. if (!$addition && !$deletion && !$isSvnBinary && $hasTextChunks) {
  130. # Standard patch, patch tool can handle this.
  131. if (basename($fullPath) eq "ChangeLog") {
  132. my $changeLogDotOrigExisted = -f "${fullPath}.orig";
  133. my $changeLogHash = fixChangeLogPatch($patch);
  134. unapplyPatch(unsetChangeLogDate($fullPath, $changeLogHash->{patch}), $fullPath, ["--fuzz=3"]);
  135. unlink("${fullPath}.orig") if (! $changeLogDotOrigExisted);
  136. } else {
  137. unapplyPatch($patch, $fullPath);
  138. }
  139. } else {
  140. # Either a deletion, an addition or a binary change.
  141. my $escapedFullPath = escapeSubversionPath($fullPath);
  142. # FIXME: Add support for Git binary files.
  143. if ($isSvnBinary) {
  144. # Reverse binary change
  145. unlink($fullPath) if (-e $fullPath);
  146. system "svn", "revert", $escapedFullPath;
  147. } elsif ($deletion) {
  148. # Reverse deletion
  149. rename($fullPath, "$fullPath.orig") if -e $fullPath;
  150. unapplyPatch($patch, $fullPath);
  151. # If we don't ask for the filehandle here, we always get a warning.
  152. my ($fh, $tempPath) = tempfile(basename($fullPath) . "-XXXXXXXX",
  153. DIR => dirname($fullPath), UNLINK => 1);
  154. close($fh);
  155. # Keep the version from the patch in case it's different from svn.
  156. rename($fullPath, $tempPath);
  157. system "svn", "revert", $escapedFullPath;
  158. rename($tempPath, $fullPath);
  159. # This works around a bug in the svn client.
  160. # [Issue 1960] file modifications get lost due to FAT 2s time resolution
  161. # http://subversion.tigris.org/issues/show_bug.cgi?id=1960
  162. system "touch", $fullPath;
  163. # Remove $fullPath.orig if it is the same as $fullPath
  164. unlink("$fullPath.orig") if -e "$fullPath.orig" && checksum($fullPath) eq checksum("$fullPath.orig");
  165. # Show status if the file is modifed
  166. system "svn", "stat", $escapedFullPath;
  167. } elsif ($addition) {
  168. # Reverse addition
  169. #
  170. # FIXME: This should use the same logic as svn-apply's deletion
  171. # code. In particular, svn-apply's scmRemove() subroutine
  172. # should be used here.
  173. unapplyPatch($patch, $fullPath, ["--force"]) if $patch;
  174. unlink($fullPath) if -z $fullPath;
  175. system "svn", "revert", $escapedFullPath;
  176. }
  177. }
  178. scmToggleExecutableBit($fullPath, -1 * $diffHashRef->{executableBitDelta}) if defined($diffHashRef->{executableBitDelta});
  179. }
  180. sub revertDirectories()
  181. {
  182. chdir $repositoryRootPath;
  183. my %checkedDirectories;
  184. foreach my $path (reverse sort keys %directoriesToCheck) {
  185. my @dirs = File::Spec->splitdir($path);
  186. while (scalar @dirs) {
  187. my $dir = File::Spec->catdir(@dirs);
  188. pop(@dirs);
  189. next if (exists $checkedDirectories{$dir});
  190. if (-d $dir) {
  191. my $svnOutput = svnStatus($dir);
  192. my $escapedDir = escapeSubversionPath($dir);
  193. if ($svnOutput && $svnOutput =~ m#A\s+$dir\n#) {
  194. system "svn", "revert", $escapedDir;
  195. rmdir $dir;
  196. }
  197. elsif ($svnOutput && $svnOutput =~ m#D\s+$dir\n#) {
  198. system "svn", "revert", $escapedDir;
  199. }
  200. else {
  201. # Modification
  202. print $svnOutput if $svnOutput;
  203. }
  204. $checkedDirectories{$dir} = 1;
  205. }
  206. else {
  207. die "'$dir' is not a directory";
  208. }
  209. }
  210. }
  211. }
  212. # Args:
  213. # $patch: a patch string.
  214. # $pathRelativeToRoot: the path of the file to be patched, relative to the
  215. # repository root. This should normally be the path
  216. # found in the patch's "Index:" line.
  217. # $options: a reference to an array of options to pass to the patch command.
  218. # Do not include --reverse in this array.
  219. sub unapplyPatch($$;$)
  220. {
  221. my ($patch, $pathRelativeToRoot, $options) = @_;
  222. my $optionalArgs = {options => $options, ensureForce => $force, shouldReverse => 1};
  223. my $exitStatus = runPatchCommand($patch, $repositoryRootPath, $pathRelativeToRoot, $optionalArgs);
  224. if ($exitStatus) {
  225. $globalExitStatus = $exitStatus;
  226. }
  227. }
  228. sub unsetChangeLogDate($$)
  229. {
  230. my $fullPath = shift;
  231. my $patch = shift;
  232. my $newDate;
  233. sysopen(CHANGELOG, $fullPath, O_RDONLY) or die "Failed to open $fullPath: $!";
  234. sysseek(CHANGELOG, 0, SEEK_SET);
  235. my $byteCount = sysread(CHANGELOG, $newDate, 10);
  236. die "Failed reading $fullPath: $!" if !$byteCount || $byteCount != 10;
  237. close(CHANGELOG);
  238. $patch =~ s/(\n\+)\d{4}-[^-]{2}-[^-]{2}( )/$1$newDate$2/;
  239. return $patch;
  240. }