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