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