1#!/usr/bin/perl -w
2
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)
6#
7# Redistribution and use in source and binary forms, with or without
8# modification, are permitted provided that the following conditions
9# are met:
10#
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. 
19#
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.
30
31# "unpatch" script for WebKit Open Source Project, used to remove patches.
32
33# Differences from invoking "patch -p0 -R":
34#
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
47#
48# Missing features:
49#
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
58
59use strict;
60use warnings;
61
62use Cwd;
63use Digest::MD5;
64use Fcntl qw(:DEFAULT :seek);
65use File::Basename;
66use File::Spec;
67use File::Temp qw(tempfile);
68use Getopt::Long;
69
70use FindBin;
71use lib $FindBin::Bin;
72use VCSUtils;
73
74sub checksum($);
75sub patch($);
76sub revertDirectories();
77sub unapplyPatch($$;$);
78sub unsetChangeLogDate($$);
79
80my $force = 0;
81my $showHelp = 0;
82
83my $optionParseSuccess = GetOptions(
84    "force!" => \$force,
85    "help!" => \$showHelp
86);
87
88if (!$optionParseSuccess || $showHelp) {
89    print STDERR basename($0) . " [-h|--help] [--force] patch1 [patch2 ...]\n";
90    exit 1;
91}
92
93my $globalExitStatus = 0;
94
95my $repositoryRootPath = determineVCSRoot();
96
97my @copiedFiles;
98my %directoriesToCheck;
99
100# Need to use a typeglob to pass the file handle as a parameter,
101# otherwise get a bareword error.
102my @diffHashRefs = parsePatch(*ARGV);
103
104print "Parsed " . @diffHashRefs . " diffs from patch file(s).\n";
105
106my $preparedPatchHash = prepareParsedPatch($force, @diffHashRefs);
107
108my @copyDiffHashRefs = @{$preparedPatchHash->{copyDiffHashRefs}};
109my @nonCopyDiffHashRefs = @{$preparedPatchHash->{nonCopyDiffHashRefs}};
110
111for my $diffHashRef (@nonCopyDiffHashRefs) {
112    patch($diffHashRef);
113}
114
115# Handle copied and moved files last since they may have had post-copy changes that have now been unapplied
116for my $diffHashRef (@copyDiffHashRefs) {
117    patch($diffHashRef);
118}
119
120if (isSVN()) {
121    revertDirectories();
122}
123
124exit $globalExitStatus;
125
126sub checksum($)
127{
128    my $file = shift;
129    open(FILE, $file) or die "Can't open '$file': $!";
130    binmode(FILE);
131    my $checksum = Digest::MD5->new->addfile(*FILE)->hexdigest();
132    close(FILE);
133    return $checksum;
134}
135
136# Args:
137#   $diffHashRef: a diff hash reference of the type returned by parsePatch().
138sub patch($)
139{
140    my ($diffHashRef) = @_;
141
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} || "";
145
146    my $fullPath = $diffHashRef->{indexPath};
147    my $isSvnBinary = $diffHashRef->{isBinary} && $diffHashRef->{isSvn};
148
149    $directoriesToCheck{dirname($fullPath)} = 1;
150
151    my $deletion = 0;
152    my $addition = 0;
153
154    $addition = 1 if ($diffHashRef->{isNew} || $diffHashRef->{copiedFromPath} || $patch =~ /\n@@ -0,0 .* @@/);
155    $deletion = 1 if ($diffHashRef->{isDeletion} || $patch =~ /\n@@ .* \+0,0 @@/);
156
157    if (!$addition && !$deletion && !$isSvnBinary) {
158        # Standard patch, patch tool can handle this.
159        if (basename($fullPath) eq "ChangeLog") {
160            my $changeLogDotOrigExisted = -f "${fullPath}.orig";
161            my $changeLogHash = fixChangeLogPatch($patch);
162            unapplyPatch(unsetChangeLogDate($fullPath, $changeLogHash->{patch}), $fullPath, ["--fuzz=3"]);
163            unlink("${fullPath}.orig") if (! $changeLogDotOrigExisted);
164        } else {
165            unapplyPatch($patch, $fullPath);
166        }
167    } else {
168        # Either a deletion, an addition or a binary change.
169
170        # FIXME: Add support for Git binary files.
171        if ($isSvnBinary) {
172            # Reverse binary change
173            unlink($fullPath) if (-e $fullPath);
174            system "svn", "revert", $fullPath;
175        } elsif ($deletion) {
176            # Reverse deletion
177            rename($fullPath, "$fullPath.orig") if -e $fullPath;
178
179            unapplyPatch($patch, $fullPath);
180
181            # If we don't ask for the filehandle here, we always get a warning.
182            my ($fh, $tempPath) = tempfile(basename($fullPath) . "-XXXXXXXX",
183                                           DIR => dirname($fullPath), UNLINK => 1);
184            close($fh);
185
186            # Keep the version from the patch in case it's different from svn.
187            rename($fullPath, $tempPath);
188            system "svn", "revert", $fullPath;
189            rename($tempPath, $fullPath);
190
191            # This works around a bug in the svn client.
192            # [Issue 1960] file modifications get lost due to FAT 2s time resolution
193            # http://subversion.tigris.org/issues/show_bug.cgi?id=1960
194            system "touch", $fullPath;
195
196            # Remove $fullPath.orig if it is the same as $fullPath
197            unlink("$fullPath.orig") if -e "$fullPath.orig" && checksum($fullPath) eq checksum("$fullPath.orig");
198
199            # Show status if the file is modifed
200            system "svn", "stat", $fullPath;
201        } else {
202            # Reverse addition
203            #
204            # FIXME: This should use the same logic as svn-apply's deletion
205            #        code.  In particular, svn-apply's scmRemove() subroutine
206            #        should be used here.
207            unapplyPatch($patch, $fullPath, ["--force"]) if $patch;
208            unlink($fullPath) if -z $fullPath;
209            system "svn", "revert", $fullPath;
210        }
211    }
212
213    scmToggleExecutableBit($fullPath, -1 * $diffHashRef->{executableBitDelta}) if defined($diffHashRef->{executableBitDelta});
214}
215
216sub revertDirectories()
217{
218    chdir $repositoryRootPath;
219    my %checkedDirectories;
220    foreach my $path (reverse sort keys %directoriesToCheck) {
221        my @dirs = File::Spec->splitdir($path);
222        while (scalar @dirs) {
223            my $dir = File::Spec->catdir(@dirs);
224            pop(@dirs);
225            next if (exists $checkedDirectories{$dir});
226            if (-d $dir) {
227                my $svnOutput = svnStatus($dir);
228                if ($svnOutput && $svnOutput =~ m#A\s+$dir\n#) {
229                   system "svn", "revert", $dir;
230                   rmdir $dir;
231                }
232                elsif ($svnOutput && $svnOutput =~ m#D\s+$dir\n#) {
233                   system "svn", "revert", $dir;
234                }
235                else {
236                    # Modification
237                    print $svnOutput if $svnOutput;
238                }
239                $checkedDirectories{$dir} = 1;
240            }
241            else {
242                die "'$dir' is not a directory";
243            }
244        }
245    }
246}
247
248# Args:
249#   $patch: a patch string.
250#   $pathRelativeToRoot: the path of the file to be patched, relative to the
251#                        repository root. This should normally be the path
252#                        found in the patch's "Index:" line.
253#   $options: a reference to an array of options to pass to the patch command.
254#             Do not include --reverse in this array.
255sub unapplyPatch($$;$)
256{
257    my ($patch, $pathRelativeToRoot, $options) = @_;
258
259    my $optionalArgs = {options => $options, ensureForce => $force, shouldReverse => 1};
260
261    my $exitStatus = runPatchCommand($patch, $repositoryRootPath, $pathRelativeToRoot, $optionalArgs);
262
263    if ($exitStatus) {
264        $globalExitStatus = $exitStatus;
265    }
266}
267
268sub unsetChangeLogDate($$)
269{
270    my $fullPath = shift;
271    my $patch = shift;
272    my $newDate;
273    sysopen(CHANGELOG, $fullPath, O_RDONLY) or die "Failed to open $fullPath: $!";
274    sysseek(CHANGELOG, 0, SEEK_SET);
275    my $byteCount = sysread(CHANGELOG, $newDate, 10);
276    die "Failed reading $fullPath: $!" if !$byteCount || $byteCount != 10;
277    close(CHANGELOG);
278    $patch =~ s/(\n\+)\d{4}-[^-]{2}-[^-]{2}(  )/$1$newDate$2/;
279    return $patch;
280}
281