f026b240b89ce4857b5356661803affce9529f1f
   1#!/usr/bin/env perl
   2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
   3# License: GPL v2 or later
   4use warnings;
   5use strict;
   6use vars qw/    $AUTHOR $VERSION
   7                $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
   8                $GIT_SVN_INDEX $GIT_SVN
   9                $GIT_DIR $GIT_SVN_DIR $REVDB/;
  10$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
  11$VERSION = '1.1.1-broken';
  12
  13use Cwd qw/abs_path/;
  14$GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
  15$ENV{GIT_DIR} = $GIT_DIR;
  16
  17my $LC_ALL = $ENV{LC_ALL};
  18my $TZ = $ENV{TZ};
  19# make sure the svn binary gives consistent output between locales and TZs:
  20$ENV{TZ} = 'UTC';
  21$ENV{LC_ALL} = 'C';
  22
  23# If SVN:: library support is added, please make the dependencies
  24# optional and preserve the capability to use the command-line client.
  25# use eval { require SVN::... } to make it lazy load
  26# We don't use any modules not in the standard Perl distribution:
  27use Carp qw/croak/;
  28use IO::File qw//;
  29use File::Basename qw/dirname basename/;
  30use File::Path qw/mkpath/;
  31use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
  32use File::Spec qw//;
  33use POSIX qw/strftime/;
  34use IPC::Open3;
  35use Memoize;
  36memoize('revisions_eq');
  37
  38my ($SVN_PATH, $SVN, $SVN_LOG, $_use_lib);
  39$_use_lib = 1 unless $ENV{GIT_SVN_NO_LIB};
  40libsvn_load();
  41my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
  42my $sha1 = qr/[a-f\d]{40}/;
  43my $sha1_short = qr/[a-f\d]{4,40}/;
  44my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
  45        $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
  46        $_repack, $_repack_nr, $_repack_flags,
  47        $_template, $_shared, $_no_default_regex, $_no_graft_copy,
  48        $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
  49        $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m);
  50my (@_branch_from, %tree_map, %users, %rusers, %equiv);
  51my ($_svn_co_url_revs, $_svn_pg_peg_revs);
  52my @repo_path_split_cache;
  53
  54my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
  55                'branch|b=s' => \@_branch_from,
  56                'branch-all-refs|B' => \$_branch_all_refs,
  57                'authors-file|A=s' => \$_authors,
  58                'repack:i' => \$_repack,
  59                'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
  60
  61my ($_trunk, $_tags, $_branches);
  62my %multi_opts = ( 'trunk|T=s' => \$_trunk,
  63                'tags|t=s' => \$_tags,
  64                'branches|b=s' => \$_branches );
  65my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
  66
  67# yes, 'native' sets "\n".  Patches to fix this for non-*nix systems welcome:
  68my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
  69
  70my %cmd = (
  71        fetch => [ \&fetch, "Download new revisions from SVN",
  72                        { 'revision|r=s' => \$_revision, %fc_opts } ],
  73        init => [ \&init, "Initialize a repo for tracking" .
  74                          " (requires URL argument)",
  75                          \%init_opts ],
  76        commit => [ \&commit, "Commit git revisions to SVN",
  77                        {       'stdin|' => \$_stdin,
  78                                'edit|e' => \$_edit,
  79                                'rmdir' => \$_rmdir,
  80                                'find-copies-harder' => \$_find_copies_harder,
  81                                'l=i' => \$_l,
  82                                'copy-similarity|C=i'=> \$_cp_similarity,
  83                                %fc_opts,
  84                        } ],
  85        'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
  86                        { 'revision|r=i' => \$_revision } ],
  87        rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
  88                        { 'no-ignore-externals' => \$_no_ignore_ext,
  89                          'copy-remote|remote=s' => \$_cp_remote,
  90                          'upgrade' => \$_upgrade } ],
  91        'graft-branches' => [ \&graft_branches,
  92                        'Detect merges/branches from already imported history',
  93                        { 'merge-rx|m' => \@_opt_m,
  94                          'no-default-regex' => \$_no_default_regex,
  95                          'no-graft-copy' => \$_no_graft_copy } ],
  96        'multi-init' => [ \&multi_init,
  97                        'Initialize multiple trees (like git-svnimport)',
  98                        { %multi_opts, %fc_opts } ],
  99        'multi-fetch' => [ \&multi_fetch,
 100                        'Fetch multiple trees (like git-svnimport)',
 101                        \%fc_opts ],
 102        'log' => [ \&show_log, 'Show commit logs',
 103                        { 'limit=i' => \$_limit,
 104                          'revision|r=s' => \$_revision,
 105                          'verbose|v' => \$_verbose,
 106                          'incremental' => \$_incremental,
 107                          'oneline' => \$_oneline,
 108                          'show-commit' => \$_show_commit,
 109                          'authors-file|A=s' => \$_authors,
 110                        } ],
 111);
 112
 113my $cmd;
 114for (my $i = 0; $i < @ARGV; $i++) {
 115        if (defined $cmd{$ARGV[$i]}) {
 116                $cmd = $ARGV[$i];
 117                splice @ARGV, $i, 1;
 118                last;
 119        }
 120};
 121
 122my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
 123
 124read_repo_config(\%opts);
 125my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
 126                                'version|V' => \$_version,
 127                                'id|i=s' => \$GIT_SVN);
 128exit 1 if (!$rv && $cmd ne 'log');
 129
 130set_default_vals();
 131usage(0) if $_help;
 132version() if $_version;
 133usage(1) unless defined $cmd;
 134init_vars();
 135load_authors() if $_authors;
 136load_all_refs() if $_branch_all_refs;
 137svn_compat_check() unless $_use_lib;
 138migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init)$/;
 139$cmd{$cmd}->[0]->(@ARGV);
 140exit 0;
 141
 142####################### primary functions ######################
 143sub usage {
 144        my $exit = shift || 0;
 145        my $fd = $exit ? \*STDERR : \*STDOUT;
 146        print $fd <<"";
 147git-svn - bidirectional operations between a single Subversion tree and git
 148Usage: $0 <command> [options] [arguments]\n
 149
 150        print $fd "Available commands:\n" unless $cmd;
 151
 152        foreach (sort keys %cmd) {
 153                next if $cmd && $cmd ne $_;
 154                print $fd '  ',pack('A13',$_),$cmd{$_}->[1],"\n";
 155                foreach (keys %{$cmd{$_}->[2]}) {
 156                        # prints out arguments as they should be passed:
 157                        my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
 158                        print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
 159                                                        "--$_" : "-$_" }
 160                                                split /\|/,$_)," $x\n";
 161                }
 162        }
 163        print $fd <<"";
 164\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
 165arbitrary identifier if you're tracking multiple SVN branches/repositories in
 166one git repository and want to keep them separate.  See git-svn(1) for more
 167information.
 168
 169        exit $exit;
 170}
 171
 172sub version {
 173        print "git-svn version $VERSION\n";
 174        exit 0;
 175}
 176
 177sub rebuild {
 178        if (quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0")) {
 179                copy_remote_ref();
 180        }
 181        $SVN_URL = shift or undef;
 182        my $newest_rev = 0;
 183        if ($_upgrade) {
 184                sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
 185        } else {
 186                check_upgrade_needed();
 187        }
 188
 189        my $pid = open(my $rev_list,'-|');
 190        defined $pid or croak $!;
 191        if ($pid == 0) {
 192                exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
 193        }
 194        my $latest;
 195        while (<$rev_list>) {
 196                chomp;
 197                my $c = $_;
 198                croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
 199                my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
 200                next if (!@commit); # skip merges
 201                my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
 202                if (!$rev || !$uuid) {
 203                        croak "Unable to extract revision or UUID from ",
 204                                "$c, $commit[$#commit]\n";
 205                }
 206
 207                # if we merged or otherwise started elsewhere, this is
 208                # how we break out of it
 209                next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
 210                next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
 211
 212                unless (defined $latest) {
 213                        if (!$SVN_URL && !$url) {
 214                                croak "SVN repository location required: $url\n";
 215                        }
 216                        $SVN_URL ||= $url;
 217                        $SVN_UUID ||= $uuid;
 218                        setup_git_svn();
 219                        $latest = $rev;
 220                }
 221                revdb_set($REVDB, $rev, $c);
 222                print "r$rev = $c\n";
 223                $newest_rev = $rev if ($rev > $newest_rev);
 224        }
 225        close $rev_list or croak $?;
 226
 227        goto out if $_use_lib;
 228        if (!chdir $SVN_WC) {
 229                svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
 230                chdir $SVN_WC or croak $!;
 231        }
 232
 233        $pid = fork;
 234        defined $pid or croak $!;
 235        if ($pid == 0) {
 236                my @svn_up = qw(svn up);
 237                push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
 238                sys(@svn_up,"-r$newest_rev");
 239                $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
 240                index_changes();
 241                exec('git-write-tree') or croak $!;
 242        }
 243        waitpid $pid, 0;
 244        croak $? if $?;
 245out:
 246        if ($_upgrade) {
 247                print STDERR <<"";
 248Keeping deprecated refs/head/$GIT_SVN-HEAD for now.  Please remove it
 249when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
 250
 251        }
 252}
 253
 254sub init {
 255        $SVN_URL = shift or die "SVN repository location required " .
 256                                "as a command-line argument\n";
 257        $SVN_URL =~ s!/+$!!; # strip trailing slash
 258        unless (-d $GIT_DIR) {
 259                my @init_db = ('git-init-db');
 260                push @init_db, "--template=$_template" if defined $_template;
 261                push @init_db, "--shared" if defined $_shared;
 262                sys(@init_db);
 263        }
 264        setup_git_svn();
 265}
 266
 267sub fetch {
 268        check_upgrade_needed();
 269        $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
 270        my $ret = $_use_lib ? fetch_lib(@_) : fetch_cmd(@_);
 271        if ($ret->{commit} && quiet_run(qw(git-rev-parse --verify
 272                                                refs/heads/master^0))) {
 273                sys(qw(git-update-ref refs/heads/master),$ret->{commit});
 274        }
 275        return $ret;
 276}
 277
 278sub fetch_cmd {
 279        my (@parents) = @_;
 280        my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
 281        unless ($_revision) {
 282                $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
 283        }
 284        push @log_args, "-r$_revision";
 285        push @log_args, '--stop-on-copy' unless $_no_stop_copy;
 286
 287        my $svn_log = svn_log_raw(@log_args);
 288
 289        my $base = next_log_entry($svn_log) or croak "No base revision!\n";
 290        # don't need last_revision from grab_base_rev() because
 291        # user could've specified a different revision to skip (they
 292        # didn't want to import certain revisions into git for whatever
 293        # reason, so trust $base->{revision} instead.
 294        my (undef, $last_commit) = svn_grab_base_rev();
 295        unless (-d $SVN_WC) {
 296                svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
 297                chdir $SVN_WC or croak $!;
 298                read_uuid();
 299                $last_commit = git_commit($base, @parents);
 300                assert_tree($last_commit);
 301        } else {
 302                chdir $SVN_WC or croak $!;
 303                read_uuid();
 304                # looks like a user manually cp'd and svn switch'ed
 305                unless ($last_commit) {
 306                        sys(qw/svn revert -R ./);
 307                        assert_svn_wc_clean($base->{revision});
 308                        $last_commit = git_commit($base, @parents);
 309                        assert_tree($last_commit);
 310                }
 311        }
 312        my @svn_up = qw(svn up);
 313        push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
 314        my $last = $base;
 315        while (my $log_msg = next_log_entry($svn_log)) {
 316                if ($last->{revision} >= $log_msg->{revision}) {
 317                        croak "Out of order: last >= current: ",
 318                                "$last->{revision} >= $log_msg->{revision}\n";
 319                }
 320                # Revert is needed for cases like:
 321                # https://svn.musicpd.org/Jamming/trunk (r166:167), but
 322                # I can't seem to reproduce something like that on a test...
 323                sys(qw/svn revert -R ./);
 324                assert_svn_wc_clean($last->{revision});
 325                sys(@svn_up,"-r$log_msg->{revision}");
 326                $last_commit = git_commit($log_msg, $last_commit, @parents);
 327                $last = $log_msg;
 328        }
 329        close $svn_log->{fh};
 330        $last->{commit} = $last_commit;
 331        return $last;
 332}
 333
 334sub fetch_lib {
 335        my (@parents) = @_;
 336        $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
 337        my $repo;
 338        ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
 339        $SVN_LOG ||= libsvn_connect($repo);
 340        $SVN ||= libsvn_connect($repo);
 341        my ($last_rev, $last_commit) = svn_grab_base_rev();
 342        my ($base, $head) = libsvn_parse_revision($last_rev);
 343        if ($base > $head) {
 344                return { revision => $last_rev, commit => $last_commit }
 345        }
 346        my $index = set_index($GIT_SVN_INDEX);
 347
 348        # limit ourselves and also fork() since get_log won't release memory
 349        # after processing a revision and SVN stuff seems to leak
 350        my $inc = 1000;
 351        my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
 352        read_uuid();
 353        if (defined $last_commit) {
 354                unless (-e $GIT_SVN_INDEX) {
 355                        sys(qw/git-read-tree/, $last_commit);
 356                }
 357                chomp (my $x = `git-write-tree`);
 358                my ($y) = (`git-cat-file commit $last_commit`
 359                                                        =~ /^tree ($sha1)/m);
 360                if ($y ne $x) {
 361                        unlink $GIT_SVN_INDEX or croak $!;
 362                        sys(qw/git-read-tree/, $last_commit);
 363                }
 364                chomp ($x = `git-write-tree`);
 365                if ($y ne $x) {
 366                        print STDERR "trees ($last_commit) $y != $x\n",
 367                                 "Something is seriously wrong...\n";
 368                }
 369        }
 370        while (1) {
 371                # fork, because using SVN::Pool with get_log() still doesn't
 372                # seem to help enough to keep memory usage down.
 373                defined(my $pid = fork) or croak $!;
 374                if (!$pid) {
 375                        $SVN::Error::handler = \&libsvn_skip_unknown_revs;
 376
 377                        # Yes I'm perfectly aware that the fourth argument
 378                        # below is the limit revisions number.  Unfortunately
 379                        # performance sucks with it enabled, so it's much
 380                        # faster to fetch revision ranges instead of relying
 381                        # on the limiter.
 382                        libsvn_get_log($SVN_LOG, '/'.$SVN_PATH,
 383                                        $min, $max, 0, 1, 1,
 384                                sub {
 385                                        my $log_msg;
 386                                        if ($last_commit) {
 387                                                $log_msg = libsvn_fetch(
 388                                                        $last_commit, @_);
 389                                                $last_commit = git_commit(
 390                                                        $log_msg,
 391                                                        $last_commit,
 392                                                        @parents);
 393                                        } else {
 394                                                $log_msg = libsvn_new_tree(@_);
 395                                                $last_commit = git_commit(
 396                                                        $log_msg, @parents);
 397                                        }
 398                                });
 399                        exit 0;
 400                }
 401                waitpid $pid, 0;
 402                croak $? if $?;
 403                ($last_rev, $last_commit) = svn_grab_base_rev();
 404                last if ($max >= $head);
 405                $min = $max + 1;
 406                $max += $inc;
 407                $max = $head if ($max > $head);
 408        }
 409        restore_index($index);
 410        return { revision => $last_rev, commit => $last_commit };
 411}
 412
 413sub commit {
 414        my (@commits) = @_;
 415        check_upgrade_needed();
 416        if ($_stdin || !@commits) {
 417                print "Reading from stdin...\n";
 418                @commits = ();
 419                while (<STDIN>) {
 420                        if (/\b($sha1_short)\b/o) {
 421                                unshift @commits, $1;
 422                        }
 423                }
 424        }
 425        my @revs;
 426        foreach my $c (@commits) {
 427                chomp(my @tmp = safe_qx('git-rev-parse',$c));
 428                if (scalar @tmp == 1) {
 429                        push @revs, $tmp[0];
 430                } elsif (scalar @tmp > 1) {
 431                        push @revs, reverse (safe_qx('git-rev-list',@tmp));
 432                } else {
 433                        die "Failed to rev-parse $c\n";
 434                }
 435        }
 436        chomp @revs;
 437        $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
 438        print "Done committing ",scalar @revs," revisions to SVN\n";
 439}
 440
 441sub commit_cmd {
 442        my (@revs) = @_;
 443
 444        chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
 445        my $info = svn_info('.');
 446        my $fetched = fetch();
 447        if ($info->{Revision} != $fetched->{revision}) {
 448                print STDERR "There are new revisions that were fetched ",
 449                                "and need to be merged (or acknowledged) ",
 450                                "before committing.\n";
 451                exit 1;
 452        }
 453        $info = svn_info('.');
 454        read_uuid($info);
 455        my $last = $fetched;
 456        foreach my $c (@revs) {
 457                my $mods = svn_checkout_tree($last, $c);
 458                if (scalar @$mods == 0) {
 459                        print "Skipping, no changes detected\n";
 460                        next;
 461                }
 462                $last = svn_commit_tree($last, $c);
 463        }
 464}
 465
 466sub commit_lib {
 467        my (@revs) = @_;
 468        my ($r_last, $cmt_last) = svn_grab_base_rev();
 469        defined $r_last or die "Must have an existing revision to commit\n";
 470        my $fetched = fetch();
 471        if ($r_last != $fetched->{revision}) {
 472                print STDERR "There are new revisions that were fetched ",
 473                                "and need to be merged (or acknowledged) ",
 474                                "before committing.\n",
 475                                "last rev: $r_last\n",
 476                                " current: $fetched->{revision}\n";
 477                exit 1;
 478        }
 479        read_uuid();
 480        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
 481        my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
 482
 483        if (defined $LC_ALL) {
 484                $ENV{LC_ALL} = $LC_ALL;
 485        } else {
 486                delete $ENV{LC_ALL};
 487        }
 488        foreach my $c (@revs) {
 489                my $log_msg = get_commit_message($c, $commit_msg);
 490
 491                # fork for each commit because there's a memory leak I
 492                # can't track down... (it's probably in the SVN code)
 493                defined(my $pid = open my $fh, '-|') or croak $!;
 494                if (!$pid) {
 495                        my $ed = SVN::Git::Editor->new(
 496                                        {       r => $r_last,
 497                                                ra => $SVN,
 498                                                c => $c,
 499                                                svn_path => $SVN_PATH
 500                                        },
 501                                        $SVN->get_commit_editor(
 502                                                $log_msg->{msg},
 503                                                sub {
 504                                                        libsvn_commit_cb(
 505                                                                @_, $c,
 506                                                                $log_msg->{msg},
 507                                                                $r_last,
 508                                                                $cmt_last)
 509                                                },
 510                                                @lock)
 511                                        );
 512                        my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
 513                        if (@$mods == 0) {
 514                                print "No changes\nr$r_last = $cmt_last\n";
 515                                $ed->abort_edit;
 516                        } else {
 517                                $ed->close_edit;
 518                        }
 519                        exit 0;
 520                }
 521                my ($r_new, $cmt_new, $no);
 522                while (<$fh>) {
 523                        print $_;
 524                        chomp;
 525                        if (/^r(\d+) = ($sha1)$/o) {
 526                                ($r_new, $cmt_new) = ($1, $2);
 527                        } elsif ($_ eq 'No changes') {
 528                                $no = 1;
 529                        }
 530                }
 531                close $fh or croak $?;
 532                if (! defined $r_new && ! defined $cmt_new) {
 533                        unless ($no) {
 534                                die "Failed to parse revision information\n";
 535                        }
 536                } else {
 537                        ($r_last, $cmt_last) = ($r_new, $cmt_new);
 538                }
 539        }
 540        $ENV{LC_ALL} = 'C';
 541        unlink $commit_msg;
 542}
 543
 544sub show_ignore {
 545        $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
 546        $_use_lib ? show_ignore_lib() : show_ignore_cmd();
 547}
 548
 549sub show_ignore_cmd {
 550        require File::Find or die $!;
 551        if (defined $_revision) {
 552                die "-r/--revision option doesn't work unless the Perl SVN ",
 553                        "libraries are used\n";
 554        }
 555        chdir $SVN_WC or croak $!;
 556        my %ign;
 557        File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
 558                s#^\./##;
 559                @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
 560                }}, no_chdir=>1},'.');
 561
 562        print "\n# /\n";
 563        foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
 564        delete $ign{'.'};
 565        foreach my $i (sort keys %ign) {
 566                print "\n# ",$i,"\n";
 567                foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
 568        }
 569}
 570
 571sub show_ignore_lib {
 572        my $repo;
 573        ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
 574        $SVN ||= libsvn_connect($repo);
 575        my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
 576        libsvn_traverse_ignore(\*STDOUT, $SVN_PATH, $r);
 577}
 578
 579sub graft_branches {
 580        my $gr_file = "$GIT_DIR/info/grafts";
 581        my ($grafts, $comments) = read_grafts($gr_file);
 582        my $gr_sha1;
 583
 584        if (%$grafts) {
 585                # temporarily disable our grafts file to make this idempotent
 586                chomp($gr_sha1 = safe_qx(qw/git-hash-object -w/,$gr_file));
 587                rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
 588        }
 589
 590        my $l_map = read_url_paths();
 591        my @re = map { qr/$_/is } @_opt_m if @_opt_m;
 592        unless ($_no_default_regex) {
 593                push @re, (     qr/\b(?:merge|merging|merged)\s+(\S.+)/is,
 594                                qr/\b(?:from|of)\s+(\S.+)/is );
 595        }
 596        foreach my $u (keys %$l_map) {
 597                if (@re) {
 598                        foreach my $p (keys %{$l_map->{$u}}) {
 599                                graft_merge_msg($grafts,$l_map,$u,$p);
 600                        }
 601                }
 602                unless ($_no_graft_copy) {
 603                        if ($_use_lib) {
 604                                graft_file_copy_lib($grafts,$l_map,$u);
 605                        } else {
 606                                graft_file_copy_cmd($grafts,$l_map,$u);
 607                        }
 608                }
 609        }
 610
 611        write_grafts($grafts, $comments, $gr_file);
 612        unlink "$gr_file~$gr_sha1" if $gr_sha1;
 613}
 614
 615sub multi_init {
 616        my $url = shift;
 617        $_trunk ||= 'trunk';
 618        $_trunk =~ s#/+$##;
 619        $url =~ s#/+$## if $url;
 620        if ($_trunk !~ m#^[a-z\+]+://#) {
 621                $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
 622                unless ($url) {
 623                        print STDERR "E: '$_trunk' is not a complete URL ",
 624                                "and a separate URL is not specified\n";
 625                        exit 1;
 626                }
 627                $_trunk = $url . $_trunk;
 628        }
 629        if ($GIT_SVN eq 'git-svn') {
 630                print "GIT_SVN_ID set to 'trunk' for $_trunk\n";
 631                $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
 632        }
 633        init_vars();
 634        init($_trunk);
 635        complete_url_ls_init($url, $_branches, '--branches/-b', '');
 636        complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
 637}
 638
 639sub multi_fetch {
 640        # try to do trunk first, since branches/tags
 641        # may be descended from it.
 642        if (-e "$GIT_DIR/svn/trunk/info/url") {
 643                fetch_child_id('trunk', @_);
 644        }
 645        rec_fetch('', "$GIT_DIR/svn", @_);
 646}
 647
 648sub show_log {
 649        my (@args) = @_;
 650        my ($r_min, $r_max);
 651        my $r_last = -1; # prevent dupes
 652        rload_authors() if $_authors;
 653        if (defined $TZ) {
 654                $ENV{TZ} = $TZ;
 655        } else {
 656                delete $ENV{TZ};
 657        }
 658        if (defined $_revision) {
 659                if ($_revision =~ /^(\d+):(\d+)$/) {
 660                        ($r_min, $r_max) = ($1, $2);
 661                } elsif ($_revision =~ /^\d+$/) {
 662                        $r_min = $r_max = $_revision;
 663                } else {
 664                        print STDERR "-r$_revision is not supported, use ",
 665                                "standard \'git log\' arguments instead\n";
 666                        exit 1;
 667                }
 668        }
 669
 670        my $pid = open(my $log,'-|');
 671        defined $pid or croak $!;
 672        if (!$pid) {
 673                exec(git_svn_log_cmd($r_min,$r_max), @args) or croak $!;
 674        }
 675        setup_pager();
 676        my (@k, $c, $d);
 677
 678        while (<$log>) {
 679                if (/^commit ($sha1_short)/o) {
 680                        my $cmt = $1;
 681                        if ($c && cmt_showable($c) && $c->{r} != $r_last) {
 682                                $r_last = $c->{r};
 683                                process_commit($c, $r_min, $r_max, \@k) or
 684                                                                goto out;
 685                        }
 686                        $d = undef;
 687                        $c = { c => $cmt };
 688                } elsif (/^author (.+) (\d+) ([\-\+]?\d+)$/) {
 689                        get_author_info($c, $1, $2, $3);
 690                } elsif (/^(?:tree|parent|committer) /) {
 691                        # ignore
 692                } elsif (/^:\d{6} \d{6} $sha1_short/o) {
 693                        push @{$c->{raw}}, $_;
 694                } elsif (/^diff /) {
 695                        $d = 1;
 696                        push @{$c->{diff}}, $_;
 697                } elsif ($d) {
 698                        push @{$c->{diff}}, $_;
 699                } elsif (/^    (git-svn-id:.+)$/) {
 700                        (undef, $c->{r}, undef) = extract_metadata($1);
 701                } elsif (s/^    //) {
 702                        push @{$c->{l}}, $_;
 703                }
 704        }
 705        if ($c && defined $c->{r} && $c->{r} != $r_last) {
 706                $r_last = $c->{r};
 707                process_commit($c, $r_min, $r_max, \@k);
 708        }
 709        if (@k) {
 710                my $swap = $r_max;
 711                $r_max = $r_min;
 712                $r_min = $swap;
 713                process_commit($_, $r_min, $r_max) foreach reverse @k;
 714        }
 715out:
 716        close $log;
 717        print '-' x72,"\n" unless $_incremental || $_oneline;
 718}
 719
 720########################### utility functions #########################
 721
 722sub cmt_showable {
 723        my ($c) = @_;
 724        return 1 if defined $c->{r};
 725        if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
 726                                $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
 727                my @msg = safe_qx(qw/git-cat-file commit/, $c->{c});
 728                shift @msg while ($msg[0] ne "\n");
 729                shift @msg;
 730                @{$c->{l}} = grep !/^git-svn-id: /, @msg;
 731
 732                (undef, $c->{r}, undef) = extract_metadata(
 733                                (grep(/^git-svn-id: /, @msg))[-1]);
 734        }
 735        return defined $c->{r};
 736}
 737
 738sub git_svn_log_cmd {
 739        my ($r_min, $r_max) = @_;
 740        my @cmd = (qw/git-log --abbrev-commit --pretty=raw
 741                        --default/, "refs/remotes/$GIT_SVN");
 742        push @cmd, '--summary' if $_verbose;
 743        return @cmd unless defined $r_max;
 744        if ($r_max == $r_min) {
 745                push @cmd, '--max-count=1';
 746                if (my $c = revdb_get($REVDB, $r_max)) {
 747                        push @cmd, $c;
 748                }
 749        } else {
 750                my ($c_min, $c_max);
 751                $c_max = revdb_get($REVDB, $r_max);
 752                $c_min = revdb_get($REVDB, $r_min);
 753                if ($c_min && $c_max) {
 754                        if ($r_max > $r_max) {
 755                                push @cmd, "$c_min..$c_max";
 756                        } else {
 757                                push @cmd, "$c_max..$c_min";
 758                        }
 759                } elsif ($r_max > $r_min) {
 760                        push @cmd, $c_max;
 761                } else {
 762                        push @cmd, $c_min;
 763                }
 764        }
 765        return @cmd;
 766}
 767
 768sub fetch_child_id {
 769        my $id = shift;
 770        print "Fetching $id\n";
 771        my $ref = "$GIT_DIR/refs/remotes/$id";
 772        my $ca = file_to_s($ref) if (-r $ref);
 773        defined(my $pid = fork) or croak $!;
 774        if (!$pid) {
 775                $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
 776                init_vars();
 777                fetch(@_);
 778                exit 0;
 779        }
 780        waitpid $pid, 0;
 781        croak $? if $?;
 782        return unless $_repack || -r $ref;
 783
 784        my $cb = file_to_s($ref);
 785
 786        defined($pid = open my $fh, '-|') or croak $!;
 787        my $url = file_to_s("$GIT_DIR/svn/$id/info/url");
 788        $url = qr/\Q$url\E/;
 789        if (!$pid) {
 790                exec qw/git-rev-list --pretty=raw/,
 791                                $ca ? "$ca..$cb" : $cb or croak $!;
 792        }
 793        while (<$fh>) {
 794                if (/^    git-svn-id: $url\@\d+ [a-f0-9\-]+$/) {
 795                        check_repack();
 796                } elsif (/^    git-svn-id: \S+\@\d+ [a-f0-9\-]+$/) {
 797                        last;
 798                }
 799        }
 800        close $fh;
 801}
 802
 803sub rec_fetch {
 804        my ($pfx, $p, @args) = @_;
 805        my @dir;
 806        foreach (sort <$p/*>) {
 807                if (-r "$_/info/url") {
 808                        $pfx .= '/' if $pfx && $pfx !~ m!/$!;
 809                        my $id = $pfx . basename $_;
 810                        next if $id eq 'trunk';
 811                        fetch_child_id($id, @args);
 812                } elsif (-d $_) {
 813                        push @dir, $_;
 814                }
 815        }
 816        foreach (@dir) {
 817                my $x = $_;
 818                $x =~ s!^\Q$GIT_DIR\E/svn/!!;
 819                rec_fetch($x, $_);
 820        }
 821}
 822
 823sub complete_url_ls_init {
 824        my ($url, $var, $switch, $pfx) = @_;
 825        unless ($var) {
 826                print STDERR "W: $switch not specified\n";
 827                return;
 828        }
 829        $var =~ s#/+$##;
 830        if ($var !~ m#^[a-z\+]+://#) {
 831                $var = '/' . $var if ($var !~ m#^/#);
 832                unless ($url) {
 833                        print STDERR "E: '$var' is not a complete URL ",
 834                                "and a separate URL is not specified\n";
 835                        exit 1;
 836                }
 837                $var = $url . $var;
 838        }
 839        chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
 840                                : safe_qx(qw/svn ls --non-interactive/, $var));
 841        my $old = $GIT_SVN;
 842        defined(my $pid = fork) or croak $!;
 843        if (!$pid) {
 844                foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
 845                        $u =~ s#/+$##;
 846                        if ($u !~ m!\Q$var\E/(.+)$!) {
 847                                print STDERR "W: Unrecognized URL: $u\n";
 848                                die "This should never happen\n";
 849                        }
 850                        my $id = $pfx.$1;
 851                        print "init $u => $id\n";
 852                        $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
 853                        init_vars();
 854                        init($u);
 855                }
 856                exit 0;
 857        }
 858        waitpid $pid, 0;
 859        croak $? if $?;
 860}
 861
 862sub common_prefix {
 863        my $paths = shift;
 864        my %common;
 865        foreach (@$paths) {
 866                my @tmp = split m#/#, $_;
 867                my $p = '';
 868                while (my $x = shift @tmp) {
 869                        $p .= "/$x";
 870                        $common{$p} ||= 0;
 871                        $common{$p}++;
 872                }
 873        }
 874        foreach (sort {length $b <=> length $a} keys %common) {
 875                if ($common{$_} == @$paths) {
 876                        return $_;
 877                }
 878        }
 879        return '';
 880}
 881
 882# this isn't funky-filename safe, but good enough for now...
 883sub graft_file_copy_cmd {
 884        my ($grafts, $l_map, $u) = @_;
 885        my $paths = $l_map->{$u};
 886        my $pfx = common_prefix([keys %$paths]);
 887        $SVN_URL ||= $u.$pfx;
 888        my $pid = open my $fh, '-|';
 889        defined $pid or croak $!;
 890        unless ($pid) {
 891                my @exec = qw/svn log -v/;
 892                push @exec, "-r$_revision" if defined $_revision;
 893                exec @exec, $u.$pfx or croak $!;
 894        }
 895        my ($r, $mp) = (undef, undef);
 896        while (<$fh>) {
 897                chomp;
 898                if (/^\-{72}$/) {
 899                        $mp = $r = undef;
 900                } elsif (/^r(\d+) \| /) {
 901                        $r = $1 unless defined $r;
 902                } elsif (/^Changed paths:/) {
 903                        $mp = 1;
 904                } elsif ($mp && m#^   [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
 905                        my ($p1, $p0, $r0) = ($1, $2, $3);
 906                        my $c = find_graft_path_commit($paths, $p1, $r);
 907                        next unless $c;
 908                        find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
 909                }
 910        }
 911}
 912
 913sub graft_file_copy_lib {
 914        my ($grafts, $l_map, $u) = @_;
 915        my $tree_paths = $l_map->{$u};
 916        my $pfx = common_prefix([keys %$tree_paths]);
 917        my ($repo, $path) = repo_path_split($u.$pfx);
 918        $SVN_LOG ||= libsvn_connect($repo);
 919        $SVN ||= libsvn_connect($repo);
 920
 921        my ($base, $head) = libsvn_parse_revision();
 922        my $inc = 1000;
 923        my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
 924        my $eh = $SVN::Error::handler;
 925        $SVN::Error::handler = \&libsvn_skip_unknown_revs;
 926        while (1) {
 927                my $pool = SVN::Pool->new;
 928                libsvn_get_log($SVN_LOG, "/$path", $min, $max, 0, 1, 1,
 929                        sub {
 930                                libsvn_graft_file_copies($grafts, $tree_paths,
 931                                                        $path, @_);
 932                        }, $pool);
 933                $pool->clear;
 934                last if ($max >= $head);
 935                $min = $max + 1;
 936                $max += $inc;
 937                $max = $head if ($max > $head);
 938        }
 939        $SVN::Error::handler = $eh;
 940}
 941
 942sub process_merge_msg_matches {
 943        my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
 944        my (@strong, @weak);
 945        foreach (@matches) {
 946                # merging with ourselves is not interesting
 947                next if $_ eq $p;
 948                if ($l_map->{$u}->{$_}) {
 949                        push @strong, $_;
 950                } else {
 951                        push @weak, $_;
 952                }
 953        }
 954        foreach my $w (@weak) {
 955                last if @strong;
 956                # no exact match, use branch name as regexp.
 957                my $re = qr/\Q$w\E/i;
 958                foreach (keys %{$l_map->{$u}}) {
 959                        if (/$re/) {
 960                                push @strong, $_;
 961                                last;
 962                        }
 963                }
 964                last if @strong;
 965                $w = basename($w);
 966                $re = qr/\Q$w\E/i;
 967                foreach (keys %{$l_map->{$u}}) {
 968                        if (/$re/) {
 969                                push @strong, $_;
 970                                last;
 971                        }
 972                }
 973        }
 974        my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
 975                                        \s(?:[a-f\d\-]+)$/xsm);
 976        unless (defined $rev) {
 977                ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
 978                                        \@(?:[a-f\d\-]+)/xsm);
 979                return unless defined $rev;
 980        }
 981        foreach my $m (@strong) {
 982                my ($r0, $s0) = find_rev_before($rev, $m);
 983                $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
 984        }
 985}
 986
 987sub graft_merge_msg {
 988        my ($grafts, $l_map, $u, $p, @re) = @_;
 989
 990        my $x = $l_map->{$u}->{$p};
 991        my $rl = rev_list_raw($x);
 992        while (my $c = next_rev_list_entry($rl)) {
 993                foreach my $re (@re) {
 994                        my (@br) = ($c->{m} =~ /$re/g);
 995                        next unless @br;
 996                        process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
 997                }
 998        }
 999}
1000
1001sub read_uuid {
1002        return if $SVN_UUID;
1003        if ($_use_lib) {
1004                my $pool = SVN::Pool->new;
1005                $SVN_UUID = $SVN->get_uuid($pool);
1006                $pool->clear;
1007        } else {
1008                my $info = shift || svn_info('.');
1009                $SVN_UUID = $info->{'Repository UUID'} or
1010                                        croak "Repository UUID unreadable\n";
1011        }
1012}
1013
1014sub quiet_run {
1015        my $pid = fork;
1016        defined $pid or croak $!;
1017        if (!$pid) {
1018                open my $null, '>', '/dev/null' or croak $!;
1019                open STDERR, '>&', $null or croak $!;
1020                open STDOUT, '>&', $null or croak $!;
1021                exec @_ or croak $!;
1022        }
1023        waitpid $pid, 0;
1024        return $?;
1025}
1026
1027sub repo_path_split {
1028        my $full_url = shift;
1029        $full_url =~ s#/+$##;
1030
1031        foreach (@repo_path_split_cache) {
1032                if ($full_url =~ s#$_##) {
1033                        my $u = $1;
1034                        $full_url =~ s#^/+##;
1035                        return ($u, $full_url);
1036                }
1037        }
1038
1039        my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
1040        $path =~ s#^/+##;
1041        my @paths = split(m#/+#, $path);
1042
1043        if ($_use_lib) {
1044                while (1) {
1045                        $SVN = libsvn_connect($url);
1046                        last if (defined $SVN &&
1047                                defined eval { $SVN->get_latest_revnum });
1048                        my $n = shift @paths || last;
1049                        $url .= "/$n";
1050                }
1051        } else {
1052                while (quiet_run(qw/svn ls --non-interactive/, $url)) {
1053                        my $n = shift @paths || last;
1054                        $url .= "/$n";
1055                }
1056        }
1057        push @repo_path_split_cache, qr/^(\Q$url\E)/;
1058        $path = join('/',@paths);
1059        return ($url, $path);
1060}
1061
1062sub setup_git_svn {
1063        defined $SVN_URL or croak "SVN repository location required\n";
1064        unless (-d $GIT_DIR) {
1065                croak "GIT_DIR=$GIT_DIR does not exist!\n";
1066        }
1067        mkpath([$GIT_SVN_DIR]);
1068        mkpath(["$GIT_SVN_DIR/info"]);
1069        open my $fh, '>>',$REVDB or croak $!;
1070        close $fh;
1071        s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1072
1073}
1074
1075sub assert_svn_wc_clean {
1076        return if $_use_lib;
1077        my ($svn_rev) = @_;
1078        croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
1079        my $lcr = svn_info('.')->{'Last Changed Rev'};
1080        if ($svn_rev != $lcr) {
1081                print STDERR "Checking for copy-tree ... ";
1082                my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1083                                                "-r$lcr:$svn_rev")));
1084                if (@diff) {
1085                        croak "Nope!  Expected r$svn_rev, got r$lcr\n";
1086                } else {
1087                        print STDERR "OK!\n";
1088                }
1089        }
1090        my @status = grep(!/^Performing status on external/,(`svn status`));
1091        @status = grep(!/^\s*$/,@status);
1092        if (scalar @status) {
1093                print STDERR "Tree ($SVN_WC) is not clean:\n";
1094                print STDERR $_ foreach @status;
1095                croak;
1096        }
1097}
1098
1099sub get_tree_from_treeish {
1100        my ($treeish) = @_;
1101        croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1102        chomp(my $type = `git-cat-file -t $treeish`);
1103        my $expected;
1104        while ($type eq 'tag') {
1105                chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1106        }
1107        if ($type eq 'commit') {
1108                $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1109                ($expected) = ($expected =~ /^tree ($sha1)$/);
1110                die "Unable to get tree from $treeish\n" unless $expected;
1111        } elsif ($type eq 'tree') {
1112                $expected = $treeish;
1113        } else {
1114                die "$treeish is a $type, expected tree, tag or commit\n";
1115        }
1116        return $expected;
1117}
1118
1119sub assert_tree {
1120        return if $_use_lib;
1121        my ($treeish) = @_;
1122        my $expected = get_tree_from_treeish($treeish);
1123
1124        my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1125        if (-e $tmpindex) {
1126                unlink $tmpindex or croak $!;
1127        }
1128        my $old_index = set_index($tmpindex);
1129        index_changes(1);
1130        chomp(my $tree = `git-write-tree`);
1131        restore_index($old_index);
1132        if ($tree ne $expected) {
1133                croak "Tree mismatch, Got: $tree, Expected: $expected\n";
1134        }
1135        unlink $tmpindex;
1136}
1137
1138sub parse_diff_tree {
1139        my $diff_fh = shift;
1140        local $/ = "\0";
1141        my $state = 'meta';
1142        my @mods;
1143        while (<$diff_fh>) {
1144                chomp $_; # this gets rid of the trailing "\0"
1145                if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1146                                        $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1147                        push @mods, {   mode_a => $1, mode_b => $2,
1148                                        sha1_b => $3, chg => $4 };
1149                        if ($4 =~ /^(?:C|R)$/) {
1150                                $state = 'file_a';
1151                        } else {
1152                                $state = 'file_b';
1153                        }
1154                } elsif ($state eq 'file_a') {
1155                        my $x = $mods[$#mods] or croak "Empty array\n";
1156                        if ($x->{chg} !~ /^(?:C|R)$/) {
1157                                croak "Error parsing $_, $x->{chg}\n";
1158                        }
1159                        $x->{file_a} = $_;
1160                        $state = 'file_b';
1161                } elsif ($state eq 'file_b') {
1162                        my $x = $mods[$#mods] or croak "Empty array\n";
1163                        if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1164                                croak "Error parsing $_, $x->{chg}\n";
1165                        }
1166                        if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1167                                croak "Error parsing $_, $x->{chg}\n";
1168                        }
1169                        $x->{file_b} = $_;
1170                        $state = 'meta';
1171                } else {
1172                        croak "Error parsing $_\n";
1173                }
1174        }
1175        close $diff_fh or croak $?;
1176
1177        return \@mods;
1178}
1179
1180sub svn_check_prop_executable {
1181        my $m = shift;
1182        return if -l $m->{file_b};
1183        if ($m->{mode_b} =~ /755$/) {
1184                chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1185                if ($m->{mode_a} !~ /755$/) {
1186                        sys(qw(svn propset svn:executable 1), $m->{file_b});
1187                }
1188                -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
1189        } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1190                sys(qw(svn propdel svn:executable), $m->{file_b});
1191                chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1192                -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
1193        }
1194}
1195
1196sub svn_ensure_parent_path {
1197        my $dir_b = dirname(shift);
1198        svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1199        mkpath([$dir_b]) unless (-d $dir_b);
1200        sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1201}
1202
1203sub precommit_check {
1204        my $mods = shift;
1205        my (%rm_file, %rmdir_check, %added_check);
1206
1207        my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1208        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1209                if ($m->{chg} eq 'R') {
1210                        if (-d $m->{file_b}) {
1211                                err_dir_to_file("$m->{file_a} => $m->{file_b}");
1212                        }
1213                        # dir/$file => dir/file/$file
1214                        my $dirname = dirname($m->{file_b});
1215                        while ($dirname ne File::Spec->curdir) {
1216                                if ($dirname ne $m->{file_a}) {
1217                                        $dirname = dirname($dirname);
1218                                        next;
1219                                }
1220                                err_file_to_dir("$m->{file_a} => $m->{file_b}");
1221                        }
1222                        # baz/zzz => baz (baz is a file)
1223                        $dirname = dirname($m->{file_a});
1224                        while ($dirname ne File::Spec->curdir) {
1225                                if ($dirname ne $m->{file_b}) {
1226                                        $dirname = dirname($dirname);
1227                                        next;
1228                                }
1229                                err_dir_to_file("$m->{file_a} => $m->{file_b}");
1230                        }
1231                }
1232                if ($m->{chg} =~ /^(D|R)$/) {
1233                        my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1234                        $rm_file{ $m->{$t} } = 1;
1235                        my $dirname = dirname( $m->{$t} );
1236                        my $basename = basename( $m->{$t} );
1237                        $rmdir_check{$dirname}->{$basename} = 1;
1238                } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1239                        if (-d $m->{file_b}) {
1240                                err_dir_to_file($m->{file_b});
1241                        }
1242                        my $dirname = dirname( $m->{file_b} );
1243                        my $basename = basename( $m->{file_b} );
1244                        $added_check{$dirname}->{$basename} = 1;
1245                        while ($dirname ne File::Spec->curdir) {
1246                                if ($rm_file{$dirname}) {
1247                                        err_file_to_dir($m->{file_b});
1248                                }
1249                                $dirname = dirname $dirname;
1250                        }
1251                }
1252        }
1253        return (\%rmdir_check, \%added_check);
1254
1255        sub err_dir_to_file {
1256                my $file = shift;
1257                print STDERR "Node change from directory to file ",
1258                                "is not supported by Subversion: ",$file,"\n";
1259                exit 1;
1260        }
1261        sub err_file_to_dir {
1262                my $file = shift;
1263                print STDERR "Node change from file to directory ",
1264                                "is not supported by Subversion: ",$file,"\n";
1265                exit 1;
1266        }
1267}
1268
1269
1270sub get_diff {
1271        my ($from, $treeish) = @_;
1272        assert_tree($from);
1273        print "diff-tree $from $treeish\n";
1274        my $pid = open my $diff_fh, '-|';
1275        defined $pid or croak $!;
1276        if ($pid == 0) {
1277                my @diff_tree = qw(git-diff-tree -z -r);
1278                if ($_cp_similarity) {
1279                        push @diff_tree, "-C$_cp_similarity";
1280                } else {
1281                        push @diff_tree, '-C';
1282                }
1283                push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1284                push @diff_tree, "-l$_l" if defined $_l;
1285                exec(@diff_tree, $from, $treeish) or croak $!;
1286        }
1287        return parse_diff_tree($diff_fh);
1288}
1289
1290sub svn_checkout_tree {
1291        my ($from, $treeish) = @_;
1292        my $mods = get_diff($from->{commit}, $treeish);
1293        return $mods unless (scalar @$mods);
1294        my ($rm, $add) = precommit_check($mods);
1295
1296        my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1297        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1298                if ($m->{chg} eq 'C') {
1299                        svn_ensure_parent_path( $m->{file_b} );
1300                        sys(qw(svn cp),         $m->{file_a}, $m->{file_b});
1301                        apply_mod_line_blob($m);
1302                        svn_check_prop_executable($m);
1303                } elsif ($m->{chg} eq 'D') {
1304                        sys(qw(svn rm --force), $m->{file_b});
1305                } elsif ($m->{chg} eq 'R') {
1306                        svn_ensure_parent_path( $m->{file_b} );
1307                        sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
1308                        apply_mod_line_blob($m);
1309                        svn_check_prop_executable($m);
1310                } elsif ($m->{chg} eq 'M') {
1311                        apply_mod_line_blob($m);
1312                        svn_check_prop_executable($m);
1313                } elsif ($m->{chg} eq 'T') {
1314                        sys(qw(svn rm --force),$m->{file_b});
1315                        apply_mod_line_blob($m);
1316                        sys(qw(svn add), $m->{file_b});
1317                        svn_check_prop_executable($m);
1318                } elsif ($m->{chg} eq 'A') {
1319                        svn_ensure_parent_path( $m->{file_b} );
1320                        apply_mod_line_blob($m);
1321                        sys(qw(svn add), $m->{file_b});
1322                        svn_check_prop_executable($m);
1323                } else {
1324                        croak "Invalid chg: $m->{chg}\n";
1325                }
1326        }
1327
1328        assert_tree($treeish);
1329        if ($_rmdir) { # remove empty directories
1330                handle_rmdir($rm, $add);
1331        }
1332        assert_tree($treeish);
1333        return $mods;
1334}
1335
1336sub libsvn_checkout_tree {
1337        my ($from, $treeish, $ed) = @_;
1338        my $mods = get_diff($from, $treeish);
1339        return $mods unless (scalar @$mods);
1340        my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1341        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1342                my $f = $m->{chg};
1343                if (defined $o{$f}) {
1344                        $ed->$f($m);
1345                } else {
1346                        croak "Invalid change type: $f\n";
1347                }
1348        }
1349        $ed->rmdirs if $_rmdir;
1350        return $mods;
1351}
1352
1353# svn ls doesn't work with respect to the current working tree, but what's
1354# in the repository.  There's not even an option for it... *sigh*
1355# (added files don't show up and removed files remain in the ls listing)
1356sub svn_ls_current {
1357        my ($dir, $rm, $add) = @_;
1358        chomp(my @ls = safe_qx('svn','ls',$dir));
1359        my @ret = ();
1360        foreach (@ls) {
1361                s#/$##; # trailing slashes are evil
1362                push @ret, $_ unless $rm->{$dir}->{$_};
1363        }
1364        if (exists $add->{$dir}) {
1365                push @ret, keys %{$add->{$dir}};
1366        }
1367        return \@ret;
1368}
1369
1370sub handle_rmdir {
1371        my ($rm, $add) = @_;
1372
1373        foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1374                my $ls = svn_ls_current($dir, $rm, $add);
1375                next if (scalar @$ls);
1376                sys(qw(svn rm --force),$dir);
1377
1378                my $dn = dirname $dir;
1379                $rm->{ $dn }->{ basename $dir } = 1;
1380                $ls = svn_ls_current($dn, $rm, $add);
1381                while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1382                        sys(qw(svn rm --force),$dn);
1383                        $dir = basename $dn;
1384                        $dn = dirname $dn;
1385                        $rm->{ $dn }->{ $dir } = 1;
1386                        $ls = svn_ls_current($dn, $rm, $add);
1387                }
1388        }
1389}
1390
1391sub get_commit_message {
1392        my ($commit, $commit_msg) = (@_);
1393        my %log_msg = ( msg => '' );
1394        open my $msg, '>', $commit_msg or croak $!;
1395
1396        print "commit: $commit\n";
1397        chomp(my $type = `git-cat-file -t $commit`);
1398        if ($type eq 'commit') {
1399                my $pid = open my $msg_fh, '-|';
1400                defined $pid or croak $!;
1401
1402                if ($pid == 0) {
1403                        exec(qw(git-cat-file commit), $commit) or croak $!;
1404                }
1405                my $in_msg = 0;
1406                while (<$msg_fh>) {
1407                        if (!$in_msg) {
1408                                $in_msg = 1 if (/^\s*$/);
1409                        } elsif (/^git-svn-id: /) {
1410                                # skip this, we regenerate the correct one
1411                                # on re-fetch anyways
1412                        } else {
1413                                print $msg $_ or croak $!;
1414                        }
1415                }
1416                close $msg_fh or croak $?;
1417        }
1418        close $msg or croak $!;
1419
1420        if ($_edit || ($type eq 'tree')) {
1421                my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1422                system($editor, $commit_msg);
1423        }
1424
1425        # file_to_s removes all trailing newlines, so just use chomp() here:
1426        open $msg, '<', $commit_msg or croak $!;
1427        { local $/; chomp($log_msg{msg} = <$msg>); }
1428        close $msg or croak $!;
1429
1430        return \%log_msg;
1431}
1432
1433sub svn_commit_tree {
1434        my ($last, $commit) = @_;
1435        my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1436        my $log_msg = get_commit_message($commit, $commit_msg);
1437        my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
1438        print "Committing $commit: $oneline\n";
1439
1440        if (defined $LC_ALL) {
1441                $ENV{LC_ALL} = $LC_ALL;
1442        } else {
1443                delete $ENV{LC_ALL};
1444        }
1445        my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
1446        $ENV{LC_ALL} = 'C';
1447        unlink $commit_msg;
1448        my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1449        if (!defined $committed) {
1450                my $out = join("\n",@ci_output);
1451                print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1452                                $out, "\n\nAssuming English locale...";
1453                ($committed) = ($out =~ /^Committed revision \d+\./sm);
1454                defined $committed or die " FAILED!\n",
1455                        "Commit output failed to parse committed revision!\n",
1456                print STDERR " OK\n";
1457        }
1458
1459        my @svn_up = qw(svn up);
1460        push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
1461        if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
1462                push @svn_up, "-r$committed";
1463                sys(@svn_up);
1464                my $info = svn_info('.');
1465                my $date = $info->{'Last Changed Date'} or die "Missing date\n";
1466                if ($info->{'Last Changed Rev'} != $committed) {
1467                        croak "$info->{'Last Changed Rev'} != $committed\n"
1468                }
1469                my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1470                                        /(\d{4})\-(\d\d)\-(\d\d)\s
1471                                         (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1472                                         or croak "Failed to parse date: $date\n";
1473                $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1474                $log_msg->{author} = $info->{'Last Changed Author'};
1475                $log_msg->{revision} = $committed;
1476                $log_msg->{msg} .= "\n";
1477                $log_msg->{parents} = [ $last->{commit} ];
1478                $log_msg->{commit} = git_commit($log_msg, $commit);
1479                return $log_msg;
1480        }
1481        # resync immediately
1482        push @svn_up, "-r$last->{revision}";
1483        sys(@svn_up);
1484        return fetch("$committed=$commit");
1485}
1486
1487sub rev_list_raw {
1488        my (@args) = @_;
1489        my $pid = open my $fh, '-|';
1490        defined $pid or croak $!;
1491        if (!$pid) {
1492                exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1493        }
1494        return { fh => $fh, t => { } };
1495}
1496
1497sub next_rev_list_entry {
1498        my $rl = shift;
1499        my $fh = $rl->{fh};
1500        my $x = $rl->{t};
1501        while (<$fh>) {
1502                if (/^commit ($sha1)$/o) {
1503                        if ($x->{c}) {
1504                                $rl->{t} = { c => $1 };
1505                                return $x;
1506                        } else {
1507                                $x->{c} = $1;
1508                        }
1509                } elsif (/^parent ($sha1)$/o) {
1510                        $x->{p}->{$1} = 1;
1511                } elsif (s/^    //) {
1512                        $x->{m} ||= '';
1513                        $x->{m} .= $_;
1514                }
1515        }
1516        return ($x != $rl->{t}) ? $x : undef;
1517}
1518
1519# read the entire log into a temporary file (which is removed ASAP)
1520# and store the file handle + parser state
1521sub svn_log_raw {
1522        my (@log_args) = @_;
1523        my $log_fh = IO::File->new_tmpfile or croak $!;
1524        my $pid = fork;
1525        defined $pid or croak $!;
1526        if (!$pid) {
1527                open STDOUT, '>&', $log_fh or croak $!;
1528                exec (qw(svn log), @log_args) or croak $!
1529        }
1530        waitpid $pid, 0;
1531        croak $? if $?;
1532        seek $log_fh, 0, 0 or croak $!;
1533        return { state => 'sep', fh => $log_fh };
1534}
1535
1536sub next_log_entry {
1537        my $log = shift; # retval of svn_log_raw()
1538        my $ret = undef;
1539        my $fh = $log->{fh};
1540
1541        while (<$fh>) {
1542                chomp;
1543                if (/^\-{72}$/) {
1544                        if ($log->{state} eq 'msg') {
1545                                if ($ret->{lines}) {
1546                                        $ret->{msg} .= $_."\n";
1547                                        unless(--$ret->{lines}) {
1548                                                $log->{state} = 'sep';
1549                                        }
1550                                } else {
1551                                        croak "Log parse error at: $_\n",
1552                                                $ret->{revision},
1553                                                "\n";
1554                                }
1555                                next;
1556                        }
1557                        if ($log->{state} ne 'sep') {
1558                                croak "Log parse error at: $_\n",
1559                                        "state: $log->{state}\n",
1560                                        $ret->{revision},
1561                                        "\n";
1562                        }
1563                        $log->{state} = 'rev';
1564
1565                        # if we have an empty log message, put something there:
1566                        if ($ret) {
1567                                $ret->{msg} ||= "\n";
1568                                delete $ret->{lines};
1569                                return $ret;
1570                        }
1571                        next;
1572                }
1573                if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
1574                        my $rev = $1;
1575                        my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1576                        ($lines) = ($lines =~ /(\d+)/);
1577                        my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1578                                        /(\d{4})\-(\d\d)\-(\d\d)\s
1579                                         (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1580                                         or croak "Failed to parse date: $date\n";
1581                        $ret = {        revision => $rev,
1582                                        date => "$tz $Y-$m-$d $H:$M:$S",
1583                                        author => $author,
1584                                        lines => $lines,
1585                                        msg => '' };
1586                        if (defined $_authors && ! defined $users{$author}) {
1587                                die "Author: $author not defined in ",
1588                                                "$_authors file\n";
1589                        }
1590                        $log->{state} = 'msg_start';
1591                        next;
1592                }
1593                # skip the first blank line of the message:
1594                if ($log->{state} eq 'msg_start' && /^$/) {
1595                        $log->{state} = 'msg';
1596                } elsif ($log->{state} eq 'msg') {
1597                        if ($ret->{lines}) {
1598                                $ret->{msg} .= $_."\n";
1599                                unless (--$ret->{lines}) {
1600                                        $log->{state} = 'sep';
1601                                }
1602                        } else {
1603                                croak "Log parse error at: $_\n",
1604                                        $ret->{revision},"\n";
1605                        }
1606                }
1607        }
1608        return $ret;
1609}
1610
1611sub svn_info {
1612        my $url = shift || $SVN_URL;
1613
1614        my $pid = open my $info_fh, '-|';
1615        defined $pid or croak $!;
1616
1617        if ($pid == 0) {
1618                exec(qw(svn info),$url) or croak $!;
1619        }
1620
1621        my $ret = {};
1622        # only single-lines seem to exist in svn info output
1623        while (<$info_fh>) {
1624                chomp $_;
1625                if (m#^([^:]+)\s*:\s*(\S.*)$#) {
1626                        $ret->{$1} = $2;
1627                        push @{$ret->{-order}}, $1;
1628                }
1629        }
1630        close $info_fh or croak $?;
1631        return $ret;
1632}
1633
1634sub sys { system(@_) == 0 or croak $? }
1635
1636sub eol_cp {
1637        my ($from, $to) = @_;
1638        my $es = svn_propget_base('svn:eol-style', $to);
1639        open my $rfd, '<', $from or croak $!;
1640        binmode $rfd or croak $!;
1641        open my $wfd, '>', $to or croak $!;
1642        binmode $wfd or croak $!;
1643        eol_cp_fd($rfd, $wfd, $es);
1644        close $rfd or croak $!;
1645        close $wfd or croak $!;
1646}
1647
1648sub eol_cp_fd {
1649        my ($rfd, $wfd, $es) = @_;
1650        my $eol = defined $es ? $EOL{$es} : undef;
1651        my $buf;
1652        use bytes;
1653        while (1) {
1654                my ($r, $w, $t);
1655                defined($r = sysread($rfd, $buf, 4096)) or croak $!;
1656                return unless $r;
1657                if ($eol) {
1658                        if ($buf =~ /\015$/) {
1659                                my $c;
1660                                defined($r = sysread($rfd,$c,1)) or croak $!;
1661                                $buf .= $c if $r > 0;
1662                        }
1663                        $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
1664                        $r = length($buf);
1665                }
1666                for ($w = 0; $w < $r; $w += $t) {
1667                        $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
1668                }
1669        }
1670        no bytes;
1671}
1672
1673sub do_update_index {
1674        my ($z_cmd, $cmd, $no_text_base) = @_;
1675
1676        my $z = open my $p, '-|';
1677        defined $z or croak $!;
1678        unless ($z) { exec @$z_cmd or croak $! }
1679
1680        my $pid = open my $ui, '|-';
1681        defined $pid or croak $!;
1682        unless ($pid) {
1683                exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1684        }
1685        local $/ = "\0";
1686        while (my $x = <$p>) {
1687                chomp $x;
1688                if (!$no_text_base && lstat $x && ! -l _ &&
1689                                svn_propget_base('svn:keywords', $x)) {
1690                        my $mode = -x _ ? 0755 : 0644;
1691                        my ($v,$d,$f) = File::Spec->splitpath($x);
1692                        my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1693                                                'text-base',"$f.svn-base");
1694                        $tb =~ s#^/##;
1695                        unless (-f $tb) {
1696                                $tb = File::Spec->catfile($d, '.svn',
1697                                                'text-base',"$f.svn-base");
1698                                $tb =~ s#^/##;
1699                        }
1700                        unlink $x or croak $!;
1701                        eol_cp($tb, $x);
1702                        chmod(($mode &~ umask), $x) or croak $!;
1703                }
1704                print $ui $x,"\0";
1705        }
1706        close $ui or croak $?;
1707}
1708
1709sub index_changes {
1710        return if $_use_lib;
1711
1712        if (!-f "$GIT_SVN_DIR/info/exclude") {
1713                open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1714                print $fd '.svn',"\n";
1715                close $fd or croak $!;
1716        }
1717        my $no_text_base = shift;
1718        do_update_index([qw/git-diff-files --name-only -z/],
1719                        'remove',
1720                        $no_text_base);
1721        do_update_index([qw/git-ls-files -z --others/,
1722                                "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1723                        'add',
1724                        $no_text_base);
1725}
1726
1727sub s_to_file {
1728        my ($str, $file, $mode) = @_;
1729        open my $fd,'>',$file or croak $!;
1730        print $fd $str,"\n" or croak $!;
1731        close $fd or croak $!;
1732        chmod ($mode &~ umask, $file) if (defined $mode);
1733}
1734
1735sub file_to_s {
1736        my $file = shift;
1737        open my $fd,'<',$file or croak "$!: file: $file\n";
1738        local $/;
1739        my $ret = <$fd>;
1740        close $fd or croak $!;
1741        $ret =~ s/\s*$//s;
1742        return $ret;
1743}
1744
1745sub assert_revision_unknown {
1746        my $r = shift;
1747        if (my $c = revdb_get($REVDB, $r)) {
1748                croak "$r = $c already exists! Why are we refetching it?";
1749        }
1750}
1751
1752sub trees_eq {
1753        my ($x, $y) = @_;
1754        my @x = safe_qx('git-cat-file','commit',$x);
1755        my @y = safe_qx('git-cat-file','commit',$y);
1756        if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1757                                || $y[0] !~ /^tree $sha1\n$/) {
1758                print STDERR "Trees not equal: $y[0] != $x[0]\n";
1759                return 0
1760        }
1761        return 1;
1762}
1763
1764sub git_commit {
1765        my ($log_msg, @parents) = @_;
1766        assert_revision_unknown($log_msg->{revision});
1767        map_tree_joins() if (@_branch_from && !%tree_map);
1768
1769        my (@tmp_parents, @exec_parents, %seen_parent);
1770        if (my $lparents = $log_msg->{parents}) {
1771                @tmp_parents = @$lparents
1772        }
1773        # commit parents can be conditionally bound to a particular
1774        # svn revision via: "svn_revno=commit_sha1", filter them out here:
1775        foreach my $p (@parents) {
1776                next unless defined $p;
1777                if ($p =~ /^(\d+)=($sha1_short)$/o) {
1778                        if ($1 == $log_msg->{revision}) {
1779                                push @tmp_parents, $2;
1780                        }
1781                } else {
1782                        push @tmp_parents, $p if $p =~ /$sha1_short/o;
1783                }
1784        }
1785        my $tree = $log_msg->{tree};
1786        if (!defined $tree) {
1787                my $index = set_index($GIT_SVN_INDEX);
1788                index_changes();
1789                chomp($tree = `git-write-tree`);
1790                croak $? if $?;
1791                restore_index($index);
1792        }
1793        if (exists $tree_map{$tree}) {
1794                push @tmp_parents, @{$tree_map{$tree}};
1795        }
1796        foreach (@tmp_parents) {
1797                next if $seen_parent{$_};
1798                $seen_parent{$_} = 1;
1799                push @exec_parents, $_;
1800                # MAXPARENT is defined to 16 in commit-tree.c:
1801                last if @exec_parents > 16;
1802        }
1803
1804        defined(my $pid = open my $out_fh, '-|') or croak $!;
1805        if ($pid == 0) {
1806                my $msg_fh = IO::File->new_tmpfile or croak $!;
1807                print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1808                                        "$SVN_URL\@$log_msg->{revision}",
1809                                        " $SVN_UUID\n" or croak $!;
1810                $msg_fh->flush == 0 or croak $!;
1811                seek $msg_fh, 0, 0 or croak $!;
1812                set_commit_env($log_msg);
1813                my @exec = ('git-commit-tree',$tree);
1814                push @exec, '-p', $_  foreach @exec_parents;
1815                open STDIN, '<&', $msg_fh or croak $!;
1816                exec @exec or croak $!;
1817        }
1818        chomp(my $commit = do { local $/; <$out_fh> });
1819        close $out_fh or croak $?;
1820        if ($commit !~ /^$sha1$/o) {
1821                croak "Failed to commit, invalid sha1: $commit\n";
1822        }
1823        my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1824        if (my $primary_parent = shift @exec_parents) {
1825                quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0");
1826                push @update_ref, $primary_parent unless $?;
1827        }
1828        sys(@update_ref);
1829        revdb_set($REVDB, $log_msg->{revision}, $commit);
1830
1831        # this output is read via pipe, do not change:
1832        print "r$log_msg->{revision} = $commit\n";
1833        check_repack();
1834        return $commit;
1835}
1836
1837sub check_repack {
1838        if ($_repack && (--$_repack_nr == 0)) {
1839                $_repack_nr = $_repack;
1840                sys("git repack $_repack_flags");
1841        }
1842}
1843
1844sub set_commit_env {
1845        my ($log_msg) = @_;
1846        my $author = $log_msg->{author};
1847        if (!defined $author || length $author == 0) {
1848                $author = '(no author)';
1849        }
1850        my ($name,$email) = defined $users{$author} ?  @{$users{$author}}
1851                                : ($author,"$author\@$SVN_UUID");
1852        $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1853        $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1854        $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1855}
1856
1857sub apply_mod_line_blob {
1858        my $m = shift;
1859        if ($m->{mode_b} =~ /^120/) {
1860                blob_to_symlink($m->{sha1_b}, $m->{file_b});
1861        } else {
1862                blob_to_file($m->{sha1_b}, $m->{file_b});
1863        }
1864}
1865
1866sub blob_to_symlink {
1867        my ($blob, $link) = @_;
1868        defined $link or croak "\$link not defined!\n";
1869        croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1870        if (-l $link || -f _) {
1871                unlink $link or croak $!;
1872        }
1873
1874        my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1875        symlink $dest, $link or croak $!;
1876}
1877
1878sub blob_to_file {
1879        my ($blob, $file) = @_;
1880        defined $file or croak "\$file not defined!\n";
1881        croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1882        if (-l $file || -f _) {
1883                unlink $file or croak $!;
1884        }
1885
1886        open my $blob_fh, '>', $file or croak "$!: $file\n";
1887        my $pid = fork;
1888        defined $pid or croak $!;
1889
1890        if ($pid == 0) {
1891                open STDOUT, '>&', $blob_fh or croak $!;
1892                exec('git-cat-file','blob',$blob) or croak $!;
1893        }
1894        waitpid $pid, 0;
1895        croak $? if $?;
1896
1897        close $blob_fh or croak $!;
1898}
1899
1900sub safe_qx {
1901        my $pid = open my $child, '-|';
1902        defined $pid or croak $!;
1903        if ($pid == 0) {
1904                exec(@_) or croak $!;
1905        }
1906        my @ret = (<$child>);
1907        close $child or croak $?;
1908        die $? if $?; # just in case close didn't error out
1909        return wantarray ? @ret : join('',@ret);
1910}
1911
1912sub svn_compat_check {
1913        my @co_help = safe_qx(qw(svn co -h));
1914        unless (grep /ignore-externals/,@co_help) {
1915                print STDERR "W: Installed svn version does not support ",
1916                                "--ignore-externals\n";
1917                $_no_ignore_ext = 1;
1918        }
1919        if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1920                $_svn_co_url_revs = 1;
1921        }
1922        if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1923                $_svn_pg_peg_revs = 1;
1924        }
1925
1926        # I really, really hope nobody hits this...
1927        unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1928                print STDERR <<'';
1929W: The installed svn version does not support the --stop-on-copy flag in
1930   the log command.
1931   Lets hope the directory you're tracking is not a branch or tag
1932   and was never moved within the repository...
1933
1934                $_no_stop_copy = 1;
1935        }
1936}
1937
1938# *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1939# (and they won't honor URL@<rev> without -r<rev>, too!)
1940sub svn_cmd_checkout {
1941        my ($url, $rev, $dir) = @_;
1942        my @cmd = ('svn','co', "-r$rev");
1943        push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1944        $url .= "\@$rev" if $_svn_co_url_revs;
1945        sys(@cmd, $url, $dir);
1946}
1947
1948sub check_upgrade_needed {
1949        if (!-r $REVDB) {
1950                -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1951                open my $fh, '>>',$REVDB or croak $!;
1952                close $fh;
1953        }
1954        my $old = eval {
1955                my $pid = open my $child, '-|';
1956                defined $pid or croak $!;
1957                if ($pid == 0) {
1958                        close STDERR;
1959                        exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
1960                }
1961                my @ret = (<$child>);
1962                close $child or croak $?;
1963                die $? if $?; # just in case close didn't error out
1964                return wantarray ? @ret : join('',@ret);
1965        };
1966        return unless $old;
1967        my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1968        if ($@ || !$head) {
1969                print STDERR "Please run: $0 rebuild --upgrade\n";
1970                exit 1;
1971        }
1972}
1973
1974# fills %tree_map with a reverse mapping of trees to commits.  Useful
1975# for finding parents to commit on.
1976sub map_tree_joins {
1977        my %seen;
1978        foreach my $br (@_branch_from) {
1979                my $pid = open my $pipe, '-|';
1980                defined $pid or croak $!;
1981                if ($pid == 0) {
1982                        exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1983                                                                or croak $!;
1984                }
1985                while (<$pipe>) {
1986                        if (/^commit ($sha1)$/o) {
1987                                my $commit = $1;
1988
1989                                # if we've seen a commit,
1990                                # we've seen its parents
1991                                last if $seen{$commit};
1992                                my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1993                                unless (defined $tree) {
1994                                        die "Failed to parse commit $commit\n";
1995                                }
1996                                push @{$tree_map{$tree}}, $commit;
1997                                $seen{$commit} = 1;
1998                        }
1999                }
2000                close $pipe; # we could be breaking the pipe early
2001        }
2002}
2003
2004sub load_all_refs {
2005        if (@_branch_from) {
2006                print STDERR '--branch|-b parameters are ignored when ',
2007                        "--branch-all-refs|-B is passed\n";
2008        }
2009
2010        # don't worry about rev-list on non-commit objects/tags,
2011        # it shouldn't blow up if a ref is a blob or tree...
2012        chomp(@_branch_from = `git-rev-parse --symbolic --all`);
2013}
2014
2015# '<svn username> = real-name <email address>' mapping based on git-svnimport:
2016sub load_authors {
2017        open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2018        while (<$authors>) {
2019                chomp;
2020                next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2021                my ($user, $name, $email) = ($1, $2, $3);
2022                $users{$user} = [$name, $email];
2023        }
2024        close $authors or croak $!;
2025}
2026
2027sub rload_authors {
2028        open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2029        while (<$authors>) {
2030                chomp;
2031                next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2032                my ($user, $name, $email) = ($1, $2, $3);
2033                $rusers{"$name <$email>"} = $user;
2034        }
2035        close $authors or croak $!;
2036}
2037
2038sub svn_propget_base {
2039        my ($p, $f) = @_;
2040        $f .= '@BASE' if $_svn_pg_peg_revs;
2041        return safe_qx(qw/svn propget/, $p, $f);
2042}
2043
2044sub git_svn_each {
2045        my $sub = shift;
2046        foreach (`git-rev-parse --symbolic --all`) {
2047                next unless s#^refs/remotes/##;
2048                chomp $_;
2049                next unless -f "$GIT_DIR/svn/$_/info/url";
2050                &$sub($_);
2051        }
2052}
2053
2054sub migrate_revdb {
2055        git_svn_each(sub {
2056                my $id = shift;
2057                defined(my $pid = fork) or croak $!;
2058                if (!$pid) {
2059                        $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2060                        init_vars();
2061                        exit 0 if -r $REVDB;
2062                        print "Upgrading svn => git mapping...\n";
2063                        -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
2064                        open my $fh, '>>',$REVDB or croak $!;
2065                        close $fh;
2066                        rebuild();
2067                        print "Done upgrading. You may now delete the ",
2068                                "deprecated $GIT_SVN_DIR/revs directory\n";
2069                        exit 0;
2070                }
2071                waitpid $pid, 0;
2072                croak $? if $?;
2073        });
2074}
2075
2076sub migration_check {
2077        migrate_revdb() unless (-e $REVDB);
2078        return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2079        print "Upgrading repository...\n";
2080        unless (-d "$GIT_DIR/svn") {
2081                mkdir "$GIT_DIR/svn" or croak $!;
2082        }
2083        print "Data from a previous version of git-svn exists, but\n\t",
2084                                "$GIT_SVN_DIR\n\t(required for this version ",
2085                                "($VERSION) of git-svn) does not.\n";
2086
2087        foreach my $x (`git-rev-parse --symbolic --all`) {
2088                next unless $x =~ s#^refs/remotes/##;
2089                chomp $x;
2090                next unless -f "$GIT_DIR/$x/info/url";
2091                my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2092                next unless $u;
2093                my $dn = dirname("$GIT_DIR/svn/$x");
2094                mkpath([$dn]) unless -d $dn;
2095                rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
2096        }
2097        migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
2098        print "Done upgrading.\n";
2099}
2100
2101sub find_rev_before {
2102        my ($r, $id, $eq_ok) = @_;
2103        my $f = "$GIT_DIR/svn/$id/.rev_db";
2104        return (undef,undef) unless -r $f;
2105        --$r unless $eq_ok;
2106        while ($r > 0) {
2107                if (my $c = revdb_get($f, $r)) {
2108                        return ($r, $c);
2109                }
2110                --$r;
2111        }
2112        return (undef, undef);
2113}
2114
2115sub init_vars {
2116        $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2117        $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2118        $REVDB = "$GIT_SVN_DIR/.rev_db";
2119        $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2120        $SVN_URL = undef;
2121        $SVN_WC = "$GIT_SVN_DIR/tree";
2122}
2123
2124# convert GetOpt::Long specs for use by git-repo-config
2125sub read_repo_config {
2126        return unless -d $GIT_DIR;
2127        my $opts = shift;
2128        foreach my $o (keys %$opts) {
2129                my $v = $opts->{$o};
2130                my ($key) = ($o =~ /^([a-z\-]+)/);
2131                $key =~ s/-//g;
2132                my $arg = 'git-repo-config';
2133                $arg .= ' --int' if ($o =~ /[:=]i$/);
2134                $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2135                if (ref $v eq 'ARRAY') {
2136                        chomp(my @tmp = `$arg --get-all svn.$key`);
2137                        @$v = @tmp if @tmp;
2138                } else {
2139                        chomp(my $tmp = `$arg --get svn.$key`);
2140                        if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2141                                $$v = $tmp;
2142                        }
2143                }
2144        }
2145}
2146
2147sub set_default_vals {
2148        if (defined $_repack) {
2149                $_repack = 1000 if ($_repack <= 0);
2150                $_repack_nr = $_repack;
2151                $_repack_flags ||= '-d';
2152        }
2153}
2154
2155sub read_grafts {
2156        my $gr_file = shift;
2157        my ($grafts, $comments) = ({}, {});
2158        if (open my $fh, '<', $gr_file) {
2159                my @tmp;
2160                while (<$fh>) {
2161                        if (/^($sha1)\s+/) {
2162                                my $c = $1;
2163                                if (@tmp) {
2164                                        @{$comments->{$c}} = @tmp;
2165                                        @tmp = ();
2166                                }
2167                                foreach my $p (split /\s+/, $_) {
2168                                        $grafts->{$c}->{$p} = 1;
2169                                }
2170                        } else {
2171                                push @tmp, $_;
2172                        }
2173                }
2174                close $fh or croak $!;
2175                @{$comments->{'END'}} = @tmp if @tmp;
2176        }
2177        return ($grafts, $comments);
2178}
2179
2180sub write_grafts {
2181        my ($grafts, $comments, $gr_file) = @_;
2182
2183        open my $fh, '>', $gr_file or croak $!;
2184        foreach my $c (sort keys %$grafts) {
2185                if ($comments->{$c}) {
2186                        print $fh $_ foreach @{$comments->{$c}};
2187                }
2188                my $p = $grafts->{$c};
2189                delete $p->{$c}; # commits are not self-reproducing...
2190                my $pid = open my $ch, '-|';
2191                defined $pid or croak $!;
2192                if (!$pid) {
2193                        exec(qw/git-cat-file commit/, $c) or croak $!;
2194                }
2195                while (<$ch>) {
2196                        if (/^parent ([a-f\d]{40})/) {
2197                                $p->{$1} = 1;
2198                        } else {
2199                                last unless /^\S/i;
2200                        }
2201                }
2202                close $ch; # breaking the pipe
2203                print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2204        }
2205        if ($comments->{'END'}) {
2206                print $fh $_ foreach @{$comments->{'END'}};
2207        }
2208        close $fh or croak $!;
2209}
2210
2211sub read_url_paths {
2212        my $l_map = {};
2213        git_svn_each(sub { my $x = shift;
2214                        my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2215                        my ($u, $p) = repo_path_split($url);
2216                        $l_map->{$u}->{$p} = $x;
2217                        });
2218        return $l_map;
2219}
2220
2221sub extract_metadata {
2222        my $id = shift;
2223        my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2224                                                        \s([a-f\d\-]+)$/x);
2225        if (!$rev || !$uuid || !$url) {
2226                # some of the original repositories I made had
2227                # indentifiers like this:
2228                ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2229        }
2230        return ($url, $rev, $uuid);
2231}
2232
2233sub tz_to_s_offset {
2234        my ($tz) = @_;
2235        $tz =~ s/(\d\d)$//;
2236        return ($1 * 60) + ($tz * 3600);
2237}
2238
2239sub setup_pager { # translated to Perl from pager.c
2240        return unless (-t *STDOUT);
2241        my $pager = $ENV{PAGER};
2242        if (!defined $pager) {
2243                $pager = 'less';
2244        } elsif (length $pager == 0 || $pager eq 'cat') {
2245                return;
2246        }
2247        pipe my $rfd, my $wfd or return;
2248        defined(my $pid = fork) or croak $!;
2249        if (!$pid) {
2250                open STDOUT, '>&', $wfd or croak $!;
2251                return;
2252        }
2253        open STDIN, '<&', $rfd or croak $!;
2254        $ENV{LESS} ||= '-S';
2255        exec $pager or croak "Can't run pager: $!\n";;
2256}
2257
2258sub get_author_info {
2259        my ($dest, $author, $t, $tz) = @_;
2260        $author =~ s/(?:^\s*|\s*$)//g;
2261        $dest->{a_raw} = $author;
2262        my $_a;
2263        if ($_authors) {
2264                $_a = $rusers{$author} || undef;
2265        }
2266        if (!$_a) {
2267                ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2268        }
2269        $dest->{t} = $t;
2270        $dest->{tz} = $tz;
2271        $dest->{a} = $_a;
2272        # Date::Parse isn't in the standard Perl distro :(
2273        if ($tz =~ s/^\+//) {
2274                $t += tz_to_s_offset($tz);
2275        } elsif ($tz =~ s/^\-//) {
2276                $t -= tz_to_s_offset($tz);
2277        }
2278        $dest->{t_utc} = $t;
2279}
2280
2281sub process_commit {
2282        my ($c, $r_min, $r_max, $defer) = @_;
2283        if (defined $r_min && defined $r_max) {
2284                if ($r_min == $c->{r} && $r_min == $r_max) {
2285                        show_commit($c);
2286                        return 0;
2287                }
2288                return 1 if $r_min == $r_max;
2289                if ($r_min < $r_max) {
2290                        # we need to reverse the print order
2291                        return 0 if (defined $_limit && --$_limit < 0);
2292                        push @$defer, $c;
2293                        return 1;
2294                }
2295                if ($r_min != $r_max) {
2296                        return 1 if ($r_min < $c->{r});
2297                        return 1 if ($r_max > $c->{r});
2298                }
2299        }
2300        return 0 if (defined $_limit && --$_limit < 0);
2301        show_commit($c);
2302        return 1;
2303}
2304
2305sub show_commit {
2306        my $c = shift;
2307        if ($_oneline) {
2308                my $x = "\n";
2309                if (my $l = $c->{l}) {
2310                        while ($l->[0] =~ /^\s*$/) { shift @$l }
2311                        $x = $l->[0];
2312                }
2313                $_l_fmt ||= 'A' . length($c->{r});
2314                print 'r',pack($_l_fmt, $c->{r}),' | ';
2315                print "$c->{c} | " if $_show_commit;
2316                print $x;
2317        } else {
2318                show_commit_normal($c);
2319        }
2320}
2321
2322sub show_commit_normal {
2323        my ($c) = @_;
2324        print '-' x72, "\nr$c->{r} | ";
2325        print "$c->{c} | " if $_show_commit;
2326        print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2327                                 localtime($c->{t_utc})), ' | ';
2328        my $nr_line = 0;
2329
2330        if (my $l = $c->{l}) {
2331                while ($l->[$#$l] eq "\n" && $l->[($#$l - 1)] eq "\n") {
2332                        pop @$l;
2333                }
2334                $nr_line = scalar @$l;
2335                if (!$nr_line) {
2336                        print "1 line\n\n\n";
2337                } else {
2338                        if ($nr_line == 1) {
2339                                $nr_line = '1 line';
2340                        } else {
2341                                $nr_line .= ' lines';
2342                        }
2343                        print $nr_line, "\n\n";
2344                        print $_ foreach @$l;
2345                }
2346        } else {
2347                print "1 line\n\n";
2348
2349        }
2350        foreach my $x (qw/raw diff/) {
2351                if ($c->{$x}) {
2352                        print "\n";
2353                        print $_ foreach @{$c->{$x}}
2354                }
2355        }
2356}
2357
2358sub libsvn_load {
2359        return unless $_use_lib;
2360        $_use_lib = eval {
2361                require SVN::Core;
2362                if ($SVN::Core::VERSION lt '1.1.0') {
2363                        die "Need SVN::Core 1.1.0 or better ",
2364                                        "(got $SVN::Core::VERSION) ",
2365                                        "Falling back to command-line svn\n";
2366                }
2367                require SVN::Ra;
2368                require SVN::Delta;
2369                push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2370                my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2371                                        $SVN::Node::dir.$SVN::Node::unknown.
2372                                        $SVN::Node::none.$SVN::Node::file.
2373                                        $SVN::Node::dir.$SVN::Node::unknown;
2374                1;
2375        };
2376}
2377
2378sub libsvn_connect {
2379        my ($url) = @_;
2380        my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2381                          SVN::Client::get_ssl_server_trust_file_provider(),
2382                          SVN::Client::get_username_provider()]);
2383        my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2384        return $s;
2385}
2386
2387sub libsvn_get_file {
2388        my ($gui, $f, $rev) = @_;
2389        my $p = $f;
2390        return unless ($p =~ s#^\Q$SVN_PATH\E/?##);
2391
2392        my ($hash, $pid, $in, $out);
2393        my $pool = SVN::Pool->new;
2394        defined($pid = open3($in, $out, '>&STDERR',
2395                                qw/git-hash-object -w --stdin/)) or croak $!;
2396        # redirect STDOUT for SVN 1.1.x compatibility
2397        open my $stdout, '>&', \*STDOUT or croak $!;
2398        open STDOUT, '>&', $in or croak $!;
2399        $| = 1; # not sure if this is necessary, better safe than sorry...
2400        my ($r, $props) = $SVN->get_file($f, $rev, \*STDOUT, $pool);
2401        $in->flush == 0 or croak $!;
2402        open STDOUT, '>&', $stdout or croak $!;
2403        close $in or croak $!;
2404        close $stdout or croak $!;
2405        $pool->clear;
2406        chomp($hash = do { local $/; <$out> });
2407        close $out or croak $!;
2408        waitpid $pid, 0;
2409        $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2410
2411        my $mode = exists $props->{'svn:executable'} ? '100755' : '100644';
2412        if (exists $props->{'svn:special'}) {
2413                $mode = '120000';
2414                my $link = `git-cat-file blob $hash`;
2415                $link =~ s/^link // or die "svn:special file with contents: <",
2416                                                $link, "> is not understood\n";
2417                defined($pid = open3($in, $out, '>&STDERR',
2418                                qw/git-hash-object -w --stdin/)) or croak $!;
2419                print $in $link;
2420                $in->flush == 0 or croak $!;
2421                close $in or croak $!;
2422                chomp($hash = do { local $/; <$out> });
2423                close $out or croak $!;
2424                waitpid $pid, 0;
2425                $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2426        }
2427        print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
2428}
2429
2430sub libsvn_log_entry {
2431        my ($rev, $author, $date, $msg, $parents) = @_;
2432        my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2433                                         (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2434                                or die "Unable to parse date: $date\n";
2435        if (defined $_authors && ! defined $users{$author}) {
2436                die "Author: $author not defined in $_authors file\n";
2437        }
2438        return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2439                author => $author, msg => $msg."\n", parents => $parents || [] }
2440}
2441
2442sub process_rm {
2443        my ($gui, $last_commit, $f) = @_;
2444        $f =~ s#^\Q$SVN_PATH\E/?## or return;
2445        # remove entire directories.
2446        if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2447                defined(my $pid = open my $ls, '-|') or croak $!;
2448                if (!$pid) {
2449                        exec(qw/git-ls-tree -r --name-only -z/,
2450                                $last_commit,'--',$f) or croak $!;
2451                }
2452                local $/ = "\0";
2453                while (<$ls>) {
2454                        print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2455                }
2456                close $ls or croak $?;
2457        } else {
2458                print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2459        }
2460}
2461
2462sub libsvn_fetch {
2463        my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2464        open my $gui, '| git-update-index -z --index-info' or croak $!;
2465        my @amr;
2466        foreach my $f (keys %$paths) {
2467                my $m = $paths->{$f}->action();
2468                $f =~ s#^/+##;
2469                if ($m =~ /^[DR]$/) {
2470                        process_rm($gui, $last_commit, $f);
2471                        next if $m eq 'D';
2472                        # 'R' can be file replacements, too, right?
2473                }
2474                my $pool = SVN::Pool->new;
2475                my $t = $SVN->check_path($f, $rev, $pool);
2476                if ($t == $SVN::Node::file) {
2477                        if ($m =~ /^[AMR]$/) {
2478                                push @amr, $f;
2479                        } else {
2480                                die "Unrecognized action: $m, ($f r$rev)\n";
2481                        }
2482                }
2483                $pool->clear;
2484        }
2485        libsvn_get_file($gui, $_, $rev) foreach (@amr);
2486        close $gui or croak $?;
2487        return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2488}
2489
2490sub svn_grab_base_rev {
2491        defined(my $pid = open my $fh, '-|') or croak $!;
2492        if (!$pid) {
2493                open my $null, '>', '/dev/null' or croak $!;
2494                open STDERR, '>&', $null or croak $!;
2495                exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2496                                                                or croak $!;
2497        }
2498        chomp(my $c = do { local $/; <$fh> });
2499        close $fh;
2500        if (defined $c && length $c) {
2501                my ($url, $rev, $uuid) = extract_metadata((grep(/^git-svn-id: /,
2502                        safe_qx(qw/git-cat-file commit/, $c)))[-1]);
2503                return ($rev, $c);
2504        }
2505        return (undef, undef);
2506}
2507
2508sub libsvn_parse_revision {
2509        my $base = shift;
2510        my $head = $SVN->get_latest_revnum();
2511        if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2512                return ($base + 1, $head) if (defined $base);
2513                return (0, $head);
2514        }
2515        return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2516        return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2517        if ($_revision =~ /^BASE:(\d+)$/) {
2518                return ($base + 1, $1) if (defined $base);
2519                return (0, $head);
2520        }
2521        return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2522        die "revision argument: $_revision not understood by git-svn\n",
2523                "Try using the command-line svn client instead\n";
2524}
2525
2526sub libsvn_traverse {
2527        my ($gui, $pfx, $path, $rev) = @_;
2528        my $cwd = "$pfx/$path";
2529        my $pool = SVN::Pool->new;
2530        $cwd =~ s#^/+##g;
2531        my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2532        foreach my $d (keys %$dirent) {
2533                my $t = $dirent->{$d}->kind;
2534                if ($t == $SVN::Node::dir) {
2535                        libsvn_traverse($gui, $cwd, $d, $rev);
2536                } elsif ($t == $SVN::Node::file) {
2537                        libsvn_get_file($gui, "$cwd/$d", $rev);
2538                }
2539        }
2540        $pool->clear;
2541}
2542
2543sub libsvn_traverse_ignore {
2544        my ($fh, $path, $r) = @_;
2545        $path =~ s#^/+##g;
2546        my $pool = SVN::Pool->new;
2547        my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2548        my $p = $path;
2549        $p =~ s#^\Q$SVN_PATH\E/?##;
2550        print $fh length $p ? "\n# $p\n" : "\n# /\n";
2551        if (my $s = $props->{'svn:ignore'}) {
2552                $s =~ s/[\r\n]+/\n/g;
2553                chomp $s;
2554                if (length $p == 0) {
2555                        $s =~ s#\n#\n/$p#g;
2556                        print $fh "/$s\n";
2557                } else {
2558                        $s =~ s#\n#\n/$p/#g;
2559                        print $fh "/$p/$s\n";
2560                }
2561        }
2562        foreach (sort keys %$dirent) {
2563                next if $dirent->{$_}->kind != $SVN::Node::dir;
2564                libsvn_traverse_ignore($fh, "$path/$_", $r);
2565        }
2566        $pool->clear;
2567}
2568
2569sub revisions_eq {
2570        my ($path, $r0, $r1) = @_;
2571        return 1 if $r0 == $r1;
2572        my $nr = 0;
2573        if ($_use_lib) {
2574                # should be OK to use Pool here (r1 - r0) should be small
2575                my $pool = SVN::Pool->new;
2576                libsvn_get_log($SVN, "/$path", $r0, $r1,
2577                                0, 1, 1, sub {$nr++}, $pool);
2578                $pool->clear;
2579        } else {
2580                my ($url, undef) = repo_path_split($SVN_URL);
2581                my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
2582                while (next_log_entry($svn_log)) { $nr++ }
2583                close $svn_log->{fh};
2584        }
2585        return 0 if ($nr > 1);
2586        return 1;
2587}
2588
2589sub libsvn_find_parent_branch {
2590        my ($paths, $rev, $author, $date, $msg) = @_;
2591        my $svn_path = '/'.$SVN_PATH;
2592
2593        # look for a parent from another branch:
2594        my $i = $paths->{$svn_path} or return;
2595        my $branch_from = $i->copyfrom_path or return;
2596        my $r = $i->copyfrom_rev;
2597        print STDERR  "Found possible branch point: ",
2598                                "$branch_from => $svn_path, $r\n";
2599        $branch_from =~ s#^/##;
2600        my $l_map = read_url_paths();
2601        my $url = $SVN->{url};
2602        defined $l_map->{$url} or return;
2603        my $id = $l_map->{$url}->{$branch_from} or return;
2604        my ($r0, $parent) = find_rev_before($r,$id,1);
2605        return unless (defined $r0 && defined $parent);
2606        if (revisions_eq($branch_from, $r0, $r)) {
2607                unlink $GIT_SVN_INDEX;
2608                print STDERR "Found branch parent: $parent\n";
2609                sys(qw/git-read-tree/, $parent);
2610                return libsvn_fetch($parent, $paths, $rev,
2611                                        $author, $date, $msg);
2612        }
2613        print STDERR "Nope, branch point not imported or unknown\n";
2614        return undef;
2615}
2616
2617sub libsvn_get_log {
2618        my ($ra, @args) = @_;
2619        if ($SVN::Core::VERSION le '1.2.0') {
2620                splice(@args, 3, 1);
2621        }
2622        $ra->get_log(@args);
2623}
2624
2625sub libsvn_new_tree {
2626        if (my $log_entry = libsvn_find_parent_branch(@_)) {
2627                return $log_entry;
2628        }
2629        my ($paths, $rev, $author, $date, $msg) = @_;
2630        open my $gui, '| git-update-index -z --index-info' or croak $!;
2631        my $pool = SVN::Pool->new;
2632        libsvn_traverse($gui, '', $SVN_PATH, $rev, $pool);
2633        $pool->clear;
2634        close $gui or croak $?;
2635        return libsvn_log_entry($rev, $author, $date, $msg);
2636}
2637
2638sub find_graft_path_commit {
2639        my ($tree_paths, $p1, $r1) = @_;
2640        foreach my $x (keys %$tree_paths) {
2641                next unless ($p1 =~ /^\Q$x\E/);
2642                my $i = $tree_paths->{$x};
2643                my ($r0, $parent) = find_rev_before($r1,$i,1);
2644                return $parent if (defined $r0 && $r0 == $r1);
2645                print STDERR "r$r1 of $i not imported\n";
2646                next;
2647        }
2648        return undef;
2649}
2650
2651sub find_graft_path_parents {
2652        my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2653        foreach my $x (keys %$tree_paths) {
2654                next unless ($p0 =~ /^\Q$x\E/);
2655                my $i = $tree_paths->{$x};
2656                my ($r, $parent) = find_rev_before($r0, $i, 1);
2657                if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2658                        $grafts->{$c}->{$parent} = 1;
2659                }
2660        }
2661}
2662
2663sub libsvn_graft_file_copies {
2664        my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2665        foreach (keys %$paths) {
2666                my $i = $paths->{$_};
2667                my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2668                                        $i->copyfrom_rev);
2669                next unless (defined $p0 && defined $r0);
2670
2671                my $p1 = $_;
2672                $p1 =~ s#^/##;
2673                $p0 =~ s#^/##;
2674                my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2675                next unless $c;
2676                find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2677        }
2678}
2679
2680sub set_index {
2681        my $old = $ENV{GIT_INDEX_FILE};
2682        $ENV{GIT_INDEX_FILE} = shift;
2683        return $old;
2684}
2685
2686sub restore_index {
2687        my ($old) = @_;
2688        if (defined $old) {
2689                $ENV{GIT_INDEX_FILE} = $old;
2690        } else {
2691                delete $ENV{GIT_INDEX_FILE};
2692        }
2693}
2694
2695sub libsvn_commit_cb {
2696        my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2697        if ($_optimize_commits && $rev == ($r_last + 1)) {
2698                my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2699                $log->{tree} = get_tree_from_treeish($c);
2700                my $cmt = git_commit($log, $cmt_last, $c);
2701                my @diff = safe_qx('git-diff-tree', $cmt, $c);
2702                if (@diff) {
2703                        print STDERR "Trees differ: $cmt $c\n",
2704                                        join('',@diff),"\n";
2705                        exit 1;
2706                }
2707        } else {
2708                fetch("$rev=$c");
2709        }
2710}
2711
2712sub libsvn_ls_fullurl {
2713        my $fullurl = shift;
2714        my ($repo, $path) = repo_path_split($fullurl);
2715        $SVN ||= libsvn_connect($repo);
2716        my @ret;
2717        my $pool = SVN::Pool->new;
2718        my ($dirent, undef, undef) = $SVN->get_dir($path,
2719                                                $SVN->get_latest_revnum, $pool);
2720        foreach my $d (keys %$dirent) {
2721                if ($dirent->{$d}->kind == $SVN::Node::dir) {
2722                        push @ret, "$d/"; # add '/' for compat with cli svn
2723                }
2724        }
2725        $pool->clear;
2726        return @ret;
2727}
2728
2729
2730sub libsvn_skip_unknown_revs {
2731        my $err = shift;
2732        my $errno = $err->apr_err();
2733        # Maybe the branch we're tracking didn't
2734        # exist when the repo started, so it's
2735        # not an error if it doesn't, just continue
2736        #
2737        # Wonderfully consistent library, eh?
2738        # 160013 - svn:// and file://
2739        # 175002 - http(s)://
2740        #   More codes may be discovered later...
2741        if ($errno == 175002 || $errno == 160013) {
2742                return;
2743        }
2744        croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2745};
2746
2747# Tie::File seems to be prone to offset errors if revisions get sparse,
2748# it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2749# one of my favorite modules is out :<  Next up would be one of the DBM
2750# modules, but I'm not sure which is most portable...  So I'll just
2751# go with something that's plain-text, but still capable of
2752# being randomly accessed.  So here's my ultra-simple fixed-width
2753# database.  All records are 40 characters + "\n", so it's easy to seek
2754# to a revision: (41 * rev) is the byte offset.
2755# A record of 40 0s denotes an empty revision.
2756# And yes, it's still pretty fast (faster than Tie::File).
2757sub revdb_set {
2758        my ($file, $rev, $commit) = @_;
2759        length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2760        open my $fh, '+<', $file or croak $!;
2761        my $offset = $rev * 41;
2762        # assume that append is the common case:
2763        seek $fh, 0, 2 or croak $!;
2764        my $pos = tell $fh;
2765        if ($pos < $offset) {
2766                print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2767        }
2768        seek $fh, $offset, 0 or croak $!;
2769        print $fh $commit,"\n";
2770        close $fh or croak $!;
2771}
2772
2773sub revdb_get {
2774        my ($file, $rev) = @_;
2775        my $ret;
2776        my $offset = $rev * 41;
2777        open my $fh, '<', $file or croak $!;
2778        seek $fh, $offset, 0;
2779        if (tell $fh == $offset) {
2780                $ret = readline $fh;
2781                if (defined $ret) {
2782                        chomp $ret;
2783                        $ret = undef if ($ret =~ /^0{40}$/);
2784                }
2785        }
2786        close $fh or croak $!;
2787        return $ret;
2788}
2789
2790sub copy_remote_ref {
2791        my $origin = $_cp_remote ? $_cp_remote : 'origin';
2792        my $ref = "refs/remotes/$GIT_SVN";
2793        if (safe_qx('git-ls-remote', $origin, $ref)) {
2794                sys(qw/git fetch/, $origin, "$ref:$ref");
2795        } else {
2796                die "Unable to find remote reference: ",
2797                                "refs/remotes/$GIT_SVN on $origin\n";
2798        }
2799}
2800
2801package SVN::Git::Editor;
2802use vars qw/@ISA/;
2803use strict;
2804use warnings;
2805use Carp qw/croak/;
2806use IO::File;
2807
2808sub new {
2809        my $class = shift;
2810        my $git_svn = shift;
2811        my $self = SVN::Delta::Editor->new(@_);
2812        bless $self, $class;
2813        foreach (qw/svn_path c r ra /) {
2814                die "$_ required!\n" unless (defined $git_svn->{$_});
2815                $self->{$_} = $git_svn->{$_};
2816        }
2817        $self->{pool} = SVN::Pool->new;
2818        $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2819        $self->{rm} = { };
2820        require Digest::MD5;
2821        return $self;
2822}
2823
2824sub split_path {
2825        return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2826}
2827
2828sub repo_path {
2829        (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
2830                                        : $_[0]->{svn_path}
2831}
2832
2833sub url_path {
2834        my ($self, $path) = @_;
2835        $self->{ra}->{url} . '/' . $self->repo_path($path);
2836}
2837
2838sub rmdirs {
2839        my ($self) = @_;
2840        my $rm = $self->{rm};
2841        delete $rm->{''}; # we never delete the url we're tracking
2842        return unless %$rm;
2843
2844        foreach (keys %$rm) {
2845                my @d = split m#/#, $_;
2846                my $c = shift @d;
2847                $rm->{$c} = 1;
2848                while (@d) {
2849                        $c .= '/' . shift @d;
2850                        $rm->{$c} = 1;
2851                }
2852        }
2853        delete $rm->{$self->{svn_path}};
2854        delete $rm->{''}; # we never delete the url we're tracking
2855        return unless %$rm;
2856
2857        defined(my $pid = open my $fh,'-|') or croak $!;
2858        if (!$pid) {
2859                exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
2860        }
2861        local $/ = "\0";
2862        my @svn_path = split m#/#, $self->{svn_path};
2863        while (<$fh>) {
2864                chomp;
2865                my @dn = (@svn_path, (split m#/#, $_));
2866                while (pop @dn) {
2867                        delete $rm->{join '/', @dn};
2868                }
2869                unless (%$rm) {
2870                        close $fh;
2871                        return;
2872                }
2873        }
2874        close $fh;
2875
2876        my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2877        foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2878                $self->close_directory($bat->{$d}, $p);
2879                my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2880                $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2881                delete $bat->{$d};
2882        }
2883}
2884
2885sub open_or_add_dir {
2886        my ($self, $full_path, $baton) = @_;
2887        my $p = SVN::Pool->new;
2888        my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
2889        $p->clear;
2890        if ($t == $SVN::Node::none) {
2891                return $self->add_directory($full_path, $baton,
2892                                                undef, -1, $self->{pool});
2893        } elsif ($t == $SVN::Node::dir) {
2894                return $self->open_directory($full_path, $baton,
2895                                                $self->{r}, $self->{pool});
2896        }
2897        print STDERR "$full_path already exists in repository at ",
2898                "r$self->{r} and it is not a directory (",
2899                ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2900        exit 1;
2901}
2902
2903sub ensure_path {
2904        my ($self, $path) = @_;
2905        my $bat = $self->{bat};
2906        $path = $self->repo_path($path);
2907        return $bat->{''} unless (length $path);
2908        my @p = split m#/+#, $path;
2909        my $c = shift @p;
2910        $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2911        while (@p) {
2912                my $c0 = $c;
2913                $c .= '/' . shift @p;
2914                $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2915        }
2916        return $bat->{$c};
2917}
2918
2919sub A {
2920        my ($self, $m) = @_;
2921        my ($dir, $file) = split_path($m->{file_b});
2922        my $pbat = $self->ensure_path($dir);
2923        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2924                                        undef, -1);
2925        $self->chg_file($fbat, $m);
2926        $self->close_file($fbat,undef,$self->{pool});
2927}
2928
2929sub C {
2930        my ($self, $m) = @_;
2931        my ($dir, $file) = split_path($m->{file_b});
2932        my $pbat = $self->ensure_path($dir);
2933        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2934                                $self->url_path($m->{file_a}), $self->{r});
2935        $self->chg_file($fbat, $m);
2936        $self->close_file($fbat,undef,$self->{pool});
2937}
2938
2939sub delete_entry {
2940        my ($self, $path, $pbat) = @_;
2941        my $rpath = $self->repo_path($path);
2942        my ($dir, $file) = split_path($rpath);
2943        $self->{rm}->{$dir} = 1;
2944        $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2945}
2946
2947sub R {
2948        my ($self, $m) = @_;
2949        my ($dir, $file) = split_path($m->{file_b});
2950        my $pbat = $self->ensure_path($dir);
2951        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2952                                $self->url_path($m->{file_a}), $self->{r});
2953        $self->chg_file($fbat, $m);
2954        $self->close_file($fbat,undef,$self->{pool});
2955
2956        ($dir, $file) = split_path($m->{file_a});
2957        $pbat = $self->ensure_path($dir);
2958        $self->delete_entry($m->{file_a}, $pbat);
2959}
2960
2961sub M {
2962        my ($self, $m) = @_;
2963        my ($dir, $file) = split_path($m->{file_b});
2964        my $pbat = $self->ensure_path($dir);
2965        my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2966                                $pbat,$self->{r},$self->{pool});
2967        $self->chg_file($fbat, $m);
2968        $self->close_file($fbat,undef,$self->{pool});
2969}
2970
2971sub T { shift->M(@_) }
2972
2973sub change_file_prop {
2974        my ($self, $fbat, $pname, $pval) = @_;
2975        $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2976}
2977
2978sub chg_file {
2979        my ($self, $fbat, $m) = @_;
2980        if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2981                $self->change_file_prop($fbat,'svn:executable','*');
2982        } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2983                $self->change_file_prop($fbat,'svn:executable',undef);
2984        }
2985        my $fh = IO::File->new_tmpfile or croak $!;
2986        if ($m->{mode_b} =~ /^120/) {
2987                print $fh 'link ' or croak $!;
2988                $self->change_file_prop($fbat,'svn:special','*');
2989        } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2990                $self->change_file_prop($fbat,'svn:special',undef);
2991        }
2992        defined(my $pid = fork) or croak $!;
2993        if (!$pid) {
2994                open STDOUT, '>&', $fh or croak $!;
2995                exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2996        }
2997        waitpid $pid, 0;
2998        croak $? if $?;
2999        $fh->flush == 0 or croak $!;
3000        seek $fh, 0, 0 or croak $!;
3001
3002        my $md5 = Digest::MD5->new;
3003        $md5->addfile($fh) or croak $!;
3004        seek $fh, 0, 0 or croak $!;
3005
3006        my $exp = $md5->hexdigest;
3007        my $atd = $self->apply_textdelta($fbat, undef, $self->{pool});
3008        my $got = SVN::TxDelta::send_stream($fh, @$atd, $self->{pool});
3009        die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3010
3011        close $fh or croak $!;
3012}
3013
3014sub D {
3015        my ($self, $m) = @_;
3016        my ($dir, $file) = split_path($m->{file_b});
3017        my $pbat = $self->ensure_path($dir);
3018        $self->delete_entry($m->{file_b}, $pbat);
3019}
3020
3021sub close_edit {
3022        my ($self) = @_;
3023        my ($p,$bat) = ($self->{pool}, $self->{bat});
3024        foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3025                $self->close_directory($bat->{$_}, $p);
3026        }
3027        $self->SUPER::close_edit($p);
3028        $p->clear;
3029}
3030
3031sub abort_edit {
3032        my ($self) = @_;
3033        $self->SUPER::abort_edit($self->{pool});
3034        $self->{pool}->clear;
3035}
3036
3037__END__
3038
3039Data structures:
3040
3041$svn_log hashref (as returned by svn_log_raw)
3042{
3043        fh => file handle of the log file,
3044        state => state of the log file parser (sep/msg/rev/msg_start...)
3045}
3046
3047$log_msg hashref as returned by next_log_entry($svn_log)
3048{
3049        msg => 'whitespace-formatted log entry
3050',                                              # trailing newline is preserved
3051        revision => '8',                        # integer
3052        date => '2004-02-24T17:01:44.108345Z',  # commit date
3053        author => 'committer name'
3054};
3055
3056
3057@mods = array of diff-index line hashes, each element represents one line
3058        of diff-index output
3059
3060diff-index line ($m hash)
3061{
3062        mode_a => first column of diff-index output, no leading ':',
3063        mode_b => second column of diff-index output,
3064        sha1_b => sha1sum of the final blob,
3065        chg => change type [MCRADT],
3066        file_a => original file name of a file (iff chg is 'C' or 'R')
3067        file_b => new/current file name of a file (any chg)
3068}
3069;
3070
3071Notes:
3072        I don't trust the each() function on unless I created %hash myself
3073        because the internal iterator may not have started at base.