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