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