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