forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVCSUtils.pm
2461 lines (2170 loc) · 87.3 KB
/
VCSUtils.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2007-2022 Apple Inc. All rights reserved.
# Copyright (C) 2009, 2010 Chris Jerdonek ([email protected])
# Copyright (C) 2010, 2011 Research In Motion Limited. All rights reserved.
# Copyright (C) 2012 Daniel Bates ([email protected])
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of Apple Inc. ("Apple") nor the names of
# its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Module to share code to work with various version control systems.
package VCSUtils;
use strict;
use warnings;
use Cwd qw(); # "qw()" prevents warnings about redefining getcwd() with "use POSIX;"
use English; # for $POSTMATCH, etc.
use File::Basename;
use File::Spec;
use POSIX;
use Term::ANSIColor qw(colored);
BEGIN {
use Exporter ();
our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
$VERSION = 1.00;
@ISA = qw(Exporter);
@EXPORT = qw(
&applyGitBinaryPatchDelta
&callSilently
&canonicalizePath
&changeLogEmailAddress
&changeLogName
&chdirReturningRelativePath
&commitForDirectory
&decodeGitBinaryChunk
&decodeGitBinaryPatch
&determineSVNRoot
&determineVCSRoot
&escapeSubversionPath
&exitStatus
&fixChangeLogPatch
&fixSVNPatchForAdditionWithHistory
&gitBranch
&gitBranchForDirectory
&gitCommitForSVNRevision
&gitDirectory
&gitHashForDirectory
&gitTreeDirectory
&gitdiff2svndiff
&isGit
&isGitBranchBuild
&isGitDirectory
&isSVN
&isSVNDirectory
&isSVNVersion16OrNewer
&listOfChangedFilesBetweenRevisions
&makeFilePathRelative
&mergeChangeLogs
&normalizePath
&parseChunkRange
&parseDiffStartLine
&parseFirstEOL
&parsePatch
&parseSvnDiffStartLine
&pathRelativeToSVNRepositoryRootForPath
&possiblyColored
&prepareParsedPatch
&removeEOL
&runCommand
&runPatchCommand
&scmMoveOrRenameFile
&scmToggleExecutableBit
&setChangeLogDateAndReviewer
&svnIdentifierForPath
&svnInfoForPath
&svnRepositoryRootForPath
&svnRevisionForDirectory
&svnStatus
&svnURLForPath
&toWindowsLineEndings
&unixPath
);
%EXPORT_TAGS = ( );
@EXPORT_OK = ();
}
our @EXPORT_OK;
my $gitRoot;
my $isGit;
my $isGitBranchBuild;
my $isSVN;
my $svnVersion;
# Project time zone for Cupertino, CA, US
my $changeLogTimeZone = "PST8PDT";
my $unifiedDiffStartRegEx = qr#^--- ([abc]\/)?([^\r\n]+)#;
my $gitDiffStartRegEx = qr#^diff --git [^\r\n]+#;
my $gitDiffStartWithPrefixRegEx = qr#^diff --git \w/(.+) \w/([^\r\n]+)#; # We suppose that --src-prefix and --dst-prefix don't contain a non-word character (\W) and end with '/'.
my $gitDiffStartWithoutPrefixNoSpaceRegEx = qr#^diff --git (\S+) (\S+)$#;
my $svnDiffStartRegEx = qr#^Index: ([^\r\n]+)#;
my $gitDiffStartWithoutPrefixSourceDirectoryPrefixRegExp = qr#^diff --git ([^/]+/)#;
my $svnPropertiesStartRegEx = qr#^Property changes on: ([^\r\n]+)#; # $1 is normally the same as the index path.
my $svnPropertyStartRegEx = qr#^(Modified|Name|Added|Deleted): ([^\r\n]+)#; # $2 is the name of the property.
my $svnPropertyValueStartRegEx = qr#^\s*(\+|-|Merged|Reverse-merged)\s*([^\r\n]+)#; # $2 is the start of the property's value (which may span multiple lines).
my $svnPropertyValueNoNewlineRegEx = qr#\ No newline at end of property#;
# This method is for portability. Return the system-appropriate exit
# status of a child process.
#
# Args: pass the child error status returned by the last pipe close,
# for example "$?".
sub exitStatus($)
{
my ($returnvalue) = @_;
if (isWindows()) {
return $returnvalue >> 8;
}
if (!WIFEXITED($returnvalue)) {
return 254;
}
return WEXITSTATUS($returnvalue);
}
# Call a function while suppressing STDERR, and return the return values
# as an array.
sub callSilently($@) {
my ($func, @args) = @_;
# The following pattern was taken from here:
# http://www.sdsc.edu/~moreland/courses/IntroPerl/docs/manual/pod/perlfunc/open.html
#
# Also see this Perl documentation (search for "open OLDERR"):
# http://perldoc.perl.org/functions/open.html
open(OLDERR, ">&STDERR");
close(STDERR);
my @returnValue = &$func(@args);
open(STDERR, ">&OLDERR");
close(OLDERR);
return @returnValue;
}
sub toWindowsLineEndings
{
my ($text) = @_;
$text =~ s/\n/\r\n/g;
return $text;
}
# Note, this method will not error if the file corresponding to the $source path does not exist.
sub scmMoveOrRenameFile
{
my ($source, $destination) = @_;
return if ! -e $source;
if (isSVN()) {
my $escapedDestination = escapeSubversionPath($destination);
my $escapedSource = escapeSubversionPath($source);
system("svn", "move", $escapedSource, $escapedDestination);
} elsif (isGit()) {
system("git", "mv", $source, $destination);
}
}
# Note, this method will not error if the file corresponding to the path does not exist.
sub scmToggleExecutableBit
{
my ($path, $executableBitDelta) = @_;
return if ! -e $path;
if ($executableBitDelta == 1) {
scmAddExecutableBit($path);
} elsif ($executableBitDelta == -1) {
scmRemoveExecutableBit($path);
}
}
sub scmAddExecutableBit($)
{
my ($path) = @_;
if (isSVN()) {
my $escapedPath = escapeSubversionPath($path);
system("svn", "propset", "svn:executable", "on", $escapedPath) == 0 or die "Failed to run 'svn propset svn:executable on $escapedPath'.";
} elsif (isGit()) {
chmod(0755, $path);
}
}
sub scmRemoveExecutableBit($)
{
my ($path) = @_;
if (isSVN()) {
my $escapedPath = escapeSubversionPath($path);
system("svn", "propdel", "svn:executable", $escapedPath) == 0 or die "Failed to run 'svn propdel svn:executable $escapedPath'.";
} elsif (isGit()) {
chmod(0664, $path);
}
}
sub isGitDirectory($)
{
my ($directory) = @_;
return system("git -C \"$directory\" rev-parse > " . File::Spec->devnull() . " 2>&1") == 0;
}
sub isGit()
{
return $isGit if defined $isGit;
$isGit = isGitDirectory(".");
return $isGit;
}
sub gitDirectory()
{
chomp(my $result = `git rev-parse --git-dir`);
return $result;
}
sub gitHashForDirectory($)
{
my ($directory) = @_;
my $hash;
if (isGitDirectory($directory)) {
my $command = "git -C \"$directory\" rev-parse HEAD";
$command = "LC_ALL=C $command" if !isWindows();
$hash = `$command`;
chomp($hash);
}
if (!defined($hash)) {
$hash = "unknown";
warn "Unable to determine current Git hash in $directory";
}
return $hash;
}
sub gitTreeDirectory()
{
chomp(my $result = `git rev-parse --show-toplevel`);
return $result;
}
sub gitBisectStartBranchForDirectory($)
{
my ($directory) = @_;
my $bisectStartFile = File::Spec->catfile($directory, "BISECT_START");
if (!-f $bisectStartFile) {
return "";
}
open(BISECT_START, $bisectStartFile) or die "Failed to open $bisectStartFile: $!";
chomp(my $result = <BISECT_START>);
close(BISECT_START);
return $result;
}
sub gitBranchForDirectory($)
{
my ($directory) = @_;
my $gitBranch;
chomp($gitBranch = `git -C \"$directory\" symbolic-ref -q HEAD`);
my $hasDetachedHead = exitStatus($?);
if ($hasDetachedHead) {
# We may be in a git bisect session.
$gitBranch = gitBisectStartBranchForDirectory($directory);
}
$gitBranch =~ s#^refs/heads/##;
$gitBranch = "" if $gitBranch eq "master";
return $gitBranch;
}
sub gitBranch()
{
return gitBranchForDirectory(gitDirectory());
}
sub isGitBranchBuild()
{
my $branch = gitBranch();
chomp(my $override = `git config --bool branch.$branch.webKitBranchBuild`);
return 1 if $override eq "true";
return 0 if $override eq "false";
unless (defined $isGitBranchBuild) {
chomp(my $gitBranchBuild = `git config --bool core.webKitBranchBuild`);
$isGitBranchBuild = $gitBranchBuild eq "true";
}
return $isGitBranchBuild;
}
sub isSVNDirectory($)
{
my ($dir) = @_;
return system("cd $dir && svn info > " . File::Spec->devnull() . " 2>&1") == 0;
}
sub isSVN()
{
return $isSVN if defined $isSVN;
$isSVN = isSVNDirectory(".");
return $isSVN;
}
sub svnVersion()
{
return $svnVersion if defined $svnVersion;
if (!isSVN()) {
$svnVersion = 0;
} else {
chomp($svnVersion = `svn --version --quiet`);
}
return $svnVersion;
}
sub isSVNVersion16OrNewer()
{
my $version = svnVersion();
return "v$version" ge v1.6;
}
sub chdirReturningRelativePath($)
{
my ($directory) = @_;
my $previousDirectory = Cwd::getcwd();
chdir $directory;
my $newDirectory = Cwd::getcwd();
return "." if $newDirectory eq $previousDirectory;
return File::Spec->abs2rel($previousDirectory, $newDirectory);
}
sub commitForDirectory($$)
{
my ($directory, $repository) = @_;
my $result = {
repository_id => $repository,
};
if (isSVNDirectory($directory)) {
$result->{id} = svnRevisionForDirectory($directory);
my $info = svnInfoForPath($directory);
$info =~ /.*Relative URL: \^\/([a-z]+)\n.*/;
my $branch = $1;
$result->{branch} = $branch if ($branch ne 'trunk');
} elsif (isGitDirectory($directory)) {
$result->{id} = gitHashForDirectory($directory);
my $branch = gitBranchForDirectory($directory);
$result->{branch} = $branch if ($branch ne '');
} else {
die "$directory is not a recognized SCM";
}
return $result;
}
sub determineSVNRoot()
{
my $last = '';
my $path = '.';
my $parent = '..';
my $repositoryRoot;
my $repositoryUUID;
while (1) {
my $thisRoot;
my $thisUUID;
my $escapedPath = escapeSubversionPath($path);
# Ignore error messages in case we've run past the root of the checkout.
open INFO, "svn info '$escapedPath' 2> " . File::Spec->devnull() . " |" or die;
while (<INFO>) {
if (/^Repository Root: (.+)/) {
$thisRoot = $1;
}
if (/^Repository UUID: (.+)/) {
$thisUUID = $1;
}
if ($thisRoot && $thisUUID) {
local $/ = undef;
<INFO>; # Consume the rest of the input.
}
}
close INFO;
# It's possible (e.g. for developers of some ports) to have a WebKit
# checkout in a subdirectory of another checkout. So abort if the
# repository root or the repository UUID suddenly changes.
last if !$thisUUID;
$repositoryUUID = $thisUUID if !$repositoryUUID;
last if $thisUUID ne $repositoryUUID;
last if !$thisRoot;
$repositoryRoot = $thisRoot if !$repositoryRoot;
last if $thisRoot ne $repositoryRoot;
$last = $path;
$path = File::Spec->catdir($parent, $path);
}
return File::Spec->rel2abs($last);
}
sub determineVCSRoot()
{
if (isGit()) {
# This is the working tree root. If WebKit is a submodule,
# then the relevant metadata directory is somewhere else.
return gitTreeDirectory();
}
if (!isSVN()) {
# Some users have a workflow where svn-create-patch, svn-apply and
# svn-unapply are used outside of multiple svn working directores,
# so warn the user and assume Subversion is being used in this case.
warn "Unable to determine VCS root for '" . Cwd::getcwd() . "'; assuming Subversion";
$isSVN = 1;
}
return determineSVNRoot();
}
sub isWindows()
{
return ($^O eq "MSWin32") || 0;
}
sub svnRevisionForDirectory($)
{
my ($directory) = @_;
my $revision;
if (isSVNDirectory($directory)) {
my $escapedDir = escapeSubversionPath($directory);
my $command = "svn info $escapedDir | grep Revision:";
$command = "LC_ALL=C $command" if !isWindows();
my $svnInfo = `$command`;
($revision) = ($svnInfo =~ m/Revision: (\d+).*/g);
} elsif (isGitDirectory($directory)) {
my $command = "git -C \"$directory\" log --grep=\"git-svn-id: \" -n 1 | grep git-svn-id:";
$command = "LC_ALL=C $command" if !isWindows();
my $gitLog = `$command`;
($revision) = ($gitLog =~ m/ +git-svn-id: .+@(\d+) /g);
}
if (!defined($revision)) {
$revision = "unknown";
warn "Unable to determine current SVN revision in $directory";
}
return $revision;
}
sub svnInfoForPath($)
{
my ($file) = @_;
my $relativePath = File::Spec->abs2rel($file);
my $svnInfo;
if (isSVNDirectory($file)) {
my $escapedRelativePath = escapeSubversionPath($relativePath);
my $command = "svn info $escapedRelativePath";
$command = "LC_ALL=C $command" if !isWindows();
$svnInfo = `$command`;
} elsif (isGitDirectory($file)) {
my $command = "git -C \"$file\" svn info";
$command = "LC_ALL=C $command" if !isWindows();
$svnInfo = `$command`;
}
return $svnInfo;
}
sub svnURLForPath($)
{
my ($file) = @_;
my $svnInfo = svnInfoForPath($file);
$svnInfo =~ /.*^URL: (.*?)$/m;
return $1;
}
sub svnRepositoryRootForPath($)
{
my ($file) = @_;
my $svnInfo = svnInfoForPath($file);
$svnInfo =~ /.*^Repository Root: (.*?)$/m;
return $1;
}
sub pathRelativeToSVNRepositoryRootForPath($)
{
my ($file) = @_;
my $svnURL = svnURLForPath($file);
my $svnRepositoryRoot = svnRepositoryRootForPath($file);
$svnURL =~ s/$svnRepositoryRoot\///;
return $svnURL;
}
sub svnIdentifierForPath($)
{
my ($file) = @_;
my $path = pathRelativeToSVNRepositoryRootForPath($file);
$path =~ /^(trunk)|tags\/([\w\.\-]*)|branches\/([\w\.\-]*).*$/m;
return $1 || $2 || $3;
}
sub makeFilePathRelative($)
{
my ($path) = @_;
return $path unless isGit();
unless (defined $gitRoot) {
chomp($gitRoot = `git rev-parse --show-cdup`);
}
return $gitRoot . $path;
}
sub normalizePath($)
{
my ($path) = @_;
if (isWindows()) {
$path =~ s/\//\\/g;
} else {
$path =~ s/\\/\//g;
}
return $path;
}
sub unixPath($)
{
my ($path) = @_;
$path =~ s/\\/\//g;
return $path;
}
sub possiblyColored($$)
{
my ($colors, $string) = @_;
if (-t STDOUT) {
return colored([$colors], $string);
} else {
return $string;
}
}
sub canonicalizePath($)
{
my ($file) = @_;
# Remove extra slashes and '.' directories in path
$file = File::Spec->canonpath($file);
# Remove '..' directories in path
my @dirs = ();
foreach my $dir (File::Spec->splitdir($file)) {
if ($dir eq '..' && $#dirs >= 0 && $dirs[$#dirs] ne '..') {
pop(@dirs);
} else {
push(@dirs, $dir);
}
}
return ($#dirs >= 0) ? File::Spec->catdir(@dirs) : ".";
}
sub removeEOL($)
{
my ($line) = @_;
return "" unless $line;
$line =~ s/[\r\n]+$//g;
return $line;
}
sub parseFirstEOL($)
{
my ($fileHandle) = @_;
# Make input record separator the new-line character to simplify regex matching below.
my $savedInputRecordSeparator = $INPUT_RECORD_SEPARATOR;
$INPUT_RECORD_SEPARATOR = "\n";
my $firstLine = <$fileHandle>;
$INPUT_RECORD_SEPARATOR = $savedInputRecordSeparator;
return unless defined($firstLine);
my $eol;
if ($firstLine =~ /\r\n/) {
$eol = "\r\n";
} elsif ($firstLine =~ /\r/) {
$eol = "\r";
} elsif ($firstLine =~ /\n/) {
$eol = "\n";
}
return $eol;
}
sub firstEOLInFile($)
{
my ($file) = @_;
my $eol;
if (open(FILE, $file)) {
$eol = parseFirstEOL(*FILE);
close(FILE);
}
return $eol;
}
# Parses a chunk range line into its components.
#
# A chunk range line has the form: @@ -L_1,N_1 +L_2,N_2 @@, where the pairs (L_1, N_1),
# (L_2, N_2) are ranges that represent the starting line number and line count in the
# original file and new file, respectively.
#
# Note, some versions of GNU diff may omit the comma and trailing line count (e.g. N_1),
# in which case the omitted line count defaults to 1. For example, GNU diff may output
# @@ -1 +1 @@, which is equivalent to @@ -1,1 +1,1 @@.
#
# This subroutine returns undef if given an invalid or malformed chunk range.
#
# Args:
# $line: the line to parse.
# $chunkSentinel: the sentinel that surrounds the chunk range information (defaults to "@@").
#
# Returns $chunkRangeHashRef
# $chunkRangeHashRef: a hash reference representing the parts of a chunk range, as follows--
# startingLine: the starting line in the original file.
# lineCount: the line count in the original file.
# newStartingLine: the new starting line in the new file.
# newLineCount: the new line count in the new file.
sub parseChunkRange($;$)
{
my ($line, $chunkSentinel) = @_;
$chunkSentinel = "@@" if !$chunkSentinel;
my $chunkRangeRegEx = qr#^\Q$chunkSentinel\E -(\d+)(,(\d+))? \+(\d+)(,(\d+))? \Q$chunkSentinel\E#;
if ($line !~ /$chunkRangeRegEx/) {
return;
}
my %chunkRange;
$chunkRange{startingLine} = $1;
$chunkRange{lineCount} = defined($2) ? $3 : 1;
$chunkRange{newStartingLine} = $4;
$chunkRange{newLineCount} = defined($5) ? $6 : 1;
return \%chunkRange;
}
sub svnStatus($)
{
my ($fullPath) = @_;
my $escapedFullPath = escapeSubversionPath($fullPath);
my $svnStatus;
open SVN, "svn status --non-interactive --non-recursive '$escapedFullPath' |" or die;
if (-d $fullPath) {
# When running "svn stat" on a directory, we can't assume that only one
# status will be returned (since any files with a status below the
# directory will be returned), and we can't assume that the directory will
# be first (since any files with unknown status will be listed first).
my $normalizedFullPath = File::Spec->catdir(File::Spec->splitdir($fullPath));
while (<SVN>) {
# Input may use a different EOL sequence than $/, so avoid chomp.
$_ = removeEOL($_);
my $normalizedStatPath = File::Spec->catdir(File::Spec->splitdir(substr($_, 7)));
if ($normalizedFullPath eq $normalizedStatPath) {
$svnStatus = "$_\n";
last;
}
}
# Read the rest of the svn command output to avoid a broken pipe warning.
local $/ = undef;
<SVN>;
}
else {
# Files will have only one status returned.
$svnStatus = removeEOL(<SVN>) . "\n";
}
close SVN;
return $svnStatus;
}
# Return whether the given file mode is executable in the source control
# sense. We make this determination based on whether the executable bit
# is set for "others" rather than the stronger condition that it be set
# for the user, group, and others. This is sufficient for distinguishing
# the default behavior in Git and SVN.
#
# Args:
# $fileMode: A number or string representing a file mode in octal notation.
sub isExecutable($)
{
my $fileMode = shift;
return $fileMode % 2;
}
# Parses an SVN or Git diff header start line.
#
# Args:
# $line: "Index: " line or "diff --git" line.
#
# Returns the path of the target file or undef if the $line is unrecognized.
sub parseDiffStartLine($)
{
my ($line) = @_;
return parseGitDiffStartLine($line) if $line =~ /$gitDiffStartRegEx/;
return parseSvnDiffStartLine($line);
}
# Parse the Git diff header start line.
#
# Args:
# $line: "diff --git" line.
#
# Prerequisites:
# $line argument matches /$gitDiffStartRegEx/.
#
# Returns the path of the target file.
sub parseGitDiffStartLine($)
{
my $line = shift;
$_ = $line;
if (/$gitDiffStartWithPrefixRegEx/ || /$gitDiffStartWithoutPrefixNoSpaceRegEx/) {
return $2;
}
# Assume the diff was generated with --no-prefix (e.g. git diff --no-prefix).
if (!/$gitDiffStartWithoutPrefixSourceDirectoryPrefixRegExp/) {
# FIXME: Moving top directory file is not supported (e.g diff --git A.txt B.txt).
die("Could not find '/' in \"diff --git\" line: \"$line\"; only non-prefixed git diffs (i.e. not generated with --no-prefix) that move a top-level directory file are supported.");
}
my $pathPrefix = $1;
if (!/^diff --git \Q$pathPrefix\E.+ (\Q$pathPrefix\E[^\r\n]+)/) {
# FIXME: Moving a file through sub directories of top directory is not supported (e.g diff --git A/B.txt C/B.txt).
die("Could not find '/' in \"diff --git\" line: \"$line\"; only non-prefixed git diffs (i.e. not generated with --no-prefix) that move a file between top-level directories are supported.");
}
return $1;
}
# Parses an SVN diff header start line.
#
# Args:
# $line: "Index: " line.
#
# Returns the path of the target file or undef if the $line is unrecognized.
sub parseSvnDiffStartLine($)
{
my ($line) = @_;
return $1 if $line =~ /$svnDiffStartRegEx/;
return undef;
}
# Parse the next Git diff header from the given file handle, and advance
# the handle so the last line read is the first line after the header.
#
# This subroutine dies if given leading junk.
#
# Args:
# $fileHandle: advanced so the last line read from the handle is the first
# line of the header to parse. This should be a line
# beginning with "diff --git".
# $line: the line last read from $fileHandle
#
# Returns ($headerHashRef, $lastReadLine):
# $headerHashRef: a hash reference representing a diff header, as follows--
# copiedFromPath: the path from which the file was copied or moved if
# the diff is a copy or move.
# executableBitDelta: the value 1 or -1 if the executable bit was added or
# removed, respectively. New and deleted files have
# this value only if the file is executable, in which
# case the value is 1 and -1, respectively.
# indexPath: the path of the target file.
# isBinary: the value 1 if the diff is for a binary file.
# isDeletion: the value 1 if the diff is a file deletion.
# isCopyWithChanges: the value 1 if the file was copied or moved and
# the target file was changed in some way after being
# copied or moved (e.g. if its contents or executable
# bit were changed).
# isNew: the value 1 if the diff is for a new file.
# shouldDeleteSource: the value 1 if the file was copied or moved and
# the source file was deleted -- i.e. if the copy
# was actually a move.
# svnConvertedText: the header text with some lines converted to SVN
# format. Git-specific lines are preserved.
# $lastReadLine: the line last read from $fileHandle.
sub parseGitDiffHeader($$)
{
my ($fileHandle, $line) = @_;
$_ = $line;
my $indexPath;
if (/$gitDiffStartRegEx/) {
# Use $POSTMATCH to preserve the end-of-line character.
my $eol = $POSTMATCH;
$indexPath = parseGitDiffStartLine($_);
$_ = "Index: $indexPath$eol"; # Convert to SVN format.
} else {
die("Could not parse leading \"diff --git\" line: \"$line\".");
}
my $copiedFromPath;
my $foundHeaderEnding;
my $isBinary;
my $isDeletion;
my $isNew;
my $newExecutableBit = 0;
my $oldExecutableBit = 0;
my $shouldDeleteSource = 0;
my $similarityIndex = 0;
my $svnConvertedText;
while (1) {
# Temporarily strip off any end-of-line characters to simplify
# regex matching below.
s/([\n\r]+)$//;
my $eol = $1;
if (/^(deleted file|old) mode (\d+)/) {
$oldExecutableBit = (isExecutable($2) ? 1 : 0);
$isDeletion = 1 if $1 eq "deleted file";
} elsif (/^new( file)? mode (\d+)/) {
$newExecutableBit = (isExecutable($2) ? 1 : 0);
$isNew = 1 if $1;
} elsif (/^similarity index (\d+)%/) {
$similarityIndex = $1;
} elsif (/^copy from ([^\t\r\n]+)/) {
$copiedFromPath = $1;
} elsif (/^rename from ([^\t\r\n]+)/) {
# FIXME: Record this as a move rather than as a copy-and-delete.
# This will simplify adding rename support to svn-unapply.
# Otherwise, the hash for a deletion would have to know
# everything about the file being deleted in order to
# support undoing itself. Recording as a move will also
# permit us to use "svn move" and "git move".
$copiedFromPath = $1;
$shouldDeleteSource = 1;
} elsif (/^--- \S+/) {
# Convert to SVN format.
# We emit the suffix "\t(revision 0)" to handle $indexPath which contains a space character.
# The patch(1) command thinks a file path is characters before a tab.
# This suffix make our diff more closely match the SVN diff format.
$_ = "--- $indexPath\t(revision 0)";
} elsif (/^\+\+\+ \S+/) {
# Convert to SVN format.
# We emit the suffix "\t(working copy)" to handle $indexPath which contains a space character.
# The patch(1) command thinks a file path is characters before a tab.
# This suffix make our diff more closely match the SVN diff format.
$_ = "+++ $indexPath\t(working copy)";
$foundHeaderEnding = 1;
} elsif (/^GIT binary patch$/ ) {
$isBinary = 1;
$foundHeaderEnding = 1;
# The "git diff" command includes a line of the form "Binary files
# <path1> and <path2> differ" if the --binary flag is not used.
} elsif (/^Binary files / ) {
die("Error: the Git diff contains a binary file without the binary data in ".
"line: \"$_\". Be sure to use the --binary flag when invoking \"git diff\" ".
"with diffs containing binary files.");
}
$svnConvertedText .= "$_$eol"; # Also restore end-of-line characters.
$_ = <$fileHandle>; # Not defined if end-of-file reached.
last if (!defined($_) || /$gitDiffStartRegEx/ || $foundHeaderEnding);
}
my $executableBitDelta = $newExecutableBit - $oldExecutableBit;
my %header;
$header{copiedFromPath} = $copiedFromPath if $copiedFromPath;
$header{executableBitDelta} = $executableBitDelta if $executableBitDelta;
$header{indexPath} = $indexPath;
$header{isBinary} = $isBinary if $isBinary;
$header{isCopyWithChanges} = 1 if ($copiedFromPath && ($similarityIndex != 100 || $executableBitDelta));
$header{isDeletion} = $isDeletion if $isDeletion;
$header{isNew} = $isNew if $isNew;
$header{shouldDeleteSource} = $shouldDeleteSource if $shouldDeleteSource;
$header{svnConvertedText} = $svnConvertedText;
return (\%header, $_);
}
# Parse the next SVN diff header from the given file handle, and advance
# the handle so the last line read is the first line after the header.
#
# This subroutine dies if given leading junk or if it could not detect
# the end of the header block.
#
# Args:
# $fileHandle: advanced so the last line read from the handle is the first
# line of the header to parse. This should be a line
# beginning with "Index:".
# $line: the line last read from $fileHandle
#
# Returns ($headerHashRef, $lastReadLine):
# $headerHashRef: a hash reference representing a diff header, as follows--
# copiedFromPath: the path from which the file was copied if the diff
# is a copy.
# indexPath: the path of the target file, which is the path found in
# the "Index:" line.
# isBinary: the value 1 if the diff is for a binary file.
# isNew: the value 1 if the diff is for a new file.
# sourceRevision: the revision number of the source, if it exists. This
# is the same as the revision number the file was copied
# from, in the case of a file copy.
# svnConvertedText: the header text converted to a header with the paths
# in some lines corrected.
# $lastReadLine: the line last read from $fileHandle.
sub parseSvnDiffHeader($$)
{
my ($fileHandle, $line) = @_;
$_ = $line;
my $indexPath;
if (/$svnDiffStartRegEx/) {
$indexPath = $1;
} else {
die("First line of SVN diff does not begin with \"Index \": \"$_\"");
}
my $copiedFromPath;
my $foundHeaderEnding;
my $isBinary;
my $isDeletion;
my $isNew;
my $sourceRevision;
my $svnConvertedText;
while (1) {
# Temporarily strip off any end-of-line characters to simplify
# regex matching below.
s/([\n\r]+)$//;
my $eol = $1;
# Fix paths on "---" and "+++" lines to match the leading
# index line.
if (s/^--- [^\t\n\r]+/--- $indexPath/) {
# ---
if (/^--- .+\(revision (\d+)\)/) {
$sourceRevision = $1;
$isNew = 1 if !$sourceRevision; # if revision 0.
if (/\(from (\S+):(\d+)\)$/) {
# The "from" clause is created by svn-create-patch, in
# which case there is always also a "revision" clause.
$copiedFromPath = $1;
die("Revision number \"$2\" in \"from\" clause does not match " .
"source revision number \"$sourceRevision\".") if ($2 != $sourceRevision);
}
}
} elsif (s/^\+\+\+ [^\t\n\r]+/+++ $indexPath/ || $isBinary && /^$/) {
$foundHeaderEnding = 1;
} elsif (/^Cannot display: file marked as a binary type.$/) {
$isBinary = 1;
# SVN 1.7 has an unusual display format for a binary diff. It repeats the first
# two lines of the diff header. For example:
# Index: test_file.swf
# ===================================================================
# Cannot display: file marked as a binary type.
# svn:mime-type = application/octet-stream
# Index: test_file.swf
# ===================================================================
# --- test_file.swf
# +++ test_file.swf
#
# ...
# Q1dTBx0AAAB42itg4GlgYJjGwMDDyODMxMDw34GBgQEAJPQDJA==
# Therefore, we continue reading the diff header until we either encounter a line
# that begins with "+++" (SVN 1.7 or greater) or an empty line (SVN version less
# than 1.7).
}
$svnConvertedText .= "$_$eol"; # Also restore end-of-line characters.
$_ = <$fileHandle>; # Not defined if end-of-file reached.