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