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