use Git::SVN->path accessor globally
[alt-git.git] / perl / Git / SVN.pm
bloba16acbbbfffea35cf325f602ecda30258000a3d9
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(fatal can_compress);
28 my $can_use_yaml;
29 BEGIN {
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:
41 my %SKIP_PROP;
42 BEGIN {
43 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
44 svn:special svn:executable
45 svn:entry:committed-rev
46 svn:entry:last-author
47 svn:entry:uuid
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
53 no strict 'refs';
54 for my $option (qw/follow_parent no_metadata use_svm_props
55 use_svnsync_props/) {
56 my $key = $option;
57 $key =~ tr/_//d;
58 my $prop = "-$option";
59 *$option = sub {
60 my ($self) = @_;
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) };
64 if ($@) {
65 $self->{$prop} = ${"Git::SVN::_$option"};
66 } else {
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);
77 END {
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}$#;
89 my $p = $1;
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",
105 " real path: $u\n",
106 "Continuing ahead with $u\n";
107 next;
109 } else {
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";
128 sub fetch_all {
129 my ($repo_id, $remotes) = @_;
130 if (ref $repo_id) {
131 my $gs = $repo_id;
132 $repo_id = undef;
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";
140 my (@gs, @globs);
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)) {
159 $base = $max_rev;
160 } elsif (!defined $max_rev) {
161 $base = 0;
165 if ($fetch) {
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;
169 if (defined $lr) {
170 $base = $lr if ($lr < $base);
172 push @gs, $gs;
176 ($base, $head) = parse_revision_argument($base, $head);
177 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
180 sub read_all_remotes {
181 my $r = {};
182 my $use_svm_props = eval { command_oneline(qw/config --bool
183 svn.useSvmProps/) };
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) =
205 ($1, $2, $3, $4);
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);
211 require Git::SVN::GlobSpec;
212 my $rs = {
213 t => $t,
214 remote => $remote,
215 path => Git::SVN::GlobSpec->new($local_ref, 1),
216 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
217 if (length($rs->{ref}->{right}) != 0) {
218 die "The '*' glob character must be the last ",
219 "character of '$remote_ref'\n";
221 push @{ $r->{$remote}->{$t} }, $rs;
225 map {
226 if (defined $r->{$_}->{svm}) {
227 my $svm;
228 eval {
229 my $section = "svn-remote.$_";
230 $svm = {
231 source => tmp_config('--get',
232 "$section.svm-source"),
233 replace => tmp_config('--get',
234 "$section.svm-replace"),
237 $r->{$_}->{svm} = $svm;
239 } keys %$r;
241 foreach my $remote (keys %$r) {
242 foreach ( grep { defined $_ }
243 map { $r->{$remote}->{$_} } qw(branches tags) ) {
244 foreach my $rs ( @$_ ) {
245 $rs->{ignore_refs_regex} =
246 $r->{$remote}->{ignore_refs_regex};
254 sub init_vars {
255 $_gc_nr = $_gc_period = 1000;
256 if (defined $_repack || defined $_repack_flags) {
257 warn "Repack options are obsolete; they have no effect.\n";
261 sub verify_remotes_sanity {
262 return unless -d $ENV{GIT_DIR};
263 my %seen;
264 foreach (command(qw/config -l/)) {
265 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
266 if ($seen{$1}) {
267 die "Remote ref refs/remote/$1 is tracked by",
268 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
269 "Please resolve this ambiguity in ",
270 "your git configuration file before ",
271 "continuing\n";
273 $seen{$1} = $_;
278 sub find_existing_remote {
279 my ($url, $remotes) = @_;
280 return undef if $no_reuse_existing;
281 my $existing;
282 foreach my $repo_id (keys %$remotes) {
283 my $u = $remotes->{$repo_id}->{url} or next;
284 next if $u ne $url;
285 $existing = $repo_id;
286 last;
288 $existing;
291 sub init_remote_config {
292 my ($self, $url, $no_write) = @_;
293 $url =~ s!/+$!!; # strip trailing slash
294 my $r = read_all_remotes();
295 my $existing = find_existing_remote($url, $r);
296 if ($existing) {
297 unless ($no_write) {
298 print STDERR "Using existing ",
299 "[svn-remote \"$existing\"]\n";
301 $self->{repo_id} = $existing;
302 } elsif ($_minimize_url) {
303 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
304 $existing = find_existing_remote($min_url, $r);
305 if ($existing) {
306 unless ($no_write) {
307 print STDERR "Using existing ",
308 "[svn-remote \"$existing\"]\n";
310 $self->{repo_id} = $existing;
312 if ($min_url ne $url) {
313 unless ($no_write) {
314 print STDERR "Using higher level of URL: ",
315 "$url => $min_url\n";
317 my $old_path = $self->path;
318 $url =~ s!^\Q$min_url\E(/|$)!!;
319 if (length $old_path) {
320 $url .= "/$old_path";
322 $self->path($url);
323 $url = $min_url;
326 my $orig_url;
327 if (!$existing) {
328 # verify that we aren't overwriting anything:
329 $orig_url = eval {
330 command_oneline('config', '--get',
331 "svn-remote.$self->{repo_id}.url")
333 if ($orig_url && ($orig_url ne $url)) {
334 die "svn-remote.$self->{repo_id}.url already set: ",
335 "$orig_url\nwanted to set to: $url\n";
338 my ($xrepo_id, $xpath) = find_ref($self->refname);
339 if (!$no_write && defined $xpath) {
340 die "svn-remote.$xrepo_id.fetch already set to track ",
341 "$xpath:", $self->refname, "\n";
343 unless ($no_write) {
344 command_noisy('config',
345 "svn-remote.$self->{repo_id}.url", $url);
346 my $path = $self->path;
347 $path =~ s{^/}{};
348 $path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
349 $self->path($path);
350 command_noisy('config', '--add',
351 "svn-remote.$self->{repo_id}.fetch",
352 $self->path.":".$self->refname);
354 $self->url($url);
357 sub find_by_url { # repos_root and, path are optional
358 my ($class, $full_url, $repos_root, $path) = @_;
360 return undef unless defined $full_url;
361 remove_username($full_url);
362 remove_username($repos_root) if defined $repos_root;
363 my $remotes = read_all_remotes();
364 if (defined $full_url && defined $repos_root && !defined $path) {
365 $path = $full_url;
366 $path =~ s#^\Q$repos_root\E(?:/|$)##;
368 foreach my $repo_id (keys %$remotes) {
369 my $u = $remotes->{$repo_id}->{url} or next;
370 remove_username($u);
371 next if defined $repos_root && $repos_root ne $u;
373 my $fetch = $remotes->{$repo_id}->{fetch} || {};
374 foreach my $t (qw/branches tags/) {
375 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
376 resolve_local_globs($u, $fetch, $globspec);
379 my $p = $path;
380 my $rwr = rewrite_root({repo_id => $repo_id});
381 my $svm = $remotes->{$repo_id}->{svm}
382 if defined $remotes->{$repo_id}->{svm};
383 unless (defined $p) {
384 $p = $full_url;
385 my $z = $u;
386 my $prefix = '';
387 if ($rwr) {
388 $z = $rwr;
389 remove_username($z);
390 } elsif (defined $svm) {
391 $z = $svm->{source};
392 $prefix = $svm->{replace};
393 $prefix =~ s#^\Q$u\E(?:/|$)##;
394 $prefix =~ s#/$##;
396 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
398 foreach my $f (keys %$fetch) {
399 next if $f ne $p;
400 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
403 undef;
406 sub init {
407 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
408 my $self = _new($class, $repo_id, $ref_id, $path);
409 if (defined $url) {
410 $self->init_remote_config($url, $no_write);
412 $self;
415 sub find_ref {
416 my ($ref_id) = @_;
417 foreach (command(qw/config -l/)) {
418 next unless m!^svn-remote\.(.+)\.fetch=
419 \s*(.*?)\s*:\s*(.+?)\s*$!x;
420 my ($repo_id, $path, $ref) = ($1, $2, $3);
421 if ($ref eq $ref_id) {
422 $path = '' if ($path =~ m#^\./?#);
423 return ($repo_id, $path);
426 (undef, undef, undef);
429 sub new {
430 my ($class, $ref_id, $repo_id, $path) = @_;
431 if (defined $ref_id && !defined $repo_id && !defined $path) {
432 ($repo_id, $path) = find_ref($ref_id);
433 if (!defined $repo_id) {
434 die "Could not find a \"svn-remote.*.fetch\" key ",
435 "in the repository configuration matching: ",
436 "$ref_id\n";
439 my $self = _new($class, $repo_id, $ref_id, $path);
440 if (!defined $self->path || !length $self->path) {
441 my $fetch = command_oneline('config', '--get',
442 "svn-remote.$repo_id.fetch",
443 ":$ref_id\$") or
444 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
445 "\":$ref_id\$\" in config\n";
446 my($path) = split(/\s*:\s*/, $fetch);
447 $self->path($path);
450 my $path = $self->path;
451 $path =~ s{/+}{/}g;
452 $path =~ s{\A/}{};
453 $path =~ s{/\z}{};
454 $self->path($path);
456 my $url = command_oneline('config', '--get',
457 "svn-remote.$repo_id.url") or
458 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
459 $self->url($url);
460 $self->{pushurl} = eval { command_oneline('config', '--get',
461 "svn-remote.$repo_id.pushurl") };
462 $self->rebuild;
463 $self;
466 sub refname {
467 my ($refname) = $_[0]->{ref_id} ;
469 # It cannot end with a slash /, we'll throw up on this because
470 # SVN can't have directories with a slash in their name, either:
471 if ($refname =~ m{/$}) {
472 die "ref: '$refname' ends with a trailing slash, this is ",
473 "not permitted by git nor Subversion\n";
476 # It cannot have ASCII control character space, tilde ~, caret ^,
477 # colon :, question-mark ?, asterisk *, space, or open bracket [
478 # anywhere.
480 # Additionally, % must be escaped because it is used for escaping
481 # and we want our escaped refname to be reversible
482 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
484 # no slash-separated component can begin with a dot .
485 # /.* becomes /%2E*
486 $refname =~ s{/\.}{/%2E}g;
488 # It cannot have two consecutive dots .. anywhere
489 # .. becomes %2E%2E
490 $refname =~ s{\.\.}{%2E%2E}g;
492 # trailing dots and .lock are not allowed
493 # .$ becomes %2E and .lock becomes %2Elock
494 $refname =~ s{\.(?=$|lock$)}{%2E};
496 # the sequence @{ is used to access the reflog
497 # @{ becomes %40{
498 $refname =~ s{\@\{}{%40\{}g;
500 return $refname;
503 sub desanitize_refname {
504 my ($refname) = @_;
505 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
506 return $refname;
509 sub svm_uuid {
510 my ($self) = @_;
511 return $self->{svm}->{uuid} if $self->svm;
512 $self->ra;
513 unless ($self->{svm}) {
514 die "SVM UUID not cached, and reading remotely failed\n";
516 $self->{svm}->{uuid};
519 sub svm {
520 my ($self) = @_;
521 return $self->{svm} if $self->{svm};
522 my $svm;
523 # see if we have it in our config, first:
524 eval {
525 my $section = "svn-remote.$self->{repo_id}";
526 $svm = {
527 source => tmp_config('--get', "$section.svm-source"),
528 uuid => tmp_config('--get', "$section.svm-uuid"),
529 replace => tmp_config('--get', "$section.svm-replace"),
532 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
533 $self->{svm} = $svm;
535 $self->{svm};
538 sub _set_svm_vars {
539 my ($self, $ra) = @_;
540 return $ra if $self->svm;
542 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
543 "(svm:source, svm:uuid) ",
544 "from the following URLs:\n" );
545 sub read_svm_props {
546 my ($self, $ra, $path, $r) = @_;
547 my $props = ($ra->get_dir($path, $r))[2];
548 my $src = $props->{'svm:source'};
549 my $uuid = $props->{'svm:uuid'};
550 return undef if (!$src || !$uuid);
552 chomp($src, $uuid);
554 $uuid =~ m{^[0-9a-f\-]{30,}$}i
555 or die "doesn't look right - svm:uuid is '$uuid'\n";
557 # the '!' is used to mark the repos_root!/relative/path
558 $src =~ s{/?!/?}{/};
559 $src =~ s{/+$}{}; # no trailing slashes please
560 # username is of no interest
561 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
563 my $replace = $ra->{url};
564 $replace .= "/$path" if length $path;
566 my $section = "svn-remote.$self->{repo_id}";
567 tmp_config("$section.svm-source", $src);
568 tmp_config("$section.svm-replace", $replace);
569 tmp_config("$section.svm-uuid", $uuid);
570 $self->{svm} = {
571 source => $src,
572 uuid => $uuid,
573 replace => $replace
577 my $r = $ra->get_latest_revnum;
578 my $path = $self->path;
579 my %tried;
580 while (length $path) {
581 my $try = $self->url . "/$path";
582 unless ($tried{$try}) {
583 return $ra if $self->read_svm_props($ra, $path, $r);
584 $tried{$try} = 1;
586 $path =~ s#/?[^/]+$##;
588 die "Path: '$path' should be ''\n" if $path ne '';
589 return $ra if $self->read_svm_props($ra, $path, $r);
590 $tried{$self->url."/$path"} = 1;
592 if ($ra->{repos_root} eq $self->url) {
593 die @err, (map { " $_\n" } keys %tried), "\n";
596 # nope, make sure we're connected to the repository root:
597 my $ok;
598 my @tried_b;
599 $path = $ra->{svn_path};
600 $ra = Git::SVN::Ra->new($ra->{repos_root});
601 while (length $path) {
602 unless ($tried{"$ra->{url}/$path"}) {
603 $ok = $self->read_svm_props($ra, $path, $r);
604 last if $ok;
605 $tried{"$ra->{url}/$path"} = 1;
607 $path =~ s#/?[^/]+$##;
609 die "Path: '$path' should be ''\n" if $path ne '';
610 $ok ||= $self->read_svm_props($ra, $path, $r);
611 $tried{"$ra->{url}/$path"} = 1;
612 if (!$ok) {
613 die @err, (map { " $_\n" } keys %tried), "\n";
615 Git::SVN::Ra->new($self->url);
618 sub svnsync {
619 my ($self) = @_;
620 return $self->{svnsync} if $self->{svnsync};
622 if ($self->no_metadata) {
623 die "Can't have both 'noMetadata' and ",
624 "'useSvnsyncProps' options set!\n";
626 if ($self->rewrite_root) {
627 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
628 "options set!\n";
630 if ($self->rewrite_uuid) {
631 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
632 "options set!\n";
635 my $svnsync;
636 # see if we have it in our config, first:
637 eval {
638 my $section = "svn-remote.$self->{repo_id}";
640 my $url = tmp_config('--get', "$section.svnsync-url");
641 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
642 die "doesn't look right - svn:sync-from-url is '$url'\n";
644 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
645 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
646 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
648 $svnsync = { url => $url, uuid => $uuid }
650 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
651 return $self->{svnsync} = $svnsync;
654 my $err = "useSvnsyncProps set, but failed to read " .
655 "svnsync property: svn:sync-from-";
656 my $rp = $self->ra->rev_proplist(0);
658 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
659 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
660 die "doesn't look right - svn:sync-from-url is '$url'\n";
662 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
663 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
664 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
666 my $section = "svn-remote.$self->{repo_id}";
667 tmp_config('--add', "$section.svnsync-uuid", $uuid);
668 tmp_config('--add', "$section.svnsync-url", $url);
669 return $self->{svnsync} = { url => $url, uuid => $uuid };
672 # this allows us to memoize our SVN::Ra UUID locally and avoid a
673 # remote lookup (useful for 'git svn log').
674 sub ra_uuid {
675 my ($self) = @_;
676 unless ($self->{ra_uuid}) {
677 my $key = "svn-remote.$self->{repo_id}.uuid";
678 my $uuid = eval { tmp_config('--get', $key) };
679 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
680 $self->{ra_uuid} = $uuid;
681 } else {
682 die "ra_uuid called without URL\n" unless $self->url;
683 $self->{ra_uuid} = $self->ra->get_uuid;
684 tmp_config('--add', $key, $self->{ra_uuid});
687 $self->{ra_uuid};
690 sub _set_repos_root {
691 my ($self, $repos_root) = @_;
692 my $k = "svn-remote.$self->{repo_id}.reposRoot";
693 $repos_root ||= $self->ra->{repos_root};
694 tmp_config($k, $repos_root);
695 $repos_root;
698 sub repos_root {
699 my ($self) = @_;
700 my $k = "svn-remote.$self->{repo_id}.reposRoot";
701 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
704 sub ra {
705 my ($self) = shift;
706 my $ra = Git::SVN::Ra->new($self->url);
707 $self->_set_repos_root($ra->{repos_root});
708 if ($self->use_svm_props && !$self->{svm}) {
709 if ($self->no_metadata) {
710 die "Can't have both 'noMetadata' and ",
711 "'useSvmProps' options set!\n";
712 } elsif ($self->use_svnsync_props) {
713 die "Can't have both 'useSvnsyncProps' and ",
714 "'useSvmProps' options set!\n";
716 $ra = $self->_set_svm_vars($ra);
717 $self->{-want_revprops} = 1;
719 $ra;
722 # prop_walk(PATH, REV, SUB)
723 # -------------------------
724 # Recursively traverse PATH at revision REV and invoke SUB for each
725 # directory that contains a SVN property. SUB will be invoked as
726 # follows: &SUB(gs, path, props); where `gs' is this instance of
727 # Git::SVN, `path' the path to the directory where the properties
728 # `props' were found. The `path' will be relative to point of checkout,
729 # that is, if url://repo/trunk is the current Git branch, and that
730 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
731 # as `path' (note the trailing `/').
732 sub prop_walk {
733 my ($self, $path, $rev, $sub) = @_;
735 $path =~ s#^/##;
736 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
737 $path =~ s#^/*#/#g;
738 my $p = $path;
739 # Strip the irrelevant part of the path.
740 $p =~ s#^/+\Q@{[$self->path]}\E(/|$)#/#;
741 # Ensure the path is terminated by a `/'.
742 $p =~ s#/*$#/#;
744 # The properties contain all the internal SVN stuff nobody
745 # (usually) cares about.
746 my $interesting_props = 0;
747 foreach (keys %{$props}) {
748 # If it doesn't start with `svn:', it must be a
749 # user-defined property.
750 ++$interesting_props and next if $_ !~ /^svn:/;
751 # FIXME: Fragile, if SVN adds new public properties,
752 # this needs to be updated.
753 ++$interesting_props if /^svn:(?:ignore|keywords|executable
754 |eol-style|mime-type
755 |externals|needs-lock)$/x;
757 &$sub($self, $p, $props) if $interesting_props;
759 foreach (sort keys %$dirent) {
760 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
761 $self->prop_walk($self->path . $p . $_, $rev, $sub);
765 sub last_rev { ($_[0]->last_rev_commit)[0] }
766 sub last_commit { ($_[0]->last_rev_commit)[1] }
768 # returns the newest SVN revision number and newest commit SHA1
769 sub last_rev_commit {
770 my ($self) = @_;
771 if (defined $self->{last_rev} && defined $self->{last_commit}) {
772 return ($self->{last_rev}, $self->{last_commit});
774 my $c = ::verify_ref($self->refname.'^0');
775 if ($c && !$self->use_svm_props && !$self->no_metadata) {
776 my $rev = (::cmt_metadata($c))[1];
777 if (defined $rev) {
778 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
779 return ($rev, $c);
782 my $map_path = $self->map_path;
783 unless (-e $map_path) {
784 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
785 return (undef, undef);
787 my ($rev, $commit) = $self->rev_map_max(1);
788 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
789 return ($rev, $commit);
792 sub get_fetch_range {
793 my ($self, $min, $max) = @_;
794 $max ||= $self->ra->get_latest_revnum;
795 $min ||= $self->rev_map_max;
796 (++$min, $max);
799 sub tmp_config {
800 my (@args) = @_;
801 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
802 my $config = "$ENV{GIT_DIR}/svn/.metadata";
803 if (! -f $config && -f $old_def_config) {
804 rename $old_def_config, $config or
805 die "Failed rename $old_def_config => $config: $!\n";
807 my $old_config = $ENV{GIT_CONFIG};
808 $ENV{GIT_CONFIG} = $config;
809 $@ = undef;
810 my @ret = eval {
811 unless (-f $config) {
812 mkfile($config);
813 open my $fh, '>', $config or
814 die "Can't open $config: $!\n";
815 print $fh "; This file is used internally by ",
816 "git-svn\n" or die
817 "Couldn't write to $config: $!\n";
818 print $fh "; You should not have to edit it\n" or
819 die "Couldn't write to $config: $!\n";
820 close $fh or die "Couldn't close $config: $!\n";
822 command('config', @args);
824 my $err = $@;
825 if (defined $old_config) {
826 $ENV{GIT_CONFIG} = $old_config;
827 } else {
828 delete $ENV{GIT_CONFIG};
830 die $err if $err;
831 wantarray ? @ret : $ret[0];
834 sub tmp_index_do {
835 my ($self, $sub) = @_;
836 my $old_index = $ENV{GIT_INDEX_FILE};
837 $ENV{GIT_INDEX_FILE} = $self->{index};
838 $@ = undef;
839 my @ret = eval {
840 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
841 mkpath([$dir]) unless -d $dir;
842 &$sub;
844 my $err = $@;
845 if (defined $old_index) {
846 $ENV{GIT_INDEX_FILE} = $old_index;
847 } else {
848 delete $ENV{GIT_INDEX_FILE};
850 die $err if $err;
851 wantarray ? @ret : $ret[0];
854 sub assert_index_clean {
855 my ($self, $treeish) = @_;
857 $self->tmp_index_do(sub {
858 command_noisy('read-tree', $treeish) unless -e $self->{index};
859 my $x = command_oneline('write-tree');
860 my ($y) = (command(qw/cat-file commit/, $treeish) =~
861 /^tree ($::sha1)/mo);
862 return if $y eq $x;
864 warn "Index mismatch: $y != $x\nrereading $treeish\n";
865 unlink $self->{index} or die "unlink $self->{index}: $!\n";
866 command_noisy('read-tree', $treeish);
867 $x = command_oneline('write-tree');
868 if ($y ne $x) {
869 fatal "trees ($treeish) $y != $x\n",
870 "Something is seriously wrong...";
875 sub get_commit_parents {
876 my ($self, $log_entry) = @_;
877 my (%seen, @ret, @tmp);
878 # legacy support for 'set-tree'; this is only used by set_tree_cb:
879 if (my $ip = $self->{inject_parents}) {
880 if (my $commit = delete $ip->{$log_entry->{revision}}) {
881 push @tmp, $commit;
884 if (my $cur = ::verify_ref($self->refname.'^0')) {
885 push @tmp, $cur;
887 if (my $ipd = $self->{inject_parents_dcommit}) {
888 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
889 push @tmp, @$commit;
892 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
893 while (my $p = shift @tmp) {
894 next if $seen{$p};
895 $seen{$p} = 1;
896 push @ret, $p;
898 @ret;
901 sub rewrite_root {
902 my ($self) = @_;
903 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
904 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
905 my $rwr = eval { command_oneline(qw/config --get/, $k) };
906 if ($rwr) {
907 $rwr =~ s#/+$##;
908 if ($rwr !~ m#^[a-z\+]+://#) {
909 die "$rwr is not a valid URL (key: $k)\n";
912 $self->{-rewrite_root} = $rwr;
915 sub rewrite_uuid {
916 my ($self) = @_;
917 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
918 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
919 my $rwid = eval { command_oneline(qw/config --get/, $k) };
920 if ($rwid) {
921 $rwid =~ s#/+$##;
922 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
923 die "$rwid is not a valid UUID (key: $k)\n";
926 $self->{-rewrite_uuid} = $rwid;
929 sub metadata_url {
930 my ($self) = @_;
931 ($self->rewrite_root || $self->url) .
932 (length $self->path ? '/' . $self->path : '');
935 sub full_url {
936 my ($self) = @_;
937 $self->url . (length $self->path ? '/' . $self->path : '');
940 sub full_pushurl {
941 my ($self) = @_;
942 if ($self->{pushurl}) {
943 return $self->{pushurl} . (length $self->path ? '/' .
944 $self->path : '');
945 } else {
946 return $self->full_url;
950 sub set_commit_header_env {
951 my ($log_entry) = @_;
952 my %env;
953 foreach my $ned (qw/NAME EMAIL DATE/) {
954 foreach my $ac (qw/AUTHOR COMMITTER/) {
955 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
959 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
960 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
961 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
963 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
964 ? $log_entry->{commit_name}
965 : $log_entry->{name};
966 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
967 ? $log_entry->{commit_email}
968 : $log_entry->{email};
969 \%env;
972 sub restore_commit_header_env {
973 my ($env) = @_;
974 foreach my $ned (qw/NAME EMAIL DATE/) {
975 foreach my $ac (qw/AUTHOR COMMITTER/) {
976 my $k = "GIT_${ac}_${ned}";
977 if (defined $env->{$k}) {
978 $ENV{$k} = $env->{$k};
979 } else {
980 delete $ENV{$k};
986 sub gc {
987 command_noisy('gc', '--auto');
990 sub do_git_commit {
991 my ($self, $log_entry) = @_;
992 my $lr = $self->last_rev;
993 if (defined $lr && $lr >= $log_entry->{revision}) {
994 die "Last fetched revision of ", $self->refname,
995 " was r$lr, but we are about to fetch: ",
996 "r$log_entry->{revision}!\n";
998 if (my $c = $self->rev_map_get($log_entry->{revision})) {
999 croak "$log_entry->{revision} = $c already exists! ",
1000 "Why are we refetching it?\n";
1002 my $old_env = set_commit_header_env($log_entry);
1003 my $tree = $log_entry->{tree};
1004 if (!defined $tree) {
1005 $tree = $self->tmp_index_do(sub {
1006 command_oneline('write-tree') });
1008 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1010 my @exec = ('git', 'commit-tree', $tree);
1011 foreach ($self->get_commit_parents($log_entry)) {
1012 push @exec, '-p', $_;
1014 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1015 or croak $!;
1016 binmode $msg_fh;
1018 # we always get UTF-8 from SVN, but we may want our commits in
1019 # a different encoding.
1020 if (my $enc = Git::config('i18n.commitencoding')) {
1021 require Encode;
1022 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
1024 print $msg_fh $log_entry->{log} or croak $!;
1025 restore_commit_header_env($old_env);
1026 unless ($self->no_metadata) {
1027 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1028 or croak $!;
1030 $msg_fh->flush == 0 or croak $!;
1031 close $msg_fh or croak $!;
1032 chomp(my $commit = do { local $/; <$out_fh> });
1033 close $out_fh or croak $!;
1034 waitpid $pid, 0;
1035 croak $? if $?;
1036 if ($commit !~ /^$::sha1$/o) {
1037 die "Failed to commit, invalid sha1: $commit\n";
1040 $self->rev_map_set($log_entry->{revision}, $commit, 1);
1042 $self->{last_rev} = $log_entry->{revision};
1043 $self->{last_commit} = $commit;
1044 print "r$log_entry->{revision}" unless $::_q > 1;
1045 if (defined $log_entry->{svm_revision}) {
1046 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
1047 $self->rev_map_set($log_entry->{svm_revision}, $commit,
1048 0, $self->svm_uuid);
1050 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
1051 if (--$_gc_nr == 0) {
1052 $_gc_nr = $_gc_period;
1053 gc();
1055 return $commit;
1058 sub match_paths {
1059 my ($self, $paths, $r) = @_;
1060 return 1 if $self->path eq '';
1061 if (my $path = $paths->{"/".$self->path}) {
1062 return ($path->{action} eq 'D') ? 0 : 1;
1064 $self->{path_regex} ||= qr{^/\Q@{[$self->path]}\E/};
1065 if (grep /$self->{path_regex}/, keys %$paths) {
1066 return 1;
1068 my $c = '';
1069 foreach (split m#/#, $self->path) {
1070 $c .= "/$_";
1071 next unless ($paths->{$c} &&
1072 ($paths->{$c}->{action} =~ /^[AR]$/));
1073 if ($self->ra->check_path($self->path, $r) ==
1074 $SVN::Node::dir) {
1075 return 1;
1078 return 0;
1081 sub find_parent_branch {
1082 my ($self, $paths, $rev) = @_;
1083 return undef unless $self->follow_parent;
1084 unless (defined $paths) {
1085 my $err_handler = $SVN::Error::handler;
1086 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1087 $self->ra->get_log([$self->path], $rev, $rev, 0, 1, 1,
1088 sub { $paths = $_[0] });
1089 $SVN::Error::handler = $err_handler;
1091 return undef unless defined $paths;
1093 # look for a parent from another branch:
1094 my @b_path_components = split m#/#, $self->path;
1095 my @a_path_components;
1096 my $i;
1097 while (@b_path_components) {
1098 $i = $paths->{'/'.join('/', @b_path_components)};
1099 last if $i && defined $i->{copyfrom_path};
1100 unshift(@a_path_components, pop(@b_path_components));
1102 return undef unless defined $i && defined $i->{copyfrom_path};
1103 my $branch_from = $i->{copyfrom_path};
1104 if (@a_path_components) {
1105 print STDERR "branch_from: $branch_from => ";
1106 $branch_from .= '/'.join('/', @a_path_components);
1107 print STDERR $branch_from, "\n";
1109 my $r = $i->{copyfrom_rev};
1110 my $repos_root = $self->ra->{repos_root};
1111 my $url = $self->ra->{url};
1112 my $new_url = $url . $branch_from;
1113 print STDERR "Found possible branch point: ",
1114 "$new_url => ", $self->full_url, ", $r\n"
1115 unless $::_q > 1;
1116 $branch_from =~ s#^/##;
1117 my $gs = $self->other_gs($new_url, $url,
1118 $branch_from, $r, $self->{ref_id});
1119 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1121 my ($base, $head);
1122 if (!defined $r0 || !defined $parent) {
1123 ($base, $head) = parse_revision_argument(0, $r);
1124 } else {
1125 if ($r0 < $r) {
1126 $gs->ra->get_log([$gs->path], $r0 + 1, $r, 1,
1127 0, 1, sub { $base = $_[1] - 1 });
1130 if (defined $base && $base <= $r) {
1131 $gs->fetch($base, $r);
1133 ($r0, $parent) = $gs->find_rev_before($r, 1);
1135 if (defined $r0 && defined $parent) {
1136 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
1137 unless $::_q > 1;
1138 my $ed;
1139 if ($self->ra->can_do_switch) {
1140 $self->assert_index_clean($parent);
1141 print STDERR "Following parent with do_switch\n"
1142 unless $::_q > 1;
1143 # do_switch works with svn/trunk >= r22312, but that
1144 # is not included with SVN 1.4.3 (the latest version
1145 # at the moment), so we can't rely on it
1146 $self->{last_rev} = $r0;
1147 $self->{last_commit} = $parent;
1148 $ed = Git::SVN::Fetcher->new($self, $gs->path);
1149 $gs->ra->gs_do_switch($r0, $rev, $gs,
1150 $self->full_url, $ed)
1151 or die "SVN connection failed somewhere...\n";
1152 } elsif ($self->ra->trees_match($new_url, $r0,
1153 $self->full_url, $rev)) {
1154 print STDERR "Trees match:\n",
1155 " $new_url\@$r0\n",
1156 " ${\$self->full_url}\@$rev\n",
1157 "Following parent with no changes\n"
1158 unless $::_q > 1;
1159 $self->tmp_index_do(sub {
1160 command_noisy('read-tree', $parent);
1162 $self->{last_commit} = $parent;
1163 } else {
1164 print STDERR "Following parent with do_update\n"
1165 unless $::_q > 1;
1166 $ed = Git::SVN::Fetcher->new($self);
1167 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1168 or die "SVN connection failed somewhere...\n";
1170 print STDERR "Successfully followed parent\n" unless $::_q > 1;
1171 return $self->make_log_entry($rev, [$parent], $ed);
1173 return undef;
1176 sub do_fetch {
1177 my ($self, $paths, $rev) = @_;
1178 my $ed;
1179 my ($last_rev, @parents);
1180 if (my $lc = $self->last_commit) {
1181 # we can have a branch that was deleted, then re-added
1182 # under the same name but copied from another path, in
1183 # which case we'll have multiple parents (we don't
1184 # want to break the original ref, nor lose copypath info):
1185 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1186 push @{$log_entry->{parents}}, $lc;
1187 return $log_entry;
1189 $ed = Git::SVN::Fetcher->new($self);
1190 $last_rev = $self->{last_rev};
1191 $ed->{c} = $lc;
1192 @parents = ($lc);
1193 } else {
1194 $last_rev = $rev;
1195 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1196 return $log_entry;
1198 $ed = Git::SVN::Fetcher->new($self);
1200 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1201 die "SVN connection failed somewhere...\n";
1203 $self->make_log_entry($rev, \@parents, $ed);
1206 sub mkemptydirs {
1207 my ($self, $r) = @_;
1209 sub scan {
1210 my ($r, $empty_dirs, $line) = @_;
1211 if (defined $r && $line =~ /^r(\d+)$/) {
1212 return 0 if $1 > $r;
1213 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
1214 $empty_dirs->{$1} = 1;
1215 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
1216 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
1217 delete @$empty_dirs{@d};
1219 1; # continue
1222 my %empty_dirs = ();
1223 my $gz_file = "$self->{dir}/unhandled.log.gz";
1224 if (-f $gz_file) {
1225 if (!can_compress()) {
1226 warn "Compress::Zlib could not be found; ",
1227 "empty directories in $gz_file will not be read\n";
1228 } else {
1229 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
1230 die "Unable to open $gz_file: $!\n";
1231 my $line;
1232 while ($gz->gzreadline($line) > 0) {
1233 scan($r, \%empty_dirs, $line) or last;
1235 $gz->gzclose;
1239 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
1240 binmode $fh or croak "binmode: $!";
1241 while (<$fh>) {
1242 scan($r, \%empty_dirs, $_) or last;
1244 close $fh;
1247 my $strip = qr/\A\Q@{[$self->path]}\E(?:\/|$)/;
1248 foreach my $d (sort keys %empty_dirs) {
1249 $d = uri_decode($d);
1250 $d =~ s/$strip//;
1251 next unless length($d);
1252 next if -d $d;
1253 if (-e $d) {
1254 warn "$d exists but is not a directory\n";
1255 } else {
1256 print "creating empty directory: $d\n";
1257 mkpath([$d]);
1262 sub get_untracked {
1263 my ($self, $ed) = @_;
1264 my @out;
1265 my $h = $ed->{empty};
1266 foreach (sort keys %$h) {
1267 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1268 push @out, " $act: " . uri_encode($_);
1269 warn "W: $act: $_\n";
1271 foreach my $t (qw/dir_prop file_prop/) {
1272 $h = $ed->{$t} or next;
1273 foreach my $path (sort keys %$h) {
1274 my $ppath = $path eq '' ? '.' : $path;
1275 foreach my $prop (sort keys %{$h->{$path}}) {
1276 next if $SKIP_PROP{$prop};
1277 my $v = $h->{$path}->{$prop};
1278 my $t_ppath_prop = "$t: " .
1279 uri_encode($ppath) . ' ' .
1280 uri_encode($prop);
1281 if (defined $v) {
1282 push @out, " +$t_ppath_prop " .
1283 uri_encode($v);
1284 } else {
1285 push @out, " -$t_ppath_prop";
1290 foreach my $t (qw/absent_file absent_directory/) {
1291 $h = $ed->{$t} or next;
1292 foreach my $parent (sort keys %$h) {
1293 foreach my $path (sort @{$h->{$parent}}) {
1294 push @out, " $t: " .
1295 uri_encode("$parent/$path");
1296 warn "W: $t: $parent/$path ",
1297 "Insufficient permissions?\n";
1301 \@out;
1304 sub get_tz {
1305 # some systmes don't handle or mishandle %z, so be creative.
1306 my $t = shift || time;
1307 my $gm = timelocal(gmtime($t));
1308 my $sign = qw( + + - )[ $t <=> $gm ];
1309 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
1312 # parse_svn_date(DATE)
1313 # --------------------
1314 # Given a date (in UTC) from Subversion, return a string in the format
1315 # "<TZ Offset> <local date/time>" that Git will use.
1317 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
1318 # is true we'll convert it to the local timezone instead.
1319 sub parse_svn_date {
1320 my $date = shift || return '+0000 1970-01-01 00:00:00';
1321 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1322 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1323 croak "Unable to parse date: $date\n";
1324 my $parsed_date; # Set next.
1326 if ($Git::SVN::_localtime) {
1327 # Translate the Subversion datetime to an epoch time.
1328 # Begin by switching ourselves to $date's timezone, UTC.
1329 my $old_env_TZ = $ENV{TZ};
1330 $ENV{TZ} = 'UTC';
1332 my $epoch_in_UTC =
1333 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
1335 # Determine our local timezone (including DST) at the
1336 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
1337 # value of TZ, if any, at the time we were run.
1338 if (defined $Git::SVN::Log::TZ) {
1339 $ENV{TZ} = $Git::SVN::Log::TZ;
1340 } else {
1341 delete $ENV{TZ};
1344 my $our_TZ = get_tz();
1346 # This converts $epoch_in_UTC into our local timezone.
1347 my ($sec, $min, $hour, $mday, $mon, $year,
1348 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
1350 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
1351 $our_TZ, $year + 1900, $mon + 1,
1352 $mday, $hour, $min, $sec);
1354 # Reset us to the timezone in effect when we entered
1355 # this routine.
1356 if (defined $old_env_TZ) {
1357 $ENV{TZ} = $old_env_TZ;
1358 } else {
1359 delete $ENV{TZ};
1361 } else {
1362 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
1365 return $parsed_date;
1368 sub other_gs {
1369 my ($self, $new_url, $url,
1370 $branch_from, $r, $old_ref_id) = @_;
1371 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
1372 unless ($gs) {
1373 my $ref_id = $old_ref_id;
1374 $ref_id =~ s/\@\d+-*$//;
1375 $ref_id .= "\@$r";
1376 # just grow a tail if we're not unique enough :x
1377 $ref_id .= '-' while find_ref($ref_id);
1378 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
1379 if ($u =~ s#^\Q$url\E(/|$)##) {
1380 $p = $u;
1381 $u = $url;
1382 $repo_id = $self->{repo_id};
1384 while (1) {
1385 # It is possible to tag two different subdirectories at
1386 # the same revision. If the url for an existing ref
1387 # does not match, we must either find a ref with a
1388 # matching url or create a new ref by growing a tail.
1389 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
1390 my (undef, $max_commit) = $gs->rev_map_max(1);
1391 last if (!$max_commit);
1392 my ($url) = ::cmt_metadata($max_commit);
1393 last if ($url eq $gs->metadata_url);
1394 $ref_id .= '-';
1396 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
1401 sub call_authors_prog {
1402 my ($orig_author) = @_;
1403 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
1404 my $author = `$::_authors_prog $orig_author`;
1405 if ($? != 0) {
1406 die "$::_authors_prog failed with exit code $?\n"
1408 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
1409 my ($name, $email) = ($1, $2);
1410 $email = undef if length $2 == 0;
1411 return [$name, $email];
1412 } else {
1413 die "Author: $orig_author: $::_authors_prog returned "
1414 . "invalid author format: $author\n";
1418 sub check_author {
1419 my ($author) = @_;
1420 if (!defined $author || length $author == 0) {
1421 $author = '(no author)';
1423 if (!defined $::users{$author}) {
1424 if (defined $::_authors_prog) {
1425 $::users{$author} = call_authors_prog($author);
1426 } elsif (defined $::_authors) {
1427 die "Author: $author not defined in $::_authors file\n";
1430 $author;
1433 sub find_extra_svk_parents {
1434 my ($self, $ed, $tickets, $parents) = @_;
1435 # aha! svk:merge property changed...
1436 my @tickets = split "\n", $tickets;
1437 my @known_parents;
1438 for my $ticket ( @tickets ) {
1439 my ($uuid, $path, $rev) = split /:/, $ticket;
1440 if ( $uuid eq $self->ra_uuid ) {
1441 my $url = $self->url;
1442 my $repos_root = $url;
1443 my $branch_from = $path;
1444 $branch_from =~ s{^/}{};
1445 my $gs = $self->other_gs($repos_root."/".$branch_from,
1446 $url,
1447 $branch_from,
1448 $rev,
1449 $self->{ref_id});
1450 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
1451 # wahey! we found it, but it might be
1452 # an old one (!)
1453 push @known_parents, [ $rev, $commit ];
1457 # Ordering matters; highest-numbered commit merge tickets
1458 # first, as they may account for later merge ticket additions
1459 # or changes.
1460 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
1461 for my $parent ( @known_parents ) {
1462 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
1463 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
1464 my $new;
1465 while ( <$msg_fh> ) {
1466 $new=1;last;
1468 command_close_pipe($msg_fh, $ctx);
1469 if ( $new ) {
1470 print STDERR
1471 "Found merge parent (svk:merge ticket): $parent\n";
1472 push @$parents, $parent;
1477 sub lookup_svn_merge {
1478 my $uuid = shift;
1479 my $url = shift;
1480 my $merge = shift;
1482 my ($source, $revs) = split ":", $merge;
1483 my $path = $source;
1484 $path =~ s{^/}{};
1485 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
1486 if ( !$gs ) {
1487 warn "Couldn't find revmap for $url$source\n";
1488 return;
1490 my @ranges = split ",", $revs;
1491 my ($tip, $tip_commit);
1492 my @merged_commit_ranges;
1493 # find the tip
1494 for my $range ( @ranges ) {
1495 my ($bottom, $top) = split "-", $range;
1496 $top ||= $bottom;
1497 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
1498 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
1500 unless ($top_commit and $bottom_commit) {
1501 warn "W:unknown path/rev in svn:mergeinfo "
1502 ."dirprop: $source:$range\n";
1503 next;
1506 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
1507 push @merged_commit_ranges,
1508 "$bottom_commit^..$top_commit";
1509 } else {
1510 push @merged_commit_ranges, "$top_commit";
1513 if ( !defined $tip or $top > $tip ) {
1514 $tip = $top;
1515 $tip_commit = $top_commit;
1518 return ($tip_commit, @merged_commit_ranges);
1521 sub _rev_list {
1522 my ($msg_fh, $ctx) = command_output_pipe(
1523 "rev-list", @_,
1525 my @rv;
1526 while ( <$msg_fh> ) {
1527 chomp;
1528 push @rv, $_;
1530 command_close_pipe($msg_fh, $ctx);
1531 @rv;
1534 sub check_cherry_pick {
1535 my $base = shift;
1536 my $tip = shift;
1537 my $parents = shift;
1538 my @ranges = @_;
1539 my %commits = map { $_ => 1 }
1540 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
1541 for my $range ( @ranges ) {
1542 delete @commits{_rev_list($range, "--")};
1544 for my $commit (keys %commits) {
1545 if (has_no_changes($commit)) {
1546 delete $commits{$commit};
1549 return (keys %commits);
1552 sub has_no_changes {
1553 my $commit = shift;
1555 my @revs = split / /, command_oneline(
1556 qw(rev-list --parents -1 -m), $commit);
1558 # Commits with no parents, e.g. the start of a partial branch,
1559 # have changes by definition.
1560 return 1 if (@revs < 2);
1562 # Commits with multiple parents, e.g a merge, have no changes
1563 # by definition.
1564 return 0 if (@revs > 2);
1566 return (command_oneline("rev-parse", "$commit^{tree}") eq
1567 command_oneline("rev-parse", "$commit~1^{tree}"));
1570 sub tie_for_persistent_memoization {
1571 my $hash = shift;
1572 my $path = shift;
1574 if ($can_use_yaml) {
1575 tie %$hash => 'Git::SVN::Memoize::YAML', "$path.yaml";
1576 } else {
1577 tie %$hash => 'Memoize::Storable', "$path.db", 'nstore';
1581 # The GIT_DIR environment variable is not always set until after the command
1582 # line arguments are processed, so we can't memoize in a BEGIN block.
1584 my $memoized = 0;
1586 sub memoize_svn_mergeinfo_functions {
1587 return if $memoized;
1588 $memoized = 1;
1590 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1591 mkpath([$cache_path]) unless -d $cache_path;
1593 my %lookup_svn_merge_cache;
1594 my %check_cherry_pick_cache;
1595 my %has_no_changes_cache;
1597 tie_for_persistent_memoization(\%lookup_svn_merge_cache,
1598 "$cache_path/lookup_svn_merge");
1599 memoize 'lookup_svn_merge',
1600 SCALAR_CACHE => 'FAULT',
1601 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
1604 tie_for_persistent_memoization(\%check_cherry_pick_cache,
1605 "$cache_path/check_cherry_pick");
1606 memoize 'check_cherry_pick',
1607 SCALAR_CACHE => 'FAULT',
1608 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
1611 tie_for_persistent_memoization(\%has_no_changes_cache,
1612 "$cache_path/has_no_changes");
1613 memoize 'has_no_changes',
1614 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
1615 LIST_CACHE => 'FAULT',
1619 sub unmemoize_svn_mergeinfo_functions {
1620 return if not $memoized;
1621 $memoized = 0;
1623 Memoize::unmemoize 'lookup_svn_merge';
1624 Memoize::unmemoize 'check_cherry_pick';
1625 Memoize::unmemoize 'has_no_changes';
1628 Memoize::memoize 'Git::SVN::repos_root';
1631 END {
1632 # Force cache writeout explicitly instead of waiting for
1633 # global destruction to avoid segfault in Storable:
1634 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
1635 unmemoize_svn_mergeinfo_functions();
1638 sub parents_exclude {
1639 my $parents = shift;
1640 my @commits = @_;
1641 return unless @commits;
1643 my @excluded;
1644 my $excluded;
1645 do {
1646 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
1647 $excluded = command_oneline(@cmd);
1648 if ( $excluded ) {
1649 my @new;
1650 my $found;
1651 for my $commit ( @commits ) {
1652 if ( $commit eq $excluded ) {
1653 push @excluded, $commit;
1654 $found++;
1655 last;
1657 else {
1658 push @new, $commit;
1661 die "saw commit '$excluded' in rev-list output, "
1662 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
1663 unless $found;
1664 @commits = @new;
1667 while ($excluded and @commits);
1669 return @excluded;
1673 # note: this function should only be called if the various dirprops
1674 # have actually changed
1675 sub find_extra_svn_parents {
1676 my ($self, $ed, $mergeinfo, $parents) = @_;
1677 # aha! svk:merge property changed...
1679 memoize_svn_mergeinfo_functions();
1681 # We first search for merged tips which are not in our
1682 # history. Then, we figure out which git revisions are in
1683 # that tip, but not this revision. If all of those revisions
1684 # are now marked as merge, we can add the tip as a parent.
1685 my @merges = split "\n", $mergeinfo;
1686 my @merge_tips;
1687 my $url = $self->url;
1688 my $uuid = $self->ra_uuid;
1689 my %ranges;
1690 for my $merge ( @merges ) {
1691 my ($tip_commit, @ranges) =
1692 lookup_svn_merge( $uuid, $url, $merge );
1693 unless (!$tip_commit or
1694 grep { $_ eq $tip_commit } @$parents ) {
1695 push @merge_tips, $tip_commit;
1696 $ranges{$tip_commit} = \@ranges;
1697 } else {
1698 push @merge_tips, undef;
1702 my %excluded = map { $_ => 1 }
1703 parents_exclude($parents, grep { defined } @merge_tips);
1705 # check merge tips for new parents
1706 my @new_parents;
1707 for my $merge_tip ( @merge_tips ) {
1708 my $spec = shift @merges;
1709 next unless $merge_tip and $excluded{$merge_tip};
1711 my $ranges = $ranges{$merge_tip};
1713 # check out 'new' tips
1714 my $merge_base;
1715 eval {
1716 $merge_base = command_oneline(
1717 "merge-base",
1718 @$parents, $merge_tip,
1721 if ($@) {
1722 die "An error occurred during merge-base"
1723 unless $@->isa("Git::Error::Command");
1725 warn "W: Cannot find common ancestor between ".
1726 "@$parents and $merge_tip. Ignoring merge info.\n";
1727 next;
1730 # double check that there are no missing non-merge commits
1731 my (@incomplete) = check_cherry_pick(
1732 $merge_base, $merge_tip,
1733 $parents,
1734 @$ranges,
1737 if ( @incomplete ) {
1738 warn "W:svn cherry-pick ignored ($spec) - missing "
1739 .@incomplete." commit(s) (eg $incomplete[0])\n";
1740 } else {
1741 warn
1742 "Found merge parent (svn:mergeinfo prop): ",
1743 $merge_tip, "\n";
1744 push @new_parents, $merge_tip;
1748 # cater for merges which merge commits from multiple branches
1749 if ( @new_parents > 1 ) {
1750 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
1751 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
1752 next if $i == $j;
1753 next unless $new_parents[$i];
1754 next unless $new_parents[$j];
1755 my $revs = command_oneline(
1756 "rev-list", "-1",
1757 "$new_parents[$i]..$new_parents[$j]",
1759 if ( !$revs ) {
1760 undef($new_parents[$j]);
1765 push @$parents, grep { defined } @new_parents;
1768 sub make_log_entry {
1769 my ($self, $rev, $parents, $ed) = @_;
1770 my $untracked = $self->get_untracked($ed);
1772 my @parents = @$parents;
1773 my $ps = $ed->{path_strip} || "";
1774 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
1775 my $props = $ed->{dir_prop}{$path};
1776 if ( $props->{"svk:merge"} ) {
1777 $self->find_extra_svk_parents
1778 ($ed, $props->{"svk:merge"}, \@parents);
1780 if ( $props->{"svn:mergeinfo"} ) {
1781 $self->find_extra_svn_parents
1782 ($ed,
1783 $props->{"svn:mergeinfo"},
1784 \@parents);
1788 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1789 print $un "r$rev\n" or croak $!;
1790 print $un $_, "\n" foreach @$untracked;
1791 my %log_entry = ( parents => \@parents, revision => $rev,
1792 log => '');
1794 my $headrev;
1795 my $logged = delete $self->{logged_rev_props};
1796 if (!$logged || $self->{-want_revprops}) {
1797 my $rp = $self->ra->rev_proplist($rev);
1798 foreach (sort keys %$rp) {
1799 my $v = $rp->{$_};
1800 if (/^svn:(author|date|log)$/) {
1801 $log_entry{$1} = $v;
1802 } elsif ($_ eq 'svm:headrev') {
1803 $headrev = $v;
1804 } else {
1805 print $un " rev_prop: ", uri_encode($_), ' ',
1806 uri_encode($v), "\n";
1809 } else {
1810 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1812 close $un or croak $!;
1814 $log_entry{date} = parse_svn_date($log_entry{date});
1815 $log_entry{log} .= "\n";
1816 my $author = $log_entry{author} = check_author($log_entry{author});
1817 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1818 : ($author, undef);
1820 my ($commit_name, $commit_email) = ($name, $email);
1821 if ($_use_log_author) {
1822 my $name_field;
1823 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
1824 $name_field = $1;
1825 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
1826 $name_field = $1;
1828 if (!defined $name_field) {
1829 if (!defined $email) {
1830 $email = $name;
1832 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
1833 ($name, $email) = ($1, $2);
1834 } elsif ($name_field =~ /(.*)@/) {
1835 ($name, $email) = ($1, $name_field);
1836 } else {
1837 ($name, $email) = ($name_field, $name_field);
1840 if (defined $headrev && $self->use_svm_props) {
1841 if ($self->rewrite_root) {
1842 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1843 "options set!\n";
1845 if ($self->rewrite_uuid) {
1846 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
1847 "options set!\n";
1849 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
1850 # we don't want "SVM: initializing mirror for junk" ...
1851 return undef if $r == 0;
1852 my $svm = $self->svm;
1853 if ($uuid ne $svm->{uuid}) {
1854 die "UUID mismatch on SVM path:\n",
1855 "expected: $svm->{uuid}\n",
1856 " got: $uuid\n";
1858 my $full_url = $self->full_url;
1859 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1860 die "Failed to replace '$svm->{replace}' with ",
1861 "'$svm->{source}' in $full_url\n";
1862 # throw away username for storing in records
1863 remove_username($full_url);
1864 $log_entry{metadata} = "$full_url\@$r $uuid";
1865 $log_entry{svm_revision} = $r;
1866 $email ||= "$author\@$uuid";
1867 $commit_email ||= "$author\@$uuid";
1868 } elsif ($self->use_svnsync_props) {
1869 my $full_url = $self->svnsync->{url};
1870 $full_url .= "/".$self->path if length $self->path;
1871 remove_username($full_url);
1872 my $uuid = $self->svnsync->{uuid};
1873 $log_entry{metadata} = "$full_url\@$rev $uuid";
1874 $email ||= "$author\@$uuid";
1875 $commit_email ||= "$author\@$uuid";
1876 } else {
1877 my $url = $self->metadata_url;
1878 remove_username($url);
1879 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
1880 $log_entry{metadata} = "$url\@$rev " . $uuid;
1881 $email ||= "$author\@" . $uuid;
1882 $commit_email ||= "$author\@" . $uuid;
1884 $log_entry{name} = $name;
1885 $log_entry{email} = $email;
1886 $log_entry{commit_name} = $commit_name;
1887 $log_entry{commit_email} = $commit_email;
1888 \%log_entry;
1891 sub fetch {
1892 my ($self, $min_rev, $max_rev, @parents) = @_;
1893 my ($last_rev, $last_commit) = $self->last_rev_commit;
1894 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1895 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1898 sub set_tree_cb {
1899 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1900 $self->{inject_parents} = { $rev => $tree };
1901 $self->fetch(undef, undef);
1904 sub set_tree {
1905 my ($self, $tree) = (shift, shift);
1906 my $log_entry = ::get_commit_entry($tree);
1907 unless ($self->{last_rev}) {
1908 fatal("Must have an existing revision to commit");
1910 my %ed_opts = ( r => $self->{last_rev},
1911 log => $log_entry->{log},
1912 ra => $self->ra,
1913 tree_a => $self->{last_commit},
1914 tree_b => $tree,
1915 editor_cb => sub {
1916 $self->set_tree_cb($log_entry, $tree, @_) },
1917 svn_path => $self->path );
1918 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1919 print "No changes\nr$self->{last_rev} = $tree\n";
1923 sub rebuild_from_rev_db {
1924 my ($self, $path) = @_;
1925 my $r = -1;
1926 open my $fh, '<', $path or croak "open: $!";
1927 binmode $fh or croak "binmode: $!";
1928 while (<$fh>) {
1929 length($_) == 41 or croak "inconsistent size in ($_) != 41";
1930 chomp($_);
1931 ++$r;
1932 next if $_ eq ('0' x 40);
1933 $self->rev_map_set($r, $_);
1934 print "r$r = $_\n";
1936 close $fh or croak "close: $!";
1937 unlink $path or croak "unlink: $!";
1940 sub rebuild {
1941 my ($self) = @_;
1942 my $map_path = $self->map_path;
1943 my $partial = (-e $map_path && ! -z $map_path);
1944 return unless ::verify_ref($self->refname.'^0');
1945 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
1946 my $rev_db = $self->rev_db_path;
1947 $self->rebuild_from_rev_db($rev_db);
1948 if ($self->use_svm_props) {
1949 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
1950 $self->rebuild_from_rev_db($svm_rev_db);
1952 $self->unlink_rev_db_symlink;
1953 return;
1955 print "Rebuilding $map_path ...\n" if (!$partial);
1956 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
1957 (undef, undef));
1958 my ($log, $ctx) =
1959 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
1960 ($head ? "$head.." : "") . $self->refname,
1961 '--');
1962 my $metadata_url = $self->metadata_url;
1963 remove_username($metadata_url);
1964 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
1965 my $c;
1966 while (<$log>) {
1967 if ( m{^commit ($::sha1)$} ) {
1968 $c = $1;
1969 next;
1971 next unless s{^\s*(git-svn-id:)}{$1};
1972 my ($url, $rev, $uuid) = ::extract_metadata($_);
1973 remove_username($url);
1975 # ignore merges (from set-tree)
1976 next if (!defined $rev || !$uuid);
1978 # if we merged or otherwise started elsewhere, this is
1979 # how we break out of it
1980 if (($uuid ne $svn_uuid) ||
1981 ($metadata_url && $url && ($url ne $metadata_url))) {
1982 next;
1984 if ($partial && $head) {
1985 print "Partial-rebuilding $map_path ...\n";
1986 print "Currently at $base_rev = $head\n";
1987 $head = undef;
1990 $self->rev_map_set($rev, $c);
1991 print "r$rev = $c\n";
1993 command_close_pipe($log, $ctx);
1994 print "Done rebuilding $map_path\n" if (!$partial || !$head);
1995 my $rev_db_path = $self->rev_db_path;
1996 if (-f $self->rev_db_path) {
1997 unlink $self->rev_db_path or croak "unlink: $!";
1999 $self->unlink_rev_db_symlink;
2002 # rev_map:
2003 # Tie::File seems to be prone to offset errors if revisions get sparse,
2004 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2005 # one of my favorite modules is out :< Next up would be one of the DBM
2006 # modules, but I'm not sure which is most portable...
2008 # This is the replacement for the rev_db format, which was too big
2009 # and inefficient for large repositories with a lot of sparse history
2010 # (mainly tags)
2012 # The format is this:
2013 # - 24 bytes for every record,
2014 # * 4 bytes for the integer representing an SVN revision number
2015 # * 20 bytes representing the sha1 of a git commit
2016 # - No empty padding records like the old format
2017 # (except the last record, which can be overwritten)
2018 # - new records are written append-only since SVN revision numbers
2019 # increase monotonically
2020 # - lookups on SVN revision number are done via a binary search
2021 # - Piping the file to xxd -c24 is a good way of dumping it for
2022 # viewing or editing (piped back through xxd -r), should the need
2023 # ever arise.
2024 # - The last record can be padding revision with an all-zero sha1
2025 # This is used to optimize fetch performance when using multiple
2026 # "fetch" directives in .git/config
2028 # These files are disposable unless noMetadata or useSvmProps is set
2030 sub _rev_map_set {
2031 my ($fh, $rev, $commit) = @_;
2033 binmode $fh or croak "binmode: $!";
2034 my $size = (stat($fh))[7];
2035 ($size % 24) == 0 or croak "inconsistent size: $size";
2037 my $wr_offset = 0;
2038 if ($size > 0) {
2039 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2040 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2041 $read == 24 or croak "read only $read bytes (!= 24)";
2042 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2043 if ($last_commit eq ('0' x40)) {
2044 if ($size >= 48) {
2045 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2046 $read = sysread($fh, $buf, 24) or
2047 croak "read: $!";
2048 $read == 24 or
2049 croak "read only $read bytes (!= 24)";
2050 ($last_rev, $last_commit) =
2051 unpack(rev_map_fmt, $buf);
2052 if ($last_commit eq ('0' x40)) {
2053 croak "inconsistent .rev_map\n";
2056 if ($last_rev >= $rev) {
2057 croak "last_rev is higher!: $last_rev >= $rev";
2059 $wr_offset = -24;
2062 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2063 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2064 croak "write: $!";
2067 sub _rev_map_reset {
2068 my ($fh, $rev, $commit) = @_;
2069 my $c = _rev_map_get($fh, $rev);
2070 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
2071 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
2072 truncate $fh, $offset or croak "truncate: $!";
2075 sub mkfile {
2076 my ($path) = @_;
2077 unless (-e $path) {
2078 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2079 mkpath([$dir]) unless -d $dir;
2080 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2081 close $fh or die "Couldn't close (create) $path: $!\n";
2085 sub rev_map_set {
2086 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2087 defined $commit or die "missing arg3\n";
2088 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2089 my $db = $self->map_path($uuid);
2090 my $db_lock = "$db.lock";
2091 my $sigmask;
2092 $update_ref ||= 0;
2093 if ($update_ref) {
2094 $sigmask = POSIX::SigSet->new();
2095 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
2096 SIGALRM, SIGUSR1, SIGUSR2);
2097 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
2098 croak "Can't block signals: $!";
2100 mkfile($db);
2102 $LOCKFILES{$db_lock} = 1;
2103 my $sync;
2104 # both of these options make our .rev_db file very, very important
2105 # and we can't afford to lose it because rebuild() won't work
2106 if ($self->use_svm_props || $self->no_metadata) {
2107 $sync = 1;
2108 copy($db, $db_lock) or die "rev_map_set(@_): ",
2109 "Failed to copy: ",
2110 "$db => $db_lock ($!)\n";
2111 } else {
2112 rename $db, $db_lock or die "rev_map_set(@_): ",
2113 "Failed to rename: ",
2114 "$db => $db_lock ($!)\n";
2117 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2118 or croak "Couldn't open $db_lock: $!\n";
2119 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
2120 _rev_map_set($fh, $rev, $commit);
2121 if ($sync) {
2122 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2123 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2125 close $fh or croak $!;
2126 if ($update_ref) {
2127 $_head = $self;
2128 my $note = "";
2129 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
2130 command_noisy('update-ref', '-m', "r$rev$note",
2131 $self->refname, $commit);
2133 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2134 "$db_lock => $db ($!)\n";
2135 delete $LOCKFILES{$db_lock};
2136 if ($update_ref) {
2137 sigprocmask(SIG_SETMASK, $sigmask) or
2138 croak "Can't restore signal mask: $!";
2142 # If want_commit, this will return an array of (rev, commit) where
2143 # commit _must_ be a valid commit in the archive.
2144 # Otherwise, it'll return the max revision (whether or not the
2145 # commit is valid or just a 0x40 placeholder).
2146 sub rev_map_max {
2147 my ($self, $want_commit) = @_;
2148 $self->rebuild;
2149 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2150 $want_commit ? ($r, $c) : $r;
2153 sub rev_map_max_norebuild {
2154 my ($self, $want_commit) = @_;
2155 my $map_path = $self->map_path;
2156 stat $map_path or return $want_commit ? (0, undef) : 0;
2157 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2158 binmode $fh or croak "binmode: $!";
2159 my $size = (stat($fh))[7];
2160 ($size % 24) == 0 or croak "inconsistent size: $size";
2162 if ($size == 0) {
2163 close $fh or croak "close: $!";
2164 return $want_commit ? (0, undef) : 0;
2167 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2168 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2169 my ($r, $c) = unpack(rev_map_fmt, $buf);
2170 if ($want_commit && $c eq ('0' x40)) {
2171 if ($size < 48) {
2172 return $want_commit ? (0, undef) : 0;
2174 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2175 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2176 ($r, $c) = unpack(rev_map_fmt, $buf);
2177 if ($c eq ('0'x40)) {
2178 croak "Penultimate record is all-zeroes in $map_path";
2181 close $fh or croak "close: $!";
2182 $want_commit ? ($r, $c) : $r;
2185 sub rev_map_get {
2186 my ($self, $rev, $uuid) = @_;
2187 my $map_path = $self->map_path($uuid);
2188 return undef unless -e $map_path;
2190 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2191 my $c = _rev_map_get($fh, $rev);
2192 close($fh) or croak "close: $!";
2196 sub _rev_map_get {
2197 my ($fh, $rev) = @_;
2199 binmode $fh or croak "binmode: $!";
2200 my $size = (stat($fh))[7];
2201 ($size % 24) == 0 or croak "inconsistent size: $size";
2203 if ($size == 0) {
2204 return undef;
2207 my ($l, $u) = (0, $size - 24);
2208 my ($r, $c, $buf);
2210 while ($l <= $u) {
2211 my $i = int(($l/24 + $u/24) / 2) * 24;
2212 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2213 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2214 my ($r, $c) = unpack(rev_map_fmt, $buf);
2216 if ($r < $rev) {
2217 $l = $i + 24;
2218 } elsif ($r > $rev) {
2219 $u = $i - 24;
2220 } else { # $r == $rev
2221 return $c eq ('0' x 40) ? undef : $c;
2224 undef;
2227 # Finds the first svn revision that exists on (if $eq_ok is true) or
2228 # before $rev for the current branch. It will not search any lower
2229 # than $min_rev. Returns the git commit hash and svn revision number
2230 # if found, else (undef, undef).
2231 sub find_rev_before {
2232 my ($self, $rev, $eq_ok, $min_rev) = @_;
2233 --$rev unless $eq_ok;
2234 $min_rev ||= 1;
2235 my $max_rev = $self->rev_map_max;
2236 $rev = $max_rev if ($rev > $max_rev);
2237 while ($rev >= $min_rev) {
2238 if (my $c = $self->rev_map_get($rev)) {
2239 return ($rev, $c);
2241 --$rev;
2243 return (undef, undef);
2246 # Finds the first svn revision that exists on (if $eq_ok is true) or
2247 # after $rev for the current branch. It will not search any higher
2248 # than $max_rev. Returns the git commit hash and svn revision number
2249 # if found, else (undef, undef).
2250 sub find_rev_after {
2251 my ($self, $rev, $eq_ok, $max_rev) = @_;
2252 ++$rev unless $eq_ok;
2253 $max_rev ||= $self->rev_map_max;
2254 while ($rev <= $max_rev) {
2255 if (my $c = $self->rev_map_get($rev)) {
2256 return ($rev, $c);
2258 ++$rev;
2260 return (undef, undef);
2263 sub _new {
2264 my ($class, $repo_id, $ref_id, $path) = @_;
2265 unless (defined $repo_id && length $repo_id) {
2266 $repo_id = $default_repo_id;
2268 unless (defined $ref_id && length $ref_id) {
2269 # Access the prefix option from the git-svn main program if it's loaded.
2270 my $prefix = defined &::opt_prefix ? ::opt_prefix() : "";
2271 $_[2] = $ref_id =
2272 "refs/remotes/$prefix$default_ref_id";
2274 $_[1] = $repo_id;
2275 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2277 # Older repos imported by us used $GIT_DIR/svn/foo instead of
2278 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
2279 if ($ref_id =~ m{^refs/remotes/(.*)}) {
2280 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
2281 if (-d $old_dir && ! -d $dir) {
2282 $dir = $old_dir;
2286 $_[3] = $path = '' unless (defined $path);
2287 mkpath([$dir]);
2288 my $obj = bless {
2289 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2290 config => "$ENV{GIT_DIR}/svn/config",
2291 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2293 # Ensure it gets canonicalized
2294 $obj->path($path);
2296 return $obj;
2299 sub path {
2300 my $self = shift;
2302 if (@_) {
2303 my $path = shift;
2304 $self->{path} = $path;
2305 return;
2308 return $self->{path};
2311 sub url {
2312 my $self = shift;
2314 if (@_) {
2315 my $url = shift;
2316 $self->{url} = $url;
2317 return;
2320 return $self->{url};
2323 # for read-only access of old .rev_db formats
2324 sub unlink_rev_db_symlink {
2325 my ($self) = @_;
2326 my $link = $self->rev_db_path;
2327 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2328 if (-l $link) {
2329 unlink $link or croak "unlink: $link failed!";
2333 sub rev_db_path {
2334 my ($self, $uuid) = @_;
2335 my $db_path = $self->map_path($uuid);
2336 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2337 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2338 $db_path;
2341 # the new replacement for .rev_db
2342 sub map_path {
2343 my ($self, $uuid) = @_;
2344 $uuid ||= $self->ra_uuid;
2345 "$self->{map_root}.$uuid";
2348 sub uri_encode {
2349 my ($f) = @_;
2350 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2354 sub uri_decode {
2355 my ($f) = @_;
2356 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
2360 sub remove_username {
2361 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};