Sync with 1.8.1.5
[git/jnareb-git.git] / perl / Git / SVN.pm
blob0ebc68ac7e64171acc52abe59063fec48ca3c129
1 package Git::SVN;
2 use strict;
3 use warnings;
4 use Fcntl qw/:DEFAULT :seek/;
5 use constant rev_map_fmt => 'NH40';
6 use 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/;
10 use Carp qw/croak/;
11 use File::Path qw/mkpath/;
12 use File::Copy qw/copy/;
13 use IPC::Open3;
14 use Memoize; # core since 5.8.0, Jul 2002
15 use Memoize::Storable;
16 use POSIX qw(:signal_h);
18 use Git qw(
19 command
20 command_oneline
21 command_noisy
22 command_output_pipe
23 command_close_pipe
24 get_tz_offset
26 use Git::SVN::Utils qw(
27 fatal
28 can_compress
29 join_paths
30 canonicalize_path
31 canonicalize_url
32 add_path_to_url
35 my $can_use_yaml;
36 BEGIN {
37 $can_use_yaml = eval { require Git::SVN::Memoize::YAML; 1};
40 our $_follow_parent = 1;
41 our $_minimize_url = 'unset';
42 our $default_repo_id = 'svn';
43 our $default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
45 my ($_gc_nr, $_gc_period);
47 # properties that we do not log:
48 my %SKIP_PROP;
49 BEGIN {
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/;
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;
77 return $self->{$prop};
83 my (%LOCKFILES, %INDEX_FILES);
84 END {
85 unlink keys %LOCKFILES if %LOCKFILES;
86 unlink keys %INDEX_FILES if %INDEX_FILES;
89 sub 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";
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;
116 } else {
117 $fetch->{$pathname} = $refname;
122 sub parse_revision_argument {
123 my ($base, $head) = @_;
124 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
125 return ($base, $head);
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";
135 sub 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};
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;
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 $@;
156 my $base = defined $fetch ? $head : 0;
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}};
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;
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);
179 push @gs, $gs;
183 ($base, $head) = parse_revision_argument($base, $head);
184 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
187 sub 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);
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";
228 push @{ $r->{$remote}->{$t} }, $rs;
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"),
244 $r->{$_}->{svm} = $svm;
246 } keys %$r;
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};
261 sub 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";
268 sub 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";
280 $seen{$1} = $_;
285 sub 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;
295 $existing;
298 sub 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";
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";
317 $self->{repo_id} = $existing;
319 if ($min_url ne $url) {
320 unless ($no_write) {
321 print STDERR "Using higher level of URL: ",
322 "$url => $min_url\n";
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;
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")
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";
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";
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);
359 $self->url($url);
362 sub find_by_url { # repos_root and, path are optional
363 my ($class, $full_url, $repos_root, $path) = @_;
365 $full_url = canonicalize_url($full_url);
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(?:/|$)##;
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;
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);
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#/$##;
403 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
406 # remote fetch paths are not URI escaped. Decode ours
407 # so they match
408 $p = uri_decode($p);
410 foreach my $f (keys %$fetch) {
411 next if $f ne $p;
412 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
415 undef;
418 sub 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);
424 $self;
427 sub 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);
438 (undef, undef, undef);
441 sub 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";
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);
462 my $path = $self->path;
463 $path =~ s{\A/}{};
464 $path =~ s{/\z}{};
465 $self->path($path);
467 my $url = command_oneline('config', '--get',
468 "svn-remote.$repo_id.url") or
469 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
470 $self->url($url);
471 $self->{pushurl} = eval { command_oneline('config', '--get',
472 "svn-remote.$repo_id.pushurl") };
473 $self->rebuild;
474 $self;
477 sub refname {
478 my ($refname) = $_[0]->{ref_id} ;
480 # It cannot end with a slash /, we'll throw up on this because
481 # SVN can't have directories with a slash in their name, either:
482 if ($refname =~ m{/$}) {
483 die "ref: '$refname' ends with a trailing slash, this is ",
484 "not permitted by git nor Subversion\n";
487 # It cannot have ASCII control character space, tilde ~, caret ^,
488 # colon :, question-mark ?, asterisk *, space, or open bracket [
489 # anywhere.
491 # Additionally, % must be escaped because it is used for escaping
492 # and we want our escaped refname to be reversible
493 $refname =~ s{([ \%~\^:\?\*\[\t])}{sprintf('%%%02X',ord($1))}eg;
495 # no slash-separated component can begin with a dot .
496 # /.* becomes /%2E*
497 $refname =~ s{/\.}{/%2E}g;
499 # It cannot have two consecutive dots .. anywhere
500 # .. becomes %2E%2E
501 $refname =~ s{\.\.}{%2E%2E}g;
503 # trailing dots and .lock are not allowed
504 # .$ becomes %2E and .lock becomes %2Elock
505 $refname =~ s{\.(?=$|lock$)}{%2E};
507 # the sequence @{ is used to access the reflog
508 # @{ becomes %40{
509 $refname =~ s{\@\{}{%40\{}g;
511 return $refname;
514 sub desanitize_refname {
515 my ($refname) = @_;
516 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
517 return $refname;
520 sub svm_uuid {
521 my ($self) = @_;
522 return $self->{svm}->{uuid} if $self->svm;
523 $self->ra;
524 unless ($self->{svm}) {
525 die "SVM UUID not cached, and reading remotely failed\n";
527 $self->{svm}->{uuid};
530 sub svm {
531 my ($self) = @_;
532 return $self->{svm} if $self->{svm};
533 my $svm;
534 # see if we have it in our config, first:
535 eval {
536 my $section = "svn-remote.$self->{repo_id}";
537 $svm = {
538 source => tmp_config('--get', "$section.svm-source"),
539 uuid => tmp_config('--get', "$section.svm-uuid"),
540 replace => tmp_config('--get', "$section.svm-replace"),
543 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
544 $self->{svm} = $svm;
546 $self->{svm};
549 sub _set_svm_vars {
550 my ($self, $ra) = @_;
551 return $ra if $self->svm;
553 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
554 "(svm:source, svm:uuid) ",
555 "from the following URLs:\n" );
556 sub read_svm_props {
557 my ($self, $ra, $path, $r) = @_;
558 my $props = ($ra->get_dir($path, $r))[2];
559 my $src = $props->{'svm:source'};
560 my $uuid = $props->{'svm:uuid'};
561 return undef if (!$src || !$uuid);
563 chomp($src, $uuid);
565 $uuid =~ m{^[0-9a-f\-]{30,}$}i
566 or die "doesn't look right - svm:uuid is '$uuid'\n";
568 # the '!' is used to mark the repos_root!/relative/path
569 $src =~ s{/?!/?}{/};
570 $src =~ s{/+$}{}; # no trailing slashes please
571 # username is of no interest
572 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
574 my $replace = add_path_to_url($ra->url, $path);
576 my $section = "svn-remote.$self->{repo_id}";
577 tmp_config("$section.svm-source", $src);
578 tmp_config("$section.svm-replace", $replace);
579 tmp_config("$section.svm-uuid", $uuid);
580 $self->{svm} = {
581 source => $src,
582 uuid => $uuid,
583 replace => $replace
587 my $r = $ra->get_latest_revnum;
588 my $path = $self->path;
589 my %tried;
590 while (length $path) {
591 my $try = add_path_to_url($self->url, $path);
592 unless ($tried{$try}) {
593 return $ra if $self->read_svm_props($ra, $path, $r);
594 $tried{$try} = 1;
596 $path =~ s#/?[^/]+$##;
598 die "Path: '$path' should be ''\n" if $path ne '';
599 return $ra if $self->read_svm_props($ra, $path, $r);
600 $tried{ add_path_to_url($self->url, $path) } = 1;
602 if ($ra->{repos_root} eq $self->url) {
603 die @err, (map { " $_\n" } keys %tried), "\n";
606 # nope, make sure we're connected to the repository root:
607 my $ok;
608 my @tried_b;
609 $path = $ra->{svn_path};
610 $ra = Git::SVN::Ra->new($ra->{repos_root});
611 while (length $path) {
612 my $try = add_path_to_url($ra->url, $path);
613 unless ($tried{$try}) {
614 $ok = $self->read_svm_props($ra, $path, $r);
615 last if $ok;
616 $tried{$try} = 1;
618 $path =~ s#/?[^/]+$##;
620 die "Path: '$path' should be ''\n" if $path ne '';
621 $ok ||= $self->read_svm_props($ra, $path, $r);
622 $tried{ add_path_to_url($ra->url, $path) } = 1;
623 if (!$ok) {
624 die @err, (map { " $_\n" } keys %tried), "\n";
626 Git::SVN::Ra->new($self->url);
629 sub svnsync {
630 my ($self) = @_;
631 return $self->{svnsync} if $self->{svnsync};
633 if ($self->no_metadata) {
634 die "Can't have both 'noMetadata' and ",
635 "'useSvnsyncProps' options set!\n";
637 if ($self->rewrite_root) {
638 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
639 "options set!\n";
641 if ($self->rewrite_uuid) {
642 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
643 "options set!\n";
646 my $svnsync;
647 # see if we have it in our config, first:
648 eval {
649 my $section = "svn-remote.$self->{repo_id}";
651 my $url = tmp_config('--get', "$section.svnsync-url");
652 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
653 die "doesn't look right - svn:sync-from-url is '$url'\n";
655 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
656 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
657 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
659 $svnsync = { url => $url, uuid => $uuid }
661 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
662 return $self->{svnsync} = $svnsync;
665 my $err = "useSvnsyncProps set, but failed to read " .
666 "svnsync property: svn:sync-from-";
667 my $rp = $self->ra->rev_proplist(0);
669 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
670 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
671 die "doesn't look right - svn:sync-from-url is '$url'\n";
673 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
674 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
675 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
677 my $section = "svn-remote.$self->{repo_id}";
678 tmp_config('--add', "$section.svnsync-uuid", $uuid);
679 tmp_config('--add', "$section.svnsync-url", $url);
680 return $self->{svnsync} = { url => $url, uuid => $uuid };
683 # this allows us to memoize our SVN::Ra UUID locally and avoid a
684 # remote lookup (useful for 'git svn log').
685 sub ra_uuid {
686 my ($self) = @_;
687 unless ($self->{ra_uuid}) {
688 my $key = "svn-remote.$self->{repo_id}.uuid";
689 my $uuid = eval { tmp_config('--get', $key) };
690 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
691 $self->{ra_uuid} = $uuid;
692 } else {
693 die "ra_uuid called without URL\n" unless $self->url;
694 $self->{ra_uuid} = $self->ra->get_uuid;
695 tmp_config('--add', $key, $self->{ra_uuid});
698 $self->{ra_uuid};
701 sub _set_repos_root {
702 my ($self, $repos_root) = @_;
703 my $k = "svn-remote.$self->{repo_id}.reposRoot";
704 $repos_root ||= $self->ra->{repos_root};
705 tmp_config($k, $repos_root);
706 $repos_root;
709 sub repos_root {
710 my ($self) = @_;
711 my $k = "svn-remote.$self->{repo_id}.reposRoot";
712 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
715 sub ra {
716 my ($self) = shift;
717 my $ra = Git::SVN::Ra->new($self->url);
718 $self->_set_repos_root($ra->{repos_root});
719 if ($self->use_svm_props && !$self->{svm}) {
720 if ($self->no_metadata) {
721 die "Can't have both 'noMetadata' and ",
722 "'useSvmProps' options set!\n";
723 } elsif ($self->use_svnsync_props) {
724 die "Can't have both 'useSvnsyncProps' and ",
725 "'useSvmProps' options set!\n";
727 $ra = $self->_set_svm_vars($ra);
728 $self->{-want_revprops} = 1;
730 $ra;
733 # prop_walk(PATH, REV, SUB)
734 # -------------------------
735 # Recursively traverse PATH at revision REV and invoke SUB for each
736 # directory that contains a SVN property. SUB will be invoked as
737 # follows: &SUB(gs, path, props); where `gs' is this instance of
738 # Git::SVN, `path' the path to the directory where the properties
739 # `props' were found. The `path' will be relative to point of checkout,
740 # that is, if url://repo/trunk is the current Git branch, and that
741 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
742 # as `path' (note the trailing `/').
743 sub prop_walk {
744 my ($self, $path, $rev, $sub) = @_;
746 $path =~ s#^/##;
747 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
748 $path =~ s#^/*#/#g;
749 my $p = $path;
750 # Strip the irrelevant part of the path.
751 $p =~ s#^/+\Q@{[$self->path]}\E(/|$)#/#;
752 # Ensure the path is terminated by a `/'.
753 $p =~ s#/*$#/#;
755 # The properties contain all the internal SVN stuff nobody
756 # (usually) cares about.
757 my $interesting_props = 0;
758 foreach (keys %{$props}) {
759 # If it doesn't start with `svn:', it must be a
760 # user-defined property.
761 ++$interesting_props and next if $_ !~ /^svn:/;
762 # FIXME: Fragile, if SVN adds new public properties,
763 # this needs to be updated.
764 ++$interesting_props if /^svn:(?:ignore|keywords|executable
765 |eol-style|mime-type
766 |externals|needs-lock)$/x;
768 &$sub($self, $p, $props) if $interesting_props;
770 foreach (sort keys %$dirent) {
771 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
772 $self->prop_walk($self->path . $p . $_, $rev, $sub);
776 sub last_rev { ($_[0]->last_rev_commit)[0] }
777 sub last_commit { ($_[0]->last_rev_commit)[1] }
779 # returns the newest SVN revision number and newest commit SHA1
780 sub last_rev_commit {
781 my ($self) = @_;
782 if (defined $self->{last_rev} && defined $self->{last_commit}) {
783 return ($self->{last_rev}, $self->{last_commit});
785 my $c = ::verify_ref($self->refname.'^0');
786 if ($c && !$self->use_svm_props && !$self->no_metadata) {
787 my $rev = (::cmt_metadata($c))[1];
788 if (defined $rev) {
789 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
790 return ($rev, $c);
793 my $map_path = $self->map_path;
794 unless (-e $map_path) {
795 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
796 return (undef, undef);
798 my ($rev, $commit) = $self->rev_map_max(1);
799 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
800 return ($rev, $commit);
803 sub get_fetch_range {
804 my ($self, $min, $max) = @_;
805 $max ||= $self->ra->get_latest_revnum;
806 $min ||= $self->rev_map_max;
807 (++$min, $max);
810 sub tmp_config {
811 my (@args) = @_;
812 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
813 my $config = "$ENV{GIT_DIR}/svn/.metadata";
814 if (! -f $config && -f $old_def_config) {
815 rename $old_def_config, $config or
816 die "Failed rename $old_def_config => $config: $!\n";
818 my $old_config = $ENV{GIT_CONFIG};
819 $ENV{GIT_CONFIG} = $config;
820 $@ = undef;
821 my @ret = eval {
822 unless (-f $config) {
823 mkfile($config);
824 open my $fh, '>', $config or
825 die "Can't open $config: $!\n";
826 print $fh "; This file is used internally by ",
827 "git-svn\n" or die
828 "Couldn't write to $config: $!\n";
829 print $fh "; You should not have to edit it\n" or
830 die "Couldn't write to $config: $!\n";
831 close $fh or die "Couldn't close $config: $!\n";
833 command('config', @args);
835 my $err = $@;
836 if (defined $old_config) {
837 $ENV{GIT_CONFIG} = $old_config;
838 } else {
839 delete $ENV{GIT_CONFIG};
841 die $err if $err;
842 wantarray ? @ret : $ret[0];
845 sub tmp_index_do {
846 my ($self, $sub) = @_;
847 my $old_index = $ENV{GIT_INDEX_FILE};
848 $ENV{GIT_INDEX_FILE} = $self->{index};
849 $@ = undef;
850 my @ret = eval {
851 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
852 mkpath([$dir]) unless -d $dir;
853 &$sub;
855 my $err = $@;
856 if (defined $old_index) {
857 $ENV{GIT_INDEX_FILE} = $old_index;
858 } else {
859 delete $ENV{GIT_INDEX_FILE};
861 die $err if $err;
862 wantarray ? @ret : $ret[0];
865 sub assert_index_clean {
866 my ($self, $treeish) = @_;
868 $self->tmp_index_do(sub {
869 command_noisy('read-tree', $treeish) unless -e $self->{index};
870 my $x = command_oneline('write-tree');
871 my ($y) = (command(qw/cat-file commit/, $treeish) =~
872 /^tree ($::sha1)/mo);
873 return if $y eq $x;
875 warn "Index mismatch: $y != $x\nrereading $treeish\n";
876 unlink $self->{index} or die "unlink $self->{index}: $!\n";
877 command_noisy('read-tree', $treeish);
878 $x = command_oneline('write-tree');
879 if ($y ne $x) {
880 fatal "trees ($treeish) $y != $x\n",
881 "Something is seriously wrong...";
886 sub get_commit_parents {
887 my ($self, $log_entry) = @_;
888 my (%seen, @ret, @tmp);
889 # legacy support for 'set-tree'; this is only used by set_tree_cb:
890 if (my $ip = $self->{inject_parents}) {
891 if (my $commit = delete $ip->{$log_entry->{revision}}) {
892 push @tmp, $commit;
895 if (my $cur = ::verify_ref($self->refname.'^0')) {
896 push @tmp, $cur;
898 if (my $ipd = $self->{inject_parents_dcommit}) {
899 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
900 push @tmp, @$commit;
903 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
904 while (my $p = shift @tmp) {
905 next if $seen{$p};
906 $seen{$p} = 1;
907 push @ret, $p;
909 @ret;
912 sub rewrite_root {
913 my ($self) = @_;
914 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
915 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
916 my $rwr = eval { command_oneline(qw/config --get/, $k) };
917 if ($rwr) {
918 $rwr =~ s#/+$##;
919 if ($rwr !~ m#^[a-z\+]+://#) {
920 die "$rwr is not a valid URL (key: $k)\n";
923 $self->{-rewrite_root} = $rwr;
926 sub rewrite_uuid {
927 my ($self) = @_;
928 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
929 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
930 my $rwid = eval { command_oneline(qw/config --get/, $k) };
931 if ($rwid) {
932 $rwid =~ s#/+$##;
933 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
934 die "$rwid is not a valid UUID (key: $k)\n";
937 $self->{-rewrite_uuid} = $rwid;
940 sub metadata_url {
941 my ($self) = @_;
942 my $url = $self->rewrite_root || $self->url;
943 return canonicalize_url( add_path_to_url( $url, $self->path ) );
946 sub full_url {
947 my ($self) = @_;
948 return canonicalize_url( add_path_to_url( $self->url, $self->path ) );
951 sub full_pushurl {
952 my ($self) = @_;
953 if ($self->{pushurl}) {
954 return canonicalize_url( add_path_to_url( $self->{pushurl}, $self->path ) );
955 } else {
956 return $self->full_url;
960 sub set_commit_header_env {
961 my ($log_entry) = @_;
962 my %env;
963 foreach my $ned (qw/NAME EMAIL DATE/) {
964 foreach my $ac (qw/AUTHOR COMMITTER/) {
965 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
969 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
970 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
971 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
973 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
974 ? $log_entry->{commit_name}
975 : $log_entry->{name};
976 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
977 ? $log_entry->{commit_email}
978 : $log_entry->{email};
979 \%env;
982 sub restore_commit_header_env {
983 my ($env) = @_;
984 foreach my $ned (qw/NAME EMAIL DATE/) {
985 foreach my $ac (qw/AUTHOR COMMITTER/) {
986 my $k = "GIT_${ac}_${ned}";
987 if (defined $env->{$k}) {
988 $ENV{$k} = $env->{$k};
989 } else {
990 delete $ENV{$k};
996 sub gc {
997 command_noisy('gc', '--auto');
1000 sub do_git_commit {
1001 my ($self, $log_entry) = @_;
1002 my $lr = $self->last_rev;
1003 if (defined $lr && $lr >= $log_entry->{revision}) {
1004 die "Last fetched revision of ", $self->refname,
1005 " was r$lr, but we are about to fetch: ",
1006 "r$log_entry->{revision}!\n";
1008 if (my $c = $self->rev_map_get($log_entry->{revision})) {
1009 croak "$log_entry->{revision} = $c already exists! ",
1010 "Why are we refetching it?\n";
1012 my $old_env = set_commit_header_env($log_entry);
1013 my $tree = $log_entry->{tree};
1014 if (!defined $tree) {
1015 $tree = $self->tmp_index_do(sub {
1016 command_oneline('write-tree') });
1018 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1020 my @exec = ('git', 'commit-tree', $tree);
1021 foreach ($self->get_commit_parents($log_entry)) {
1022 push @exec, '-p', $_;
1024 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1025 or croak $!;
1026 binmode $msg_fh;
1028 # we always get UTF-8 from SVN, but we may want our commits in
1029 # a different encoding.
1030 if (my $enc = Git::config('i18n.commitencoding')) {
1031 require Encode;
1032 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
1034 print $msg_fh $log_entry->{log} or croak $!;
1035 restore_commit_header_env($old_env);
1036 unless ($self->no_metadata) {
1037 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1038 or croak $!;
1040 $msg_fh->flush == 0 or croak $!;
1041 close $msg_fh or croak $!;
1042 chomp(my $commit = do { local $/; <$out_fh> });
1043 close $out_fh or croak $!;
1044 waitpid $pid, 0;
1045 croak $? if $?;
1046 if ($commit !~ /^$::sha1$/o) {
1047 die "Failed to commit, invalid sha1: $commit\n";
1050 $self->rev_map_set($log_entry->{revision}, $commit, 1);
1052 $self->{last_rev} = $log_entry->{revision};
1053 $self->{last_commit} = $commit;
1054 print "r$log_entry->{revision}" unless $::_q > 1;
1055 if (defined $log_entry->{svm_revision}) {
1056 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
1057 $self->rev_map_set($log_entry->{svm_revision}, $commit,
1058 0, $self->svm_uuid);
1060 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
1061 if (--$_gc_nr == 0) {
1062 $_gc_nr = $_gc_period;
1063 gc();
1065 return $commit;
1068 sub match_paths {
1069 my ($self, $paths, $r) = @_;
1070 return 1 if $self->path eq '';
1071 if (my $path = $paths->{"/".$self->path}) {
1072 return ($path->{action} eq 'D') ? 0 : 1;
1074 $self->{path_regex} ||= qr{^/\Q@{[$self->path]}\E/};
1075 if (grep /$self->{path_regex}/, keys %$paths) {
1076 return 1;
1078 my $c = '';
1079 foreach (split m#/#, $self->path) {
1080 $c .= "/$_";
1081 next unless ($paths->{$c} &&
1082 ($paths->{$c}->{action} =~ /^[AR]$/));
1083 if ($self->ra->check_path($self->path, $r) ==
1084 $SVN::Node::dir) {
1085 return 1;
1088 return 0;
1091 sub find_parent_branch {
1092 my ($self, $paths, $rev) = @_;
1093 return undef unless $self->follow_parent;
1094 unless (defined $paths) {
1095 my $err_handler = $SVN::Error::handler;
1096 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1097 $self->ra->get_log([$self->path], $rev, $rev, 0, 1, 1,
1098 sub { $paths = $_[0] });
1099 $SVN::Error::handler = $err_handler;
1101 return undef unless defined $paths;
1103 # look for a parent from another branch:
1104 my @b_path_components = split m#/#, $self->path;
1105 my @a_path_components;
1106 my $i;
1107 while (@b_path_components) {
1108 $i = $paths->{'/'.join('/', @b_path_components)};
1109 last if $i && defined $i->{copyfrom_path};
1110 unshift(@a_path_components, pop(@b_path_components));
1112 return undef unless defined $i && defined $i->{copyfrom_path};
1113 my $branch_from = $i->{copyfrom_path};
1114 if (@a_path_components) {
1115 print STDERR "branch_from: $branch_from => ";
1116 $branch_from .= '/'.join('/', @a_path_components);
1117 print STDERR $branch_from, "\n";
1119 my $r = $i->{copyfrom_rev};
1120 my $repos_root = $self->ra->{repos_root};
1121 my $url = $self->ra->url;
1122 my $new_url = canonicalize_url( add_path_to_url( $url, $branch_from ) );
1123 print STDERR "Found possible branch point: ",
1124 "$new_url => ", $self->full_url, ", $r\n"
1125 unless $::_q > 1;
1126 $branch_from =~ s#^/##;
1127 my $gs = $self->other_gs($new_url, $url,
1128 $branch_from, $r, $self->{ref_id});
1129 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1131 my ($base, $head);
1132 if (!defined $r0 || !defined $parent) {
1133 ($base, $head) = parse_revision_argument(0, $r);
1134 } else {
1135 if ($r0 < $r) {
1136 $gs->ra->get_log([$gs->path], $r0 + 1, $r, 1,
1137 0, 1, sub { $base = $_[1] - 1 });
1140 if (defined $base && $base <= $r) {
1141 $gs->fetch($base, $r);
1143 ($r0, $parent) = $gs->find_rev_before($r, 1);
1145 if (defined $r0 && defined $parent) {
1146 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
1147 unless $::_q > 1;
1148 my $ed;
1149 if ($self->ra->can_do_switch) {
1150 $self->assert_index_clean($parent);
1151 print STDERR "Following parent with do_switch\n"
1152 unless $::_q > 1;
1153 # do_switch works with svn/trunk >= r22312, but that
1154 # is not included with SVN 1.4.3 (the latest version
1155 # at the moment), so we can't rely on it
1156 $self->{last_rev} = $r0;
1157 $self->{last_commit} = $parent;
1158 $ed = Git::SVN::Fetcher->new($self, $gs->path);
1159 $gs->ra->gs_do_switch($r0, $rev, $gs,
1160 $self->full_url, $ed)
1161 or die "SVN connection failed somewhere...\n";
1162 } elsif ($self->ra->trees_match($new_url, $r0,
1163 $self->full_url, $rev)) {
1164 print STDERR "Trees match:\n",
1165 " $new_url\@$r0\n",
1166 " ${\$self->full_url}\@$rev\n",
1167 "Following parent with no changes\n"
1168 unless $::_q > 1;
1169 $self->tmp_index_do(sub {
1170 command_noisy('read-tree', $parent);
1172 $self->{last_commit} = $parent;
1173 } else {
1174 print STDERR "Following parent with do_update\n"
1175 unless $::_q > 1;
1176 $ed = Git::SVN::Fetcher->new($self);
1177 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1178 or die "SVN connection failed somewhere...\n";
1180 print STDERR "Successfully followed parent\n" unless $::_q > 1;
1181 return $self->make_log_entry($rev, [$parent], $ed);
1183 return undef;
1186 sub do_fetch {
1187 my ($self, $paths, $rev) = @_;
1188 my $ed;
1189 my ($last_rev, @parents);
1190 if (my $lc = $self->last_commit) {
1191 # we can have a branch that was deleted, then re-added
1192 # under the same name but copied from another path, in
1193 # which case we'll have multiple parents (we don't
1194 # want to break the original ref, nor lose copypath info):
1195 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1196 push @{$log_entry->{parents}}, $lc;
1197 return $log_entry;
1199 $ed = Git::SVN::Fetcher->new($self);
1200 $last_rev = $self->{last_rev};
1201 $ed->{c} = $lc;
1202 @parents = ($lc);
1203 } else {
1204 $last_rev = $rev;
1205 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1206 return $log_entry;
1208 $ed = Git::SVN::Fetcher->new($self);
1210 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1211 die "SVN connection failed somewhere...\n";
1213 $self->make_log_entry($rev, \@parents, $ed);
1216 sub mkemptydirs {
1217 my ($self, $r) = @_;
1219 sub scan {
1220 my ($r, $empty_dirs, $line) = @_;
1221 if (defined $r && $line =~ /^r(\d+)$/) {
1222 return 0 if $1 > $r;
1223 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
1224 $empty_dirs->{$1} = 1;
1225 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
1226 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
1227 delete @$empty_dirs{@d};
1229 1; # continue
1232 my %empty_dirs = ();
1233 my $gz_file = "$self->{dir}/unhandled.log.gz";
1234 if (-f $gz_file) {
1235 if (!can_compress()) {
1236 warn "Compress::Zlib could not be found; ",
1237 "empty directories in $gz_file will not be read\n";
1238 } else {
1239 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
1240 die "Unable to open $gz_file: $!\n";
1241 my $line;
1242 while ($gz->gzreadline($line) > 0) {
1243 scan($r, \%empty_dirs, $line) or last;
1245 $gz->gzclose;
1249 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
1250 binmode $fh or croak "binmode: $!";
1251 while (<$fh>) {
1252 scan($r, \%empty_dirs, $_) or last;
1254 close $fh;
1257 my $strip = qr/\A\Q@{[$self->path]}\E(?:\/|$)/;
1258 foreach my $d (sort keys %empty_dirs) {
1259 $d = uri_decode($d);
1260 $d =~ s/$strip//;
1261 next unless length($d);
1262 next if -d $d;
1263 if (-e $d) {
1264 warn "$d exists but is not a directory\n";
1265 } else {
1266 print "creating empty directory: $d\n";
1267 mkpath([$d]);
1272 sub get_untracked {
1273 my ($self, $ed) = @_;
1274 my @out;
1275 my $h = $ed->{empty};
1276 foreach (sort keys %$h) {
1277 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1278 push @out, " $act: " . uri_encode($_);
1279 warn "W: $act: $_\n";
1281 foreach my $t (qw/dir_prop file_prop/) {
1282 $h = $ed->{$t} or next;
1283 foreach my $path (sort keys %$h) {
1284 my $ppath = $path eq '' ? '.' : $path;
1285 foreach my $prop (sort keys %{$h->{$path}}) {
1286 next if $SKIP_PROP{$prop};
1287 my $v = $h->{$path}->{$prop};
1288 my $t_ppath_prop = "$t: " .
1289 uri_encode($ppath) . ' ' .
1290 uri_encode($prop);
1291 if (defined $v) {
1292 push @out, " +$t_ppath_prop " .
1293 uri_encode($v);
1294 } else {
1295 push @out, " -$t_ppath_prop";
1300 foreach my $t (qw/absent_file absent_directory/) {
1301 $h = $ed->{$t} or next;
1302 foreach my $parent (sort keys %$h) {
1303 foreach my $path (sort @{$h->{$parent}}) {
1304 push @out, " $t: " .
1305 uri_encode("$parent/$path");
1306 warn "W: $t: $parent/$path ",
1307 "Insufficient permissions?\n";
1311 \@out;
1314 # parse_svn_date(DATE)
1315 # --------------------
1316 # Given a date (in UTC) from Subversion, return a string in the format
1317 # "<TZ Offset> <local date/time>" that Git will use.
1319 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
1320 # is true we'll convert it to the local timezone instead.
1321 sub parse_svn_date {
1322 my $date = shift || return '+0000 1970-01-01 00:00:00';
1323 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1324 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1325 croak "Unable to parse date: $date\n";
1326 my $parsed_date; # Set next.
1328 if ($Git::SVN::_localtime) {
1329 # Translate the Subversion datetime to an epoch time.
1330 # Begin by switching ourselves to $date's timezone, UTC.
1331 my $old_env_TZ = $ENV{TZ};
1332 $ENV{TZ} = 'UTC';
1334 my $epoch_in_UTC =
1335 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
1337 # Determine our local timezone (including DST) at the
1338 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
1339 # value of TZ, if any, at the time we were run.
1340 if (defined $Git::SVN::Log::TZ) {
1341 $ENV{TZ} = $Git::SVN::Log::TZ;
1342 } else {
1343 delete $ENV{TZ};
1346 my $our_TZ = get_tz_offset();
1348 # This converts $epoch_in_UTC into our local timezone.
1349 my ($sec, $min, $hour, $mday, $mon, $year,
1350 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
1352 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
1353 $our_TZ, $year + 1900, $mon + 1,
1354 $mday, $hour, $min, $sec);
1356 # Reset us to the timezone in effect when we entered
1357 # this routine.
1358 if (defined $old_env_TZ) {
1359 $ENV{TZ} = $old_env_TZ;
1360 } else {
1361 delete $ENV{TZ};
1363 } else {
1364 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
1367 return $parsed_date;
1370 sub other_gs {
1371 my ($self, $new_url, $url,
1372 $branch_from, $r, $old_ref_id) = @_;
1373 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
1374 unless ($gs) {
1375 my $ref_id = $old_ref_id;
1376 $ref_id =~ s/\@\d+-*$//;
1377 $ref_id .= "\@$r";
1378 # just grow a tail if we're not unique enough :x
1379 $ref_id .= '-' while find_ref($ref_id);
1380 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
1381 if ($u =~ s#^\Q$url\E(/|$)##) {
1382 $p = $u;
1383 $u = $url;
1384 $repo_id = $self->{repo_id};
1386 while (1) {
1387 # It is possible to tag two different subdirectories at
1388 # the same revision. If the url for an existing ref
1389 # does not match, we must either find a ref with a
1390 # matching url or create a new ref by growing a tail.
1391 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
1392 my (undef, $max_commit) = $gs->rev_map_max(1);
1393 last if (!$max_commit);
1394 my ($url) = ::cmt_metadata($max_commit);
1395 last if ($url eq $gs->metadata_url);
1396 $ref_id .= '-';
1398 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
1403 sub call_authors_prog {
1404 my ($orig_author) = @_;
1405 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
1406 my $author = `$::_authors_prog $orig_author`;
1407 if ($? != 0) {
1408 die "$::_authors_prog failed with exit code $?\n"
1410 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
1411 my ($name, $email) = ($1, $2);
1412 $email = undef if length $2 == 0;
1413 return [$name, $email];
1414 } else {
1415 die "Author: $orig_author: $::_authors_prog returned "
1416 . "invalid author format: $author\n";
1420 sub check_author {
1421 my ($author) = @_;
1422 if (!defined $author || length $author == 0) {
1423 $author = '(no author)';
1425 if (!defined $::users{$author}) {
1426 if (defined $::_authors_prog) {
1427 $::users{$author} = call_authors_prog($author);
1428 } elsif (defined $::_authors) {
1429 die "Author: $author not defined in $::_authors file\n";
1432 $author;
1435 sub find_extra_svk_parents {
1436 my ($self, $ed, $tickets, $parents) = @_;
1437 # aha! svk:merge property changed...
1438 my @tickets = split "\n", $tickets;
1439 my @known_parents;
1440 for my $ticket ( @tickets ) {
1441 my ($uuid, $path, $rev) = split /:/, $ticket;
1442 if ( $uuid eq $self->ra_uuid ) {
1443 my $repos_root = $self->url;
1444 my $branch_from = $path;
1445 $branch_from =~ s{^/}{};
1446 my $gs = $self->other_gs(add_path_to_url( $repos_root, $branch_from ),
1447 $repos_root,
1448 $branch_from,
1449 $rev,
1450 $self->{ref_id});
1451 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
1452 # wahey! we found it, but it might be
1453 # an old one (!)
1454 push @known_parents, [ $rev, $commit ];
1458 # Ordering matters; highest-numbered commit merge tickets
1459 # first, as they may account for later merge ticket additions
1460 # or changes.
1461 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
1462 for my $parent ( @known_parents ) {
1463 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
1464 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
1465 my $new;
1466 while ( <$msg_fh> ) {
1467 $new=1;last;
1469 command_close_pipe($msg_fh, $ctx);
1470 if ( $new ) {
1471 print STDERR
1472 "Found merge parent (svk:merge ticket): $parent\n";
1473 push @$parents, $parent;
1478 sub lookup_svn_merge {
1479 my $uuid = shift;
1480 my $url = shift;
1481 my $merge = shift;
1483 my ($source, $revs) = split ":", $merge;
1484 my $path = $source;
1485 $path =~ s{^/}{};
1486 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
1487 if ( !$gs ) {
1488 warn "Couldn't find revmap for $url$source\n";
1489 return;
1491 my @ranges = split ",", $revs;
1492 my ($tip, $tip_commit);
1493 my @merged_commit_ranges;
1494 # find the tip
1495 for my $range ( @ranges ) {
1496 my ($bottom, $top) = split "-", $range;
1497 $top ||= $bottom;
1498 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
1499 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
1501 unless ($top_commit and $bottom_commit) {
1502 warn "W:unknown path/rev in svn:mergeinfo "
1503 ."dirprop: $source:$range\n";
1504 next;
1507 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
1508 push @merged_commit_ranges,
1509 "$bottom_commit^..$top_commit";
1510 } else {
1511 push @merged_commit_ranges, "$top_commit";
1514 if ( !defined $tip or $top > $tip ) {
1515 $tip = $top;
1516 $tip_commit = $top_commit;
1519 return ($tip_commit, @merged_commit_ranges);
1522 sub _rev_list {
1523 my ($msg_fh, $ctx) = command_output_pipe(
1524 "rev-list", @_,
1526 my @rv;
1527 while ( <$msg_fh> ) {
1528 chomp;
1529 push @rv, $_;
1531 command_close_pipe($msg_fh, $ctx);
1532 @rv;
1535 sub check_cherry_pick {
1536 my $base = shift;
1537 my $tip = shift;
1538 my $parents = shift;
1539 my @ranges = @_;
1540 my %commits = map { $_ => 1 }
1541 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
1542 for my $range ( @ranges ) {
1543 delete @commits{_rev_list($range, "--")};
1545 for my $commit (keys %commits) {
1546 if (has_no_changes($commit)) {
1547 delete $commits{$commit};
1550 return (keys %commits);
1553 sub has_no_changes {
1554 my $commit = shift;
1556 my @revs = split / /, command_oneline(
1557 qw(rev-list --parents -1 -m), $commit);
1559 # Commits with no parents, e.g. the start of a partial branch,
1560 # have changes by definition.
1561 return 1 if (@revs < 2);
1563 # Commits with multiple parents, e.g a merge, have no changes
1564 # by definition.
1565 return 0 if (@revs > 2);
1567 return (command_oneline("rev-parse", "$commit^{tree}") eq
1568 command_oneline("rev-parse", "$commit~1^{tree}"));
1571 sub tie_for_persistent_memoization {
1572 my $hash = shift;
1573 my $path = shift;
1575 if ($can_use_yaml) {
1576 tie %$hash => 'Git::SVN::Memoize::YAML', "$path.yaml";
1577 } else {
1578 tie %$hash => 'Memoize::Storable', "$path.db", 'nstore';
1582 # The GIT_DIR environment variable is not always set until after the command
1583 # line arguments are processed, so we can't memoize in a BEGIN block.
1585 my $memoized = 0;
1587 sub memoize_svn_mergeinfo_functions {
1588 return if $memoized;
1589 $memoized = 1;
1591 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1592 mkpath([$cache_path]) unless -d $cache_path;
1594 my %lookup_svn_merge_cache;
1595 my %check_cherry_pick_cache;
1596 my %has_no_changes_cache;
1598 tie_for_persistent_memoization(\%lookup_svn_merge_cache,
1599 "$cache_path/lookup_svn_merge");
1600 memoize 'lookup_svn_merge',
1601 SCALAR_CACHE => 'FAULT',
1602 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
1605 tie_for_persistent_memoization(\%check_cherry_pick_cache,
1606 "$cache_path/check_cherry_pick");
1607 memoize 'check_cherry_pick',
1608 SCALAR_CACHE => 'FAULT',
1609 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
1612 tie_for_persistent_memoization(\%has_no_changes_cache,
1613 "$cache_path/has_no_changes");
1614 memoize 'has_no_changes',
1615 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
1616 LIST_CACHE => 'FAULT',
1620 sub unmemoize_svn_mergeinfo_functions {
1621 return if not $memoized;
1622 $memoized = 0;
1624 Memoize::unmemoize 'lookup_svn_merge';
1625 Memoize::unmemoize 'check_cherry_pick';
1626 Memoize::unmemoize 'has_no_changes';
1629 sub clear_memoized_mergeinfo_caches {
1630 die "Only call this method in non-memoized context" if ($memoized);
1632 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1633 return unless -d $cache_path;
1635 for my $cache_file (("$cache_path/lookup_svn_merge",
1636 "$cache_path/check_cherry_pick",
1637 "$cache_path/has_no_changes")) {
1638 for my $suffix (qw(yaml db)) {
1639 my $file = "$cache_file.$suffix";
1640 next unless -e $file;
1641 unlink($file) or die "unlink($file) failed: $!\n";
1647 Memoize::memoize 'Git::SVN::repos_root';
1650 END {
1651 # Force cache writeout explicitly instead of waiting for
1652 # global destruction to avoid segfault in Storable:
1653 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
1654 unmemoize_svn_mergeinfo_functions();
1657 sub parents_exclude {
1658 my $parents = shift;
1659 my @commits = @_;
1660 return unless @commits;
1662 my @excluded;
1663 my $excluded;
1664 do {
1665 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
1666 $excluded = command_oneline(@cmd);
1667 if ( $excluded ) {
1668 my @new;
1669 my $found;
1670 for my $commit ( @commits ) {
1671 if ( $commit eq $excluded ) {
1672 push @excluded, $commit;
1673 $found++;
1675 else {
1676 push @new, $commit;
1679 die "saw commit '$excluded' in rev-list output, "
1680 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
1681 unless $found;
1682 @commits = @new;
1685 while ($excluded and @commits);
1687 return @excluded;
1691 # note: this function should only be called if the various dirprops
1692 # have actually changed
1693 sub find_extra_svn_parents {
1694 my ($self, $ed, $mergeinfo, $parents) = @_;
1695 # aha! svk:merge property changed...
1697 memoize_svn_mergeinfo_functions();
1699 # We first search for merged tips which are not in our
1700 # history. Then, we figure out which git revisions are in
1701 # that tip, but not this revision. If all of those revisions
1702 # are now marked as merge, we can add the tip as a parent.
1703 my @merges = split "\n", $mergeinfo;
1704 my @merge_tips;
1705 my $url = $self->url;
1706 my $uuid = $self->ra_uuid;
1707 my @all_ranges;
1708 for my $merge ( @merges ) {
1709 my ($tip_commit, @ranges) =
1710 lookup_svn_merge( $uuid, $url, $merge );
1711 unless (!$tip_commit or
1712 grep { $_ eq $tip_commit } @$parents ) {
1713 push @merge_tips, $tip_commit;
1714 push @all_ranges, @ranges;
1715 } else {
1716 push @merge_tips, undef;
1720 my %excluded = map { $_ => 1 }
1721 parents_exclude($parents, grep { defined } @merge_tips);
1723 # check merge tips for new parents
1724 my @new_parents;
1725 for my $merge_tip ( @merge_tips ) {
1726 my $spec = shift @merges;
1727 next unless $merge_tip and $excluded{$merge_tip};
1729 # check out 'new' tips
1730 my $merge_base;
1731 eval {
1732 $merge_base = command_oneline(
1733 "merge-base",
1734 @$parents, $merge_tip,
1737 if ($@) {
1738 die "An error occurred during merge-base"
1739 unless $@->isa("Git::Error::Command");
1741 warn "W: Cannot find common ancestor between ".
1742 "@$parents and $merge_tip. Ignoring merge info.\n";
1743 next;
1746 # double check that there are no missing non-merge commits
1747 my (@incomplete) = check_cherry_pick(
1748 $merge_base, $merge_tip,
1749 $parents,
1750 @all_ranges,
1753 if ( @incomplete ) {
1754 warn "W:svn cherry-pick ignored ($spec) - missing "
1755 .@incomplete." commit(s) (eg $incomplete[0])\n";
1756 } else {
1757 warn
1758 "Found merge parent (svn:mergeinfo prop): ",
1759 $merge_tip, "\n";
1760 push @new_parents, $merge_tip;
1764 # cater for merges which merge commits from multiple branches
1765 if ( @new_parents > 1 ) {
1766 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
1767 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
1768 next if $i == $j;
1769 next unless $new_parents[$i];
1770 next unless $new_parents[$j];
1771 my $revs = command_oneline(
1772 "rev-list", "-1",
1773 "$new_parents[$i]..$new_parents[$j]",
1775 if ( !$revs ) {
1776 undef($new_parents[$j]);
1781 push @$parents, grep { defined } @new_parents;
1784 sub make_log_entry {
1785 my ($self, $rev, $parents, $ed) = @_;
1786 my $untracked = $self->get_untracked($ed);
1788 my @parents = @$parents;
1789 my $ps = $ed->{path_strip} || "";
1790 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
1791 my $props = $ed->{dir_prop}{$path};
1792 if ( $props->{"svk:merge"} ) {
1793 $self->find_extra_svk_parents
1794 ($ed, $props->{"svk:merge"}, \@parents);
1796 if ( $props->{"svn:mergeinfo"} ) {
1797 $self->find_extra_svn_parents
1798 ($ed,
1799 $props->{"svn:mergeinfo"},
1800 \@parents);
1804 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1805 print $un "r$rev\n" or croak $!;
1806 print $un $_, "\n" foreach @$untracked;
1807 my %log_entry = ( parents => \@parents, revision => $rev,
1808 log => '');
1810 my $headrev;
1811 my $logged = delete $self->{logged_rev_props};
1812 if (!$logged || $self->{-want_revprops}) {
1813 my $rp = $self->ra->rev_proplist($rev);
1814 foreach (sort keys %$rp) {
1815 my $v = $rp->{$_};
1816 if (/^svn:(author|date|log)$/) {
1817 $log_entry{$1} = $v;
1818 } elsif ($_ eq 'svm:headrev') {
1819 $headrev = $v;
1820 } else {
1821 print $un " rev_prop: ", uri_encode($_), ' ',
1822 uri_encode($v), "\n";
1825 } else {
1826 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1828 close $un or croak $!;
1830 $log_entry{date} = parse_svn_date($log_entry{date});
1831 $log_entry{log} .= "\n";
1832 my $author = $log_entry{author} = check_author($log_entry{author});
1833 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1834 : ($author, undef);
1836 my ($commit_name, $commit_email) = ($name, $email);
1837 if ($_use_log_author) {
1838 my $name_field;
1839 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
1840 $name_field = $1;
1841 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
1842 $name_field = $1;
1844 if (!defined $name_field) {
1845 if (!defined $email) {
1846 $email = $name;
1848 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
1849 ($name, $email) = ($1, $2);
1850 } elsif ($name_field =~ /(.*)@/) {
1851 ($name, $email) = ($1, $name_field);
1852 } else {
1853 ($name, $email) = ($name_field, $name_field);
1856 if (defined $headrev && $self->use_svm_props) {
1857 if ($self->rewrite_root) {
1858 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1859 "options set!\n";
1861 if ($self->rewrite_uuid) {
1862 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
1863 "options set!\n";
1865 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
1866 # we don't want "SVM: initializing mirror for junk" ...
1867 return undef if $r == 0;
1868 my $svm = $self->svm;
1869 if ($uuid ne $svm->{uuid}) {
1870 die "UUID mismatch on SVM path:\n",
1871 "expected: $svm->{uuid}\n",
1872 " got: $uuid\n";
1874 my $full_url = $self->full_url;
1875 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1876 die "Failed to replace '$svm->{replace}' with ",
1877 "'$svm->{source}' in $full_url\n";
1878 # throw away username for storing in records
1879 remove_username($full_url);
1880 $log_entry{metadata} = "$full_url\@$r $uuid";
1881 $log_entry{svm_revision} = $r;
1882 $email ||= "$author\@$uuid";
1883 $commit_email ||= "$author\@$uuid";
1884 } elsif ($self->use_svnsync_props) {
1885 my $full_url = canonicalize_url(
1886 add_path_to_url( $self->svnsync->{url}, $self->path )
1888 remove_username($full_url);
1889 my $uuid = $self->svnsync->{uuid};
1890 $log_entry{metadata} = "$full_url\@$rev $uuid";
1891 $email ||= "$author\@$uuid";
1892 $commit_email ||= "$author\@$uuid";
1893 } else {
1894 my $url = $self->metadata_url;
1895 remove_username($url);
1896 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
1897 $log_entry{metadata} = "$url\@$rev " . $uuid;
1898 $email ||= "$author\@" . $uuid;
1899 $commit_email ||= "$author\@" . $uuid;
1901 $log_entry{name} = $name;
1902 $log_entry{email} = $email;
1903 $log_entry{commit_name} = $commit_name;
1904 $log_entry{commit_email} = $commit_email;
1905 \%log_entry;
1908 sub fetch {
1909 my ($self, $min_rev, $max_rev, @parents) = @_;
1910 my ($last_rev, $last_commit) = $self->last_rev_commit;
1911 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1912 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1915 sub set_tree_cb {
1916 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1917 $self->{inject_parents} = { $rev => $tree };
1918 $self->fetch(undef, undef);
1921 sub set_tree {
1922 my ($self, $tree) = (shift, shift);
1923 my $log_entry = ::get_commit_entry($tree);
1924 unless ($self->{last_rev}) {
1925 fatal("Must have an existing revision to commit");
1927 my %ed_opts = ( r => $self->{last_rev},
1928 log => $log_entry->{log},
1929 ra => $self->ra,
1930 tree_a => $self->{last_commit},
1931 tree_b => $tree,
1932 editor_cb => sub {
1933 $self->set_tree_cb($log_entry, $tree, @_) },
1934 svn_path => $self->path );
1935 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1936 print "No changes\nr$self->{last_rev} = $tree\n";
1940 sub rebuild_from_rev_db {
1941 my ($self, $path) = @_;
1942 my $r = -1;
1943 open my $fh, '<', $path or croak "open: $!";
1944 binmode $fh or croak "binmode: $!";
1945 while (<$fh>) {
1946 length($_) == 41 or croak "inconsistent size in ($_) != 41";
1947 chomp($_);
1948 ++$r;
1949 next if $_ eq ('0' x 40);
1950 $self->rev_map_set($r, $_);
1951 print "r$r = $_\n";
1953 close $fh or croak "close: $!";
1954 unlink $path or croak "unlink: $!";
1957 sub rebuild {
1958 my ($self) = @_;
1959 my $map_path = $self->map_path;
1960 my $partial = (-e $map_path && ! -z $map_path);
1961 return unless ::verify_ref($self->refname.'^0');
1962 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
1963 my $rev_db = $self->rev_db_path;
1964 $self->rebuild_from_rev_db($rev_db);
1965 if ($self->use_svm_props) {
1966 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
1967 $self->rebuild_from_rev_db($svm_rev_db);
1969 $self->unlink_rev_db_symlink;
1970 return;
1972 print "Rebuilding $map_path ...\n" if (!$partial);
1973 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
1974 (undef, undef));
1975 my ($log, $ctx) =
1976 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
1977 ($head ? "$head.." : "") . $self->refname,
1978 '--');
1979 my $metadata_url = $self->metadata_url;
1980 remove_username($metadata_url);
1981 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
1982 my $c;
1983 while (<$log>) {
1984 if ( m{^commit ($::sha1)$} ) {
1985 $c = $1;
1986 next;
1988 next unless s{^\s*(git-svn-id:)}{$1};
1989 my ($url, $rev, $uuid) = ::extract_metadata($_);
1990 remove_username($url);
1992 # ignore merges (from set-tree)
1993 next if (!defined $rev || !$uuid);
1995 # if we merged or otherwise started elsewhere, this is
1996 # how we break out of it
1997 if (($uuid ne $svn_uuid) ||
1998 ($metadata_url && $url && ($url ne $metadata_url))) {
1999 next;
2001 if ($partial && $head) {
2002 print "Partial-rebuilding $map_path ...\n";
2003 print "Currently at $base_rev = $head\n";
2004 $head = undef;
2007 $self->rev_map_set($rev, $c);
2008 print "r$rev = $c\n";
2010 command_close_pipe($log, $ctx);
2011 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2012 my $rev_db_path = $self->rev_db_path;
2013 if (-f $self->rev_db_path) {
2014 unlink $self->rev_db_path or croak "unlink: $!";
2016 $self->unlink_rev_db_symlink;
2019 # rev_map:
2020 # Tie::File seems to be prone to offset errors if revisions get sparse,
2021 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2022 # one of my favorite modules is out :< Next up would be one of the DBM
2023 # modules, but I'm not sure which is most portable...
2025 # This is the replacement for the rev_db format, which was too big
2026 # and inefficient for large repositories with a lot of sparse history
2027 # (mainly tags)
2029 # The format is this:
2030 # - 24 bytes for every record,
2031 # * 4 bytes for the integer representing an SVN revision number
2032 # * 20 bytes representing the sha1 of a git commit
2033 # - No empty padding records like the old format
2034 # (except the last record, which can be overwritten)
2035 # - new records are written append-only since SVN revision numbers
2036 # increase monotonically
2037 # - lookups on SVN revision number are done via a binary search
2038 # - Piping the file to xxd -c24 is a good way of dumping it for
2039 # viewing or editing (piped back through xxd -r), should the need
2040 # ever arise.
2041 # - The last record can be padding revision with an all-zero sha1
2042 # This is used to optimize fetch performance when using multiple
2043 # "fetch" directives in .git/config
2045 # These files are disposable unless noMetadata or useSvmProps is set
2047 sub _rev_map_set {
2048 my ($fh, $rev, $commit) = @_;
2050 binmode $fh or croak "binmode: $!";
2051 my $size = (stat($fh))[7];
2052 ($size % 24) == 0 or croak "inconsistent size: $size";
2054 my $wr_offset = 0;
2055 if ($size > 0) {
2056 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2057 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2058 $read == 24 or croak "read only $read bytes (!= 24)";
2059 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2060 if ($last_commit eq ('0' x40)) {
2061 if ($size >= 48) {
2062 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2063 $read = sysread($fh, $buf, 24) or
2064 croak "read: $!";
2065 $read == 24 or
2066 croak "read only $read bytes (!= 24)";
2067 ($last_rev, $last_commit) =
2068 unpack(rev_map_fmt, $buf);
2069 if ($last_commit eq ('0' x40)) {
2070 croak "inconsistent .rev_map\n";
2073 if ($last_rev >= $rev) {
2074 croak "last_rev is higher!: $last_rev >= $rev";
2076 $wr_offset = -24;
2079 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2080 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2081 croak "write: $!";
2084 sub _rev_map_reset {
2085 my ($fh, $rev, $commit) = @_;
2086 my $c = _rev_map_get($fh, $rev);
2087 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
2088 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
2089 truncate $fh, $offset or croak "truncate: $!";
2092 sub mkfile {
2093 my ($path) = @_;
2094 unless (-e $path) {
2095 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2096 mkpath([$dir]) unless -d $dir;
2097 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2098 close $fh or die "Couldn't close (create) $path: $!\n";
2102 sub rev_map_set {
2103 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2104 defined $commit or die "missing arg3\n";
2105 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2106 my $db = $self->map_path($uuid);
2107 my $db_lock = "$db.lock";
2108 my $sigmask;
2109 $update_ref ||= 0;
2110 if ($update_ref) {
2111 $sigmask = POSIX::SigSet->new();
2112 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
2113 SIGALRM, SIGUSR1, SIGUSR2);
2114 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
2115 croak "Can't block signals: $!";
2117 mkfile($db);
2119 $LOCKFILES{$db_lock} = 1;
2120 my $sync;
2121 # both of these options make our .rev_db file very, very important
2122 # and we can't afford to lose it because rebuild() won't work
2123 if ($self->use_svm_props || $self->no_metadata) {
2124 $sync = 1;
2125 copy($db, $db_lock) or die "rev_map_set(@_): ",
2126 "Failed to copy: ",
2127 "$db => $db_lock ($!)\n";
2128 } else {
2129 rename $db, $db_lock or die "rev_map_set(@_): ",
2130 "Failed to rename: ",
2131 "$db => $db_lock ($!)\n";
2134 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2135 or croak "Couldn't open $db_lock: $!\n";
2136 if ($update_ref eq 'reset') {
2137 clear_memoized_mergeinfo_caches();
2138 _rev_map_reset($fh, $rev, $commit);
2139 } else {
2140 _rev_map_set($fh, $rev, $commit);
2143 if ($sync) {
2144 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2145 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2147 close $fh or croak $!;
2148 if ($update_ref) {
2149 $_head = $self;
2150 my $note = "";
2151 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
2152 command_noisy('update-ref', '-m', "r$rev$note",
2153 $self->refname, $commit);
2155 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2156 "$db_lock => $db ($!)\n";
2157 delete $LOCKFILES{$db_lock};
2158 if ($update_ref) {
2159 sigprocmask(SIG_SETMASK, $sigmask) or
2160 croak "Can't restore signal mask: $!";
2164 # If want_commit, this will return an array of (rev, commit) where
2165 # commit _must_ be a valid commit in the archive.
2166 # Otherwise, it'll return the max revision (whether or not the
2167 # commit is valid or just a 0x40 placeholder).
2168 sub rev_map_max {
2169 my ($self, $want_commit) = @_;
2170 $self->rebuild;
2171 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2172 $want_commit ? ($r, $c) : $r;
2175 sub rev_map_max_norebuild {
2176 my ($self, $want_commit) = @_;
2177 my $map_path = $self->map_path;
2178 stat $map_path or return $want_commit ? (0, undef) : 0;
2179 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2180 binmode $fh or croak "binmode: $!";
2181 my $size = (stat($fh))[7];
2182 ($size % 24) == 0 or croak "inconsistent size: $size";
2184 if ($size == 0) {
2185 close $fh or croak "close: $!";
2186 return $want_commit ? (0, undef) : 0;
2189 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2190 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2191 my ($r, $c) = unpack(rev_map_fmt, $buf);
2192 if ($want_commit && $c eq ('0' x40)) {
2193 if ($size < 48) {
2194 return $want_commit ? (0, undef) : 0;
2196 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2197 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2198 ($r, $c) = unpack(rev_map_fmt, $buf);
2199 if ($c eq ('0'x40)) {
2200 croak "Penultimate record is all-zeroes in $map_path";
2203 close $fh or croak "close: $!";
2204 $want_commit ? ($r, $c) : $r;
2207 sub rev_map_get {
2208 my ($self, $rev, $uuid) = @_;
2209 my $map_path = $self->map_path($uuid);
2210 return undef unless -e $map_path;
2212 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2213 my $c = _rev_map_get($fh, $rev);
2214 close($fh) or croak "close: $!";
2218 sub _rev_map_get {
2219 my ($fh, $rev) = @_;
2221 binmode $fh or croak "binmode: $!";
2222 my $size = (stat($fh))[7];
2223 ($size % 24) == 0 or croak "inconsistent size: $size";
2225 if ($size == 0) {
2226 return undef;
2229 my ($l, $u) = (0, $size - 24);
2230 my ($r, $c, $buf);
2232 while ($l <= $u) {
2233 my $i = int(($l/24 + $u/24) / 2) * 24;
2234 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2235 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2236 my ($r, $c) = unpack(rev_map_fmt, $buf);
2238 if ($r < $rev) {
2239 $l = $i + 24;
2240 } elsif ($r > $rev) {
2241 $u = $i - 24;
2242 } else { # $r == $rev
2243 return $c eq ('0' x 40) ? undef : $c;
2246 undef;
2249 # Finds the first svn revision that exists on (if $eq_ok is true) or
2250 # before $rev for the current branch. It will not search any lower
2251 # than $min_rev. Returns the git commit hash and svn revision number
2252 # if found, else (undef, undef).
2253 sub find_rev_before {
2254 my ($self, $rev, $eq_ok, $min_rev) = @_;
2255 --$rev unless $eq_ok;
2256 $min_rev ||= 1;
2257 my $max_rev = $self->rev_map_max;
2258 $rev = $max_rev if ($rev > $max_rev);
2259 while ($rev >= $min_rev) {
2260 if (my $c = $self->rev_map_get($rev)) {
2261 return ($rev, $c);
2263 --$rev;
2265 return (undef, undef);
2268 # Finds the first svn revision that exists on (if $eq_ok is true) or
2269 # after $rev for the current branch. It will not search any higher
2270 # than $max_rev. Returns the git commit hash and svn revision number
2271 # if found, else (undef, undef).
2272 sub find_rev_after {
2273 my ($self, $rev, $eq_ok, $max_rev) = @_;
2274 ++$rev unless $eq_ok;
2275 $max_rev ||= $self->rev_map_max;
2276 while ($rev <= $max_rev) {
2277 if (my $c = $self->rev_map_get($rev)) {
2278 return ($rev, $c);
2280 ++$rev;
2282 return (undef, undef);
2285 sub _new {
2286 my ($class, $repo_id, $ref_id, $path) = @_;
2287 unless (defined $repo_id && length $repo_id) {
2288 $repo_id = $default_repo_id;
2290 unless (defined $ref_id && length $ref_id) {
2291 # Access the prefix option from the git-svn main program if it's loaded.
2292 my $prefix = defined &::opt_prefix ? ::opt_prefix() : "";
2293 $_[2] = $ref_id =
2294 "refs/remotes/$prefix$default_ref_id";
2296 $_[1] = $repo_id;
2297 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2299 # Older repos imported by us used $GIT_DIR/svn/foo instead of
2300 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
2301 if ($ref_id =~ m{^refs/remotes/(.*)}) {
2302 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
2303 if (-d $old_dir && ! -d $dir) {
2304 $dir = $old_dir;
2308 $_[3] = $path = '' unless (defined $path);
2309 mkpath([$dir]);
2310 my $obj = bless {
2311 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2312 config => "$ENV{GIT_DIR}/svn/config",
2313 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2315 # Ensure it gets canonicalized
2316 $obj->path($path);
2318 return $obj;
2321 sub path {
2322 my $self = shift;
2324 if (@_) {
2325 my $path = shift;
2326 $self->{_path} = canonicalize_path($path);
2327 return;
2330 return $self->{_path};
2333 sub url {
2334 my $self = shift;
2336 if (@_) {
2337 my $url = shift;
2338 $self->{url} = canonicalize_url($url);
2339 return;
2342 return $self->{url};
2345 # for read-only access of old .rev_db formats
2346 sub unlink_rev_db_symlink {
2347 my ($self) = @_;
2348 my $link = $self->rev_db_path;
2349 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2350 if (-l $link) {
2351 unlink $link or croak "unlink: $link failed!";
2355 sub rev_db_path {
2356 my ($self, $uuid) = @_;
2357 my $db_path = $self->map_path($uuid);
2358 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2359 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2360 $db_path;
2363 # the new replacement for .rev_db
2364 sub map_path {
2365 my ($self, $uuid) = @_;
2366 $uuid ||= $self->ra_uuid;
2367 "$self->{map_root}.$uuid";
2370 sub uri_encode {
2371 my ($f) = @_;
2372 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#sprintf("%%%02X",ord($1))#eg;
2376 sub uri_decode {
2377 my ($f) = @_;
2378 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
2382 sub remove_username {
2383 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};