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