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