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