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