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/;
12 use File::Copy qw/copy/;
15 use Memoize; # core since 5.8.0, Jul 2002
16 use Memoize::Storable;
17 use POSIX qw(:signal_h);
26 use Git::SVN::Utils qw(
34 $can_use_yaml = eval { require Git::SVN::Memoize::YAML; 1};
37 our $_follow_parent = 1;
38 our $_minimize_url = 'unset';
39 our $default_repo_id = 'svn';
40 our $default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
42 my ($_gc_nr, $_gc_period);
44 # properties that we do not log:
47 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
48 svn:special svn:executable
49 svn:entry:committed-rev
52 svn:entry:committed-date/;
54 # some options are read globally, but can be overridden locally
55 # per [svn-remote "..."] section. Command-line options will *NOT*
56 # override options set in an [svn-remote "..."] section
58 for my $option (qw/follow_parent no_metadata use_svm_props
62 my $prop = "-$option";
65 return $self->{$prop} if exists $self->{$prop};
66 my $k = "svn-remote.$self->{repo_id}.$key";
67 eval { command_oneline(qw/config --get/, $k) };
69 $self->{$prop} = ${"Git::SVN::_$option"};
71 my $v = command_oneline(qw/config --bool/,$k);
72 $self->{$prop} = $v eq 'false' ? 0 : 1;
74 return $self->{$prop};
80 my (%LOCKFILES, %INDEX_FILES);
82 unlink keys %LOCKFILES if %LOCKFILES;
83 unlink keys %INDEX_FILES if %INDEX_FILES;
86 sub resolve_local_globs {
87 my ($url, $fetch, $glob_spec) = @_;
88 return unless defined $glob_spec;
89 my $ref = $glob_spec->{ref};
90 my $path = $glob_spec->{path};
91 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
92 next unless m#^$ref->{regex}$#;
94 my $pathname = desanitize_refname($path->full_path($p));
95 my $refname = desanitize_refname($ref->full_path($p));
96 if (my $existing = $fetch->{$pathname}) {
97 if ($existing ne $refname) {
98 die "Refspec conflict:\n",
99 "existing: $existing\n",
100 " globbed: $refname\n";
102 my $u = (::cmt_metadata("$refname"))[0];
103 $u =~ s!^\Q$url\E(/|$)!! or die
104 "$refname: '$url' not found in '$u'\n";
105 if ($pathname ne $u) {
106 warn "W: Refspec glob conflict ",
107 "(ref: $refname):\n",
108 "expected path: $pathname\n",
110 "Continuing ahead with $u\n";
114 $fetch->{$pathname} = $refname;
119 sub parse_revision_argument {
120 my ($base, $head) = @_;
121 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
122 return ($base, $head);
124 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
125 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
126 return ($head, $head) if ($::_revision eq 'HEAD');
127 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
128 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
129 die "revision argument: $::_revision not understood by git-svn\n";
133 my ($repo_id, $remotes) = @_;
137 $repo_id = $gs->{repo_id};
139 $remotes ||= read_all_remotes();
140 my $remote = $remotes->{$repo_id} or
141 die "[svn-remote \"$repo_id\"] unknown\n";
142 my $fetch = $remote->{fetch};
143 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
145 my $ra = Git::SVN::Ra->new($url);
146 my $uuid = $ra->get_uuid;
147 my $head = $ra->get_latest_revnum;
149 # ignore errors, $head revision may not even exist anymore
150 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
151 warn "W: $@\n" if $@;
153 my $base = defined $fetch ? $head : 0;
155 # read the max revs for wildcard expansion (branches/*, tags/*)
156 foreach my $t (qw/branches tags/) {
157 defined $remote->{$t} or next;
158 push @globs, @{$remote->{$t}};
160 my $max_rev = eval { tmp_config(qw/--int --get/,
161 "svn-remote.$repo_id.${t}-maxRev") };
162 if (defined $max_rev && ($max_rev < $base)) {
164 } elsif (!defined $max_rev) {
170 foreach my $p (sort keys %$fetch) {
171 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
172 my $lr = $gs->rev_map_max;
174 $base = $lr if ($lr < $base);
180 ($base, $head) = parse_revision_argument($base, $head);
181 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
184 sub read_all_remotes {
186 my $use_svm_props = eval { command_oneline(qw/config --bool
188 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
189 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
190 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
191 if (m!^(.+)\.fetch=$svn_refspec$!) {
192 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
193 die("svn-remote.$remote: remote ref '$remote_ref' "
194 . "must start with 'refs/'\n")
195 unless $remote_ref =~ m{^refs/};
196 $local_ref = uri_decode($local_ref);
197 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
198 $r->{$remote}->{svm} = {} if $use_svm_props;
199 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
200 $r->{$1}->{svm} = {};
201 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
202 $r->{$1}->{url} = $2;
203 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
204 $r->{$1}->{pushurl} = $2;
205 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
206 $r->{$1}->{ignore_refs_regex} = $2;
207 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
208 my ($remote, $t, $local_ref, $remote_ref) =
210 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
211 . "must start with 'refs/'\n")
212 unless $remote_ref =~ m{^refs/};
213 $local_ref = uri_decode($local_ref);
215 require Git::SVN::GlobSpec;
219 path => Git::SVN::GlobSpec->new($local_ref, 1),
220 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
221 if (length($rs->{ref}->{right}) != 0) {
222 die "The '*' glob character must be the last ",
223 "character of '$remote_ref'\n";
225 push @{ $r->{$remote}->{$t} }, $rs;
230 if (defined $r->{$_}->{svm}) {
233 my $section = "svn-remote.$_";
235 source => tmp_config('--get',
236 "$section.svm-source"),
237 replace => tmp_config('--get',
238 "$section.svm-replace"),
241 $r->{$_}->{svm} = $svm;
245 foreach my $remote (keys %$r) {
246 foreach ( grep { defined $_ }
247 map { $r->{$remote}->{$_} } qw(branches tags) ) {
248 foreach my $rs ( @$_ ) {
249 $rs->{ignore_refs_regex} =
250 $r->{$remote}->{ignore_refs_regex};
259 $_gc_nr = $_gc_period = 1000;
260 if (defined $_repack || defined $_repack_flags) {
261 warn "Repack options are obsolete; they have no effect.\n";
265 sub verify_remotes_sanity {
266 return unless -d $ENV{GIT_DIR};
268 foreach (command(qw/config -l/)) {
269 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
271 die "Remote ref refs/remote/$1 is tracked by",
272 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
273 "Please resolve this ambiguity in ",
274 "your git configuration file before ",
282 sub find_existing_remote {
283 my ($url, $remotes) = @_;
284 return undef if $no_reuse_existing;
286 foreach my $repo_id (keys %$remotes) {
287 my $u = $remotes->{$repo_id}->{url} or next;
289 $existing = $repo_id;
295 sub init_remote_config {
296 my ($self, $url, $no_write) = @_;
297 $url =~ s!/+$!!; # strip trailing slash
298 my $r = read_all_remotes();
299 my $existing = find_existing_remote($url, $r);
302 print STDERR "Using existing ",
303 "[svn-remote \"$existing\"]\n";
305 $self->{repo_id} = $existing;
306 } elsif ($_minimize_url) {
307 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
308 $existing = find_existing_remote($min_url, $r);
311 print STDERR "Using existing ",
312 "[svn-remote \"$existing\"]\n";
314 $self->{repo_id} = $existing;
316 if ($min_url ne $url) {
318 print STDERR "Using higher level of URL: ",
319 "$url => $min_url\n";
321 my $old_path = $self->path;
322 $url =~ s!^\Q$min_url\E(/|$)!!;
323 $url = join_paths($url, $old_path);
330 # verify that we aren't overwriting anything:
332 command_oneline('config', '--get',
333 "svn-remote.$self->{repo_id}.url")
335 if ($orig_url && ($orig_url ne $url)) {
336 die "svn-remote.$self->{repo_id}.url already set: ",
337 "$orig_url\nwanted to set to: $url\n";
340 my ($xrepo_id, $xpath) = find_ref($self->refname);
341 if (!$no_write && defined $xpath) {
342 die "svn-remote.$xrepo_id.fetch already set to track ",
343 "$xpath:", $self->refname, "\n";
346 command_noisy('config',
347 "svn-remote.$self->{repo_id}.url", $url);
348 my $path = $self->path;
350 $path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
352 command_noisy('config', '--add',
353 "svn-remote.$self->{repo_id}.fetch",
354 $self->path.":".$self->refname);
359 sub find_by_url { # repos_root and, path are optional
360 my ($class, $full_url, $repos_root, $path) = @_;
362 return undef unless defined $full_url;
363 remove_username($full_url);
364 remove_username($repos_root) if defined $repos_root;
365 my $remotes = read_all_remotes();
366 if (defined $full_url && defined $repos_root && !defined $path) {
368 $path =~ s#^\Q$repos_root\E(?:/|$)##;
370 foreach my $repo_id (keys %$remotes) {
371 my $u = $remotes->{$repo_id}->{url} or next;
373 next if defined $repos_root && $repos_root ne $u;
375 my $fetch = $remotes->{$repo_id}->{fetch} || {};
376 foreach my $t (qw/branches tags/) {
377 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
378 resolve_local_globs($u, $fetch, $globspec);
382 my $rwr = rewrite_root({repo_id => $repo_id});
383 my $svm = $remotes->{$repo_id}->{svm}
384 if defined $remotes->{$repo_id}->{svm};
385 unless (defined $p) {
392 } elsif (defined $svm) {
394 $prefix = $svm->{replace};
395 $prefix =~ s#^\Q$u\E(?:/|$)##;
398 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
400 foreach my $f (keys %$fetch) {
402 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
409 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
410 my $self = _new($class, $repo_id, $ref_id, $path);
412 $self->init_remote_config($url, $no_write);
419 foreach (command(qw/config -l/)) {
420 next unless m!^svn-remote\.(.+)\.fetch=
421 \s*(.*?)\s*:\s*(.+?)\s*$!x;
422 my ($repo_id, $path, $ref) = ($1, $2, $3);
423 if ($ref eq $ref_id) {
424 $path = '' if ($path =~ m#^\./?#);
425 return ($repo_id, $path);
428 (undef, undef, undef);
432 my ($class, $ref_id, $repo_id, $path) = @_;
433 if (defined $ref_id && !defined $repo_id && !defined $path) {
434 ($repo_id, $path) = find_ref($ref_id);
435 if (!defined $repo_id) {
436 die "Could not find a \"svn-remote.*.fetch\" key ",
437 "in the repository configuration matching: ",
441 my $self = _new($class, $repo_id, $ref_id, $path);
442 if (!defined $self->path || !length $self->path) {
443 my $fetch = command_oneline('config', '--get',
444 "svn-remote.$repo_id.fetch",
446 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
447 "\":$ref_id\$\" in config\n";
448 my($path) = split(/\s*:\s*/, $fetch);
452 my $path = $self->path;
458 my $url = command_oneline('config', '--get',
459 "svn-remote.$repo_id.url") or
460 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
462 $self->{pushurl} = eval { command_oneline('config', '--get',
463 "svn-remote.$repo_id.pushurl") };
469 my ($refname) = $_[0]->{ref_id} ;
471 # It cannot end with a slash /, we'll throw up on this because
472 # SVN can't have directories with a slash in their name, either:
473 if ($refname =~ m{/$}) {
474 die "ref: '$refname' ends with a trailing slash, this is ",
475 "not permitted by git nor Subversion\n";
478 # It cannot have ASCII control character space, tilde ~, caret ^,
479 # colon :, question-mark ?, asterisk *, space, or open bracket [
482 # Additionally, % must be escaped because it is used for escaping
483 # and we want our escaped refname to be reversible
484 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
486 # no slash-separated component can begin with a dot .
488 $refname =~ s{/\.}{/%2E}g;
490 # It cannot have two consecutive dots .. anywhere
492 $refname =~ s{\.\.}{%2E%2E}g;
494 # trailing dots and .lock are not allowed
495 # .$ becomes %2E and .lock becomes %2Elock
496 $refname =~ s{\.(?=$|lock$)}{%2E};
498 # the sequence @{ is used to access the reflog
500 $refname =~ s{\@\{}{%40\{}g;
505 sub desanitize_refname {
507 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
513 return $self->{svm}->{uuid} if $self->svm;
515 unless ($self->{svm}) {
516 die "SVM UUID not cached, and reading remotely failed\n";
518 $self->{svm}->{uuid};
523 return $self->{svm} if $self->{svm};
525 # see if we have it in our config, first:
527 my $section = "svn-remote.$self->{repo_id}";
529 source => tmp_config('--get', "$section.svm-source"),
530 uuid => tmp_config('--get', "$section.svm-uuid"),
531 replace => tmp_config('--get', "$section.svm-replace"),
534 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
541 my ($self, $ra) = @_;
542 return $ra if $self->svm;
544 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
545 "(svm:source, svm:uuid) ",
546 "from the following URLs:\n" );
548 my ($self, $ra, $path, $r) = @_;
549 my $props = ($ra->get_dir($path, $r))[2];
550 my $src = $props->{'svm:source'};
551 my $uuid = $props->{'svm:uuid'};
552 return undef if (!$src || !$uuid);
556 $uuid =~ m{^[0-9a-f\-]{30,}$}i
557 or die "doesn't look right - svm:uuid is '$uuid'\n";
559 # the '!' is used to mark the repos_root!/relative/path
561 $src =~ s{/+$}{}; # no trailing slashes please
562 # username is of no interest
563 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
565 my $replace = $ra->url;
566 $replace .= "/$path" if length $path;
568 my $section = "svn-remote.$self->{repo_id}";
569 tmp_config("$section.svm-source", $src);
570 tmp_config("$section.svm-replace", $replace);
571 tmp_config("$section.svm-uuid", $uuid);
579 my $r = $ra->get_latest_revnum;
580 my $path = $self->path;
582 while (length $path) {
583 my $try = $self->url . "/$path";
584 unless ($tried{$try}) {
585 return $ra if $self->read_svm_props($ra, $path, $r);
588 $path =~ s#/?[^/]+$##;
590 die "Path: '$path' should be ''\n" if $path ne '';
591 return $ra if $self->read_svm_props($ra, $path, $r);
592 $tried{$self->url."/$path"} = 1;
594 if ($ra->{repos_root} eq $self->url) {
595 die @err, (map { " $_\n" } keys %tried), "\n";
598 # nope, make sure we're connected to the repository root:
601 $path = $ra->{svn_path};
602 $ra = Git::SVN::Ra->new($ra->{repos_root});
603 while (length $path) {
604 my $try = $ra->url ."/$path";
605 unless ($tried{$try}) {
606 $ok = $self->read_svm_props($ra, $path, $r);
610 $path =~ s#/?[^/]+$##;
612 die "Path: '$path' should be ''\n" if $path ne '';
613 $ok ||= $self->read_svm_props($ra, $path, $r);
614 $tried{$ra->url ."/$path"} = 1;
616 die @err, (map { " $_\n" } keys %tried), "\n";
618 Git::SVN::Ra->new($self->url);
623 return $self->{svnsync} if $self->{svnsync};
625 if ($self->no_metadata) {
626 die "Can't have both 'noMetadata' and ",
627 "'useSvnsyncProps' options set!\n";
629 if ($self->rewrite_root) {
630 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
633 if ($self->rewrite_uuid) {
634 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
639 # see if we have it in our config, first:
641 my $section = "svn-remote.$self->{repo_id}";
643 my $url = tmp_config('--get', "$section.svnsync-url");
644 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
645 die "doesn't look right - svn:sync-from-url is '$url'\n";
647 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
648 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
649 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
651 $svnsync = { url => $url, uuid => $uuid }
653 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
654 return $self->{svnsync} = $svnsync;
657 my $err = "useSvnsyncProps set, but failed to read " .
658 "svnsync property: svn:sync-from-";
659 my $rp = $self->ra->rev_proplist(0);
661 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
662 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
663 die "doesn't look right - svn:sync-from-url is '$url'\n";
665 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
666 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
667 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
669 my $section = "svn-remote.$self->{repo_id}";
670 tmp_config('--add', "$section.svnsync-uuid", $uuid);
671 tmp_config('--add', "$section.svnsync-url", $url);
672 return $self->{svnsync} = { url => $url, uuid => $uuid };
675 # this allows us to memoize our SVN::Ra UUID locally and avoid a
676 # remote lookup (useful for 'git svn log').
679 unless ($self->{ra_uuid}) {
680 my $key = "svn-remote.$self->{repo_id}.uuid";
681 my $uuid = eval { tmp_config('--get', $key) };
682 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
683 $self->{ra_uuid} = $uuid;
685 die "ra_uuid called without URL\n" unless $self->url;
686 $self->{ra_uuid} = $self->ra->get_uuid;
687 tmp_config('--add', $key, $self->{ra_uuid});
693 sub _set_repos_root {
694 my ($self, $repos_root) = @_;
695 my $k = "svn-remote.$self->{repo_id}.reposRoot";
696 $repos_root ||= $self->ra->{repos_root};
697 tmp_config($k, $repos_root);
703 my $k = "svn-remote.$self->{repo_id}.reposRoot";
704 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
709 my $ra = Git::SVN::Ra->new($self->url);
710 $self->_set_repos_root($ra->{repos_root});
711 if ($self->use_svm_props && !$self->{svm}) {
712 if ($self->no_metadata) {
713 die "Can't have both 'noMetadata' and ",
714 "'useSvmProps' options set!\n";
715 } elsif ($self->use_svnsync_props) {
716 die "Can't have both 'useSvnsyncProps' and ",
717 "'useSvmProps' options set!\n";
719 $ra = $self->_set_svm_vars($ra);
720 $self->{-want_revprops} = 1;
725 # prop_walk(PATH, REV, SUB)
726 # -------------------------
727 # Recursively traverse PATH at revision REV and invoke SUB for each
728 # directory that contains a SVN property. SUB will be invoked as
729 # follows: &SUB(gs, path, props); where `gs' is this instance of
730 # Git::SVN, `path' the path to the directory where the properties
731 # `props' were found. The `path' will be relative to point of checkout,
732 # that is, if url://repo/trunk is the current Git branch, and that
733 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
734 # as `path' (note the trailing `/').
736 my ($self, $path, $rev, $sub) = @_;
739 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
742 # Strip the irrelevant part of the path.
743 $p =~ s#^/+\Q@{[$self->path]}\E(/|$)#/#;
744 # Ensure the path is terminated by a `/'.
747 # The properties contain all the internal SVN stuff nobody
748 # (usually) cares about.
749 my $interesting_props = 0;
750 foreach (keys %{$props}) {
751 # If it doesn't start with `svn:', it must be a
752 # user-defined property.
753 ++$interesting_props and next if $_ !~ /^svn:/;
754 # FIXME: Fragile, if SVN adds new public properties,
755 # this needs to be updated.
756 ++$interesting_props if /^svn:(?:ignore|keywords|executable
758 |externals|needs-lock)$/x;
760 &$sub($self, $p, $props) if $interesting_props;
762 foreach (sort keys %$dirent) {
763 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
764 $self->prop_walk($self->path . $p . $_, $rev, $sub);
768 sub last_rev { ($_[0]->last_rev_commit)[0] }
769 sub last_commit { ($_[0]->last_rev_commit)[1] }
771 # returns the newest SVN revision number and newest commit SHA1
772 sub last_rev_commit {
774 if (defined $self->{last_rev} && defined $self->{last_commit}) {
775 return ($self->{last_rev}, $self->{last_commit});
777 my $c = ::verify_ref($self->refname.'^0');
778 if ($c && !$self->use_svm_props && !$self->no_metadata) {
779 my $rev = (::cmt_metadata($c))[1];
781 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
785 my $map_path = $self->map_path;
786 unless (-e $map_path) {
787 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
788 return (undef, undef);
790 my ($rev, $commit) = $self->rev_map_max(1);
791 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
792 return ($rev, $commit);
795 sub get_fetch_range {
796 my ($self, $min, $max) = @_;
797 $max ||= $self->ra->get_latest_revnum;
798 $min ||= $self->rev_map_max;
804 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
805 my $config = "$ENV{GIT_DIR}/svn/.metadata";
806 if (! -f $config && -f $old_def_config) {
807 rename $old_def_config, $config or
808 die "Failed rename $old_def_config => $config: $!\n";
810 my $old_config = $ENV{GIT_CONFIG};
811 $ENV{GIT_CONFIG} = $config;
814 unless (-f $config) {
816 open my $fh, '>', $config or
817 die "Can't open $config: $!\n";
818 print $fh "; This file is used internally by ",
820 "Couldn't write to $config: $!\n";
821 print $fh "; You should not have to edit it\n" or
822 die "Couldn't write to $config: $!\n";
823 close $fh or die "Couldn't close $config: $!\n";
825 command('config', @args);
828 if (defined $old_config) {
829 $ENV{GIT_CONFIG} = $old_config;
831 delete $ENV{GIT_CONFIG};
834 wantarray ? @ret : $ret[0];
838 my ($self, $sub) = @_;
839 my $old_index = $ENV{GIT_INDEX_FILE};
840 $ENV{GIT_INDEX_FILE} = $self->{index};
843 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
844 mkpath([$dir]) unless -d $dir;
848 if (defined $old_index) {
849 $ENV{GIT_INDEX_FILE} = $old_index;
851 delete $ENV{GIT_INDEX_FILE};
854 wantarray ? @ret : $ret[0];
857 sub assert_index_clean {
858 my ($self, $treeish) = @_;
860 $self->tmp_index_do(sub {
861 command_noisy('read-tree', $treeish) unless -e $self->{index};
862 my $x = command_oneline('write-tree');
863 my ($y) = (command(qw/cat-file commit/, $treeish) =~
864 /^tree ($::sha1)/mo);
867 warn "Index mismatch: $y != $x\nrereading $treeish\n";
868 unlink $self->{index} or die "unlink $self->{index}: $!\n";
869 command_noisy('read-tree', $treeish);
870 $x = command_oneline('write-tree');
872 fatal "trees ($treeish) $y != $x\n",
873 "Something is seriously wrong...";
878 sub get_commit_parents {
879 my ($self, $log_entry) = @_;
880 my (%seen, @ret, @tmp);
881 # legacy support for 'set-tree'; this is only used by set_tree_cb:
882 if (my $ip = $self->{inject_parents}) {
883 if (my $commit = delete $ip->{$log_entry->{revision}}) {
887 if (my $cur = ::verify_ref($self->refname.'^0')) {
890 if (my $ipd = $self->{inject_parents_dcommit}) {
891 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
895 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
896 while (my $p = shift @tmp) {
906 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
907 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
908 my $rwr = eval { command_oneline(qw/config --get/, $k) };
911 if ($rwr !~ m#^[a-z\+]+://#) {
912 die "$rwr is not a valid URL (key: $k)\n";
915 $self->{-rewrite_root} = $rwr;
920 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
921 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
922 my $rwid = eval { command_oneline(qw/config --get/, $k) };
925 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
926 die "$rwid is not a valid UUID (key: $k)\n";
929 $self->{-rewrite_uuid} = $rwid;
934 ($self->rewrite_root || $self->url) .
935 (length $self->path ? '/' . $self->path : '');
940 $self->url . (length $self->path ? '/' . $self->path : '');
945 if ($self->{pushurl}) {
946 return $self->{pushurl} . (length $self->path ? '/' .
949 return $self->full_url;
953 sub set_commit_header_env {
954 my ($log_entry) = @_;
956 foreach my $ned (qw/NAME EMAIL DATE/) {
957 foreach my $ac (qw/AUTHOR COMMITTER/) {
958 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
962 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
963 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
964 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
966 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
967 ? $log_entry->{commit_name}
968 : $log_entry->{name};
969 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
970 ? $log_entry->{commit_email}
971 : $log_entry->{email};
975 sub restore_commit_header_env {
977 foreach my $ned (qw/NAME EMAIL DATE/) {
978 foreach my $ac (qw/AUTHOR COMMITTER/) {
979 my $k = "GIT_${ac}_${ned}";
980 if (defined $env->{$k}) {
981 $ENV{$k} = $env->{$k};
990 command_noisy('gc', '--auto');
994 my ($self, $log_entry) = @_;
995 my $lr = $self->last_rev;
996 if (defined $lr && $lr >= $log_entry->{revision}) {
997 die "Last fetched revision of ", $self->refname,
998 " was r$lr, but we are about to fetch: ",
999 "r$log_entry->{revision}!\n";
1001 if (my $c = $self->rev_map_get($log_entry->{revision})) {
1002 croak "$log_entry->{revision} = $c already exists! ",
1003 "Why are we refetching it?\n";
1005 my $old_env = set_commit_header_env($log_entry);
1006 my $tree = $log_entry->{tree};
1007 if (!defined $tree) {
1008 $tree = $self->tmp_index_do(sub {
1009 command_oneline('write-tree') });
1011 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1013 my @exec = ('git', 'commit-tree', $tree);
1014 foreach ($self->get_commit_parents($log_entry)) {
1015 push @exec, '-p', $_;
1017 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1021 # we always get UTF-8 from SVN, but we may want our commits in
1022 # a different encoding.
1023 if (my $enc = Git::config('i18n.commitencoding')) {
1025 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
1027 print $msg_fh $log_entry->{log} or croak $!;
1028 restore_commit_header_env($old_env);
1029 unless ($self->no_metadata) {
1030 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1033 $msg_fh->flush == 0 or croak $!;
1034 close $msg_fh or croak $!;
1035 chomp(my $commit = do { local $/; <$out_fh> });
1036 close $out_fh or croak $!;
1039 if ($commit !~ /^$::sha1$/o) {
1040 die "Failed to commit, invalid sha1: $commit\n";
1043 $self->rev_map_set($log_entry->{revision}, $commit, 1);
1045 $self->{last_rev} = $log_entry->{revision};
1046 $self->{last_commit} = $commit;
1047 print "r$log_entry->{revision}" unless $::_q > 1;
1048 if (defined $log_entry->{svm_revision}) {
1049 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
1050 $self->rev_map_set($log_entry->{svm_revision}, $commit,
1051 0, $self->svm_uuid);
1053 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
1054 if (--$_gc_nr == 0) {
1055 $_gc_nr = $_gc_period;
1062 my ($self, $paths, $r) = @_;
1063 return 1 if $self->path eq '';
1064 if (my $path = $paths->{"/".$self->path}) {
1065 return ($path->{action} eq 'D') ? 0 : 1;
1067 $self->{path_regex} ||= qr{^/\Q@{[$self->path]}\E/};
1068 if (grep /$self->{path_regex}/, keys %$paths) {
1072 foreach (split m#/#, $self->path) {
1074 next unless ($paths->{$c} &&
1075 ($paths->{$c}->{action} =~ /^[AR]$/));
1076 if ($self->ra->check_path($self->path, $r) ==
1084 sub find_parent_branch {
1085 my ($self, $paths, $rev) = @_;
1086 return undef unless $self->follow_parent;
1087 unless (defined $paths) {
1088 my $err_handler = $SVN::Error::handler;
1089 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1090 $self->ra->get_log([$self->path], $rev, $rev, 0, 1, 1,
1091 sub { $paths = $_[0] });
1092 $SVN::Error::handler = $err_handler;
1094 return undef unless defined $paths;
1096 # look for a parent from another branch:
1097 my @b_path_components = split m#/#, $self->path;
1098 my @a_path_components;
1100 while (@b_path_components) {
1101 $i = $paths->{'/'.join('/', @b_path_components)};
1102 last if $i && defined $i->{copyfrom_path};
1103 unshift(@a_path_components, pop(@b_path_components));
1105 return undef unless defined $i && defined $i->{copyfrom_path};
1106 my $branch_from = $i->{copyfrom_path};
1107 if (@a_path_components) {
1108 print STDERR "branch_from: $branch_from => ";
1109 $branch_from .= '/'.join('/', @a_path_components);
1110 print STDERR $branch_from, "\n";
1112 my $r = $i->{copyfrom_rev};
1113 my $repos_root = $self->ra->{repos_root};
1114 my $url = $self->ra->url;
1115 my $new_url = $url . $branch_from;
1116 print STDERR "Found possible branch point: ",
1117 "$new_url => ", $self->full_url, ", $r\n"
1119 $branch_from =~ s#^/##;
1120 my $gs = $self->other_gs($new_url, $url,
1121 $branch_from, $r, $self->{ref_id});
1122 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1125 if (!defined $r0 || !defined $parent) {
1126 ($base, $head) = parse_revision_argument(0, $r);
1129 $gs->ra->get_log([$gs->path], $r0 + 1, $r, 1,
1130 0, 1, sub { $base = $_[1] - 1 });
1133 if (defined $base && $base <= $r) {
1134 $gs->fetch($base, $r);
1136 ($r0, $parent) = $gs->find_rev_before($r, 1);
1138 if (defined $r0 && defined $parent) {
1139 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
1142 if ($self->ra->can_do_switch) {
1143 $self->assert_index_clean($parent);
1144 print STDERR "Following parent with do_switch\n"
1146 # do_switch works with svn/trunk >= r22312, but that
1147 # is not included with SVN 1.4.3 (the latest version
1148 # at the moment), so we can't rely on it
1149 $self->{last_rev} = $r0;
1150 $self->{last_commit} = $parent;
1151 $ed = Git::SVN::Fetcher->new($self, $gs->path);
1152 $gs->ra->gs_do_switch($r0, $rev, $gs,
1153 $self->full_url, $ed)
1154 or die "SVN connection failed somewhere...\n";
1155 } elsif ($self->ra->trees_match($new_url, $r0,
1156 $self->full_url, $rev)) {
1157 print STDERR "Trees match:\n",
1159 " ${\$self->full_url}\@$rev\n",
1160 "Following parent with no changes\n"
1162 $self->tmp_index_do(sub {
1163 command_noisy('read-tree', $parent);
1165 $self->{last_commit} = $parent;
1167 print STDERR "Following parent with do_update\n"
1169 $ed = Git::SVN::Fetcher->new($self);
1170 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1171 or die "SVN connection failed somewhere...\n";
1173 print STDERR "Successfully followed parent\n" unless $::_q > 1;
1174 return $self->make_log_entry($rev, [$parent], $ed);
1180 my ($self, $paths, $rev) = @_;
1182 my ($last_rev, @parents);
1183 if (my $lc = $self->last_commit) {
1184 # we can have a branch that was deleted, then re-added
1185 # under the same name but copied from another path, in
1186 # which case we'll have multiple parents (we don't
1187 # want to break the original ref, nor lose copypath info):
1188 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1189 push @{$log_entry->{parents}}, $lc;
1192 $ed = Git::SVN::Fetcher->new($self);
1193 $last_rev = $self->{last_rev};
1198 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1201 $ed = Git::SVN::Fetcher->new($self);
1203 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1204 die "SVN connection failed somewhere...\n";
1206 $self->make_log_entry($rev, \@parents, $ed);
1210 my ($self, $r) = @_;
1213 my ($r, $empty_dirs, $line) = @_;
1214 if (defined $r && $line =~ /^r(\d+)$/) {
1215 return 0 if $1 > $r;
1216 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
1217 $empty_dirs->{$1} = 1;
1218 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
1219 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
1220 delete @$empty_dirs{@d};
1225 my %empty_dirs = ();
1226 my $gz_file = "$self->{dir}/unhandled.log.gz";
1228 if (!can_compress()) {
1229 warn "Compress::Zlib could not be found; ",
1230 "empty directories in $gz_file will not be read\n";
1232 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
1233 die "Unable to open $gz_file: $!\n";
1235 while ($gz->gzreadline($line) > 0) {
1236 scan($r, \%empty_dirs, $line) or last;
1242 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
1243 binmode $fh or croak "binmode: $!";
1245 scan($r, \%empty_dirs, $_) or last;
1250 my $strip = qr/\A\Q@{[$self->path]}\E(?:\/|$)/;
1251 foreach my $d (sort keys %empty_dirs) {
1252 $d = uri_decode($d);
1254 next unless length($d);
1257 warn "$d exists but is not a directory\n";
1259 print "creating empty directory: $d\n";
1266 my ($self, $ed) = @_;
1268 my $h = $ed->{empty};
1269 foreach (sort keys %$h) {
1270 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1271 push @out, " $act: " . uri_encode($_);
1272 warn "W: $act: $_\n";
1274 foreach my $t (qw/dir_prop file_prop/) {
1275 $h = $ed->{$t} or next;
1276 foreach my $path (sort keys %$h) {
1277 my $ppath = $path eq '' ? '.' : $path;
1278 foreach my $prop (sort keys %{$h->{$path}}) {
1279 next if $SKIP_PROP{$prop};
1280 my $v = $h->{$path}->{$prop};
1281 my $t_ppath_prop = "$t: " .
1282 uri_encode($ppath) . ' ' .
1285 push @out, " +$t_ppath_prop " .
1288 push @out, " -$t_ppath_prop";
1293 foreach my $t (qw/absent_file absent_directory/) {
1294 $h = $ed->{$t} or next;
1295 foreach my $parent (sort keys %$h) {
1296 foreach my $path (sort @{$h->{$parent}}) {
1297 push @out, " $t: " .
1298 uri_encode("$parent/$path");
1299 warn "W: $t: $parent/$path ",
1300 "Insufficient permissions?\n";
1308 # some systmes don't handle or mishandle %z, so be creative.
1309 my $t = shift || time;
1310 my $gm = timelocal(gmtime($t));
1311 my $sign = qw( + + - )[ $t <=> $gm ];
1312 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
1315 # parse_svn_date(DATE)
1316 # --------------------
1317 # Given a date (in UTC) from Subversion, return a string in the format
1318 # "<TZ Offset> <local date/time>" that Git will use.
1320 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
1321 # is true we'll convert it to the local timezone instead.
1322 sub parse_svn_date {
1323 my $date = shift || return '+0000 1970-01-01 00:00:00';
1324 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1325 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1326 croak "Unable to parse date: $date\n";
1327 my $parsed_date; # Set next.
1329 if ($Git::SVN::_localtime) {
1330 # Translate the Subversion datetime to an epoch time.
1331 # Begin by switching ourselves to $date's timezone, UTC.
1332 my $old_env_TZ = $ENV{TZ};
1336 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
1338 # Determine our local timezone (including DST) at the
1339 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
1340 # value of TZ, if any, at the time we were run.
1341 if (defined $Git::SVN::Log::TZ) {
1342 $ENV{TZ} = $Git::SVN::Log::TZ;
1347 my $our_TZ = get_tz();
1349 # This converts $epoch_in_UTC into our local timezone.
1350 my ($sec, $min, $hour, $mday, $mon, $year,
1351 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
1353 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
1354 $our_TZ, $year + 1900, $mon + 1,
1355 $mday, $hour, $min, $sec);
1357 # Reset us to the timezone in effect when we entered
1359 if (defined $old_env_TZ) {
1360 $ENV{TZ} = $old_env_TZ;
1365 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
1368 return $parsed_date;
1372 my ($self, $new_url, $url,
1373 $branch_from, $r, $old_ref_id) = @_;
1374 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
1376 my $ref_id = $old_ref_id;
1377 $ref_id =~ s/\@\d+-*$//;
1379 # just grow a tail if we're not unique enough :x
1380 $ref_id .= '-' while find_ref($ref_id);
1381 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
1382 if ($u =~ s#^\Q$url\E(/|$)##) {
1385 $repo_id = $self->{repo_id};
1388 # It is possible to tag two different subdirectories at
1389 # the same revision. If the url for an existing ref
1390 # does not match, we must either find a ref with a
1391 # matching url or create a new ref by growing a tail.
1392 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
1393 my (undef, $max_commit) = $gs->rev_map_max(1);
1394 last if (!$max_commit);
1395 my ($url) = ::cmt_metadata($max_commit);
1396 last if ($url eq $gs->metadata_url);
1399 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
1404 sub call_authors_prog {
1405 my ($orig_author) = @_;
1406 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
1407 my $author = `$::_authors_prog $orig_author`;
1409 die "$::_authors_prog failed with exit code $?\n"
1411 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
1412 my ($name, $email) = ($1, $2);
1413 $email = undef if length $2 == 0;
1414 return [$name, $email];
1416 die "Author: $orig_author: $::_authors_prog returned "
1417 . "invalid author format: $author\n";
1423 if (!defined $author || length $author == 0) {
1424 $author = '(no author)';
1426 if (!defined $::users{$author}) {
1427 if (defined $::_authors_prog) {
1428 $::users{$author} = call_authors_prog($author);
1429 } elsif (defined $::_authors) {
1430 die "Author: $author not defined in $::_authors file\n";
1436 sub find_extra_svk_parents {
1437 my ($self, $ed, $tickets, $parents) = @_;
1438 # aha! svk:merge property changed...
1439 my @tickets = split "\n", $tickets;
1441 for my $ticket ( @tickets ) {
1442 my ($uuid, $path, $rev) = split /:/, $ticket;
1443 if ( $uuid eq $self->ra_uuid ) {
1444 my $url = $self->url;
1445 my $repos_root = $url;
1446 my $branch_from = $path;
1447 $branch_from =~ s{^/}{};
1448 my $gs = $self->other_gs($repos_root."/".$branch_from,
1453 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
1454 # wahey! we found it, but it might be
1456 push @known_parents, [ $rev, $commit ];
1460 # Ordering matters; highest-numbered commit merge tickets
1461 # first, as they may account for later merge ticket additions
1463 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
1464 for my $parent ( @known_parents ) {
1465 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
1466 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
1468 while ( <$msg_fh> ) {
1471 command_close_pipe($msg_fh, $ctx);
1474 "Found merge parent (svk:merge ticket): $parent\n";
1475 push @$parents, $parent;
1480 sub lookup_svn_merge {
1485 my ($source, $revs) = split ":", $merge;
1488 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
1490 warn "Couldn't find revmap for $url$source\n";
1493 my @ranges = split ",", $revs;
1494 my ($tip, $tip_commit);
1495 my @merged_commit_ranges;
1497 for my $range ( @ranges ) {
1498 my ($bottom, $top) = split "-", $range;
1500 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
1501 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
1503 unless ($top_commit and $bottom_commit) {
1504 warn "W:unknown path/rev in svn:mergeinfo "
1505 ."dirprop: $source:$range\n";
1509 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
1510 push @merged_commit_ranges,
1511 "$bottom_commit^..$top_commit";
1513 push @merged_commit_ranges, "$top_commit";
1516 if ( !defined $tip or $top > $tip ) {
1518 $tip_commit = $top_commit;
1521 return ($tip_commit, @merged_commit_ranges);
1525 my ($msg_fh, $ctx) = command_output_pipe(
1529 while ( <$msg_fh> ) {
1533 command_close_pipe($msg_fh, $ctx);
1537 sub check_cherry_pick {
1540 my $parents = shift;
1542 my %commits = map { $_ => 1 }
1543 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
1544 for my $range ( @ranges ) {
1545 delete @commits{_rev_list($range, "--")};
1547 for my $commit (keys %commits) {
1548 if (has_no_changes($commit)) {
1549 delete $commits{$commit};
1552 return (keys %commits);
1555 sub has_no_changes {
1558 my @revs = split / /, command_oneline(
1559 qw(rev-list --parents -1 -m), $commit);
1561 # Commits with no parents, e.g. the start of a partial branch,
1562 # have changes by definition.
1563 return 1 if (@revs < 2);
1565 # Commits with multiple parents, e.g a merge, have no changes
1567 return 0 if (@revs > 2);
1569 return (command_oneline("rev-parse", "$commit^{tree}") eq
1570 command_oneline("rev-parse", "$commit~1^{tree}"));
1573 sub tie_for_persistent_memoization {
1577 if ($can_use_yaml) {
1578 tie %$hash => 'Git::SVN::Memoize::YAML', "$path.yaml";
1580 tie %$hash => 'Memoize::Storable', "$path.db", 'nstore';
1584 # The GIT_DIR environment variable is not always set until after the command
1585 # line arguments are processed, so we can't memoize in a BEGIN block.
1589 sub memoize_svn_mergeinfo_functions {
1590 return if $memoized;
1593 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1594 mkpath([$cache_path]) unless -d $cache_path;
1596 my %lookup_svn_merge_cache;
1597 my %check_cherry_pick_cache;
1598 my %has_no_changes_cache;
1600 tie_for_persistent_memoization(\%lookup_svn_merge_cache,
1601 "$cache_path/lookup_svn_merge");
1602 memoize 'lookup_svn_merge',
1603 SCALAR_CACHE => 'FAULT',
1604 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
1607 tie_for_persistent_memoization(\%check_cherry_pick_cache,
1608 "$cache_path/check_cherry_pick");
1609 memoize 'check_cherry_pick',
1610 SCALAR_CACHE => 'FAULT',
1611 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
1614 tie_for_persistent_memoization(\%has_no_changes_cache,
1615 "$cache_path/has_no_changes");
1616 memoize 'has_no_changes',
1617 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
1618 LIST_CACHE => 'FAULT',
1622 sub unmemoize_svn_mergeinfo_functions {
1623 return if not $memoized;
1626 Memoize::unmemoize 'lookup_svn_merge';
1627 Memoize::unmemoize 'check_cherry_pick';
1628 Memoize::unmemoize 'has_no_changes';
1631 Memoize::memoize 'Git::SVN::repos_root';
1635 # Force cache writeout explicitly instead of waiting for
1636 # global destruction to avoid segfault in Storable:
1637 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
1638 unmemoize_svn_mergeinfo_functions();
1641 sub parents_exclude {
1642 my $parents = shift;
1644 return unless @commits;
1649 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
1650 $excluded = command_oneline(@cmd);
1654 for my $commit ( @commits ) {
1655 if ( $commit eq $excluded ) {
1656 push @excluded, $commit;
1664 die "saw commit '$excluded' in rev-list output, "
1665 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
1670 while ($excluded and @commits);
1676 # note: this function should only be called if the various dirprops
1677 # have actually changed
1678 sub find_extra_svn_parents {
1679 my ($self, $ed, $mergeinfo, $parents) = @_;
1680 # aha! svk:merge property changed...
1682 memoize_svn_mergeinfo_functions();
1684 # We first search for merged tips which are not in our
1685 # history. Then, we figure out which git revisions are in
1686 # that tip, but not this revision. If all of those revisions
1687 # are now marked as merge, we can add the tip as a parent.
1688 my @merges = split "\n", $mergeinfo;
1690 my $url = $self->url;
1691 my $uuid = $self->ra_uuid;
1693 for my $merge ( @merges ) {
1694 my ($tip_commit, @ranges) =
1695 lookup_svn_merge( $uuid, $url, $merge );
1696 unless (!$tip_commit or
1697 grep { $_ eq $tip_commit } @$parents ) {
1698 push @merge_tips, $tip_commit;
1699 $ranges{$tip_commit} = \@ranges;
1701 push @merge_tips, undef;
1705 my %excluded = map { $_ => 1 }
1706 parents_exclude($parents, grep { defined } @merge_tips);
1708 # check merge tips for new parents
1710 for my $merge_tip ( @merge_tips ) {
1711 my $spec = shift @merges;
1712 next unless $merge_tip and $excluded{$merge_tip};
1714 my $ranges = $ranges{$merge_tip};
1716 # check out 'new' tips
1719 $merge_base = command_oneline(
1721 @$parents, $merge_tip,
1725 die "An error occurred during merge-base"
1726 unless $@->isa("Git::Error::Command");
1728 warn "W: Cannot find common ancestor between ".
1729 "@$parents and $merge_tip. Ignoring merge info.\n";
1733 # double check that there are no missing non-merge commits
1734 my (@incomplete) = check_cherry_pick(
1735 $merge_base, $merge_tip,
1740 if ( @incomplete ) {
1741 warn "W:svn cherry-pick ignored ($spec) - missing "
1742 .@incomplete." commit(s) (eg $incomplete[0])\n";
1745 "Found merge parent (svn:mergeinfo prop): ",
1747 push @new_parents, $merge_tip;
1751 # cater for merges which merge commits from multiple branches
1752 if ( @new_parents > 1 ) {
1753 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
1754 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
1756 next unless $new_parents[$i];
1757 next unless $new_parents[$j];
1758 my $revs = command_oneline(
1760 "$new_parents[$i]..$new_parents[$j]",
1763 undef($new_parents[$j]);
1768 push @$parents, grep { defined } @new_parents;
1771 sub make_log_entry {
1772 my ($self, $rev, $parents, $ed) = @_;
1773 my $untracked = $self->get_untracked($ed);
1775 my @parents = @$parents;
1776 my $ps = $ed->{path_strip} || "";
1777 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
1778 my $props = $ed->{dir_prop}{$path};
1779 if ( $props->{"svk:merge"} ) {
1780 $self->find_extra_svk_parents
1781 ($ed, $props->{"svk:merge"}, \@parents);
1783 if ( $props->{"svn:mergeinfo"} ) {
1784 $self->find_extra_svn_parents
1786 $props->{"svn:mergeinfo"},
1791 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1792 print $un "r$rev\n" or croak $!;
1793 print $un $_, "\n" foreach @$untracked;
1794 my %log_entry = ( parents => \@parents, revision => $rev,
1798 my $logged = delete $self->{logged_rev_props};
1799 if (!$logged || $self->{-want_revprops}) {
1800 my $rp = $self->ra->rev_proplist($rev);
1801 foreach (sort keys %$rp) {
1803 if (/^svn:(author|date|log)$/) {
1804 $log_entry{$1} = $v;
1805 } elsif ($_ eq 'svm:headrev') {
1808 print $un " rev_prop: ", uri_encode($_), ' ',
1809 uri_encode($v), "\n";
1813 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1815 close $un or croak $!;
1817 $log_entry{date} = parse_svn_date($log_entry{date});
1818 $log_entry{log} .= "\n";
1819 my $author = $log_entry{author} = check_author($log_entry{author});
1820 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1823 my ($commit_name, $commit_email) = ($name, $email);
1824 if ($_use_log_author) {
1826 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
1828 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
1831 if (!defined $name_field) {
1832 if (!defined $email) {
1835 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
1836 ($name, $email) = ($1, $2);
1837 } elsif ($name_field =~ /(.*)@/) {
1838 ($name, $email) = ($1, $name_field);
1840 ($name, $email) = ($name_field, $name_field);
1843 if (defined $headrev && $self->use_svm_props) {
1844 if ($self->rewrite_root) {
1845 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1848 if ($self->rewrite_uuid) {
1849 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
1852 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
1853 # we don't want "SVM: initializing mirror for junk" ...
1854 return undef if $r == 0;
1855 my $svm = $self->svm;
1856 if ($uuid ne $svm->{uuid}) {
1857 die "UUID mismatch on SVM path:\n",
1858 "expected: $svm->{uuid}\n",
1861 my $full_url = $self->full_url;
1862 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1863 die "Failed to replace '$svm->{replace}' with ",
1864 "'$svm->{source}' in $full_url\n";
1865 # throw away username for storing in records
1866 remove_username($full_url);
1867 $log_entry{metadata} = "$full_url\@$r $uuid";
1868 $log_entry{svm_revision} = $r;
1869 $email ||= "$author\@$uuid";
1870 $commit_email ||= "$author\@$uuid";
1871 } elsif ($self->use_svnsync_props) {
1872 my $full_url = $self->svnsync->{url};
1873 $full_url .= "/".$self->path if length $self->path;
1874 remove_username($full_url);
1875 my $uuid = $self->svnsync->{uuid};
1876 $log_entry{metadata} = "$full_url\@$rev $uuid";
1877 $email ||= "$author\@$uuid";
1878 $commit_email ||= "$author\@$uuid";
1880 my $url = $self->metadata_url;
1881 remove_username($url);
1882 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
1883 $log_entry{metadata} = "$url\@$rev " . $uuid;
1884 $email ||= "$author\@" . $uuid;
1885 $commit_email ||= "$author\@" . $uuid;
1887 $log_entry{name} = $name;
1888 $log_entry{email} = $email;
1889 $log_entry{commit_name} = $commit_name;
1890 $log_entry{commit_email} = $commit_email;
1895 my ($self, $min_rev, $max_rev, @parents) = @_;
1896 my ($last_rev, $last_commit) = $self->last_rev_commit;
1897 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1898 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1902 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1903 $self->{inject_parents} = { $rev => $tree };
1904 $self->fetch(undef, undef);
1908 my ($self, $tree) = (shift, shift);
1909 my $log_entry = ::get_commit_entry($tree);
1910 unless ($self->{last_rev}) {
1911 fatal("Must have an existing revision to commit");
1913 my %ed_opts = ( r => $self->{last_rev},
1914 log => $log_entry->{log},
1916 tree_a => $self->{last_commit},
1919 $self->set_tree_cb($log_entry, $tree, @_) },
1920 svn_path => $self->path );
1921 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1922 print "No changes\nr$self->{last_rev} = $tree\n";
1926 sub rebuild_from_rev_db {
1927 my ($self, $path) = @_;
1929 open my $fh, '<', $path or croak "open: $!";
1930 binmode $fh or croak "binmode: $!";
1932 length($_) == 41 or croak "inconsistent size in ($_) != 41";
1935 next if $_ eq ('0' x 40);
1936 $self->rev_map_set($r, $_);
1939 close $fh or croak "close: $!";
1940 unlink $path or croak "unlink: $!";
1945 my $map_path = $self->map_path;
1946 my $partial = (-e $map_path && ! -z $map_path);
1947 return unless ::verify_ref($self->refname.'^0');
1948 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
1949 my $rev_db = $self->rev_db_path;
1950 $self->rebuild_from_rev_db($rev_db);
1951 if ($self->use_svm_props) {
1952 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
1953 $self->rebuild_from_rev_db($svm_rev_db);
1955 $self->unlink_rev_db_symlink;
1958 print "Rebuilding $map_path ...\n" if (!$partial);
1959 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
1962 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
1963 ($head ? "$head.." : "") . $self->refname,
1965 my $metadata_url = $self->metadata_url;
1966 remove_username($metadata_url);
1967 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
1970 if ( m{^commit ($::sha1)$} ) {
1974 next unless s{^\s*(git-svn-id:)}{$1};
1975 my ($url, $rev, $uuid) = ::extract_metadata($_);
1976 remove_username($url);
1978 # ignore merges (from set-tree)
1979 next if (!defined $rev || !$uuid);
1981 # if we merged or otherwise started elsewhere, this is
1982 # how we break out of it
1983 if (($uuid ne $svn_uuid) ||
1984 ($metadata_url && $url && ($url ne $metadata_url))) {
1987 if ($partial && $head) {
1988 print "Partial-rebuilding $map_path ...\n";
1989 print "Currently at $base_rev = $head\n";
1993 $self->rev_map_set($rev, $c);
1994 print "r$rev = $c\n";
1996 command_close_pipe($log, $ctx);
1997 print "Done rebuilding $map_path\n" if (!$partial || !$head);
1998 my $rev_db_path = $self->rev_db_path;
1999 if (-f $self->rev_db_path) {
2000 unlink $self->rev_db_path or croak "unlink: $!";
2002 $self->unlink_rev_db_symlink;
2006 # Tie::File seems to be prone to offset errors if revisions get sparse,
2007 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2008 # one of my favorite modules is out :< Next up would be one of the DBM
2009 # modules, but I'm not sure which is most portable...
2011 # This is the replacement for the rev_db format, which was too big
2012 # and inefficient for large repositories with a lot of sparse history
2015 # The format is this:
2016 # - 24 bytes for every record,
2017 # * 4 bytes for the integer representing an SVN revision number
2018 # * 20 bytes representing the sha1 of a git commit
2019 # - No empty padding records like the old format
2020 # (except the last record, which can be overwritten)
2021 # - new records are written append-only since SVN revision numbers
2022 # increase monotonically
2023 # - lookups on SVN revision number are done via a binary search
2024 # - Piping the file to xxd -c24 is a good way of dumping it for
2025 # viewing or editing (piped back through xxd -r), should the need
2027 # - The last record can be padding revision with an all-zero sha1
2028 # This is used to optimize fetch performance when using multiple
2029 # "fetch" directives in .git/config
2031 # These files are disposable unless noMetadata or useSvmProps is set
2034 my ($fh, $rev, $commit) = @_;
2036 binmode $fh or croak "binmode: $!";
2037 my $size = (stat($fh))[7];
2038 ($size % 24) == 0 or croak "inconsistent size: $size";
2042 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2043 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2044 $read == 24 or croak "read only $read bytes (!= 24)";
2045 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2046 if ($last_commit eq ('0' x40)) {
2048 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2049 $read = sysread($fh, $buf, 24) or
2052 croak "read only $read bytes (!= 24)";
2053 ($last_rev, $last_commit) =
2054 unpack(rev_map_fmt, $buf);
2055 if ($last_commit eq ('0' x40)) {
2056 croak "inconsistent .rev_map\n";
2059 if ($last_rev >= $rev) {
2060 croak "last_rev is higher!: $last_rev >= $rev";
2065 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2066 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2070 sub _rev_map_reset {
2071 my ($fh, $rev, $commit) = @_;
2072 my $c = _rev_map_get($fh, $rev);
2073 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
2074 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
2075 truncate $fh, $offset or croak "truncate: $!";
2081 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2082 mkpath([$dir]) unless -d $dir;
2083 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2084 close $fh or die "Couldn't close (create) $path: $!\n";
2089 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2090 defined $commit or die "missing arg3\n";
2091 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2092 my $db = $self->map_path($uuid);
2093 my $db_lock = "$db.lock";
2097 $sigmask = POSIX::SigSet->new();
2098 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
2099 SIGALRM, SIGUSR1, SIGUSR2);
2100 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
2101 croak "Can't block signals: $!";
2105 $LOCKFILES{$db_lock} = 1;
2107 # both of these options make our .rev_db file very, very important
2108 # and we can't afford to lose it because rebuild() won't work
2109 if ($self->use_svm_props || $self->no_metadata) {
2111 copy($db, $db_lock) or die "rev_map_set(@_): ",
2113 "$db => $db_lock ($!)\n";
2115 rename $db, $db_lock or die "rev_map_set(@_): ",
2116 "Failed to rename: ",
2117 "$db => $db_lock ($!)\n";
2120 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2121 or croak "Couldn't open $db_lock: $!\n";
2122 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
2123 _rev_map_set($fh, $rev, $commit);
2125 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2126 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2128 close $fh or croak $!;
2132 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
2133 command_noisy('update-ref', '-m', "r$rev$note",
2134 $self->refname, $commit);
2136 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2137 "$db_lock => $db ($!)\n";
2138 delete $LOCKFILES{$db_lock};
2140 sigprocmask(SIG_SETMASK, $sigmask) or
2141 croak "Can't restore signal mask: $!";
2145 # If want_commit, this will return an array of (rev, commit) where
2146 # commit _must_ be a valid commit in the archive.
2147 # Otherwise, it'll return the max revision (whether or not the
2148 # commit is valid or just a 0x40 placeholder).
2150 my ($self, $want_commit) = @_;
2152 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2153 $want_commit ? ($r, $c) : $r;
2156 sub rev_map_max_norebuild {
2157 my ($self, $want_commit) = @_;
2158 my $map_path = $self->map_path;
2159 stat $map_path or return $want_commit ? (0, undef) : 0;
2160 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2161 binmode $fh or croak "binmode: $!";
2162 my $size = (stat($fh))[7];
2163 ($size % 24) == 0 or croak "inconsistent size: $size";
2166 close $fh or croak "close: $!";
2167 return $want_commit ? (0, undef) : 0;
2170 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2171 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2172 my ($r, $c) = unpack(rev_map_fmt, $buf);
2173 if ($want_commit && $c eq ('0' x40)) {
2175 return $want_commit ? (0, undef) : 0;
2177 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2178 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2179 ($r, $c) = unpack(rev_map_fmt, $buf);
2180 if ($c eq ('0'x40)) {
2181 croak "Penultimate record is all-zeroes in $map_path";
2184 close $fh or croak "close: $!";
2185 $want_commit ? ($r, $c) : $r;
2189 my ($self, $rev, $uuid) = @_;
2190 my $map_path = $self->map_path($uuid);
2191 return undef unless -e $map_path;
2193 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2194 my $c = _rev_map_get($fh, $rev);
2195 close($fh) or croak "close: $!";
2200 my ($fh, $rev) = @_;
2202 binmode $fh or croak "binmode: $!";
2203 my $size = (stat($fh))[7];
2204 ($size % 24) == 0 or croak "inconsistent size: $size";
2210 my ($l, $u) = (0, $size - 24);
2214 my $i = int(($l/24 + $u/24) / 2) * 24;
2215 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2216 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2217 my ($r, $c) = unpack(rev_map_fmt, $buf);
2221 } elsif ($r > $rev) {
2223 } else { # $r == $rev
2224 return $c eq ('0' x 40) ? undef : $c;
2230 # Finds the first svn revision that exists on (if $eq_ok is true) or
2231 # before $rev for the current branch. It will not search any lower
2232 # than $min_rev. Returns the git commit hash and svn revision number
2233 # if found, else (undef, undef).
2234 sub find_rev_before {
2235 my ($self, $rev, $eq_ok, $min_rev) = @_;
2236 --$rev unless $eq_ok;
2238 my $max_rev = $self->rev_map_max;
2239 $rev = $max_rev if ($rev > $max_rev);
2240 while ($rev >= $min_rev) {
2241 if (my $c = $self->rev_map_get($rev)) {
2246 return (undef, undef);
2249 # Finds the first svn revision that exists on (if $eq_ok is true) or
2250 # after $rev for the current branch. It will not search any higher
2251 # than $max_rev. Returns the git commit hash and svn revision number
2252 # if found, else (undef, undef).
2253 sub find_rev_after {
2254 my ($self, $rev, $eq_ok, $max_rev) = @_;
2255 ++$rev unless $eq_ok;
2256 $max_rev ||= $self->rev_map_max;
2257 while ($rev <= $max_rev) {
2258 if (my $c = $self->rev_map_get($rev)) {
2263 return (undef, undef);
2267 my ($class, $repo_id, $ref_id, $path) = @_;
2268 unless (defined $repo_id && length $repo_id) {
2269 $repo_id = $default_repo_id;
2271 unless (defined $ref_id && length $ref_id) {
2272 # Access the prefix option from the git-svn main program if it's loaded.
2273 my $prefix = defined &::opt_prefix ? ::opt_prefix() : "";
2275 "refs/remotes/$prefix$default_ref_id";
2278 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2280 # Older repos imported by us used $GIT_DIR/svn/foo instead of
2281 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
2282 if ($ref_id =~ m{^refs/remotes/(.*)}) {
2283 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
2284 if (-d $old_dir && ! -d $dir) {
2289 $_[3] = $path = '' unless (defined $path);
2292 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2293 config => "$ENV{GIT_DIR}/svn/config",
2294 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2296 # Ensure it gets canonicalized
2307 $self->{path} = $path;
2311 return $self->{path};
2319 $self->{url} = $url;
2323 return $self->{url};
2326 # for read-only access of old .rev_db formats
2327 sub unlink_rev_db_symlink {
2329 my $link = $self->rev_db_path;
2330 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2332 unlink $link or croak "unlink: $link failed!";
2337 my ($self, $uuid) = @_;
2338 my $db_path = $self->map_path($uuid);
2339 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2340 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2344 # the new replacement for .rev_db
2346 my ($self, $uuid) = @_;
2347 $uuid ||= $self->ra_uuid;
2348 "$self->{map_root}.$uuid";
2353 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2359 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
2363 sub remove_username {
2364 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};