2e0d7f0373fe33782d31163f673e9e45491bdac1
1package Git::SVN;
2use strict;
3use warnings;
4use Fcntl qw/:DEFAULT :seek/;
5use constant rev_map_fmt => 'NH40';
6use vars qw/$_no_metadata
7 $_repack $_repack_flags $_use_svm_props $_head
8 $_use_svnsync_props $no_reuse_existing
9 $_use_log_author $_add_author_from $_localtime/;
10use Carp qw/croak/;
11use File::Path qw/mkpath/;
12use File::Copy qw/copy/;
13use IPC::Open3;
14use Time::Local;
15use Memoize; # core since 5.8.0, Jul 2002
16use Memoize::Storable;
17use POSIX qw(:signal_h);
18
19use Git qw(
20 command
21 command_oneline
22 command_noisy
23 command_output_pipe
24 command_close_pipe
25);
26use Git::SVN::Utils qw(fatal can_compress);
27
28my $can_use_yaml;
29BEGIN {
30 $can_use_yaml = eval { require Git::SVN::Memoize::YAML; 1};
31}
32
33our $_follow_parent = 1;
34our $_minimize_url = 'unset';
35our $default_repo_id = 'svn';
36our $default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
37
38my ($_gc_nr, $_gc_period);
39
40# properties that we do not log:
41my %SKIP_PROP;
42BEGIN {
43 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
44 svn:special svn:executable
45 svn:entry:committed-rev
46 svn:entry:last-author
47 svn:entry:uuid
48 svn:entry:committed-date/;
49
50 # some options are read globally, but can be overridden locally
51 # per [svn-remote "..."] section. Command-line options will *NOT*
52 # override options set in an [svn-remote "..."] section
53 no strict 'refs';
54 for my $option (qw/follow_parent no_metadata use_svm_props
55 use_svnsync_props/) {
56 my $key = $option;
57 $key =~ tr/_//d;
58 my $prop = "-$option";
59 *$option = sub {
60 my ($self) = @_;
61 return $self->{$prop} if exists $self->{$prop};
62 my $k = "svn-remote.$self->{repo_id}.$key";
63 eval { command_oneline(qw/config --get/, $k) };
64 if ($@) {
65 $self->{$prop} = ${"Git::SVN::_$option"};
66 } else {
67 my $v = command_oneline(qw/config --bool/,$k);
68 $self->{$prop} = $v eq 'false' ? 0 : 1;
69 }
70 return $self->{$prop};
71 }
72 }
73}
74
75
76my (%LOCKFILES, %INDEX_FILES);
77END {
78 unlink keys %LOCKFILES if %LOCKFILES;
79 unlink keys %INDEX_FILES if %INDEX_FILES;
80}
81
82sub resolve_local_globs {
83 my ($url, $fetch, $glob_spec) = @_;
84 return unless defined $glob_spec;
85 my $ref = $glob_spec->{ref};
86 my $path = $glob_spec->{path};
87 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
88 next unless m#^$ref->{regex}$#;
89 my $p = $1;
90 my $pathname = desanitize_refname($path->full_path($p));
91 my $refname = desanitize_refname($ref->full_path($p));
92 if (my $existing = $fetch->{$pathname}) {
93 if ($existing ne $refname) {
94 die "Refspec conflict:\n",
95 "existing: $existing\n",
96 " globbed: $refname\n";
97 }
98 my $u = (::cmt_metadata("$refname"))[0];
99 $u =~ s!^\Q$url\E(/|$)!! or die
100 "$refname: '$url' not found in '$u'\n";
101 if ($pathname ne $u) {
102 warn "W: Refspec glob conflict ",
103 "(ref: $refname):\n",
104 "expected path: $pathname\n",
105 " real path: $u\n",
106 "Continuing ahead with $u\n";
107 next;
108 }
109 } else {
110 $fetch->{$pathname} = $refname;
111 }
112 }
113}
114
115sub parse_revision_argument {
116 my ($base, $head) = @_;
117 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
118 return ($base, $head);
119 }
120 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
121 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
122 return ($head, $head) if ($::_revision eq 'HEAD');
123 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
124 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
125 die "revision argument: $::_revision not understood by git-svn\n";
126}
127
128sub fetch_all {
129 my ($repo_id, $remotes) = @_;
130 if (ref $repo_id) {
131 my $gs = $repo_id;
132 $repo_id = undef;
133 $repo_id = $gs->{repo_id};
134 }
135 $remotes ||= read_all_remotes();
136 my $remote = $remotes->{$repo_id} or
137 die "[svn-remote \"$repo_id\"] unknown\n";
138 my $fetch = $remote->{fetch};
139 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
140 my (@gs, @globs);
141 my $ra = Git::SVN::Ra->new($url);
142 my $uuid = $ra->get_uuid;
143 my $head = $ra->get_latest_revnum;
144
145 # ignore errors, $head revision may not even exist anymore
146 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
147 warn "W: $@\n" if $@;
148
149 my $base = defined $fetch ? $head : 0;
150
151 # read the max revs for wildcard expansion (branches/*, tags/*)
152 foreach my $t (qw/branches tags/) {
153 defined $remote->{$t} or next;
154 push @globs, @{$remote->{$t}};
155
156 my $max_rev = eval { tmp_config(qw/--int --get/,
157 "svn-remote.$repo_id.${t}-maxRev") };
158 if (defined $max_rev && ($max_rev < $base)) {
159 $base = $max_rev;
160 } elsif (!defined $max_rev) {
161 $base = 0;
162 }
163 }
164
165 if ($fetch) {
166 foreach my $p (sort keys %$fetch) {
167 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
168 my $lr = $gs->rev_map_max;
169 if (defined $lr) {
170 $base = $lr if ($lr < $base);
171 }
172 push @gs, $gs;
173 }
174 }
175
176 ($base, $head) = parse_revision_argument($base, $head);
177 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
178}
179
180sub read_all_remotes {
181 my $r = {};
182 my $use_svm_props = eval { command_oneline(qw/config --bool
183 svn.useSvmProps/) };
184 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
185 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
186 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
187 if (m!^(.+)\.fetch=$svn_refspec$!) {
188 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
189 die("svn-remote.$remote: remote ref '$remote_ref' "
190 . "must start with 'refs/'\n")
191 unless $remote_ref =~ m{^refs/};
192 $local_ref = uri_decode($local_ref);
193 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
194 $r->{$remote}->{svm} = {} if $use_svm_props;
195 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
196 $r->{$1}->{svm} = {};
197 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
198 $r->{$1}->{url} = $2;
199 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
200 $r->{$1}->{pushurl} = $2;
201 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
202 $r->{$1}->{ignore_refs_regex} = $2;
203 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
204 my ($remote, $t, $local_ref, $remote_ref) =
205 ($1, $2, $3, $4);
206 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
207 . "must start with 'refs/'\n")
208 unless $remote_ref =~ m{^refs/};
209 $local_ref = uri_decode($local_ref);
210 my $rs = {
211 t => $t,
212 remote => $remote,
213 path => Git::SVN::GlobSpec->new($local_ref, 1),
214 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
215 if (length($rs->{ref}->{right}) != 0) {
216 die "The '*' glob character must be the last ",
217 "character of '$remote_ref'\n";
218 }
219 push @{ $r->{$remote}->{$t} }, $rs;
220 }
221 }
222
223 map {
224 if (defined $r->{$_}->{svm}) {
225 my $svm;
226 eval {
227 my $section = "svn-remote.$_";
228 $svm = {
229 source => tmp_config('--get',
230 "$section.svm-source"),
231 replace => tmp_config('--get',
232 "$section.svm-replace"),
233 }
234 };
235 $r->{$_}->{svm} = $svm;
236 }
237 } keys %$r;
238
239 foreach my $remote (keys %$r) {
240 foreach ( grep { defined $_ }
241 map { $r->{$remote}->{$_} } qw(branches tags) ) {
242 foreach my $rs ( @$_ ) {
243 $rs->{ignore_refs_regex} =
244 $r->{$remote}->{ignore_refs_regex};
245 }
246 }
247 }
248
249 $r;
250}
251
252sub init_vars {
253 $_gc_nr = $_gc_period = 1000;
254 if (defined $_repack || defined $_repack_flags) {
255 warn "Repack options are obsolete; they have no effect.\n";
256 }
257}
258
259sub verify_remotes_sanity {
260 return unless -d $ENV{GIT_DIR};
261 my %seen;
262 foreach (command(qw/config -l/)) {
263 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
264 if ($seen{$1}) {
265 die "Remote ref refs/remote/$1 is tracked by",
266 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
267 "Please resolve this ambiguity in ",
268 "your git configuration file before ",
269 "continuing\n";
270 }
271 $seen{$1} = $_;
272 }
273 }
274}
275
276sub find_existing_remote {
277 my ($url, $remotes) = @_;
278 return undef if $no_reuse_existing;
279 my $existing;
280 foreach my $repo_id (keys %$remotes) {
281 my $u = $remotes->{$repo_id}->{url} or next;
282 next if $u ne $url;
283 $existing = $repo_id;
284 last;
285 }
286 $existing;
287}
288
289sub init_remote_config {
290 my ($self, $url, $no_write) = @_;
291 $url =~ s!/+$!!; # strip trailing slash
292 my $r = read_all_remotes();
293 my $existing = find_existing_remote($url, $r);
294 if ($existing) {
295 unless ($no_write) {
296 print STDERR "Using existing ",
297 "[svn-remote \"$existing\"]\n";
298 }
299 $self->{repo_id} = $existing;
300 } elsif ($_minimize_url) {
301 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
302 $existing = find_existing_remote($min_url, $r);
303 if ($existing) {
304 unless ($no_write) {
305 print STDERR "Using existing ",
306 "[svn-remote \"$existing\"]\n";
307 }
308 $self->{repo_id} = $existing;
309 }
310 if ($min_url ne $url) {
311 unless ($no_write) {
312 print STDERR "Using higher level of URL: ",
313 "$url => $min_url\n";
314 }
315 my $old_path = $self->{path};
316 $self->{path} = $url;
317 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
318 if (length $old_path) {
319 $self->{path} .= "/$old_path";
320 }
321 $url = $min_url;
322 }
323 }
324 my $orig_url;
325 if (!$existing) {
326 # verify that we aren't overwriting anything:
327 $orig_url = eval {
328 command_oneline('config', '--get',
329 "svn-remote.$self->{repo_id}.url")
330 };
331 if ($orig_url && ($orig_url ne $url)) {
332 die "svn-remote.$self->{repo_id}.url already set: ",
333 "$orig_url\nwanted to set to: $url\n";
334 }
335 }
336 my ($xrepo_id, $xpath) = find_ref($self->refname);
337 if (!$no_write && defined $xpath) {
338 die "svn-remote.$xrepo_id.fetch already set to track ",
339 "$xpath:", $self->refname, "\n";
340 }
341 unless ($no_write) {
342 command_noisy('config',
343 "svn-remote.$self->{repo_id}.url", $url);
344 $self->{path} =~ s{^/}{};
345 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
346 command_noisy('config', '--add',
347 "svn-remote.$self->{repo_id}.fetch",
348 "$self->{path}:".$self->refname);
349 }
350 $self->{url} = $url;
351}
352
353sub find_by_url { # repos_root and, path are optional
354 my ($class, $full_url, $repos_root, $path) = @_;
355
356 return undef unless defined $full_url;
357 remove_username($full_url);
358 remove_username($repos_root) if defined $repos_root;
359 my $remotes = read_all_remotes();
360 if (defined $full_url && defined $repos_root && !defined $path) {
361 $path = $full_url;
362 $path =~ s#^\Q$repos_root\E(?:/|$)##;
363 }
364 foreach my $repo_id (keys %$remotes) {
365 my $u = $remotes->{$repo_id}->{url} or next;
366 remove_username($u);
367 next if defined $repos_root && $repos_root ne $u;
368
369 my $fetch = $remotes->{$repo_id}->{fetch} || {};
370 foreach my $t (qw/branches tags/) {
371 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
372 resolve_local_globs($u, $fetch, $globspec);
373 }
374 }
375 my $p = $path;
376 my $rwr = rewrite_root({repo_id => $repo_id});
377 my $svm = $remotes->{$repo_id}->{svm}
378 if defined $remotes->{$repo_id}->{svm};
379 unless (defined $p) {
380 $p = $full_url;
381 my $z = $u;
382 my $prefix = '';
383 if ($rwr) {
384 $z = $rwr;
385 remove_username($z);
386 } elsif (defined $svm) {
387 $z = $svm->{source};
388 $prefix = $svm->{replace};
389 $prefix =~ s#^\Q$u\E(?:/|$)##;
390 $prefix =~ s#/$##;
391 }
392 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
393 }
394 foreach my $f (keys %$fetch) {
395 next if $f ne $p;
396 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
397 }
398 }
399 undef;
400}
401
402sub init {
403 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
404 my $self = _new($class, $repo_id, $ref_id, $path);
405 if (defined $url) {
406 $self->init_remote_config($url, $no_write);
407 }
408 $self;
409}
410
411sub find_ref {
412 my ($ref_id) = @_;
413 foreach (command(qw/config -l/)) {
414 next unless m!^svn-remote\.(.+)\.fetch=
415 \s*(.*?)\s*:\s*(.+?)\s*$!x;
416 my ($repo_id, $path, $ref) = ($1, $2, $3);
417 if ($ref eq $ref_id) {
418 $path = '' if ($path =~ m#^\./?#);
419 return ($repo_id, $path);
420 }
421 }
422 (undef, undef, undef);
423}
424
425sub new {
426 my ($class, $ref_id, $repo_id, $path) = @_;
427 if (defined $ref_id && !defined $repo_id && !defined $path) {
428 ($repo_id, $path) = find_ref($ref_id);
429 if (!defined $repo_id) {
430 die "Could not find a \"svn-remote.*.fetch\" key ",
431 "in the repository configuration matching: ",
432 "$ref_id\n";
433 }
434 }
435 my $self = _new($class, $repo_id, $ref_id, $path);
436 if (!defined $self->{path} || !length $self->{path}) {
437 my $fetch = command_oneline('config', '--get',
438 "svn-remote.$repo_id.fetch",
439 ":$ref_id\$") or
440 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
441 "\":$ref_id\$\" in config\n";
442 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
443 }
444 $self->{path} =~ s{/+}{/}g;
445 $self->{path} =~ s{\A/}{};
446 $self->{path} =~ s{/\z}{};
447 $self->{url} = command_oneline('config', '--get',
448 "svn-remote.$repo_id.url") or
449 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
450 $self->{pushurl} = eval { command_oneline('config', '--get',
451 "svn-remote.$repo_id.pushurl") };
452 $self->rebuild;
453 $self;
454}
455
456sub refname {
457 my ($refname) = $_[0]->{ref_id} ;
458
459 # It cannot end with a slash /, we'll throw up on this because
460 # SVN can't have directories with a slash in their name, either:
461 if ($refname =~ m{/$}) {
462 die "ref: '$refname' ends with a trailing slash, this is ",
463 "not permitted by git nor Subversion\n";
464 }
465
466 # It cannot have ASCII control character space, tilde ~, caret ^,
467 # colon :, question-mark ?, asterisk *, space, or open bracket [
468 # anywhere.
469 #
470 # Additionally, % must be escaped because it is used for escaping
471 # and we want our escaped refname to be reversible
472 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
473
474 # no slash-separated component can begin with a dot .
475 # /.* becomes /%2E*
476 $refname =~ s{/\.}{/%2E}g;
477
478 # It cannot have two consecutive dots .. anywhere
479 # .. becomes %2E%2E
480 $refname =~ s{\.\.}{%2E%2E}g;
481
482 # trailing dots and .lock are not allowed
483 # .$ becomes %2E and .lock becomes %2Elock
484 $refname =~ s{\.(?=$|lock$)}{%2E};
485
486 # the sequence @{ is used to access the reflog
487 # @{ becomes %40{
488 $refname =~ s{\@\{}{%40\{}g;
489
490 return $refname;
491}
492
493sub desanitize_refname {
494 my ($refname) = @_;
495 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
496 return $refname;
497}
498
499sub svm_uuid {
500 my ($self) = @_;
501 return $self->{svm}->{uuid} if $self->svm;
502 $self->ra;
503 unless ($self->{svm}) {
504 die "SVM UUID not cached, and reading remotely failed\n";
505 }
506 $self->{svm}->{uuid};
507}
508
509sub svm {
510 my ($self) = @_;
511 return $self->{svm} if $self->{svm};
512 my $svm;
513 # see if we have it in our config, first:
514 eval {
515 my $section = "svn-remote.$self->{repo_id}";
516 $svm = {
517 source => tmp_config('--get', "$section.svm-source"),
518 uuid => tmp_config('--get', "$section.svm-uuid"),
519 replace => tmp_config('--get', "$section.svm-replace"),
520 }
521 };
522 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
523 $self->{svm} = $svm;
524 }
525 $self->{svm};
526}
527
528sub _set_svm_vars {
529 my ($self, $ra) = @_;
530 return $ra if $self->svm;
531
532 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
533 "(svm:source, svm:uuid) ",
534 "from the following URLs:\n" );
535 sub read_svm_props {
536 my ($self, $ra, $path, $r) = @_;
537 my $props = ($ra->get_dir($path, $r))[2];
538 my $src = $props->{'svm:source'};
539 my $uuid = $props->{'svm:uuid'};
540 return undef if (!$src || !$uuid);
541
542 chomp($src, $uuid);
543
544 $uuid =~ m{^[0-9a-f\-]{30,}$}i
545 or die "doesn't look right - svm:uuid is '$uuid'\n";
546
547 # the '!' is used to mark the repos_root!/relative/path
548 $src =~ s{/?!/?}{/};
549 $src =~ s{/+$}{}; # no trailing slashes please
550 # username is of no interest
551 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
552
553 my $replace = $ra->{url};
554 $replace .= "/$path" if length $path;
555
556 my $section = "svn-remote.$self->{repo_id}";
557 tmp_config("$section.svm-source", $src);
558 tmp_config("$section.svm-replace", $replace);
559 tmp_config("$section.svm-uuid", $uuid);
560 $self->{svm} = {
561 source => $src,
562 uuid => $uuid,
563 replace => $replace
564 };
565 }
566
567 my $r = $ra->get_latest_revnum;
568 my $path = $self->{path};
569 my %tried;
570 while (length $path) {
571 unless ($tried{"$self->{url}/$path"}) {
572 return $ra if $self->read_svm_props($ra, $path, $r);
573 $tried{"$self->{url}/$path"} = 1;
574 }
575 $path =~ s#/?[^/]+$##;
576 }
577 die "Path: '$path' should be ''\n" if $path ne '';
578 return $ra if $self->read_svm_props($ra, $path, $r);
579 $tried{"$self->{url}/$path"} = 1;
580
581 if ($ra->{repos_root} eq $self->{url}) {
582 die @err, (map { " $_\n" } keys %tried), "\n";
583 }
584
585 # nope, make sure we're connected to the repository root:
586 my $ok;
587 my @tried_b;
588 $path = $ra->{svn_path};
589 $ra = Git::SVN::Ra->new($ra->{repos_root});
590 while (length $path) {
591 unless ($tried{"$ra->{url}/$path"}) {
592 $ok = $self->read_svm_props($ra, $path, $r);
593 last if $ok;
594 $tried{"$ra->{url}/$path"} = 1;
595 }
596 $path =~ s#/?[^/]+$##;
597 }
598 die "Path: '$path' should be ''\n" if $path ne '';
599 $ok ||= $self->read_svm_props($ra, $path, $r);
600 $tried{"$ra->{url}/$path"} = 1;
601 if (!$ok) {
602 die @err, (map { " $_\n" } keys %tried), "\n";
603 }
604 Git::SVN::Ra->new($self->{url});
605}
606
607sub svnsync {
608 my ($self) = @_;
609 return $self->{svnsync} if $self->{svnsync};
610
611 if ($self->no_metadata) {
612 die "Can't have both 'noMetadata' and ",
613 "'useSvnsyncProps' options set!\n";
614 }
615 if ($self->rewrite_root) {
616 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
617 "options set!\n";
618 }
619 if ($self->rewrite_uuid) {
620 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
621 "options set!\n";
622 }
623
624 my $svnsync;
625 # see if we have it in our config, first:
626 eval {
627 my $section = "svn-remote.$self->{repo_id}";
628
629 my $url = tmp_config('--get', "$section.svnsync-url");
630 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
631 die "doesn't look right - svn:sync-from-url is '$url'\n";
632
633 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
634 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
635 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
636
637 $svnsync = { url => $url, uuid => $uuid }
638 };
639 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
640 return $self->{svnsync} = $svnsync;
641 }
642
643 my $err = "useSvnsyncProps set, but failed to read " .
644 "svnsync property: svn:sync-from-";
645 my $rp = $self->ra->rev_proplist(0);
646
647 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
648 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
649 die "doesn't look right - svn:sync-from-url is '$url'\n";
650
651 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
652 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
653 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
654
655 my $section = "svn-remote.$self->{repo_id}";
656 tmp_config('--add', "$section.svnsync-uuid", $uuid);
657 tmp_config('--add', "$section.svnsync-url", $url);
658 return $self->{svnsync} = { url => $url, uuid => $uuid };
659}
660
661# this allows us to memoize our SVN::Ra UUID locally and avoid a
662# remote lookup (useful for 'git svn log').
663sub ra_uuid {
664 my ($self) = @_;
665 unless ($self->{ra_uuid}) {
666 my $key = "svn-remote.$self->{repo_id}.uuid";
667 my $uuid = eval { tmp_config('--get', $key) };
668 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
669 $self->{ra_uuid} = $uuid;
670 } else {
671 die "ra_uuid called without URL\n" unless $self->{url};
672 $self->{ra_uuid} = $self->ra->get_uuid;
673 tmp_config('--add', $key, $self->{ra_uuid});
674 }
675 }
676 $self->{ra_uuid};
677}
678
679sub _set_repos_root {
680 my ($self, $repos_root) = @_;
681 my $k = "svn-remote.$self->{repo_id}.reposRoot";
682 $repos_root ||= $self->ra->{repos_root};
683 tmp_config($k, $repos_root);
684 $repos_root;
685}
686
687sub repos_root {
688 my ($self) = @_;
689 my $k = "svn-remote.$self->{repo_id}.reposRoot";
690 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
691}
692
693sub ra {
694 my ($self) = shift;
695 my $ra = Git::SVN::Ra->new($self->{url});
696 $self->_set_repos_root($ra->{repos_root});
697 if ($self->use_svm_props && !$self->{svm}) {
698 if ($self->no_metadata) {
699 die "Can't have both 'noMetadata' and ",
700 "'useSvmProps' options set!\n";
701 } elsif ($self->use_svnsync_props) {
702 die "Can't have both 'useSvnsyncProps' and ",
703 "'useSvmProps' options set!\n";
704 }
705 $ra = $self->_set_svm_vars($ra);
706 $self->{-want_revprops} = 1;
707 }
708 $ra;
709}
710
711# prop_walk(PATH, REV, SUB)
712# -------------------------
713# Recursively traverse PATH at revision REV and invoke SUB for each
714# directory that contains a SVN property. SUB will be invoked as
715# follows: &SUB(gs, path, props); where `gs' is this instance of
716# Git::SVN, `path' the path to the directory where the properties
717# `props' were found. The `path' will be relative to point of checkout,
718# that is, if url://repo/trunk is the current Git branch, and that
719# directory contains a sub-directory `d', SUB will be invoked with `/d/'
720# as `path' (note the trailing `/').
721sub prop_walk {
722 my ($self, $path, $rev, $sub) = @_;
723
724 $path =~ s#^/##;
725 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
726 $path =~ s#^/*#/#g;
727 my $p = $path;
728 # Strip the irrelevant part of the path.
729 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
730 # Ensure the path is terminated by a `/'.
731 $p =~ s#/*$#/#;
732
733 # The properties contain all the internal SVN stuff nobody
734 # (usually) cares about.
735 my $interesting_props = 0;
736 foreach (keys %{$props}) {
737 # If it doesn't start with `svn:', it must be a
738 # user-defined property.
739 ++$interesting_props and next if $_ !~ /^svn:/;
740 # FIXME: Fragile, if SVN adds new public properties,
741 # this needs to be updated.
742 ++$interesting_props if /^svn:(?:ignore|keywords|executable
743 |eol-style|mime-type
744 |externals|needs-lock)$/x;
745 }
746 &$sub($self, $p, $props) if $interesting_props;
747
748 foreach (sort keys %$dirent) {
749 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
750 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
751 }
752}
753
754sub last_rev { ($_[0]->last_rev_commit)[0] }
755sub last_commit { ($_[0]->last_rev_commit)[1] }
756
757# returns the newest SVN revision number and newest commit SHA1
758sub last_rev_commit {
759 my ($self) = @_;
760 if (defined $self->{last_rev} && defined $self->{last_commit}) {
761 return ($self->{last_rev}, $self->{last_commit});
762 }
763 my $c = ::verify_ref($self->refname.'^0');
764 if ($c && !$self->use_svm_props && !$self->no_metadata) {
765 my $rev = (::cmt_metadata($c))[1];
766 if (defined $rev) {
767 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
768 return ($rev, $c);
769 }
770 }
771 my $map_path = $self->map_path;
772 unless (-e $map_path) {
773 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
774 return (undef, undef);
775 }
776 my ($rev, $commit) = $self->rev_map_max(1);
777 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
778 return ($rev, $commit);
779}
780
781sub get_fetch_range {
782 my ($self, $min, $max) = @_;
783 $max ||= $self->ra->get_latest_revnum;
784 $min ||= $self->rev_map_max;
785 (++$min, $max);
786}
787
788sub tmp_config {
789 my (@args) = @_;
790 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
791 my $config = "$ENV{GIT_DIR}/svn/.metadata";
792 if (! -f $config && -f $old_def_config) {
793 rename $old_def_config, $config or
794 die "Failed rename $old_def_config => $config: $!\n";
795 }
796 my $old_config = $ENV{GIT_CONFIG};
797 $ENV{GIT_CONFIG} = $config;
798 $@ = undef;
799 my @ret = eval {
800 unless (-f $config) {
801 mkfile($config);
802 open my $fh, '>', $config or
803 die "Can't open $config: $!\n";
804 print $fh "; This file is used internally by ",
805 "git-svn\n" or die
806 "Couldn't write to $config: $!\n";
807 print $fh "; You should not have to edit it\n" or
808 die "Couldn't write to $config: $!\n";
809 close $fh or die "Couldn't close $config: $!\n";
810 }
811 command('config', @args);
812 };
813 my $err = $@;
814 if (defined $old_config) {
815 $ENV{GIT_CONFIG} = $old_config;
816 } else {
817 delete $ENV{GIT_CONFIG};
818 }
819 die $err if $err;
820 wantarray ? @ret : $ret[0];
821}
822
823sub tmp_index_do {
824 my ($self, $sub) = @_;
825 my $old_index = $ENV{GIT_INDEX_FILE};
826 $ENV{GIT_INDEX_FILE} = $self->{index};
827 $@ = undef;
828 my @ret = eval {
829 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
830 mkpath([$dir]) unless -d $dir;
831 &$sub;
832 };
833 my $err = $@;
834 if (defined $old_index) {
835 $ENV{GIT_INDEX_FILE} = $old_index;
836 } else {
837 delete $ENV{GIT_INDEX_FILE};
838 }
839 die $err if $err;
840 wantarray ? @ret : $ret[0];
841}
842
843sub assert_index_clean {
844 my ($self, $treeish) = @_;
845
846 $self->tmp_index_do(sub {
847 command_noisy('read-tree', $treeish) unless -e $self->{index};
848 my $x = command_oneline('write-tree');
849 my ($y) = (command(qw/cat-file commit/, $treeish) =~
850 /^tree ($::sha1)/mo);
851 return if $y eq $x;
852
853 warn "Index mismatch: $y != $x\nrereading $treeish\n";
854 unlink $self->{index} or die "unlink $self->{index}: $!\n";
855 command_noisy('read-tree', $treeish);
856 $x = command_oneline('write-tree');
857 if ($y ne $x) {
858 fatal "trees ($treeish) $y != $x\n",
859 "Something is seriously wrong...";
860 }
861 });
862}
863
864sub get_commit_parents {
865 my ($self, $log_entry) = @_;
866 my (%seen, @ret, @tmp);
867 # legacy support for 'set-tree'; this is only used by set_tree_cb:
868 if (my $ip = $self->{inject_parents}) {
869 if (my $commit = delete $ip->{$log_entry->{revision}}) {
870 push @tmp, $commit;
871 }
872 }
873 if (my $cur = ::verify_ref($self->refname.'^0')) {
874 push @tmp, $cur;
875 }
876 if (my $ipd = $self->{inject_parents_dcommit}) {
877 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
878 push @tmp, @$commit;
879 }
880 }
881 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
882 while (my $p = shift @tmp) {
883 next if $seen{$p};
884 $seen{$p} = 1;
885 push @ret, $p;
886 }
887 @ret;
888}
889
890sub rewrite_root {
891 my ($self) = @_;
892 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
893 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
894 my $rwr = eval { command_oneline(qw/config --get/, $k) };
895 if ($rwr) {
896 $rwr =~ s#/+$##;
897 if ($rwr !~ m#^[a-z\+]+://#) {
898 die "$rwr is not a valid URL (key: $k)\n";
899 }
900 }
901 $self->{-rewrite_root} = $rwr;
902}
903
904sub rewrite_uuid {
905 my ($self) = @_;
906 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
907 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
908 my $rwid = eval { command_oneline(qw/config --get/, $k) };
909 if ($rwid) {
910 $rwid =~ s#/+$##;
911 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
912 die "$rwid is not a valid UUID (key: $k)\n";
913 }
914 }
915 $self->{-rewrite_uuid} = $rwid;
916}
917
918sub metadata_url {
919 my ($self) = @_;
920 ($self->rewrite_root || $self->{url}) .
921 (length $self->{path} ? '/' . $self->{path} : '');
922}
923
924sub full_url {
925 my ($self) = @_;
926 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
927}
928
929sub full_pushurl {
930 my ($self) = @_;
931 if ($self->{pushurl}) {
932 return $self->{pushurl} . (length $self->{path} ? '/' .
933 $self->{path} : '');
934 } else {
935 return $self->full_url;
936 }
937}
938
939sub set_commit_header_env {
940 my ($log_entry) = @_;
941 my %env;
942 foreach my $ned (qw/NAME EMAIL DATE/) {
943 foreach my $ac (qw/AUTHOR COMMITTER/) {
944 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
945 }
946 }
947
948 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
949 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
950 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
951
952 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
953 ? $log_entry->{commit_name}
954 : $log_entry->{name};
955 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
956 ? $log_entry->{commit_email}
957 : $log_entry->{email};
958 \%env;
959}
960
961sub restore_commit_header_env {
962 my ($env) = @_;
963 foreach my $ned (qw/NAME EMAIL DATE/) {
964 foreach my $ac (qw/AUTHOR COMMITTER/) {
965 my $k = "GIT_${ac}_${ned}";
966 if (defined $env->{$k}) {
967 $ENV{$k} = $env->{$k};
968 } else {
969 delete $ENV{$k};
970 }
971 }
972 }
973}
974
975sub gc {
976 command_noisy('gc', '--auto');
977};
978
979sub do_git_commit {
980 my ($self, $log_entry) = @_;
981 my $lr = $self->last_rev;
982 if (defined $lr && $lr >= $log_entry->{revision}) {
983 die "Last fetched revision of ", $self->refname,
984 " was r$lr, but we are about to fetch: ",
985 "r$log_entry->{revision}!\n";
986 }
987 if (my $c = $self->rev_map_get($log_entry->{revision})) {
988 croak "$log_entry->{revision} = $c already exists! ",
989 "Why are we refetching it?\n";
990 }
991 my $old_env = set_commit_header_env($log_entry);
992 my $tree = $log_entry->{tree};
993 if (!defined $tree) {
994 $tree = $self->tmp_index_do(sub {
995 command_oneline('write-tree') });
996 }
997 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
998
999 my @exec = ('git', 'commit-tree', $tree);
1000 foreach ($self->get_commit_parents($log_entry)) {
1001 push @exec, '-p', $_;
1002 }
1003 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1004 or croak $!;
1005 binmode $msg_fh;
1006
1007 # we always get UTF-8 from SVN, but we may want our commits in
1008 # a different encoding.
1009 if (my $enc = Git::config('i18n.commitencoding')) {
1010 require Encode;
1011 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
1012 }
1013 print $msg_fh $log_entry->{log} or croak $!;
1014 restore_commit_header_env($old_env);
1015 unless ($self->no_metadata) {
1016 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1017 or croak $!;
1018 }
1019 $msg_fh->flush == 0 or croak $!;
1020 close $msg_fh or croak $!;
1021 chomp(my $commit = do { local $/; <$out_fh> });
1022 close $out_fh or croak $!;
1023 waitpid $pid, 0;
1024 croak $? if $?;
1025 if ($commit !~ /^$::sha1$/o) {
1026 die "Failed to commit, invalid sha1: $commit\n";
1027 }
1028
1029 $self->rev_map_set($log_entry->{revision}, $commit, 1);
1030
1031 $self->{last_rev} = $log_entry->{revision};
1032 $self->{last_commit} = $commit;
1033 print "r$log_entry->{revision}" unless $::_q > 1;
1034 if (defined $log_entry->{svm_revision}) {
1035 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
1036 $self->rev_map_set($log_entry->{svm_revision}, $commit,
1037 0, $self->svm_uuid);
1038 }
1039 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
1040 if (--$_gc_nr == 0) {
1041 $_gc_nr = $_gc_period;
1042 gc();
1043 }
1044 return $commit;
1045}
1046
1047sub match_paths {
1048 my ($self, $paths, $r) = @_;
1049 return 1 if $self->{path} eq '';
1050 if (my $path = $paths->{"/$self->{path}"}) {
1051 return ($path->{action} eq 'D') ? 0 : 1;
1052 }
1053 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1054 if (grep /$self->{path_regex}/, keys %$paths) {
1055 return 1;
1056 }
1057 my $c = '';
1058 foreach (split m#/#, $self->{path}) {
1059 $c .= "/$_";
1060 next unless ($paths->{$c} &&
1061 ($paths->{$c}->{action} =~ /^[AR]$/));
1062 if ($self->ra->check_path($self->{path}, $r) ==
1063 $SVN::Node::dir) {
1064 return 1;
1065 }
1066 }
1067 return 0;
1068}
1069
1070sub find_parent_branch {
1071 my ($self, $paths, $rev) = @_;
1072 return undef unless $self->follow_parent;
1073 unless (defined $paths) {
1074 my $err_handler = $SVN::Error::handler;
1075 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1076 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
1077 sub { $paths = $_[0] });
1078 $SVN::Error::handler = $err_handler;
1079 }
1080 return undef unless defined $paths;
1081
1082 # look for a parent from another branch:
1083 my @b_path_components = split m#/#, $self->{path};
1084 my @a_path_components;
1085 my $i;
1086 while (@b_path_components) {
1087 $i = $paths->{'/'.join('/', @b_path_components)};
1088 last if $i && defined $i->{copyfrom_path};
1089 unshift(@a_path_components, pop(@b_path_components));
1090 }
1091 return undef unless defined $i && defined $i->{copyfrom_path};
1092 my $branch_from = $i->{copyfrom_path};
1093 if (@a_path_components) {
1094 print STDERR "branch_from: $branch_from => ";
1095 $branch_from .= '/'.join('/', @a_path_components);
1096 print STDERR $branch_from, "\n";
1097 }
1098 my $r = $i->{copyfrom_rev};
1099 my $repos_root = $self->ra->{repos_root};
1100 my $url = $self->ra->{url};
1101 my $new_url = $url . $branch_from;
1102 print STDERR "Found possible branch point: ",
1103 "$new_url => ", $self->full_url, ", $r\n"
1104 unless $::_q > 1;
1105 $branch_from =~ s#^/##;
1106 my $gs = $self->other_gs($new_url, $url,
1107 $branch_from, $r, $self->{ref_id});
1108 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1109 {
1110 my ($base, $head);
1111 if (!defined $r0 || !defined $parent) {
1112 ($base, $head) = parse_revision_argument(0, $r);
1113 } else {
1114 if ($r0 < $r) {
1115 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
1116 0, 1, sub { $base = $_[1] - 1 });
1117 }
1118 }
1119 if (defined $base && $base <= $r) {
1120 $gs->fetch($base, $r);
1121 }
1122 ($r0, $parent) = $gs->find_rev_before($r, 1);
1123 }
1124 if (defined $r0 && defined $parent) {
1125 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
1126 unless $::_q > 1;
1127 my $ed;
1128 if ($self->ra->can_do_switch) {
1129 $self->assert_index_clean($parent);
1130 print STDERR "Following parent with do_switch\n"
1131 unless $::_q > 1;
1132 # do_switch works with svn/trunk >= r22312, but that
1133 # is not included with SVN 1.4.3 (the latest version
1134 # at the moment), so we can't rely on it
1135 $self->{last_rev} = $r0;
1136 $self->{last_commit} = $parent;
1137 $ed = Git::SVN::Fetcher->new($self, $gs->{path});
1138 $gs->ra->gs_do_switch($r0, $rev, $gs,
1139 $self->full_url, $ed)
1140 or die "SVN connection failed somewhere...\n";
1141 } elsif ($self->ra->trees_match($new_url, $r0,
1142 $self->full_url, $rev)) {
1143 print STDERR "Trees match:\n",
1144 " $new_url\@$r0\n",
1145 " ${\$self->full_url}\@$rev\n",
1146 "Following parent with no changes\n"
1147 unless $::_q > 1;
1148 $self->tmp_index_do(sub {
1149 command_noisy('read-tree', $parent);
1150 });
1151 $self->{last_commit} = $parent;
1152 } else {
1153 print STDERR "Following parent with do_update\n"
1154 unless $::_q > 1;
1155 $ed = Git::SVN::Fetcher->new($self);
1156 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1157 or die "SVN connection failed somewhere...\n";
1158 }
1159 print STDERR "Successfully followed parent\n" unless $::_q > 1;
1160 return $self->make_log_entry($rev, [$parent], $ed);
1161 }
1162 return undef;
1163}
1164
1165sub do_fetch {
1166 my ($self, $paths, $rev) = @_;
1167 my $ed;
1168 my ($last_rev, @parents);
1169 if (my $lc = $self->last_commit) {
1170 # we can have a branch that was deleted, then re-added
1171 # under the same name but copied from another path, in
1172 # which case we'll have multiple parents (we don't
1173 # want to break the original ref, nor lose copypath info):
1174 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1175 push @{$log_entry->{parents}}, $lc;
1176 return $log_entry;
1177 }
1178 $ed = Git::SVN::Fetcher->new($self);
1179 $last_rev = $self->{last_rev};
1180 $ed->{c} = $lc;
1181 @parents = ($lc);
1182 } else {
1183 $last_rev = $rev;
1184 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1185 return $log_entry;
1186 }
1187 $ed = Git::SVN::Fetcher->new($self);
1188 }
1189 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1190 die "SVN connection failed somewhere...\n";
1191 }
1192 $self->make_log_entry($rev, \@parents, $ed);
1193}
1194
1195sub mkemptydirs {
1196 my ($self, $r) = @_;
1197
1198 sub scan {
1199 my ($r, $empty_dirs, $line) = @_;
1200 if (defined $r && $line =~ /^r(\d+)$/) {
1201 return 0 if $1 > $r;
1202 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
1203 $empty_dirs->{$1} = 1;
1204 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
1205 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
1206 delete @$empty_dirs{@d};
1207 }
1208 1; # continue
1209 };
1210
1211 my %empty_dirs = ();
1212 my $gz_file = "$self->{dir}/unhandled.log.gz";
1213 if (-f $gz_file) {
1214 if (!can_compress()) {
1215 warn "Compress::Zlib could not be found; ",
1216 "empty directories in $gz_file will not be read\n";
1217 } else {
1218 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
1219 die "Unable to open $gz_file: $!\n";
1220 my $line;
1221 while ($gz->gzreadline($line) > 0) {
1222 scan($r, \%empty_dirs, $line) or last;
1223 }
1224 $gz->gzclose;
1225 }
1226 }
1227
1228 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
1229 binmode $fh or croak "binmode: $!";
1230 while (<$fh>) {
1231 scan($r, \%empty_dirs, $_) or last;
1232 }
1233 close $fh;
1234 }
1235
1236 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
1237 foreach my $d (sort keys %empty_dirs) {
1238 $d = uri_decode($d);
1239 $d =~ s/$strip//;
1240 next unless length($d);
1241 next if -d $d;
1242 if (-e $d) {
1243 warn "$d exists but is not a directory\n";
1244 } else {
1245 print "creating empty directory: $d\n";
1246 mkpath([$d]);
1247 }
1248 }
1249}
1250
1251sub get_untracked {
1252 my ($self, $ed) = @_;
1253 my @out;
1254 my $h = $ed->{empty};
1255 foreach (sort keys %$h) {
1256 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1257 push @out, " $act: " . uri_encode($_);
1258 warn "W: $act: $_\n";
1259 }
1260 foreach my $t (qw/dir_prop file_prop/) {
1261 $h = $ed->{$t} or next;
1262 foreach my $path (sort keys %$h) {
1263 my $ppath = $path eq '' ? '.' : $path;
1264 foreach my $prop (sort keys %{$h->{$path}}) {
1265 next if $SKIP_PROP{$prop};
1266 my $v = $h->{$path}->{$prop};
1267 my $t_ppath_prop = "$t: " .
1268 uri_encode($ppath) . ' ' .
1269 uri_encode($prop);
1270 if (defined $v) {
1271 push @out, " +$t_ppath_prop " .
1272 uri_encode($v);
1273 } else {
1274 push @out, " -$t_ppath_prop";
1275 }
1276 }
1277 }
1278 }
1279 foreach my $t (qw/absent_file absent_directory/) {
1280 $h = $ed->{$t} or next;
1281 foreach my $parent (sort keys %$h) {
1282 foreach my $path (sort @{$h->{$parent}}) {
1283 push @out, " $t: " .
1284 uri_encode("$parent/$path");
1285 warn "W: $t: $parent/$path ",
1286 "Insufficient permissions?\n";
1287 }
1288 }
1289 }
1290 \@out;
1291}
1292
1293sub get_tz {
1294 # some systmes don't handle or mishandle %z, so be creative.
1295 my $t = shift || time;
1296 my $gm = timelocal(gmtime($t));
1297 my $sign = qw( + + - )[ $t <=> $gm ];
1298 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
1299}
1300
1301# parse_svn_date(DATE)
1302# --------------------
1303# Given a date (in UTC) from Subversion, return a string in the format
1304# "<TZ Offset> <local date/time>" that Git will use.
1305#
1306# By default the parsed date will be in UTC; if $Git::SVN::_localtime
1307# is true we'll convert it to the local timezone instead.
1308sub parse_svn_date {
1309 my $date = shift || return '+0000 1970-01-01 00:00:00';
1310 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1311 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1312 croak "Unable to parse date: $date\n";
1313 my $parsed_date; # Set next.
1314
1315 if ($Git::SVN::_localtime) {
1316 # Translate the Subversion datetime to an epoch time.
1317 # Begin by switching ourselves to $date's timezone, UTC.
1318 my $old_env_TZ = $ENV{TZ};
1319 $ENV{TZ} = 'UTC';
1320
1321 my $epoch_in_UTC =
1322 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
1323
1324 # Determine our local timezone (including DST) at the
1325 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
1326 # value of TZ, if any, at the time we were run.
1327 if (defined $Git::SVN::Log::TZ) {
1328 $ENV{TZ} = $Git::SVN::Log::TZ;
1329 } else {
1330 delete $ENV{TZ};
1331 }
1332
1333 my $our_TZ = get_tz();
1334
1335 # This converts $epoch_in_UTC into our local timezone.
1336 my ($sec, $min, $hour, $mday, $mon, $year,
1337 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
1338
1339 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
1340 $our_TZ, $year + 1900, $mon + 1,
1341 $mday, $hour, $min, $sec);
1342
1343 # Reset us to the timezone in effect when we entered
1344 # this routine.
1345 if (defined $old_env_TZ) {
1346 $ENV{TZ} = $old_env_TZ;
1347 } else {
1348 delete $ENV{TZ};
1349 }
1350 } else {
1351 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
1352 }
1353
1354 return $parsed_date;
1355}
1356
1357sub other_gs {
1358 my ($self, $new_url, $url,
1359 $branch_from, $r, $old_ref_id) = @_;
1360 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
1361 unless ($gs) {
1362 my $ref_id = $old_ref_id;
1363 $ref_id =~ s/\@\d+-*$//;
1364 $ref_id .= "\@$r";
1365 # just grow a tail if we're not unique enough :x
1366 $ref_id .= '-' while find_ref($ref_id);
1367 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
1368 if ($u =~ s#^\Q$url\E(/|$)##) {
1369 $p = $u;
1370 $u = $url;
1371 $repo_id = $self->{repo_id};
1372 }
1373 while (1) {
1374 # It is possible to tag two different subdirectories at
1375 # the same revision. If the url for an existing ref
1376 # does not match, we must either find a ref with a
1377 # matching url or create a new ref by growing a tail.
1378 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
1379 my (undef, $max_commit) = $gs->rev_map_max(1);
1380 last if (!$max_commit);
1381 my ($url) = ::cmt_metadata($max_commit);
1382 last if ($url eq $gs->metadata_url);
1383 $ref_id .= '-';
1384 }
1385 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
1386 }
1387 $gs
1388}
1389
1390sub call_authors_prog {
1391 my ($orig_author) = @_;
1392 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
1393 my $author = `$::_authors_prog $orig_author`;
1394 if ($? != 0) {
1395 die "$::_authors_prog failed with exit code $?\n"
1396 }
1397 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
1398 my ($name, $email) = ($1, $2);
1399 $email = undef if length $2 == 0;
1400 return [$name, $email];
1401 } else {
1402 die "Author: $orig_author: $::_authors_prog returned "
1403 . "invalid author format: $author\n";
1404 }
1405}
1406
1407sub check_author {
1408 my ($author) = @_;
1409 if (!defined $author || length $author == 0) {
1410 $author = '(no author)';
1411 }
1412 if (!defined $::users{$author}) {
1413 if (defined $::_authors_prog) {
1414 $::users{$author} = call_authors_prog($author);
1415 } elsif (defined $::_authors) {
1416 die "Author: $author not defined in $::_authors file\n";
1417 }
1418 }
1419 $author;
1420}
1421
1422sub find_extra_svk_parents {
1423 my ($self, $ed, $tickets, $parents) = @_;
1424 # aha! svk:merge property changed...
1425 my @tickets = split "\n", $tickets;
1426 my @known_parents;
1427 for my $ticket ( @tickets ) {
1428 my ($uuid, $path, $rev) = split /:/, $ticket;
1429 if ( $uuid eq $self->ra_uuid ) {
1430 my $url = $self->{url};
1431 my $repos_root = $url;
1432 my $branch_from = $path;
1433 $branch_from =~ s{^/}{};
1434 my $gs = $self->other_gs($repos_root."/".$branch_from,
1435 $url,
1436 $branch_from,
1437 $rev,
1438 $self->{ref_id});
1439 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
1440 # wahey! we found it, but it might be
1441 # an old one (!)
1442 push @known_parents, [ $rev, $commit ];
1443 }
1444 }
1445 }
1446 # Ordering matters; highest-numbered commit merge tickets
1447 # first, as they may account for later merge ticket additions
1448 # or changes.
1449 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
1450 for my $parent ( @known_parents ) {
1451 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
1452 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
1453 my $new;
1454 while ( <$msg_fh> ) {
1455 $new=1;last;
1456 }
1457 command_close_pipe($msg_fh, $ctx);
1458 if ( $new ) {
1459 print STDERR
1460 "Found merge parent (svk:merge ticket): $parent\n";
1461 push @$parents, $parent;
1462 }
1463 }
1464}
1465
1466sub lookup_svn_merge {
1467 my $uuid = shift;
1468 my $url = shift;
1469 my $merge = shift;
1470
1471 my ($source, $revs) = split ":", $merge;
1472 my $path = $source;
1473 $path =~ s{^/}{};
1474 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
1475 if ( !$gs ) {
1476 warn "Couldn't find revmap for $url$source\n";
1477 return;
1478 }
1479 my @ranges = split ",", $revs;
1480 my ($tip, $tip_commit);
1481 my @merged_commit_ranges;
1482 # find the tip
1483 for my $range ( @ranges ) {
1484 my ($bottom, $top) = split "-", $range;
1485 $top ||= $bottom;
1486 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
1487 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
1488
1489 unless ($top_commit and $bottom_commit) {
1490 warn "W:unknown path/rev in svn:mergeinfo "
1491 ."dirprop: $source:$range\n";
1492 next;
1493 }
1494
1495 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
1496 push @merged_commit_ranges,
1497 "$bottom_commit^..$top_commit";
1498 } else {
1499 push @merged_commit_ranges, "$top_commit";
1500 }
1501
1502 if ( !defined $tip or $top > $tip ) {
1503 $tip = $top;
1504 $tip_commit = $top_commit;
1505 }
1506 }
1507 return ($tip_commit, @merged_commit_ranges);
1508}
1509
1510sub _rev_list {
1511 my ($msg_fh, $ctx) = command_output_pipe(
1512 "rev-list", @_,
1513 );
1514 my @rv;
1515 while ( <$msg_fh> ) {
1516 chomp;
1517 push @rv, $_;
1518 }
1519 command_close_pipe($msg_fh, $ctx);
1520 @rv;
1521}
1522
1523sub check_cherry_pick {
1524 my $base = shift;
1525 my $tip = shift;
1526 my $parents = shift;
1527 my @ranges = @_;
1528 my %commits = map { $_ => 1 }
1529 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
1530 for my $range ( @ranges ) {
1531 delete @commits{_rev_list($range, "--")};
1532 }
1533 for my $commit (keys %commits) {
1534 if (has_no_changes($commit)) {
1535 delete $commits{$commit};
1536 }
1537 }
1538 return (keys %commits);
1539}
1540
1541sub has_no_changes {
1542 my $commit = shift;
1543
1544 my @revs = split / /, command_oneline(
1545 qw(rev-list --parents -1 -m), $commit);
1546
1547 # Commits with no parents, e.g. the start of a partial branch,
1548 # have changes by definition.
1549 return 1 if (@revs < 2);
1550
1551 # Commits with multiple parents, e.g a merge, have no changes
1552 # by definition.
1553 return 0 if (@revs > 2);
1554
1555 return (command_oneline("rev-parse", "$commit^{tree}") eq
1556 command_oneline("rev-parse", "$commit~1^{tree}"));
1557}
1558
1559sub tie_for_persistent_memoization {
1560 my $hash = shift;
1561 my $path = shift;
1562
1563 if ($can_use_yaml) {
1564 tie %$hash => 'Git::SVN::Memoize::YAML', "$path.yaml";
1565 } else {
1566 tie %$hash => 'Memoize::Storable', "$path.db", 'nstore';
1567 }
1568}
1569
1570# The GIT_DIR environment variable is not always set until after the command
1571# line arguments are processed, so we can't memoize in a BEGIN block.
1572{
1573 my $memoized = 0;
1574
1575 sub memoize_svn_mergeinfo_functions {
1576 return if $memoized;
1577 $memoized = 1;
1578
1579 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1580 mkpath([$cache_path]) unless -d $cache_path;
1581
1582 my %lookup_svn_merge_cache;
1583 my %check_cherry_pick_cache;
1584 my %has_no_changes_cache;
1585
1586 tie_for_persistent_memoization(\%lookup_svn_merge_cache,
1587 "$cache_path/lookup_svn_merge");
1588 memoize 'lookup_svn_merge',
1589 SCALAR_CACHE => 'FAULT',
1590 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
1591 ;
1592
1593 tie_for_persistent_memoization(\%check_cherry_pick_cache,
1594 "$cache_path/check_cherry_pick");
1595 memoize 'check_cherry_pick',
1596 SCALAR_CACHE => 'FAULT',
1597 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
1598 ;
1599
1600 tie_for_persistent_memoization(\%has_no_changes_cache,
1601 "$cache_path/has_no_changes");
1602 memoize 'has_no_changes',
1603 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
1604 LIST_CACHE => 'FAULT',
1605 ;
1606 }
1607
1608 sub unmemoize_svn_mergeinfo_functions {
1609 return if not $memoized;
1610 $memoized = 0;
1611
1612 Memoize::unmemoize 'lookup_svn_merge';
1613 Memoize::unmemoize 'check_cherry_pick';
1614 Memoize::unmemoize 'has_no_changes';
1615 }
1616
1617 Memoize::memoize 'Git::SVN::repos_root';
1618}
1619
1620END {
1621 # Force cache writeout explicitly instead of waiting for
1622 # global destruction to avoid segfault in Storable:
1623 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
1624 unmemoize_svn_mergeinfo_functions();
1625}
1626
1627sub parents_exclude {
1628 my $parents = shift;
1629 my @commits = @_;
1630 return unless @commits;
1631
1632 my @excluded;
1633 my $excluded;
1634 do {
1635 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
1636 $excluded = command_oneline(@cmd);
1637 if ( $excluded ) {
1638 my @new;
1639 my $found;
1640 for my $commit ( @commits ) {
1641 if ( $commit eq $excluded ) {
1642 push @excluded, $commit;
1643 $found++;
1644 last;
1645 }
1646 else {
1647 push @new, $commit;
1648 }
1649 }
1650 die "saw commit '$excluded' in rev-list output, "
1651 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
1652 unless $found;
1653 @commits = @new;
1654 }
1655 }
1656 while ($excluded and @commits);
1657
1658 return @excluded;
1659}
1660
1661
1662# note: this function should only be called if the various dirprops
1663# have actually changed
1664sub find_extra_svn_parents {
1665 my ($self, $ed, $mergeinfo, $parents) = @_;
1666 # aha! svk:merge property changed...
1667
1668 memoize_svn_mergeinfo_functions();
1669
1670 # We first search for merged tips which are not in our
1671 # history. Then, we figure out which git revisions are in
1672 # that tip, but not this revision. If all of those revisions
1673 # are now marked as merge, we can add the tip as a parent.
1674 my @merges = split "\n", $mergeinfo;
1675 my @merge_tips;
1676 my $url = $self->{url};
1677 my $uuid = $self->ra_uuid;
1678 my %ranges;
1679 for my $merge ( @merges ) {
1680 my ($tip_commit, @ranges) =
1681 lookup_svn_merge( $uuid, $url, $merge );
1682 unless (!$tip_commit or
1683 grep { $_ eq $tip_commit } @$parents ) {
1684 push @merge_tips, $tip_commit;
1685 $ranges{$tip_commit} = \@ranges;
1686 } else {
1687 push @merge_tips, undef;
1688 }
1689 }
1690
1691 my %excluded = map { $_ => 1 }
1692 parents_exclude($parents, grep { defined } @merge_tips);
1693
1694 # check merge tips for new parents
1695 my @new_parents;
1696 for my $merge_tip ( @merge_tips ) {
1697 my $spec = shift @merges;
1698 next unless $merge_tip and $excluded{$merge_tip};
1699
1700 my $ranges = $ranges{$merge_tip};
1701
1702 # check out 'new' tips
1703 my $merge_base;
1704 eval {
1705 $merge_base = command_oneline(
1706 "merge-base",
1707 @$parents, $merge_tip,
1708 );
1709 };
1710 if ($@) {
1711 die "An error occurred during merge-base"
1712 unless $@->isa("Git::Error::Command");
1713
1714 warn "W: Cannot find common ancestor between ".
1715 "@$parents and $merge_tip. Ignoring merge info.\n";
1716 next;
1717 }
1718
1719 # double check that there are no missing non-merge commits
1720 my (@incomplete) = check_cherry_pick(
1721 $merge_base, $merge_tip,
1722 $parents,
1723 @$ranges,
1724 );
1725
1726 if ( @incomplete ) {
1727 warn "W:svn cherry-pick ignored ($spec) - missing "
1728 .@incomplete." commit(s) (eg $incomplete[0])\n";
1729 } else {
1730 warn
1731 "Found merge parent (svn:mergeinfo prop): ",
1732 $merge_tip, "\n";
1733 push @new_parents, $merge_tip;
1734 }
1735 }
1736
1737 # cater for merges which merge commits from multiple branches
1738 if ( @new_parents > 1 ) {
1739 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
1740 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
1741 next if $i == $j;
1742 next unless $new_parents[$i];
1743 next unless $new_parents[$j];
1744 my $revs = command_oneline(
1745 "rev-list", "-1",
1746 "$new_parents[$i]..$new_parents[$j]",
1747 );
1748 if ( !$revs ) {
1749 undef($new_parents[$j]);
1750 }
1751 }
1752 }
1753 }
1754 push @$parents, grep { defined } @new_parents;
1755}
1756
1757sub make_log_entry {
1758 my ($self, $rev, $parents, $ed) = @_;
1759 my $untracked = $self->get_untracked($ed);
1760
1761 my @parents = @$parents;
1762 my $ps = $ed->{path_strip} || "";
1763 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
1764 my $props = $ed->{dir_prop}{$path};
1765 if ( $props->{"svk:merge"} ) {
1766 $self->find_extra_svk_parents
1767 ($ed, $props->{"svk:merge"}, \@parents);
1768 }
1769 if ( $props->{"svn:mergeinfo"} ) {
1770 $self->find_extra_svn_parents
1771 ($ed,
1772 $props->{"svn:mergeinfo"},
1773 \@parents);
1774 }
1775 }
1776
1777 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1778 print $un "r$rev\n" or croak $!;
1779 print $un $_, "\n" foreach @$untracked;
1780 my %log_entry = ( parents => \@parents, revision => $rev,
1781 log => '');
1782
1783 my $headrev;
1784 my $logged = delete $self->{logged_rev_props};
1785 if (!$logged || $self->{-want_revprops}) {
1786 my $rp = $self->ra->rev_proplist($rev);
1787 foreach (sort keys %$rp) {
1788 my $v = $rp->{$_};
1789 if (/^svn:(author|date|log)$/) {
1790 $log_entry{$1} = $v;
1791 } elsif ($_ eq 'svm:headrev') {
1792 $headrev = $v;
1793 } else {
1794 print $un " rev_prop: ", uri_encode($_), ' ',
1795 uri_encode($v), "\n";
1796 }
1797 }
1798 } else {
1799 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1800 }
1801 close $un or croak $!;
1802
1803 $log_entry{date} = parse_svn_date($log_entry{date});
1804 $log_entry{log} .= "\n";
1805 my $author = $log_entry{author} = check_author($log_entry{author});
1806 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1807 : ($author, undef);
1808
1809 my ($commit_name, $commit_email) = ($name, $email);
1810 if ($_use_log_author) {
1811 my $name_field;
1812 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
1813 $name_field = $1;
1814 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
1815 $name_field = $1;
1816 }
1817 if (!defined $name_field) {
1818 if (!defined $email) {
1819 $email = $name;
1820 }
1821 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
1822 ($name, $email) = ($1, $2);
1823 } elsif ($name_field =~ /(.*)@/) {
1824 ($name, $email) = ($1, $name_field);
1825 } else {
1826 ($name, $email) = ($name_field, $name_field);
1827 }
1828 }
1829 if (defined $headrev && $self->use_svm_props) {
1830 if ($self->rewrite_root) {
1831 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1832 "options set!\n";
1833 }
1834 if ($self->rewrite_uuid) {
1835 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
1836 "options set!\n";
1837 }
1838 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
1839 # we don't want "SVM: initializing mirror for junk" ...
1840 return undef if $r == 0;
1841 my $svm = $self->svm;
1842 if ($uuid ne $svm->{uuid}) {
1843 die "UUID mismatch on SVM path:\n",
1844 "expected: $svm->{uuid}\n",
1845 " got: $uuid\n";
1846 }
1847 my $full_url = $self->full_url;
1848 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1849 die "Failed to replace '$svm->{replace}' with ",
1850 "'$svm->{source}' in $full_url\n";
1851 # throw away username for storing in records
1852 remove_username($full_url);
1853 $log_entry{metadata} = "$full_url\@$r $uuid";
1854 $log_entry{svm_revision} = $r;
1855 $email ||= "$author\@$uuid";
1856 $commit_email ||= "$author\@$uuid";
1857 } elsif ($self->use_svnsync_props) {
1858 my $full_url = $self->svnsync->{url};
1859 $full_url .= "/$self->{path}" if length $self->{path};
1860 remove_username($full_url);
1861 my $uuid = $self->svnsync->{uuid};
1862 $log_entry{metadata} = "$full_url\@$rev $uuid";
1863 $email ||= "$author\@$uuid";
1864 $commit_email ||= "$author\@$uuid";
1865 } else {
1866 my $url = $self->metadata_url;
1867 remove_username($url);
1868 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
1869 $log_entry{metadata} = "$url\@$rev " . $uuid;
1870 $email ||= "$author\@" . $uuid;
1871 $commit_email ||= "$author\@" . $uuid;
1872 }
1873 $log_entry{name} = $name;
1874 $log_entry{email} = $email;
1875 $log_entry{commit_name} = $commit_name;
1876 $log_entry{commit_email} = $commit_email;
1877 \%log_entry;
1878}
1879
1880sub fetch {
1881 my ($self, $min_rev, $max_rev, @parents) = @_;
1882 my ($last_rev, $last_commit) = $self->last_rev_commit;
1883 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1884 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1885}
1886
1887sub set_tree_cb {
1888 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1889 $self->{inject_parents} = { $rev => $tree };
1890 $self->fetch(undef, undef);
1891}
1892
1893sub set_tree {
1894 my ($self, $tree) = (shift, shift);
1895 my $log_entry = ::get_commit_entry($tree);
1896 unless ($self->{last_rev}) {
1897 fatal("Must have an existing revision to commit");
1898 }
1899 my %ed_opts = ( r => $self->{last_rev},
1900 log => $log_entry->{log},
1901 ra => $self->ra,
1902 tree_a => $self->{last_commit},
1903 tree_b => $tree,
1904 editor_cb => sub {
1905 $self->set_tree_cb($log_entry, $tree, @_) },
1906 svn_path => $self->{path} );
1907 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1908 print "No changes\nr$self->{last_rev} = $tree\n";
1909 }
1910}
1911
1912sub rebuild_from_rev_db {
1913 my ($self, $path) = @_;
1914 my $r = -1;
1915 open my $fh, '<', $path or croak "open: $!";
1916 binmode $fh or croak "binmode: $!";
1917 while (<$fh>) {
1918 length($_) == 41 or croak "inconsistent size in ($_) != 41";
1919 chomp($_);
1920 ++$r;
1921 next if $_ eq ('0' x 40);
1922 $self->rev_map_set($r, $_);
1923 print "r$r = $_\n";
1924 }
1925 close $fh or croak "close: $!";
1926 unlink $path or croak "unlink: $!";
1927}
1928
1929sub rebuild {
1930 my ($self) = @_;
1931 my $map_path = $self->map_path;
1932 my $partial = (-e $map_path && ! -z $map_path);
1933 return unless ::verify_ref($self->refname.'^0');
1934 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
1935 my $rev_db = $self->rev_db_path;
1936 $self->rebuild_from_rev_db($rev_db);
1937 if ($self->use_svm_props) {
1938 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
1939 $self->rebuild_from_rev_db($svm_rev_db);
1940 }
1941 $self->unlink_rev_db_symlink;
1942 return;
1943 }
1944 print "Rebuilding $map_path ...\n" if (!$partial);
1945 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
1946 (undef, undef));
1947 my ($log, $ctx) =
1948 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
1949 ($head ? "$head.." : "") . $self->refname,
1950 '--');
1951 my $metadata_url = $self->metadata_url;
1952 remove_username($metadata_url);
1953 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
1954 my $c;
1955 while (<$log>) {
1956 if ( m{^commit ($::sha1)$} ) {
1957 $c = $1;
1958 next;
1959 }
1960 next unless s{^\s*(git-svn-id:)}{$1};
1961 my ($url, $rev, $uuid) = ::extract_metadata($_);
1962 remove_username($url);
1963
1964 # ignore merges (from set-tree)
1965 next if (!defined $rev || !$uuid);
1966
1967 # if we merged or otherwise started elsewhere, this is
1968 # how we break out of it
1969 if (($uuid ne $svn_uuid) ||
1970 ($metadata_url && $url && ($url ne $metadata_url))) {
1971 next;
1972 }
1973 if ($partial && $head) {
1974 print "Partial-rebuilding $map_path ...\n";
1975 print "Currently at $base_rev = $head\n";
1976 $head = undef;
1977 }
1978
1979 $self->rev_map_set($rev, $c);
1980 print "r$rev = $c\n";
1981 }
1982 command_close_pipe($log, $ctx);
1983 print "Done rebuilding $map_path\n" if (!$partial || !$head);
1984 my $rev_db_path = $self->rev_db_path;
1985 if (-f $self->rev_db_path) {
1986 unlink $self->rev_db_path or croak "unlink: $!";
1987 }
1988 $self->unlink_rev_db_symlink;
1989}
1990
1991# rev_map:
1992# Tie::File seems to be prone to offset errors if revisions get sparse,
1993# it's not that fast, either. Tie::File is also not in Perl 5.6. So
1994# one of my favorite modules is out :< Next up would be one of the DBM
1995# modules, but I'm not sure which is most portable...
1996#
1997# This is the replacement for the rev_db format, which was too big
1998# and inefficient for large repositories with a lot of sparse history
1999# (mainly tags)
2000#
2001# The format is this:
2002# - 24 bytes for every record,
2003# * 4 bytes for the integer representing an SVN revision number
2004# * 20 bytes representing the sha1 of a git commit
2005# - No empty padding records like the old format
2006# (except the last record, which can be overwritten)
2007# - new records are written append-only since SVN revision numbers
2008# increase monotonically
2009# - lookups on SVN revision number are done via a binary search
2010# - Piping the file to xxd -c24 is a good way of dumping it for
2011# viewing or editing (piped back through xxd -r), should the need
2012# ever arise.
2013# - The last record can be padding revision with an all-zero sha1
2014# This is used to optimize fetch performance when using multiple
2015# "fetch" directives in .git/config
2016#
2017# These files are disposable unless noMetadata or useSvmProps is set
2018
2019sub _rev_map_set {
2020 my ($fh, $rev, $commit) = @_;
2021
2022 binmode $fh or croak "binmode: $!";
2023 my $size = (stat($fh))[7];
2024 ($size % 24) == 0 or croak "inconsistent size: $size";
2025
2026 my $wr_offset = 0;
2027 if ($size > 0) {
2028 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2029 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2030 $read == 24 or croak "read only $read bytes (!= 24)";
2031 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2032 if ($last_commit eq ('0' x40)) {
2033 if ($size >= 48) {
2034 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2035 $read = sysread($fh, $buf, 24) or
2036 croak "read: $!";
2037 $read == 24 or
2038 croak "read only $read bytes (!= 24)";
2039 ($last_rev, $last_commit) =
2040 unpack(rev_map_fmt, $buf);
2041 if ($last_commit eq ('0' x40)) {
2042 croak "inconsistent .rev_map\n";
2043 }
2044 }
2045 if ($last_rev >= $rev) {
2046 croak "last_rev is higher!: $last_rev >= $rev";
2047 }
2048 $wr_offset = -24;
2049 }
2050 }
2051 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2052 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2053 croak "write: $!";
2054}
2055
2056sub _rev_map_reset {
2057 my ($fh, $rev, $commit) = @_;
2058 my $c = _rev_map_get($fh, $rev);
2059 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
2060 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
2061 truncate $fh, $offset or croak "truncate: $!";
2062}
2063
2064sub mkfile {
2065 my ($path) = @_;
2066 unless (-e $path) {
2067 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2068 mkpath([$dir]) unless -d $dir;
2069 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2070 close $fh or die "Couldn't close (create) $path: $!\n";
2071 }
2072}
2073
2074sub rev_map_set {
2075 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2076 defined $commit or die "missing arg3\n";
2077 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2078 my $db = $self->map_path($uuid);
2079 my $db_lock = "$db.lock";
2080 my $sigmask;
2081 $update_ref ||= 0;
2082 if ($update_ref) {
2083 $sigmask = POSIX::SigSet->new();
2084 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
2085 SIGALRM, SIGUSR1, SIGUSR2);
2086 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
2087 croak "Can't block signals: $!";
2088 }
2089 mkfile($db);
2090
2091 $LOCKFILES{$db_lock} = 1;
2092 my $sync;
2093 # both of these options make our .rev_db file very, very important
2094 # and we can't afford to lose it because rebuild() won't work
2095 if ($self->use_svm_props || $self->no_metadata) {
2096 $sync = 1;
2097 copy($db, $db_lock) or die "rev_map_set(@_): ",
2098 "Failed to copy: ",
2099 "$db => $db_lock ($!)\n";
2100 } else {
2101 rename $db, $db_lock or die "rev_map_set(@_): ",
2102 "Failed to rename: ",
2103 "$db => $db_lock ($!)\n";
2104 }
2105
2106 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2107 or croak "Couldn't open $db_lock: $!\n";
2108 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
2109 _rev_map_set($fh, $rev, $commit);
2110 if ($sync) {
2111 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2112 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2113 }
2114 close $fh or croak $!;
2115 if ($update_ref) {
2116 $_head = $self;
2117 my $note = "";
2118 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
2119 command_noisy('update-ref', '-m', "r$rev$note",
2120 $self->refname, $commit);
2121 }
2122 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2123 "$db_lock => $db ($!)\n";
2124 delete $LOCKFILES{$db_lock};
2125 if ($update_ref) {
2126 sigprocmask(SIG_SETMASK, $sigmask) or
2127 croak "Can't restore signal mask: $!";
2128 }
2129}
2130
2131# If want_commit, this will return an array of (rev, commit) where
2132# commit _must_ be a valid commit in the archive.
2133# Otherwise, it'll return the max revision (whether or not the
2134# commit is valid or just a 0x40 placeholder).
2135sub rev_map_max {
2136 my ($self, $want_commit) = @_;
2137 $self->rebuild;
2138 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2139 $want_commit ? ($r, $c) : $r;
2140}
2141
2142sub rev_map_max_norebuild {
2143 my ($self, $want_commit) = @_;
2144 my $map_path = $self->map_path;
2145 stat $map_path or return $want_commit ? (0, undef) : 0;
2146 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2147 binmode $fh or croak "binmode: $!";
2148 my $size = (stat($fh))[7];
2149 ($size % 24) == 0 or croak "inconsistent size: $size";
2150
2151 if ($size == 0) {
2152 close $fh or croak "close: $!";
2153 return $want_commit ? (0, undef) : 0;
2154 }
2155
2156 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2157 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2158 my ($r, $c) = unpack(rev_map_fmt, $buf);
2159 if ($want_commit && $c eq ('0' x40)) {
2160 if ($size < 48) {
2161 return $want_commit ? (0, undef) : 0;
2162 }
2163 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2164 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2165 ($r, $c) = unpack(rev_map_fmt, $buf);
2166 if ($c eq ('0'x40)) {
2167 croak "Penultimate record is all-zeroes in $map_path";
2168 }
2169 }
2170 close $fh or croak "close: $!";
2171 $want_commit ? ($r, $c) : $r;
2172}
2173
2174sub rev_map_get {
2175 my ($self, $rev, $uuid) = @_;
2176 my $map_path = $self->map_path($uuid);
2177 return undef unless -e $map_path;
2178
2179 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2180 my $c = _rev_map_get($fh, $rev);
2181 close($fh) or croak "close: $!";
2182 $c
2183}
2184
2185sub _rev_map_get {
2186 my ($fh, $rev) = @_;
2187
2188 binmode $fh or croak "binmode: $!";
2189 my $size = (stat($fh))[7];
2190 ($size % 24) == 0 or croak "inconsistent size: $size";
2191
2192 if ($size == 0) {
2193 return undef;
2194 }
2195
2196 my ($l, $u) = (0, $size - 24);
2197 my ($r, $c, $buf);
2198
2199 while ($l <= $u) {
2200 my $i = int(($l/24 + $u/24) / 2) * 24;
2201 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2202 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2203 my ($r, $c) = unpack(rev_map_fmt, $buf);
2204
2205 if ($r < $rev) {
2206 $l = $i + 24;
2207 } elsif ($r > $rev) {
2208 $u = $i - 24;
2209 } else { # $r == $rev
2210 return $c eq ('0' x 40) ? undef : $c;
2211 }
2212 }
2213 undef;
2214}
2215
2216# Finds the first svn revision that exists on (if $eq_ok is true) or
2217# before $rev for the current branch. It will not search any lower
2218# than $min_rev. Returns the git commit hash and svn revision number
2219# if found, else (undef, undef).
2220sub find_rev_before {
2221 my ($self, $rev, $eq_ok, $min_rev) = @_;
2222 --$rev unless $eq_ok;
2223 $min_rev ||= 1;
2224 my $max_rev = $self->rev_map_max;
2225 $rev = $max_rev if ($rev > $max_rev);
2226 while ($rev >= $min_rev) {
2227 if (my $c = $self->rev_map_get($rev)) {
2228 return ($rev, $c);
2229 }
2230 --$rev;
2231 }
2232 return (undef, undef);
2233}
2234
2235# Finds the first svn revision that exists on (if $eq_ok is true) or
2236# after $rev for the current branch. It will not search any higher
2237# than $max_rev. Returns the git commit hash and svn revision number
2238# if found, else (undef, undef).
2239sub find_rev_after {
2240 my ($self, $rev, $eq_ok, $max_rev) = @_;
2241 ++$rev unless $eq_ok;
2242 $max_rev ||= $self->rev_map_max;
2243 while ($rev <= $max_rev) {
2244 if (my $c = $self->rev_map_get($rev)) {
2245 return ($rev, $c);
2246 }
2247 ++$rev;
2248 }
2249 return (undef, undef);
2250}
2251
2252sub _new {
2253 my ($class, $repo_id, $ref_id, $path) = @_;
2254 unless (defined $repo_id && length $repo_id) {
2255 $repo_id = $default_repo_id;
2256 }
2257 unless (defined $ref_id && length $ref_id) {
2258 # Access the prefix option from the git-svn main program if it's loaded.
2259 my $prefix = defined &::opt_prefix ? ::opt_prefix() : "";
2260 $_[2] = $ref_id =
2261 "refs/remotes/$prefix$default_ref_id";
2262 }
2263 $_[1] = $repo_id;
2264 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2265
2266 # Older repos imported by us used $GIT_DIR/svn/foo instead of
2267 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
2268 if ($ref_id =~ m{^refs/remotes/(.*)}) {
2269 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
2270 if (-d $old_dir && ! -d $dir) {
2271 $dir = $old_dir;
2272 }
2273 }
2274
2275 $_[3] = $path = '' unless (defined $path);
2276 mkpath([$dir]);
2277 bless {
2278 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2279 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2280 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2281}
2282
2283# for read-only access of old .rev_db formats
2284sub unlink_rev_db_symlink {
2285 my ($self) = @_;
2286 my $link = $self->rev_db_path;
2287 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2288 if (-l $link) {
2289 unlink $link or croak "unlink: $link failed!";
2290 }
2291}
2292
2293sub rev_db_path {
2294 my ($self, $uuid) = @_;
2295 my $db_path = $self->map_path($uuid);
2296 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2297 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2298 $db_path;
2299}
2300
2301# the new replacement for .rev_db
2302sub map_path {
2303 my ($self, $uuid) = @_;
2304 $uuid ||= $self->ra_uuid;
2305 "$self->{map_root}.$uuid";
2306}
2307
2308sub uri_encode {
2309 my ($f) = @_;
2310 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2311 $f
2312}
2313
2314sub uri_decode {
2315 my ($f) = @_;
2316 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
2317 $f
2318}
2319
2320sub remove_username {
2321 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2322}
2323
23241;