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