Git::SVN: use accessors internally for path
[git.git] / perl / Git / SVN.pm
bloba93ac61b67dc341d2c5277e40f1060eb902e9d7a
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 $self->{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->{pushurl} = eval { command_oneline('config', '--get',
460 "svn-remote.$repo_id.pushurl") };
461 $self->rebuild;
462 $self;
465 sub refname {
466 my ($refname) = $_[0]->{ref_id} ;
468 # It cannot end with a slash /, we'll throw up on this because
469 # SVN can't have directories with a slash in their name, either:
470 if ($refname =~ m{/$}) {
471 die "ref: '$refname' ends with a trailing slash, this is ",
472 "not permitted by git nor Subversion\n";
475 # It cannot have ASCII control character space, tilde ~, caret ^,
476 # colon :, question-mark ?, asterisk *, space, or open bracket [
477 # anywhere.
479 # Additionally, % must be escaped because it is used for escaping
480 # and we want our escaped refname to be reversible
481 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
483 # no slash-separated component can begin with a dot .
484 # /.* becomes /%2E*
485 $refname =~ s{/\.}{/%2E}g;
487 # It cannot have two consecutive dots .. anywhere
488 # .. becomes %2E%2E
489 $refname =~ s{\.\.}{%2E%2E}g;
491 # trailing dots and .lock are not allowed
492 # .$ becomes %2E and .lock becomes %2Elock
493 $refname =~ s{\.(?=$|lock$)}{%2E};
495 # the sequence @{ is used to access the reflog
496 # @{ becomes %40{
497 $refname =~ s{\@\{}{%40\{}g;
499 return $refname;
502 sub desanitize_refname {
503 my ($refname) = @_;
504 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
505 return $refname;
508 sub svm_uuid {
509 my ($self) = @_;
510 return $self->{svm}->{uuid} if $self->svm;
511 $self->ra;
512 unless ($self->{svm}) {
513 die "SVM UUID not cached, and reading remotely failed\n";
515 $self->{svm}->{uuid};
518 sub svm {
519 my ($self) = @_;
520 return $self->{svm} if $self->{svm};
521 my $svm;
522 # see if we have it in our config, first:
523 eval {
524 my $section = "svn-remote.$self->{repo_id}";
525 $svm = {
526 source => tmp_config('--get', "$section.svm-source"),
527 uuid => tmp_config('--get', "$section.svm-uuid"),
528 replace => tmp_config('--get', "$section.svm-replace"),
531 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
532 $self->{svm} = $svm;
534 $self->{svm};
537 sub _set_svm_vars {
538 my ($self, $ra) = @_;
539 return $ra if $self->svm;
541 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
542 "(svm:source, svm:uuid) ",
543 "from the following URLs:\n" );
544 sub read_svm_props {
545 my ($self, $ra, $path, $r) = @_;
546 my $props = ($ra->get_dir($path, $r))[2];
547 my $src = $props->{'svm:source'};
548 my $uuid = $props->{'svm:uuid'};
549 return undef if (!$src || !$uuid);
551 chomp($src, $uuid);
553 $uuid =~ m{^[0-9a-f\-]{30,}$}i
554 or die "doesn't look right - svm:uuid is '$uuid'\n";
556 # the '!' is used to mark the repos_root!/relative/path
557 $src =~ s{/?!/?}{/};
558 $src =~ s{/+$}{}; # no trailing slashes please
559 # username is of no interest
560 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
562 my $replace = $ra->{url};
563 $replace .= "/$path" if length $path;
565 my $section = "svn-remote.$self->{repo_id}";
566 tmp_config("$section.svm-source", $src);
567 tmp_config("$section.svm-replace", $replace);
568 tmp_config("$section.svm-uuid", $uuid);
569 $self->{svm} = {
570 source => $src,
571 uuid => $uuid,
572 replace => $replace
576 my $r = $ra->get_latest_revnum;
577 my $path = $self->path;
578 my %tried;
579 while (length $path) {
580 unless ($tried{"$self->{url}/$path"}) {
581 return $ra if $self->read_svm_props($ra, $path, $r);
582 $tried{"$self->{url}/$path"} = 1;
584 $path =~ s#/?[^/]+$##;
586 die "Path: '$path' should be ''\n" if $path ne '';
587 return $ra if $self->read_svm_props($ra, $path, $r);
588 $tried{"$self->{url}/$path"} = 1;
590 if ($ra->{repos_root} eq $self->{url}) {
591 die @err, (map { " $_\n" } keys %tried), "\n";
594 # nope, make sure we're connected to the repository root:
595 my $ok;
596 my @tried_b;
597 $path = $ra->{svn_path};
598 $ra = Git::SVN::Ra->new($ra->{repos_root});
599 while (length $path) {
600 unless ($tried{"$ra->{url}/$path"}) {
601 $ok = $self->read_svm_props($ra, $path, $r);
602 last if $ok;
603 $tried{"$ra->{url}/$path"} = 1;
605 $path =~ s#/?[^/]+$##;
607 die "Path: '$path' should be ''\n" if $path ne '';
608 $ok ||= $self->read_svm_props($ra, $path, $r);
609 $tried{"$ra->{url}/$path"} = 1;
610 if (!$ok) {
611 die @err, (map { " $_\n" } keys %tried), "\n";
613 Git::SVN::Ra->new($self->{url});
616 sub svnsync {
617 my ($self) = @_;
618 return $self->{svnsync} if $self->{svnsync};
620 if ($self->no_metadata) {
621 die "Can't have both 'noMetadata' and ",
622 "'useSvnsyncProps' options set!\n";
624 if ($self->rewrite_root) {
625 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
626 "options set!\n";
628 if ($self->rewrite_uuid) {
629 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
630 "options set!\n";
633 my $svnsync;
634 # see if we have it in our config, first:
635 eval {
636 my $section = "svn-remote.$self->{repo_id}";
638 my $url = tmp_config('--get', "$section.svnsync-url");
639 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
640 die "doesn't look right - svn:sync-from-url is '$url'\n";
642 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
643 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
644 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
646 $svnsync = { url => $url, uuid => $uuid }
648 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
649 return $self->{svnsync} = $svnsync;
652 my $err = "useSvnsyncProps set, but failed to read " .
653 "svnsync property: svn:sync-from-";
654 my $rp = $self->ra->rev_proplist(0);
656 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
657 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
658 die "doesn't look right - svn:sync-from-url is '$url'\n";
660 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
661 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
662 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
664 my $section = "svn-remote.$self->{repo_id}";
665 tmp_config('--add', "$section.svnsync-uuid", $uuid);
666 tmp_config('--add', "$section.svnsync-url", $url);
667 return $self->{svnsync} = { url => $url, uuid => $uuid };
670 # this allows us to memoize our SVN::Ra UUID locally and avoid a
671 # remote lookup (useful for 'git svn log').
672 sub ra_uuid {
673 my ($self) = @_;
674 unless ($self->{ra_uuid}) {
675 my $key = "svn-remote.$self->{repo_id}.uuid";
676 my $uuid = eval { tmp_config('--get', $key) };
677 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
678 $self->{ra_uuid} = $uuid;
679 } else {
680 die "ra_uuid called without URL\n" unless $self->{url};
681 $self->{ra_uuid} = $self->ra->get_uuid;
682 tmp_config('--add', $key, $self->{ra_uuid});
685 $self->{ra_uuid};
688 sub _set_repos_root {
689 my ($self, $repos_root) = @_;
690 my $k = "svn-remote.$self->{repo_id}.reposRoot";
691 $repos_root ||= $self->ra->{repos_root};
692 tmp_config($k, $repos_root);
693 $repos_root;
696 sub repos_root {
697 my ($self) = @_;
698 my $k = "svn-remote.$self->{repo_id}.reposRoot";
699 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
702 sub ra {
703 my ($self) = shift;
704 my $ra = Git::SVN::Ra->new($self->{url});
705 $self->_set_repos_root($ra->{repos_root});
706 if ($self->use_svm_props && !$self->{svm}) {
707 if ($self->no_metadata) {
708 die "Can't have both 'noMetadata' and ",
709 "'useSvmProps' options set!\n";
710 } elsif ($self->use_svnsync_props) {
711 die "Can't have both 'useSvnsyncProps' and ",
712 "'useSvmProps' options set!\n";
714 $ra = $self->_set_svm_vars($ra);
715 $self->{-want_revprops} = 1;
717 $ra;
720 # prop_walk(PATH, REV, SUB)
721 # -------------------------
722 # Recursively traverse PATH at revision REV and invoke SUB for each
723 # directory that contains a SVN property. SUB will be invoked as
724 # follows: &SUB(gs, path, props); where `gs' is this instance of
725 # Git::SVN, `path' the path to the directory where the properties
726 # `props' were found. The `path' will be relative to point of checkout,
727 # that is, if url://repo/trunk is the current Git branch, and that
728 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
729 # as `path' (note the trailing `/').
730 sub prop_walk {
731 my ($self, $path, $rev, $sub) = @_;
733 $path =~ s#^/##;
734 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
735 $path =~ s#^/*#/#g;
736 my $p = $path;
737 # Strip the irrelevant part of the path.
738 $p =~ s#^/+\Q@{[$self->path]}\E(/|$)#/#;
739 # Ensure the path is terminated by a `/'.
740 $p =~ s#/*$#/#;
742 # The properties contain all the internal SVN stuff nobody
743 # (usually) cares about.
744 my $interesting_props = 0;
745 foreach (keys %{$props}) {
746 # If it doesn't start with `svn:', it must be a
747 # user-defined property.
748 ++$interesting_props and next if $_ !~ /^svn:/;
749 # FIXME: Fragile, if SVN adds new public properties,
750 # this needs to be updated.
751 ++$interesting_props if /^svn:(?:ignore|keywords|executable
752 |eol-style|mime-type
753 |externals|needs-lock)$/x;
755 &$sub($self, $p, $props) if $interesting_props;
757 foreach (sort keys %$dirent) {
758 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
759 $self->prop_walk($self->path . $p . $_, $rev, $sub);
763 sub last_rev { ($_[0]->last_rev_commit)[0] }
764 sub last_commit { ($_[0]->last_rev_commit)[1] }
766 # returns the newest SVN revision number and newest commit SHA1
767 sub last_rev_commit {
768 my ($self) = @_;
769 if (defined $self->{last_rev} && defined $self->{last_commit}) {
770 return ($self->{last_rev}, $self->{last_commit});
772 my $c = ::verify_ref($self->refname.'^0');
773 if ($c && !$self->use_svm_props && !$self->no_metadata) {
774 my $rev = (::cmt_metadata($c))[1];
775 if (defined $rev) {
776 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
777 return ($rev, $c);
780 my $map_path = $self->map_path;
781 unless (-e $map_path) {
782 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
783 return (undef, undef);
785 my ($rev, $commit) = $self->rev_map_max(1);
786 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
787 return ($rev, $commit);
790 sub get_fetch_range {
791 my ($self, $min, $max) = @_;
792 $max ||= $self->ra->get_latest_revnum;
793 $min ||= $self->rev_map_max;
794 (++$min, $max);
797 sub tmp_config {
798 my (@args) = @_;
799 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
800 my $config = "$ENV{GIT_DIR}/svn/.metadata";
801 if (! -f $config && -f $old_def_config) {
802 rename $old_def_config, $config or
803 die "Failed rename $old_def_config => $config: $!\n";
805 my $old_config = $ENV{GIT_CONFIG};
806 $ENV{GIT_CONFIG} = $config;
807 $@ = undef;
808 my @ret = eval {
809 unless (-f $config) {
810 mkfile($config);
811 open my $fh, '>', $config or
812 die "Can't open $config: $!\n";
813 print $fh "; This file is used internally by ",
814 "git-svn\n" or die
815 "Couldn't write to $config: $!\n";
816 print $fh "; You should not have to edit it\n" or
817 die "Couldn't write to $config: $!\n";
818 close $fh or die "Couldn't close $config: $!\n";
820 command('config', @args);
822 my $err = $@;
823 if (defined $old_config) {
824 $ENV{GIT_CONFIG} = $old_config;
825 } else {
826 delete $ENV{GIT_CONFIG};
828 die $err if $err;
829 wantarray ? @ret : $ret[0];
832 sub tmp_index_do {
833 my ($self, $sub) = @_;
834 my $old_index = $ENV{GIT_INDEX_FILE};
835 $ENV{GIT_INDEX_FILE} = $self->{index};
836 $@ = undef;
837 my @ret = eval {
838 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
839 mkpath([$dir]) unless -d $dir;
840 &$sub;
842 my $err = $@;
843 if (defined $old_index) {
844 $ENV{GIT_INDEX_FILE} = $old_index;
845 } else {
846 delete $ENV{GIT_INDEX_FILE};
848 die $err if $err;
849 wantarray ? @ret : $ret[0];
852 sub assert_index_clean {
853 my ($self, $treeish) = @_;
855 $self->tmp_index_do(sub {
856 command_noisy('read-tree', $treeish) unless -e $self->{index};
857 my $x = command_oneline('write-tree');
858 my ($y) = (command(qw/cat-file commit/, $treeish) =~
859 /^tree ($::sha1)/mo);
860 return if $y eq $x;
862 warn "Index mismatch: $y != $x\nrereading $treeish\n";
863 unlink $self->{index} or die "unlink $self->{index}: $!\n";
864 command_noisy('read-tree', $treeish);
865 $x = command_oneline('write-tree');
866 if ($y ne $x) {
867 fatal "trees ($treeish) $y != $x\n",
868 "Something is seriously wrong...";
873 sub get_commit_parents {
874 my ($self, $log_entry) = @_;
875 my (%seen, @ret, @tmp);
876 # legacy support for 'set-tree'; this is only used by set_tree_cb:
877 if (my $ip = $self->{inject_parents}) {
878 if (my $commit = delete $ip->{$log_entry->{revision}}) {
879 push @tmp, $commit;
882 if (my $cur = ::verify_ref($self->refname.'^0')) {
883 push @tmp, $cur;
885 if (my $ipd = $self->{inject_parents_dcommit}) {
886 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
887 push @tmp, @$commit;
890 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
891 while (my $p = shift @tmp) {
892 next if $seen{$p};
893 $seen{$p} = 1;
894 push @ret, $p;
896 @ret;
899 sub rewrite_root {
900 my ($self) = @_;
901 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
902 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
903 my $rwr = eval { command_oneline(qw/config --get/, $k) };
904 if ($rwr) {
905 $rwr =~ s#/+$##;
906 if ($rwr !~ m#^[a-z\+]+://#) {
907 die "$rwr is not a valid URL (key: $k)\n";
910 $self->{-rewrite_root} = $rwr;
913 sub rewrite_uuid {
914 my ($self) = @_;
915 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
916 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
917 my $rwid = eval { command_oneline(qw/config --get/, $k) };
918 if ($rwid) {
919 $rwid =~ s#/+$##;
920 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
921 die "$rwid is not a valid UUID (key: $k)\n";
924 $self->{-rewrite_uuid} = $rwid;
927 sub metadata_url {
928 my ($self) = @_;
929 ($self->rewrite_root || $self->{url}) .
930 (length $self->path ? '/' . $self->path : '');
933 sub full_url {
934 my ($self) = @_;
935 $self->{url} . (length $self->path ? '/' . $self->path : '');
938 sub full_pushurl {
939 my ($self) = @_;
940 if ($self->{pushurl}) {
941 return $self->{pushurl} . (length $self->path ? '/' .
942 $self->path : '');
943 } else {
944 return $self->full_url;
948 sub set_commit_header_env {
949 my ($log_entry) = @_;
950 my %env;
951 foreach my $ned (qw/NAME EMAIL DATE/) {
952 foreach my $ac (qw/AUTHOR COMMITTER/) {
953 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
957 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
958 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
959 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
961 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
962 ? $log_entry->{commit_name}
963 : $log_entry->{name};
964 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
965 ? $log_entry->{commit_email}
966 : $log_entry->{email};
967 \%env;
970 sub restore_commit_header_env {
971 my ($env) = @_;
972 foreach my $ned (qw/NAME EMAIL DATE/) {
973 foreach my $ac (qw/AUTHOR COMMITTER/) {
974 my $k = "GIT_${ac}_${ned}";
975 if (defined $env->{$k}) {
976 $ENV{$k} = $env->{$k};
977 } else {
978 delete $ENV{$k};
984 sub gc {
985 command_noisy('gc', '--auto');
988 sub do_git_commit {
989 my ($self, $log_entry) = @_;
990 my $lr = $self->last_rev;
991 if (defined $lr && $lr >= $log_entry->{revision}) {
992 die "Last fetched revision of ", $self->refname,
993 " was r$lr, but we are about to fetch: ",
994 "r$log_entry->{revision}!\n";
996 if (my $c = $self->rev_map_get($log_entry->{revision})) {
997 croak "$log_entry->{revision} = $c already exists! ",
998 "Why are we refetching it?\n";
1000 my $old_env = set_commit_header_env($log_entry);
1001 my $tree = $log_entry->{tree};
1002 if (!defined $tree) {
1003 $tree = $self->tmp_index_do(sub {
1004 command_oneline('write-tree') });
1006 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1008 my @exec = ('git', 'commit-tree', $tree);
1009 foreach ($self->get_commit_parents($log_entry)) {
1010 push @exec, '-p', $_;
1012 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1013 or croak $!;
1014 binmode $msg_fh;
1016 # we always get UTF-8 from SVN, but we may want our commits in
1017 # a different encoding.
1018 if (my $enc = Git::config('i18n.commitencoding')) {
1019 require Encode;
1020 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
1022 print $msg_fh $log_entry->{log} or croak $!;
1023 restore_commit_header_env($old_env);
1024 unless ($self->no_metadata) {
1025 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1026 or croak $!;
1028 $msg_fh->flush == 0 or croak $!;
1029 close $msg_fh or croak $!;
1030 chomp(my $commit = do { local $/; <$out_fh> });
1031 close $out_fh or croak $!;
1032 waitpid $pid, 0;
1033 croak $? if $?;
1034 if ($commit !~ /^$::sha1$/o) {
1035 die "Failed to commit, invalid sha1: $commit\n";
1038 $self->rev_map_set($log_entry->{revision}, $commit, 1);
1040 $self->{last_rev} = $log_entry->{revision};
1041 $self->{last_commit} = $commit;
1042 print "r$log_entry->{revision}" unless $::_q > 1;
1043 if (defined $log_entry->{svm_revision}) {
1044 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
1045 $self->rev_map_set($log_entry->{svm_revision}, $commit,
1046 0, $self->svm_uuid);
1048 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
1049 if (--$_gc_nr == 0) {
1050 $_gc_nr = $_gc_period;
1051 gc();
1053 return $commit;
1056 sub match_paths {
1057 my ($self, $paths, $r) = @_;
1058 return 1 if $self->path eq '';
1059 if (my $path = $paths->{"/".$self->path}) {
1060 return ($path->{action} eq 'D') ? 0 : 1;
1062 $self->{path_regex} ||= qr{^/\Q@{[$self->path]}\E/};
1063 if (grep /$self->{path_regex}/, keys %$paths) {
1064 return 1;
1066 my $c = '';
1067 foreach (split m#/#, $self->path) {
1068 $c .= "/$_";
1069 next unless ($paths->{$c} &&
1070 ($paths->{$c}->{action} =~ /^[AR]$/));
1071 if ($self->ra->check_path($self->path, $r) ==
1072 $SVN::Node::dir) {
1073 return 1;
1076 return 0;
1079 sub find_parent_branch {
1080 my ($self, $paths, $rev) = @_;
1081 return undef unless $self->follow_parent;
1082 unless (defined $paths) {
1083 my $err_handler = $SVN::Error::handler;
1084 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1085 $self->ra->get_log([$self->path], $rev, $rev, 0, 1, 1,
1086 sub { $paths = $_[0] });
1087 $SVN::Error::handler = $err_handler;
1089 return undef unless defined $paths;
1091 # look for a parent from another branch:
1092 my @b_path_components = split m#/#, $self->path;
1093 my @a_path_components;
1094 my $i;
1095 while (@b_path_components) {
1096 $i = $paths->{'/'.join('/', @b_path_components)};
1097 last if $i && defined $i->{copyfrom_path};
1098 unshift(@a_path_components, pop(@b_path_components));
1100 return undef unless defined $i && defined $i->{copyfrom_path};
1101 my $branch_from = $i->{copyfrom_path};
1102 if (@a_path_components) {
1103 print STDERR "branch_from: $branch_from => ";
1104 $branch_from .= '/'.join('/', @a_path_components);
1105 print STDERR $branch_from, "\n";
1107 my $r = $i->{copyfrom_rev};
1108 my $repos_root = $self->ra->{repos_root};
1109 my $url = $self->ra->{url};
1110 my $new_url = $url . $branch_from;
1111 print STDERR "Found possible branch point: ",
1112 "$new_url => ", $self->full_url, ", $r\n"
1113 unless $::_q > 1;
1114 $branch_from =~ s#^/##;
1115 my $gs = $self->other_gs($new_url, $url,
1116 $branch_from, $r, $self->{ref_id});
1117 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1119 my ($base, $head);
1120 if (!defined $r0 || !defined $parent) {
1121 ($base, $head) = parse_revision_argument(0, $r);
1122 } else {
1123 if ($r0 < $r) {
1124 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
1125 0, 1, sub { $base = $_[1] - 1 });
1128 if (defined $base && $base <= $r) {
1129 $gs->fetch($base, $r);
1131 ($r0, $parent) = $gs->find_rev_before($r, 1);
1133 if (defined $r0 && defined $parent) {
1134 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
1135 unless $::_q > 1;
1136 my $ed;
1137 if ($self->ra->can_do_switch) {
1138 $self->assert_index_clean($parent);
1139 print STDERR "Following parent with do_switch\n"
1140 unless $::_q > 1;
1141 # do_switch works with svn/trunk >= r22312, but that
1142 # is not included with SVN 1.4.3 (the latest version
1143 # at the moment), so we can't rely on it
1144 $self->{last_rev} = $r0;
1145 $self->{last_commit} = $parent;
1146 $ed = Git::SVN::Fetcher->new($self, $gs->{path});
1147 $gs->ra->gs_do_switch($r0, $rev, $gs,
1148 $self->full_url, $ed)
1149 or die "SVN connection failed somewhere...\n";
1150 } elsif ($self->ra->trees_match($new_url, $r0,
1151 $self->full_url, $rev)) {
1152 print STDERR "Trees match:\n",
1153 " $new_url\@$r0\n",
1154 " ${\$self->full_url}\@$rev\n",
1155 "Following parent with no changes\n"
1156 unless $::_q > 1;
1157 $self->tmp_index_do(sub {
1158 command_noisy('read-tree', $parent);
1160 $self->{last_commit} = $parent;
1161 } else {
1162 print STDERR "Following parent with do_update\n"
1163 unless $::_q > 1;
1164 $ed = Git::SVN::Fetcher->new($self);
1165 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1166 or die "SVN connection failed somewhere...\n";
1168 print STDERR "Successfully followed parent\n" unless $::_q > 1;
1169 return $self->make_log_entry($rev, [$parent], $ed);
1171 return undef;
1174 sub do_fetch {
1175 my ($self, $paths, $rev) = @_;
1176 my $ed;
1177 my ($last_rev, @parents);
1178 if (my $lc = $self->last_commit) {
1179 # we can have a branch that was deleted, then re-added
1180 # under the same name but copied from another path, in
1181 # which case we'll have multiple parents (we don't
1182 # want to break the original ref, nor lose copypath info):
1183 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1184 push @{$log_entry->{parents}}, $lc;
1185 return $log_entry;
1187 $ed = Git::SVN::Fetcher->new($self);
1188 $last_rev = $self->{last_rev};
1189 $ed->{c} = $lc;
1190 @parents = ($lc);
1191 } else {
1192 $last_rev = $rev;
1193 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1194 return $log_entry;
1196 $ed = Git::SVN::Fetcher->new($self);
1198 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1199 die "SVN connection failed somewhere...\n";
1201 $self->make_log_entry($rev, \@parents, $ed);
1204 sub mkemptydirs {
1205 my ($self, $r) = @_;
1207 sub scan {
1208 my ($r, $empty_dirs, $line) = @_;
1209 if (defined $r && $line =~ /^r(\d+)$/) {
1210 return 0 if $1 > $r;
1211 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
1212 $empty_dirs->{$1} = 1;
1213 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
1214 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
1215 delete @$empty_dirs{@d};
1217 1; # continue
1220 my %empty_dirs = ();
1221 my $gz_file = "$self->{dir}/unhandled.log.gz";
1222 if (-f $gz_file) {
1223 if (!can_compress()) {
1224 warn "Compress::Zlib could not be found; ",
1225 "empty directories in $gz_file will not be read\n";
1226 } else {
1227 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
1228 die "Unable to open $gz_file: $!\n";
1229 my $line;
1230 while ($gz->gzreadline($line) > 0) {
1231 scan($r, \%empty_dirs, $line) or last;
1233 $gz->gzclose;
1237 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
1238 binmode $fh or croak "binmode: $!";
1239 while (<$fh>) {
1240 scan($r, \%empty_dirs, $_) or last;
1242 close $fh;
1245 my $strip = qr/\A\Q@{[$self->path]}\E(?:\/|$)/;
1246 foreach my $d (sort keys %empty_dirs) {
1247 $d = uri_decode($d);
1248 $d =~ s/$strip//;
1249 next unless length($d);
1250 next if -d $d;
1251 if (-e $d) {
1252 warn "$d exists but is not a directory\n";
1253 } else {
1254 print "creating empty directory: $d\n";
1255 mkpath([$d]);
1260 sub get_untracked {
1261 my ($self, $ed) = @_;
1262 my @out;
1263 my $h = $ed->{empty};
1264 foreach (sort keys %$h) {
1265 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1266 push @out, " $act: " . uri_encode($_);
1267 warn "W: $act: $_\n";
1269 foreach my $t (qw/dir_prop file_prop/) {
1270 $h = $ed->{$t} or next;
1271 foreach my $path (sort keys %$h) {
1272 my $ppath = $path eq '' ? '.' : $path;
1273 foreach my $prop (sort keys %{$h->{$path}}) {
1274 next if $SKIP_PROP{$prop};
1275 my $v = $h->{$path}->{$prop};
1276 my $t_ppath_prop = "$t: " .
1277 uri_encode($ppath) . ' ' .
1278 uri_encode($prop);
1279 if (defined $v) {
1280 push @out, " +$t_ppath_prop " .
1281 uri_encode($v);
1282 } else {
1283 push @out, " -$t_ppath_prop";
1288 foreach my $t (qw/absent_file absent_directory/) {
1289 $h = $ed->{$t} or next;
1290 foreach my $parent (sort keys %$h) {
1291 foreach my $path (sort @{$h->{$parent}}) {
1292 push @out, " $t: " .
1293 uri_encode("$parent/$path");
1294 warn "W: $t: $parent/$path ",
1295 "Insufficient permissions?\n";
1299 \@out;
1302 sub get_tz {
1303 # some systmes don't handle or mishandle %z, so be creative.
1304 my $t = shift || time;
1305 my $gm = timelocal(gmtime($t));
1306 my $sign = qw( + + - )[ $t <=> $gm ];
1307 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
1310 # parse_svn_date(DATE)
1311 # --------------------
1312 # Given a date (in UTC) from Subversion, return a string in the format
1313 # "<TZ Offset> <local date/time>" that Git will use.
1315 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
1316 # is true we'll convert it to the local timezone instead.
1317 sub parse_svn_date {
1318 my $date = shift || return '+0000 1970-01-01 00:00:00';
1319 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1320 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1321 croak "Unable to parse date: $date\n";
1322 my $parsed_date; # Set next.
1324 if ($Git::SVN::_localtime) {
1325 # Translate the Subversion datetime to an epoch time.
1326 # Begin by switching ourselves to $date's timezone, UTC.
1327 my $old_env_TZ = $ENV{TZ};
1328 $ENV{TZ} = 'UTC';
1330 my $epoch_in_UTC =
1331 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
1333 # Determine our local timezone (including DST) at the
1334 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
1335 # value of TZ, if any, at the time we were run.
1336 if (defined $Git::SVN::Log::TZ) {
1337 $ENV{TZ} = $Git::SVN::Log::TZ;
1338 } else {
1339 delete $ENV{TZ};
1342 my $our_TZ = get_tz();
1344 # This converts $epoch_in_UTC into our local timezone.
1345 my ($sec, $min, $hour, $mday, $mon, $year,
1346 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
1348 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
1349 $our_TZ, $year + 1900, $mon + 1,
1350 $mday, $hour, $min, $sec);
1352 # Reset us to the timezone in effect when we entered
1353 # this routine.
1354 if (defined $old_env_TZ) {
1355 $ENV{TZ} = $old_env_TZ;
1356 } else {
1357 delete $ENV{TZ};
1359 } else {
1360 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
1363 return $parsed_date;
1366 sub other_gs {
1367 my ($self, $new_url, $url,
1368 $branch_from, $r, $old_ref_id) = @_;
1369 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
1370 unless ($gs) {
1371 my $ref_id = $old_ref_id;
1372 $ref_id =~ s/\@\d+-*$//;
1373 $ref_id .= "\@$r";
1374 # just grow a tail if we're not unique enough :x
1375 $ref_id .= '-' while find_ref($ref_id);
1376 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
1377 if ($u =~ s#^\Q$url\E(/|$)##) {
1378 $p = $u;
1379 $u = $url;
1380 $repo_id = $self->{repo_id};
1382 while (1) {
1383 # It is possible to tag two different subdirectories at
1384 # the same revision. If the url for an existing ref
1385 # does not match, we must either find a ref with a
1386 # matching url or create a new ref by growing a tail.
1387 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
1388 my (undef, $max_commit) = $gs->rev_map_max(1);
1389 last if (!$max_commit);
1390 my ($url) = ::cmt_metadata($max_commit);
1391 last if ($url eq $gs->metadata_url);
1392 $ref_id .= '-';
1394 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
1399 sub call_authors_prog {
1400 my ($orig_author) = @_;
1401 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
1402 my $author = `$::_authors_prog $orig_author`;
1403 if ($? != 0) {
1404 die "$::_authors_prog failed with exit code $?\n"
1406 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
1407 my ($name, $email) = ($1, $2);
1408 $email = undef if length $2 == 0;
1409 return [$name, $email];
1410 } else {
1411 die "Author: $orig_author: $::_authors_prog returned "
1412 . "invalid author format: $author\n";
1416 sub check_author {
1417 my ($author) = @_;
1418 if (!defined $author || length $author == 0) {
1419 $author = '(no author)';
1421 if (!defined $::users{$author}) {
1422 if (defined $::_authors_prog) {
1423 $::users{$author} = call_authors_prog($author);
1424 } elsif (defined $::_authors) {
1425 die "Author: $author not defined in $::_authors file\n";
1428 $author;
1431 sub find_extra_svk_parents {
1432 my ($self, $ed, $tickets, $parents) = @_;
1433 # aha! svk:merge property changed...
1434 my @tickets = split "\n", $tickets;
1435 my @known_parents;
1436 for my $ticket ( @tickets ) {
1437 my ($uuid, $path, $rev) = split /:/, $ticket;
1438 if ( $uuid eq $self->ra_uuid ) {
1439 my $url = $self->{url};
1440 my $repos_root = $url;
1441 my $branch_from = $path;
1442 $branch_from =~ s{^/}{};
1443 my $gs = $self->other_gs($repos_root."/".$branch_from,
1444 $url,
1445 $branch_from,
1446 $rev,
1447 $self->{ref_id});
1448 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
1449 # wahey! we found it, but it might be
1450 # an old one (!)
1451 push @known_parents, [ $rev, $commit ];
1455 # Ordering matters; highest-numbered commit merge tickets
1456 # first, as they may account for later merge ticket additions
1457 # or changes.
1458 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
1459 for my $parent ( @known_parents ) {
1460 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
1461 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
1462 my $new;
1463 while ( <$msg_fh> ) {
1464 $new=1;last;
1466 command_close_pipe($msg_fh, $ctx);
1467 if ( $new ) {
1468 print STDERR
1469 "Found merge parent (svk:merge ticket): $parent\n";
1470 push @$parents, $parent;
1475 sub lookup_svn_merge {
1476 my $uuid = shift;
1477 my $url = shift;
1478 my $merge = shift;
1480 my ($source, $revs) = split ":", $merge;
1481 my $path = $source;
1482 $path =~ s{^/}{};
1483 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
1484 if ( !$gs ) {
1485 warn "Couldn't find revmap for $url$source\n";
1486 return;
1488 my @ranges = split ",", $revs;
1489 my ($tip, $tip_commit);
1490 my @merged_commit_ranges;
1491 # find the tip
1492 for my $range ( @ranges ) {
1493 my ($bottom, $top) = split "-", $range;
1494 $top ||= $bottom;
1495 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
1496 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
1498 unless ($top_commit and $bottom_commit) {
1499 warn "W:unknown path/rev in svn:mergeinfo "
1500 ."dirprop: $source:$range\n";
1501 next;
1504 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
1505 push @merged_commit_ranges,
1506 "$bottom_commit^..$top_commit";
1507 } else {
1508 push @merged_commit_ranges, "$top_commit";
1511 if ( !defined $tip or $top > $tip ) {
1512 $tip = $top;
1513 $tip_commit = $top_commit;
1516 return ($tip_commit, @merged_commit_ranges);
1519 sub _rev_list {
1520 my ($msg_fh, $ctx) = command_output_pipe(
1521 "rev-list", @_,
1523 my @rv;
1524 while ( <$msg_fh> ) {
1525 chomp;
1526 push @rv, $_;
1528 command_close_pipe($msg_fh, $ctx);
1529 @rv;
1532 sub check_cherry_pick {
1533 my $base = shift;
1534 my $tip = shift;
1535 my $parents = shift;
1536 my @ranges = @_;
1537 my %commits = map { $_ => 1 }
1538 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
1539 for my $range ( @ranges ) {
1540 delete @commits{_rev_list($range, "--")};
1542 for my $commit (keys %commits) {
1543 if (has_no_changes($commit)) {
1544 delete $commits{$commit};
1547 return (keys %commits);
1550 sub has_no_changes {
1551 my $commit = shift;
1553 my @revs = split / /, command_oneline(
1554 qw(rev-list --parents -1 -m), $commit);
1556 # Commits with no parents, e.g. the start of a partial branch,
1557 # have changes by definition.
1558 return 1 if (@revs < 2);
1560 # Commits with multiple parents, e.g a merge, have no changes
1561 # by definition.
1562 return 0 if (@revs > 2);
1564 return (command_oneline("rev-parse", "$commit^{tree}") eq
1565 command_oneline("rev-parse", "$commit~1^{tree}"));
1568 sub tie_for_persistent_memoization {
1569 my $hash = shift;
1570 my $path = shift;
1572 if ($can_use_yaml) {
1573 tie %$hash => 'Git::SVN::Memoize::YAML', "$path.yaml";
1574 } else {
1575 tie %$hash => 'Memoize::Storable', "$path.db", 'nstore';
1579 # The GIT_DIR environment variable is not always set until after the command
1580 # line arguments are processed, so we can't memoize in a BEGIN block.
1582 my $memoized = 0;
1584 sub memoize_svn_mergeinfo_functions {
1585 return if $memoized;
1586 $memoized = 1;
1588 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1589 mkpath([$cache_path]) unless -d $cache_path;
1591 my %lookup_svn_merge_cache;
1592 my %check_cherry_pick_cache;
1593 my %has_no_changes_cache;
1595 tie_for_persistent_memoization(\%lookup_svn_merge_cache,
1596 "$cache_path/lookup_svn_merge");
1597 memoize 'lookup_svn_merge',
1598 SCALAR_CACHE => 'FAULT',
1599 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
1602 tie_for_persistent_memoization(\%check_cherry_pick_cache,
1603 "$cache_path/check_cherry_pick");
1604 memoize 'check_cherry_pick',
1605 SCALAR_CACHE => 'FAULT',
1606 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
1609 tie_for_persistent_memoization(\%has_no_changes_cache,
1610 "$cache_path/has_no_changes");
1611 memoize 'has_no_changes',
1612 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
1613 LIST_CACHE => 'FAULT',
1617 sub unmemoize_svn_mergeinfo_functions {
1618 return if not $memoized;
1619 $memoized = 0;
1621 Memoize::unmemoize 'lookup_svn_merge';
1622 Memoize::unmemoize 'check_cherry_pick';
1623 Memoize::unmemoize 'has_no_changes';
1626 Memoize::memoize 'Git::SVN::repos_root';
1629 END {
1630 # Force cache writeout explicitly instead of waiting for
1631 # global destruction to avoid segfault in Storable:
1632 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
1633 unmemoize_svn_mergeinfo_functions();
1636 sub parents_exclude {
1637 my $parents = shift;
1638 my @commits = @_;
1639 return unless @commits;
1641 my @excluded;
1642 my $excluded;
1643 do {
1644 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
1645 $excluded = command_oneline(@cmd);
1646 if ( $excluded ) {
1647 my @new;
1648 my $found;
1649 for my $commit ( @commits ) {
1650 if ( $commit eq $excluded ) {
1651 push @excluded, $commit;
1652 $found++;
1653 last;
1655 else {
1656 push @new, $commit;
1659 die "saw commit '$excluded' in rev-list output, "
1660 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
1661 unless $found;
1662 @commits = @new;
1665 while ($excluded and @commits);
1667 return @excluded;
1671 # note: this function should only be called if the various dirprops
1672 # have actually changed
1673 sub find_extra_svn_parents {
1674 my ($self, $ed, $mergeinfo, $parents) = @_;
1675 # aha! svk:merge property changed...
1677 memoize_svn_mergeinfo_functions();
1679 # We first search for merged tips which are not in our
1680 # history. Then, we figure out which git revisions are in
1681 # that tip, but not this revision. If all of those revisions
1682 # are now marked as merge, we can add the tip as a parent.
1683 my @merges = split "\n", $mergeinfo;
1684 my @merge_tips;
1685 my $url = $self->{url};
1686 my $uuid = $self->ra_uuid;
1687 my %ranges;
1688 for my $merge ( @merges ) {
1689 my ($tip_commit, @ranges) =
1690 lookup_svn_merge( $uuid, $url, $merge );
1691 unless (!$tip_commit or
1692 grep { $_ eq $tip_commit } @$parents ) {
1693 push @merge_tips, $tip_commit;
1694 $ranges{$tip_commit} = \@ranges;
1695 } else {
1696 push @merge_tips, undef;
1700 my %excluded = map { $_ => 1 }
1701 parents_exclude($parents, grep { defined } @merge_tips);
1703 # check merge tips for new parents
1704 my @new_parents;
1705 for my $merge_tip ( @merge_tips ) {
1706 my $spec = shift @merges;
1707 next unless $merge_tip and $excluded{$merge_tip};
1709 my $ranges = $ranges{$merge_tip};
1711 # check out 'new' tips
1712 my $merge_base;
1713 eval {
1714 $merge_base = command_oneline(
1715 "merge-base",
1716 @$parents, $merge_tip,
1719 if ($@) {
1720 die "An error occurred during merge-base"
1721 unless $@->isa("Git::Error::Command");
1723 warn "W: Cannot find common ancestor between ".
1724 "@$parents and $merge_tip. Ignoring merge info.\n";
1725 next;
1728 # double check that there are no missing non-merge commits
1729 my (@incomplete) = check_cherry_pick(
1730 $merge_base, $merge_tip,
1731 $parents,
1732 @$ranges,
1735 if ( @incomplete ) {
1736 warn "W:svn cherry-pick ignored ($spec) - missing "
1737 .@incomplete." commit(s) (eg $incomplete[0])\n";
1738 } else {
1739 warn
1740 "Found merge parent (svn:mergeinfo prop): ",
1741 $merge_tip, "\n";
1742 push @new_parents, $merge_tip;
1746 # cater for merges which merge commits from multiple branches
1747 if ( @new_parents > 1 ) {
1748 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
1749 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
1750 next if $i == $j;
1751 next unless $new_parents[$i];
1752 next unless $new_parents[$j];
1753 my $revs = command_oneline(
1754 "rev-list", "-1",
1755 "$new_parents[$i]..$new_parents[$j]",
1757 if ( !$revs ) {
1758 undef($new_parents[$j]);
1763 push @$parents, grep { defined } @new_parents;
1766 sub make_log_entry {
1767 my ($self, $rev, $parents, $ed) = @_;
1768 my $untracked = $self->get_untracked($ed);
1770 my @parents = @$parents;
1771 my $ps = $ed->{path_strip} || "";
1772 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
1773 my $props = $ed->{dir_prop}{$path};
1774 if ( $props->{"svk:merge"} ) {
1775 $self->find_extra_svk_parents
1776 ($ed, $props->{"svk:merge"}, \@parents);
1778 if ( $props->{"svn:mergeinfo"} ) {
1779 $self->find_extra_svn_parents
1780 ($ed,
1781 $props->{"svn:mergeinfo"},
1782 \@parents);
1786 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1787 print $un "r$rev\n" or croak $!;
1788 print $un $_, "\n" foreach @$untracked;
1789 my %log_entry = ( parents => \@parents, revision => $rev,
1790 log => '');
1792 my $headrev;
1793 my $logged = delete $self->{logged_rev_props};
1794 if (!$logged || $self->{-want_revprops}) {
1795 my $rp = $self->ra->rev_proplist($rev);
1796 foreach (sort keys %$rp) {
1797 my $v = $rp->{$_};
1798 if (/^svn:(author|date|log)$/) {
1799 $log_entry{$1} = $v;
1800 } elsif ($_ eq 'svm:headrev') {
1801 $headrev = $v;
1802 } else {
1803 print $un " rev_prop: ", uri_encode($_), ' ',
1804 uri_encode($v), "\n";
1807 } else {
1808 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1810 close $un or croak $!;
1812 $log_entry{date} = parse_svn_date($log_entry{date});
1813 $log_entry{log} .= "\n";
1814 my $author = $log_entry{author} = check_author($log_entry{author});
1815 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1816 : ($author, undef);
1818 my ($commit_name, $commit_email) = ($name, $email);
1819 if ($_use_log_author) {
1820 my $name_field;
1821 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
1822 $name_field = $1;
1823 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
1824 $name_field = $1;
1826 if (!defined $name_field) {
1827 if (!defined $email) {
1828 $email = $name;
1830 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
1831 ($name, $email) = ($1, $2);
1832 } elsif ($name_field =~ /(.*)@/) {
1833 ($name, $email) = ($1, $name_field);
1834 } else {
1835 ($name, $email) = ($name_field, $name_field);
1838 if (defined $headrev && $self->use_svm_props) {
1839 if ($self->rewrite_root) {
1840 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1841 "options set!\n";
1843 if ($self->rewrite_uuid) {
1844 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
1845 "options set!\n";
1847 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
1848 # we don't want "SVM: initializing mirror for junk" ...
1849 return undef if $r == 0;
1850 my $svm = $self->svm;
1851 if ($uuid ne $svm->{uuid}) {
1852 die "UUID mismatch on SVM path:\n",
1853 "expected: $svm->{uuid}\n",
1854 " got: $uuid\n";
1856 my $full_url = $self->full_url;
1857 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1858 die "Failed to replace '$svm->{replace}' with ",
1859 "'$svm->{source}' in $full_url\n";
1860 # throw away username for storing in records
1861 remove_username($full_url);
1862 $log_entry{metadata} = "$full_url\@$r $uuid";
1863 $log_entry{svm_revision} = $r;
1864 $email ||= "$author\@$uuid";
1865 $commit_email ||= "$author\@$uuid";
1866 } elsif ($self->use_svnsync_props) {
1867 my $full_url = $self->svnsync->{url};
1868 $full_url .= "/".$self->path if length $self->path;
1869 remove_username($full_url);
1870 my $uuid = $self->svnsync->{uuid};
1871 $log_entry{metadata} = "$full_url\@$rev $uuid";
1872 $email ||= "$author\@$uuid";
1873 $commit_email ||= "$author\@$uuid";
1874 } else {
1875 my $url = $self->metadata_url;
1876 remove_username($url);
1877 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
1878 $log_entry{metadata} = "$url\@$rev " . $uuid;
1879 $email ||= "$author\@" . $uuid;
1880 $commit_email ||= "$author\@" . $uuid;
1882 $log_entry{name} = $name;
1883 $log_entry{email} = $email;
1884 $log_entry{commit_name} = $commit_name;
1885 $log_entry{commit_email} = $commit_email;
1886 \%log_entry;
1889 sub fetch {
1890 my ($self, $min_rev, $max_rev, @parents) = @_;
1891 my ($last_rev, $last_commit) = $self->last_rev_commit;
1892 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1893 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1896 sub set_tree_cb {
1897 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1898 $self->{inject_parents} = { $rev => $tree };
1899 $self->fetch(undef, undef);
1902 sub set_tree {
1903 my ($self, $tree) = (shift, shift);
1904 my $log_entry = ::get_commit_entry($tree);
1905 unless ($self->{last_rev}) {
1906 fatal("Must have an existing revision to commit");
1908 my %ed_opts = ( r => $self->{last_rev},
1909 log => $log_entry->{log},
1910 ra => $self->ra,
1911 tree_a => $self->{last_commit},
1912 tree_b => $tree,
1913 editor_cb => sub {
1914 $self->set_tree_cb($log_entry, $tree, @_) },
1915 svn_path => $self->path );
1916 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1917 print "No changes\nr$self->{last_rev} = $tree\n";
1921 sub rebuild_from_rev_db {
1922 my ($self, $path) = @_;
1923 my $r = -1;
1924 open my $fh, '<', $path or croak "open: $!";
1925 binmode $fh or croak "binmode: $!";
1926 while (<$fh>) {
1927 length($_) == 41 or croak "inconsistent size in ($_) != 41";
1928 chomp($_);
1929 ++$r;
1930 next if $_ eq ('0' x 40);
1931 $self->rev_map_set($r, $_);
1932 print "r$r = $_\n";
1934 close $fh or croak "close: $!";
1935 unlink $path or croak "unlink: $!";
1938 sub rebuild {
1939 my ($self) = @_;
1940 my $map_path = $self->map_path;
1941 my $partial = (-e $map_path && ! -z $map_path);
1942 return unless ::verify_ref($self->refname.'^0');
1943 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
1944 my $rev_db = $self->rev_db_path;
1945 $self->rebuild_from_rev_db($rev_db);
1946 if ($self->use_svm_props) {
1947 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
1948 $self->rebuild_from_rev_db($svm_rev_db);
1950 $self->unlink_rev_db_symlink;
1951 return;
1953 print "Rebuilding $map_path ...\n" if (!$partial);
1954 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
1955 (undef, undef));
1956 my ($log, $ctx) =
1957 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
1958 ($head ? "$head.." : "") . $self->refname,
1959 '--');
1960 my $metadata_url = $self->metadata_url;
1961 remove_username($metadata_url);
1962 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
1963 my $c;
1964 while (<$log>) {
1965 if ( m{^commit ($::sha1)$} ) {
1966 $c = $1;
1967 next;
1969 next unless s{^\s*(git-svn-id:)}{$1};
1970 my ($url, $rev, $uuid) = ::extract_metadata($_);
1971 remove_username($url);
1973 # ignore merges (from set-tree)
1974 next if (!defined $rev || !$uuid);
1976 # if we merged or otherwise started elsewhere, this is
1977 # how we break out of it
1978 if (($uuid ne $svn_uuid) ||
1979 ($metadata_url && $url && ($url ne $metadata_url))) {
1980 next;
1982 if ($partial && $head) {
1983 print "Partial-rebuilding $map_path ...\n";
1984 print "Currently at $base_rev = $head\n";
1985 $head = undef;
1988 $self->rev_map_set($rev, $c);
1989 print "r$rev = $c\n";
1991 command_close_pipe($log, $ctx);
1992 print "Done rebuilding $map_path\n" if (!$partial || !$head);
1993 my $rev_db_path = $self->rev_db_path;
1994 if (-f $self->rev_db_path) {
1995 unlink $self->rev_db_path or croak "unlink: $!";
1997 $self->unlink_rev_db_symlink;
2000 # rev_map:
2001 # Tie::File seems to be prone to offset errors if revisions get sparse,
2002 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2003 # one of my favorite modules is out :< Next up would be one of the DBM
2004 # modules, but I'm not sure which is most portable...
2006 # This is the replacement for the rev_db format, which was too big
2007 # and inefficient for large repositories with a lot of sparse history
2008 # (mainly tags)
2010 # The format is this:
2011 # - 24 bytes for every record,
2012 # * 4 bytes for the integer representing an SVN revision number
2013 # * 20 bytes representing the sha1 of a git commit
2014 # - No empty padding records like the old format
2015 # (except the last record, which can be overwritten)
2016 # - new records are written append-only since SVN revision numbers
2017 # increase monotonically
2018 # - lookups on SVN revision number are done via a binary search
2019 # - Piping the file to xxd -c24 is a good way of dumping it for
2020 # viewing or editing (piped back through xxd -r), should the need
2021 # ever arise.
2022 # - The last record can be padding revision with an all-zero sha1
2023 # This is used to optimize fetch performance when using multiple
2024 # "fetch" directives in .git/config
2026 # These files are disposable unless noMetadata or useSvmProps is set
2028 sub _rev_map_set {
2029 my ($fh, $rev, $commit) = @_;
2031 binmode $fh or croak "binmode: $!";
2032 my $size = (stat($fh))[7];
2033 ($size % 24) == 0 or croak "inconsistent size: $size";
2035 my $wr_offset = 0;
2036 if ($size > 0) {
2037 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2038 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2039 $read == 24 or croak "read only $read bytes (!= 24)";
2040 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2041 if ($last_commit eq ('0' x40)) {
2042 if ($size >= 48) {
2043 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2044 $read = sysread($fh, $buf, 24) or
2045 croak "read: $!";
2046 $read == 24 or
2047 croak "read only $read bytes (!= 24)";
2048 ($last_rev, $last_commit) =
2049 unpack(rev_map_fmt, $buf);
2050 if ($last_commit eq ('0' x40)) {
2051 croak "inconsistent .rev_map\n";
2054 if ($last_rev >= $rev) {
2055 croak "last_rev is higher!: $last_rev >= $rev";
2057 $wr_offset = -24;
2060 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2061 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2062 croak "write: $!";
2065 sub _rev_map_reset {
2066 my ($fh, $rev, $commit) = @_;
2067 my $c = _rev_map_get($fh, $rev);
2068 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
2069 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
2070 truncate $fh, $offset or croak "truncate: $!";
2073 sub mkfile {
2074 my ($path) = @_;
2075 unless (-e $path) {
2076 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2077 mkpath([$dir]) unless -d $dir;
2078 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2079 close $fh or die "Couldn't close (create) $path: $!\n";
2083 sub rev_map_set {
2084 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2085 defined $commit or die "missing arg3\n";
2086 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2087 my $db = $self->map_path($uuid);
2088 my $db_lock = "$db.lock";
2089 my $sigmask;
2090 $update_ref ||= 0;
2091 if ($update_ref) {
2092 $sigmask = POSIX::SigSet->new();
2093 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
2094 SIGALRM, SIGUSR1, SIGUSR2);
2095 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
2096 croak "Can't block signals: $!";
2098 mkfile($db);
2100 $LOCKFILES{$db_lock} = 1;
2101 my $sync;
2102 # both of these options make our .rev_db file very, very important
2103 # and we can't afford to lose it because rebuild() won't work
2104 if ($self->use_svm_props || $self->no_metadata) {
2105 $sync = 1;
2106 copy($db, $db_lock) or die "rev_map_set(@_): ",
2107 "Failed to copy: ",
2108 "$db => $db_lock ($!)\n";
2109 } else {
2110 rename $db, $db_lock or die "rev_map_set(@_): ",
2111 "Failed to rename: ",
2112 "$db => $db_lock ($!)\n";
2115 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2116 or croak "Couldn't open $db_lock: $!\n";
2117 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
2118 _rev_map_set($fh, $rev, $commit);
2119 if ($sync) {
2120 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2121 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2123 close $fh or croak $!;
2124 if ($update_ref) {
2125 $_head = $self;
2126 my $note = "";
2127 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
2128 command_noisy('update-ref', '-m', "r$rev$note",
2129 $self->refname, $commit);
2131 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2132 "$db_lock => $db ($!)\n";
2133 delete $LOCKFILES{$db_lock};
2134 if ($update_ref) {
2135 sigprocmask(SIG_SETMASK, $sigmask) or
2136 croak "Can't restore signal mask: $!";
2140 # If want_commit, this will return an array of (rev, commit) where
2141 # commit _must_ be a valid commit in the archive.
2142 # Otherwise, it'll return the max revision (whether or not the
2143 # commit is valid or just a 0x40 placeholder).
2144 sub rev_map_max {
2145 my ($self, $want_commit) = @_;
2146 $self->rebuild;
2147 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2148 $want_commit ? ($r, $c) : $r;
2151 sub rev_map_max_norebuild {
2152 my ($self, $want_commit) = @_;
2153 my $map_path = $self->map_path;
2154 stat $map_path or return $want_commit ? (0, undef) : 0;
2155 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2156 binmode $fh or croak "binmode: $!";
2157 my $size = (stat($fh))[7];
2158 ($size % 24) == 0 or croak "inconsistent size: $size";
2160 if ($size == 0) {
2161 close $fh or croak "close: $!";
2162 return $want_commit ? (0, undef) : 0;
2165 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2166 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2167 my ($r, $c) = unpack(rev_map_fmt, $buf);
2168 if ($want_commit && $c eq ('0' x40)) {
2169 if ($size < 48) {
2170 return $want_commit ? (0, undef) : 0;
2172 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2173 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2174 ($r, $c) = unpack(rev_map_fmt, $buf);
2175 if ($c eq ('0'x40)) {
2176 croak "Penultimate record is all-zeroes in $map_path";
2179 close $fh or croak "close: $!";
2180 $want_commit ? ($r, $c) : $r;
2183 sub rev_map_get {
2184 my ($self, $rev, $uuid) = @_;
2185 my $map_path = $self->map_path($uuid);
2186 return undef unless -e $map_path;
2188 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2189 my $c = _rev_map_get($fh, $rev);
2190 close($fh) or croak "close: $!";
2194 sub _rev_map_get {
2195 my ($fh, $rev) = @_;
2197 binmode $fh or croak "binmode: $!";
2198 my $size = (stat($fh))[7];
2199 ($size % 24) == 0 or croak "inconsistent size: $size";
2201 if ($size == 0) {
2202 return undef;
2205 my ($l, $u) = (0, $size - 24);
2206 my ($r, $c, $buf);
2208 while ($l <= $u) {
2209 my $i = int(($l/24 + $u/24) / 2) * 24;
2210 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2211 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2212 my ($r, $c) = unpack(rev_map_fmt, $buf);
2214 if ($r < $rev) {
2215 $l = $i + 24;
2216 } elsif ($r > $rev) {
2217 $u = $i - 24;
2218 } else { # $r == $rev
2219 return $c eq ('0' x 40) ? undef : $c;
2222 undef;
2225 # Finds the first svn revision that exists on (if $eq_ok is true) or
2226 # before $rev for the current branch. It will not search any lower
2227 # than $min_rev. Returns the git commit hash and svn revision number
2228 # if found, else (undef, undef).
2229 sub find_rev_before {
2230 my ($self, $rev, $eq_ok, $min_rev) = @_;
2231 --$rev unless $eq_ok;
2232 $min_rev ||= 1;
2233 my $max_rev = $self->rev_map_max;
2234 $rev = $max_rev if ($rev > $max_rev);
2235 while ($rev >= $min_rev) {
2236 if (my $c = $self->rev_map_get($rev)) {
2237 return ($rev, $c);
2239 --$rev;
2241 return (undef, undef);
2244 # Finds the first svn revision that exists on (if $eq_ok is true) or
2245 # after $rev for the current branch. It will not search any higher
2246 # than $max_rev. Returns the git commit hash and svn revision number
2247 # if found, else (undef, undef).
2248 sub find_rev_after {
2249 my ($self, $rev, $eq_ok, $max_rev) = @_;
2250 ++$rev unless $eq_ok;
2251 $max_rev ||= $self->rev_map_max;
2252 while ($rev <= $max_rev) {
2253 if (my $c = $self->rev_map_get($rev)) {
2254 return ($rev, $c);
2256 ++$rev;
2258 return (undef, undef);
2261 sub _new {
2262 my ($class, $repo_id, $ref_id, $path) = @_;
2263 unless (defined $repo_id && length $repo_id) {
2264 $repo_id = $default_repo_id;
2266 unless (defined $ref_id && length $ref_id) {
2267 # Access the prefix option from the git-svn main program if it's loaded.
2268 my $prefix = defined &::opt_prefix ? ::opt_prefix() : "";
2269 $_[2] = $ref_id =
2270 "refs/remotes/$prefix$default_ref_id";
2272 $_[1] = $repo_id;
2273 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2275 # Older repos imported by us used $GIT_DIR/svn/foo instead of
2276 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
2277 if ($ref_id =~ m{^refs/remotes/(.*)}) {
2278 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
2279 if (-d $old_dir && ! -d $dir) {
2280 $dir = $old_dir;
2284 $_[3] = $path = '' unless (defined $path);
2285 mkpath([$dir]);
2286 my $obj = bless {
2287 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2288 config => "$ENV{GIT_DIR}/svn/config",
2289 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2291 # Ensure it gets canonicalized
2292 $obj->path($path);
2294 return $obj;
2297 sub path {
2298 my $self = shift;
2300 if (@_) {
2301 my $path = shift;
2302 $self->{path} = $path;
2303 return;
2306 return $self->{path};
2309 # for read-only access of old .rev_db formats
2310 sub unlink_rev_db_symlink {
2311 my ($self) = @_;
2312 my $link = $self->rev_db_path;
2313 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2314 if (-l $link) {
2315 unlink $link or croak "unlink: $link failed!";
2319 sub rev_db_path {
2320 my ($self, $uuid) = @_;
2321 my $db_path = $self->map_path($uuid);
2322 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2323 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2324 $db_path;
2327 # the new replacement for .rev_db
2328 sub map_path {
2329 my ($self, $uuid) = @_;
2330 $uuid ||= $self->ra_uuid;
2331 "$self->{map_root}.$uuid";
2334 sub uri_encode {
2335 my ($f) = @_;
2336 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2340 sub uri_decode {
2341 my ($f) = @_;
2342 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
2346 sub remove_username {
2347 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};