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