git-svn: lazy load some modules
[git] / perl / Git / SVN.pm
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 IPC::Open3;
13 use Memoize;  # core since 5.8.0, Jul 2002
14 use POSIX qw(:signal_h);
15
16 use Git qw(
17     command
18     command_oneline
19     command_noisy
20     command_output_pipe
21     command_close_pipe
22     get_tz_offset
23 );
24 use Git::SVN::Utils qw(
25         fatal
26         can_compress
27         join_paths
28         canonicalize_path
29         canonicalize_url
30         add_path_to_url
31 );
32
33 my $memo_backend;
34 our $_follow_parent  = 1;
35 our $_minimize_url   = 'unset';
36 our $default_repo_id = 'svn';
37 our $default_ref_id  = $ENV{GIT_SVN_ID} || 'git-svn';
38
39 my ($_gc_nr, $_gc_period);
40
41 # properties that we do not log:
42 my %SKIP_PROP;
43 BEGIN {
44         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
45                                         svn:special svn:executable
46                                         svn:entry:committed-rev
47                                         svn:entry:last-author
48                                         svn:entry:uuid
49                                         svn:entry:committed-date/;
50
51         # some options are read globally, but can be overridden locally
52         # per [svn-remote "..."] section.  Command-line options will *NOT*
53         # override options set in an [svn-remote "..."] section
54         no strict 'refs';
55         for my $option (qw/follow_parent no_metadata use_svm_props
56                            use_svnsync_props/) {
57                 my $key = $option;
58                 $key =~ tr/_//d;
59                 my $prop = "-$option";
60                 *$option = sub {
61                         my ($self) = @_;
62                         return $self->{$prop} if exists $self->{$prop};
63                         my $k = "svn-remote.$self->{repo_id}.$key";
64                         eval { command_oneline(qw/config --get/, $k) };
65                         if ($@) {
66                                 $self->{$prop} = ${"Git::SVN::_$option"};
67                         } else {
68                                 my $v = command_oneline(qw/config --bool/,$k);
69                                 $self->{$prop} = $v eq 'false' ? 0 : 1;
70                         }
71                         return $self->{$prop};
72                 }
73         }
74 }
75
76
77 my (%LOCKFILES, %INDEX_FILES);
78 END {
79         unlink keys %LOCKFILES if %LOCKFILES;
80         unlink keys %INDEX_FILES if %INDEX_FILES;
81 }
82
83 sub resolve_local_globs {
84         my ($url, $fetch, $glob_spec) = @_;
85         return unless defined $glob_spec;
86         my $ref = $glob_spec->{ref};
87         my $path = $glob_spec->{path};
88         foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
89                 next unless m#^$ref->{regex}$#;
90                 my $p = $1;
91                 my $pathname = desanitize_refname($path->full_path($p));
92                 my $refname = desanitize_refname($ref->full_path($p));
93                 if (my $existing = $fetch->{$pathname}) {
94                         if ($existing ne $refname) {
95                                 die "Refspec conflict:\n",
96                                     "existing: $existing\n",
97                                     " globbed: $refname\n";
98                         }
99                         my $u = (::cmt_metadata("$refname"))[0];
100                         $u =~ s!^\Q$url\E(/|$)!! or die
101                           "$refname: '$url' not found in '$u'\n";
102                         if ($pathname ne $u) {
103                                 warn "W: Refspec glob conflict ",
104                                      "(ref: $refname):\n",
105                                      "expected path: $pathname\n",
106                                      "    real path: $u\n",
107                                      "Continuing ahead with $u\n";
108                                 next;
109                         }
110                 } else {
111                         $fetch->{$pathname} = $refname;
112                 }
113         }
114 }
115
116 sub parse_revision_argument {
117         my ($base, $head) = @_;
118         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
119                 return ($base, $head);
120         }
121         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
122         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
123         return ($head, $head) if ($::_revision eq 'HEAD');
124         return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
125         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
126         die "revision argument: $::_revision not understood by git-svn\n";
127 }
128
129 sub fetch_all {
130         my ($repo_id, $remotes) = @_;
131         if (ref $repo_id) {
132                 my $gs = $repo_id;
133                 $repo_id = undef;
134                 $repo_id = $gs->{repo_id};
135         }
136         $remotes ||= read_all_remotes();
137         my $remote = $remotes->{$repo_id} or
138                      die "[svn-remote \"$repo_id\"] unknown\n";
139         my $fetch = $remote->{fetch};
140         my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
141         my (@gs, @globs);
142         my $ra = Git::SVN::Ra->new($url);
143         my $uuid = $ra->get_uuid;
144         my $head = $ra->get_latest_revnum;
145
146         # ignore errors, $head revision may not even exist anymore
147         eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
148         warn "W: $@\n" if $@;
149
150         my $base = defined $fetch ? $head : 0;
151
152         # read the max revs for wildcard expansion (branches/*, tags/*)
153         foreach my $t (qw/branches tags/) {
154                 defined $remote->{$t} or next;
155                 push @globs, @{$remote->{$t}};
156
157                 my $max_rev = eval { tmp_config(qw/--int --get/,
158                                          "svn-remote.$repo_id.${t}-maxRev") };
159                 if (defined $max_rev && ($max_rev < $base)) {
160                         $base = $max_rev;
161                 } elsif (!defined $max_rev) {
162                         $base = 0;
163                 }
164         }
165
166         if ($fetch) {
167                 foreach my $p (sort keys %$fetch) {
168                         my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
169                         my $lr = $gs->rev_map_max;
170                         if (defined $lr) {
171                                 $base = $lr if ($lr < $base);
172                         }
173                         push @gs, $gs;
174                 }
175         }
176
177         ($base, $head) = parse_revision_argument($base, $head);
178         $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
179 }
180
181 sub read_all_remotes {
182         my $r = {};
183         my $use_svm_props = eval { command_oneline(qw/config --bool
184             svn.useSvmProps/) };
185         $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
186         my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
187         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
188                 if (m!^(.+)\.fetch=$svn_refspec$!) {
189                         my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
190                         die("svn-remote.$remote: remote ref '$remote_ref' "
191                             . "must start with 'refs/'\n")
192                                 unless $remote_ref =~ m{^refs/};
193                         $local_ref = uri_decode($local_ref);
194                         $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
195                         $r->{$remote}->{svm} = {} if $use_svm_props;
196                 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
197                         $r->{$1}->{svm} = {};
198                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
199                         $r->{$1}->{url} = canonicalize_url($2);
200                 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
201                         $r->{$1}->{pushurl} = canonicalize_url($2);
202                 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
203                         $r->{$1}->{ignore_refs_regex} = $2;
204                 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
205                         my ($remote, $t, $local_ref, $remote_ref) =
206                                                              ($1, $2, $3, $4);
207                         die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
208                             . "must start with 'refs/'\n")
209                                 unless $remote_ref =~ m{^refs/};
210                         $local_ref = uri_decode($local_ref);
211
212                         require Git::SVN::GlobSpec;
213                         my $rs = {
214                             t => $t,
215                             remote => $remote,
216                             path => Git::SVN::GlobSpec->new($local_ref, 1),
217                             ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
218                         if (length($rs->{ref}->{right}) != 0) {
219                                 die "The '*' glob character must be the last ",
220                                     "character of '$remote_ref'\n";
221                         }
222                         push @{ $r->{$remote}->{$t} }, $rs;
223                 }
224         }
225
226         map {
227                 if (defined $r->{$_}->{svm}) {
228                         my $svm;
229                         eval {
230                                 my $section = "svn-remote.$_";
231                                 $svm = {
232                                         source => tmp_config('--get',
233                                             "$section.svm-source"),
234                                         replace => tmp_config('--get',
235                                             "$section.svm-replace"),
236                                 }
237                         };
238                         $r->{$_}->{svm} = $svm;
239                 }
240         } keys %$r;
241
242         foreach my $remote (keys %$r) {
243                 foreach ( grep { defined $_ }
244                           map { $r->{$remote}->{$_} } qw(branches tags) ) {
245                         foreach my $rs ( @$_ ) {
246                                 $rs->{ignore_refs_regex} =
247                                     $r->{$remote}->{ignore_refs_regex};
248                         }
249                 }
250         }
251
252         $r;
253 }
254
255 sub init_vars {
256         $_gc_nr = $_gc_period = 1000;
257         if (defined $_repack || defined $_repack_flags) {
258                warn "Repack options are obsolete; they have no effect.\n";
259         }
260 }
261
262 sub verify_remotes_sanity {
263         return unless -d $ENV{GIT_DIR};
264         my %seen;
265         foreach (command(qw/config -l/)) {
266                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
267                         if ($seen{$1}) {
268                                 die "Remote ref refs/remote/$1 is tracked by",
269                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
270                                     "Please resolve this ambiguity in ",
271                                     "your git configuration file before ",
272                                     "continuing\n";
273                         }
274                         $seen{$1} = $_;
275                 }
276         }
277 }
278
279 sub find_existing_remote {
280         my ($url, $remotes) = @_;
281         return undef if $no_reuse_existing;
282         my $existing;
283         foreach my $repo_id (keys %$remotes) {
284                 my $u = $remotes->{$repo_id}->{url} or next;
285                 next if $u ne $url;
286                 $existing = $repo_id;
287                 last;
288         }
289         $existing;
290 }
291
292 sub init_remote_config {
293         my ($self, $url, $no_write) = @_;
294         $url = canonicalize_url($url);
295         my $r = read_all_remotes();
296         my $existing = find_existing_remote($url, $r);
297         if ($existing) {
298                 unless ($no_write) {
299                         print STDERR "Using existing ",
300                                      "[svn-remote \"$existing\"]\n";
301                 }
302                 $self->{repo_id} = $existing;
303         } elsif ($_minimize_url) {
304                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
305                 $existing = find_existing_remote($min_url, $r);
306                 if ($existing) {
307                         unless ($no_write) {
308                                 print STDERR "Using existing ",
309                                              "[svn-remote \"$existing\"]\n";
310                         }
311                         $self->{repo_id} = $existing;
312                 }
313                 if ($min_url ne $url) {
314                         unless ($no_write) {
315                                 print STDERR "Using higher level of URL: ",
316                                              "$url => $min_url\n";
317                         }
318                         my $old_path = $self->path;
319                         $url =~ s!^\Q$min_url\E(/|$)!!;
320                         $url = join_paths($url, $old_path);
321                         $self->path($url);
322                         $url = $min_url;
323                 }
324         }
325         my $orig_url;
326         if (!$existing) {
327                 # verify that we aren't overwriting anything:
328                 $orig_url = eval {
329                         command_oneline('config', '--get',
330                                         "svn-remote.$self->{repo_id}.url")
331                 };
332                 if ($orig_url && ($orig_url ne $url)) {
333                         die "svn-remote.$self->{repo_id}.url already set: ",
334                             "$orig_url\nwanted to set to: $url\n";
335                 }
336         }
337         my ($xrepo_id, $xpath) = find_ref($self->refname);
338         if (!$no_write && defined $xpath) {
339                 die "svn-remote.$xrepo_id.fetch already set to track ",
340                     "$xpath:", $self->refname, "\n";
341         }
342         unless ($no_write) {
343                 command_noisy('config',
344                               "svn-remote.$self->{repo_id}.url", $url);
345                 my $path = $self->path;
346                 $path =~ s{^/}{};
347                 $path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
348                 $self->path($path);
349                 command_noisy('config', '--add',
350                               "svn-remote.$self->{repo_id}.fetch",
351                               $self->path.":".$self->refname);
352         }
353         $self->url($url);
354 }
355
356 sub find_by_url { # repos_root and, path are optional
357         my ($class, $full_url, $repos_root, $path) = @_;
358
359         $full_url = canonicalize_url($full_url);
360
361         return undef unless defined $full_url;
362         remove_username($full_url);
363         remove_username($repos_root) if defined $repos_root;
364         my $remotes = read_all_remotes();
365         if (defined $full_url && defined $repos_root && !defined $path) {
366                 $path = $full_url;
367                 $path =~ s#^\Q$repos_root\E(?:/|$)##;
368         }
369         foreach my $repo_id (keys %$remotes) {
370                 my $u = $remotes->{$repo_id}->{url} or next;
371                 remove_username($u);
372                 next if defined $repos_root && $repos_root ne $u;
373
374                 my $fetch = $remotes->{$repo_id}->{fetch} || {};
375                 foreach my $t (qw/branches tags/) {
376                         foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
377                                 resolve_local_globs($u, $fetch, $globspec);
378                         }
379                 }
380                 my $p = $path;
381                 my $rwr = rewrite_root({repo_id => $repo_id});
382                 my $svm = $remotes->{$repo_id}->{svm}
383                         if defined $remotes->{$repo_id}->{svm};
384                 unless (defined $p) {
385                         $p = $full_url;
386                         my $z = $u;
387                         my $prefix = '';
388                         if ($rwr) {
389                                 $z = $rwr;
390                                 remove_username($z);
391                         } elsif (defined $svm) {
392                                 $z = $svm->{source};
393                                 $prefix = $svm->{replace};
394                                 $prefix =~ s#^\Q$u\E(?:/|$)##;
395                                 $prefix =~ s#/$##;
396                         }
397                         $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
398                 }
399
400                 # remote fetch paths are not URI escaped.  Decode ours
401                 # so they match
402                 $p = uri_decode($p);
403
404                 foreach my $f (keys %$fetch) {
405                         next if $f ne $p;
406                         return Git::SVN->new($fetch->{$f}, $repo_id, $f);
407                 }
408         }
409         undef;
410 }
411
412 sub init {
413         my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
414         my $self = _new($class, $repo_id, $ref_id, $path);
415         if (defined $url) {
416                 $self->init_remote_config($url, $no_write);
417         }
418         $self;
419 }
420
421 sub find_ref {
422         my ($ref_id) = @_;
423         foreach (command(qw/config -l/)) {
424                 next unless m!^svn-remote\.(.+)\.fetch=
425                               \s*(.*?)\s*:\s*(.+?)\s*$!x;
426                 my ($repo_id, $path, $ref) = ($1, $2, $3);
427                 if ($ref eq $ref_id) {
428                         $path = '' if ($path =~ m#^\./?#);
429                         return ($repo_id, $path);
430                 }
431         }
432         (undef, undef, undef);
433 }
434
435 sub new {
436         my ($class, $ref_id, $repo_id, $path) = @_;
437         if (defined $ref_id && !defined $repo_id && !defined $path) {
438                 ($repo_id, $path) = find_ref($ref_id);
439                 if (!defined $repo_id) {
440                         die "Could not find a \"svn-remote.*.fetch\" key ",
441                             "in the repository configuration matching: ",
442                             "$ref_id\n";
443                 }
444         }
445         my $self = _new($class, $repo_id, $ref_id, $path);
446         if (!defined $self->path || !length $self->path) {
447                 my $fetch = command_oneline('config', '--get',
448                                             "svn-remote.$repo_id.fetch",
449                                             ":$ref_id\$") or
450                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
451                          "\":$ref_id\$\" in config\n";
452                 my($path) = split(/\s*:\s*/, $fetch);
453                 $self->path($path);
454         }
455         {
456                 my $path = $self->path;
457                 $path =~ s{\A/}{};
458                 $path =~ s{/\z}{};
459                 $self->path($path);
460         }
461         my $url = command_oneline('config', '--get',
462                                   "svn-remote.$repo_id.url") or
463                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
464         $self->url($url);
465         $self->{pushurl} = eval { command_oneline('config', '--get',
466                                   "svn-remote.$repo_id.pushurl") };
467         $self->rebuild;
468         $self;
469 }
470
471 sub refname {
472         my ($refname) = $_[0]->{ref_id} ;
473
474         # It cannot end with a slash /, we'll throw up on this because
475         # SVN can't have directories with a slash in their name, either:
476         if ($refname =~ m{/$}) {
477                 die "ref: '$refname' ends with a trailing slash; this is ",
478                     "not permitted by git or Subversion\n";
479         }
480
481         # It cannot have ASCII control character space, tilde ~, caret ^,
482         # colon :, question-mark ?, asterisk *, space, or open bracket [
483         # anywhere.
484         #
485         # Additionally, % must be escaped because it is used for escaping
486         # and we want our escaped refname to be reversible
487         $refname =~ s{([ \%~\^:\?\*\[\t])}{sprintf('%%%02X',ord($1))}eg;
488
489         # no slash-separated component can begin with a dot .
490         # /.* becomes /%2E*
491         $refname =~ s{/\.}{/%2E}g;
492
493         # It cannot have two consecutive dots .. anywhere
494         # .. becomes %2E%2E
495         $refname =~ s{\.\.}{%2E%2E}g;
496
497         # trailing dots and .lock are not allowed
498         # .$ becomes %2E and .lock becomes %2Elock
499         $refname =~ s{\.(?=$|lock$)}{%2E};
500
501         # the sequence @{ is used to access the reflog
502         # @{ becomes %40{
503         $refname =~ s{\@\{}{%40\{}g;
504
505         return $refname;
506 }
507
508 sub desanitize_refname {
509         my ($refname) = @_;
510         $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
511         return $refname;
512 }
513
514 sub svm_uuid {
515         my ($self) = @_;
516         return $self->{svm}->{uuid} if $self->svm;
517         $self->ra;
518         unless ($self->{svm}) {
519                 die "SVM UUID not cached, and reading remotely failed\n";
520         }
521         $self->{svm}->{uuid};
522 }
523
524 sub svm {
525         my ($self) = @_;
526         return $self->{svm} if $self->{svm};
527         my $svm;
528         # see if we have it in our config, first:
529         eval {
530                 my $section = "svn-remote.$self->{repo_id}";
531                 $svm = {
532                   source => tmp_config('--get', "$section.svm-source"),
533                   uuid => tmp_config('--get', "$section.svm-uuid"),
534                   replace => tmp_config('--get', "$section.svm-replace"),
535                 }
536         };
537         if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
538                 $self->{svm} = $svm;
539         }
540         $self->{svm};
541 }
542
543 sub _set_svm_vars {
544         my ($self, $ra) = @_;
545         return $ra if $self->svm;
546
547         my @err = ( "useSvmProps set, but failed to read SVM properties\n",
548                     "(svm:source, svm:uuid) ",
549                     "from the following URLs:\n" );
550         sub read_svm_props {
551                 my ($self, $ra, $path, $r) = @_;
552                 my $props = ($ra->get_dir($path, $r))[2];
553                 my $src = $props->{'svm:source'};
554                 my $uuid = $props->{'svm:uuid'};
555                 return undef if (!$src || !$uuid);
556
557                 chomp($src, $uuid);
558
559                 $uuid =~ m{^[0-9a-f\-]{30,}$}i
560                     or die "doesn't look right - svm:uuid is '$uuid'\n";
561
562                 # the '!' is used to mark the repos_root!/relative/path
563                 $src =~ s{/?!/?}{/};
564                 $src =~ s{/+$}{}; # no trailing slashes please
565                 # username is of no interest
566                 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
567
568                 my $replace = add_path_to_url($ra->url, $path);
569
570                 my $section = "svn-remote.$self->{repo_id}";
571                 tmp_config("$section.svm-source", $src);
572                 tmp_config("$section.svm-replace", $replace);
573                 tmp_config("$section.svm-uuid", $uuid);
574                 $self->{svm} = {
575                         source => $src,
576                         uuid => $uuid,
577                         replace => $replace
578                 };
579         }
580
581         my $r = $ra->get_latest_revnum;
582         my $path = $self->path;
583         my %tried;
584         while (length $path) {
585                 my $try = add_path_to_url($self->url, $path);
586                 unless ($tried{$try}) {
587                         return $ra if $self->read_svm_props($ra, $path, $r);
588                         $tried{$try} = 1;
589                 }
590                 $path =~ s#/?[^/]+$##;
591         }
592         die "Path: '$path' should be ''\n" if $path ne '';
593         return $ra if $self->read_svm_props($ra, $path, $r);
594         $tried{ add_path_to_url($self->url, $path) } = 1;
595
596         if ($ra->{repos_root} eq $self->url) {
597                 die @err, (map { "  $_\n" } keys %tried), "\n";
598         }
599
600         # nope, make sure we're connected to the repository root:
601         my $ok;
602         my @tried_b;
603         $path = $ra->{svn_path};
604         $ra = Git::SVN::Ra->new($ra->{repos_root});
605         while (length $path) {
606                 my $try = add_path_to_url($ra->url, $path);
607                 unless ($tried{$try}) {
608                         $ok = $self->read_svm_props($ra, $path, $r);
609                         last if $ok;
610                         $tried{$try} = 1;
611                 }
612                 $path =~ s#/?[^/]+$##;
613         }
614         die "Path: '$path' should be ''\n" if $path ne '';
615         $ok ||= $self->read_svm_props($ra, $path, $r);
616         $tried{ add_path_to_url($ra->url, $path) } = 1;
617         if (!$ok) {
618                 die @err, (map { "  $_\n" } keys %tried), "\n";
619         }
620         Git::SVN::Ra->new($self->url);
621 }
622
623 sub svnsync {
624         my ($self) = @_;
625         return $self->{svnsync} if $self->{svnsync};
626
627         if ($self->no_metadata) {
628                 die "Can't have both 'noMetadata' and ",
629                     "'useSvnsyncProps' options set!\n";
630         }
631         if ($self->rewrite_root) {
632                 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
633                     "options set!\n";
634         }
635         if ($self->rewrite_uuid) {
636                 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
637                     "options set!\n";
638         }
639
640         my $svnsync;
641         # see if we have it in our config, first:
642         eval {
643                 my $section = "svn-remote.$self->{repo_id}";
644
645                 my $url = tmp_config('--get', "$section.svnsync-url");
646                 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
647                    die "doesn't look right - svn:sync-from-url is '$url'\n";
648
649                 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
650                 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
651                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
652
653                 $svnsync = { url => $url, uuid => $uuid }
654         };
655         if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
656                 return $self->{svnsync} = $svnsync;
657         }
658
659         my $err = "useSvnsyncProps set, but failed to read " .
660                   "svnsync property: svn:sync-from-";
661         my $rp = $self->ra->rev_proplist(0);
662
663         my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
664         ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
665                    die "doesn't look right - svn:sync-from-url is '$url'\n";
666
667         my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
668         ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
669                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
670
671         my $section = "svn-remote.$self->{repo_id}";
672         tmp_config('--add', "$section.svnsync-uuid", $uuid);
673         tmp_config('--add', "$section.svnsync-url", $url);
674         return $self->{svnsync} = { url => $url, uuid => $uuid };
675 }
676
677 # this allows us to memoize our SVN::Ra UUID locally and avoid a
678 # remote lookup (useful for 'git svn log').
679 sub ra_uuid {
680         my ($self) = @_;
681         unless ($self->{ra_uuid}) {
682                 my $key = "svn-remote.$self->{repo_id}.uuid";
683                 my $uuid = eval { tmp_config('--get', $key) };
684                 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
685                         $self->{ra_uuid} = $uuid;
686                 } else {
687                         die "ra_uuid called without URL\n" unless $self->url;
688                         $self->{ra_uuid} = $self->ra->get_uuid;
689                         tmp_config('--add', $key, $self->{ra_uuid});
690                 }
691         }
692         $self->{ra_uuid};
693 }
694
695 sub _set_repos_root {
696         my ($self, $repos_root) = @_;
697         my $k = "svn-remote.$self->{repo_id}.reposRoot";
698         $repos_root ||= $self->ra->{repos_root};
699         tmp_config($k, $repos_root);
700         $repos_root;
701 }
702
703 sub repos_root {
704         my ($self) = @_;
705         my $k = "svn-remote.$self->{repo_id}.reposRoot";
706         eval { tmp_config('--get', $k) } || $self->_set_repos_root;
707 }
708
709 sub ra {
710         my ($self) = shift;
711         my $ra = Git::SVN::Ra->new($self->url);
712         $self->_set_repos_root($ra->{repos_root});
713         if ($self->use_svm_props && !$self->{svm}) {
714                 if ($self->no_metadata) {
715                         die "Can't have both 'noMetadata' and ",
716                             "'useSvmProps' options set!\n";
717                 } elsif ($self->use_svnsync_props) {
718                         die "Can't have both 'useSvnsyncProps' and ",
719                             "'useSvmProps' options set!\n";
720                 }
721                 $ra = $self->_set_svm_vars($ra);
722                 $self->{-want_revprops} = 1;
723         }
724         $ra;
725 }
726
727 # prop_walk(PATH, REV, SUB)
728 # -------------------------
729 # Recursively traverse PATH at revision REV and invoke SUB for each
730 # directory that contains a SVN property.  SUB will be invoked as
731 # follows:  &SUB(gs, path, props);  where `gs' is this instance of
732 # Git::SVN, `path' the path to the directory where the properties
733 # `props' were found.  The `path' will be relative to point of checkout,
734 # that is, if url://repo/trunk is the current Git branch, and that
735 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
736 # as `path' (note the trailing `/').
737 sub prop_walk {
738         my ($self, $path, $rev, $sub) = @_;
739
740         $path =~ s#^/##;
741         my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
742         $path =~ s#^/*#/#g;
743         my $p = $path;
744         # Strip the irrelevant part of the path.
745         $p =~ s#^/+\Q@{[$self->path]}\E(/|$)#/#;
746         # Ensure the path is terminated by a `/'.
747         $p =~ s#/*$#/#;
748
749         # The properties contain all the internal SVN stuff nobody
750         # (usually) cares about.
751         my $interesting_props = 0;
752         foreach (keys %{$props}) {
753                 # If it doesn't start with `svn:', it must be a
754                 # user-defined property.
755                 ++$interesting_props and next if $_ !~ /^svn:/;
756                 # FIXME: Fragile, if SVN adds new public properties,
757                 # this needs to be updated.
758                 ++$interesting_props if /^svn:(?:ignore|keywords|executable
759                                                  |eol-style|mime-type
760                                                  |externals|needs-lock)$/x;
761         }
762         &$sub($self, $p, $props) if $interesting_props;
763
764         foreach (sort keys %$dirent) {
765                 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
766                 $self->prop_walk($self->path . $p . $_, $rev, $sub);
767         }
768 }
769
770 sub last_rev { ($_[0]->last_rev_commit)[0] }
771 sub last_commit { ($_[0]->last_rev_commit)[1] }
772
773 # returns the newest SVN revision number and newest commit SHA1
774 sub last_rev_commit {
775         my ($self) = @_;
776         if (defined $self->{last_rev} && defined $self->{last_commit}) {
777                 return ($self->{last_rev}, $self->{last_commit});
778         }
779         my $c = ::verify_ref($self->refname.'^0');
780         if ($c && !$self->use_svm_props && !$self->no_metadata) {
781                 my $rev = (::cmt_metadata($c))[1];
782                 if (defined $rev) {
783                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
784                         return ($rev, $c);
785                 }
786         }
787         my $map_path = $self->map_path;
788         unless (-e $map_path) {
789                 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
790                 return (undef, undef);
791         }
792         my ($rev, $commit) = $self->rev_map_max(1);
793         ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
794         return ($rev, $commit);
795 }
796
797 sub get_fetch_range {
798         my ($self, $min, $max) = @_;
799         $max ||= $self->ra->get_latest_revnum;
800         $min ||= $self->rev_map_max;
801         (++$min, $max);
802 }
803
804 sub tmp_config {
805         my (@args) = @_;
806         my $old_def_config = "$ENV{GIT_DIR}/svn/config";
807         my $config = "$ENV{GIT_DIR}/svn/.metadata";
808         if (! -f $config && -f $old_def_config) {
809                 rename $old_def_config, $config or
810                        die "Failed rename $old_def_config => $config: $!\n";
811         }
812         my $old_config = $ENV{GIT_CONFIG};
813         $ENV{GIT_CONFIG} = $config;
814         $@ = undef;
815         my @ret = eval {
816                 unless (-f $config) {
817                         mkfile($config);
818                         open my $fh, '>', $config or
819                             die "Can't open $config: $!\n";
820                         print $fh "; This file is used internally by ",
821                                   "git-svn\n" or die
822                                   "Couldn't write to $config: $!\n";
823                         print $fh "; You should not have to edit it\n" or
824                               die "Couldn't write to $config: $!\n";
825                         close $fh or die "Couldn't close $config: $!\n";
826                 }
827                 command('config', @args);
828         };
829         my $err = $@;
830         if (defined $old_config) {
831                 $ENV{GIT_CONFIG} = $old_config;
832         } else {
833                 delete $ENV{GIT_CONFIG};
834         }
835         die $err if $err;
836         wantarray ? @ret : $ret[0];
837 }
838
839 sub tmp_index_do {
840         my ($self, $sub) = @_;
841         my $old_index = $ENV{GIT_INDEX_FILE};
842         $ENV{GIT_INDEX_FILE} = $self->{index};
843         $@ = undef;
844         my @ret = eval {
845                 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
846                 mkpath([$dir]) unless -d $dir;
847                 &$sub;
848         };
849         my $err = $@;
850         if (defined $old_index) {
851                 $ENV{GIT_INDEX_FILE} = $old_index;
852         } else {
853                 delete $ENV{GIT_INDEX_FILE};
854         }
855         die $err if $err;
856         wantarray ? @ret : $ret[0];
857 }
858
859 sub assert_index_clean {
860         my ($self, $treeish) = @_;
861
862         $self->tmp_index_do(sub {
863                 command_noisy('read-tree', $treeish) unless -e $self->{index};
864                 my $x = command_oneline('write-tree');
865                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
866                            /^tree ($::sha1)/mo);
867                 return if $y eq $x;
868
869                 warn "Index mismatch: $y != $x\nrereading $treeish\n";
870                 unlink $self->{index} or die "unlink $self->{index}: $!\n";
871                 command_noisy('read-tree', $treeish);
872                 $x = command_oneline('write-tree');
873                 if ($y ne $x) {
874                         fatal "trees ($treeish) $y != $x\n",
875                               "Something is seriously wrong...";
876                 }
877         });
878 }
879
880 sub get_commit_parents {
881         my ($self, $log_entry) = @_;
882         my (%seen, @ret, @tmp);
883         # legacy support for 'set-tree'; this is only used by set_tree_cb:
884         if (my $ip = $self->{inject_parents}) {
885                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
886                         push @tmp, $commit;
887                 }
888         }
889         if (my $cur = ::verify_ref($self->refname.'^0')) {
890                 push @tmp, $cur;
891         }
892         if (my $ipd = $self->{inject_parents_dcommit}) {
893                 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
894                         push @tmp, @$commit;
895                 }
896         }
897         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
898         while (my $p = shift @tmp) {
899                 next if $seen{$p};
900                 $seen{$p} = 1;
901                 push @ret, $p;
902         }
903         @ret;
904 }
905
906 sub rewrite_root {
907         my ($self) = @_;
908         return $self->{-rewrite_root} if exists $self->{-rewrite_root};
909         my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
910         my $rwr = eval { command_oneline(qw/config --get/, $k) };
911         if ($rwr) {
912                 $rwr =~ s#/+$##;
913                 if ($rwr !~ m#^[a-z\+]+://#) {
914                         die "$rwr is not a valid URL (key: $k)\n";
915                 }
916         }
917         $self->{-rewrite_root} = $rwr;
918 }
919
920 sub rewrite_uuid {
921         my ($self) = @_;
922         return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
923         my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
924         my $rwid = eval { command_oneline(qw/config --get/, $k) };
925         if ($rwid) {
926                 $rwid =~ s#/+$##;
927                 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
928                         die "$rwid is not a valid UUID (key: $k)\n";
929                 }
930         }
931         $self->{-rewrite_uuid} = $rwid;
932 }
933
934 sub metadata_url {
935         my ($self) = @_;
936         my $url = $self->rewrite_root || $self->url;
937         return canonicalize_url( add_path_to_url( $url, $self->path ) );
938 }
939
940 sub full_url {
941         my ($self) = @_;
942         return canonicalize_url( add_path_to_url( $self->url, $self->path ) );
943 }
944
945 sub full_pushurl {
946         my ($self) = @_;
947         if ($self->{pushurl}) {
948                 return canonicalize_url( add_path_to_url( $self->{pushurl}, $self->path ) );
949         } else {
950                 return $self->full_url;
951         }
952 }
953
954 sub set_commit_header_env {
955         my ($log_entry) = @_;
956         my %env;
957         foreach my $ned (qw/NAME EMAIL DATE/) {
958                 foreach my $ac (qw/AUTHOR COMMITTER/) {
959                         $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
960                 }
961         }
962
963         $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
964         $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
965         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
966
967         $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
968                                                 ? $log_entry->{commit_name}
969                                                 : $log_entry->{name};
970         $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
971                                                 ? $log_entry->{commit_email}
972                                                 : $log_entry->{email};
973         \%env;
974 }
975
976 sub restore_commit_header_env {
977         my ($env) = @_;
978         foreach my $ned (qw/NAME EMAIL DATE/) {
979                 foreach my $ac (qw/AUTHOR COMMITTER/) {
980                         my $k = "GIT_${ac}_${ned}";
981                         if (defined $env->{$k}) {
982                                 $ENV{$k} = $env->{$k};
983                         } else {
984                                 delete $ENV{$k};
985                         }
986                 }
987         }
988 }
989
990 sub gc {
991         command_noisy('gc', '--auto');
992 };
993
994 sub do_git_commit {
995         my ($self, $log_entry) = @_;
996         my $lr = $self->last_rev;
997         if (defined $lr && $lr >= $log_entry->{revision}) {
998                 die "Last fetched revision of ", $self->refname,
999                     " was r$lr, but we are about to fetch: ",
1000                     "r$log_entry->{revision}!\n";
1001         }
1002         if (my $c = $self->rev_map_get($log_entry->{revision})) {
1003                 croak "$log_entry->{revision} = $c already exists! ",
1004                       "Why are we refetching it?\n";
1005         }
1006         my $old_env = set_commit_header_env($log_entry);
1007         my $tree = $log_entry->{tree};
1008         if (!defined $tree) {
1009                 $tree = $self->tmp_index_do(sub {
1010                                             command_oneline('write-tree') });
1011         }
1012         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1013
1014         my @exec = ('git', 'commit-tree', $tree);
1015         foreach ($self->get_commit_parents($log_entry)) {
1016                 push @exec, '-p', $_;
1017         }
1018         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1019                                                                    or croak $!;
1020         binmode $msg_fh;
1021
1022         # we always get UTF-8 from SVN, but we may want our commits in
1023         # a different encoding.
1024         if (my $enc = Git::config('i18n.commitencoding')) {
1025                 require Encode;
1026                 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
1027         }
1028         print $msg_fh $log_entry->{log} or croak $!;
1029         restore_commit_header_env($old_env);
1030         unless ($self->no_metadata) {
1031                 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1032                               or croak $!;
1033         }
1034         $msg_fh->flush == 0 or croak $!;
1035         close $msg_fh or croak $!;
1036         chomp(my $commit = do { local $/; <$out_fh> });
1037         close $out_fh or croak $!;
1038         waitpid $pid, 0;
1039         croak $? if $?;
1040         if ($commit !~ /^$::sha1$/o) {
1041                 die "Failed to commit, invalid sha1: $commit\n";
1042         }
1043
1044         $self->rev_map_set($log_entry->{revision}, $commit, 1);
1045
1046         $self->{last_rev} = $log_entry->{revision};
1047         $self->{last_commit} = $commit;
1048         print "r$log_entry->{revision}" unless $::_q > 1;
1049         if (defined $log_entry->{svm_revision}) {
1050                  print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
1051                  $self->rev_map_set($log_entry->{svm_revision}, $commit,
1052                                    0, $self->svm_uuid);
1053         }
1054         print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
1055         if (--$_gc_nr == 0) {
1056                 $_gc_nr = $_gc_period;
1057                 gc();
1058         }
1059         return $commit;
1060 }
1061
1062 sub match_paths {
1063         my ($self, $paths, $r) = @_;
1064         return 1 if $self->path eq '';
1065         if (my $path = $paths->{"/".$self->path}) {
1066                 return ($path->{action} eq 'D') ? 0 : 1;
1067         }
1068         $self->{path_regex} ||= qr{^/\Q@{[$self->path]}\E/};
1069         if (grep /$self->{path_regex}/, keys %$paths) {
1070                 return 1;
1071         }
1072         my $c = '';
1073         foreach (split m#/#, $self->path) {
1074                 $c .= "/$_";
1075                 next unless ($paths->{$c} &&
1076                              ($paths->{$c}->{action} =~ /^[AR]$/));
1077                 if ($self->ra->check_path($self->path, $r) ==
1078                     $SVN::Node::dir) {
1079                         return 1;
1080                 }
1081         }
1082         return 0;
1083 }
1084
1085 sub find_parent_branch {
1086         my ($self, $paths, $rev) = @_;
1087         return undef unless $self->follow_parent;
1088         unless (defined $paths) {
1089                 my $err_handler = $SVN::Error::handler;
1090                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1091                 $self->ra->get_log([$self->path], $rev, $rev, 0, 1, 1,
1092                                    sub { $paths = $_[0] });
1093                 $SVN::Error::handler = $err_handler;
1094         }
1095         return undef unless defined $paths;
1096
1097         # look for a parent from another branch:
1098         my @b_path_components = split m#/#, $self->path;
1099         my @a_path_components;
1100         my $i;
1101         while (@b_path_components) {
1102                 $i = $paths->{'/'.join('/', @b_path_components)};
1103                 last if $i && defined $i->{copyfrom_path};
1104                 unshift(@a_path_components, pop(@b_path_components));
1105         }
1106         return undef unless defined $i && defined $i->{copyfrom_path};
1107         my $branch_from = $i->{copyfrom_path};
1108         if (@a_path_components) {
1109                 print STDERR "branch_from: $branch_from => ";
1110                 $branch_from .= '/'.join('/', @a_path_components);
1111                 print STDERR $branch_from, "\n";
1112         }
1113         my $r = $i->{copyfrom_rev};
1114         my $repos_root = $self->ra->{repos_root};
1115         my $url = $self->ra->url;
1116         my $new_url = canonicalize_url( add_path_to_url( $url, $branch_from ) );
1117         print STDERR  "Found possible branch point: ",
1118                       "$new_url => ", $self->full_url, ", $r\n"
1119                       unless $::_q > 1;
1120         $branch_from =~ s#^/##;
1121         my $gs = $self->other_gs($new_url, $url,
1122                                  $branch_from, $r, $self->{ref_id});
1123         my ($r0, $parent) = $gs->find_rev_before($r, 1);
1124         {
1125                 my ($base, $head);
1126                 if (!defined $r0 || !defined $parent) {
1127                         ($base, $head) = parse_revision_argument(0, $r);
1128                 } else {
1129                         if ($r0 < $r) {
1130                                 $gs->ra->get_log([$gs->path], $r0 + 1, $r, 1,
1131                                         0, 1, sub { $base = $_[1] - 1 });
1132                         }
1133                 }
1134                 if (defined $base && $base <= $r) {
1135                         $gs->fetch($base, $r);
1136                 }
1137                 ($r0, $parent) = $gs->find_rev_before($r, 1);
1138         }
1139         if (defined $r0 && defined $parent) {
1140                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
1141                              unless $::_q > 1;
1142                 my $ed;
1143                 if ($self->ra->can_do_switch) {
1144                         $self->assert_index_clean($parent);
1145                         print STDERR "Following parent with do_switch\n"
1146                                      unless $::_q > 1;
1147                         # do_switch works with svn/trunk >= r22312, but that
1148                         # is not included with SVN 1.4.3 (the latest version
1149                         # at the moment), so we can't rely on it
1150                         $self->{last_rev} = $r0;
1151                         $self->{last_commit} = $parent;
1152                         $ed = Git::SVN::Fetcher->new($self, $gs->path);
1153                         $gs->ra->gs_do_switch($r0, $rev, $gs,
1154                                               $self->full_url, $ed)
1155                           or die "SVN connection failed somewhere...\n";
1156                 } elsif ($self->ra->trees_match($new_url, $r0,
1157                                                 $self->full_url, $rev)) {
1158                         print STDERR "Trees match:\n",
1159                                      "  $new_url\@$r0\n",
1160                                      "  ${\$self->full_url}\@$rev\n",
1161                                      "Following parent with no changes\n"
1162                                      unless $::_q > 1;
1163                         $self->tmp_index_do(sub {
1164                             command_noisy('read-tree', $parent);
1165                         });
1166                         $self->{last_commit} = $parent;
1167                 } else {
1168                         print STDERR "Following parent with do_update\n"
1169                                      unless $::_q > 1;
1170                         $ed = Git::SVN::Fetcher->new($self);
1171                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
1172                           or die "SVN connection failed somewhere...\n";
1173                 }
1174                 print STDERR "Successfully followed parent\n" unless $::_q > 1;
1175                 return $self->make_log_entry($rev, [$parent], $ed, $r0, $branch_from);
1176         }
1177         return undef;
1178 }
1179
1180 sub do_fetch {
1181         my ($self, $paths, $rev) = @_;
1182         my $ed;
1183         my ($last_rev, @parents);
1184         if (my $lc = $self->last_commit) {
1185                 # we can have a branch that was deleted, then re-added
1186                 # under the same name but copied from another path, in
1187                 # which case we'll have multiple parents (we don't
1188                 # want to break the original ref or lose copypath info):
1189                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1190                         push @{$log_entry->{parents}}, $lc;
1191                         return $log_entry;
1192                 }
1193                 $ed = Git::SVN::Fetcher->new($self);
1194                 $last_rev = $self->{last_rev};
1195                 $ed->{c} = $lc;
1196                 @parents = ($lc);
1197         } else {
1198                 $last_rev = $rev;
1199                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1200                         return $log_entry;
1201                 }
1202                 $ed = Git::SVN::Fetcher->new($self);
1203         }
1204         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1205                 die "SVN connection failed somewhere...\n";
1206         }
1207         $self->make_log_entry($rev, \@parents, $ed, $last_rev, $self->path);
1208 }
1209
1210 sub mkemptydirs {
1211         my ($self, $r) = @_;
1212
1213         sub scan {
1214                 my ($r, $empty_dirs, $line) = @_;
1215                 if (defined $r && $line =~ /^r(\d+)$/) {
1216                         return 0 if $1 > $r;
1217                 } elsif ($line =~ /^  \+empty_dir: (.+)$/) {
1218                         $empty_dirs->{$1} = 1;
1219                 } elsif ($line =~ /^  \-empty_dir: (.+)$/) {
1220                         my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
1221                         delete @$empty_dirs{@d};
1222                 }
1223                 1; # continue
1224         };
1225
1226         my %empty_dirs = ();
1227         my $gz_file = "$self->{dir}/unhandled.log.gz";
1228         if (-f $gz_file) {
1229                 if (!can_compress()) {
1230                         warn "Compress::Zlib could not be found; ",
1231                              "empty directories in $gz_file will not be read\n";
1232                 } else {
1233                         my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
1234                                 die "Unable to open $gz_file: $!\n";
1235                         my $line;
1236                         while ($gz->gzreadline($line) > 0) {
1237                                 scan($r, \%empty_dirs, $line) or last;
1238                         }
1239                         $gz->gzclose;
1240                 }
1241         }
1242
1243         if (open my $fh, '<', "$self->{dir}/unhandled.log") {
1244                 binmode $fh or croak "binmode: $!";
1245                 while (<$fh>) {
1246                         scan($r, \%empty_dirs, $_) or last;
1247                 }
1248                 close $fh;
1249         }
1250
1251         my $strip = qr/\A\Q@{[$self->path]}\E(?:\/|$)/;
1252         foreach my $d (sort keys %empty_dirs) {
1253                 $d = uri_decode($d);
1254                 $d =~ s/$strip//;
1255                 next unless length($d);
1256                 next if -d $d;
1257                 if (-e $d) {
1258                         warn "$d exists but is not a directory\n";
1259                 } else {
1260                         print "creating empty directory: $d\n";
1261                         mkpath([$d]);
1262                 }
1263         }
1264 }
1265
1266 sub get_untracked {
1267         my ($self, $ed) = @_;
1268         my @out;
1269         my $h = $ed->{empty};
1270         foreach (sort keys %$h) {
1271                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1272                 push @out, "  $act: " . uri_encode($_);
1273                 warn "W: $act: $_\n";
1274         }
1275         foreach my $t (qw/dir_prop file_prop/) {
1276                 $h = $ed->{$t} or next;
1277                 foreach my $path (sort keys %$h) {
1278                         my $ppath = $path eq '' ? '.' : $path;
1279                         foreach my $prop (sort keys %{$h->{$path}}) {
1280                                 next if $SKIP_PROP{$prop};
1281                                 my $v = $h->{$path}->{$prop};
1282                                 my $t_ppath_prop = "$t: " .
1283                                                     uri_encode($ppath) . ' ' .
1284                                                     uri_encode($prop);
1285                                 if (defined $v) {
1286                                         push @out, "  +$t_ppath_prop " .
1287                                                    uri_encode($v);
1288                                 } else {
1289                                         push @out, "  -$t_ppath_prop";
1290                                 }
1291                         }
1292                 }
1293         }
1294         foreach my $t (qw/absent_file absent_directory/) {
1295                 $h = $ed->{$t} or next;
1296                 foreach my $parent (sort keys %$h) {
1297                         foreach my $path (sort @{$h->{$parent}}) {
1298                                 push @out, "  $t: " .
1299                                            uri_encode("$parent/$path");
1300                                 warn "W: $t: $parent/$path ",
1301                                      "Insufficient permissions?\n";
1302                         }
1303                 }
1304         }
1305         \@out;
1306 }
1307
1308 # parse_svn_date(DATE)
1309 # --------------------
1310 # Given a date (in UTC) from Subversion, return a string in the format
1311 # "<TZ Offset> <local date/time>" that Git will use.
1312 #
1313 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
1314 # is true we'll convert it to the local timezone instead.
1315 sub parse_svn_date {
1316         my $date = shift || return '+0000 1970-01-01 00:00:00';
1317         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1318                                             (\d\d?)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1319                                          croak "Unable to parse date: $date\n";
1320         my $parsed_date;    # Set next.
1321
1322         if ($Git::SVN::_localtime) {
1323                 # Translate the Subversion datetime to an epoch time.
1324                 # Begin by switching ourselves to $date's timezone, UTC.
1325                 my $old_env_TZ = $ENV{TZ};
1326                 $ENV{TZ} = 'UTC';
1327
1328                 my $epoch_in_UTC =
1329                     POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
1330
1331                 # Determine our local timezone (including DST) at the
1332                 # time of $epoch_in_UTC.  $Git::SVN::Log::TZ stored the
1333                 # value of TZ, if any, at the time we were run.
1334                 if (defined $Git::SVN::Log::TZ) {
1335                         $ENV{TZ} = $Git::SVN::Log::TZ;
1336                 } else {
1337                         delete $ENV{TZ};
1338                 }
1339
1340                 my $our_TZ = get_tz_offset();
1341
1342                 # This converts $epoch_in_UTC into our local timezone.
1343                 my ($sec, $min, $hour, $mday, $mon, $year,
1344                     $wday, $yday, $isdst) = localtime($epoch_in_UTC);
1345
1346                 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
1347                                        $our_TZ, $year + 1900, $mon + 1,
1348                                        $mday, $hour, $min, $sec);
1349
1350                 # Reset us to the timezone in effect when we entered
1351                 # this routine.
1352                 if (defined $old_env_TZ) {
1353                         $ENV{TZ} = $old_env_TZ;
1354                 } else {
1355                         delete $ENV{TZ};
1356                 }
1357         } else {
1358                 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
1359         }
1360
1361         return $parsed_date;
1362 }
1363
1364 sub other_gs {
1365         my ($self, $new_url, $url,
1366             $branch_from, $r, $old_ref_id) = @_;
1367         my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
1368         unless ($gs) {
1369                 my $ref_id = $old_ref_id;
1370                 $ref_id =~ s/\@\d+-*$//;
1371                 $ref_id .= "\@$r";
1372                 # just grow a tail if we're not unique enough :x
1373                 $ref_id .= '-' while find_ref($ref_id);
1374                 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
1375                 if ($u =~ s#^\Q$url\E(/|$)##) {
1376                         $p = $u;
1377                         $u = $url;
1378                         $repo_id = $self->{repo_id};
1379                 }
1380                 while (1) {
1381                         # It is possible to tag two different subdirectories at
1382                         # the same revision.  If the url for an existing ref
1383                         # does not match, we must either find a ref with a
1384                         # matching url or create a new ref by growing a tail.
1385                         $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
1386                         my (undef, $max_commit) = $gs->rev_map_max(1);
1387                         last if (!$max_commit);
1388                         my ($url) = ::cmt_metadata($max_commit);
1389                         last if ($url eq $gs->metadata_url);
1390                         $ref_id .= '-';
1391                 }
1392                 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
1393         }
1394         $gs
1395 }
1396
1397 sub call_authors_prog {
1398         my ($orig_author) = @_;
1399         $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
1400         my $author = `$::_authors_prog $orig_author`;
1401         if ($? != 0) {
1402                 die "$::_authors_prog failed with exit code $?\n"
1403         }
1404         if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
1405                 my ($name, $email) = ($1, $2);
1406                 $email = undef if length $2 == 0;
1407                 return [$name, $email];
1408         } else {
1409                 die "Author: $orig_author: $::_authors_prog returned "
1410                         . "invalid author format: $author\n";
1411         }
1412 }
1413
1414 sub check_author {
1415         my ($author) = @_;
1416         if (!defined $author || length $author == 0) {
1417                 $author = '(no author)';
1418         }
1419         if (!defined $::users{$author}) {
1420                 if (defined $::_authors_prog) {
1421                         $::users{$author} = call_authors_prog($author);
1422                 } elsif (defined $::_authors) {
1423                         die "Author: $author not defined in $::_authors file\n";
1424                 }
1425         }
1426         $author;
1427 }
1428
1429 sub find_extra_svk_parents {
1430         my ($self, $tickets, $parents) = @_;
1431         # aha!  svk:merge property changed...
1432         my @tickets = split "\n", $tickets;
1433         my @known_parents;
1434         for my $ticket ( @tickets ) {
1435                 my ($uuid, $path, $rev) = split /:/, $ticket;
1436                 if ( $uuid eq $self->ra_uuid ) {
1437                         my $repos_root = $self->url;
1438                         my $branch_from = $path;
1439                         $branch_from =~ s{^/}{};
1440                         my $gs = $self->other_gs(add_path_to_url( $repos_root, $branch_from ),
1441                                                  $repos_root,
1442                                                  $branch_from,
1443                                                  $rev,
1444                                                  $self->{ref_id});
1445                         if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
1446                                 # wahey!  we found it, but it might be
1447                                 # an old one (!)
1448                                 push @known_parents, [ $rev, $commit ];
1449                         }
1450                 }
1451         }
1452         # Ordering matters; highest-numbered commit merge tickets
1453         # first, as they may account for later merge ticket additions
1454         # or changes.
1455         @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
1456         for my $parent ( @known_parents ) {
1457                 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
1458                 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
1459                 my $new;
1460                 while ( <$msg_fh> ) {
1461                         $new=1;last;
1462                 }
1463                 command_close_pipe($msg_fh, $ctx);
1464                 if ( $new ) {
1465                         print STDERR
1466                             "Found merge parent (svk:merge ticket): $parent\n";
1467                         push @$parents, $parent;
1468                 }
1469         }
1470 }
1471
1472 sub lookup_svn_merge {
1473         my $uuid = shift;
1474         my $url = shift;
1475         my $source = shift;
1476         my $revs = shift;
1477
1478         my $path = $source;
1479         $path =~ s{^/}{};
1480         my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
1481         if ( !$gs ) {
1482                 warn "Couldn't find revmap for $url$source\n";
1483                 return;
1484         }
1485         my @ranges = split ",", $revs;
1486         my ($tip, $tip_commit);
1487         my @merged_commit_ranges;
1488         # find the tip
1489         for my $range ( @ranges ) {
1490                 if ($range =~ /[*]$/) {
1491                         warn "W: Ignoring partial merge in svn:mergeinfo "
1492                                 ."dirprop: $source:$range\n";
1493                         next;
1494                 }
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 );
1499
1500                 unless ($top_commit and $bottom_commit) {
1501                         warn "W: unknown path/rev in svn:mergeinfo "
1502                                 ."dirprop: $source:$range\n";
1503                         next;
1504                 }
1505
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";
1511                 }
1512
1513                 if ( !defined $tip or $top > $tip ) {
1514                         $tip = $top;
1515                         $tip_commit = $top_commit;
1516                 }
1517         }
1518         return ($tip_commit, @merged_commit_ranges);
1519 }
1520
1521 sub _rev_list {
1522         my ($msg_fh, $ctx) = command_output_pipe(
1523                 "rev-list", @_,
1524                );
1525         my @rv;
1526         while ( <$msg_fh> ) {
1527                 chomp;
1528                 push @rv, $_;
1529         }
1530         command_close_pipe($msg_fh, $ctx);
1531         @rv;
1532 }
1533
1534 sub check_cherry_pick2 {
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, "--")};
1543         }
1544         for my $commit (keys %commits) {
1545                 if (has_no_changes($commit)) {
1546                         delete $commits{$commit};
1547                 }
1548         }
1549         my @k = (keys %commits);
1550         return (scalar @k, $k[0]);
1551 }
1552
1553 sub has_no_changes {
1554         my $commit = shift;
1555
1556         my @revs = split / /, command_oneline(
1557                 qw(rev-list --parents -1 -m), $commit);
1558
1559         # Commits with no parents, e.g. the start of a partial branch,
1560         # have changes by definition.
1561         return 1 if (@revs < 2);
1562
1563         # Commits with multiple parents, e.g a merge, have no changes
1564         # by definition.
1565         return 0 if (@revs > 2);
1566
1567         return (command_oneline("rev-parse", "$commit^{tree}") eq
1568                 command_oneline("rev-parse", "$commit~1^{tree}"));
1569 }
1570
1571 sub tie_for_persistent_memoization {
1572         my $hash = shift;
1573         my $path = shift;
1574
1575         unless ($memo_backend) {
1576                 if (eval { require Git::SVN::Memoize::YAML; 1}) {
1577                         $memo_backend = 1;
1578                 } else {
1579                         require Memoize::Storable;
1580                         $memo_backend = -1;
1581                 }
1582         }
1583
1584         if ($memo_backend > 0) {
1585                 tie %$hash => 'Git::SVN::Memoize::YAML', "$path.yaml";
1586         } else {
1587                 tie %$hash => 'Memoize::Storable', "$path.db", 'nstore';
1588         }
1589 }
1590
1591 # The GIT_DIR environment variable is not always set until after the command
1592 # line arguments are processed, so we can't memoize in a BEGIN block.
1593 {
1594         my $memoized = 0;
1595
1596         sub memoize_svn_mergeinfo_functions {
1597                 return if $memoized;
1598                 $memoized = 1;
1599
1600                 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1601                 mkpath([$cache_path]) unless -d $cache_path;
1602
1603                 my %lookup_svn_merge_cache;
1604                 my %check_cherry_pick2_cache;
1605                 my %has_no_changes_cache;
1606
1607                 tie_for_persistent_memoization(\%lookup_svn_merge_cache,
1608                     "$cache_path/lookup_svn_merge");
1609                 memoize 'lookup_svn_merge',
1610                         SCALAR_CACHE => 'FAULT',
1611                         LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
1612                 ;
1613
1614                 tie_for_persistent_memoization(\%check_cherry_pick2_cache,
1615                     "$cache_path/check_cherry_pick2");
1616                 memoize 'check_cherry_pick2',
1617                         SCALAR_CACHE => 'FAULT',
1618                         LIST_CACHE => ['HASH' => \%check_cherry_pick2_cache],
1619                 ;
1620
1621                 tie_for_persistent_memoization(\%has_no_changes_cache,
1622                     "$cache_path/has_no_changes");
1623                 memoize 'has_no_changes',
1624                         SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
1625                         LIST_CACHE => 'FAULT',
1626                 ;
1627         }
1628
1629         sub unmemoize_svn_mergeinfo_functions {
1630                 return if not $memoized;
1631                 $memoized = 0;
1632
1633                 Memoize::unmemoize 'lookup_svn_merge';
1634                 Memoize::unmemoize 'check_cherry_pick2';
1635                 Memoize::unmemoize 'has_no_changes';
1636         }
1637
1638         sub clear_memoized_mergeinfo_caches {
1639                 die "Only call this method in non-memoized context" if ($memoized);
1640
1641                 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
1642                 return unless -d $cache_path;
1643
1644                 for my $cache_file (("$cache_path/lookup_svn_merge",
1645                                      "$cache_path/check_cherry_pick", # old
1646                                      "$cache_path/check_cherry_pick2",
1647                                      "$cache_path/has_no_changes")) {
1648                         for my $suffix (qw(yaml db)) {
1649                                 my $file = "$cache_file.$suffix";
1650                                 next unless -e $file;
1651                                 unlink($file) or die "unlink($file) failed: $!\n";
1652                         }
1653                 }
1654         }
1655
1656
1657         Memoize::memoize 'Git::SVN::repos_root';
1658 }
1659
1660 END {
1661         # Force cache writeout explicitly instead of waiting for
1662         # global destruction to avoid segfault in Storable:
1663         # http://rt.cpan.org/Public/Bug/Display.html?id=36087
1664         unmemoize_svn_mergeinfo_functions();
1665 }
1666
1667 sub parents_exclude {
1668         my $parents = shift;
1669         my @commits = @_;
1670         return unless @commits;
1671
1672         my @excluded;
1673         my $excluded;
1674         do {
1675                 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
1676                 $excluded = command_oneline(@cmd);
1677                 if ( $excluded ) {
1678                         my @new;
1679                         my $found;
1680                         for my $commit ( @commits ) {
1681                                 if ( $commit eq $excluded ) {
1682                                         push @excluded, $commit;
1683                                         $found++;
1684                                 }
1685                                 else {
1686                                         push @new, $commit;
1687                                 }
1688                         }
1689                         die "saw commit '$excluded' in rev-list output, "
1690                                 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
1691                                         unless $found;
1692                         @commits = @new;
1693                 }
1694         }
1695                 while ($excluded and @commits);
1696
1697         return @excluded;
1698 }
1699
1700 # Compute what's new in svn:mergeinfo.
1701 sub mergeinfo_changes {
1702         my ($self, $old_path, $old_rev, $path, $rev, $mergeinfo_prop) = @_;
1703         my %minfo = map {split ":", $_ } split "\n", $mergeinfo_prop;
1704         my $old_minfo = {};
1705
1706         my $ra = $self->ra;
1707         # Give up if $old_path isn't in the repo.
1708         # This is probably a merge on a subtree.
1709         if ($ra->check_path($old_path, $old_rev) != $SVN::Node::dir) {
1710                 warn "W: ignoring svn:mergeinfo on $old_path, ",
1711                         "directory didn't exist in r$old_rev\n";
1712                 return {};
1713         }
1714         my (undef, undef, $props) = $ra->get_dir($old_path, $old_rev);
1715         if (defined $props->{"svn:mergeinfo"}) {
1716                 my %omi = map {split ":", $_ } split "\n",
1717                         $props->{"svn:mergeinfo"};
1718                 $old_minfo = \%omi;
1719         }
1720
1721         my %changes = ();
1722         foreach my $p (keys %minfo) {
1723                 my $a = $old_minfo->{$p} || "";
1724                 my $b = $minfo{$p};
1725                 # Omit merged branches whose ranges lists are unchanged.
1726                 next if $a eq $b;
1727                 # Remove any common range list prefix.
1728                 ($a ^ $b) =~ /^[\0]*/;
1729                 my $common_prefix = rindex $b, ",", $+[0] - 1;
1730                 $changes{$p} = substr $b, $common_prefix + 1;
1731         }
1732         print STDERR "Checking svn:mergeinfo changes since r$old_rev: ",
1733                 scalar(keys %minfo), " sources, ",
1734                 scalar(keys %changes), " changed\n";
1735
1736         return \%changes;
1737 }
1738
1739 # note: this function should only be called if the various dirprops
1740 # have actually changed
1741 sub find_extra_svn_parents {
1742         my ($self, $mergeinfo, $parents) = @_;
1743         # aha!  svk:merge property changed...
1744
1745         memoize_svn_mergeinfo_functions();
1746
1747         # We first search for merged tips which are not in our
1748         # history.  Then, we figure out which git revisions are in
1749         # that tip, but not this revision.  If all of those revisions
1750         # are now marked as merge, we can add the tip as a parent.
1751         my @merges = sort keys %$mergeinfo;
1752         my @merge_tips;
1753         my $url = $self->url;
1754         my $uuid = $self->ra_uuid;
1755         my @all_ranges;
1756         for my $merge ( @merges ) {
1757                 my ($tip_commit, @ranges) =
1758                         lookup_svn_merge( $uuid, $url,
1759                                           $merge, $mergeinfo->{$merge} );
1760                 unless (!$tip_commit or
1761                                 grep { $_ eq $tip_commit } @$parents ) {
1762                         push @merge_tips, $tip_commit;
1763                         push @all_ranges, @ranges;
1764                 } else {
1765                         push @merge_tips, undef;
1766                 }
1767         }
1768
1769         my %excluded = map { $_ => 1 }
1770                 parents_exclude($parents, grep { defined } @merge_tips);
1771
1772         # check merge tips for new parents
1773         my @new_parents;
1774         for my $merge_tip ( @merge_tips ) {
1775                 my $merge = shift @merges;
1776                 next unless $merge_tip and $excluded{$merge_tip};
1777                 my $spec = "$merge:$mergeinfo->{$merge}";
1778
1779                 # check out 'new' tips
1780                 my $merge_base;
1781                 eval {
1782                         $merge_base = command_oneline(
1783                                 "merge-base",
1784                                 @$parents, $merge_tip,
1785                         );
1786                 };
1787                 if ($@) {
1788                         die "An error occurred during merge-base"
1789                                 unless $@->isa("Git::Error::Command");
1790
1791                         warn "W: Cannot find common ancestor between ".
1792                              "@$parents and $merge_tip. Ignoring merge info.\n";
1793                         next;
1794                 }
1795
1796                 # double check that there are no missing non-merge commits
1797                 my ($ninc, $ifirst) = check_cherry_pick2(
1798                         $merge_base, $merge_tip,
1799                         $parents,
1800                         @all_ranges,
1801                        );
1802
1803                 if ($ninc) {
1804                         warn "W: svn cherry-pick ignored ($spec) - missing " .
1805                                 "$ninc commit(s) (eg $ifirst)\n";
1806                 } else {
1807                         warn "Found merge parent ($spec): ", $merge_tip, "\n";
1808                         push @new_parents, $merge_tip;
1809                 }
1810         }
1811
1812         # cater for merges which merge commits from multiple branches
1813         if ( @new_parents > 1 ) {
1814                 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
1815                         for ( my $j = 0; $j <= $#new_parents; $j++ ) {
1816                                 next if $i == $j;
1817                                 next unless $new_parents[$i];
1818                                 next unless $new_parents[$j];
1819                                 my $revs = command_oneline(
1820                                         "rev-list", "-1",
1821                                         "$new_parents[$i]..$new_parents[$j]",
1822                                        );
1823                                 if ( !$revs ) {
1824                                         undef($new_parents[$j]);
1825                                 }
1826                         }
1827                 }
1828         }
1829         push @$parents, grep { defined } @new_parents;
1830 }
1831
1832 sub make_log_entry {
1833         my ($self, $rev, $parents, $ed, $parent_rev, $parent_path) = @_;
1834         my $untracked = $self->get_untracked($ed);
1835
1836         my @parents = @$parents;
1837         my $props = $ed->{dir_prop}{$self->path};
1838         if ( $props->{"svk:merge"} ) {
1839                 $self->find_extra_svk_parents($props->{"svk:merge"}, \@parents);
1840         }
1841         if ( $props->{"svn:mergeinfo"} ) {
1842                 my $mi_changes = $self->mergeinfo_changes
1843                         ($parent_path, $parent_rev,
1844                          $self->path, $rev,
1845                          $props->{"svn:mergeinfo"});
1846                 $self->find_extra_svn_parents($mi_changes, \@parents);
1847         }
1848
1849         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1850         print $un "r$rev\n" or croak $!;
1851         print $un $_, "\n" foreach @$untracked;
1852         my %log_entry = ( parents => \@parents, revision => $rev,
1853                           log => '');
1854
1855         my $headrev;
1856         my $logged = delete $self->{logged_rev_props};
1857         if (!$logged || $self->{-want_revprops}) {
1858                 my $rp = $self->ra->rev_proplist($rev);
1859                 foreach (sort keys %$rp) {
1860                         my $v = $rp->{$_};
1861                         if (/^svn:(author|date|log)$/) {
1862                                 $log_entry{$1} = $v;
1863                         } elsif ($_ eq 'svm:headrev') {
1864                                 $headrev = $v;
1865                         } else {
1866                                 print $un "  rev_prop: ", uri_encode($_), ' ',
1867                                           uri_encode($v), "\n";
1868                         }
1869                 }
1870         } else {
1871                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1872         }
1873         close $un or croak $!;
1874
1875         $log_entry{date} = parse_svn_date($log_entry{date});
1876         $log_entry{log} .= "\n";
1877         my $author = $log_entry{author} = check_author($log_entry{author});
1878         my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1879                                                        : ($author, undef);
1880
1881         my ($commit_name, $commit_email) = ($name, $email);
1882         if ($_use_log_author) {
1883                 my $name_field;
1884                 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
1885                         $name_field = $1;
1886                 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
1887                         $name_field = $1;
1888                 }
1889                 if (!defined $name_field) {
1890                         if (!defined $email) {
1891                                 $email = $name;
1892                         }
1893                 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
1894                         ($name, $email) = ($1, $2);
1895                 } elsif ($name_field =~ /(.*)@/) {
1896                         ($name, $email) = ($1, $name_field);
1897                 } else {
1898                         ($name, $email) = ($name_field, $name_field);
1899                 }
1900         }
1901         if (defined $headrev && $self->use_svm_props) {
1902                 if ($self->rewrite_root) {
1903                         die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1904                             "options set!\n";
1905                 }
1906                 if ($self->rewrite_uuid) {
1907                         die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
1908                             "options set!\n";
1909                 }
1910                 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
1911                 # we don't want "SVM: initializing mirror for junk" ...
1912                 return undef if $r == 0;
1913                 my $svm = $self->svm;
1914                 if ($uuid ne $svm->{uuid}) {
1915                         die "UUID mismatch on SVM path:\n",
1916                             "expected: $svm->{uuid}\n",
1917                             "     got: $uuid\n";
1918                 }
1919                 my $full_url = $self->full_url;
1920                 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1921                              die "Failed to replace '$svm->{replace}' with ",
1922                                  "'$svm->{source}' in $full_url\n";
1923                 # throw away username for storing in records
1924                 remove_username($full_url);
1925                 $log_entry{metadata} = "$full_url\@$r $uuid";
1926                 $log_entry{svm_revision} = $r;
1927                 $email ||= "$author\@$uuid";
1928                 $commit_email ||= "$author\@$uuid";
1929         } elsif ($self->use_svnsync_props) {
1930                 my $full_url = canonicalize_url(
1931                         add_path_to_url( $self->svnsync->{url}, $self->path )
1932                 );
1933                 remove_username($full_url);
1934                 my $uuid = $self->svnsync->{uuid};
1935                 $log_entry{metadata} = "$full_url\@$rev $uuid";
1936                 $email ||= "$author\@$uuid";
1937                 $commit_email ||= "$author\@$uuid";
1938         } else {
1939                 my $url = $self->metadata_url;
1940                 remove_username($url);
1941                 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
1942                 $log_entry{metadata} = "$url\@$rev " . $uuid;
1943                 $email ||= "$author\@" . $uuid;
1944                 $commit_email ||= "$author\@" . $uuid;
1945         }
1946         $log_entry{name} = $name;
1947         $log_entry{email} = $email;
1948         $log_entry{commit_name} = $commit_name;
1949         $log_entry{commit_email} = $commit_email;
1950         \%log_entry;
1951 }
1952
1953 sub fetch {
1954         my ($self, $min_rev, $max_rev, @parents) = @_;
1955         my ($last_rev, $last_commit) = $self->last_rev_commit;
1956         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1957         $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1958 }
1959
1960 sub set_tree_cb {
1961         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1962         $self->{inject_parents} = { $rev => $tree };
1963         $self->fetch(undef, undef);
1964 }
1965
1966 sub set_tree {
1967         my ($self, $tree) = (shift, shift);
1968         my $log_entry = ::get_commit_entry($tree);
1969         unless ($self->{last_rev}) {
1970                 fatal("Must have an existing revision to commit");
1971         }
1972         my %ed_opts = ( r => $self->{last_rev},
1973                         log => $log_entry->{log},
1974                         ra => $self->ra,
1975                         tree_a => $self->{last_commit},
1976                         tree_b => $tree,
1977                         editor_cb => sub {
1978                                $self->set_tree_cb($log_entry, $tree, @_) },
1979                         svn_path => $self->path );
1980         if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1981                 print "No changes\nr$self->{last_rev} = $tree\n";
1982         }
1983 }
1984
1985 sub rebuild_from_rev_db {
1986         my ($self, $path) = @_;
1987         my $r = -1;
1988         open my $fh, '<', $path or croak "open: $!";
1989         binmode $fh or croak "binmode: $!";
1990         while (<$fh>) {
1991                 length($_) == 41 or croak "inconsistent size in ($_) != 41";
1992                 chomp($_);
1993                 ++$r;
1994                 next if $_ eq ('0' x 40);
1995                 $self->rev_map_set($r, $_);
1996                 print "r$r = $_\n";
1997         }
1998         close $fh or croak "close: $!";
1999         unlink $path or croak "unlink: $!";
2000 }
2001
2002 #define a global associate map to record rebuild status
2003 my %rebuild_status;
2004 #define a global associate map to record rebuild verify status
2005 my %rebuild_verify_status;
2006
2007 sub rebuild {
2008         my ($self) = @_;
2009         my $map_path = $self->map_path;
2010         my $partial = (-e $map_path && ! -z $map_path);
2011         my $verify_key = $self->refname.'^0';
2012         if (!$rebuild_verify_status{$verify_key}) {
2013                 my $verify_result = ::verify_ref($verify_key);
2014                 if ($verify_result) {
2015                         $rebuild_verify_status{$verify_key} = 1;
2016                 }
2017         }
2018         if (!$rebuild_verify_status{$verify_key}) {
2019                 return;
2020         }
2021         if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2022                 my $rev_db = $self->rev_db_path;
2023                 $self->rebuild_from_rev_db($rev_db);
2024                 if ($self->use_svm_props) {
2025                         my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2026                         $self->rebuild_from_rev_db($svm_rev_db);
2027                 }
2028                 $self->unlink_rev_db_symlink;
2029                 return;
2030         }
2031         print "Rebuilding $map_path ...\n" if (!$partial);
2032         my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2033                 (undef, undef));
2034         my $key_value = ($head ? "$head.." : "") . $self->refname;
2035         if (exists $rebuild_status{$key_value}) {
2036                 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2037                 my $rev_db_path = $self->rev_db_path;
2038                 if (-f $self->rev_db_path) {
2039                         unlink $self->rev_db_path or croak "unlink: $!";
2040                 }
2041                 $self->unlink_rev_db_symlink;
2042                 return;
2043         }
2044         my ($log, $ctx) =
2045                 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
2046                                 $key_value,
2047                                 '--');
2048         $rebuild_status{$key_value} = 1;
2049         my $metadata_url = $self->metadata_url;
2050         remove_username($metadata_url);
2051         my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
2052         my $c;
2053         while (<$log>) {
2054                 if ( m{^commit ($::sha1)$} ) {
2055                         $c = $1;
2056                         next;
2057                 }
2058                 next unless s{^\s*(git-svn-id:)}{$1};
2059                 my ($url, $rev, $uuid) = ::extract_metadata($_);
2060                 remove_username($url);
2061
2062                 # ignore merges (from set-tree)
2063                 next if (!defined $rev || !$uuid);
2064
2065                 # if we merged or otherwise started elsewhere, this is
2066                 # how we break out of it
2067                 if (($uuid ne $svn_uuid) ||
2068                     ($metadata_url && $url && ($url ne $metadata_url))) {
2069                         next;
2070                 }
2071                 if ($partial && $head) {
2072                         print "Partial-rebuilding $map_path ...\n";
2073                         print "Currently at $base_rev = $head\n";
2074                         $head = undef;
2075                 }
2076
2077                 $self->rev_map_set($rev, $c);
2078                 print "r$rev = $c\n";
2079         }
2080         command_close_pipe($log, $ctx);
2081         print "Done rebuilding $map_path\n" if (!$partial || !$head);
2082         my $rev_db_path = $self->rev_db_path;
2083         if (-f $self->rev_db_path) {
2084                 unlink $self->rev_db_path or croak "unlink: $!";
2085         }
2086         $self->unlink_rev_db_symlink;
2087 }
2088
2089 # rev_map:
2090 # Tie::File seems to be prone to offset errors if revisions get sparse,
2091 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2092 # one of my favorite modules is out :<  Next up would be one of the DBM
2093 # modules, but I'm not sure which is most portable...
2094 #
2095 # This is the replacement for the rev_db format, which was too big
2096 # and inefficient for large repositories with a lot of sparse history
2097 # (mainly tags)
2098 #
2099 # The format is this:
2100 #   - 24 bytes for every record,
2101 #     * 4 bytes for the integer representing an SVN revision number
2102 #     * 20 bytes representing the sha1 of a git commit
2103 #   - No empty padding records like the old format
2104 #     (except the last record, which can be overwritten)
2105 #   - new records are written append-only since SVN revision numbers
2106 #     increase monotonically
2107 #   - lookups on SVN revision number are done via a binary search
2108 #   - Piping the file to xxd -c24 is a good way of dumping it for
2109 #     viewing or editing (piped back through xxd -r), should the need
2110 #     ever arise.
2111 #   - The last record can be padding revision with an all-zero sha1
2112 #     This is used to optimize fetch performance when using multiple
2113 #     "fetch" directives in .git/config
2114 #
2115 # These files are disposable unless noMetadata or useSvmProps is set
2116
2117 sub _rev_map_set {
2118         my ($fh, $rev, $commit) = @_;
2119
2120         binmode $fh or croak "binmode: $!";
2121         my $size = (stat($fh))[7];
2122         ($size % 24) == 0 or croak "inconsistent size: $size";
2123
2124         my $wr_offset = 0;
2125         if ($size > 0) {
2126                 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2127                 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2128                 $read == 24 or croak "read only $read bytes (!= 24)";
2129                 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2130                 if ($last_commit eq ('0' x40)) {
2131                         if ($size >= 48) {
2132                                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2133                                 $read = sysread($fh, $buf, 24) or
2134                                     croak "read: $!";
2135                                 $read == 24 or
2136                                     croak "read only $read bytes (!= 24)";
2137                                 ($last_rev, $last_commit) =
2138                                     unpack(rev_map_fmt, $buf);
2139                                 if ($last_commit eq ('0' x40)) {
2140                                         croak "inconsistent .rev_map\n";
2141                                 }
2142                         }
2143                         if ($last_rev >= $rev) {
2144                                 croak "last_rev is higher!: $last_rev >= $rev";
2145                         }
2146                         $wr_offset = -24;
2147                 }
2148         }
2149         sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2150         syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2151           croak "write: $!";
2152 }
2153
2154 sub _rev_map_reset {
2155         my ($fh, $rev, $commit) = @_;
2156         my $c = _rev_map_get($fh, $rev);
2157         $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
2158         my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
2159         truncate $fh, $offset or croak "truncate: $!";
2160 }
2161
2162 sub mkfile {
2163         my ($path) = @_;
2164         unless (-e $path) {
2165                 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2166                 mkpath([$dir]) unless -d $dir;
2167                 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2168                 close $fh or die "Couldn't close (create) $path: $!\n";
2169         }
2170 }
2171
2172 sub rev_map_set {
2173         my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2174         defined $commit or die "missing arg3\n";
2175         length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2176         my $db = $self->map_path($uuid);
2177         my $db_lock = "$db.lock";
2178         my $sigmask;
2179         $update_ref ||= 0;
2180         if ($update_ref) {
2181                 $sigmask = POSIX::SigSet->new();
2182                 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
2183                         SIGALRM, SIGUSR1, SIGUSR2);
2184                 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
2185                         croak "Can't block signals: $!";
2186         }
2187         mkfile($db);
2188
2189         $LOCKFILES{$db_lock} = 1;
2190         my $sync;
2191         # both of these options make our .rev_db file very, very important
2192         # and we can't afford to lose it because rebuild() won't work
2193         if ($self->use_svm_props || $self->no_metadata) {
2194                 require File::Copy;
2195                 $sync = 1;
2196                 File::Copy::copy($db, $db_lock) or die "rev_map_set(@_): ",
2197                                            "Failed to copy: ",
2198                                            "$db => $db_lock ($!)\n";
2199         } else {
2200                 rename $db, $db_lock or die "rev_map_set(@_): ",
2201                                             "Failed to rename: ",
2202                                             "$db => $db_lock ($!)\n";
2203         }
2204
2205         sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2206              or croak "Couldn't open $db_lock: $!\n";
2207         if ($update_ref eq 'reset') {
2208                 clear_memoized_mergeinfo_caches();
2209                 _rev_map_reset($fh, $rev, $commit);
2210         } else {
2211                 _rev_map_set($fh, $rev, $commit);
2212         }
2213
2214         if ($sync) {
2215                 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2216                 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2217         }
2218         close $fh or croak $!;
2219         if ($update_ref) {
2220                 $_head = $self;
2221                 my $note = "";
2222                 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
2223                 command_noisy('update-ref', '-m', "r$rev$note",
2224                               $self->refname, $commit);
2225         }
2226         rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2227                                     "$db_lock => $db ($!)\n";
2228         delete $LOCKFILES{$db_lock};
2229         if ($update_ref) {
2230                 sigprocmask(SIG_SETMASK, $sigmask) or
2231                         croak "Can't restore signal mask: $!";
2232         }
2233 }
2234
2235 # If want_commit, this will return an array of (rev, commit) where
2236 # commit _must_ be a valid commit in the archive.
2237 # Otherwise, it'll return the max revision (whether or not the
2238 # commit is valid or just a 0x40 placeholder).
2239 sub rev_map_max {
2240         my ($self, $want_commit) = @_;
2241         $self->rebuild;
2242         my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2243         $want_commit ? ($r, $c) : $r;
2244 }
2245
2246 sub rev_map_max_norebuild {
2247         my ($self, $want_commit) = @_;
2248         my $map_path = $self->map_path;
2249         stat $map_path or return $want_commit ? (0, undef) : 0;
2250         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2251         binmode $fh or croak "binmode: $!";
2252         my $size = (stat($fh))[7];
2253         ($size % 24) == 0 or croak "inconsistent size: $size";
2254
2255         if ($size == 0) {
2256                 close $fh or croak "close: $!";
2257                 return $want_commit ? (0, undef) : 0;
2258         }
2259
2260         sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2261         sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2262         my ($r, $c) = unpack(rev_map_fmt, $buf);
2263         if ($want_commit && $c eq ('0' x40)) {
2264                 if ($size < 48) {
2265                         return $want_commit ? (0, undef) : 0;
2266                 }
2267                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2268                 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2269                 ($r, $c) = unpack(rev_map_fmt, $buf);
2270                 if ($c eq ('0'x40)) {
2271                         croak "Penultimate record is all-zeroes in $map_path";
2272                 }
2273         }
2274         close $fh or croak "close: $!";
2275         $want_commit ? ($r, $c) : $r;
2276 }
2277
2278 sub rev_map_get {
2279         my ($self, $rev, $uuid) = @_;
2280         my $map_path = $self->map_path($uuid);
2281         return undef unless -e $map_path;
2282
2283         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2284         my $c = _rev_map_get($fh, $rev);
2285         close($fh) or croak "close: $!";
2286         $c
2287 }
2288
2289 sub _rev_map_get {
2290         my ($fh, $rev) = @_;
2291
2292         binmode $fh or croak "binmode: $!";
2293         my $size = (stat($fh))[7];
2294         ($size % 24) == 0 or croak "inconsistent size: $size";
2295
2296         if ($size == 0) {
2297                 return undef;
2298         }
2299
2300         my ($l, $u) = (0, $size - 24);
2301         my ($r, $c, $buf);
2302
2303         while ($l <= $u) {
2304                 my $i = int(($l/24 + $u/24) / 2) * 24;
2305                 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2306                 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2307                 my ($r, $c) = unpack(rev_map_fmt, $buf);
2308
2309                 if ($r < $rev) {
2310                         $l = $i + 24;
2311                 } elsif ($r > $rev) {
2312                         $u = $i - 24;
2313                 } else { # $r == $rev
2314                         return $c eq ('0' x 40) ? undef : $c;
2315                 }
2316         }
2317         undef;
2318 }
2319
2320 # Finds the first svn revision that exists on (if $eq_ok is true) or
2321 # before $rev for the current branch.  It will not search any lower
2322 # than $min_rev.  Returns the git commit hash and svn revision number
2323 # if found, else (undef, undef).
2324 sub find_rev_before {
2325         my ($self, $rev, $eq_ok, $min_rev) = @_;
2326         --$rev unless $eq_ok;
2327         $min_rev ||= 1;
2328         my $max_rev = $self->rev_map_max;
2329         $rev = $max_rev if ($rev > $max_rev);
2330         while ($rev >= $min_rev) {
2331                 if (my $c = $self->rev_map_get($rev)) {
2332                         return ($rev, $c);
2333                 }
2334                 --$rev;
2335         }
2336         return (undef, undef);
2337 }
2338
2339 # Finds the first svn revision that exists on (if $eq_ok is true) or
2340 # after $rev for the current branch.  It will not search any higher
2341 # than $max_rev.  Returns the git commit hash and svn revision number
2342 # if found, else (undef, undef).
2343 sub find_rev_after {
2344         my ($self, $rev, $eq_ok, $max_rev) = @_;
2345         ++$rev unless $eq_ok;
2346         $max_rev ||= $self->rev_map_max;
2347         while ($rev <= $max_rev) {
2348                 if (my $c = $self->rev_map_get($rev)) {
2349                         return ($rev, $c);
2350                 }
2351                 ++$rev;
2352         }
2353         return (undef, undef);
2354 }
2355
2356 sub _new {
2357         my ($class, $repo_id, $ref_id, $path) = @_;
2358         unless (defined $repo_id && length $repo_id) {
2359                 $repo_id = $default_repo_id;
2360         }
2361         unless (defined $ref_id && length $ref_id) {
2362                 # Access the prefix option from the git-svn main program if it's loaded.
2363                 my $prefix = defined &::opt_prefix ? ::opt_prefix() : "";
2364                 $_[2] = $ref_id =
2365                              "refs/remotes/$prefix$default_ref_id";
2366         }
2367         $_[1] = $repo_id;
2368         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2369
2370         # Older repos imported by us used $GIT_DIR/svn/foo instead of
2371         # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
2372         if ($ref_id =~ m{^refs/remotes/(.+)}) {
2373                 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
2374                 if (-d $old_dir && ! -d $dir) {
2375                         $dir = $old_dir;
2376                 }
2377         }
2378
2379         $_[3] = $path = '' unless (defined $path);
2380         mkpath([$dir]);
2381         my $obj = bless {
2382                 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2383                 config => "$ENV{GIT_DIR}/svn/config",
2384                 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2385
2386         # Ensure it gets canonicalized
2387         $obj->path($path);
2388
2389         return $obj;
2390 }
2391
2392 sub path {
2393         my $self = shift;
2394
2395         if (@_) {
2396                 my $path = shift;
2397                 $self->{_path} = canonicalize_path($path);
2398                 return;
2399         }
2400
2401         return $self->{_path};
2402 }
2403
2404 sub url {
2405         my $self = shift;
2406
2407         if (@_) {
2408                 my $url = shift;
2409                 $self->{url} = canonicalize_url($url);
2410                 return;
2411         }
2412
2413         return $self->{url};
2414 }
2415
2416 # for read-only access of old .rev_db formats
2417 sub unlink_rev_db_symlink {
2418         my ($self) = @_;
2419         my $link = $self->rev_db_path;
2420         $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2421         if (-l $link) {
2422                 unlink $link or croak "unlink: $link failed!";
2423         }
2424 }
2425
2426 sub rev_db_path {
2427         my ($self, $uuid) = @_;
2428         my $db_path = $self->map_path($uuid);
2429         $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2430             or croak "map_path: $db_path does not contain '/.rev_map.' !";
2431         $db_path;
2432 }
2433
2434 # the new replacement for .rev_db
2435 sub map_path {
2436         my ($self, $uuid) = @_;
2437         $uuid ||= $self->ra_uuid;
2438         "$self->{map_root}.$uuid";
2439 }
2440
2441 sub uri_encode {
2442         my ($f) = @_;
2443         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#sprintf("%%%02X",ord($1))#eg;
2444         $f
2445 }
2446
2447 sub uri_decode {
2448         my ($f) = @_;
2449         $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
2450         $f
2451 }
2452
2453 sub remove_username {
2454         $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2455 }
2456
2457 1;