-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathp42svn.pl
executable file
·2030 lines (1729 loc) · 67.4 KB
/
p42svn.pl
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
#!/usr/bin/env perl
=pod
=head1 NAME
B<p42svn> - dump Perforce repository in Subversion portable dump/load format.
=head1 SYNOPSIS
B<p42svn> [I<options>] [B<--branch> I<p4_branch_spec=svn_path>] ...
=head1 OPTIONS
=over 8
=item B<--help>
Print detailed help message and exit.
=item B<--usage>
Print brief usage message and exit.
=item B<--debug>
Print debug messages to STDERR.
=item B<--verbose>
Print status messages to STDERR.
=item B<--version>
Print out the version of this program, the P4 API, and Perl itself.
=item B<--dry-run>
Don't actually retrieve file data, but go through the motions. This is
useful for checking depot validity and for debugging.
=item B<--changes> I<list>
Specifies which changelists to process. The list can contain a list of
numbers and ranges separated by commas, such as 12,39-45,68.
=item B<--revlimit> I<num>
Only convert the given number of revisions. This is useful when
doing incremental imports (--changes) of parts of a depot (--branch).
In that case, saying --changes 32, may convert nothing if change 32
is not within the scope of the --branch specs.
=item B<--branch> I<p4_depot_spec=svn_path>
Specify mapping of Perforce branch to repository path. Takes an
argument of the form p4_depot_spec=svn_path. Multiple branch mappings
may be specified, but at least one is required.
=item B<--label> I<regexp=p4_depot_spec=svn_path>
Specify mapping of Perforce labels to repository path. The regexp is
used to specify which labels to import, ".*" will match all labels.
The other two parameters are the same as the ones for --branch.
Alternately the keywords "each" or "all" may be given. The keyword
"all" means that labels will be placed in a top level "tags" directory
for all branch mappings. The keyword "each" means that labels will be
placed in a "tags" directory for each branch mapping.
For example, given the branch options
--branch //p1=p1 --branch //p2=p2,
the option --label each would translate to
--label ".*=//p1=/p1/tags" --label ".*=//p2=/p2/tags"
the option --label all would translate to
--label ".*=//p1=/tags/p1" --label ".*=//p2=/tags/p2"
The keyword "none" may also be given. This has the effect of canceling out
all other --label options on the command line. This is really only useful
in when this is called from L<p42svnsync>.
=item B<--redolabels|--noredolabels>
Do/don't redo labels on files which already have already been tagged in SVN.
The default is to not redo labels. The only reason to change this is if
you have labels moving onto different versions of the same files.
Only meaningful with --label, --changes, --existing-revs and --existing-files
(in other words, incremental imports).
=item B<--munge-keywords|--nomunge-keywords>
Do/don't convert Perforce keywords to their Subversion equivalent.
Default is not to perform keyword conversion.
=item B<--convert-eol|--noconvert-eol>
Do/don't set the svn:eol-style property for Perforce types text/unicode.
Default is not to set the svn:eol-style property.
=item B<--parse-mime-types|--noparse-mime-types>
Do/don't attempt to parse content MIME type and add svn:mime-type
property. Default is not to parse MIME types.
=item B<--mime-magic-path> I<path>
Specify path of MIME magic file, overriding the default
F</usr/share/file/magic.mime>. Ignored unless B<--parse-mime-types>
is true.
=item B<--delete-empty-dirs|--nodelete-empty-dirs>
Do/don't delete the parent directory when the last file/directory it
contains is deleted. Default is to delete empty directories.
=item B<--user> I<name>
Specify Perforce username; this overrides $P4USER, $USER, and
$USERNAME in the environment.
=item B<--client> I<name>
Specify Perforce client; this overrides $P4CLIENT in the environment
and the default, the hostname.
=item B<--port> I<[host:]port>
Specify Perforce server and port; this overrides $P4PORT in the
environment and the default, perforce:1666.
=item B<--password> I<token>
Specify Perforce password; this overrides $P4PASSWD in the
environment.
=item B<--charset> I<token>
Specify Perforce charset; this overrides $P4CHARSET in the
environment
=item B<--fix-case> I<map|uc|lc|ucfirst>
If a Perforce repository is hosted on a case-insensitive filesystem
the depot may return pathnames with varying case. The parameters
"uc", "lc", and "ucfirst" use the corresponding perl functions to
transform the case to a consistent name. The parameter "map" tells
the converter to map all case variants to the first-encountered
variant.
=item B<--rawcharset> I<charset>
Interpret filenames according to the given character set when
converting filenames to utf8. The default is to interpret filenames
as utf8. A depot used exclusively by windows machines will likely
need to specify cp1252 here.
This may be specified multiple times, and all those character sets will be tried.
UTF8 will always be tried last. If the file is not valid in any character set,
the non-ascii characters will be converted to hex strings.
Do not change this option between runs using --changes as new files
with variant filenames will be introduced.
=item B<--contentcache> I<directory>
Use the given directory as a cache for the contents of each file version.
The first time you run with this option the file contents will be pulled
from the Perforce depot and saved in the cache. On subsequent runs, the
contents will be pulled from the cache rather than from Perforce.
This option is useful if the Perforce depot is distant or slow. It
can also speed up imports by running through the process several
times, saving the cache, and then the production migration can be done
faster.
=item B<--save-changenum> I<prop,comm>
Instructs B<p42svn> to save the Perforce revision number in the
subversion dump file either as a property (if given "prop") or as an
addendum to the checkin comment (if given "comm"), or both (if given
"prop,comm" or "both").
=item B<--svn-change-prop> I<propname>
Set the svn revision property <propname> to the p4 change number,
Implies "--save-changenum prop". Defaults to "p42svn:changenum".
=item B<--syncrevs>
Add in dummy revisions to ensure the Perforce change numbers and the
Subversion change numbers match exactly. Probably only of use in full
depot conversions. This will definitely not work in incremental
imports with labels.
=item B<--existing-files> I<file>
Load a file containing a list of files assumed to already exist
in the svn repository (to be used in conjunction with --changes).
The list can be obtained from svn with the
command "svnlook tree --full-paths repositorypath"
=item B<--existing-revs> I<file>
Load a file containing an SVN log for mapping labels and branches to
their revisions (otherwise file contents will be imported with no
relatinoship to the previous history). This assumes that previous
imports have used "--svn-changenum prop" (otherwise no Perforce
revision numbers will be found).
This output is generated with this command:
svn log --xml --with-all-revprops <repository-url>
This will also cause the revision numbers to start at the next
available one in the target repository. There will be trouble if
there are intervening checkins.
=item B<--skipcorrupt>
By default if a file's contents cannot be read from the Perforce server,
the program exits. This option allows the conversion to continue if
the error indicates corruption in the depot. This is useful if there
is corruption in the depot which cannot be fixed.
=item B<--partialrev|--nopartialrev>
If an error occurs while fetching things from Perforce, the dump file
could be truncated in a way that would not indicate that files are
missing in that revision. That is the default behavior, the
option --nopartialrev will try to prevent this by dumping the error
messages into the dump file, which should cause svnadmin load to fail
without completing the in-progress transaction.
=item B<--verify>
Just get the change list from Perforce and compare it to what is in a
subversion repository. You must specify --existing-revs, and that svn
log output must have the file changes (i.e. the -v option), and that
repository must have been generated with the option "--save-changenum
prop".
=item B<--stopfile> I<file>
If the given file is found, p42svn will stop at the end of the
revision/changelist currently being processed.
If not specified, the file monitored is
TMPDIR/p42svn.PID, where TMPDIR is the temporary directory returned by
L<File::Spec::tmpdir> and PID is the process id of the p42svn process.
=back
=head1 DESCRIPTION
B<p42svn> connects to a Perforce server and examines changelists
affecting the specified repository branch(es). Records reflecting
each change are written to STDOUT in Subversion portable dump/load
format. Each Perforce changelist corresponds to a single Subversion
revision. Changelists restricted to files outside the specified
Perforce branch(es) are ignored.
Migration of a Perforce depot to Subversion can thus be achieved in
two easy steps:
=over 4
=item C<svnadmin create /path/to/repository>
=item C<p42svn --branch //depot/projectA=trunk/projectA | svnadmin load /path/to/repository>
=back
It is also possible to specify multiple branch mappings to change the
repository layout when migrating, for example:
=over 4
=item C<p42svn --branch //depot/projectA/devel=projectA/trunk --branch
//depot/projectA/release-1.0=projectA/tags/release1.0>
=back
=head1 REQUIREMENTS
This program requires the Perforce Perl API, which is available for
download from
E<lt>http://www.perforce.com/perforce/loadsupp.html#apiE<gt>.
Version 0.16 has been tested By Ray Miller against version 1.2587 of the P4 module built
against release 2002.2 of the Perforce API.
Versions 0.16, 0.17, and 0.18 have been tested by Dimitri Papadopoulos-Orfanos against
version 3.4804 of the P4 module built against release 2005.2 of the Perforce API.
Version 0.19 has been tested by Dimitri Papadopoulos-Orfanos against version 3.5708 of
the P4 module built against release 2006.1 of the Perforce API.
Version 0.21 has been tested by Dimitri Papadopoulos-Orfanos against version 2008.2 of
the Perforce Perl API and the Perforce C/C++ API.
Version 0.30 has been tested by Trent Fisher against version 2010.1 of
the Perforce Perl API and the Perforce C/C++ API.
=head1 VERSION
This is version 0.30.
=head1 AUTHOR
Ray Miller E<lt>[email protected]<gt>,
Dimitri Papadopoulos-Orfanos,
and
Trent Fisher.
=head1 SEE ALSO
The Subversion dump file format is documented at
http://svn.apache.org/repos/asf/subversion/trunk/notes/dump-load-format.txt
=head1 BUGS
Please report any bugs to the issue tracker
E<lt>http://p42svn.tigris.org/servlets/ProjectIssuesE<gt>.
Accuracy of determined MIME types is dependent on your system's MIME
magic data. This program defaults to using data in
F</usr/share/file/magic.mime>. This location appears to comply with
the Filesystem Hierarchy Standard (FHS) 2.3, although it may differ
from system to system in practice.
The B<--changes> option has known bugs unless used with the
--existing-files and --existing-revs options. Even then there may be
subtle bugs remaining. Also --existing-revs doesn't use a full XML
parser so if SVN changes their formatting, it could break.
The ETA calculations do not take into account the number of actions
being performed each rev.
The --syncrevs option may be ill-advised and incorrect in some cases.
=head1 COPYRIGHT
Copyright (C) 2010-2012 Oracle and/or its affiliates.
Copyright (C) 2006-2009 Commissariat a l'Energie Atomique
Copyright (C) 2003-2006 University of Oxford
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
=cut
use strict;
use warnings;
use P4;
use Data::Dumper;
use Date::Format;
use Digest::MD5 qw(md5_hex);
use File::MMagic;
use Getopt::Long;
use Pod::Usage;
use File::Temp;
use File::Spec;
use Encode qw(decode encode_utf8);
use constant MIME_MAGIC_PATH => '/usr/share/file/magic.mime';
use constant SVN_FS_DUMP_FORMAT_VERSION => 1;
use constant SVN_DATE_TEMPLATE => '%Y-%m-%dT%T.000000Z';
our (%rev_map, %rev_act, %dir_seen, %file_seen, %dir_usage, @deleted_files, @ranges);
my $svn_rev = 1;
our %KEYWORD_MAP = ('Author' => 'LastChangedBy',
'Date' => 'LastChangedDate',
'Revision' => 'LastChangedRevision',
'File' => 'HeadURL',
'Id' => 'Id');
use constant OPT_SPEC => qw(help usage debug verbose|v dry-run changes=s ignore!
branch=s% delete-empty-dirs! munge-keywords!
convert-eol! parse-mime-types! mime-magic-path=s
user=s client=s port=s password=s charset=s
label=s@ fix-case=s save-changenum=s rawcharset=s
contentcache=s syncrevs skipcorrupt partialrev!
existing-revs=s existing-files=s
redolabels! verify revlimit=i
svn-change-prop=s version);
our %options = ('help' => 0,
'usage' => 0,
'version' => 0,
'debug' => 0,
'verbose' => 0,
'dry-run' => 0,
'ignore' => 1,
'changes' => undef,
'delete-empty-dirs' => 1,
'munge-keywords' => 0,
'convert-eol' => 0,
'parse-mime-types' => 0,
'label' => [],
'redolabels' => 0,
'fix-case' => 0,
'save-changenum' => [],
'rawcharset' => [],
'contentcache' => 0,
'syncrevs' => 0,
'existing-files' => undef,
'existing-revs' => undef,
'verify' => undef,
'svn-change-prop' => undef,
'skipcorrupt' => undef,
'partialrev' => 1,
'revlimit' => 0,
'stopfile' => File::Spec->catfile(
File::Spec->tmpdir(), "p42svn.$$"),
'mime-magic-path' => MIME_MAGIC_PATH,
'branch' => {});
########################################################################
# Identify Perforce Perl API version, so that we can adapt to the API.
########################################################################
my $p4perl_version = undef;
if (defined $P4::VERSION) {
# This is original version of P4Perl from Tony Smith's page.
# Latest version 3.6001 has been written for P4API 2007.2 or earlier.
$p4perl_version = $P4::VERSION;
$p4perl_version =~ s/^\s+//;
$p4perl_version =~ s/\s+$//;
} else {
# This the new version of the Perforce Perl API from the FTP server.
# The Perforce Perl API is now released together with Perforce,
# starting with 2007.3.
$p4perl_version = P4::Identify();
if ($p4perl_version =~ /P4PERL\/[^\/]+\/(\d+\.\d+)[^\/]*\/\d+/s) {
$p4perl_version = $1;
}
}
my $p42svn_version = 0.30;
########################################################################
# Print debugging messages when debug option is set.
########################################################################
sub debug {
return unless $options{'debug'};
print STDERR @_;
}
sub verbose {
return unless $options{'verbose'} or $options{'debug'};
if (ref $_[0] eq "CODE")
{
print STDERR $_[0]->();
}
else
{
print STDERR @_;
}
}
# display seconds as days+hours:min:sec
sub hourminsec
{
my $seconds = shift;
my ($days,$hours,$minutes);
$days = int($seconds / (24 * 3600));
$seconds -= $days * (24 * 3600);
$hours = int($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = int($seconds / 60);
$seconds -= $minutes * 60;
return sprintf("%d+%02d:%02d:%02d",
$days, $hours, $minutes, $seconds) if $days;
return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds)
}
########################################################################
# Helper routines for option validation.
########################################################################
sub is_valid_depot {
my $depot = shift;
return $depot =~ m{^//([^/]+/?)*$};
}
sub is_valid_svnpath {
my $path = shift;
return $path =~ m{^/?([^/]+/?)*$};
}
########################################################################
# Helper routines for handling changelist ranges.
########################################################################
sub is_in_range {
my $change = shift;
return 1 unless @ranges;
foreach (@ranges) {
$_->[0] <= $change && $change <= $_->[1] && return 1;
}
return 0;
}
########################################################################
# Process command-line options.
########################################################################
sub process_options {
GetOptions(\%options, OPT_SPEC) and @ARGV == 0
or pod2usage(-exitval => 2, -verbose => 1);
pod2usage(-exitval => 1, -verbose => 2)
if $options{'help'};
pod2usage(-exitval => 1, -verbose => 1)
if $options{'usage'};
if ($options{'version'}) {
print "p42svn version $p42svn_version using p4perl $p4perl_version and perl $]\n";
exit 0;
}
pod2usage(-exitval => 2, -verbose => 0,
-message => "Must specify at least one branch or label")
unless keys %{$options{'branch'}} || @{$options{'label'}};
pod2usage(-exitval => 1, -verbose => 0,
-message => "Must specify --existing-revs with --verify")
if $options{'verify'} and not $options{'existing-revs'};
if ($options{'stopfile'} and -e $options{'stopfile'}) {
unlink($options{'stopfile'}) or
die "Error: stopfile ".$options{'stopfile'}." cannot be removed: $!\n";
}
# the incoming character sets should always end with utf8
push @{$options{'rawcharset'}}, "utf8";
# Build list of [start,end] pairs (changelist ranges to process)
if ($options{'changes'}) {
foreach (split(/,/,$options{'changes'})) {
my @range = split(/-/,$_);
pod2usage(-exitval => 3, -verbose => 1,
-message => "Invalid range of changelists")
if (@range > 2);
push(@ranges, [int($range[0]),int($range[$#range])]);
}
}
# Validate and sanitize branch specifications
while (my ($key, $val) = each %{$options{'branch'}}) {
pod2usage(-exitval => 2, -verbose => 0,
-message => "Invalid Perforce depot specification: \"$key\"")
unless is_valid_depot($key);
pod2usage(-exitval => 2, -verbose => 0,
-message => "Invalid Subversion repository path \"$val\"")
unless is_valid_svnpath($val);
# make sure there's a trailing slash, if anything is there
if ($val =~ m{.+[^/]$}) {
$options{'branch'}{$key} .= "/";
}
if ($key =~ m{[^/]$}) {
$options{'branch'}{"$key/"} = $options{'branch'}{$key};
delete $options{'branch'}{$key};
$key .= "/";
}
debug("process_options: branch $key => $options{'branch'}{$key}\n");
}
# Validate and sanitize label specifications
# first deal with special shorthand keywords
# the keyword "none" will eliminate all label options
$options{'label'} = [] if $options{'label'} and grep(/^none$/, @{$options{'label'}});
# the keyword "all" means that all labels should go to a global /tags
if ($options{'label'}[0] and $options{'label'}[0] eq "all") {
$options{'label'} = [];
while (my ($key, $val) = each %{$options{'branch'}}) {
my $s = ".*=$key=tags/$val";
push @{$options{'label'}}, $s;
debug("process_options: all labels add $s\n");
}
# the keyword each means each label should go to separate tags dirs
} elsif ($options{'label'}[0] and $options{'label'}[0] eq "each") {
$options{'label'} = [];
while (my ($key, $val) = each %{$options{'branch'}}) {
my $s = ".*=$key=$val"."tags/";
push @{$options{'label'}}, $s;
debug("process_options: all labels add $s\n");
}
}
foreach my $l (@{$options{'label'}}) {
my ($labelre, $from, $to) = split(/=/, $l);
pod2usage(-exitval => 2, -verbose => 0,
-message => "bad label substitution \"$l\"")
unless defined $from && defined $to;
pod2usage(-exitval => 2, -verbose => 0,
-message => "Invalid Perforce depot specification: \"$from\"")
unless is_valid_depot($from);
pod2usage(-exitval => 2, -verbose => 0,
-message => "Invalid Subversion repository path \"$to\"")
unless $to eq "DISCARD" or is_valid_svnpath($to);
# ensure paths end with a single slash and no leading slashes on svn dest
$from =~ s,/*$,/,;
$to =~ s,/*$,/,;
$to =~ s,^/+,,;
$l = join("=", $labelre, $from, $to);
debug("process_options: label $labelre => $from => $to\n");
}
# Load the directory usage
if($options{'existing-files'}) {
verbose("Loading existing files from ".$options{'existing-files'}."\n");
local *EXF;
open(EXF,'<',$options{'existing-files'}) or
die("Cannot open $options{'existing-files'}: $!");
binmode(EXF, ":utf8");
my $f;
while($f=<EXF>) {
chomp($f);
if($f=~/\/$/) {
$dir_seen{$f}=1;
} else {
$file_seen{$f}=1;
}
casemap($f); # init casemap cache if needed
$dir_usage{parent_directory($f)}++;
}
close EXF;
}
# validate/fix the save-changenum arguments:
# split up comma separated things, and substitute "both" with "prop,comm"
$options{'save-changenum'} = [
map(split(/,/, $_),
grep(s/^(both|all)$/prop,comm/ || $_,
map(split(/,/, $_), @{$options{'save-changenum'}})))];
if (my @bad = grep($_ !~ /^(prop|comm)$/, @{$options{'save-changenum'}}))
{
die "Error: invalid --save-changenum argument @bad\n";
}
# if --svn-change-prop is set, make sure save-changenum is set too
push @{$options{'save-changenum'}}, "prop"
if $options{'svn-change-prop'};
# set the default property name
$options{'svn-change-prop'} = 'p42svn:changenum'
unless $options{'svn-change-prop'};
debug("process_options: save-changenum = ".join(", ", @{$options{'save-changenum'}})."\n");
if($options{'existing-revs'}) {
verbose("Loading existing revs from ".$options{'existing-revs'}."\n");
# we expect output from svn log --xml --with-all-revprops
# though we aren't doing full xml parsing
local *EXR;
open(EXR,'<',$options{'existing-revs'}) or
die("Cannot open $options{'existing-revs'}: $!");
binmode(EXR, ":utf8");
my $f;
my $rev;
my $kind;
while($f=<EXR>) {
if ($f =~ /revision="(\d+)">/) {
# this is also the svn rev used in the dump file
$rev = $1;
$svn_rev = $rev+1 if $rev > $svn_rev;
}
elsif ($f =~ m/name="$options{'svn-change-prop'}">(\d+)/) {
# use the first rev we find, as earlier ones could
# be incomplete
if ($rev_map{$1}) {
warn "Warning: duplicate revision for p4 $1 in svn $rev (using ".$rev_map{$1}.")\n";
} else {
$rev_map{$1} = $rev;
}
}
elsif ($f =~ m/kind="(\w+)"/)
{
$kind = $1;
}
elsif ($f =~ m/action="(\w)">(.+)<\/path>/)
{
push @{$rev_act{$rev}}, {kind => $kind,
action => $1,
path => $2};
}
}
}
}
########################################################################
# Does Perforce file lie in a branch we're processing?
########################################################################
sub is_wanted_file {
my $filespec = shift;
debug("is_wanted_file: $filespec\n");
foreach (keys %{$options{'branch'}}) {
debug("is_wanted_file: considering $_\n");
return 1 if $filespec =~ /^$_/ and $options{'branch'}{$_} ne "EXCLUDE";
return 1 if $options{'fix-case'} and $filespec =~ /^$_/i and $options{'branch'}{$_} ne "EXCLUDE";;
}
debug("is_wanted_file: ignoring $filespec\n");
return 0;
}
########################################################################
# Map Perforce depot spec to Subversion path.
########################################################################
# fix any characters to conform to utf8
sub fixcharset {
my $origional = shift;
my $rawcharset;
my $converted;
foreach $rawcharset (@{$options{'rawcharset'}}) {
my $d = $origional; # we do this because decode can change it's arg
$converted = eval { local $SIG{__DIE__} = "DEFAULT";
decode($rawcharset,
$d, Encode::FB_CROAK); };
last unless $@;
}
if (not $converted) {
warn "Warning: Cannot convert string $origional to utf8, forcing to ascii: $@\n";
$converted = $origional;
$converted =~ s/([[:^ascii:]])/sprintf('=%X', ord($1))/ge;
}
# display the non ascii chars with hex codes
if ($options{'debug'} and $converted ne $origional) {
my $o = sprintf("depot2svnpath: mapping charset %5s: %s\n".
" to utf8: %s\n",
$rawcharset, $origional, $converted);
$o =~ s/([[:^ascii:]])/sprintf('\\x{%x}', ord($1))/ge;
debug($o);
}
# this doesn't really belong here... fix line endings
$converted =~ s/\r//g;
return $converted;
}
sub depot2svnpath {
my $depot = shift;
my $branches = $options{'branch'};
my $key = undef;
# first try to turn the pathname into valid utf8,
# if it fails, issue a warning and do the conversion
# such that a substitute utf8 char will be used instead
$depot = fixcharset($depot);
local $_;
foreach (sort {length($a) <=> length($b)} keys %$branches) {
if ($depot =~ /^$_/ or ($options{'fix-case'} and $depot =~ /^$_/i) ) {
$key = $_;
last;
}
}
return undef unless $key;
my $svnpath = $depot;
($options{'fix-case'} ?
$svnpath =~ s/^$key/$branches->{$key}/i :
$svnpath =~ s/^$key/$branches->{$key}/) or
warn "Error: unable to map $key to $branches->{$key}";
$svnpath =~ s/%40/@/;
$svnpath =~ s/%23/#/;
$svnpath =~ s/%2a/*/;
$svnpath =~ s/%25/%/;
debug("depot2svnpath: $depot => $svnpath\n");
$svnpath = casemap($svnpath);
return $svnpath;
}
my $casemapcache = {};
sub casemap
{
my $svnpath = shift;
# if the depot is on a case-insensitive server we may get paths
# with any case, so we try to map them to the first case we encountered
if ($options{'fix-case'} =~ /^(uc|lc|ucfirst)$/i)
{
my $origsvnpath = $svnpath;
# brute force... but fast... and less memory :)
if (lc($1) eq "lc") { $svnpath = lc($svnpath); }
elsif (lc($1) eq "uc") { $svnpath = uc($svnpath); }
elsif (lc($1) eq "ucfirst") {
$svnpath =~ s,(/)([^/])([^/]*),$1.uc($2).lc($3),ge; }
debug("casemap: mapping case $origsvnpath\n".
" to $svnpath\n")
if $origsvnpath ne $svnpath;
}
elsif ($options{'fix-case'} eq "map")
{
my $origsvnpath = $svnpath;
my @path = split(m([\\/]), $svnpath);
my $root = $casemapcache;
my @mpath = ();
while (@path)
{
my $this = shift @path;
# create an entry if there isn't one
$root->{lc($this)} = [$this, {}]
if (not exists $root->{lc($this)});
push @mpath, $root->{lc($this)}[0];
# continue examining path
$root = $root->{lc($this)}[1];
}
$svnpath = join("/", @mpath);
debug("casemap: mapping case $origsvnpath\n".
" to $svnpath\n")
if $origsvnpath ne $svnpath;
}
return $svnpath;
}
########################################################################
# Helper routines for Perforce file types.
########################################################################
sub p4_has_keyword_expansion {
my $type = shift;
return $type =~ /^k/ || $type =~ /\+.*k/;
}
sub p4_has_executable_flag {
my $type = shift;
return $type =~ /^[cku]?x/ || $type =~ /\+.*x/;
}
sub p4_has_text_flag {
my $type = shift;
return $type =~ /text|unicode/;
}
########################################################################
# Return property list based on Perforce file type and (optionally)
# content MIME type.
########################################################################
my $mmagic;
sub properties {
my ($type, $content_ref) = @_;
my @properties;
if (p4_has_keyword_expansion($type)) {
push @properties, 'svn:keywords' => join(' ', values %KEYWORD_MAP);
}
if (p4_has_executable_flag($type)) {
push @properties, 'svn:executable' => 'on';
}
if ($options{'convert-eol'} && p4_has_text_flag($type)) {
push @properties, 'svn:eol-style' => 'native';
}
if ($options{'parse-mime-types'}) {
unless ($mmagic) {
$mmagic = File::MMagic->new($options{'mime-magic-path'})
or die "Unable to open MIME magic file "
. $options{'mime-magic-path'} . $!;
}
my $mtype = $mmagic->checktype_contents($$content_ref);
push(@properties, 'svn:mime-type' => $mtype) if $mtype;
}
return \@properties;
}
########################################################################
# Replace Perforce keywords in file content with equivalent Subversion
# keywords.
########################################################################
sub munge_keywords {
return unless $options{'munge-keywords'};
my $content_ref = shift;
while (my ($key, $val) = each %KEYWORD_MAP) {
$$content_ref =~ s/\$$key(?\:[^\$\n]*)?\$(\W)/\$$val\$$1/g;
}
}
########################################################################
# Return parent directories of a path
########################################################################
sub parent_directories {
my $path = shift;
my @components;
my $offset = 0;
while ((my $ix = index($path, '/', $offset)) >= 0) {
$offset = $ix + 1;
push @components, substr($path, 0, $offset);
}
return @components;
}
########################################################################
# Return parent directory of a path
########################################################################
sub parent_directory {
my $path = shift;
(my $parent_dir = $path) =~ s|[^/]+/?$||;
return $parent_dir;
}
########################################################################
# Convert Subversion property list to string.
########################################################################
sub svn_props2string {
my $properties = shift;
my $result;
if (defined $properties) {
while (my ($key, $val) = splice(@$properties, 0, 2)) {
$result .= sprintf("K %d\n%s\n", length($key), $key);
# this string will be printed out in UTF8, so we
# have to calculate the byte length based on that, but length()
# will give us the number of characters, not encoded bytes
# XXX do we need to do the same for the key?
$result .= sprintf("V %d\n%s\n", length(encode_utf8($val)), $val);
# $result .= sprintf("V %d\n%s\n", length($val), $val);
}
}
$result .= 'PROPS-END';
return $result;
}
########################################################################
# Routines to print Subversion records.
########################################################################
sub svn_dump_format_version {
my ($version) = @_;
print "SVN-fs-dump-format-version: $version\n\n";
}
sub svn_revision {
my ($revision, $properties) = @_;
my $ppty_txt = svn_props2string($properties);
my $ppty_len = length(encode_utf8($ppty_txt)) + 1;
binmode(STDOUT, ":utf8");
print <<EOT;
Revision-number: $revision
Prop-content-length: $ppty_len
Content-length: $ppty_len
$ppty_txt
EOT
binmode(STDOUT);
}
sub svn_add_dir {
my ($path, $properties) = @_;
$dir_usage{parent_directory($path)}++;
my $ppty_txt = svn_props2string($properties);
my $ppty_len = length($ppty_txt) + 1;
binmode(STDOUT, ":utf8");
print <<EOT;
Node-path: $path
Node-kind: dir
Node-action: add
Prop-content-length: $ppty_len
Content-length: $ppty_len
$ppty_txt
EOT
binmode(STDOUT);
}
sub svn_add_file {
my ($path, $properties, $text) = @_;
$dir_usage{parent_directory($path)}++;
my $ppty_txt = svn_props2string($properties);
my $ppty_len = length($ppty_txt) + 1;
my $text_len = length($$text);