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