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