git-svn: replace URL escapes with canonicalization
[alt-git.git] / perl / Git / SVN.pm
blob6a2a52e8086027ac7f26ae160be12f79e13e51c7
1 package Git::SVN;
2 use strict;
3 use warnings;
4 use Fcntl qw/:DEFAULT :seek/;
5 use constant rev_map_fmt => 'NH40';
6 use vars qw/$_no_metadata
7 $_repack $_repack_flags $_use_svm_props $_head
8 $_use_svnsync_props $no_reuse_existing
9 $_use_log_author $_add_author_from $_localtime/;
10 use Carp qw/croak/;
11 use File::Path qw/mkpath/;
12 use File::Copy qw/copy/;
13 use IPC::Open3;
14 use Time::Local;
15 use Memoize; # core since 5.8.0, Jul 2002
16 use Memoize::Storable;
17 use POSIX qw(:signal_h);
19 use Git qw(
20 command
21 command_oneline
22 command_noisy
23 command_output_pipe
24 command_close_pipe
26 use Git::SVN::Utils qw(
27 fatal
28 can_compress
29 join_paths
30 canonicalize_path
31 canonicalize_url
34 my $can_use_yaml;
35 BEGIN {
36 $can_use_yaml = eval { require Git::SVN::Memoize::YAML; 1};
39 our $_follow_parent = 1;
40 our $_minimize_url = 'unset';
41 our $default_repo_id = 'svn';
42 our $default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
44 my ($_gc_nr, $_gc_period);
46 # properties that we do not log:
47 my %SKIP_PROP;
48 BEGIN {
49 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
50 svn:special svn:executable
51 svn:entry:committed-rev
52 svn:entry:last-author
53 svn:entry:uuid
54 svn:entry:committed-date/;
56 # some options are read globally, but can be overridden locally
57 # per [svn-remote "..."] section. Command-line options will *NOT*
58 # override options set in an [svn-remote "..."] section
59 no strict 'refs';
60 for my $option (qw/follow_parent no_metadata use_svm_props
61 use_svnsync_props/) {
62 my $key = $option;
63 $key =~ tr/_//d;
64 my $prop = "-$option";
65 *$option = sub {
66 my ($self) = @_;
67 return $self->{$prop} if exists $self->{$prop};
68 my $k = "svn-remote.$self->{repo_id}.$key";
69 eval { command_oneline(qw/config --get/, $k) };
70 if ($@) {
71 $self->{$prop} = ${"Git::SVN::_$option"};
72 } else {
73 my $v = command_oneline(qw/config --bool/,$k);
74 $self->{$prop} = $v eq 'false' ? 0 : 1;
76 return $self->{$prop};
82 my (%LOCKFILES, %INDEX_FILES);
83 END {
84 unlink keys %LOCKFILES if %LOCKFILES;
85 unlink keys %INDEX_FILES if %INDEX_FILES;
88 sub resolve_local_globs {
89 my ($url, $fetch, $glob_spec) = @_;
90 return unless defined $glob_spec;
91 my $ref = $glob_spec->{ref};
92 my $path = $glob_spec->{path};
93 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
94 next unless m#^$ref->{regex}$#;
95 my $p = $1;
96 my $pathname = desanitize_refname($path->full_path($p));
97 my $refname = desanitize_refname($ref->full_path($p));
98 if (my $existing = $fetch->{$pathname}) {
99 if ($existing ne $refname) {
100 die "Refspec conflict:\n",
101 "existing: $existing\n",
102 " globbed: $refname\n";
104 my $u = (::cmt_metadata("$refname"))[0];
105 $u =~ s!^\Q$url\E(/|$)!! or die
106 "$refname: '$url' not found in '$u'\n";
107 if ($pathname ne $u) {
108 warn "W: Refspec glob conflict ",
109 "(ref: $refname):\n",
110 "expected path: $pathname\n",
111 " real path: $u\n",
112 "Continuing ahead with $u\n";
113 next;
115 } else {
116 $fetch->{$pathname} = $refname;
121 sub parse_revision_argument {
122 my ($base, $head) = @_;
123 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
124 return ($base, $head);
126 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
127 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
128 return ($head, $head) if ($::_revision eq 'HEAD');
129 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
130 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
131 die "revision argument: $::_revision not understood by git-svn\n";
134 sub fetch_all {
135 my ($repo_id, $remotes) = @_;
136 if (ref $repo_id) {
137 my $gs = $repo_id;
138 $repo_id = undef;
139 $repo_id = $gs->{repo_id};
141 $remotes ||= read_all_remotes();
142 my $remote = $remotes->{$repo_id} or
143 die "[svn-remote \"$repo_id\"] unknown\n";
144 my $fetch = $remote->{fetch};
145 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
146 my (@gs, @globs);
147 my $ra = Git::SVN::Ra->new($url);
148 my $uuid = $ra->get_uuid;
149 my $head = $ra->get_latest_revnum;
151 # ignore errors, $head revision may not even exist anymore
152 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
153 warn "W: $@\n" if $@;
155 my $base = defined $fetch ? $head : 0;
157 # read the max revs for wildcard expansion (branches/*, tags/*)
158 foreach my $t (qw/branches tags/) {
159 defined $remote->{$t} or next;
160 push @globs, @{$remote->{$t}};
162 my $max_rev = eval { tmp_config(qw/--int --get/,
163 "svn-remote.$repo_id.${t}-maxRev") };
164 if (defined $max_rev && ($max_rev < $base)) {
165 $base = $max_rev;
166 } elsif (!defined $max_rev) {
167 $base = 0;
171 if ($fetch) {
172 foreach my $p (sort keys %$fetch) {
173 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
174 my $lr = $gs->rev_map_max;
175 if (defined $lr) {
176 $base = $lr if ($lr < $base);
178 push @gs, $gs;
182 ($base, $head) = parse_revision_argument($base, $head);
183 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
186 sub read_all_remotes {
187 my $r = {};
188 my $use_svm_props = eval { command_oneline(qw/config --bool
189 svn.useSvmProps/) };
190 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
191 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
192 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
193 if (m!^(.+)\.fetch=$svn_refspec$!) {
194 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
195 die("svn-remote.$remote: remote ref '$remote_ref' "
196 . "must start with 'refs/'\n")
197 unless $remote_ref =~ m{^refs/};
198 $local_ref = uri_decode($local_ref);
199 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
200 $r->{$remote}->{svm} = {} if $use_svm_props;
201 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
202 $r->{$1}->{svm} = {};
203 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
204 $r->{$1}->{url} = canonicalize_url($2);
205 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
206 $r->{$1}->{pushurl} = canonicalize_url($2);
207 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
208 $r->{$1}->{ignore_refs_regex} = $2;
209 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
210 my ($remote, $t, $local_ref, $remote_ref) =
211 ($1, $2, $3, $4);
212 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
213 . "must start with 'refs/'\n")
214 unless $remote_ref =~ m{^refs/};
215 $local_ref = uri_decode($local_ref);
217 require Git::SVN::GlobSpec;
218 my $rs = {
219 t => $t,
220 remote => $remote,
221 path => Git::SVN::GlobSpec->new($local_ref, 1),
222 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
223 if (length($rs->{ref}->{right}) != 0) {
224 die "The '*' glob character must be the last ",
225 "character of '$remote_ref'\n";
227 push @{ $r->{$remote}->{$t} }, $rs;
231 map {
232 if (defined $r->{$_}->{svm}) {
233 my $svm;
234 eval {
235 my $section = "svn-remote.$_";
236 $svm = {
237 source => tmp_config('--get',
238 "$section.svm-source"),
239 replace => tmp_config('--get',
240 "$section.svm-replace"),
243 $r->{$_}->{svm} = $svm;
245 } keys %$r;
247 foreach my $remote (keys %$r) {
248 foreach ( grep { defined $_ }
249 map { $r->{$remote}->{$_} } qw(branches tags) ) {
250 foreach my $rs ( @$_ ) {
251 $rs->{ignore_refs_regex} =
252 $r->{$remote}->{ignore_refs_regex};
260 sub init_vars {
261 $_gc_nr = $_gc_period = 1000;
262 if (defined $_repack || defined $_repack_flags) {
263 warn "Repack options are obsolete; they have no effect.\n";
267 sub verify_remotes_sanity {
268 return unless -d $ENV{GIT_DIR};
269 my %seen;
270 foreach (command(qw/config -l/)) {
271 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
272 if ($seen{$1}) {
273 die "Remote ref refs/remote/$1 is tracked by",
274 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
275 "Please resolve this ambiguity in ",
276 "your git configuration file before ",
277 "continuing\n";
279 $seen{$1} = $_;
284 sub find_existing_remote {
285 my ($url, $remotes) = @_;
286 return undef if $no_reuse_existing;
287 my $existing;
288 foreach my $repo_id (keys %$remotes) {
289 my $u = $remotes->{$repo_id}->{url} or next;
290 next if $u ne $url;
291 $existing = $repo_id;
292 last;
294 $existing;
297 sub init_remote_config {
298 my ($self, $url, $no_write) = @_;
299 $url = canonicalize_url($url);
300 my $r = read_all_remotes();
301 my $existing = find_existing_remote($url, $r);
302 if ($existing) {
303 unless ($no_write) {
304 print STDERR "Using existing ",
305 "[svn-remote \"$existing\"]\n";
307 $self->{repo_id} = $existing;
308 } elsif ($_minimize_url) {
309 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
310 $existing = find_existing_remote($min_url, $r);
311 if ($existing) {
312 unless ($no_write) {
313 print STDERR "Using existing ",
314 "[svn-remote \"$existing\"]\n";
316 $self->{repo_id} = $existing;
318 if ($min_url ne $url) {
319 unless ($no_write) {
320 print STDERR "Using higher level of URL: ",
321 "$url => $min_url\n";
323 my $old_path = $self->path;
324 $url =~ s!^\Q$min_url\E(/|$)!!;
325 $url = join_paths($url, $old_path);
326 $self->path($url);
327 $url = $min_url;
330 my $orig_url;
331 if (!$existing) {
332 # verify that we aren't overwriting anything:
333 $orig_url = eval {
334 command_oneline('config', '--get',
335 "svn-remote.$self->{repo_id}.url")
337 if ($orig_url && ($orig_url ne $url)) {
338 die "svn-remote.$self->{repo_id}.url already set: ",
339 "$orig_url\nwanted to set to: $url\n";
342 my ($xrepo_id, $xpath) = find_ref($self->refname);
343 if (!$no_write && defined $xpath) {
344 die "svn-remote.$xrepo_id.fetch already set to track ",
345 "$xpath:", $self->refname, "\n";
347 unless ($no_write) {
348 command_noisy('config',
349 "svn-remote.$self->{repo_id}.url", $url);
350 my $path = $self->path;
351 $path =~ s{^/}{};
352 $path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
353 $self->path($path);
354 command_noisy('config', '--add',
355 "svn-remote.$self->{repo_id}.fetch",
356 $self->path.":".$self->refname);
358 $self->url($url);
361 sub find_by_url { # repos_root and, path are optional
362 my ($class, $full_url, $repos_root, $path) = @_;
364 return undef unless defined $full_url;
365 remove_username($full_url);
366 remove_username($repos_root) if defined $repos_root;
367 my $remotes = read_all_remotes();
368 if (defined $full_url && defined $repos_root && !defined $path) {
369 $path = $full_url;
370 $path =~ s#^\Q$repos_root\E(?:/|$)##;
372 foreach my $repo_id (keys %$remotes) {
373 my $u = $remotes->{$repo_id}->{url} or next;
374 remove_username($u);
375 next if defined $repos_root && $repos_root ne $u;
377 my $fetch = $remotes->{$repo_id}->{fetch} || {};
378 foreach my $t (qw/branches tags/) {
379 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
380 resolve_local_globs($u, $fetch, $globspec);
383 my $p = $path;
384 my $rwr = rewrite_root({repo_id => $repo_id});
385 my $svm = $remotes->{$repo_id}->{svm}
386 if defined $remotes->{$repo_id}->{svm};
387 unless (defined $p) {
388 $p = $full_url;
389 my $z = $u;
390 my $prefix = '';
391 if ($rwr) {
392 $z = $rwr;
393 remove_username($z);
394 } elsif (defined $svm) {
395 $z = $svm->{source};
396 $prefix = $svm->{replace};
397 $prefix =~ s#^\Q$u\E(?:/|$)##;
398 $prefix =~ s#/$##;
400 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
402 foreach my $f (keys %$fetch) {
403 next if $f ne $p;
404 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
407 undef;
410 sub init {
411 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
412 my $self = _new($class, $repo_id, $ref_id, $path);
413 if (defined $url) {
414 $self->init_remote_config($url, $no_write);
416 $self;
419 sub find_ref {
420 my ($ref_id) = @_;
421 foreach (command(qw/config -l/)) {
422 next unless m!^svn-remote\.(.+)\.fetch=
423 \s*(.*?)\s*:\s*(.+?)\s*$!x;
424 my ($repo_id, $path, $ref) = ($1, $2, $3);
425 if ($ref eq $ref_id) {
426 $path = '' if ($path =~ m#^\./?#);
427 return ($repo_id, $path);
430 (undef, undef, undef);
433 sub new {
434 my ($class, $ref_id, $repo_id, $path) = @_;
435 if (defined $ref_id && !defined $repo_id && !defined $path) {
436 ($repo_id, $path) = find_ref($ref_id);
437 if (!defined $repo_id) {
438 die "Could not find a \"svn-remote.*.fetch\" key ",
439 "in the repository configuration matching: ",
440 "$ref_id\n";
443 my $self = _new($class, $repo_id, $ref_id, $path);
444 if (!defined $self->path || !length $self->path) {
445 my $fetch = command_oneline('config', '--get',
446 "svn-remote.$repo_id.fetch",
447 ":$ref_id\$") or
448 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
449 "\":$ref_id\$\" in config\n";
450 my($path) = split(/\s*:\s*/, $fetch);
451 $self->path($path);
454 my $path = $self->path;
455 $path =~ s{/+}{/}g;
456 $path =~ s{\A/}{};
457 $path =~ s{/\z}{};
458 $self->path($path);
460 my $url = command_oneline('config', '--get',
461 "svn-remote.$repo_id.url") or
462 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
463 $self->url($url);
464 $self->{pushurl} = eval { command_oneline('config', '--get',
465 "svn-remote.$repo_id.pushurl") };
466 $self->rebuild;
467 $self;
470 sub refname {
471 my ($refname) = $_[0]->{ref_id} ;
473 # It cannot end with a slash /, we'll throw up on this because
474 # SVN can't have directories with a slash in their name, either:
475 if ($refname =~ m{/$}) {
476 die "ref: '$refname' ends with a trailing slash, this is ",
477 "not permitted by git nor Subversion\n";
480 # It cannot have ASCII control character space, tilde ~, caret ^,
481 # colon :, question-mark ?, asterisk *, space, or open bracket [
482 # anywhere.
484 # Additionally, % must be escaped because it is used for escaping
485 # and we want our escaped refname to be reversible
486 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
488 # no slash-separated component can begin with a dot .
489 # /.* becomes /%2E*
490 $refname =~ s{/\.}{/%2E}g;
492 # It cannot have two consecutive dots .. anywhere
493 # .. becomes %2E%2E
494 $refname =~ s{\.\.}{%2E%2E}g;
496 # trailing dots and .lock are not allowed
497 # .$ becomes %2E and .lock becomes %2Elock
498 $refname =~ s{\.(?=$|lock$)}{%2E};
500 # the sequence @{ is used to access the reflog
501 # @{ becomes %40{
502 $refname =~ s{\@\{}{%40\{}g;
504 return $refname;
507 sub desanitize_refname {
508 my ($refname) = @_;
509 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
510 return $refname;
513 sub svm_uuid {
514 my ($self) = @_;
515 return $self->{svm}->{uuid} if $self->svm;
516 $self->ra;
517 unless ($self->{svm}) {
518 die "SVM UUID not cached, and reading remotely failed\n";
520 $self->{svm}->{uuid};
523 sub svm {
524 my ($self) = @_;
525 return $self->{svm} if $self->{svm};
526 my $svm;
527 # see if we have it in our config, first:
528 eval {
529 my $section = "svn-remote.$self->{repo_id}";
530 $svm = {
531 source => tmp_config('--get', "$section.svm-source"),
532 uuid => tmp_config('--get', "$section.svm-uuid"),
533 replace => tmp_config('--get', "$section.svm-replace"),
536 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
537 $self->{svm} = $svm;
539 $self->{svm};
542 sub _set_svm_vars {
543 my ($self, $ra) = @_;
544 return $ra if $self->svm;
546 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
547 "(svm:source, svm:uuid) ",
548 "from the following URLs:\n" );
549 sub read_svm_props {
550 my ($self, $ra, $path, $r) = @_;
551 my $props = ($ra->get_dir($path, $r))[2];
552 my $src = $props->{'svm:source'};
553 my $uuid = $props->{'svm:uuid'};
554 return undef if (!$src || !$uuid);
556 chomp($src, $uuid);
558 $uuid =~ m{^[0-9a-f\-]{30,}$}i
559 or die "doesn't look right - svm:uuid is '$uuid'\n";
561 # the '!' is used to mark the repos_root!/relative/path
562 $src =~ s{/?!/?}{/};
563 $src =~ s{/+$}{}; # no trailing slashes please
564 # username is of no interest
565 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
567 my $replace = $ra->url;
568 $replace .= "/$path" if length $path;
570 my $section = "svn-remote.$self->{repo_id}";
571 tmp_config("$section.svm-source", $src);
572 tmp_config("$section.svm-replace", $replace);
573 tmp_config("$section.svm-uuid", $uuid);
574 $self->{svm} = {
575 source => $src,
576 uuid => $uuid,
577 replace => $replace
581 my $r = $ra->get_latest_revnum;
582 my $path = $self->path;
583 my %tried;
584 while (length $path) {
585 my $try = $self->url . "/$path";
586 unless ($tried{$try}) {
587 return $ra if $self->read_svm_props($ra, $path, $r);
588 $tried{$try} = 1;
590 $path =~ s#/?[^/]+$##;
592 die "Path: '$path' should be ''\n" if $path ne '';
593 return $ra if $self->read_svm_props($ra, $path, $r);
594 $tried{$self->url."/$path"} = 1;
596 if ($ra->{repos_root} eq $self->url) {
597 die @err, (map { " $_\n" } keys %tried), "\n";
600 # nope, make sure we're connected to the repository root:
601 my $ok;
602 my @tried_b;
603 $path = $ra->{svn_path};
604 $ra = Git::SVN::Ra->new($ra->{repos_root});
605 while (length $path) {
606 my $try = $ra->url ."/$path";
607 unless ($tried{$try}) {
608 $ok = $self->read_svm_props($ra, $path, $r);
609 last if $ok;
610 $tried{$try} = 1;
612 $path =~ s#/?[^/]+$##;
614 die "Path: '$path' should be ''\n" if $path ne '';
615 $ok ||= $self->read_svm_props($ra, $path, $r);
616 $tried{$ra->url ."/$path"} = 1;
617 if (!$ok) {
618 die @err, (map { " $_\n" } keys %tried), "\n";
620 Git::SVN::Ra->new($self->url);
623 sub svnsync {
624 my ($self) = @_;
625 return $self->{svnsync} if $self->{svnsync};
627 if ($self->no_metadata) {
628 die "Can't have both 'noMetadata' and ",
629 "'useSvnsyncProps' options set!\n";
631 if ($self->rewrite_root) {
632 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
633 "options set!\n";
635 if ($self->rewrite_uuid) {
636 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
637 "options set!\n";
640 my $svnsync;
641 # see if we have it in our config, first:
642 eval {
643 my $section = "svn-remote.$self->{repo_id}";
645 my $url = tmp_config('--get', "$section.svnsync-url");
646 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
647 die "doesn't look right - svn:sync-from-url is '$url'\n";
649 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
650 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
651 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
653 $svnsync = { url => $url, uuid => $uuid }
655 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
656 return $self->{svnsync} = $svnsync;
659 my $err = "useSvnsyncProps set, but failed to read " .
660 "svnsync property: svn:sync-from-";
661 my $rp = $self->ra->rev_proplist(0);
663 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
664 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
665 die "doesn't look right - svn:sync-from-url is '$url'\n";
667 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
668 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
669 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
671 my $section = "svn-remote.$self->{repo_id}";
672 tmp_config('--add', "$section.svnsync-uuid", $uuid);
673 tmp_config('--add', "$section.svnsync-url", $url);
674 return $self->{svnsync} = { url => $url, uuid => $uuid };
677 # this allows us to memoize our SVN::Ra UUID locally and avoid a
678 # remote lookup (useful for 'git svn log').
679 sub ra_uuid {
680 my ($self) = @_;
681 unless ($self->{ra_uuid}) {
682 my $key = "svn-remote.$self->{repo_id}.uuid";
683 my $uuid = eval { tmp_config('--get', $key) };
684 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
685 $self->{ra_uuid} = $uuid;
686 } else {
687 die "ra_uuid called without URL\n" unless $self->url;
688 $self->{ra_uuid} = $self->ra->get_uuid;
689 tmp_config('--add', $key, $self->{ra_uuid});
692 $self->{ra_uuid};
695 sub _set_repos_root {
696 my ($self, $repos_root) = @_;
697 my $k = "svn-remote.$self->{repo_id}.reposRoot";
698 $repos_root ||= $self->ra->{repos_root};
699 tmp_config($k, $repos_root);
700 $repos_root;
703 sub repos_root {
704 my ($self) = @_;
705 my $k = "svn-remote.$self->{repo_id}.reposRoot";
706 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
709 sub ra {
710 my ($self) = shift;
711 my $ra = Git::SVN::Ra->new($self->url);
712 $self->_set_repos_root($ra->{repos_root});
713 if ($self->use_svm_props && !$self->{svm}) {
714 if ($self->no_metadata) {
715 die "Can't have both 'noMetadata' and ",
716 "'useSvmProps' options set!\n";
717 } elsif ($self->use_svnsync_props) {
718 die "Can't have both 'useSvnsyncProps' and ",
719 "'useSvmProps' options set!\n";
721 $ra = $self->_set_svm_vars($ra);
722 $self->{-want_revprops} = 1;
724 $ra;
727 # prop_walk(PATH, REV, SUB)
728 # -------------------------
729 # Recursively traverse PATH at revision REV and invoke SUB for each
730 # directory that contains a SVN property. SUB will be invoked as
731 # follows: &SUB(gs, path, props); where `gs' is this instance of
732 # Git::SVN, `path' the path to the directory where the properties
733 # `props' were found. The `path' will be relative to point of checkout,
734 # that is, if url://repo/trunk is the current Git branch, and that
735 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
736 # as `path' (note the trailing `/').
737 sub prop_walk {
738 my ($self, $path, $rev, $sub) = @_;
740 $path =~ s#^/##;
741 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
742 $path =~ s#^/*#/#g;
743 my $p = $path;
744 # Strip the irrelevant part of the path.
745 $p =~ s#^/+\Q@{[$self->path]}\E(/|$)#/#;
746 # Ensure the path is terminated by a `/'.
747 $p =~ s#/*$#/#;
749 # The properties contain all the internal SVN stuff nobody
750 # (usually) cares about.
751 my $interesting_props = 0;
752 foreach (keys %{$props}) {
753 # If it doesn't start with `svn:', it must be a
754 # user-defined property.
755 ++$interesting_props and next if $_ !~ /^svn:/;
756 # FIXME: Fragile, if SVN adds new public properties,
757 # this needs to be updated.
758 ++$interesting_props if /^svn:(?:ignore|keywords|executable
759 |eol-style|mime-type
760 |externals|needs-lock)$/x;
762 &$sub($self, $p, $props) if $interesting_props;
764 foreach (sort keys %$dirent) {
765 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
766 $self->prop_walk($self->path . $p . $_, $rev, $sub);
770 sub last_rev { ($_[0]->last_rev_commit)[0] }
771 sub last_commit { ($_[0]->last_rev_commit)[1] }
773 # returns the newest SVN revision number and newest commit SHA1
774 sub last_rev_commit {
775 my ($self) = @_;
776 if (defined $self->{last_rev} && defined $self->{last_commit}) {
777 return ($self->{last_rev}, $self->{last_commit});
779 my $c = ::verify_ref($self->refname.'^0');
780 if ($c && !$self->use_svm_props && !$self->no_metadata) {
781 my $rev = (::cmt_metadata($c))[1];
782 if (defined $rev) {
783 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
784 return ($rev, $c);
787 my $map_path = $self->map_path;
788 unless (-e $map_path) {
789 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
790 return (undef, undef);
792 my ($rev, $commit) = $self->rev_map_max(1);
793 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
794 return ($rev, $commit);
797 sub get_fetch_range {
798 my ($self, $min, $max) = @_;
799 $max ||= $self->ra->get_latest_revnum;
800 $min ||= $self->rev_map_max;
801 (++$min, $max);
804 sub tmp_config {
805 my (@args) = @_;
806 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
807 my $config = "$ENV{GIT_DIR}/svn/.metadata";
808 if (! -f $config && -f $old_def_config) {
809 rename $old_def_config, $config or
810 die "Failed rename $old_def_config => $config: $!\n";
812 my $old_config = $ENV{GIT_CONFIG};
813 $ENV{GIT_CONFIG} = $config;
814 $@ = undef;
815 my @ret = eval {
816 unless (-f $config) {
817 mkfile($config);
818 open my $fh, '>', $config or
819 die "Can't open $config: $!\n";
820 print $fh "; This file is used internally by ",
821 "git-svn\n" or die
822 "Couldn't write to $config: $!\n";
823 print $fh "; You should not have to edit it\n" or
824 die "Couldn't write to $config: $!\n";
825 close $fh or die "Couldn't close $config: $!\n";
827 command('config', @args);
829 my $err = $@;
830 if (defined $old_config) {
831 $ENV{GIT_CONFIG} = $old_config;
832 } else {
833 delete $ENV{GIT_CONFIG};
835 die $err if $err;
836 wantarray ? @ret : $ret[0];
839 sub tmp_index_do {
840 my ($self, $sub) = @_;
841 my $old_index = $ENV{GIT_INDEX_FILE};
842 $ENV{GIT_INDEX_FILE} = $self->{index};
843 $@ = undef;
844 my @ret = eval {
845 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
846 mkpath([$dir]) unless -d $dir;
847 &$sub;
849 my $err = $@;
850 if (defined $old_index) {
851 $ENV{GIT_INDEX_FILE} = $old_index;
852 } else {
853 delete $ENV{GIT_INDEX_FILE};
855 die $err if $err;
856 wantarray ? @ret : $ret[0];
859 sub assert_index_clean {
860 my ($self, $treeish) = @_;
862 $self->tmp_index_do(sub {
863 command_noisy('read-tree', $treeish) unless -e $self->{index};
864 my $x = command_oneline('write-tree');
865 my ($y) = (command(qw/cat-file commit/, $treeish) =~
866 /^tree ($::sha1)/mo);
867 return if $y eq $x;
869 warn "Index mismatch: $y != $x\nrereading $treeish\n";
870 unlink $self->{index} or die "unlink $self->{index}: $!\n";
871 command_noisy('read-tree', $treeish);
872 $x = command_oneline('write-tree');
873 if ($y ne $x) {
874 fatal "trees ($treeish) $y != $x\n",
875 "Something is seriously wrong...";
880 sub get_commit_parents {
881 my ($self, $log_entry) = @_;
882 my (%seen, @ret, @tmp);
883 # legacy support for 'set-tree'; this is only used by set_tree_cb:
884 if (my $ip = $self->{inject_parents}) {
885 if (my $commit = delete $ip->{$log_entry->{revision}}) {
886 push @tmp, $commit;
889 if (my $cur = ::verify_ref($self->refname.'^0')) {
890 push @tmp, $cur;
892 if (my $ipd = $self->{inject_parents_dcommit}) {
893 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
894 push @tmp, @$commit;
897 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
898 while (my $p = shift @tmp) {
899 next if $seen{$p};
900 $seen{$p} = 1;
901 push @ret, $p;
903 @ret;
906 sub rewrite_root {
907 my ($self) = @_;
908 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
909 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
910 my $rwr = eval { command_oneline(qw/config --get/, $k) };
911 if ($rwr) {
912 $rwr =~ s#/+$##;
913 if ($rwr !~ m#^[a-z\+]+://#) {
914 die "$rwr is not a valid URL (key: $k)\n";
917 $self->{-rewrite_root} = $rwr;
920 sub rewrite_uuid {
921 my ($self) = @_;
922 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
923 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
924 my $rwid = eval { command_oneline(qw/config --get/, $k) };
925 if ($rwid) {
926 $rwid =~ s#/+$##;
927 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
928 die "$rwid is not a valid UUID (key: $k)\n";
931 $self->{-rewrite_uuid} = $rwid;
934 sub metadata_url {
935 my ($self) = @_;
936 ($self->rewrite_root || $self->url) .
937 (length $self->path ? '/' . $self->path : '');
940 sub full_url {
941 my ($self) = @_;
942 $self->url . (length $self->path ? '/' . $self->path : '');
945 sub full_pushurl {
946 my ($self) = @_;
947 if ($self->{pushurl}) {
948 return $self->{pushurl} . (length $self->path ? '/' .
949 $self->path : '');
950 } else {
951 return $self->full_url;
955 sub set_commit_header_env {
956 my ($log_entry) = @_;
957 my %env;
958 foreach my $ned (qw/NAME EMAIL DATE/) {
959 foreach my $ac (qw/AUTHOR COMMITTER/) {
960 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
964 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
965 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
966 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
968 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
969 ? $log_entry->{commit_name}
970 : $log_entry->{name};
971 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
972 ? $log_entry->{commit_email}
973 : $log_entry->{email};
974 \%env;
977 sub restore_commit_header_env {
978 my ($env) = @_;
979 foreach my $ned (qw/NAME EMAIL DATE/) {
980 foreach my $ac (qw/AUTHOR COMMITTER/) {
981 my $k = "GIT_${ac}_${ned}";
982 if (defined $env->{$k}) {
983 $ENV{$k} = $env->{$k};
984 } else {
985 delete $ENV{$k};
991 sub gc {
992 command_noisy('gc', '--auto');
995 sub do_git_commit {
996 my ($self, $log_entry) = @_;
997 my $lr = $self->last_rev;
998 if (defined $lr && $lr >= $log_entry->{revision}) {
999 die "Last fetched revision of ", $self->refname,
1000 " was r$lr, but we are about to fetch: ",
1001 "r$log_entry->{revision}!\n";
1003 if (my $c = $self->rev_map_get($log_entry->{revision})) {
1004 croak "$log_entry->{revision} = $c already exists! ",
1005 "Why are we refetching it?\n";
1007 my $old_env = set_commit_header_env($log_entry);
1008 my $tree = $log_entry->{tree};
1009 if (!defined $tree) {
1010 $tree = $self->tmp_index_do(sub {
1011 command_oneline('write-tree') });
1013 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1015 my @exec = ('git', 'commit-tree', $tree);
1016 foreach ($self->get_commit_parents($log_entry)) {
1017 push @exec, '-p', $_;
1019 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1020 or croak $!;
1021 binmode $msg_fh;
1023 # we always get UTF-8 from SVN, but we may want our commits in
1024 # a different encoding.
1025 if (my $enc = Git::config('i18n.commitencoding')) {
1026 require Encode;
1027 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
1029 print $msg_fh $log_entry->{log} or croak $!;
1030 restore_commit_header_env($old_env);
1031 unless ($self->no_metadata) {
1032 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1033 or croak $!;
1035 $msg_fh->flush == 0 or croak $!;
1036 close $msg_fh or croak $!;
1037 chomp(my $commit = do { local $/; <$out_fh> });
1038 close $out_fh or croak $!;
1039 waitpid $pid, 0;
1040 croak $? if $?;
1041 if ($commit !~ /^$::sha1$/o) {
1042 die "Failed to commit, invalid sha1: $commit\n";
1045 $self->rev_map_set($log_entry->{revision}, $commit, 1);
1047 $self->{last_rev} = $log_entry->{revision};
1048 $self->{last_commit} = $commit;
1049 print "r$log_entry->{revision}" unless $::_q > 1;
1050 if (defined $log_entry->{svm_revision}) {
1051 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
1052 $self->rev_map_set($log_entry->{svm_revision}, $commit,
1053 0, $self->svm_uuid);
1055 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
1056 if (--$_gc_nr == 0) {
1057 $_gc_nr = $_gc_period;
1058 gc();
1060 return $commit;
1063 sub match_paths {
1064 my ($self, $paths, $r) = @_;
1065 return 1 if $self->path eq '';
1066 if (my $path = $paths->{"/".$self->path}) {
1067 return ($path->{action} eq 'D') ? 0 : 1;
1069 $self->{path_regex} ||= qr{^/\Q@{[$self->path]}\E/};
1070 if (grep /$self->{path_regex}/, keys %$paths) {
1071 return 1;
1073 my $c = '';
1074 foreach (split m#/#, $self->path) {
1075 $c .= "/$_";
1076 next unless ($paths->{$c} &&
1077 ($paths->{$c}->{action} =~ /^[AR]$/));
1078 if ($self->ra->check_path($self->path, $r) ==
1079 $SVN::Node::dir) {
1080 return 1;
1083 return 0;
1086 sub find_parent_branch {
1087 my ($self, $paths, $rev) = @_;
1088 return undef unless $self->follow_parent;
1089 unless (defined $paths) {
1090 my $err_handler = $SVN::Error::handler;
1091 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1092 $self->ra->get_log([$self->path], $rev, $rev, 0, 1, 1,
1093 sub { $paths = $_[0] });
1094 $SVN::Error::handler = $err_handler;
1096 return undef unless defined $paths;
1098 # look for a parent from another branch:
1099 my @b_path_components = split m#/#, $self->path;
1100 my @a_path_components;
1101 my $i;
1102 while (@b_path_components) {
1103 $i = $paths->{'/'.join('/', @b_path_components)};
1104 last if $i && defined $i->{copyfrom_path};
1105 unshift(@a_path_components, pop(@b_path_components));
1107 return undef unless defined $i && defined $i->{copyfrom_path};
1108 my $branch_from = $i->{copyfrom_path};
1109 if (@a_path_components) {
1110 print STDERR "branch_from: $branch_from => ";
1111 $branch_from .= '/'.join('/', @a_path_components);
1112 print STDERR $branch_from, "\n";
1114 my $r = $i->{copyfrom_rev};
1115 my $repos_root = $self->ra->{repos_root};
1116 my $url = $self->ra->url;
1117 my $new_url = $url . $branch_from;
1118 print STDERR "Found possible branch point: ",
1119 "$new_url => ", $self->full_url, ", $r\n"
1120 unless $::_q > 1;
1121 $branch_from =~ s#^/##;
1122 my $gs = $self->other_gs($new_url, $url,
1123 $branch_from, $r, $self->{ref_id});
1124 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1126 my ($base, $head);
1127 if (!defined $r0 || !defined $parent) {
1128 ($base, $head) = parse_revision_argument(0, $r);
1129 } else {
1130 if ($r0 < $r) {
1131 $gs->ra->get_log([$gs->path], $r0 + 1, $r, 1,
1132 0, 1, sub { $base = $_[1] - 1 });
1135 if (defined $base && $base <= $r) {
1136 $gs->fetch($base, $r);
1138 ($r0, $parent) = $gs->find_rev_before($r, 1);
1140 if (defined $r0 && defined $parent) {
1141 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
1142 unless $::_q > 1;
1143 my $ed;
1144 if ($self->ra->can_do_switch) {
1145 $self->assert_index_clean($parent);
1146 print STDERR "Following parent with do_switch\n"
1147 unless $::_q > 1;
1148 # do_switch works with svn/trunk >= r22312, but that
1149 # is not included with SVN 1.4.3 (the latest version
1150 # at the moment), so we can't rely on it
1151 $self->{last_rev} = $r0;
1152 $self->{last_commit} = $parent;
1153 $ed = Git::SVN::Fetcher->new($self, $gs->path);
1154 $gs->ra->gs_do_switch($r0, $rev, $gs,
1155 $self->full_url, $ed)
1156 or die "SVN connection failed somewhere...\n";
1157 } elsif ($self->ra->trees_match($new_url, $r0,
1158 $self->full_url, $rev)) {
1159 print STDERR "Trees match:\n",
1160 " $new_url\@$r0\n",
1161 " ${\$self->full_url}\@$rev\n",
1162 "Following parent with no changes\n"
1163 unless $::_q > 1;
1164 $self->tmp_index_do(sub {
1165 command_noisy('read-tree', $parent);
1167 $self->{last_commit} = $parent;
1168 } else {
1169 print STDERR "Following parent with do_update\n"
1170 unless $::_q > 1;
1171 $ed = Git::SVN::Fetcher->new($self);
1172 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1173 or die "SVN connection failed somewhere...\n";
1175 print STDERR "Successfully followed parent\n" unless $::_q > 1;
1176 return $self->make_log_entry($rev, [$parent], $ed);
1178 return undef;
1181 sub do_fetch {
1182 my ($self, $paths, $rev) = @_;
1183 my $ed;
1184 my ($last_rev, @parents);
1185 if (my $lc = $self->last_commit) {
1186 # we can have a branch that was deleted, then re-added
1187 # under the same name but copied from another path, in
1188 # which case we'll have multiple parents (we don't
1189 # want to break the original ref, nor lose copypath info):
1190 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1191 push @{$log_entry->{parents}}, $lc;
1192 return $log_entry;
1194 $ed = Git::SVN::Fetcher->new($self);
1195 $last_rev = $self->{last_rev};
1196 $ed->{c} = $lc;
1197 @parents = ($lc);
1198 } else {
1199 $last_rev = $rev;
1200 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1201 return $log_entry;
1203 $ed = Git::SVN::Fetcher->new($self);
1205 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1206 die "SVN connection failed somewhere...\n";
1208 $self->make_log_entry($rev, \@parents, $ed);
1211 sub mkemptydirs {
1212 my ($self, $r) = @_;
1214 sub scan {
1215 my ($r, $empty_dirs, $line) = @_;
1216 if (defined $r && $line =~ /^r(\d+)$/) {
1217 return 0 if $1 > $r;
1218 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
1219 $empty_dirs->{$1} = 1;
1220 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
1221 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
1222 delete @$empty_dirs{@d};
1224 1; # continue
1227 my %empty_dirs = ();
1228 my $gz_file = "$self->{dir}/unhandled.log.gz";
1229 if (-f $gz_file) {
1230 if (!can_compress()) {
1231 warn "Compress::Zlib could not be found; ",
1232 "empty directories in $gz_file will not be read\n";
1233 } else {
1234 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
1235 die "Unable to open $gz_file: $!\n";
1236 my $line;
1237 while ($gz->gzreadline($line) > 0) {
1238 scan($r, \%empty_dirs, $line) or last;
1240 $gz->gzclose;
1244 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
1245 binmode $fh or croak "binmode: $!";
1246 while (<$fh>) {
1247 scan($r, \%empty_dirs, $_) or last;
1249 close $fh;
1252 my $strip = qr/\A\Q@{[$self->path]}\E(?:\/|$)/;
1253 foreach my $d (sort keys %empty_dirs) {
1254 $d = uri_decode($d);
1255 $d =~ s/$strip//;
1256 next unless length($d);
1257 next if -d $d;
1258 if (-e $d) {
1259 warn "$d exists but is not a directory\n";
1260 } else {
1261 print "creating empty directory: $d\n";
1262 mkpath([$d]);
1267 sub get_untracked {
1268 my ($self, $ed) = @_;
1269 my @out;
1270 my $h = $ed->{empty};
1271 foreach (sort keys %$h) {
1272 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1273 push @out, " $act: " . uri_encode($_);
1274 warn "W: $act: $_\n";
1276 foreach my $t (qw/dir_prop file_prop/) {
1277 $h = $ed->{$t} or next;
1278 foreach my $path (sort keys %$h) {
1279 my $ppath = $path eq '' ? '.' : $path;
1280 foreach my $prop (sort keys %{$h->{$path}}) {
1281 next if $SKIP_PROP{$prop};
1282 my $v = $h->{$path}->{$prop};
1283 my $t_ppath_prop = "$t: " .
1284 uri_encode($ppath) . ' ' .
1285 uri_encode($prop);
1286 if (defined $v) {
1287 push @out, " +$t_ppath_prop " .
1288 uri_encode($v);
1289 } else {
1290 push @out, " -$t_ppath_prop";
1295 foreach my $t (qw/absent_file absent_directory/) {
1296 $h = $ed->{$t} or next;
1297 foreach my $parent (sort keys %$h) {
1298 foreach my $path (sort @{$h->{$parent}}) {
1299 push @out, " $t: " .
1300 uri_encode("$parent/$path");
1301 warn "W: $t: $parent/$path ",
1302 "Insufficient permissions?\n";
1306 \@out;
1309 sub get_tz {
1310 # some systmes don't handle or mishandle %z, so be creative.
1311 my $t = shift || time;
1312 my $gm = timelocal(gmtime($t));
1313 my $sign = qw( + + - )[ $t <=> $gm ];
1314 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
1317 # parse_svn_date(DATE)
1318 # --------------------
1319 # Given a date (in UTC) from Subversion, return a string in the format
1320 # "<TZ Offset> <local date/time>" that Git will use.
1322 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
1323 # is true we'll convert it to the local timezone instead.
1324 sub parse_svn_date {
1325 my $date = shift || return '+0000 1970-01-01 00:00:00';
1326 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1327 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1328 croak "Unable to parse date: $date\n";
1329 my $parsed_date; # Set next.
1331 if ($Git::SVN::_localtime) {
1332 # Translate the Subversion datetime to an epoch time.
1333 # Begin by switching ourselves to $date's timezone, UTC.
1334 my $old_env_TZ = $ENV{TZ};
1335 $ENV{TZ} = 'UTC';
1337 my $epoch_in_UTC =
1338 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
1340 # Determine our local timezone (including DST) at the
1341 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
1342 # value of TZ, if any, at the time we were run.
1343 if (defined $Git::SVN::Log::TZ) {
1344 $ENV{TZ} = $Git::SVN::Log::TZ;
1345 } else {
1346 delete $ENV{TZ};
1349 my $our_TZ = get_tz();
1351 # This converts $epoch_in_UTC into our local timezone.
1352 my ($sec, $min, $hour, $mday, $mon, $year,
1353 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
1355 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
1356 $our_TZ, $year + 1900, $mon + 1,
1357 $mday, $hour, $min, $sec);
1359 # Reset us to the timezone in effect when we entered
1360 # this routine.
1361 if (defined $old_env_TZ) {
1362 $ENV{TZ} = $old_env_TZ;
1363 } else {
1364 delete $ENV{TZ};
1366 } else {
1367 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
1370 return $parsed_date;
1373 sub other_gs {
1374 my ($self, $new_url, $url,
1375 $branch_from, $r, $old_ref_id) = @_;
1376 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
1377 unless ($gs) {
1378 my $ref_id = $old_ref_id;
1379 $ref_id =~ s/\@\d+-*$//;
1380 $ref_id .= "\@$r";
1381 # just grow a tail if we're not unique enough :x
1382 $ref_id .= '-' while find_ref($ref_id);
1383 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
1384 if ($u =~ s#^\Q$url\E(/|$)##) {
1385 $p = $u;
1386 $u = $url;
1387 $repo_id = $self->{repo_id};
1389 while (1) {
1390 # It is possible to tag two different subdirectories at
1391 # the same revision. If the url for an existing ref
1392 # does not match, we must either find a ref with a
1393 # matching url or create a new ref by growing a tail.
1394 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
1395 my (undef, $max_commit) = $gs->rev_map_max(1);
1396 last if (!$max_commit);
1397 my ($url) = ::cmt_metadata($max_commit);
1398 last if ($url eq $gs->metadata_url);
1399 $ref_id .= '-';
1401 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
1406 sub call_authors_prog {
1407 my ($orig_author) = @_;
1408 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
1409 my $author = `$::_authors_prog $orig_author`;
1410 if ($? != 0) {
1411 die "$::_authors_prog failed with exit code $?\n"
1413 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
1414 my ($name, $email) = ($1, $2);
1415 $email = undef if length $2 == 0;
1416 return [$name, $email];
1417 } else {
1418 die "Author: $orig_author: $::_authors_prog returned "
1419 . "invalid author format: $author\n";
1423 sub check_author {
1424 my ($author) = @_;
1425 if (!defined $author || length $author == 0) {
1426 $author = '(no author)';
1428 if (!defined $::users{$author}) {
1429 if (defined $::_authors_prog) {
1430 $::users{$author} = call_authors_prog($author);
1431 } elsif (defined $::_authors) {
1432 die "Author: $author not defined in $::_authors file\n";
1435 $author;
1438 sub find_extra_svk_parents {
1439 my ($self, $ed, $tickets, $parents) = @_;
1440 # aha! svk:merge property changed...
1441 my @tickets = split "\n", $tickets;
1442 my @known_parents;
1443 for my $ticket ( @tickets ) {
1444 my ($uuid, $path, $rev) = split /:/, $ticket;
1445 if ( $uuid eq $self->ra_uuid ) {
1446 my $url = $self->url;
1447 my $repos_root = $url;
1448 my $branch_from = $path;
1449 $branch_from =~ s{^/}{};
1450 my $gs = $self->other_gs($repos_root."/".$branch_from,
1451 $url,
1452 $branch_from,
1453 $rev,
1454 $self->{ref_id});
1455 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
1456 # wahey! we found it, but it might be
1457 # an old one (!)
1458 push @known_parents, [ $rev, $commit ];
1462 # Ordering matters; highest-numbered commit merge tickets
1463 # first, as they may account for later merge ticket additions
1464 # or changes.
1465 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
1466 for my $parent ( @known_parents ) {
1467 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
1468 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
1469 my $new;
1470 while ( <$msg_fh> ) {
1471 $new=1;last;
1473 command_close_pipe($msg_fh, $ctx);
1474 if ( $new ) {
1475 print STDERR
1476 "Found merge parent (svk:merge ticket): $parent\n";
1477 push @$parents, $parent;
1482 sub lookup_svn_merge {
1483 my $uuid = shift;
1484 my $url = shift;
1485 my $merge = shift;
1487 my ($source, $revs) = split ":", $merge;
1488 my $path = $source;
1489 $path =~ s{^/}{};
1490 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
1491 if ( !$gs ) {
1492 warn "Couldn't find revmap for $url$source\n";
1493 return;
1495 my @ranges = split ",", $revs;
1496 my ($tip, $tip_commit);
1497 my @merged_commit_ranges;
1498 # find the tip
1499 for my $range ( @ranges ) {
1500 my ($bottom, $top) = split "-", $range;
1501 $top ||= $bottom;
1502 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
1503 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
1505 unless ($top_commit and $bottom_commit) {
1506 warn "W:unknown path/rev in svn:mergeinfo "
1507 ."dirprop: $source:$range\n";
1508 next;
1511 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
1512 push @merged_commit_ranges,
1513 "$bottom_commit^..$top_commit";
1514 } else {
1515 push @merged_commit_ranges, "$top_commit";
1518 if ( !defined $tip or $top > $tip ) {
1519 $tip = $top;
1520 $tip_commit = $top_commit;
1523 return ($tip_commit, @merged_commit_ranges);
1526 sub _rev_list {
1527 my ($msg_fh, $ctx) = command_output_pipe(
1528 "rev-list", @_,
1530 my @rv;
1531 while ( <$msg_fh> ) {
1532 chomp;
1533 push @rv, $_;
1535 command_close_pipe($msg_fh, $ctx);
1536 @rv;
1539 sub check_cherry_pick {
1540 my $base = shift;
1541 my $tip = shift;
1542 my $parents = shift;
1543 my @ranges = @_;
1544 my %commits = map { $_ => 1 }
1545 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
1546 for my $range ( @ranges ) {
1547 delete @commits{_rev_list($range, "--")};
1549 for my $commit (keys %commits) {
1550 if (has_no_changes($commit)) {
1551 delete $commits{$commit};
1554 return (keys %commits);
1557 sub has_no_changes {
1558 my $commit = shift;
1560 my @revs = split / /, command_oneline(
1561 qw(rev-list --parents -1 -m), $commit);
1563 # Commits with no parents, e.g. the start of a partial branch,
1564 # have changes by definition.
1565 return 1 if (@revs < 2);
1567 # Commits with multiple parents, e.g a merge, have no changes
1568 # by definition.
1569 return 0 if (@revs > 2);
1571 return (command_oneline("rev-parse", "$commit^{tree}") eq
1572 command_oneline("rev-parse", "$commit~1^{tree}"));
1575 sub tie_for_persistent_memoization {
1576 my $hash = shift;
1577 my $path = shift;
1579 if ($can_use_yaml) {
1580 tie %$hash => 'Git::SVN::Memoize::YAML', "$path.yaml";
1581 } else {
1582 tie %$hash => 'Memoize::Storable', "$path.db", 'nstore';
1586 # The GIT_DIR environment variable is not always set until after the command
1587 # line arguments are processed, so we can't memoize in a BEGIN block.
1589 my $memoized = 0;
1591 sub memoize_svn_mergeinfo_functions {
1592 return if $memoized;
1593 $memoized = 1;
1595 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1596 mkpath([$cache_path]) unless -d $cache_path;
1598 my %lookup_svn_merge_cache;
1599 my %check_cherry_pick_cache;
1600 my %has_no_changes_cache;
1602 tie_for_persistent_memoization(\%lookup_svn_merge_cache,
1603 "$cache_path/lookup_svn_merge");
1604 memoize 'lookup_svn_merge',
1605 SCALAR_CACHE => 'FAULT',
1606 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
1609 tie_for_persistent_memoization(\%check_cherry_pick_cache,
1610 "$cache_path/check_cherry_pick");
1611 memoize 'check_cherry_pick',
1612 SCALAR_CACHE => 'FAULT',
1613 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
1616 tie_for_persistent_memoization(\%has_no_changes_cache,
1617 "$cache_path/has_no_changes");
1618 memoize 'has_no_changes',
1619 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
1620 LIST_CACHE => 'FAULT',
1624 sub unmemoize_svn_mergeinfo_functions {
1625 return if not $memoized;
1626 $memoized = 0;
1628 Memoize::unmemoize 'lookup_svn_merge';
1629 Memoize::unmemoize 'check_cherry_pick';
1630 Memoize::unmemoize 'has_no_changes';
1633 Memoize::memoize 'Git::SVN::repos_root';
1636 END {
1637 # Force cache writeout explicitly instead of waiting for
1638 # global destruction to avoid segfault in Storable:
1639 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
1640 unmemoize_svn_mergeinfo_functions();
1643 sub parents_exclude {
1644 my $parents = shift;
1645 my @commits = @_;
1646 return unless @commits;
1648 my @excluded;
1649 my $excluded;
1650 do {
1651 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
1652 $excluded = command_oneline(@cmd);
1653 if ( $excluded ) {
1654 my @new;
1655 my $found;
1656 for my $commit ( @commits ) {
1657 if ( $commit eq $excluded ) {
1658 push @excluded, $commit;
1659 $found++;
1660 last;
1662 else {
1663 push @new, $commit;
1666 die "saw commit '$excluded' in rev-list output, "
1667 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
1668 unless $found;
1669 @commits = @new;
1672 while ($excluded and @commits);
1674 return @excluded;
1678 # note: this function should only be called if the various dirprops
1679 # have actually changed
1680 sub find_extra_svn_parents {
1681 my ($self, $ed, $mergeinfo, $parents) = @_;
1682 # aha! svk:merge property changed...
1684 memoize_svn_mergeinfo_functions();
1686 # We first search for merged tips which are not in our
1687 # history. Then, we figure out which git revisions are in
1688 # that tip, but not this revision. If all of those revisions
1689 # are now marked as merge, we can add the tip as a parent.
1690 my @merges = split "\n", $mergeinfo;
1691 my @merge_tips;
1692 my $url = $self->url;
1693 my $uuid = $self->ra_uuid;
1694 my %ranges;
1695 for my $merge ( @merges ) {
1696 my ($tip_commit, @ranges) =
1697 lookup_svn_merge( $uuid, $url, $merge );
1698 unless (!$tip_commit or
1699 grep { $_ eq $tip_commit } @$parents ) {
1700 push @merge_tips, $tip_commit;
1701 $ranges{$tip_commit} = \@ranges;
1702 } else {
1703 push @merge_tips, undef;
1707 my %excluded = map { $_ => 1 }
1708 parents_exclude($parents, grep { defined } @merge_tips);
1710 # check merge tips for new parents
1711 my @new_parents;
1712 for my $merge_tip ( @merge_tips ) {
1713 my $spec = shift @merges;
1714 next unless $merge_tip and $excluded{$merge_tip};
1716 my $ranges = $ranges{$merge_tip};
1718 # check out 'new' tips
1719 my $merge_base;
1720 eval {
1721 $merge_base = command_oneline(
1722 "merge-base",
1723 @$parents, $merge_tip,
1726 if ($@) {
1727 die "An error occurred during merge-base"
1728 unless $@->isa("Git::Error::Command");
1730 warn "W: Cannot find common ancestor between ".
1731 "@$parents and $merge_tip. Ignoring merge info.\n";
1732 next;
1735 # double check that there are no missing non-merge commits
1736 my (@incomplete) = check_cherry_pick(
1737 $merge_base, $merge_tip,
1738 $parents,
1739 @$ranges,
1742 if ( @incomplete ) {
1743 warn "W:svn cherry-pick ignored ($spec) - missing "
1744 .@incomplete." commit(s) (eg $incomplete[0])\n";
1745 } else {
1746 warn
1747 "Found merge parent (svn:mergeinfo prop): ",
1748 $merge_tip, "\n";
1749 push @new_parents, $merge_tip;
1753 # cater for merges which merge commits from multiple branches
1754 if ( @new_parents > 1 ) {
1755 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
1756 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
1757 next if $i == $j;
1758 next unless $new_parents[$i];
1759 next unless $new_parents[$j];
1760 my $revs = command_oneline(
1761 "rev-list", "-1",
1762 "$new_parents[$i]..$new_parents[$j]",
1764 if ( !$revs ) {
1765 undef($new_parents[$j]);
1770 push @$parents, grep { defined } @new_parents;
1773 sub make_log_entry {
1774 my ($self, $rev, $parents, $ed) = @_;
1775 my $untracked = $self->get_untracked($ed);
1777 my @parents = @$parents;
1778 my $ps = $ed->{path_strip} || "";
1779 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
1780 my $props = $ed->{dir_prop}{$path};
1781 if ( $props->{"svk:merge"} ) {
1782 $self->find_extra_svk_parents
1783 ($ed, $props->{"svk:merge"}, \@parents);
1785 if ( $props->{"svn:mergeinfo"} ) {
1786 $self->find_extra_svn_parents
1787 ($ed,
1788 $props->{"svn:mergeinfo"},
1789 \@parents);
1793 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1794 print $un "r$rev\n" or croak $!;
1795 print $un $_, "\n" foreach @$untracked;
1796 my %log_entry = ( parents => \@parents, revision => $rev,
1797 log => '');
1799 my $headrev;
1800 my $logged = delete $self->{logged_rev_props};
1801 if (!$logged || $self->{-want_revprops}) {
1802 my $rp = $self->ra->rev_proplist($rev);
1803 foreach (sort keys %$rp) {
1804 my $v = $rp->{$_};
1805 if (/^svn:(author|date|log)$/) {
1806 $log_entry{$1} = $v;
1807 } elsif ($_ eq 'svm:headrev') {
1808 $headrev = $v;
1809 } else {
1810 print $un " rev_prop: ", uri_encode($_), ' ',
1811 uri_encode($v), "\n";
1814 } else {
1815 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1817 close $un or croak $!;
1819 $log_entry{date} = parse_svn_date($log_entry{date});
1820 $log_entry{log} .= "\n";
1821 my $author = $log_entry{author} = check_author($log_entry{author});
1822 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1823 : ($author, undef);
1825 my ($commit_name, $commit_email) = ($name, $email);
1826 if ($_use_log_author) {
1827 my $name_field;
1828 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
1829 $name_field = $1;
1830 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
1831 $name_field = $1;
1833 if (!defined $name_field) {
1834 if (!defined $email) {
1835 $email = $name;
1837 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
1838 ($name, $email) = ($1, $2);
1839 } elsif ($name_field =~ /(.*)@/) {
1840 ($name, $email) = ($1, $name_field);
1841 } else {
1842 ($name, $email) = ($name_field, $name_field);
1845 if (defined $headrev && $self->use_svm_props) {
1846 if ($self->rewrite_root) {
1847 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1848 "options set!\n";
1850 if ($self->rewrite_uuid) {
1851 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
1852 "options set!\n";
1854 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
1855 # we don't want "SVM: initializing mirror for junk" ...
1856 return undef if $r == 0;
1857 my $svm = $self->svm;
1858 if ($uuid ne $svm->{uuid}) {
1859 die "UUID mismatch on SVM path:\n",
1860 "expected: $svm->{uuid}\n",
1861 " got: $uuid\n";
1863 my $full_url = $self->full_url;
1864 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1865 die "Failed to replace '$svm->{replace}' with ",
1866 "'$svm->{source}' in $full_url\n";
1867 # throw away username for storing in records
1868 remove_username($full_url);
1869 $log_entry{metadata} = "$full_url\@$r $uuid";
1870 $log_entry{svm_revision} = $r;
1871 $email ||= "$author\@$uuid";
1872 $commit_email ||= "$author\@$uuid";
1873 } elsif ($self->use_svnsync_props) {
1874 my $full_url = $self->svnsync->{url};
1875 $full_url .= "/".$self->path if length $self->path;
1876 remove_username($full_url);
1877 my $uuid = $self->svnsync->{uuid};
1878 $log_entry{metadata} = "$full_url\@$rev $uuid";
1879 $email ||= "$author\@$uuid";
1880 $commit_email ||= "$author\@$uuid";
1881 } else {
1882 my $url = $self->metadata_url;
1883 remove_username($url);
1884 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
1885 $log_entry{metadata} = "$url\@$rev " . $uuid;
1886 $email ||= "$author\@" . $uuid;
1887 $commit_email ||= "$author\@" . $uuid;
1889 $log_entry{name} = $name;
1890 $log_entry{email} = $email;
1891 $log_entry{commit_name} = $commit_name;
1892 $log_entry{commit_email} = $commit_email;
1893 \%log_entry;
1896 sub fetch {
1897 my ($self, $min_rev, $max_rev, @parents) = @_;
1898 my ($last_rev, $last_commit) = $self->last_rev_commit;
1899 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1900 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1903 sub set_tree_cb {
1904 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1905 $self->{inject_parents} = { $rev => $tree };
1906 $self->fetch(undef, undef);
1909 sub set_tree {
1910 my ($self, $tree) = (shift, shift);
1911 my $log_entry = ::get_commit_entry($tree);
1912 unless ($self->{last_rev}) {
1913 fatal("Must have an existing revision to commit");
1915 my %ed_opts = ( r => $self->{last_rev},
1916 log => $log_entry->{log},
1917 ra => $self->ra,
1918 tree_a => $self->{last_commit},
1919 tree_b => $tree,
1920 editor_cb => sub {
1921 $self->set_tree_cb($log_entry, $tree, @_) },
1922 svn_path => $self->path );
1923 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1924 print "No changes\nr$self->{last_rev} = $tree\n";
1928 sub rebuild_from_rev_db {
1929 my ($self, $path) = @_;
1930 my $r = -1;
1931 open my $fh, '<', $path or croak "open: $!";
1932 binmode $fh or croak "binmode: $!";
1933 while (<$fh>) {
1934 length($_) == 41 or croak "inconsistent size in ($_) != 41";
1935 chomp($_);
1936 ++$r;
1937 next if $_ eq ('0' x 40);
1938 $self->rev_map_set($r, $_);
1939 print "r$r = $_\n";
1941 close $fh or croak "close: $!";
1942 unlink $path or croak "unlink: $!";
1945 sub rebuild {
1946 my ($self) = @_;
1947 my $map_path = $self->map_path;
1948 my $partial = (-e $map_path && ! -z $map_path);
1949 return unless ::verify_ref($self->refname.'^0');
1950 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
1951 my $rev_db = $self->rev_db_path;
1952 $self->rebuild_from_rev_db($rev_db);
1953 if ($self->use_svm_props) {
1954 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
1955 $self->rebuild_from_rev_db($svm_rev_db);
1957 $self->unlink_rev_db_symlink;
1958 return;
1960 print "Rebuilding $map_path ...\n" if (!$partial);
1961 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
1962 (undef, undef));
1963 my ($log, $ctx) =
1964 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
1965 ($head ? "$head.." : "") . $self->refname,
1966 '--');
1967 my $metadata_url = $self->metadata_url;
1968 remove_username($metadata_url);
1969 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
1970 my $c;
1971 while (<$log>) {
1972 if ( m{^commit ($::sha1)$} ) {
1973 $c = $1;
1974 next;
1976 next unless s{^\s*(git-svn-id:)}{$1};
1977 my ($url, $rev, $uuid) = ::extract_metadata($_);
1978 remove_username($url);
1980 # ignore merges (from set-tree)
1981 next if (!defined $rev || !$uuid);
1983 # if we merged or otherwise started elsewhere, this is
1984 # how we break out of it
1985 if (($uuid ne $svn_uuid) ||
1986 ($metadata_url && $url && ($url ne $metadata_url))) {
1987 next;
1989 if ($partial && $head) {
1990 print "Partial-rebuilding $map_path ...\n";
1991 print "Currently at $base_rev = $head\n";
1992 $head = undef;
1995 $self->rev_map_set($rev, $c);
1996 print "r$rev = $c\n";
1998 command_close_pipe($log, $ctx);
1999 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2000 my $rev_db_path = $self->rev_db_path;
2001 if (-f $self->rev_db_path) {
2002 unlink $self->rev_db_path or croak "unlink: $!";
2004 $self->unlink_rev_db_symlink;
2007 # rev_map:
2008 # Tie::File seems to be prone to offset errors if revisions get sparse,
2009 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2010 # one of my favorite modules is out :< Next up would be one of the DBM
2011 # modules, but I'm not sure which is most portable...
2013 # This is the replacement for the rev_db format, which was too big
2014 # and inefficient for large repositories with a lot of sparse history
2015 # (mainly tags)
2017 # The format is this:
2018 # - 24 bytes for every record,
2019 # * 4 bytes for the integer representing an SVN revision number
2020 # * 20 bytes representing the sha1 of a git commit
2021 # - No empty padding records like the old format
2022 # (except the last record, which can be overwritten)
2023 # - new records are written append-only since SVN revision numbers
2024 # increase monotonically
2025 # - lookups on SVN revision number are done via a binary search
2026 # - Piping the file to xxd -c24 is a good way of dumping it for
2027 # viewing or editing (piped back through xxd -r), should the need
2028 # ever arise.
2029 # - The last record can be padding revision with an all-zero sha1
2030 # This is used to optimize fetch performance when using multiple
2031 # "fetch" directives in .git/config
2033 # These files are disposable unless noMetadata or useSvmProps is set
2035 sub _rev_map_set {
2036 my ($fh, $rev, $commit) = @_;
2038 binmode $fh or croak "binmode: $!";
2039 my $size = (stat($fh))[7];
2040 ($size % 24) == 0 or croak "inconsistent size: $size";
2042 my $wr_offset = 0;
2043 if ($size > 0) {
2044 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2045 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2046 $read == 24 or croak "read only $read bytes (!= 24)";
2047 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2048 if ($last_commit eq ('0' x40)) {
2049 if ($size >= 48) {
2050 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2051 $read = sysread($fh, $buf, 24) or
2052 croak "read: $!";
2053 $read == 24 or
2054 croak "read only $read bytes (!= 24)";
2055 ($last_rev, $last_commit) =
2056 unpack(rev_map_fmt, $buf);
2057 if ($last_commit eq ('0' x40)) {
2058 croak "inconsistent .rev_map\n";
2061 if ($last_rev >= $rev) {
2062 croak "last_rev is higher!: $last_rev >= $rev";
2064 $wr_offset = -24;
2067 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2068 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2069 croak "write: $!";
2072 sub _rev_map_reset {
2073 my ($fh, $rev, $commit) = @_;
2074 my $c = _rev_map_get($fh, $rev);
2075 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
2076 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
2077 truncate $fh, $offset or croak "truncate: $!";
2080 sub mkfile {
2081 my ($path) = @_;
2082 unless (-e $path) {
2083 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2084 mkpath([$dir]) unless -d $dir;
2085 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2086 close $fh or die "Couldn't close (create) $path: $!\n";
2090 sub rev_map_set {
2091 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2092 defined $commit or die "missing arg3\n";
2093 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2094 my $db = $self->map_path($uuid);
2095 my $db_lock = "$db.lock";
2096 my $sigmask;
2097 $update_ref ||= 0;
2098 if ($update_ref) {
2099 $sigmask = POSIX::SigSet->new();
2100 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
2101 SIGALRM, SIGUSR1, SIGUSR2);
2102 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
2103 croak "Can't block signals: $!";
2105 mkfile($db);
2107 $LOCKFILES{$db_lock} = 1;
2108 my $sync;
2109 # both of these options make our .rev_db file very, very important
2110 # and we can't afford to lose it because rebuild() won't work
2111 if ($self->use_svm_props || $self->no_metadata) {
2112 $sync = 1;
2113 copy($db, $db_lock) or die "rev_map_set(@_): ",
2114 "Failed to copy: ",
2115 "$db => $db_lock ($!)\n";
2116 } else {
2117 rename $db, $db_lock or die "rev_map_set(@_): ",
2118 "Failed to rename: ",
2119 "$db => $db_lock ($!)\n";
2122 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2123 or croak "Couldn't open $db_lock: $!\n";
2124 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
2125 _rev_map_set($fh, $rev, $commit);
2126 if ($sync) {
2127 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2128 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2130 close $fh or croak $!;
2131 if ($update_ref) {
2132 $_head = $self;
2133 my $note = "";
2134 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
2135 command_noisy('update-ref', '-m', "r$rev$note",
2136 $self->refname, $commit);
2138 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2139 "$db_lock => $db ($!)\n";
2140 delete $LOCKFILES{$db_lock};
2141 if ($update_ref) {
2142 sigprocmask(SIG_SETMASK, $sigmask) or
2143 croak "Can't restore signal mask: $!";
2147 # If want_commit, this will return an array of (rev, commit) where
2148 # commit _must_ be a valid commit in the archive.
2149 # Otherwise, it'll return the max revision (whether or not the
2150 # commit is valid or just a 0x40 placeholder).
2151 sub rev_map_max {
2152 my ($self, $want_commit) = @_;
2153 $self->rebuild;
2154 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2155 $want_commit ? ($r, $c) : $r;
2158 sub rev_map_max_norebuild {
2159 my ($self, $want_commit) = @_;
2160 my $map_path = $self->map_path;
2161 stat $map_path or return $want_commit ? (0, undef) : 0;
2162 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2163 binmode $fh or croak "binmode: $!";
2164 my $size = (stat($fh))[7];
2165 ($size % 24) == 0 or croak "inconsistent size: $size";
2167 if ($size == 0) {
2168 close $fh or croak "close: $!";
2169 return $want_commit ? (0, undef) : 0;
2172 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2173 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2174 my ($r, $c) = unpack(rev_map_fmt, $buf);
2175 if ($want_commit && $c eq ('0' x40)) {
2176 if ($size < 48) {
2177 return $want_commit ? (0, undef) : 0;
2179 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2180 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2181 ($r, $c) = unpack(rev_map_fmt, $buf);
2182 if ($c eq ('0'x40)) {
2183 croak "Penultimate record is all-zeroes in $map_path";
2186 close $fh or croak "close: $!";
2187 $want_commit ? ($r, $c) : $r;
2190 sub rev_map_get {
2191 my ($self, $rev, $uuid) = @_;
2192 my $map_path = $self->map_path($uuid);
2193 return undef unless -e $map_path;
2195 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2196 my $c = _rev_map_get($fh, $rev);
2197 close($fh) or croak "close: $!";
2201 sub _rev_map_get {
2202 my ($fh, $rev) = @_;
2204 binmode $fh or croak "binmode: $!";
2205 my $size = (stat($fh))[7];
2206 ($size % 24) == 0 or croak "inconsistent size: $size";
2208 if ($size == 0) {
2209 return undef;
2212 my ($l, $u) = (0, $size - 24);
2213 my ($r, $c, $buf);
2215 while ($l <= $u) {
2216 my $i = int(($l/24 + $u/24) / 2) * 24;
2217 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2218 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2219 my ($r, $c) = unpack(rev_map_fmt, $buf);
2221 if ($r < $rev) {
2222 $l = $i + 24;
2223 } elsif ($r > $rev) {
2224 $u = $i - 24;
2225 } else { # $r == $rev
2226 return $c eq ('0' x 40) ? undef : $c;
2229 undef;
2232 # Finds the first svn revision that exists on (if $eq_ok is true) or
2233 # before $rev for the current branch. It will not search any lower
2234 # than $min_rev. Returns the git commit hash and svn revision number
2235 # if found, else (undef, undef).
2236 sub find_rev_before {
2237 my ($self, $rev, $eq_ok, $min_rev) = @_;
2238 --$rev unless $eq_ok;
2239 $min_rev ||= 1;
2240 my $max_rev = $self->rev_map_max;
2241 $rev = $max_rev if ($rev > $max_rev);
2242 while ($rev >= $min_rev) {
2243 if (my $c = $self->rev_map_get($rev)) {
2244 return ($rev, $c);
2246 --$rev;
2248 return (undef, undef);
2251 # Finds the first svn revision that exists on (if $eq_ok is true) or
2252 # after $rev for the current branch. It will not search any higher
2253 # than $max_rev. Returns the git commit hash and svn revision number
2254 # if found, else (undef, undef).
2255 sub find_rev_after {
2256 my ($self, $rev, $eq_ok, $max_rev) = @_;
2257 ++$rev unless $eq_ok;
2258 $max_rev ||= $self->rev_map_max;
2259 while ($rev <= $max_rev) {
2260 if (my $c = $self->rev_map_get($rev)) {
2261 return ($rev, $c);
2263 ++$rev;
2265 return (undef, undef);
2268 sub _new {
2269 my ($class, $repo_id, $ref_id, $path) = @_;
2270 unless (defined $repo_id && length $repo_id) {
2271 $repo_id = $default_repo_id;
2273 unless (defined $ref_id && length $ref_id) {
2274 # Access the prefix option from the git-svn main program if it's loaded.
2275 my $prefix = defined &::opt_prefix ? ::opt_prefix() : "";
2276 $_[2] = $ref_id =
2277 "refs/remotes/$prefix$default_ref_id";
2279 $_[1] = $repo_id;
2280 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2282 # Older repos imported by us used $GIT_DIR/svn/foo instead of
2283 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
2284 if ($ref_id =~ m{^refs/remotes/(.*)}) {
2285 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
2286 if (-d $old_dir && ! -d $dir) {
2287 $dir = $old_dir;
2291 $_[3] = $path = '' unless (defined $path);
2292 mkpath([$dir]);
2293 my $obj = bless {
2294 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2295 config => "$ENV{GIT_DIR}/svn/config",
2296 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2298 # Ensure it gets canonicalized
2299 $obj->path($path);
2301 return $obj;
2304 sub path {
2305 my $self = shift;
2307 if (@_) {
2308 my $path = shift;
2309 $self->{path} = canonicalize_path($path);
2310 return;
2313 return $self->{path};
2316 sub url {
2317 my $self = shift;
2319 if (@_) {
2320 my $url = shift;
2321 $self->{url} = canonicalize_url($url);
2322 return;
2325 return $self->{url};
2328 # for read-only access of old .rev_db formats
2329 sub unlink_rev_db_symlink {
2330 my ($self) = @_;
2331 my $link = $self->rev_db_path;
2332 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2333 if (-l $link) {
2334 unlink $link or croak "unlink: $link failed!";
2338 sub rev_db_path {
2339 my ($self, $uuid) = @_;
2340 my $db_path = $self->map_path($uuid);
2341 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2342 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2343 $db_path;
2346 # the new replacement for .rev_db
2347 sub map_path {
2348 my ($self, $uuid) = @_;
2349 $uuid ||= $self->ra_uuid;
2350 "$self->{map_root}.$uuid";
2353 sub uri_encode {
2354 my ($f) = @_;
2355 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2359 sub uri_decode {
2360 my ($f) = @_;
2361 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
2365 sub remove_username {
2366 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};