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(fatal can_compress);
30 $can_use_yaml = eval { require Git::SVN::Memoize::YAML; 1};
33 our $_follow_parent = 1;
34 our $_minimize_url = 'unset';
35 our $default_repo_id = 'svn';
36 our $default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
38 my ($_gc_nr, $_gc_period);
40 # properties that we do not log:
43 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
44 svn:special svn:executable
45 svn:entry:committed-rev
48 svn:entry:committed-date/;
50 # some options are read globally, but can be overridden locally
51 # per [svn-remote "..."] section. Command-line options will *NOT*
52 # override options set in an [svn-remote "..."] section
54 for my $option (qw/follow_parent no_metadata use_svm_props
58 my $prop = "-$option";
61 return $self->{$prop} if exists $self->{$prop};
62 my $k = "svn-remote.$self->{repo_id}.$key";
63 eval { command_oneline(qw/config --get/, $k) };
65 $self->{$prop} = ${"Git::SVN::_$option"};
67 my $v = command_oneline(qw/config --bool/,$k);
68 $self->{$prop} = $v eq 'false' ? 0 : 1;
70 return $self->{$prop};
76 my (%LOCKFILES, %INDEX_FILES);
78 unlink keys %LOCKFILES if %LOCKFILES;
79 unlink keys %INDEX_FILES if %INDEX_FILES;
82 sub resolve_local_globs {
83 my ($url, $fetch, $glob_spec) = @_;
84 return unless defined $glob_spec;
85 my $ref = $glob_spec->{ref};
86 my $path = $glob_spec->{path};
87 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
88 next unless m#^$ref->{regex}$#;
90 my $pathname = desanitize_refname($path->full_path($p));
91 my $refname = desanitize_refname($ref->full_path($p));
92 if (my $existing = $fetch->{$pathname}) {
93 if ($existing ne $refname) {
94 die "Refspec conflict:\n",
95 "existing: $existing\n",
96 " globbed: $refname\n";
98 my $u = (::cmt_metadata("$refname"))[0];
99 $u =~ s!^\Q$url\E(/|$)!! or die
100 "$refname: '$url' not found in '$u'\n";
101 if ($pathname ne $u) {
102 warn "W: Refspec glob conflict ",
103 "(ref: $refname):\n",
104 "expected path: $pathname\n",
106 "Continuing ahead with $u\n";
110 $fetch->{$pathname} = $refname;
115 sub parse_revision_argument {
116 my ($base, $head) = @_;
117 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
118 return ($base, $head);
120 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
121 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
122 return ($head, $head) if ($::_revision eq 'HEAD');
123 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
124 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
125 die "revision argument: $::_revision not understood by git-svn\n";
129 my ($repo_id, $remotes) = @_;
133 $repo_id = $gs->{repo_id};
135 $remotes ||= read_all_remotes();
136 my $remote = $remotes->{$repo_id} or
137 die "[svn-remote \"$repo_id\"] unknown\n";
138 my $fetch = $remote->{fetch};
139 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
141 my $ra = Git::SVN::Ra->new($url);
142 my $uuid = $ra->get_uuid;
143 my $head = $ra->get_latest_revnum;
145 # ignore errors, $head revision may not even exist anymore
146 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
147 warn "W: $@\n" if $@;
149 my $base = defined $fetch ? $head : 0;
151 # read the max revs for wildcard expansion (branches/*, tags/*)
152 foreach my $t (qw/branches tags/) {
153 defined $remote->{$t} or next;
154 push @globs, @{$remote->{$t}};
156 my $max_rev = eval { tmp_config(qw/--int --get/,
157 "svn-remote.$repo_id.${t}-maxRev") };
158 if (defined $max_rev && ($max_rev < $base)) {
160 } elsif (!defined $max_rev) {
166 foreach my $p (sort keys %$fetch) {
167 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
168 my $lr = $gs->rev_map_max;
170 $base = $lr if ($lr < $base);
176 ($base, $head) = parse_revision_argument($base, $head);
177 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
180 sub read_all_remotes {
182 my $use_svm_props = eval { command_oneline(qw/config --bool
184 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
185 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
186 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
187 if (m!^(.+)\.fetch=$svn_refspec$!) {
188 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
189 die("svn-remote.$remote: remote ref '$remote_ref' "
190 . "must start with 'refs/'\n")
191 unless $remote_ref =~ m{^refs/};
192 $local_ref = uri_decode($local_ref);
193 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
194 $r->{$remote}->{svm} = {} if $use_svm_props;
195 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
196 $r->{$1}->{svm} = {};
197 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
198 $r->{$1}->{url} = $2;
199 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
200 $r->{$1}->{pushurl} = $2;
201 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
202 $r->{$1}->{ignore_refs_regex} = $2;
203 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
204 my ($remote, $t, $local_ref, $remote_ref) =
206 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
207 . "must start with 'refs/'\n")
208 unless $remote_ref =~ m{^refs/};
209 $local_ref = uri_decode($local_ref);
213 path => Git::SVN::GlobSpec->new($local_ref, 1),
214 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
215 if (length($rs->{ref}->{right}) != 0) {
216 die "The '*' glob character must be the last ",
217 "character of '$remote_ref'\n";
219 push @{ $r->{$remote}->{$t} }, $rs;
224 if (defined $r->{$_}->{svm}) {
227 my $section = "svn-remote.$_";
229 source => tmp_config('--get',
230 "$section.svm-source"),
231 replace => tmp_config('--get',
232 "$section.svm-replace"),
235 $r->{$_}->{svm} = $svm;
239 foreach my $remote (keys %$r) {
240 foreach ( grep { defined $_ }
241 map { $r->{$remote}->{$_} } qw(branches tags) ) {
242 foreach my $rs ( @$_ ) {
243 $rs->{ignore_refs_regex} =
244 $r->{$remote}->{ignore_refs_regex};
253 $_gc_nr = $_gc_period = 1000;
254 if (defined $_repack || defined $_repack_flags) {
255 warn "Repack options are obsolete; they have no effect.\n";
259 sub verify_remotes_sanity {
260 return unless -d $ENV{GIT_DIR};
262 foreach (command(qw/config -l/)) {
263 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
265 die "Remote ref refs/remote/$1 is tracked by",
266 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
267 "Please resolve this ambiguity in ",
268 "your git configuration file before ",
276 sub find_existing_remote {
277 my ($url, $remotes) = @_;
278 return undef if $no_reuse_existing;
280 foreach my $repo_id (keys %$remotes) {
281 my $u = $remotes->{$repo_id}->{url} or next;
283 $existing = $repo_id;
289 sub init_remote_config {
290 my ($self, $url, $no_write) = @_;
291 $url =~ s!/+$!!; # strip trailing slash
292 my $r = read_all_remotes();
293 my $existing = find_existing_remote($url, $r);
296 print STDERR "Using existing ",
297 "[svn-remote \"$existing\"]\n";
299 $self->{repo_id} = $existing;
300 } elsif ($_minimize_url) {
301 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
302 $existing = find_existing_remote($min_url, $r);
305 print STDERR "Using existing ",
306 "[svn-remote \"$existing\"]\n";
308 $self->{repo_id} = $existing;
310 if ($min_url ne $url) {
312 print STDERR "Using higher level of URL: ",
313 "$url => $min_url\n";
315 my $old_path = $self->{path};
316 $self->{path} = $url;
317 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
318 if (length $old_path) {
319 $self->{path} .= "/$old_path";
326 # verify that we aren't overwriting anything:
328 command_oneline('config', '--get',
329 "svn-remote.$self->{repo_id}.url")
331 if ($orig_url && ($orig_url ne $url)) {
332 die "svn-remote.$self->{repo_id}.url already set: ",
333 "$orig_url\nwanted to set to: $url\n";
336 my ($xrepo_id, $xpath) = find_ref($self->refname);
337 if (!$no_write && defined $xpath) {
338 die "svn-remote.$xrepo_id.fetch already set to track ",
339 "$xpath:", $self->refname, "\n";
342 command_noisy('config',
343 "svn-remote.$self->{repo_id}.url", $url);
344 $self->{path} =~ s{^/}{};
345 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
346 command_noisy('config', '--add',
347 "svn-remote.$self->{repo_id}.fetch",
348 "$self->{path}:".$self->refname);
353 sub find_by_url { # repos_root and, path are optional
354 my ($class, $full_url, $repos_root, $path) = @_;
356 return undef unless defined $full_url;
357 remove_username($full_url);
358 remove_username($repos_root) if defined $repos_root;
359 my $remotes = read_all_remotes();
360 if (defined $full_url && defined $repos_root && !defined $path) {
362 $path =~ s#^\Q$repos_root\E(?:/|$)##;
364 foreach my $repo_id (keys %$remotes) {
365 my $u = $remotes->{$repo_id}->{url} or next;
367 next if defined $repos_root && $repos_root ne $u;
369 my $fetch = $remotes->{$repo_id}->{fetch} || {};
370 foreach my $t (qw/branches tags/) {
371 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
372 resolve_local_globs($u, $fetch, $globspec);
376 my $rwr = rewrite_root({repo_id => $repo_id});
377 my $svm = $remotes->{$repo_id}->{svm}
378 if defined $remotes->{$repo_id}->{svm};
379 unless (defined $p) {
386 } elsif (defined $svm) {
388 $prefix = $svm->{replace};
389 $prefix =~ s#^\Q$u\E(?:/|$)##;
392 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
394 foreach my $f (keys %$fetch) {
396 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
403 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
404 my $self = _new($class, $repo_id, $ref_id, $path);
406 $self->init_remote_config($url, $no_write);
413 foreach (command(qw/config -l/)) {
414 next unless m!^svn-remote\.(.+)\.fetch=
415 \s*(.*?)\s*:\s*(.+?)\s*$!x;
416 my ($repo_id, $path, $ref) = ($1, $2, $3);
417 if ($ref eq $ref_id) {
418 $path = '' if ($path =~ m#^\./?#);
419 return ($repo_id, $path);
422 (undef, undef, undef);
426 my ($class, $ref_id, $repo_id, $path) = @_;
427 if (defined $ref_id && !defined $repo_id && !defined $path) {
428 ($repo_id, $path) = find_ref($ref_id);
429 if (!defined $repo_id) {
430 die "Could not find a \"svn-remote.*.fetch\" key ",
431 "in the repository configuration matching: ",
435 my $self = _new($class, $repo_id, $ref_id, $path);
436 if (!defined $self->{path} || !length $self->{path}) {
437 my $fetch = command_oneline('config', '--get',
438 "svn-remote.$repo_id.fetch",
440 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
441 "\":$ref_id\$\" in config\n";
442 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
444 $self->{path} =~ s{/+}{/}g;
445 $self->{path} =~ s{\A/}{};
446 $self->{path} =~ s{/\z}{};
447 $self->{url} = command_oneline('config', '--get',
448 "svn-remote.$repo_id.url") or
449 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
450 $self->{pushurl} = eval { command_oneline('config', '--get',
451 "svn-remote.$repo_id.pushurl") };
457 my ($refname) = $_[0]->{ref_id} ;
459 # It cannot end with a slash /, we'll throw up on this because
460 # SVN can't have directories with a slash in their name, either:
461 if ($refname =~ m{/$}) {
462 die "ref: '$refname' ends with a trailing slash, this is ",
463 "not permitted by git nor Subversion\n";
466 # It cannot have ASCII control character space, tilde ~, caret ^,
467 # colon :, question-mark ?, asterisk *, space, or open bracket [
470 # Additionally, % must be escaped because it is used for escaping
471 # and we want our escaped refname to be reversible
472 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
474 # no slash-separated component can begin with a dot .
476 $refname =~ s{/\.}{/%2E}g;
478 # It cannot have two consecutive dots .. anywhere
480 $refname =~ s{\.\.}{%2E%2E}g;
482 # trailing dots and .lock are not allowed
483 # .$ becomes %2E and .lock becomes %2Elock
484 $refname =~ s{\.(?=$|lock$)}{%2E};
486 # the sequence @{ is used to access the reflog
488 $refname =~ s{\@\{}{%40\{}g;
493 sub desanitize_refname {
495 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
501 return $self->{svm}->{uuid} if $self->svm;
503 unless ($self->{svm}) {
504 die "SVM UUID not cached, and reading remotely failed\n";
506 $self->{svm}->{uuid};
511 return $self->{svm} if $self->{svm};
513 # see if we have it in our config, first:
515 my $section = "svn-remote.$self->{repo_id}";
517 source => tmp_config('--get', "$section.svm-source"),
518 uuid => tmp_config('--get', "$section.svm-uuid"),
519 replace => tmp_config('--get', "$section.svm-replace"),
522 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
529 my ($self, $ra) = @_;
530 return $ra if $self->svm;
532 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
533 "(svm:source, svm:uuid) ",
534 "from the following URLs:\n" );
536 my ($self, $ra, $path, $r) = @_;
537 my $props = ($ra->get_dir($path, $r))[2];
538 my $src = $props->{'svm:source'};
539 my $uuid = $props->{'svm:uuid'};
540 return undef if (!$src || !$uuid);
544 $uuid =~ m{^[0-9a-f\-]{30,}$}i
545 or die "doesn't look right - svm:uuid is '$uuid'\n";
547 # the '!' is used to mark the repos_root!/relative/path
549 $src =~ s{/+$}{}; # no trailing slashes please
550 # username is of no interest
551 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
553 my $replace = $ra->{url};
554 $replace .= "/$path" if length $path;
556 my $section = "svn-remote.$self->{repo_id}";
557 tmp_config("$section.svm-source", $src);
558 tmp_config("$section.svm-replace", $replace);
559 tmp_config("$section.svm-uuid", $uuid);
567 my $r = $ra->get_latest_revnum;
568 my $path = $self->{path};
570 while (length $path) {
571 unless ($tried{"$self->{url}/$path"}) {
572 return $ra if $self->read_svm_props($ra, $path, $r);
573 $tried{"$self->{url}/$path"} = 1;
575 $path =~ s#/?[^/]+$##;
577 die "Path: '$path' should be ''\n" if $path ne '';
578 return $ra if $self->read_svm_props($ra, $path, $r);
579 $tried{"$self->{url}/$path"} = 1;
581 if ($ra->{repos_root} eq $self->{url}) {
582 die @err, (map { " $_\n" } keys %tried), "\n";
585 # nope, make sure we're connected to the repository root:
588 $path = $ra->{svn_path};
589 $ra = Git::SVN::Ra->new($ra->{repos_root});
590 while (length $path) {
591 unless ($tried{"$ra->{url}/$path"}) {
592 $ok = $self->read_svm_props($ra, $path, $r);
594 $tried{"$ra->{url}/$path"} = 1;
596 $path =~ s#/?[^/]+$##;
598 die "Path: '$path' should be ''\n" if $path ne '';
599 $ok ||= $self->read_svm_props($ra, $path, $r);
600 $tried{"$ra->{url}/$path"} = 1;
602 die @err, (map { " $_\n" } keys %tried), "\n";
604 Git::SVN::Ra->new($self->{url});
609 return $self->{svnsync} if $self->{svnsync};
611 if ($self->no_metadata) {
612 die "Can't have both 'noMetadata' and ",
613 "'useSvnsyncProps' options set!\n";
615 if ($self->rewrite_root) {
616 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
619 if ($self->rewrite_uuid) {
620 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
625 # see if we have it in our config, first:
627 my $section = "svn-remote.$self->{repo_id}";
629 my $url = tmp_config('--get', "$section.svnsync-url");
630 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
631 die "doesn't look right - svn:sync-from-url is '$url'\n";
633 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
634 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
635 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
637 $svnsync = { url => $url, uuid => $uuid }
639 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
640 return $self->{svnsync} = $svnsync;
643 my $err = "useSvnsyncProps set, but failed to read " .
644 "svnsync property: svn:sync-from-";
645 my $rp = $self->ra->rev_proplist(0);
647 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
648 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
649 die "doesn't look right - svn:sync-from-url is '$url'\n";
651 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
652 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
653 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
655 my $section = "svn-remote.$self->{repo_id}";
656 tmp_config('--add', "$section.svnsync-uuid", $uuid);
657 tmp_config('--add', "$section.svnsync-url", $url);
658 return $self->{svnsync} = { url => $url, uuid => $uuid };
661 # this allows us to memoize our SVN::Ra UUID locally and avoid a
662 # remote lookup (useful for 'git svn log').
665 unless ($self->{ra_uuid}) {
666 my $key = "svn-remote.$self->{repo_id}.uuid";
667 my $uuid = eval { tmp_config('--get', $key) };
668 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
669 $self->{ra_uuid} = $uuid;
671 die "ra_uuid called without URL\n" unless $self->{url};
672 $self->{ra_uuid} = $self->ra->get_uuid;
673 tmp_config('--add', $key, $self->{ra_uuid});
679 sub _set_repos_root {
680 my ($self, $repos_root) = @_;
681 my $k = "svn-remote.$self->{repo_id}.reposRoot";
682 $repos_root ||= $self->ra->{repos_root};
683 tmp_config($k, $repos_root);
689 my $k = "svn-remote.$self->{repo_id}.reposRoot";
690 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
695 my $ra = Git::SVN::Ra->new($self->{url});
696 $self->_set_repos_root($ra->{repos_root});
697 if ($self->use_svm_props && !$self->{svm}) {
698 if ($self->no_metadata) {
699 die "Can't have both 'noMetadata' and ",
700 "'useSvmProps' options set!\n";
701 } elsif ($self->use_svnsync_props) {
702 die "Can't have both 'useSvnsyncProps' and ",
703 "'useSvmProps' options set!\n";
705 $ra = $self->_set_svm_vars($ra);
706 $self->{-want_revprops} = 1;
711 # prop_walk(PATH, REV, SUB)
712 # -------------------------
713 # Recursively traverse PATH at revision REV and invoke SUB for each
714 # directory that contains a SVN property. SUB will be invoked as
715 # follows: &SUB(gs, path, props); where `gs' is this instance of
716 # Git::SVN, `path' the path to the directory where the properties
717 # `props' were found. The `path' will be relative to point of checkout,
718 # that is, if url://repo/trunk is the current Git branch, and that
719 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
720 # as `path' (note the trailing `/').
722 my ($self, $path, $rev, $sub) = @_;
725 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
728 # Strip the irrelevant part of the path.
729 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
730 # Ensure the path is terminated by a `/'.
733 # The properties contain all the internal SVN stuff nobody
734 # (usually) cares about.
735 my $interesting_props = 0;
736 foreach (keys %{$props}) {
737 # If it doesn't start with `svn:', it must be a
738 # user-defined property.
739 ++$interesting_props and next if $_ !~ /^svn:/;
740 # FIXME: Fragile, if SVN adds new public properties,
741 # this needs to be updated.
742 ++$interesting_props if /^svn:(?:ignore|keywords|executable
744 |externals|needs-lock)$/x;
746 &$sub($self, $p, $props) if $interesting_props;
748 foreach (sort keys %$dirent) {
749 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
750 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
754 sub last_rev { ($_[0]->last_rev_commit)[0] }
755 sub last_commit { ($_[0]->last_rev_commit)[1] }
757 # returns the newest SVN revision number and newest commit SHA1
758 sub last_rev_commit {
760 if (defined $self->{last_rev} && defined $self->{last_commit}) {
761 return ($self->{last_rev}, $self->{last_commit});
763 my $c = ::verify_ref($self->refname.'^0');
764 if ($c && !$self->use_svm_props && !$self->no_metadata) {
765 my $rev = (::cmt_metadata($c))[1];
767 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
771 my $map_path = $self->map_path;
772 unless (-e $map_path) {
773 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
774 return (undef, undef);
776 my ($rev, $commit) = $self->rev_map_max(1);
777 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
778 return ($rev, $commit);
781 sub get_fetch_range {
782 my ($self, $min, $max) = @_;
783 $max ||= $self->ra->get_latest_revnum;
784 $min ||= $self->rev_map_max;
790 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
791 my $config = "$ENV{GIT_DIR}/svn/.metadata";
792 if (! -f $config && -f $old_def_config) {
793 rename $old_def_config, $config or
794 die "Failed rename $old_def_config => $config: $!\n";
796 my $old_config = $ENV{GIT_CONFIG};
797 $ENV{GIT_CONFIG} = $config;
800 unless (-f $config) {
802 open my $fh, '>', $config or
803 die "Can't open $config: $!\n";
804 print $fh "; This file is used internally by ",
806 "Couldn't write to $config: $!\n";
807 print $fh "; You should not have to edit it\n" or
808 die "Couldn't write to $config: $!\n";
809 close $fh or die "Couldn't close $config: $!\n";
811 command('config', @args);
814 if (defined $old_config) {
815 $ENV{GIT_CONFIG} = $old_config;
817 delete $ENV{GIT_CONFIG};
820 wantarray ? @ret : $ret[0];
824 my ($self, $sub) = @_;
825 my $old_index = $ENV{GIT_INDEX_FILE};
826 $ENV{GIT_INDEX_FILE} = $self->{index};
829 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
830 mkpath([$dir]) unless -d $dir;
834 if (defined $old_index) {
835 $ENV{GIT_INDEX_FILE} = $old_index;
837 delete $ENV{GIT_INDEX_FILE};
840 wantarray ? @ret : $ret[0];
843 sub assert_index_clean {
844 my ($self, $treeish) = @_;
846 $self->tmp_index_do(sub {
847 command_noisy('read-tree', $treeish) unless -e $self->{index};
848 my $x = command_oneline('write-tree');
849 my ($y) = (command(qw/cat-file commit/, $treeish) =~
850 /^tree ($::sha1)/mo);
853 warn "Index mismatch: $y != $x\nrereading $treeish\n";
854 unlink $self->{index} or die "unlink $self->{index}: $!\n";
855 command_noisy('read-tree', $treeish);
856 $x = command_oneline('write-tree');
858 fatal "trees ($treeish) $y != $x\n",
859 "Something is seriously wrong...";
864 sub get_commit_parents {
865 my ($self, $log_entry) = @_;
866 my (%seen, @ret, @tmp);
867 # legacy support for 'set-tree'; this is only used by set_tree_cb:
868 if (my $ip = $self->{inject_parents}) {
869 if (my $commit = delete $ip->{$log_entry->{revision}}) {
873 if (my $cur = ::verify_ref($self->refname.'^0')) {
876 if (my $ipd = $self->{inject_parents_dcommit}) {
877 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
881 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
882 while (my $p = shift @tmp) {
892 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
893 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
894 my $rwr = eval { command_oneline(qw/config --get/, $k) };
897 if ($rwr !~ m#^[a-z\+]+://#) {
898 die "$rwr is not a valid URL (key: $k)\n";
901 $self->{-rewrite_root} = $rwr;
906 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
907 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
908 my $rwid = eval { command_oneline(qw/config --get/, $k) };
911 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
912 die "$rwid is not a valid UUID (key: $k)\n";
915 $self->{-rewrite_uuid} = $rwid;
920 ($self->rewrite_root || $self->{url}) .
921 (length $self->{path} ? '/' . $self->{path} : '');
926 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
931 if ($self->{pushurl}) {
932 return $self->{pushurl} . (length $self->{path} ? '/' .
935 return $self->full_url;
939 sub set_commit_header_env {
940 my ($log_entry) = @_;
942 foreach my $ned (qw/NAME EMAIL DATE/) {
943 foreach my $ac (qw/AUTHOR COMMITTER/) {
944 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
948 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
949 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
950 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
952 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
953 ? $log_entry->{commit_name}
954 : $log_entry->{name};
955 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
956 ? $log_entry->{commit_email}
957 : $log_entry->{email};
961 sub restore_commit_header_env {
963 foreach my $ned (qw/NAME EMAIL DATE/) {
964 foreach my $ac (qw/AUTHOR COMMITTER/) {
965 my $k = "GIT_${ac}_${ned}";
966 if (defined $env->{$k}) {
967 $ENV{$k} = $env->{$k};
976 command_noisy('gc', '--auto');
980 my ($self, $log_entry) = @_;
981 my $lr = $self->last_rev;
982 if (defined $lr && $lr >= $log_entry->{revision}) {
983 die "Last fetched revision of ", $self->refname,
984 " was r$lr, but we are about to fetch: ",
985 "r$log_entry->{revision}!\n";
987 if (my $c = $self->rev_map_get($log_entry->{revision})) {
988 croak "$log_entry->{revision} = $c already exists! ",
989 "Why are we refetching it?\n";
991 my $old_env = set_commit_header_env($log_entry);
992 my $tree = $log_entry->{tree};
993 if (!defined $tree) {
994 $tree = $self->tmp_index_do(sub {
995 command_oneline('write-tree') });
997 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
999 my @exec = ('git', 'commit-tree', $tree);
1000 foreach ($self->get_commit_parents($log_entry)) {
1001 push @exec, '-p', $_;
1003 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1007 # we always get UTF-8 from SVN, but we may want our commits in
1008 # a different encoding.
1009 if (my $enc = Git::config('i18n.commitencoding')) {
1011 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
1013 print $msg_fh $log_entry->{log} or croak $!;
1014 restore_commit_header_env($old_env);
1015 unless ($self->no_metadata) {
1016 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1019 $msg_fh->flush == 0 or croak $!;
1020 close $msg_fh or croak $!;
1021 chomp(my $commit = do { local $/; <$out_fh> });
1022 close $out_fh or croak $!;
1025 if ($commit !~ /^$::sha1$/o) {
1026 die "Failed to commit, invalid sha1: $commit\n";
1029 $self->rev_map_set($log_entry->{revision}, $commit, 1);
1031 $self->{last_rev} = $log_entry->{revision};
1032 $self->{last_commit} = $commit;
1033 print "r$log_entry->{revision}" unless $::_q > 1;
1034 if (defined $log_entry->{svm_revision}) {
1035 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
1036 $self->rev_map_set($log_entry->{svm_revision}, $commit,
1037 0, $self->svm_uuid);
1039 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
1040 if (--$_gc_nr == 0) {
1041 $_gc_nr = $_gc_period;
1048 my ($self, $paths, $r) = @_;
1049 return 1 if $self->{path} eq '';
1050 if (my $path = $paths->{"/$self->{path}"}) {
1051 return ($path->{action} eq 'D') ? 0 : 1;
1053 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1054 if (grep /$self->{path_regex}/, keys %$paths) {
1058 foreach (split m#/#, $self->{path}) {
1060 next unless ($paths->{$c} &&
1061 ($paths->{$c}->{action} =~ /^[AR]$/));
1062 if ($self->ra->check_path($self->{path}, $r) ==
1070 sub find_parent_branch {
1071 my ($self, $paths, $rev) = @_;
1072 return undef unless $self->follow_parent;
1073 unless (defined $paths) {
1074 my $err_handler = $SVN::Error::handler;
1075 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1076 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
1077 sub { $paths = $_[0] });
1078 $SVN::Error::handler = $err_handler;
1080 return undef unless defined $paths;
1082 # look for a parent from another branch:
1083 my @b_path_components = split m#/#, $self->{path};
1084 my @a_path_components;
1086 while (@b_path_components) {
1087 $i = $paths->{'/'.join('/', @b_path_components)};
1088 last if $i && defined $i->{copyfrom_path};
1089 unshift(@a_path_components, pop(@b_path_components));
1091 return undef unless defined $i && defined $i->{copyfrom_path};
1092 my $branch_from = $i->{copyfrom_path};
1093 if (@a_path_components) {
1094 print STDERR "branch_from: $branch_from => ";
1095 $branch_from .= '/'.join('/', @a_path_components);
1096 print STDERR $branch_from, "\n";
1098 my $r = $i->{copyfrom_rev};
1099 my $repos_root = $self->ra->{repos_root};
1100 my $url = $self->ra->{url};
1101 my $new_url = $url . $branch_from;
1102 print STDERR "Found possible branch point: ",
1103 "$new_url => ", $self->full_url, ", $r\n"
1105 $branch_from =~ s#^/##;
1106 my $gs = $self->other_gs($new_url, $url,
1107 $branch_from, $r, $self->{ref_id});
1108 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1111 if (!defined $r0 || !defined $parent) {
1112 ($base, $head) = parse_revision_argument(0, $r);
1115 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
1116 0, 1, sub { $base = $_[1] - 1 });
1119 if (defined $base && $base <= $r) {
1120 $gs->fetch($base, $r);
1122 ($r0, $parent) = $gs->find_rev_before($r, 1);
1124 if (defined $r0 && defined $parent) {
1125 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
1128 if ($self->ra->can_do_switch) {
1129 $self->assert_index_clean($parent);
1130 print STDERR "Following parent with do_switch\n"
1132 # do_switch works with svn/trunk >= r22312, but that
1133 # is not included with SVN 1.4.3 (the latest version
1134 # at the moment), so we can't rely on it
1135 $self->{last_rev} = $r0;
1136 $self->{last_commit} = $parent;
1137 $ed = Git::SVN::Fetcher->new($self, $gs->{path});
1138 $gs->ra->gs_do_switch($r0, $rev, $gs,
1139 $self->full_url, $ed)
1140 or die "SVN connection failed somewhere...\n";
1141 } elsif ($self->ra->trees_match($new_url, $r0,
1142 $self->full_url, $rev)) {
1143 print STDERR "Trees match:\n",
1145 " ${\$self->full_url}\@$rev\n",
1146 "Following parent with no changes\n"
1148 $self->tmp_index_do(sub {
1149 command_noisy('read-tree', $parent);
1151 $self->{last_commit} = $parent;
1153 print STDERR "Following parent with do_update\n"
1155 $ed = Git::SVN::Fetcher->new($self);
1156 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1157 or die "SVN connection failed somewhere...\n";
1159 print STDERR "Successfully followed parent\n" unless $::_q > 1;
1160 return $self->make_log_entry($rev, [$parent], $ed);
1166 my ($self, $paths, $rev) = @_;
1168 my ($last_rev, @parents);
1169 if (my $lc = $self->last_commit) {
1170 # we can have a branch that was deleted, then re-added
1171 # under the same name but copied from another path, in
1172 # which case we'll have multiple parents (we don't
1173 # want to break the original ref, nor lose copypath info):
1174 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1175 push @{$log_entry->{parents}}, $lc;
1178 $ed = Git::SVN::Fetcher->new($self);
1179 $last_rev = $self->{last_rev};
1184 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1187 $ed = Git::SVN::Fetcher->new($self);
1189 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1190 die "SVN connection failed somewhere...\n";
1192 $self->make_log_entry($rev, \@parents, $ed);
1196 my ($self, $r) = @_;
1199 my ($r, $empty_dirs, $line) = @_;
1200 if (defined $r && $line =~ /^r(\d+)$/) {
1201 return 0 if $1 > $r;
1202 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
1203 $empty_dirs->{$1} = 1;
1204 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
1205 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
1206 delete @$empty_dirs{@d};
1211 my %empty_dirs = ();
1212 my $gz_file = "$self->{dir}/unhandled.log.gz";
1214 if (!can_compress()) {
1215 warn "Compress::Zlib could not be found; ",
1216 "empty directories in $gz_file will not be read\n";
1218 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
1219 die "Unable to open $gz_file: $!\n";
1221 while ($gz->gzreadline($line) > 0) {
1222 scan($r, \%empty_dirs, $line) or last;
1228 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
1229 binmode $fh or croak "binmode: $!";
1231 scan($r, \%empty_dirs, $_) or last;
1236 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
1237 foreach my $d (sort keys %empty_dirs) {
1238 $d = uri_decode($d);
1240 next unless length($d);
1243 warn "$d exists but is not a directory\n";
1245 print "creating empty directory: $d\n";
1252 my ($self, $ed) = @_;
1254 my $h = $ed->{empty};
1255 foreach (sort keys %$h) {
1256 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1257 push @out, " $act: " . uri_encode($_);
1258 warn "W: $act: $_\n";
1260 foreach my $t (qw/dir_prop file_prop/) {
1261 $h = $ed->{$t} or next;
1262 foreach my $path (sort keys %$h) {
1263 my $ppath = $path eq '' ? '.' : $path;
1264 foreach my $prop (sort keys %{$h->{$path}}) {
1265 next if $SKIP_PROP{$prop};
1266 my $v = $h->{$path}->{$prop};
1267 my $t_ppath_prop = "$t: " .
1268 uri_encode($ppath) . ' ' .
1271 push @out, " +$t_ppath_prop " .
1274 push @out, " -$t_ppath_prop";
1279 foreach my $t (qw/absent_file absent_directory/) {
1280 $h = $ed->{$t} or next;
1281 foreach my $parent (sort keys %$h) {
1282 foreach my $path (sort @{$h->{$parent}}) {
1283 push @out, " $t: " .
1284 uri_encode("$parent/$path");
1285 warn "W: $t: $parent/$path ",
1286 "Insufficient permissions?\n";
1294 # some systmes don't handle or mishandle %z, so be creative.
1295 my $t = shift || time;
1296 my $gm = timelocal(gmtime($t));
1297 my $sign = qw( + + - )[ $t <=> $gm ];
1298 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
1301 # parse_svn_date(DATE)
1302 # --------------------
1303 # Given a date (in UTC) from Subversion, return a string in the format
1304 # "<TZ Offset> <local date/time>" that Git will use.
1306 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
1307 # is true we'll convert it to the local timezone instead.
1308 sub parse_svn_date {
1309 my $date = shift || return '+0000 1970-01-01 00:00:00';
1310 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1311 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1312 croak "Unable to parse date: $date\n";
1313 my $parsed_date; # Set next.
1315 if ($Git::SVN::_localtime) {
1316 # Translate the Subversion datetime to an epoch time.
1317 # Begin by switching ourselves to $date's timezone, UTC.
1318 my $old_env_TZ = $ENV{TZ};
1322 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
1324 # Determine our local timezone (including DST) at the
1325 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
1326 # value of TZ, if any, at the time we were run.
1327 if (defined $Git::SVN::Log::TZ) {
1328 $ENV{TZ} = $Git::SVN::Log::TZ;
1333 my $our_TZ = get_tz();
1335 # This converts $epoch_in_UTC into our local timezone.
1336 my ($sec, $min, $hour, $mday, $mon, $year,
1337 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
1339 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
1340 $our_TZ, $year + 1900, $mon + 1,
1341 $mday, $hour, $min, $sec);
1343 # Reset us to the timezone in effect when we entered
1345 if (defined $old_env_TZ) {
1346 $ENV{TZ} = $old_env_TZ;
1351 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
1354 return $parsed_date;
1358 my ($self, $new_url, $url,
1359 $branch_from, $r, $old_ref_id) = @_;
1360 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
1362 my $ref_id = $old_ref_id;
1363 $ref_id =~ s/\@\d+-*$//;
1365 # just grow a tail if we're not unique enough :x
1366 $ref_id .= '-' while find_ref($ref_id);
1367 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
1368 if ($u =~ s#^\Q$url\E(/|$)##) {
1371 $repo_id = $self->{repo_id};
1374 # It is possible to tag two different subdirectories at
1375 # the same revision. If the url for an existing ref
1376 # does not match, we must either find a ref with a
1377 # matching url or create a new ref by growing a tail.
1378 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
1379 my (undef, $max_commit) = $gs->rev_map_max(1);
1380 last if (!$max_commit);
1381 my ($url) = ::cmt_metadata($max_commit);
1382 last if ($url eq $gs->metadata_url);
1385 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
1390 sub call_authors_prog {
1391 my ($orig_author) = @_;
1392 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
1393 my $author = `$::_authors_prog $orig_author`;
1395 die "$::_authors_prog failed with exit code $?\n"
1397 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
1398 my ($name, $email) = ($1, $2);
1399 $email = undef if length $2 == 0;
1400 return [$name, $email];
1402 die "Author: $orig_author: $::_authors_prog returned "
1403 . "invalid author format: $author\n";
1409 if (!defined $author || length $author == 0) {
1410 $author = '(no author)';
1412 if (!defined $::users{$author}) {
1413 if (defined $::_authors_prog) {
1414 $::users{$author} = call_authors_prog($author);
1415 } elsif (defined $::_authors) {
1416 die "Author: $author not defined in $::_authors file\n";
1422 sub find_extra_svk_parents {
1423 my ($self, $ed, $tickets, $parents) = @_;
1424 # aha! svk:merge property changed...
1425 my @tickets = split "\n", $tickets;
1427 for my $ticket ( @tickets ) {
1428 my ($uuid, $path, $rev) = split /:/, $ticket;
1429 if ( $uuid eq $self->ra_uuid ) {
1430 my $url = $self->{url};
1431 my $repos_root = $url;
1432 my $branch_from = $path;
1433 $branch_from =~ s{^/}{};
1434 my $gs = $self->other_gs($repos_root."/".$branch_from,
1439 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
1440 # wahey! we found it, but it might be
1442 push @known_parents, [ $rev, $commit ];
1446 # Ordering matters; highest-numbered commit merge tickets
1447 # first, as they may account for later merge ticket additions
1449 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
1450 for my $parent ( @known_parents ) {
1451 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
1452 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
1454 while ( <$msg_fh> ) {
1457 command_close_pipe($msg_fh, $ctx);
1460 "Found merge parent (svk:merge ticket): $parent\n";
1461 push @$parents, $parent;
1466 sub lookup_svn_merge {
1471 my ($source, $revs) = split ":", $merge;
1474 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
1476 warn "Couldn't find revmap for $url$source\n";
1479 my @ranges = split ",", $revs;
1480 my ($tip, $tip_commit);
1481 my @merged_commit_ranges;
1483 for my $range ( @ranges ) {
1484 my ($bottom, $top) = split "-", $range;
1486 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
1487 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
1489 unless ($top_commit and $bottom_commit) {
1490 warn "W:unknown path/rev in svn:mergeinfo "
1491 ."dirprop: $source:$range\n";
1495 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
1496 push @merged_commit_ranges,
1497 "$bottom_commit^..$top_commit";
1499 push @merged_commit_ranges, "$top_commit";
1502 if ( !defined $tip or $top > $tip ) {
1504 $tip_commit = $top_commit;
1507 return ($tip_commit, @merged_commit_ranges);
1511 my ($msg_fh, $ctx) = command_output_pipe(
1515 while ( <$msg_fh> ) {
1519 command_close_pipe($msg_fh, $ctx);
1523 sub check_cherry_pick {
1526 my $parents = shift;
1528 my %commits = map { $_ => 1 }
1529 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
1530 for my $range ( @ranges ) {
1531 delete @commits{_rev_list($range, "--")};
1533 for my $commit (keys %commits) {
1534 if (has_no_changes($commit)) {
1535 delete $commits{$commit};
1538 return (keys %commits);
1541 sub has_no_changes {
1544 my @revs = split / /, command_oneline(
1545 qw(rev-list --parents -1 -m), $commit);
1547 # Commits with no parents, e.g. the start of a partial branch,
1548 # have changes by definition.
1549 return 1 if (@revs < 2);
1551 # Commits with multiple parents, e.g a merge, have no changes
1553 return 0 if (@revs > 2);
1555 return (command_oneline("rev-parse", "$commit^{tree}") eq
1556 command_oneline("rev-parse", "$commit~1^{tree}"));
1559 sub tie_for_persistent_memoization {
1563 if ($can_use_yaml) {
1564 tie %$hash => 'Git::SVN::Memoize::YAML', "$path.yaml";
1566 tie %$hash => 'Memoize::Storable', "$path.db", 'nstore';
1570 # The GIT_DIR environment variable is not always set until after the command
1571 # line arguments are processed, so we can't memoize in a BEGIN block.
1575 sub memoize_svn_mergeinfo_functions {
1576 return if $memoized;
1579 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1580 mkpath([$cache_path]) unless -d $cache_path;
1582 my %lookup_svn_merge_cache;
1583 my %check_cherry_pick_cache;
1584 my %has_no_changes_cache;
1586 tie_for_persistent_memoization(\%lookup_svn_merge_cache,
1587 "$cache_path/lookup_svn_merge");
1588 memoize 'lookup_svn_merge',
1589 SCALAR_CACHE => 'FAULT',
1590 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
1593 tie_for_persistent_memoization(\%check_cherry_pick_cache,
1594 "$cache_path/check_cherry_pick");
1595 memoize 'check_cherry_pick',
1596 SCALAR_CACHE => 'FAULT',
1597 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
1600 tie_for_persistent_memoization(\%has_no_changes_cache,
1601 "$cache_path/has_no_changes");
1602 memoize 'has_no_changes',
1603 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
1604 LIST_CACHE => 'FAULT',
1608 sub unmemoize_svn_mergeinfo_functions {
1609 return if not $memoized;
1612 Memoize::unmemoize 'lookup_svn_merge';
1613 Memoize::unmemoize 'check_cherry_pick';
1614 Memoize::unmemoize 'has_no_changes';
1617 Memoize::memoize 'Git::SVN::repos_root';
1621 # Force cache writeout explicitly instead of waiting for
1622 # global destruction to avoid segfault in Storable:
1623 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
1624 unmemoize_svn_mergeinfo_functions();
1627 sub parents_exclude {
1628 my $parents = shift;
1630 return unless @commits;
1635 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
1636 $excluded = command_oneline(@cmd);
1640 for my $commit ( @commits ) {
1641 if ( $commit eq $excluded ) {
1642 push @excluded, $commit;
1650 die "saw commit '$excluded' in rev-list output, "
1651 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
1656 while ($excluded and @commits);
1662 # note: this function should only be called if the various dirprops
1663 # have actually changed
1664 sub find_extra_svn_parents {
1665 my ($self, $ed, $mergeinfo, $parents) = @_;
1666 # aha! svk:merge property changed...
1668 memoize_svn_mergeinfo_functions();
1670 # We first search for merged tips which are not in our
1671 # history. Then, we figure out which git revisions are in
1672 # that tip, but not this revision. If all of those revisions
1673 # are now marked as merge, we can add the tip as a parent.
1674 my @merges = split "\n", $mergeinfo;
1676 my $url = $self->{url};
1677 my $uuid = $self->ra_uuid;
1679 for my $merge ( @merges ) {
1680 my ($tip_commit, @ranges) =
1681 lookup_svn_merge( $uuid, $url, $merge );
1682 unless (!$tip_commit or
1683 grep { $_ eq $tip_commit } @$parents ) {
1684 push @merge_tips, $tip_commit;
1685 $ranges{$tip_commit} = \@ranges;
1687 push @merge_tips, undef;
1691 my %excluded = map { $_ => 1 }
1692 parents_exclude($parents, grep { defined } @merge_tips);
1694 # check merge tips for new parents
1696 for my $merge_tip ( @merge_tips ) {
1697 my $spec = shift @merges;
1698 next unless $merge_tip and $excluded{$merge_tip};
1700 my $ranges = $ranges{$merge_tip};
1702 # check out 'new' tips
1705 $merge_base = command_oneline(
1707 @$parents, $merge_tip,
1711 die "An error occurred during merge-base"
1712 unless $@->isa("Git::Error::Command");
1714 warn "W: Cannot find common ancestor between ".
1715 "@$parents and $merge_tip. Ignoring merge info.\n";
1719 # double check that there are no missing non-merge commits
1720 my (@incomplete) = check_cherry_pick(
1721 $merge_base, $merge_tip,
1726 if ( @incomplete ) {
1727 warn "W:svn cherry-pick ignored ($spec) - missing "
1728 .@incomplete." commit(s) (eg $incomplete[0])\n";
1731 "Found merge parent (svn:mergeinfo prop): ",
1733 push @new_parents, $merge_tip;
1737 # cater for merges which merge commits from multiple branches
1738 if ( @new_parents > 1 ) {
1739 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
1740 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
1742 next unless $new_parents[$i];
1743 next unless $new_parents[$j];
1744 my $revs = command_oneline(
1746 "$new_parents[$i]..$new_parents[$j]",
1749 undef($new_parents[$j]);
1754 push @$parents, grep { defined } @new_parents;
1757 sub make_log_entry {
1758 my ($self, $rev, $parents, $ed) = @_;
1759 my $untracked = $self->get_untracked($ed);
1761 my @parents = @$parents;
1762 my $ps = $ed->{path_strip} || "";
1763 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
1764 my $props = $ed->{dir_prop}{$path};
1765 if ( $props->{"svk:merge"} ) {
1766 $self->find_extra_svk_parents
1767 ($ed, $props->{"svk:merge"}, \@parents);
1769 if ( $props->{"svn:mergeinfo"} ) {
1770 $self->find_extra_svn_parents
1772 $props->{"svn:mergeinfo"},
1777 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1778 print $un "r$rev\n" or croak $!;
1779 print $un $_, "\n" foreach @$untracked;
1780 my %log_entry = ( parents => \@parents, revision => $rev,
1784 my $logged = delete $self->{logged_rev_props};
1785 if (!$logged || $self->{-want_revprops}) {
1786 my $rp = $self->ra->rev_proplist($rev);
1787 foreach (sort keys %$rp) {
1789 if (/^svn:(author|date|log)$/) {
1790 $log_entry{$1} = $v;
1791 } elsif ($_ eq 'svm:headrev') {
1794 print $un " rev_prop: ", uri_encode($_), ' ',
1795 uri_encode($v), "\n";
1799 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1801 close $un or croak $!;
1803 $log_entry{date} = parse_svn_date($log_entry{date});
1804 $log_entry{log} .= "\n";
1805 my $author = $log_entry{author} = check_author($log_entry{author});
1806 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1809 my ($commit_name, $commit_email) = ($name, $email);
1810 if ($_use_log_author) {
1812 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
1814 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
1817 if (!defined $name_field) {
1818 if (!defined $email) {
1821 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
1822 ($name, $email) = ($1, $2);
1823 } elsif ($name_field =~ /(.*)@/) {
1824 ($name, $email) = ($1, $name_field);
1826 ($name, $email) = ($name_field, $name_field);
1829 if (defined $headrev && $self->use_svm_props) {
1830 if ($self->rewrite_root) {
1831 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1834 if ($self->rewrite_uuid) {
1835 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
1838 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
1839 # we don't want "SVM: initializing mirror for junk" ...
1840 return undef if $r == 0;
1841 my $svm = $self->svm;
1842 if ($uuid ne $svm->{uuid}) {
1843 die "UUID mismatch on SVM path:\n",
1844 "expected: $svm->{uuid}\n",
1847 my $full_url = $self->full_url;
1848 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1849 die "Failed to replace '$svm->{replace}' with ",
1850 "'$svm->{source}' in $full_url\n";
1851 # throw away username for storing in records
1852 remove_username($full_url);
1853 $log_entry{metadata} = "$full_url\@$r $uuid";
1854 $log_entry{svm_revision} = $r;
1855 $email ||= "$author\@$uuid";
1856 $commit_email ||= "$author\@$uuid";
1857 } elsif ($self->use_svnsync_props) {
1858 my $full_url = $self->svnsync->{url};
1859 $full_url .= "/$self->{path}" if length $self->{path};
1860 remove_username($full_url);
1861 my $uuid = $self->svnsync->{uuid};
1862 $log_entry{metadata} = "$full_url\@$rev $uuid";
1863 $email ||= "$author\@$uuid";
1864 $commit_email ||= "$author\@$uuid";
1866 my $url = $self->metadata_url;
1867 remove_username($url);
1868 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
1869 $log_entry{metadata} = "$url\@$rev " . $uuid;
1870 $email ||= "$author\@" . $uuid;
1871 $commit_email ||= "$author\@" . $uuid;
1873 $log_entry{name} = $name;
1874 $log_entry{email} = $email;
1875 $log_entry{commit_name} = $commit_name;
1876 $log_entry{commit_email} = $commit_email;
1881 my ($self, $min_rev, $max_rev, @parents) = @_;
1882 my ($last_rev, $last_commit) = $self->last_rev_commit;
1883 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1884 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1888 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1889 $self->{inject_parents} = { $rev => $tree };
1890 $self->fetch(undef, undef);
1894 my ($self, $tree) = (shift, shift);
1895 my $log_entry = ::get_commit_entry($tree);
1896 unless ($self->{last_rev}) {
1897 fatal("Must have an existing revision to commit");
1899 my %ed_opts = ( r => $self->{last_rev},
1900 log => $log_entry->{log},
1902 tree_a => $self->{last_commit},
1905 $self->set_tree_cb($log_entry, $tree, @_) },
1906 svn_path => $self->{path} );
1907 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1908 print "No changes\nr$self->{last_rev} = $tree\n";
1912 sub rebuild_from_rev_db {
1913 my ($self, $path) = @_;
1915 open my $fh, '<', $path or croak "open: $!";
1916 binmode $fh or croak "binmode: $!";
1918 length($_) == 41 or croak "inconsistent size in ($_) != 41";
1921 next if $_ eq ('0' x 40);
1922 $self->rev_map_set($r, $_);
1925 close $fh or croak "close: $!";
1926 unlink $path or croak "unlink: $!";
1931 my $map_path = $self->map_path;
1932 my $partial = (-e $map_path && ! -z $map_path);
1933 return unless ::verify_ref($self->refname.'^0');
1934 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
1935 my $rev_db = $self->rev_db_path;
1936 $self->rebuild_from_rev_db($rev_db);
1937 if ($self->use_svm_props) {
1938 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
1939 $self->rebuild_from_rev_db($svm_rev_db);
1941 $self->unlink_rev_db_symlink;
1944 print "Rebuilding $map_path ...\n" if (!$partial);
1945 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
1948 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
1949 ($head ? "$head.." : "") . $self->refname,
1951 my $metadata_url = $self->metadata_url;
1952 remove_username($metadata_url);
1953 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
1956 if ( m{^commit ($::sha1)$} ) {
1960 next unless s{^\s*(git-svn-id:)}{$1};
1961 my ($url, $rev, $uuid) = ::extract_metadata($_);
1962 remove_username($url);
1964 # ignore merges (from set-tree)
1965 next if (!defined $rev || !$uuid);
1967 # if we merged or otherwise started elsewhere, this is
1968 # how we break out of it
1969 if (($uuid ne $svn_uuid) ||
1970 ($metadata_url && $url && ($url ne $metadata_url))) {
1973 if ($partial && $head) {
1974 print "Partial-rebuilding $map_path ...\n";
1975 print "Currently at $base_rev = $head\n";
1979 $self->rev_map_set($rev, $c);
1980 print "r$rev = $c\n";
1982 command_close_pipe($log, $ctx);
1983 print "Done rebuilding $map_path\n" if (!$partial || !$head);
1984 my $rev_db_path = $self->rev_db_path;
1985 if (-f $self->rev_db_path) {
1986 unlink $self->rev_db_path or croak "unlink: $!";
1988 $self->unlink_rev_db_symlink;
1992 # Tie::File seems to be prone to offset errors if revisions get sparse,
1993 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
1994 # one of my favorite modules is out :< Next up would be one of the DBM
1995 # modules, but I'm not sure which is most portable...
1997 # This is the replacement for the rev_db format, which was too big
1998 # and inefficient for large repositories with a lot of sparse history
2001 # The format is this:
2002 # - 24 bytes for every record,
2003 # * 4 bytes for the integer representing an SVN revision number
2004 # * 20 bytes representing the sha1 of a git commit
2005 # - No empty padding records like the old format
2006 # (except the last record, which can be overwritten)
2007 # - new records are written append-only since SVN revision numbers
2008 # increase monotonically
2009 # - lookups on SVN revision number are done via a binary search
2010 # - Piping the file to xxd -c24 is a good way of dumping it for
2011 # viewing or editing (piped back through xxd -r), should the need
2013 # - The last record can be padding revision with an all-zero sha1
2014 # This is used to optimize fetch performance when using multiple
2015 # "fetch" directives in .git/config
2017 # These files are disposable unless noMetadata or useSvmProps is set
2020 my ($fh, $rev, $commit) = @_;
2022 binmode $fh or croak "binmode: $!";
2023 my $size = (stat($fh))[7];
2024 ($size % 24) == 0 or croak "inconsistent size: $size";
2028 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2029 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2030 $read == 24 or croak "read only $read bytes (!= 24)";
2031 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2032 if ($last_commit eq ('0' x40)) {
2034 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2035 $read = sysread($fh, $buf, 24) or
2038 croak "read only $read bytes (!= 24)";
2039 ($last_rev, $last_commit) =
2040 unpack(rev_map_fmt, $buf);
2041 if ($last_commit eq ('0' x40)) {
2042 croak "inconsistent .rev_map\n";
2045 if ($last_rev >= $rev) {
2046 croak "last_rev is higher!: $last_rev >= $rev";
2051 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2052 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2056 sub _rev_map_reset {
2057 my ($fh, $rev, $commit) = @_;
2058 my $c = _rev_map_get($fh, $rev);
2059 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
2060 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
2061 truncate $fh, $offset or croak "truncate: $!";
2067 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2068 mkpath([$dir]) unless -d $dir;
2069 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2070 close $fh or die "Couldn't close (create) $path: $!\n";
2075 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2076 defined $commit or die "missing arg3\n";
2077 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2078 my $db = $self->map_path($uuid);
2079 my $db_lock = "$db.lock";
2083 $sigmask = POSIX::SigSet->new();
2084 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
2085 SIGALRM, SIGUSR1, SIGUSR2);
2086 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
2087 croak "Can't block signals: $!";
2091 $LOCKFILES{$db_lock} = 1;
2093 # both of these options make our .rev_db file very, very important
2094 # and we can't afford to lose it because rebuild() won't work
2095 if ($self->use_svm_props || $self->no_metadata) {
2097 copy($db, $db_lock) or die "rev_map_set(@_): ",
2099 "$db => $db_lock ($!)\n";
2101 rename $db, $db_lock or die "rev_map_set(@_): ",
2102 "Failed to rename: ",
2103 "$db => $db_lock ($!)\n";
2106 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2107 or croak "Couldn't open $db_lock: $!\n";
2108 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
2109 _rev_map_set($fh, $rev, $commit);
2111 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2112 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2114 close $fh or croak $!;
2118 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
2119 command_noisy('update-ref', '-m', "r$rev$note",
2120 $self->refname, $commit);
2122 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2123 "$db_lock => $db ($!)\n";
2124 delete $LOCKFILES{$db_lock};
2126 sigprocmask(SIG_SETMASK, $sigmask) or
2127 croak "Can't restore signal mask: $!";
2131 # If want_commit, this will return an array of (rev, commit) where
2132 # commit _must_ be a valid commit in the archive.
2133 # Otherwise, it'll return the max revision (whether or not the
2134 # commit is valid or just a 0x40 placeholder).
2136 my ($self, $want_commit) = @_;
2138 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2139 $want_commit ? ($r, $c) : $r;
2142 sub rev_map_max_norebuild {
2143 my ($self, $want_commit) = @_;
2144 my $map_path = $self->map_path;
2145 stat $map_path or return $want_commit ? (0, undef) : 0;
2146 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2147 binmode $fh or croak "binmode: $!";
2148 my $size = (stat($fh))[7];
2149 ($size % 24) == 0 or croak "inconsistent size: $size";
2152 close $fh or croak "close: $!";
2153 return $want_commit ? (0, undef) : 0;
2156 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2157 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2158 my ($r, $c) = unpack(rev_map_fmt, $buf);
2159 if ($want_commit && $c eq ('0' x40)) {
2161 return $want_commit ? (0, undef) : 0;
2163 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2164 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2165 ($r, $c) = unpack(rev_map_fmt, $buf);
2166 if ($c eq ('0'x40)) {
2167 croak "Penultimate record is all-zeroes in $map_path";
2170 close $fh or croak "close: $!";
2171 $want_commit ? ($r, $c) : $r;
2175 my ($self, $rev, $uuid) = @_;
2176 my $map_path = $self->map_path($uuid);
2177 return undef unless -e $map_path;
2179 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2180 my $c = _rev_map_get($fh, $rev);
2181 close($fh) or croak "close: $!";
2186 my ($fh, $rev) = @_;
2188 binmode $fh or croak "binmode: $!";
2189 my $size = (stat($fh))[7];
2190 ($size % 24) == 0 or croak "inconsistent size: $size";
2196 my ($l, $u) = (0, $size - 24);
2200 my $i = int(($l/24 + $u/24) / 2) * 24;
2201 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2202 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2203 my ($r, $c) = unpack(rev_map_fmt, $buf);
2207 } elsif ($r > $rev) {
2209 } else { # $r == $rev
2210 return $c eq ('0' x 40) ? undef : $c;
2216 # Finds the first svn revision that exists on (if $eq_ok is true) or
2217 # before $rev for the current branch. It will not search any lower
2218 # than $min_rev. Returns the git commit hash and svn revision number
2219 # if found, else (undef, undef).
2220 sub find_rev_before {
2221 my ($self, $rev, $eq_ok, $min_rev) = @_;
2222 --$rev unless $eq_ok;
2224 my $max_rev = $self->rev_map_max;
2225 $rev = $max_rev if ($rev > $max_rev);
2226 while ($rev >= $min_rev) {
2227 if (my $c = $self->rev_map_get($rev)) {
2232 return (undef, undef);
2235 # Finds the first svn revision that exists on (if $eq_ok is true) or
2236 # after $rev for the current branch. It will not search any higher
2237 # than $max_rev. Returns the git commit hash and svn revision number
2238 # if found, else (undef, undef).
2239 sub find_rev_after {
2240 my ($self, $rev, $eq_ok, $max_rev) = @_;
2241 ++$rev unless $eq_ok;
2242 $max_rev ||= $self->rev_map_max;
2243 while ($rev <= $max_rev) {
2244 if (my $c = $self->rev_map_get($rev)) {
2249 return (undef, undef);
2253 my ($class, $repo_id, $ref_id, $path) = @_;
2254 unless (defined $repo_id && length $repo_id) {
2255 $repo_id = $default_repo_id;
2257 unless (defined $ref_id && length $ref_id) {
2258 # Access the prefix option from the git-svn main program if it's loaded.
2259 my $prefix = defined &::opt_prefix ? ::opt_prefix() : "";
2261 "refs/remotes/$prefix$default_ref_id";
2264 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2266 # Older repos imported by us used $GIT_DIR/svn/foo instead of
2267 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
2268 if ($ref_id =~ m{^refs/remotes/(.*)}) {
2269 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
2270 if (-d $old_dir && ! -d $dir) {
2275 $_[3] = $path = '' unless (defined $path);
2278 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2279 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2280 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2283 # for read-only access of old .rev_db formats
2284 sub unlink_rev_db_symlink {
2286 my $link = $self->rev_db_path;
2287 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2289 unlink $link or croak "unlink: $link failed!";
2294 my ($self, $uuid) = @_;
2295 my $db_path = $self->map_path($uuid);
2296 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2297 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2301 # the new replacement for .rev_db
2303 my ($self, $uuid) = @_;
2304 $uuid ||= $self->ra_uuid;
2305 "$self->{map_root}.$uuid";
2310 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2316 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
2320 sub remove_username {
2321 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};