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