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/;
11 use File::Path qw/mkpath/;
13 use Memoize; # core since 5.8.0, Jul 2002
14 use POSIX qw(:signal_h);
25 use Git::SVN::Utils qw(
35 our $_follow_parent = 1;
36 our $_minimize_url = 'unset';
37 our $default_repo_id = 'svn';
38 our $default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
40 my ($_gc_nr, $_gc_period);
42 # properties that we do not log:
45 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
46 svn:special svn:executable
47 svn:entry:committed-rev
50 svn:entry:committed-date/;
52 # some options are read globally, but can be overridden locally
53 # per [svn-remote "..."] section. Command-line options will *NOT*
54 # override options set in an [svn-remote "..."] section
56 for my $option (qw/follow_parent no_metadata use_svm_props
60 my $prop = "-$option";
63 return $self->{$prop} if exists $self->{$prop};
64 my $k = "svn-remote.$self->{repo_id}.$key";
65 eval { command_oneline(qw/config --get/, $k) };
67 $self->{$prop} = ${"Git::SVN::_$option"};
69 my $v = command_oneline(qw/config --bool/,$k);
70 $self->{$prop} = $v eq 'false' ? 0 : 1;
72 return $self->{$prop};
78 my (%LOCKFILES, %INDEX_FILES);
80 unlink keys %LOCKFILES if %LOCKFILES;
81 unlink keys %INDEX_FILES if %INDEX_FILES;
84 sub resolve_local_globs {
85 my ($url, $fetch, $glob_spec) = @_;
86 return unless defined $glob_spec;
87 my $ref = $glob_spec->{ref};
88 my $path = $glob_spec->{path};
89 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
90 next unless m#^$ref->{regex}$#;
92 my $pathname = desanitize_refname($path->full_path($p));
93 my $refname = desanitize_refname($ref->full_path($p));
94 if (my $existing = $fetch->{$pathname}) {
95 if ($existing ne $refname) {
96 die "Refspec conflict:\n",
97 "existing: $existing\n",
98 " globbed: $refname\n";
100 my $u = (::cmt_metadata("$refname"))[0] or die
101 "$refname: no associated commit metadata\n";
102 $u =~ s!^\Q$url\E(/|$)!! or die
103 "$refname: '$url' not found in '$u'\n";
104 if ($pathname ne $u) {
105 warn "W: Refspec glob conflict ",
106 "(ref: $refname):\n",
107 "expected path: $pathname\n",
109 "Continuing ahead with $u\n";
113 $fetch->{$pathname} = $refname;
118 sub parse_revision_argument {
119 my ($base, $head) = @_;
120 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
121 return ($base, $head);
123 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
124 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
125 return ($head, $head) if ($::_revision eq 'HEAD');
126 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
127 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
128 die "revision argument: $::_revision not understood by git-svn\n";
132 my ($repo_id, $remotes) = @_;
136 $repo_id = $gs->{repo_id};
138 $remotes ||= read_all_remotes();
139 my $remote = $remotes->{$repo_id} or
140 die "[svn-remote \"$repo_id\"] unknown\n";
141 my $fetch = $remote->{fetch};
142 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
144 my $ra = Git::SVN::Ra->new($url);
145 my $uuid = $ra->get_uuid;
146 my $head = $ra->get_latest_revnum;
148 # ignore errors, $head revision may not even exist anymore
149 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
150 warn "W: $@\n" if $@;
152 my $base = defined $fetch ? $head : 0;
154 # read the max revs for wildcard expansion (branches/*, tags/*)
155 foreach my $t (qw/branches tags/) {
156 defined $remote->{$t} or next;
157 push @globs, @{$remote->{$t}};
159 my $max_rev = eval { tmp_config(qw/--int --get/,
160 "svn-remote.$repo_id.${t}-maxRev") };
161 if (defined $max_rev && ($max_rev < $base)) {
163 } elsif (!defined $max_rev) {
169 foreach my $p (sort keys %$fetch) {
170 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
171 my $lr = $gs->rev_map_max;
173 $base = $lr if ($lr < $base);
179 ($base, $head) = parse_revision_argument($base, $head);
180 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
183 sub read_all_remotes {
185 my $use_svm_props = eval { command_oneline(qw/config --bool
187 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
188 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
189 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
190 if (m!^(.+)\.fetch=$svn_refspec$!) {
191 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
192 die("svn-remote.$remote: remote ref '$remote_ref' "
193 . "must start with 'refs/'\n")
194 unless $remote_ref =~ m{^refs/};
195 $local_ref = uri_decode($local_ref);
196 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
197 $r->{$remote}->{svm} = {} if $use_svm_props;
198 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
199 $r->{$1}->{svm} = {};
200 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
201 $r->{$1}->{url} = canonicalize_url($2);
202 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
203 $r->{$1}->{pushurl} = canonicalize_url($2);
204 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
205 $r->{$1}->{ignore_refs_regex} = $2;
206 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
207 my ($remote, $t, $local_ref, $remote_ref) =
209 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
210 . "must start with 'refs/'\n")
211 unless $remote_ref =~ m{^refs/};
212 $local_ref = uri_decode($local_ref);
214 require Git::SVN::GlobSpec;
218 path => Git::SVN::GlobSpec->new($local_ref, 1),
219 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
220 if (length($rs->{ref}->{right}) != 0) {
221 die "The '*' glob character must be the last ",
222 "character of '$remote_ref'\n";
224 push @{ $r->{$remote}->{$t} }, $rs;
229 if (defined $r->{$_}->{svm}) {
232 my $section = "svn-remote.$_";
234 source => tmp_config('--get',
235 "$section.svm-source"),
236 replace => tmp_config('--get',
237 "$section.svm-replace"),
240 $r->{$_}->{svm} = $svm;
244 foreach my $remote (keys %$r) {
245 foreach ( grep { defined $_ }
246 map { $r->{$remote}->{$_} } qw(branches tags) ) {
247 foreach my $rs ( @$_ ) {
248 $rs->{ignore_refs_regex} =
249 $r->{$remote}->{ignore_refs_regex};
258 $_gc_nr = $_gc_period = 1000;
259 if (defined $_repack || defined $_repack_flags) {
260 warn "Repack options are obsolete; they have no effect.\n";
264 sub verify_remotes_sanity {
265 return unless -d $ENV{GIT_DIR};
267 foreach (command(qw/config -l/)) {
268 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
270 die "Remote ref refs/remote/$1 is tracked by",
271 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
272 "Please resolve this ambiguity in ",
273 "your git configuration file before ",
281 sub find_existing_remote {
282 my ($url, $remotes) = @_;
283 return undef if $no_reuse_existing;
285 foreach my $repo_id (keys %$remotes) {
286 my $u = $remotes->{$repo_id}->{url} or next;
288 $existing = $repo_id;
294 sub init_remote_config {
295 my ($self, $url, $no_write) = @_;
296 $url = canonicalize_url($url);
297 my $r = read_all_remotes();
298 my $existing = find_existing_remote($url, $r);
301 print STDERR "Using existing ",
302 "[svn-remote \"$existing\"]\n";
304 $self->{repo_id} = $existing;
305 } elsif ($_minimize_url) {
306 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
307 $existing = find_existing_remote($min_url, $r);
310 print STDERR "Using existing ",
311 "[svn-remote \"$existing\"]\n";
313 $self->{repo_id} = $existing;
315 if ($min_url ne $url) {
317 print STDERR "Using higher level of URL: ",
318 "$url => $min_url\n";
320 my $old_path = $self->path;
321 $url =~ s!^\Q$min_url\E(/|$)!!;
322 $url = join_paths($url, $old_path);
329 # verify that we aren't overwriting anything:
331 command_oneline('config', '--get',
332 "svn-remote.$self->{repo_id}.url")
334 if ($orig_url && ($orig_url ne $url)) {
335 die "svn-remote.$self->{repo_id}.url already set: ",
336 "$orig_url\nwanted to set to: $url\n";
339 my ($xrepo_id, $xpath) = find_ref($self->refname);
340 if (!$no_write && defined $xpath) {
341 die "svn-remote.$xrepo_id.fetch already set to track ",
342 "$xpath:", $self->refname, "\n";
345 command_noisy('config',
346 "svn-remote.$self->{repo_id}.url", $url);
347 my $path = $self->path;
349 $path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
351 command_noisy('config', '--add',
352 "svn-remote.$self->{repo_id}.fetch",
353 $self->path.":".$self->refname);
358 sub find_by_url { # repos_root and, path are optional
359 my ($class, $full_url, $repos_root, $path) = @_;
361 $full_url = canonicalize_url($full_url);
363 return undef unless defined $full_url;
364 remove_username($full_url);
365 remove_username($repos_root) if defined $repos_root;
366 my $remotes = read_all_remotes();
367 if (defined $full_url && defined $repos_root && !defined $path) {
369 $path =~ s#^\Q$repos_root\E(?:/|$)##;
371 foreach my $repo_id (keys %$remotes) {
372 my $u = $remotes->{$repo_id}->{url} or next;
374 next if defined $repos_root && $repos_root ne $u;
376 my $fetch = $remotes->{$repo_id}->{fetch} || {};
377 foreach my $t (qw/branches tags/) {
378 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
379 resolve_local_globs($u, $fetch, $globspec);
383 my $rwr = rewrite_root({repo_id => $repo_id});
384 my $svm = $remotes->{$repo_id}->{svm}
385 if defined $remotes->{$repo_id}->{svm};
386 unless (defined $p) {
393 } elsif (defined $svm) {
395 $prefix = $svm->{replace};
396 $prefix =~ s#^\Q$u\E(?:/|$)##;
399 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
402 # remote fetch paths are not URI escaped. Decode ours
406 foreach my $f (keys %$fetch) {
408 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
415 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
416 my $self = _new($class, $repo_id, $ref_id, $path);
418 $self->init_remote_config($url, $no_write);
425 foreach (command(qw/config -l/)) {
426 next unless m!^svn-remote\.(.+)\.fetch=
427 \s*(.*?)\s*:\s*(.+?)\s*$!x;
428 my ($repo_id, $path, $ref) = ($1, $2, $3);
429 if ($ref eq $ref_id) {
430 $path = '' if ($path =~ m#^\./?#);
431 return ($repo_id, $path);
434 (undef, undef, undef);
438 my ($class, $ref_id, $repo_id, $path) = @_;
439 if (defined $ref_id && !defined $repo_id && !defined $path) {
440 ($repo_id, $path) = find_ref($ref_id);
441 if (!defined $repo_id) {
442 die "Could not find a \"svn-remote.*.fetch\" key ",
443 "in the repository configuration matching: ",
447 my $self = _new($class, $repo_id, $ref_id, $path);
448 if (!defined $self->path || !length $self->path) {
449 my $fetch = command_oneline('config', '--get',
450 "svn-remote.$repo_id.fetch",
452 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
453 "\":$ref_id\$\" in config\n";
454 my($path) = split(/\s*:\s*/, $fetch);
458 my $path = $self->path;
463 my $url = command_oneline('config', '--get',
464 "svn-remote.$repo_id.url") or
465 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
467 $self->{pushurl} = eval { command_oneline('config', '--get',
468 "svn-remote.$repo_id.pushurl") };
474 my ($refname) = $_[0]->{ref_id} ;
476 # It cannot end with a slash /, we'll throw up on this because
477 # SVN can't have directories with a slash in their name, either:
478 if ($refname =~ m{/$}) {
479 die "ref: '$refname' ends with a trailing slash; this is ",
480 "not permitted by git or Subversion\n";
483 # It cannot have ASCII control character space, tilde ~, caret ^,
484 # colon :, question-mark ?, asterisk *, space, or open bracket [
487 # Additionally, % must be escaped because it is used for escaping
488 # and we want our escaped refname to be reversible
489 $refname =~ s{([ \%~\^:\?\*\[\t])}{sprintf('%%%02X',ord($1))}eg;
491 # no slash-separated component can begin with a dot .
493 $refname =~ s{/\.}{/%2E}g;
495 # It cannot have two consecutive dots .. anywhere
497 $refname =~ s{\.\.}{%2E%2E}g;
499 # trailing dots and .lock are not allowed
500 # .$ becomes %2E and .lock becomes %2Elock
501 $refname =~ s{\.(?=$|lock$)}{%2E};
503 # the sequence @{ is used to access the reflog
505 $refname =~ s{\@\{}{%40\{}g;
510 sub desanitize_refname {
512 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
518 return $self->{svm}->{uuid} if $self->svm;
520 unless ($self->{svm}) {
521 die "SVM UUID not cached, and reading remotely failed\n";
523 $self->{svm}->{uuid};
528 return $self->{svm} if $self->{svm};
530 # see if we have it in our config, first:
532 my $section = "svn-remote.$self->{repo_id}";
534 source => tmp_config('--get', "$section.svm-source"),
535 uuid => tmp_config('--get', "$section.svm-uuid"),
536 replace => tmp_config('--get', "$section.svm-replace"),
539 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
546 my ($self, $ra) = @_;
547 return $ra if $self->svm;
549 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
550 "(svm:source, svm:uuid) ",
551 "from the following URLs:\n" );
553 my ($self, $ra, $path, $r) = @_;
554 my $props = ($ra->get_dir($path, $r))[2];
555 my $src = $props->{'svm:source'};
556 my $uuid = $props->{'svm:uuid'};
557 return undef if (!$src || !$uuid);
561 $uuid =~ m{^[0-9a-f\-]{30,}$}i
562 or die "doesn't look right - svm:uuid is '$uuid'\n";
564 # the '!' is used to mark the repos_root!/relative/path
566 $src =~ s{/+$}{}; # no trailing slashes please
567 # username is of no interest
568 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
570 my $replace = add_path_to_url($ra->url, $path);
572 my $section = "svn-remote.$self->{repo_id}";
573 tmp_config("$section.svm-source", $src);
574 tmp_config("$section.svm-replace", $replace);
575 tmp_config("$section.svm-uuid", $uuid);
583 my $r = $ra->get_latest_revnum;
584 my $path = $self->path;
586 while (length $path) {
587 my $try = add_path_to_url($self->url, $path);
588 unless ($tried{$try}) {
589 return $ra if $self->read_svm_props($ra, $path, $r);
592 $path =~ s#/?[^/]+$##;
594 die "Path: '$path' should be ''\n" if $path ne '';
595 return $ra if $self->read_svm_props($ra, $path, $r);
596 $tried{ add_path_to_url($self->url, $path) } = 1;
598 if ($ra->{repos_root} eq $self->url) {
599 die @err, (map { " $_\n" } keys %tried), "\n";
602 # nope, make sure we're connected to the repository root:
605 $path = $ra->{svn_path};
606 $ra = Git::SVN::Ra->new($ra->{repos_root});
607 while (length $path) {
608 my $try = add_path_to_url($ra->url, $path);
609 unless ($tried{$try}) {
610 $ok = $self->read_svm_props($ra, $path, $r);
614 $path =~ s#/?[^/]+$##;
616 die "Path: '$path' should be ''\n" if $path ne '';
617 $ok ||= $self->read_svm_props($ra, $path, $r);
618 $tried{ add_path_to_url($ra->url, $path) } = 1;
620 die @err, (map { " $_\n" } keys %tried), "\n";
622 Git::SVN::Ra->new($self->url);
627 return $self->{svnsync} if $self->{svnsync};
629 if ($self->no_metadata) {
630 die "Can't have both 'noMetadata' and ",
631 "'useSvnsyncProps' options set!\n";
633 if ($self->rewrite_root) {
634 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
637 if ($self->rewrite_uuid) {
638 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
643 # see if we have it in our config, first:
645 my $section = "svn-remote.$self->{repo_id}";
647 my $url = tmp_config('--get', "$section.svnsync-url");
648 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
649 die "doesn't look right - svn:sync-from-url is '$url'\n";
651 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
652 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
653 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
655 $svnsync = { url => $url, uuid => $uuid }
657 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
658 return $self->{svnsync} = $svnsync;
661 my $err = "useSvnsyncProps set, but failed to read " .
662 "svnsync property: svn:sync-from-";
663 my $rp = $self->ra->rev_proplist(0);
665 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
666 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
667 die "doesn't look right - svn:sync-from-url is '$url'\n";
669 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
670 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
671 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
673 my $section = "svn-remote.$self->{repo_id}";
674 tmp_config('--add', "$section.svnsync-uuid", $uuid);
675 tmp_config('--add', "$section.svnsync-url", $url);
676 return $self->{svnsync} = { url => $url, uuid => $uuid };
679 # this allows us to memoize our SVN::Ra UUID locally and avoid a
680 # remote lookup (useful for 'git svn log').
683 unless ($self->{ra_uuid}) {
684 my $key = "svn-remote.$self->{repo_id}.uuid";
685 my $uuid = eval { tmp_config('--get', $key) };
686 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
687 $self->{ra_uuid} = $uuid;
689 die "ra_uuid called without URL\n" unless $self->url;
690 $self->{ra_uuid} = $self->ra->get_uuid;
691 tmp_config('--add', $key, $self->{ra_uuid});
697 sub _set_repos_root {
698 my ($self, $repos_root) = @_;
699 my $k = "svn-remote.$self->{repo_id}.reposRoot";
700 $repos_root ||= $self->ra->{repos_root};
701 tmp_config($k, $repos_root);
707 my $k = "svn-remote.$self->{repo_id}.reposRoot";
708 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
713 my $ra = Git::SVN::Ra->new($self->url);
714 $self->_set_repos_root($ra->{repos_root});
715 if ($self->use_svm_props && !$self->{svm}) {
716 if ($self->no_metadata) {
717 die "Can't have both 'noMetadata' and ",
718 "'useSvmProps' options set!\n";
719 } elsif ($self->use_svnsync_props) {
720 die "Can't have both 'useSvnsyncProps' and ",
721 "'useSvmProps' options set!\n";
723 $ra = $self->_set_svm_vars($ra);
724 $self->{-want_revprops} = 1;
729 # prop_walk(PATH, REV, SUB)
730 # -------------------------
731 # Recursively traverse PATH at revision REV and invoke SUB for each
732 # directory that contains a SVN property. SUB will be invoked as
733 # follows: &SUB(gs, path, props); where `gs' is this instance of
734 # Git::SVN, `path' the path to the directory where the properties
735 # `props' were found. The `path' will be relative to point of checkout,
736 # that is, if url://repo/trunk is the current Git branch, and that
737 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
738 # as `path' (note the trailing `/').
740 my ($self, $path, $rev, $sub) = @_;
743 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
746 # Strip the irrelevant part of the path.
747 $p =~ s#^/+\Q@{[$self->path]}\E(/|$)#/#;
748 # Ensure the path is terminated by a `/'.
751 # The properties contain all the internal SVN stuff nobody
752 # (usually) cares about.
753 my $interesting_props = 0;
754 foreach (keys %{$props}) {
755 # If it doesn't start with `svn:', it must be a
756 # user-defined property.
757 ++$interesting_props and next if $_ !~ /^svn:/;
758 # FIXME: Fragile, if SVN adds new public properties,
759 # this needs to be updated.
760 ++$interesting_props if /^svn:(?:ignore|keywords|executable
762 |externals|needs-lock)$/x;
764 &$sub($self, $p, $props) if $interesting_props;
766 foreach (sort keys %$dirent) {
767 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
768 $self->prop_walk($self->path . $p . $_, $rev, $sub);
772 sub last_rev { ($_[0]->last_rev_commit)[0] }
773 sub last_commit { ($_[0]->last_rev_commit)[1] }
775 # returns the newest SVN revision number and newest commit SHA1
776 sub last_rev_commit {
778 if (defined $self->{last_rev} && defined $self->{last_commit}) {
779 return ($self->{last_rev}, $self->{last_commit});
781 my $c = ::verify_ref($self->refname.'^0');
782 if ($c && !$self->use_svm_props && !$self->no_metadata) {
783 my $rev = (::cmt_metadata($c))[1];
785 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
789 my $map_path = $self->map_path;
790 unless (-e $map_path) {
791 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
792 return (undef, undef);
794 my ($rev, $commit) = $self->rev_map_max(1);
795 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
796 return ($rev, $commit);
799 sub get_fetch_range {
800 my ($self, $min, $max) = @_;
801 $max ||= $self->ra->get_latest_revnum;
802 $min ||= $self->rev_map_max;
808 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
809 my $config = "$ENV{GIT_DIR}/svn/.metadata";
810 if (! -f $config && -f $old_def_config) {
811 rename $old_def_config, $config or
812 die "Failed rename $old_def_config => $config: $!\n";
814 my $old_config = $ENV{GIT_CONFIG};
815 $ENV{GIT_CONFIG} = $config;
818 unless (-f $config) {
820 open my $fh, '>', $config or
821 die "Can't open $config: $!\n";
822 print $fh "; This file is used internally by ",
824 "Couldn't write to $config: $!\n";
825 print $fh "; You should not have to edit it\n" or
826 die "Couldn't write to $config: $!\n";
827 close $fh or die "Couldn't close $config: $!\n";
829 command('config', @args);
832 if (defined $old_config) {
833 $ENV{GIT_CONFIG} = $old_config;
835 delete $ENV{GIT_CONFIG};
838 wantarray ? @ret : $ret[0];
842 my ($self, $sub) = @_;
843 my $old_index = $ENV{GIT_INDEX_FILE};
844 $ENV{GIT_INDEX_FILE} = $self->{index};
847 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
848 mkpath([$dir]) unless -d $dir;
852 if (defined $old_index) {
853 $ENV{GIT_INDEX_FILE} = $old_index;
855 delete $ENV{GIT_INDEX_FILE};
858 wantarray ? @ret : $ret[0];
861 sub assert_index_clean {
862 my ($self, $treeish) = @_;
864 $self->tmp_index_do(sub {
865 command_noisy('read-tree', $treeish) unless -e $self->{index};
866 my $x = command_oneline('write-tree');
867 my ($y) = (command(qw/cat-file commit/, $treeish) =~
868 /^tree ($::sha1)/mo);
871 warn "Index mismatch: $y != $x\nrereading $treeish\n";
872 unlink $self->{index} or die "unlink $self->{index}: $!\n";
873 command_noisy('read-tree', $treeish);
874 $x = command_oneline('write-tree');
876 fatal "trees ($treeish) $y != $x\n",
877 "Something is seriously wrong...";
882 sub get_commit_parents {
883 my ($self, $log_entry) = @_;
884 my (%seen, @ret, @tmp);
885 # legacy support for 'set-tree'; this is only used by set_tree_cb:
886 if (my $ip = $self->{inject_parents}) {
887 if (my $commit = delete $ip->{$log_entry->{revision}}) {
891 if (my $cur = ::verify_ref($self->refname.'^0')) {
894 if (my $ipd = $self->{inject_parents_dcommit}) {
895 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
899 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
900 while (my $p = shift @tmp) {
910 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
911 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
912 my $rwr = eval { command_oneline(qw/config --get/, $k) };
915 if ($rwr !~ m#^[a-z\+]+://#) {
916 die "$rwr is not a valid URL (key: $k)\n";
919 $self->{-rewrite_root} = $rwr;
924 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
925 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
926 my $rwid = eval { command_oneline(qw/config --get/, $k) };
929 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
930 die "$rwid is not a valid UUID (key: $k)\n";
933 $self->{-rewrite_uuid} = $rwid;
938 my $url = $self->rewrite_root || $self->url;
939 return canonicalize_url( add_path_to_url( $url, $self->path ) );
944 return canonicalize_url( add_path_to_url( $self->url, $self->path ) );
949 if ($self->{pushurl}) {
950 return canonicalize_url( add_path_to_url( $self->{pushurl}, $self->path ) );
952 return $self->full_url;
956 sub set_commit_header_env {
957 my ($log_entry) = @_;
959 foreach my $ned (qw/NAME EMAIL DATE/) {
960 foreach my $ac (qw/AUTHOR COMMITTER/) {
961 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
965 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
966 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
967 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
969 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
970 ? $log_entry->{commit_name}
971 : $log_entry->{name};
972 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
973 ? $log_entry->{commit_email}
974 : $log_entry->{email};
978 sub restore_commit_header_env {
980 foreach my $ned (qw/NAME EMAIL DATE/) {
981 foreach my $ac (qw/AUTHOR COMMITTER/) {
982 my $k = "GIT_${ac}_${ned}";
983 if (defined $env->{$k}) {
984 $ENV{$k} = $env->{$k};
993 command_noisy('gc', '--auto');
997 my ($self, $log_entry) = @_;
998 my $lr = $self->last_rev;
999 if (defined $lr && $lr >= $log_entry->{revision}) {
1000 die "Last fetched revision of ", $self->refname,
1001 " was r$lr, but we are about to fetch: ",
1002 "r$log_entry->{revision}!\n";
1004 if (my $c = $self->rev_map_get($log_entry->{revision})) {
1005 croak "$log_entry->{revision} = $c already exists! ",
1006 "Why are we refetching it?\n";
1008 my $old_env = set_commit_header_env($log_entry);
1009 my $tree = $log_entry->{tree};
1010 if (!defined $tree) {
1011 $tree = $self->tmp_index_do(sub {
1012 command_oneline('write-tree') });
1014 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1016 my @exec = ('git', 'commit-tree', $tree);
1017 foreach ($self->get_commit_parents($log_entry)) {
1018 push @exec, '-p', $_;
1020 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1024 # we always get UTF-8 from SVN, but we may want our commits in
1025 # a different encoding.
1026 if (my $enc = Git::config('i18n.commitencoding')) {
1028 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
1030 print $msg_fh $log_entry->{log} or croak $!;
1031 restore_commit_header_env($old_env);
1032 unless ($self->no_metadata) {
1033 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1036 $msg_fh->flush == 0 or croak $!;
1037 close $msg_fh or croak $!;
1038 chomp(my $commit = do { local $/; <$out_fh> });
1039 close $out_fh or croak $!;
1042 if ($commit !~ /^$::sha1$/o) {
1043 die "Failed to commit, invalid sha1: $commit\n";
1046 $self->rev_map_set($log_entry->{revision}, $commit, 1);
1048 $self->{last_rev} = $log_entry->{revision};
1049 $self->{last_commit} = $commit;
1050 print "r$log_entry->{revision}" unless $::_q > 1;
1051 if (defined $log_entry->{svm_revision}) {
1052 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
1053 $self->rev_map_set($log_entry->{svm_revision}, $commit,
1054 0, $self->svm_uuid);
1056 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
1057 if (--$_gc_nr == 0) {
1058 $_gc_nr = $_gc_period;
1065 my ($self, $paths, $r) = @_;
1066 return 1 if $self->path eq '';
1067 if (my $path = $paths->{"/".$self->path}) {
1068 return ($path->{action} eq 'D') ? 0 : 1;
1070 $self->{path_regex} ||= qr{^/\Q@{[$self->path]}\E/};
1071 if (grep /$self->{path_regex}/, keys %$paths) {
1075 foreach (split m#/#, $self->path) {
1077 next unless ($paths->{$c} &&
1078 ($paths->{$c}->{action} =~ /^[AR]$/));
1079 if ($self->ra->check_path($self->path, $r) ==
1087 sub find_parent_branch {
1088 my ($self, $paths, $rev) = @_;
1089 return undef unless $self->follow_parent;
1090 unless (defined $paths) {
1091 my $err_handler = $SVN::Error::handler;
1092 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1093 $self->ra->get_log([$self->path], $rev, $rev, 0, 1, 1,
1094 sub { $paths = $_[0] });
1095 $SVN::Error::handler = $err_handler;
1097 return undef unless defined $paths;
1099 # look for a parent from another branch:
1100 my @b_path_components = split m#/#, $self->path;
1101 my @a_path_components;
1103 while (@b_path_components) {
1104 $i = $paths->{'/'.join('/', @b_path_components)};
1105 last if $i && defined $i->{copyfrom_path};
1106 unshift(@a_path_components, pop(@b_path_components));
1108 return undef unless defined $i && defined $i->{copyfrom_path};
1109 my $branch_from = $i->{copyfrom_path};
1110 if (@a_path_components) {
1111 print STDERR "branch_from: $branch_from => ";
1112 $branch_from .= '/'.join('/', @a_path_components);
1113 print STDERR $branch_from, "\n";
1115 my $r = $i->{copyfrom_rev};
1116 my $repos_root = $self->ra->{repos_root};
1117 my $url = $self->ra->url;
1118 my $new_url = canonicalize_url( add_path_to_url( $url, $branch_from ) );
1119 print STDERR "Found possible branch point: ",
1120 "$new_url => ", $self->full_url, ", $r\n"
1122 $branch_from =~ s#^/##;
1123 my $gs = $self->other_gs($new_url, $url,
1124 $branch_from, $r, $self->{ref_id});
1125 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1128 if (!defined $r0 || !defined $parent) {
1129 ($base, $head) = parse_revision_argument(0, $r);
1132 $gs->ra->get_log([$gs->path], $r0 + 1, $r, 1,
1133 0, 1, sub { $base = $_[1] - 1 });
1136 if (defined $base && $base <= $r) {
1137 $gs->fetch($base, $r);
1139 ($r0, $parent) = $gs->find_rev_before($r, 1);
1141 if (defined $r0 && defined $parent) {
1142 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
1145 if ($self->ra->can_do_switch) {
1146 $self->assert_index_clean($parent);
1147 print STDERR "Following parent with do_switch\n"
1149 # do_switch works with svn/trunk >= r22312, but that
1150 # is not included with SVN 1.4.3 (the latest version
1151 # at the moment), so we can't rely on it
1152 $self->{last_rev} = $r0;
1153 $self->{last_commit} = $parent;
1154 $ed = Git::SVN::Fetcher->new($self, $gs->path);
1155 $gs->ra->gs_do_switch($r0, $rev, $gs,
1156 $self->full_url, $ed)
1157 or die "SVN connection failed somewhere...\n";
1158 } elsif ($self->ra->trees_match($new_url, $r0,
1159 $self->full_url, $rev)) {
1160 print STDERR "Trees match:\n",
1162 " ${\$self->full_url}\@$rev\n",
1163 "Following parent with no changes\n"
1165 $self->tmp_index_do(sub {
1166 command_noisy('read-tree', $parent);
1168 $self->{last_commit} = $parent;
1170 print STDERR "Following parent with do_update\n"
1172 $ed = Git::SVN::Fetcher->new($self);
1173 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1174 or die "SVN connection failed somewhere...\n";
1176 print STDERR "Successfully followed parent\n" unless $::_q > 1;
1177 return $self->make_log_entry($rev, [$parent], $ed, $r0, $branch_from);
1183 my ($self, $paths, $rev) = @_;
1185 my ($last_rev, @parents);
1186 if (my $lc = $self->last_commit) {
1187 # we can have a branch that was deleted, then re-added
1188 # under the same name but copied from another path, in
1189 # which case we'll have multiple parents (we don't
1190 # want to break the original ref or lose copypath info):
1191 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1192 push @{$log_entry->{parents}}, $lc;
1195 $ed = Git::SVN::Fetcher->new($self);
1196 $last_rev = $self->{last_rev};
1201 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1204 $ed = Git::SVN::Fetcher->new($self);
1206 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1207 die "SVN connection failed somewhere...\n";
1209 $self->make_log_entry($rev, \@parents, $ed, $last_rev, $self->path);
1213 my ($self, $r) = @_;
1215 # add/remove/collect a paths table
1217 # Paths are split into a tree of nodes, stored as a hash of hashes.
1219 # Each node contains a 'path' entry for the path (if any) associated
1220 # with that node and a 'children' entry for any nodes under that
1223 # Removing a path requires a hash lookup for each component then
1224 # dropping that node (and anything under it), which is substantially
1225 # faster than a grep slice into a single hash of paths for large
1228 # For a large (200K) number of empty_dir directives this reduces
1229 # scanning time to 3 seconds vs 10 minutes for grep+delete on a single
1232 my ($paths_table, $path) = @_;
1235 foreach my $x (split('/', $path)) {
1236 if (!exists($paths_table->{$x})) {
1237 $paths_table->{$x} = { children => {} };
1240 $node_ref = $paths_table->{$x};
1241 $paths_table = $paths_table->{$x}->{children};
1244 $node_ref->{path} = $path;
1248 my ($paths_table, $path) = @_;
1252 foreach my $x (split('/', $path)) {
1253 if (!exists($paths_table->{$x})) {
1257 $nodes_ref = $paths_table;
1260 $paths_table = $paths_table->{$x}->{children};
1263 delete($nodes_ref->{$node_name});
1267 my ($paths_table, $paths_ref) = @_;
1269 foreach my $v (values %$paths_table) {
1271 my $c = $v->{children};
1273 collect_paths($c, $paths_ref);
1276 push(@$paths_ref, $p);
1282 my ($r, $paths_table, $line) = @_;
1283 if (defined $r && $line =~ /^r(\d+)$/) {
1284 return 0 if $1 > $r;
1285 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
1286 add_path($paths_table, $1);
1287 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
1288 remove_path($paths_table, $1);
1296 my $gz_file = "$self->{dir}/unhandled.log.gz";
1298 if (!can_compress()) {
1299 warn "Compress::Zlib could not be found; ",
1300 "empty directories in $gz_file will not be read\n";
1302 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
1303 die "Unable to open $gz_file: $!\n";
1305 while ($gz->gzreadline($line) > 0) {
1306 scan($r, \%paths_table, $line) or last;
1312 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
1313 binmode $fh or croak "binmode: $!";
1315 scan($r, \%paths_table, $_) or last;
1320 collect_paths(\%paths_table, \@empty_dirs);
1321 my $strip = qr/\A\Q@{[$self->path]}\E(?:\/|$)/;
1322 foreach my $d (sort @empty_dirs) {
1323 $d = uri_decode($d);
1325 next unless length($d);
1328 warn "$d exists but is not a directory\n";
1330 print "creating empty directory: $d\n";
1337 my ($self, $ed) = @_;
1339 my $h = $ed->{empty};
1340 foreach (sort keys %$h) {
1341 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1342 push @out, " $act: " . uri_encode($_);
1343 warn "W: $act: $_\n";
1345 foreach my $t (qw/dir_prop file_prop/) {
1346 $h = $ed->{$t} or next;
1347 foreach my $path (sort keys %$h) {
1348 my $ppath = $path eq '' ? '.' : $path;
1349 foreach my $prop (sort keys %{$h->{$path}}) {
1350 next if $SKIP_PROP{$prop};
1351 my $v = $h->{$path}->{$prop};
1352 my $t_ppath_prop = "$t: " .
1353 uri_encode($ppath) . ' ' .
1356 push @out, " +$t_ppath_prop " .
1359 push @out, " -$t_ppath_prop";
1364 foreach my $t (qw/absent_file absent_directory/) {
1365 $h = $ed->{$t} or next;
1366 foreach my $parent (sort keys %$h) {
1367 foreach my $path (sort @{$h->{$parent}}) {
1368 push @out, " $t: " .
1369 uri_encode("$parent/$path");
1370 warn "W: $t: $parent/$path ",
1371 "Insufficient permissions?\n";
1378 # parse_svn_date(DATE)
1379 # --------------------
1380 # Given a date (in UTC) from Subversion, return a string in the format
1381 # "<TZ Offset> <local date/time>" that Git will use.
1383 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
1384 # is true we'll convert it to the local timezone instead.
1385 sub parse_svn_date {
1386 my $date = shift || return '+0000 1970-01-01 00:00:00';
1387 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1388 (\d\d?)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1389 croak "Unable to parse date: $date\n";
1390 my $parsed_date; # Set next.
1392 if ($Git::SVN::_localtime) {
1393 # Translate the Subversion datetime to an epoch time.
1394 # Begin by switching ourselves to $date's timezone, UTC.
1395 my $old_env_TZ = $ENV{TZ};
1399 Time::Local::timelocal($S, $M, $H, $d, $m - 1, $Y - 1900);
1401 # Determine our local timezone (including DST) at the
1402 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
1403 # value of TZ, if any, at the time we were run.
1404 if (defined $Git::SVN::Log::TZ) {
1405 $ENV{TZ} = $Git::SVN::Log::TZ;
1410 my $our_TZ = get_tz_offset();
1412 # This converts $epoch_in_UTC into our local timezone.
1413 my ($sec, $min, $hour, $mday, $mon, $year,
1414 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
1416 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
1417 $our_TZ, $year + 1900, $mon + 1,
1418 $mday, $hour, $min, $sec);
1420 # Reset us to the timezone in effect when we entered
1422 if (defined $old_env_TZ) {
1423 $ENV{TZ} = $old_env_TZ;
1428 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
1431 return $parsed_date;
1435 my ($self, $new_url, $url,
1436 $branch_from, $r, $old_ref_id) = @_;
1437 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
1439 my $ref_id = $old_ref_id;
1440 $ref_id =~ s/\@\d+-*$//;
1442 # just grow a tail if we're not unique enough :x
1443 $ref_id .= '-' while find_ref($ref_id);
1444 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
1445 if ($u =~ s#^\Q$url\E(/|$)##) {
1448 $repo_id = $self->{repo_id};
1451 # It is possible to tag two different subdirectories at
1452 # the same revision. If the url for an existing ref
1453 # does not match, we must either find a ref with a
1454 # matching url or create a new ref by growing a tail.
1455 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
1456 my (undef, $max_commit) = $gs->rev_map_max(1);
1457 last if (!$max_commit);
1458 my ($url) = ::cmt_metadata($max_commit);
1459 last if ($url eq $gs->metadata_url);
1462 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
1467 sub call_authors_prog {
1468 my ($orig_author) = @_;
1469 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
1470 my $author = `$::_authors_prog $orig_author`;
1472 die "$::_authors_prog failed with exit code $?\n"
1474 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
1475 my ($name, $email) = ($1, $2);
1476 $email = undef if length $2 == 0;
1477 return [$name, $email];
1479 die "Author: $orig_author: $::_authors_prog returned "
1480 . "invalid author format: $author\n";
1486 if (!defined $author || length $author == 0) {
1487 $author = '(no author)';
1489 if (!defined $::users{$author}) {
1490 if (defined $::_authors_prog) {
1491 $::users{$author} = call_authors_prog($author);
1492 } elsif (defined $::_authors) {
1493 die "Author: $author not defined in $::_authors file\n";
1499 sub find_extra_svk_parents {
1500 my ($self, $tickets, $parents) = @_;
1501 # aha! svk:merge property changed...
1502 my @tickets = split "\n", $tickets;
1504 for my $ticket ( @tickets ) {
1505 my ($uuid, $path, $rev) = split /:/, $ticket;
1506 if ( $uuid eq $self->ra_uuid ) {
1507 my $repos_root = $self->url;
1508 my $branch_from = $path;
1509 $branch_from =~ s{^/}{};
1510 my $gs = $self->other_gs(add_path_to_url( $repos_root, $branch_from ),
1515 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
1516 # wahey! we found it, but it might be
1518 push @known_parents, [ $rev, $commit ];
1522 # Ordering matters; highest-numbered commit merge tickets
1523 # first, as they may account for later merge ticket additions
1525 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
1526 for my $parent ( @known_parents ) {
1527 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
1528 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
1530 while ( <$msg_fh> ) {
1533 command_close_pipe($msg_fh, $ctx);
1536 "Found merge parent (svk:merge ticket): $parent\n";
1537 push @$parents, $parent;
1542 sub lookup_svn_merge {
1550 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
1552 warn "Couldn't find revmap for $url$source\n";
1555 my @ranges = split ",", $revs;
1556 my ($tip, $tip_commit);
1557 my @merged_commit_ranges;
1559 for my $range ( @ranges ) {
1560 if ($range =~ /[*]$/) {
1561 warn "W: Ignoring partial merge in svn:mergeinfo "
1562 ."dirprop: $source:$range\n";
1565 my ($bottom, $top) = split "-", $range;
1567 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
1568 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
1570 unless ($top_commit and $bottom_commit) {
1571 warn "W: unknown path/rev in svn:mergeinfo "
1572 ."dirprop: $source:$range\n";
1576 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
1577 push @merged_commit_ranges,
1578 "$bottom_commit^..$top_commit";
1580 push @merged_commit_ranges, "$top_commit";
1583 if ( !defined $tip or $top > $tip ) {
1585 $tip_commit = $top_commit;
1588 return ($tip_commit, @merged_commit_ranges);
1592 my ($msg_fh, $ctx) = command_output_pipe(
1596 while ( <$msg_fh> ) {
1600 command_close_pipe($msg_fh, $ctx);
1604 sub check_cherry_pick2 {
1607 my $parents = shift;
1609 my %commits = map { $_ => 1 }
1610 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
1611 for my $range ( @ranges ) {
1612 delete @commits{_rev_list($range, "--")};
1614 for my $commit (keys %commits) {
1615 if (has_no_changes($commit)) {
1616 delete $commits{$commit};
1619 my @k = (keys %commits);
1620 return (scalar @k, $k[0]);
1623 sub has_no_changes {
1626 my @revs = split / /, command_oneline(
1627 qw(rev-list --parents -1 -m), $commit);
1629 # Commits with no parents, e.g. the start of a partial branch,
1630 # have changes by definition.
1631 return 1 if (@revs < 2);
1633 # Commits with multiple parents, e.g a merge, have no changes
1635 return 0 if (@revs > 2);
1637 return (command_oneline("rev-parse", "$commit^{tree}") eq
1638 command_oneline("rev-parse", "$commit~1^{tree}"));
1641 sub tie_for_persistent_memoization {
1645 unless ($memo_backend) {
1646 if (eval { require Git::SVN::Memoize::YAML; 1}) {
1649 require Memoize::Storable;
1654 if ($memo_backend > 0) {
1655 tie %$hash => 'Git::SVN::Memoize::YAML', "$path.yaml";
1657 tie %$hash => 'Memoize::Storable', "$path.db", 'nstore';
1661 # The GIT_DIR environment variable is not always set until after the command
1662 # line arguments are processed, so we can't memoize in a BEGIN block.
1666 sub memoize_svn_mergeinfo_functions {
1667 return if $memoized;
1670 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1671 mkpath([$cache_path]) unless -d $cache_path;
1673 my %lookup_svn_merge_cache;
1674 my %check_cherry_pick2_cache;
1675 my %has_no_changes_cache;
1677 tie_for_persistent_memoization(\%lookup_svn_merge_cache,
1678 "$cache_path/lookup_svn_merge");
1679 memoize 'lookup_svn_merge',
1680 SCALAR_CACHE => 'FAULT',
1681 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
1684 tie_for_persistent_memoization(\%check_cherry_pick2_cache,
1685 "$cache_path/check_cherry_pick2");
1686 memoize 'check_cherry_pick2',
1687 SCALAR_CACHE => 'FAULT',
1688 LIST_CACHE => ['HASH' => \%check_cherry_pick2_cache],
1691 tie_for_persistent_memoization(\%has_no_changes_cache,
1692 "$cache_path/has_no_changes");
1693 memoize 'has_no_changes',
1694 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
1695 LIST_CACHE => 'FAULT',
1699 sub unmemoize_svn_mergeinfo_functions {
1700 return if not $memoized;
1703 Memoize::unmemoize 'lookup_svn_merge';
1704 Memoize::unmemoize 'check_cherry_pick2';
1705 Memoize::unmemoize 'has_no_changes';
1708 sub clear_memoized_mergeinfo_caches {
1709 die "Only call this method in non-memoized context" if ($memoized);
1711 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1712 return unless -d $cache_path;
1714 for my $cache_file (("$cache_path/lookup_svn_merge",
1715 "$cache_path/check_cherry_pick", # old
1716 "$cache_path/check_cherry_pick2",
1717 "$cache_path/has_no_changes")) {
1718 for my $suffix (qw(yaml db)) {
1719 my $file = "$cache_file.$suffix";
1720 next unless -e $file;
1721 unlink($file) or die "unlink($file) failed: $!\n";
1727 Memoize::memoize 'Git::SVN::repos_root';
1731 # Force cache writeout explicitly instead of waiting for
1732 # global destruction to avoid segfault in Storable:
1733 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
1734 unmemoize_svn_mergeinfo_functions();
1737 sub parents_exclude {
1738 my $parents = shift;
1740 return unless @commits;
1745 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
1746 $excluded = command_oneline(@cmd);
1750 for my $commit ( @commits ) {
1751 if ( $commit eq $excluded ) {
1752 push @excluded, $commit;
1759 die "saw commit '$excluded' in rev-list output, "
1760 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
1765 while ($excluded and @commits);
1770 # Compute what's new in svn:mergeinfo.
1771 sub mergeinfo_changes {
1772 my ($self, $old_path, $old_rev, $path, $rev, $mergeinfo_prop) = @_;
1773 my %minfo = map {split ":", $_ } split "\n", $mergeinfo_prop;
1777 # Give up if $old_path isn't in the repo.
1778 # This is probably a merge on a subtree.
1779 if ($ra->check_path($old_path, $old_rev) != $SVN::Node::dir) {
1780 warn "W: ignoring svn:mergeinfo on $old_path, ",
1781 "directory didn't exist in r$old_rev\n";
1784 my (undef, undef, $props) = $ra->get_dir($old_path, $old_rev);
1785 if (defined $props->{"svn:mergeinfo"}) {
1786 my %omi = map {split ":", $_ } split "\n",
1787 $props->{"svn:mergeinfo"};
1792 foreach my $p (keys %minfo) {
1793 my $a = $old_minfo->{$p} || "";
1795 # Omit merged branches whose ranges lists are unchanged.
1797 # Remove any common range list prefix.
1798 ($a ^ $b) =~ /^[\0]*/;
1799 my $common_prefix = rindex $b, ",", $+[0] - 1;
1800 $changes{$p} = substr $b, $common_prefix + 1;
1802 print STDERR "Checking svn:mergeinfo changes since r$old_rev: ",
1803 scalar(keys %minfo), " sources, ",
1804 scalar(keys %changes), " changed\n";
1809 # note: this function should only be called if the various dirprops
1810 # have actually changed
1811 sub find_extra_svn_parents {
1812 my ($self, $mergeinfo, $parents) = @_;
1813 # aha! svk:merge property changed...
1815 memoize_svn_mergeinfo_functions();
1817 # We first search for merged tips which are not in our
1818 # history. Then, we figure out which git revisions are in
1819 # that tip, but not this revision. If all of those revisions
1820 # are now marked as merge, we can add the tip as a parent.
1821 my @merges = sort keys %$mergeinfo;
1823 my $url = $self->url;
1824 my $uuid = $self->ra_uuid;
1826 for my $merge ( @merges ) {
1827 my ($tip_commit, @ranges) =
1828 lookup_svn_merge( $uuid, $url,
1829 $merge, $mergeinfo->{$merge} );
1830 unless (!$tip_commit or
1831 grep { $_ eq $tip_commit } @$parents ) {
1832 push @merge_tips, $tip_commit;
1833 push @all_ranges, @ranges;
1835 push @merge_tips, undef;
1839 my %excluded = map { $_ => 1 }
1840 parents_exclude($parents, grep { defined } @merge_tips);
1842 # check merge tips for new parents
1844 for my $merge_tip ( @merge_tips ) {
1845 my $merge = shift @merges;
1846 next unless $merge_tip and $excluded{$merge_tip};
1847 my $spec = "$merge:$mergeinfo->{$merge}";
1849 # check out 'new' tips
1852 $merge_base = command_oneline(
1854 @$parents, $merge_tip,
1858 die "An error occurred during merge-base"
1859 unless $@->isa("Git::Error::Command");
1861 warn "W: Cannot find common ancestor between ".
1862 "@$parents and $merge_tip. Ignoring merge info.\n";
1866 # double check that there are no missing non-merge commits
1867 my ($ninc, $ifirst) = check_cherry_pick2(
1868 $merge_base, $merge_tip,
1874 warn "W: svn cherry-pick ignored ($spec) - missing " .
1875 "$ninc commit(s) (eg $ifirst)\n";
1877 warn "Found merge parent ($spec): ", $merge_tip, "\n";
1878 push @new_parents, $merge_tip;
1882 # cater for merges which merge commits from multiple branches
1883 if ( @new_parents > 1 ) {
1884 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
1885 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
1887 next unless $new_parents[$i];
1888 next unless $new_parents[$j];
1889 my $revs = command_oneline(
1891 "$new_parents[$i]..$new_parents[$j]",
1894 undef($new_parents[$j]);
1899 push @$parents, grep { defined } @new_parents;
1902 sub make_log_entry {
1903 my ($self, $rev, $parents, $ed, $parent_rev, $parent_path) = @_;
1904 my $untracked = $self->get_untracked($ed);
1906 my @parents = @$parents;
1907 my $props = $ed->{dir_prop}{$self->path};
1908 if ( $props->{"svk:merge"} ) {
1909 $self->find_extra_svk_parents($props->{"svk:merge"}, \@parents);
1911 if ( $props->{"svn:mergeinfo"} ) {
1912 my $mi_changes = $self->mergeinfo_changes
1913 ($parent_path, $parent_rev,
1915 $props->{"svn:mergeinfo"});
1916 $self->find_extra_svn_parents($mi_changes, \@parents);
1919 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1920 print $un "r$rev\n" or croak $!;
1921 print $un $_, "\n" foreach @$untracked;
1922 my %log_entry = ( parents => \@parents, revision => $rev,
1926 my $logged = delete $self->{logged_rev_props};
1927 if (!$logged || $self->{-want_revprops}) {
1928 my $rp = $self->ra->rev_proplist($rev);
1929 foreach (sort keys %$rp) {
1931 if (/^svn:(author|date|log)$/) {
1932 $log_entry{$1} = $v;
1933 } elsif ($_ eq 'svm:headrev') {
1936 print $un " rev_prop: ", uri_encode($_), ' ',
1937 uri_encode($v), "\n";
1941 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1943 close $un or croak $!;
1945 $log_entry{date} = parse_svn_date($log_entry{date});
1946 $log_entry{log} .= "\n";
1947 my $author = $log_entry{author} = check_author($log_entry{author});
1948 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1951 my ($commit_name, $commit_email) = ($name, $email);
1952 if ($_use_log_author) {
1954 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
1956 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
1959 if (!defined $name_field) {
1960 if (!defined $email) {
1963 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
1964 ($name, $email) = ($1, $2);
1965 } elsif ($name_field =~ /(.*)@/) {
1966 ($name, $email) = ($1, $name_field);
1968 ($name, $email) = ($name_field, $name_field);
1971 if (defined $headrev && $self->use_svm_props) {
1972 if ($self->rewrite_root) {
1973 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1976 if ($self->rewrite_uuid) {
1977 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
1980 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
1981 # we don't want "SVM: initializing mirror for junk" ...
1982 return undef if $r == 0;
1983 my $svm = $self->svm;
1984 if ($uuid ne $svm->{uuid}) {
1985 die "UUID mismatch on SVM path:\n",
1986 "expected: $svm->{uuid}\n",
1989 my $full_url = $self->full_url;
1990 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1991 die "Failed to replace '$svm->{replace}' with ",
1992 "'$svm->{source}' in $full_url\n";
1993 # throw away username for storing in records
1994 remove_username($full_url);
1995 $log_entry{metadata} = "$full_url\@$r $uuid";
1996 $log_entry{svm_revision} = $r;
1997 $email ||= "$author\@$uuid";
1998 $commit_email ||= "$author\@$uuid";
1999 } elsif ($self->use_svnsync_props) {
2000 my $full_url = canonicalize_url(
2001 add_path_to_url( $self->svnsync->{url}, $self->path )
2003 remove_username($full_url);
2004 my $uuid = $self->svnsync->{uuid};
2005 $log_entry{metadata} = "$full_url\@$rev $uuid";
2006 $email ||= "$author\@$uuid";
2007 $commit_email ||= "$author\@$uuid";
2009 my $url = $self->metadata_url;
2010 remove_username($url);
2011 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
2012 $log_entry{metadata} = "$url\@$rev " . $uuid;
2013 $email ||= "$author\@" . $uuid;
2014 $commit_email ||= "$author\@" . $uuid;
2016 $log_entry{name} = $name;
2017 $log_entry{email} = $email;
2018 $log_entry{commit_name} = $commit_name;
2019 $log_entry{commit_email} = $commit_email;
2024 my ($self, $min_rev, $max_rev, @parents) = @_;
2025 my ($last_rev, $last_commit) = $self->last_rev_commit;
2026 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2027 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2031 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2032 $self->{inject_parents} = { $rev => $tree };
2033 $self->fetch(undef, undef);
2037 my ($self, $tree) = (shift, shift);
2038 my $log_entry = ::get_commit_entry($tree);
2039 unless ($self->{last_rev}) {
2040 fatal("Must have an existing revision to commit");
2042 my %ed_opts = ( r => $self->{last_rev},
2043 log => $log_entry->{log},
2045 tree_a => $self->{last_commit},
2048 $self->set_tree_cb($log_entry, $tree, @_) },
2049 svn_path => $self->path );
2050 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
2051 print "No changes\nr$self->{last_rev} = $tree\n";
2055 sub rebuild_from_rev_db {
2056 my ($self, $path) = @_;
2058 open my $fh, '<', $path or croak "open: $!";
2059 binmode $fh or croak "binmode: $!";
2061 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2064 next if $_ eq ('0' x 40);
2065 $self->rev_map_set($r, $_);
2068 close $fh or croak "close: $!";
2069 unlink $path or croak "unlink: $!";
2072 #define a global associate map to record rebuild status
2074 #define a global associate map to record rebuild verify status
2075 my %rebuild_verify_status;
2079 my $map_path = $self->map_path;
2080 my $partial = (-e $map_path && ! -z $map_path);
2081 my $verify_key = $self->refname.'^0';
2082 if (!$rebuild_verify_status{$verify_key}) {
2083 my $verify_result = ::verify_ref($verify_key);
2084 if ($verify_result) {
2085 $rebuild_verify_status{$verify_key} = 1;
2088 if (!$rebuild_verify_status{$verify_key}) {
2091 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2092 my $rev_db = $self->rev_db_path;
2093 $self->rebuild_from_rev_db($rev_db);
2094 if ($self->use_svm_props) {
2095 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2096 $self->rebuild_from_rev_db($svm_rev_db);
2098 $self->unlink_rev_db_symlink;
2101 print "Rebuilding $map_path ...\n" if (!$partial);
2102 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2104 my $key_value = ($head ? "$head.." : "") . $self->refname;
2105 if (exists $rebuild_status{$key_value}) {
2106 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2107 my $rev_db_path = $self->rev_db_path;
2108 if (-f $self->rev_db_path) {
2109 unlink $self->rev_db_path or croak "unlink: $!";
2111 $self->unlink_rev_db_symlink;
2115 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
2118 $rebuild_status{$key_value} = 1;
2119 my $metadata_url = $self->metadata_url;
2120 remove_username($metadata_url);
2121 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
2124 if ( m{^commit ($::sha1)$} ) {
2128 next unless s{^\s*(git-svn-id:)}{$1};
2129 my ($url, $rev, $uuid) = ::extract_metadata($_);
2130 remove_username($url);
2132 # ignore merges (from set-tree)
2133 next if (!defined $rev || !$uuid);
2135 # if we merged or otherwise started elsewhere, this is
2136 # how we break out of it
2137 if (($uuid ne $svn_uuid) ||
2138 ($metadata_url && $url && ($url ne $metadata_url))) {
2141 if ($partial && $head) {
2142 print "Partial-rebuilding $map_path ...\n";
2143 print "Currently at $base_rev = $head\n";
2147 $self->rev_map_set($rev, $c);
2148 print "r$rev = $c\n";
2150 command_close_pipe($log, $ctx);
2151 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2152 my $rev_db_path = $self->rev_db_path;
2153 if (-f $self->rev_db_path) {
2154 unlink $self->rev_db_path or croak "unlink: $!";
2156 $self->unlink_rev_db_symlink;
2160 # Tie::File seems to be prone to offset errors if revisions get sparse,
2161 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2162 # one of my favorite modules is out :< Next up would be one of the DBM
2163 # modules, but I'm not sure which is most portable...
2165 # This is the replacement for the rev_db format, which was too big
2166 # and inefficient for large repositories with a lot of sparse history
2169 # The format is this:
2170 # - 24 bytes for every record,
2171 # * 4 bytes for the integer representing an SVN revision number
2172 # * 20 bytes representing the sha1 of a git commit
2173 # - No empty padding records like the old format
2174 # (except the last record, which can be overwritten)
2175 # - new records are written append-only since SVN revision numbers
2176 # increase monotonically
2177 # - lookups on SVN revision number are done via a binary search
2178 # - Piping the file to xxd -c24 is a good way of dumping it for
2179 # viewing or editing (piped back through xxd -r), should the need
2181 # - The last record can be padding revision with an all-zero sha1
2182 # This is used to optimize fetch performance when using multiple
2183 # "fetch" directives in .git/config
2185 # These files are disposable unless noMetadata or useSvmProps is set
2188 my ($fh, $rev, $commit) = @_;
2190 binmode $fh or croak "binmode: $!";
2191 my $size = (stat($fh))[7];
2192 ($size % 24) == 0 or croak "inconsistent size: $size";
2196 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2197 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2198 $read == 24 or croak "read only $read bytes (!= 24)";
2199 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2200 if ($last_commit eq ('0' x40)) {
2202 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2203 $read = sysread($fh, $buf, 24) or
2206 croak "read only $read bytes (!= 24)";
2207 ($last_rev, $last_commit) =
2208 unpack(rev_map_fmt, $buf);
2209 if ($last_commit eq ('0' x40)) {
2210 croak "inconsistent .rev_map\n";
2213 if ($last_rev >= $rev) {
2214 croak "last_rev is higher!: $last_rev >= $rev";
2219 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2220 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2224 sub _rev_map_reset {
2225 my ($fh, $rev, $commit) = @_;
2226 my $c = _rev_map_get($fh, $rev);
2227 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
2228 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
2229 truncate $fh, $offset or croak "truncate: $!";
2235 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2236 mkpath([$dir]) unless -d $dir;
2237 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2238 close $fh or die "Couldn't close (create) $path: $!\n";
2243 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2244 defined $commit or die "missing arg3\n";
2245 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2246 my $db = $self->map_path($uuid);
2247 my $db_lock = "$db.lock";
2251 $sigmask = POSIX::SigSet->new();
2252 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
2253 SIGALRM, SIGUSR1, SIGUSR2);
2254 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
2255 croak "Can't block signals: $!";
2259 $LOCKFILES{$db_lock} = 1;
2261 # both of these options make our .rev_db file very, very important
2262 # and we can't afford to lose it because rebuild() won't work
2263 if ($self->use_svm_props || $self->no_metadata) {
2266 File::Copy::copy($db, $db_lock) or die "rev_map_set(@_): ",
2268 "$db => $db_lock ($!)\n";
2270 rename $db, $db_lock or die "rev_map_set(@_): ",
2271 "Failed to rename: ",
2272 "$db => $db_lock ($!)\n";
2275 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2276 or croak "Couldn't open $db_lock: $!\n";
2277 if ($update_ref eq 'reset') {
2278 clear_memoized_mergeinfo_caches();
2279 _rev_map_reset($fh, $rev, $commit);
2281 _rev_map_set($fh, $rev, $commit);
2285 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2286 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2288 close $fh or croak $!;
2292 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
2293 command_noisy('update-ref', '-m', "r$rev$note",
2294 $self->refname, $commit);
2296 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2297 "$db_lock => $db ($!)\n";
2298 delete $LOCKFILES{$db_lock};
2300 sigprocmask(SIG_SETMASK, $sigmask) or
2301 croak "Can't restore signal mask: $!";
2305 # If want_commit, this will return an array of (rev, commit) where
2306 # commit _must_ be a valid commit in the archive.
2307 # Otherwise, it'll return the max revision (whether or not the
2308 # commit is valid or just a 0x40 placeholder).
2310 my ($self, $want_commit) = @_;
2312 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2313 $want_commit ? ($r, $c) : $r;
2316 sub rev_map_max_norebuild {
2317 my ($self, $want_commit) = @_;
2318 my $map_path = $self->map_path;
2319 stat $map_path or return $want_commit ? (0, undef) : 0;
2320 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2321 binmode $fh or croak "binmode: $!";
2322 my $size = (stat($fh))[7];
2323 ($size % 24) == 0 or croak "inconsistent size: $size";
2326 close $fh or croak "close: $!";
2327 return $want_commit ? (0, undef) : 0;
2330 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2331 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2332 my ($r, $c) = unpack(rev_map_fmt, $buf);
2333 if ($want_commit && $c eq ('0' x40)) {
2335 return $want_commit ? (0, undef) : 0;
2337 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2338 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2339 ($r, $c) = unpack(rev_map_fmt, $buf);
2340 if ($c eq ('0'x40)) {
2341 croak "Penultimate record is all-zeroes in $map_path";
2344 close $fh or croak "close: $!";
2345 $want_commit ? ($r, $c) : $r;
2349 my ($self, $rev, $uuid) = @_;
2350 my $map_path = $self->map_path($uuid);
2351 return undef unless -e $map_path;
2353 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2354 my $c = _rev_map_get($fh, $rev);
2355 close($fh) or croak "close: $!";
2360 my ($fh, $rev) = @_;
2362 binmode $fh or croak "binmode: $!";
2363 my $size = (stat($fh))[7];
2364 ($size % 24) == 0 or croak "inconsistent size: $size";
2370 my ($l, $u) = (0, $size - 24);
2374 my $i = int(($l/24 + $u/24) / 2) * 24;
2375 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2376 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2377 my ($r, $c) = unpack(rev_map_fmt, $buf);
2381 } elsif ($r > $rev) {
2383 } else { # $r == $rev
2384 return $c eq ('0' x 40) ? undef : $c;
2390 # Finds the first svn revision that exists on (if $eq_ok is true) or
2391 # before $rev for the current branch. It will not search any lower
2392 # than $min_rev. Returns the git commit hash and svn revision number
2393 # if found, else (undef, undef).
2394 sub find_rev_before {
2395 my ($self, $rev, $eq_ok, $min_rev) = @_;
2396 --$rev unless $eq_ok;
2398 my $max_rev = $self->rev_map_max;
2399 $rev = $max_rev if ($rev > $max_rev);
2400 while ($rev >= $min_rev) {
2401 if (my $c = $self->rev_map_get($rev)) {
2406 return (undef, undef);
2409 # Finds the first svn revision that exists on (if $eq_ok is true) or
2410 # after $rev for the current branch. It will not search any higher
2411 # than $max_rev. Returns the git commit hash and svn revision number
2412 # if found, else (undef, undef).
2413 sub find_rev_after {
2414 my ($self, $rev, $eq_ok, $max_rev) = @_;
2415 ++$rev unless $eq_ok;
2416 $max_rev ||= $self->rev_map_max;
2417 while ($rev <= $max_rev) {
2418 if (my $c = $self->rev_map_get($rev)) {
2423 return (undef, undef);
2427 my ($class, $repo_id, $ref_id, $path) = @_;
2428 unless (defined $repo_id && length $repo_id) {
2429 $repo_id = $default_repo_id;
2431 unless (defined $ref_id && length $ref_id) {
2432 # Access the prefix option from the git-svn main program if it's loaded.
2433 my $prefix = defined &::opt_prefix ? ::opt_prefix() : "";
2435 "refs/remotes/$prefix$default_ref_id";
2438 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2440 # Older repos imported by us used $GIT_DIR/svn/foo instead of
2441 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
2442 if ($ref_id =~ m{^refs/remotes/(.+)}) {
2443 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
2444 if (-d $old_dir && ! -d $dir) {
2449 $_[3] = $path = '' unless (defined $path);
2452 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2453 config => "$ENV{GIT_DIR}/svn/config",
2454 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2456 # Ensure it gets canonicalized
2467 $self->{_path} = canonicalize_path($path);
2471 return $self->{_path};
2479 $self->{url} = canonicalize_url($url);
2483 return $self->{url};
2486 # for read-only access of old .rev_db formats
2487 sub unlink_rev_db_symlink {
2489 my $link = $self->rev_db_path;
2490 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2492 unlink $link or croak "unlink: $link failed!";
2497 my ($self, $uuid) = @_;
2498 my $db_path = $self->map_path($uuid);
2499 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2500 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2504 # the new replacement for .rev_db
2506 my ($self, $uuid) = @_;
2507 $uuid ||= $self->ra_uuid;
2508 "$self->{map_root}.$uuid";
2513 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#sprintf("%%%02X",ord($1))#eg;
2519 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
2523 sub remove_username {
2524 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};