git-svn.perlon commit Merge branch 'master' into gl/web (b4c27c1)
   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}
 823
 824########################### utility functions #########################
 825
 826sub cmt_showable {
 827        my ($c) = @_;
 828        return 1 if defined $c->{r};
 829        if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
 830                                $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
 831                my @msg = safe_qx(qw/git-cat-file commit/, $c->{c});
 832                shift @msg while ($msg[0] ne "\n");
 833                shift @msg;
 834                @{$c->{l}} = grep !/^git-svn-id: /, @msg;
 835
 836                (undef, $c->{r}, undef) = extract_metadata(
 837                                (grep(/^git-svn-id: /, @msg))[-1]);
 838        }
 839        return defined $c->{r};
 840}
 841
 842sub git_svn_log_cmd {
 843        my ($r_min, $r_max) = @_;
 844        my @cmd = (qw/git-log --abbrev-commit --pretty=raw
 845                        --default/, "refs/remotes/$GIT_SVN");
 846        push @cmd, '--summary' if $_verbose;
 847        return @cmd unless defined $r_max;
 848        if ($r_max == $r_min) {
 849                push @cmd, '--max-count=1';
 850                if (my $c = revdb_get($REVDB, $r_max)) {
 851                        push @cmd, $c;
 852                }
 853        } else {
 854                my ($c_min, $c_max);
 855                $c_max = revdb_get($REVDB, $r_max);
 856                $c_min = revdb_get($REVDB, $r_min);
 857                if ($c_min && $c_max) {
 858                        if ($r_max > $r_max) {
 859                                push @cmd, "$c_min..$c_max";
 860                        } else {
 861                                push @cmd, "$c_max..$c_min";
 862                        }
 863                } elsif ($r_max > $r_min) {
 864                        push @cmd, $c_max;
 865                } else {
 866                        push @cmd, $c_min;
 867                }
 868        }
 869        return @cmd;
 870}
 871
 872sub fetch_child_id {
 873        my $id = shift;
 874        print "Fetching $id\n";
 875        my $ref = "$GIT_DIR/refs/remotes/$id";
 876        defined(my $pid = open my $fh, '-|') or croak $!;
 877        if (!$pid) {
 878                $_repack = undef;
 879                $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
 880                init_vars();
 881                fetch(@_);
 882                exit 0;
 883        }
 884        while (<$fh>) {
 885                print $_;
 886                check_repack() if (/^r\d+ = $sha1/);
 887        }
 888        close $fh or croak $?;
 889}
 890
 891sub rec_fetch {
 892        my ($pfx, $p, @args) = @_;
 893        my @dir;
 894        foreach (sort <$p/*>) {
 895                if (-r "$_/info/url") {
 896                        $pfx .= '/' if $pfx && $pfx !~ m!/$!;
 897                        my $id = $pfx . basename $_;
 898                        next if $id eq 'trunk';
 899                        fetch_child_id($id, @args);
 900                } elsif (-d $_) {
 901                        push @dir, $_;
 902                }
 903        }
 904        foreach (@dir) {
 905                my $x = $_;
 906                $x =~ s!^\Q$GIT_DIR\E/svn/!!;
 907                rec_fetch($x, $_);
 908        }
 909}
 910
 911sub complete_url_ls_init {
 912        my ($url, $var, $switch, $pfx) = @_;
 913        unless ($var) {
 914                print STDERR "W: $switch not specified\n";
 915                return;
 916        }
 917        $var =~ s#/+$##;
 918        if ($var !~ m#^[a-z\+]+://#) {
 919                $var = '/' . $var if ($var !~ m#^/#);
 920                unless ($url) {
 921                        print STDERR "E: '$var' is not a complete URL ",
 922                                "and a separate URL is not specified\n";
 923                        exit 1;
 924                }
 925                $var = $url . $var;
 926        }
 927        chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
 928                                : safe_qx(qw/svn ls --non-interactive/, $var));
 929        my $old = $GIT_SVN;
 930        defined(my $pid = fork) or croak $!;
 931        if (!$pid) {
 932                foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
 933                        $u =~ s#/+$##;
 934                        if ($u !~ m!\Q$var\E/(.+)$!) {
 935                                print STDERR "W: Unrecognized URL: $u\n";
 936                                die "This should never happen\n";
 937                        }
 938                        my $id = $pfx.$1;
 939                        print "init $u => $id\n";
 940                        $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
 941                        init_vars();
 942                        init($u);
 943                }
 944                exit 0;
 945        }
 946        waitpid $pid, 0;
 947        croak $? if $?;
 948}
 949
 950sub common_prefix {
 951        my $paths = shift;
 952        my %common;
 953        foreach (@$paths) {
 954                my @tmp = split m#/#, $_;
 955                my $p = '';
 956                while (my $x = shift @tmp) {
 957                        $p .= "/$x";
 958                        $common{$p} ||= 0;
 959                        $common{$p}++;
 960                }
 961        }
 962        foreach (sort {length $b <=> length $a} keys %common) {
 963                if ($common{$_} == @$paths) {
 964                        return $_;
 965                }
 966        }
 967        return '';
 968}
 969
 970# grafts set here are 'stronger' in that they're based on actual tree
 971# matches, and won't be deleted from merge-base checking in write_grafts()
 972sub graft_tree_joins {
 973        my $grafts = shift;
 974        map_tree_joins() if (@_branch_from && !%tree_map);
 975        return unless %tree_map;
 976
 977        git_svn_each(sub {
 978                my $i = shift;
 979                defined(my $pid = open my $fh, '-|') or croak $!;
 980                if (!$pid) {
 981                        exec qw/git-rev-list --pretty=raw/,
 982                                        "refs/remotes/$i" or croak $!;
 983                }
 984                while (<$fh>) {
 985                        next unless /^commit ($sha1)$/o;
 986                        my $c = $1;
 987                        my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
 988                        next unless $tree_map{$t};
 989
 990                        my $l;
 991                        do {
 992                                $l = readline $fh;
 993                        } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
 994
 995                        my ($s, $tz) = ($1, $2);
 996                        if ($tz =~ s/^\+//) {
 997                                $s += tz_to_s_offset($tz);
 998                        } elsif ($tz =~ s/^\-//) {
 999                                $s -= tz_to_s_offset($tz);
1000                        }
1001
1002                        my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
1003
1004                        foreach my $p (@{$tree_map{$t}}) {
1005                                next if $p eq $c;
1006                                my $mb = eval {
1007                                        safe_qx('git-merge-base', $c, $p)
1008                                };
1009                                next unless ($@ || $?);
1010                                if (defined $r_a) {
1011                                        # see if SVN says it's a relative
1012                                        my ($url_b, $r_b, $uuid_b) =
1013                                                        cmt_metadata($p);
1014                                        next if (defined $url_b &&
1015                                                        defined $url_a &&
1016                                                        ($url_a eq $url_b) &&
1017                                                        ($uuid_a eq $uuid_b));
1018                                        if ($uuid_a eq $uuid_b) {
1019                                                if ($r_b < $r_a) {
1020                                                        $grafts->{$c}->{$p} = 2;
1021                                                        next;
1022                                                } elsif ($r_b > $r_a) {
1023                                                        $grafts->{$p}->{$c} = 2;
1024                                                        next;
1025                                                }
1026                                        }
1027                                }
1028                                my $ct = get_commit_time($p);
1029                                if ($ct < $s) {
1030                                        $grafts->{$c}->{$p} = 2;
1031                                } elsif ($ct > $s) {
1032                                        $grafts->{$p}->{$c} = 2;
1033                                }
1034                                # what should we do when $ct == $s ?
1035                        }
1036                }
1037                close $fh or croak $?;
1038        });
1039}
1040
1041# this isn't funky-filename safe, but good enough for now...
1042sub graft_file_copy_cmd {
1043        my ($grafts, $l_map, $u) = @_;
1044        my $paths = $l_map->{$u};
1045        my $pfx = common_prefix([keys %$paths]);
1046        $SVN_URL ||= $u.$pfx;
1047        my $pid = open my $fh, '-|';
1048        defined $pid or croak $!;
1049        unless ($pid) {
1050                my @exec = qw/svn log -v/;
1051                push @exec, "-r$_revision" if defined $_revision;
1052                exec @exec, $u.$pfx or croak $!;
1053        }
1054        my ($r, $mp) = (undef, undef);
1055        while (<$fh>) {
1056                chomp;
1057                if (/^\-{72}$/) {
1058                        $mp = $r = undef;
1059                } elsif (/^r(\d+) \| /) {
1060                        $r = $1 unless defined $r;
1061                } elsif (/^Changed paths:/) {
1062                        $mp = 1;
1063                } elsif ($mp && m#^   [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
1064                        my ($p1, $p0, $r0) = ($1, $2, $3);
1065                        my $c = find_graft_path_commit($paths, $p1, $r);
1066                        next unless $c;
1067                        find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
1068                }
1069        }
1070}
1071
1072sub graft_file_copy_lib {
1073        my ($grafts, $l_map, $u) = @_;
1074        my $tree_paths = $l_map->{$u};
1075        my $pfx = common_prefix([keys %$tree_paths]);
1076        my ($repo, $path) = repo_path_split($u.$pfx);
1077        $SVN_LOG ||= libsvn_connect($repo);
1078        $SVN ||= libsvn_connect($repo);
1079
1080        my ($base, $head) = libsvn_parse_revision();
1081        my $inc = 1000;
1082        my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
1083        my $eh = $SVN::Error::handler;
1084        $SVN::Error::handler = \&libsvn_skip_unknown_revs;
1085        while (1) {
1086                my $pool = SVN::Pool->new;
1087                libsvn_get_log($SVN_LOG, "/$path", $min, $max, 0, 1, 1,
1088                        sub {
1089                                libsvn_graft_file_copies($grafts, $tree_paths,
1090                                                        $path, @_);
1091                        }, $pool);
1092                $pool->clear;
1093                last if ($max >= $head);
1094                $min = $max + 1;
1095                $max += $inc;
1096                $max = $head if ($max > $head);
1097        }
1098        $SVN::Error::handler = $eh;
1099}
1100
1101sub process_merge_msg_matches {
1102        my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1103        my (@strong, @weak);
1104        foreach (@matches) {
1105                # merging with ourselves is not interesting
1106                next if $_ eq $p;
1107                if ($l_map->{$u}->{$_}) {
1108                        push @strong, $_;
1109                } else {
1110                        push @weak, $_;
1111                }
1112        }
1113        foreach my $w (@weak) {
1114                last if @strong;
1115                # no exact match, use branch name as regexp.
1116                my $re = qr/\Q$w\E/i;
1117                foreach (keys %{$l_map->{$u}}) {
1118                        if (/$re/) {
1119                                push @strong, $l_map->{$u}->{$_};
1120                                last;
1121                        }
1122                }
1123                last if @strong;
1124                $w = basename($w);
1125                $re = qr/\Q$w\E/i;
1126                foreach (keys %{$l_map->{$u}}) {
1127                        if (/$re/) {
1128                                push @strong, $l_map->{$u}->{$_};
1129                                last;
1130                        }
1131                }
1132        }
1133        my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1134                                        \s(?:[a-f\d\-]+)$/xsm);
1135        unless (defined $rev) {
1136                ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1137                                        \@(?:[a-f\d\-]+)/xsm);
1138                return unless defined $rev;
1139        }
1140        foreach my $m (@strong) {
1141                my ($r0, $s0) = find_rev_before($rev, $m, 1);
1142                $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1143        }
1144}
1145
1146sub graft_merge_msg {
1147        my ($grafts, $l_map, $u, $p, @re) = @_;
1148
1149        my $x = $l_map->{$u}->{$p};
1150        my $rl = rev_list_raw($x);
1151        while (my $c = next_rev_list_entry($rl)) {
1152                foreach my $re (@re) {
1153                        my (@br) = ($c->{m} =~ /$re/g);
1154                        next unless @br;
1155                        process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1156                }
1157        }
1158}
1159
1160sub read_uuid {
1161        return if $SVN_UUID;
1162        if ($_use_lib) {
1163                my $pool = SVN::Pool->new;
1164                $SVN_UUID = $SVN->get_uuid($pool);
1165                $pool->clear;
1166        } else {
1167                my $info = shift || svn_info('.');
1168                $SVN_UUID = $info->{'Repository UUID'} or
1169                                        croak "Repository UUID unreadable\n";
1170        }
1171}
1172
1173sub quiet_run {
1174        my $pid = fork;
1175        defined $pid or croak $!;
1176        if (!$pid) {
1177                open my $null, '>', '/dev/null' or croak $!;
1178                open STDERR, '>&', $null or croak $!;
1179                open STDOUT, '>&', $null or croak $!;
1180                exec @_ or croak $!;
1181        }
1182        waitpid $pid, 0;
1183        return $?;
1184}
1185
1186sub repo_path_split {
1187        my $full_url = shift;
1188        $full_url =~ s#/+$##;
1189
1190        foreach (@repo_path_split_cache) {
1191                if ($full_url =~ s#$_##) {
1192                        my $u = $1;
1193                        $full_url =~ s#^/+##;
1194                        return ($u, $full_url);
1195                }
1196        }
1197
1198        if ($_use_lib) {
1199                my $tmp = libsvn_connect($full_url);
1200                my $url = $tmp->get_repos_root;
1201                $full_url =~ s#^\Q$url\E/*##;
1202                push @repo_path_split_cache, qr/^(\Q$url\E)/;
1203                return ($url, $full_url);
1204        } else {
1205                my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
1206                $path =~ s#^/+##;
1207                my @paths = split(m#/+#, $path);
1208                while (quiet_run(qw/svn ls --non-interactive/, $url)) {
1209                        my $n = shift @paths || last;
1210                        $url .= "/$n";
1211                }
1212                push @repo_path_split_cache, qr/^(\Q$url\E)/;
1213                $path = join('/',@paths);
1214                return ($url, $path);
1215        }
1216}
1217
1218sub setup_git_svn {
1219        defined $SVN_URL or croak "SVN repository location required\n";
1220        unless (-d $GIT_DIR) {
1221                croak "GIT_DIR=$GIT_DIR does not exist!\n";
1222        }
1223        mkpath([$GIT_SVN_DIR]);
1224        mkpath(["$GIT_SVN_DIR/info"]);
1225        open my $fh, '>>',$REVDB or croak $!;
1226        close $fh;
1227        s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1228
1229}
1230
1231sub assert_svn_wc_clean {
1232        return if $_use_lib;
1233        my ($svn_rev) = @_;
1234        croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
1235        my $lcr = svn_info('.')->{'Last Changed Rev'};
1236        if ($svn_rev != $lcr) {
1237                print STDERR "Checking for copy-tree ... ";
1238                my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1239                                                "-r$lcr:$svn_rev")));
1240                if (@diff) {
1241                        croak "Nope!  Expected r$svn_rev, got r$lcr\n";
1242                } else {
1243                        print STDERR "OK!\n";
1244                }
1245        }
1246        my @status = grep(!/^Performing status on external/,(`svn status`));
1247        @status = grep(!/^\s*$/,@status);
1248        if (scalar @status) {
1249                print STDERR "Tree ($SVN_WC) is not clean:\n";
1250                print STDERR $_ foreach @status;
1251                croak;
1252        }
1253}
1254
1255sub get_tree_from_treeish {
1256        my ($treeish) = @_;
1257        croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1258        chomp(my $type = `git-cat-file -t $treeish`);
1259        my $expected;
1260        while ($type eq 'tag') {
1261                chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1262        }
1263        if ($type eq 'commit') {
1264                $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1265                ($expected) = ($expected =~ /^tree ($sha1)$/);
1266                die "Unable to get tree from $treeish\n" unless $expected;
1267        } elsif ($type eq 'tree') {
1268                $expected = $treeish;
1269        } else {
1270                die "$treeish is a $type, expected tree, tag or commit\n";
1271        }
1272        return $expected;
1273}
1274
1275sub assert_tree {
1276        return if $_use_lib;
1277        my ($treeish) = @_;
1278        my $expected = get_tree_from_treeish($treeish);
1279
1280        my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1281        if (-e $tmpindex) {
1282                unlink $tmpindex or croak $!;
1283        }
1284        my $old_index = set_index($tmpindex);
1285        index_changes(1);
1286        chomp(my $tree = `git-write-tree`);
1287        restore_index($old_index);
1288        if ($tree ne $expected) {
1289                croak "Tree mismatch, Got: $tree, Expected: $expected\n";
1290        }
1291        unlink $tmpindex;
1292}
1293
1294sub parse_diff_tree {
1295        my $diff_fh = shift;
1296        local $/ = "\0";
1297        my $state = 'meta';
1298        my @mods;
1299        while (<$diff_fh>) {
1300                chomp $_; # this gets rid of the trailing "\0"
1301                if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1302                                        $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1303                        push @mods, {   mode_a => $1, mode_b => $2,
1304                                        sha1_b => $3, chg => $4 };
1305                        if ($4 =~ /^(?:C|R)$/) {
1306                                $state = 'file_a';
1307                        } else {
1308                                $state = 'file_b';
1309                        }
1310                } elsif ($state eq 'file_a') {
1311                        my $x = $mods[$#mods] or croak "Empty array\n";
1312                        if ($x->{chg} !~ /^(?:C|R)$/) {
1313                                croak "Error parsing $_, $x->{chg}\n";
1314                        }
1315                        $x->{file_a} = $_;
1316                        $state = 'file_b';
1317                } elsif ($state eq 'file_b') {
1318                        my $x = $mods[$#mods] or croak "Empty array\n";
1319                        if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1320                                croak "Error parsing $_, $x->{chg}\n";
1321                        }
1322                        if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1323                                croak "Error parsing $_, $x->{chg}\n";
1324                        }
1325                        $x->{file_b} = $_;
1326                        $state = 'meta';
1327                } else {
1328                        croak "Error parsing $_\n";
1329                }
1330        }
1331        close $diff_fh or croak $?;
1332
1333        return \@mods;
1334}
1335
1336sub svn_check_prop_executable {
1337        my $m = shift;
1338        return if -l $m->{file_b};
1339        if ($m->{mode_b} =~ /755$/) {
1340                chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1341                if ($m->{mode_a} !~ /755$/) {
1342                        sys(qw(svn propset svn:executable 1), $m->{file_b});
1343                }
1344                -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
1345        } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1346                sys(qw(svn propdel svn:executable), $m->{file_b});
1347                chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1348                -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
1349        }
1350}
1351
1352sub svn_ensure_parent_path {
1353        my $dir_b = dirname(shift);
1354        svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1355        mkpath([$dir_b]) unless (-d $dir_b);
1356        sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1357}
1358
1359sub precommit_check {
1360        my $mods = shift;
1361        my (%rm_file, %rmdir_check, %added_check);
1362
1363        my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1364        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1365                if ($m->{chg} eq 'R') {
1366                        if (-d $m->{file_b}) {
1367                                err_dir_to_file("$m->{file_a} => $m->{file_b}");
1368                        }
1369                        # dir/$file => dir/file/$file
1370                        my $dirname = dirname($m->{file_b});
1371                        while ($dirname ne File::Spec->curdir) {
1372                                if ($dirname ne $m->{file_a}) {
1373                                        $dirname = dirname($dirname);
1374                                        next;
1375                                }
1376                                err_file_to_dir("$m->{file_a} => $m->{file_b}");
1377                        }
1378                        # baz/zzz => baz (baz is a file)
1379                        $dirname = dirname($m->{file_a});
1380                        while ($dirname ne File::Spec->curdir) {
1381                                if ($dirname ne $m->{file_b}) {
1382                                        $dirname = dirname($dirname);
1383                                        next;
1384                                }
1385                                err_dir_to_file("$m->{file_a} => $m->{file_b}");
1386                        }
1387                }
1388                if ($m->{chg} =~ /^(D|R)$/) {
1389                        my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1390                        $rm_file{ $m->{$t} } = 1;
1391                        my $dirname = dirname( $m->{$t} );
1392                        my $basename = basename( $m->{$t} );
1393                        $rmdir_check{$dirname}->{$basename} = 1;
1394                } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1395                        if (-d $m->{file_b}) {
1396                                err_dir_to_file($m->{file_b});
1397                        }
1398                        my $dirname = dirname( $m->{file_b} );
1399                        my $basename = basename( $m->{file_b} );
1400                        $added_check{$dirname}->{$basename} = 1;
1401                        while ($dirname ne File::Spec->curdir) {
1402                                if ($rm_file{$dirname}) {
1403                                        err_file_to_dir($m->{file_b});
1404                                }
1405                                $dirname = dirname $dirname;
1406                        }
1407                }
1408        }
1409        return (\%rmdir_check, \%added_check);
1410
1411        sub err_dir_to_file {
1412                my $file = shift;
1413                print STDERR "Node change from directory to file ",
1414                                "is not supported by Subversion: ",$file,"\n";
1415                exit 1;
1416        }
1417        sub err_file_to_dir {
1418                my $file = shift;
1419                print STDERR "Node change from file to directory ",
1420                                "is not supported by Subversion: ",$file,"\n";
1421                exit 1;
1422        }
1423}
1424
1425
1426sub get_diff {
1427        my ($from, $treeish) = @_;
1428        assert_tree($from);
1429        print "diff-tree $from $treeish\n";
1430        my $pid = open my $diff_fh, '-|';
1431        defined $pid or croak $!;
1432        if ($pid == 0) {
1433                my @diff_tree = qw(git-diff-tree -z -r);
1434                if ($_cp_similarity) {
1435                        push @diff_tree, "-C$_cp_similarity";
1436                } else {
1437                        push @diff_tree, '-C';
1438                }
1439                push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1440                push @diff_tree, "-l$_l" if defined $_l;
1441                exec(@diff_tree, $from, $treeish) or croak $!;
1442        }
1443        return parse_diff_tree($diff_fh);
1444}
1445
1446sub svn_checkout_tree {
1447        my ($from, $treeish) = @_;
1448        my $mods = get_diff($from->{commit}, $treeish);
1449        return $mods unless (scalar @$mods);
1450        my ($rm, $add) = precommit_check($mods);
1451
1452        my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1453        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1454                if ($m->{chg} eq 'C') {
1455                        svn_ensure_parent_path( $m->{file_b} );
1456                        sys(qw(svn cp),         $m->{file_a}, $m->{file_b});
1457                        apply_mod_line_blob($m);
1458                        svn_check_prop_executable($m);
1459                } elsif ($m->{chg} eq 'D') {
1460                        sys(qw(svn rm --force), $m->{file_b});
1461                } elsif ($m->{chg} eq 'R') {
1462                        svn_ensure_parent_path( $m->{file_b} );
1463                        sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
1464                        apply_mod_line_blob($m);
1465                        svn_check_prop_executable($m);
1466                } elsif ($m->{chg} eq 'M') {
1467                        apply_mod_line_blob($m);
1468                        svn_check_prop_executable($m);
1469                } elsif ($m->{chg} eq 'T') {
1470                        sys(qw(svn rm --force),$m->{file_b});
1471                        apply_mod_line_blob($m);
1472                        sys(qw(svn add), $m->{file_b});
1473                        svn_check_prop_executable($m);
1474                } elsif ($m->{chg} eq 'A') {
1475                        svn_ensure_parent_path( $m->{file_b} );
1476                        apply_mod_line_blob($m);
1477                        sys(qw(svn add), $m->{file_b});
1478                        svn_check_prop_executable($m);
1479                } else {
1480                        croak "Invalid chg: $m->{chg}\n";
1481                }
1482        }
1483
1484        assert_tree($treeish);
1485        if ($_rmdir) { # remove empty directories
1486                handle_rmdir($rm, $add);
1487        }
1488        assert_tree($treeish);
1489        return $mods;
1490}
1491
1492sub libsvn_checkout_tree {
1493        my ($from, $treeish, $ed) = @_;
1494        my $mods = get_diff($from, $treeish);
1495        return $mods unless (scalar @$mods);
1496        my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1497        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1498                my $f = $m->{chg};
1499                if (defined $o{$f}) {
1500                        $ed->$f($m, $_q);
1501                } else {
1502                        croak "Invalid change type: $f\n";
1503                }
1504        }
1505        $ed->rmdirs($_q) if $_rmdir;
1506        return $mods;
1507}
1508
1509# svn ls doesn't work with respect to the current working tree, but what's
1510# in the repository.  There's not even an option for it... *sigh*
1511# (added files don't show up and removed files remain in the ls listing)
1512sub svn_ls_current {
1513        my ($dir, $rm, $add) = @_;
1514        chomp(my @ls = safe_qx('svn','ls',$dir));
1515        my @ret = ();
1516        foreach (@ls) {
1517                s#/$##; # trailing slashes are evil
1518                push @ret, $_ unless $rm->{$dir}->{$_};
1519        }
1520        if (exists $add->{$dir}) {
1521                push @ret, keys %{$add->{$dir}};
1522        }
1523        return \@ret;
1524}
1525
1526sub handle_rmdir {
1527        my ($rm, $add) = @_;
1528
1529        foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1530                my $ls = svn_ls_current($dir, $rm, $add);
1531                next if (scalar @$ls);
1532                sys(qw(svn rm --force),$dir);
1533
1534                my $dn = dirname $dir;
1535                $rm->{ $dn }->{ basename $dir } = 1;
1536                $ls = svn_ls_current($dn, $rm, $add);
1537                while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1538                        sys(qw(svn rm --force),$dn);
1539                        $dir = basename $dn;
1540                        $dn = dirname $dn;
1541                        $rm->{ $dn }->{ $dir } = 1;
1542                        $ls = svn_ls_current($dn, $rm, $add);
1543                }
1544        }
1545}
1546
1547sub get_commit_message {
1548        my ($commit, $commit_msg) = (@_);
1549        my %log_msg = ( msg => '' );
1550        open my $msg, '>', $commit_msg or croak $!;
1551
1552        chomp(my $type = `git-cat-file -t $commit`);
1553        if ($type eq 'commit' || $type eq 'tag') {
1554                my $pid = open my $msg_fh, '-|';
1555                defined $pid or croak $!;
1556
1557                if ($pid == 0) {
1558                        exec('git-cat-file', $type, $commit) or croak $!;
1559                }
1560                my $in_msg = 0;
1561                while (<$msg_fh>) {
1562                        if (!$in_msg) {
1563                                $in_msg = 1 if (/^\s*$/);
1564                        } elsif (/^git-svn-id: /) {
1565                                # skip this, we regenerate the correct one
1566                                # on re-fetch anyways
1567                        } else {
1568                                print $msg $_ or croak $!;
1569                        }
1570                }
1571                close $msg_fh or croak $?;
1572        }
1573        close $msg or croak $!;
1574
1575        if ($_edit || ($type eq 'tree')) {
1576                my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1577                system($editor, $commit_msg);
1578        }
1579
1580        # file_to_s removes all trailing newlines, so just use chomp() here:
1581        open $msg, '<', $commit_msg or croak $!;
1582        { local $/; chomp($log_msg{msg} = <$msg>); }
1583        close $msg or croak $!;
1584
1585        return \%log_msg;
1586}
1587
1588sub set_svn_commit_env {
1589        if (defined $LC_ALL) {
1590                $ENV{LC_ALL} = $LC_ALL;
1591        } else {
1592                delete $ENV{LC_ALL};
1593        }
1594}
1595
1596sub svn_commit_tree {
1597        my ($last, $commit) = @_;
1598        my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1599        my $log_msg = get_commit_message($commit, $commit_msg);
1600        my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
1601        print "Committing $commit: $oneline\n";
1602
1603        set_svn_commit_env();
1604        my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
1605        $ENV{LC_ALL} = 'C';
1606        unlink $commit_msg;
1607        my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1608        if (!defined $committed) {
1609                my $out = join("\n",@ci_output);
1610                print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1611                                $out, "\n\nAssuming English locale...";
1612                ($committed) = ($out =~ /^Committed revision \d+\./sm);
1613                defined $committed or die " FAILED!\n",
1614                        "Commit output failed to parse committed revision!\n",
1615                print STDERR " OK\n";
1616        }
1617
1618        my @svn_up = qw(svn up);
1619        push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
1620        if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
1621                push @svn_up, "-r$committed";
1622                sys(@svn_up);
1623                my $info = svn_info('.');
1624                my $date = $info->{'Last Changed Date'} or die "Missing date\n";
1625                if ($info->{'Last Changed Rev'} != $committed) {
1626                        croak "$info->{'Last Changed Rev'} != $committed\n"
1627                }
1628                my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1629                                        /(\d{4})\-(\d\d)\-(\d\d)\s
1630                                         (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1631                                         or croak "Failed to parse date: $date\n";
1632                $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1633                $log_msg->{author} = $info->{'Last Changed Author'};
1634                $log_msg->{revision} = $committed;
1635                $log_msg->{msg} .= "\n";
1636                $log_msg->{parents} = [ $last->{commit} ];
1637                $log_msg->{commit} = git_commit($log_msg, $commit);
1638                return $log_msg;
1639        }
1640        # resync immediately
1641        push @svn_up, "-r$last->{revision}";
1642        sys(@svn_up);
1643        return fetch("$committed=$commit");
1644}
1645
1646sub rev_list_raw {
1647        my (@args) = @_;
1648        my $pid = open my $fh, '-|';
1649        defined $pid or croak $!;
1650        if (!$pid) {
1651                exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1652        }
1653        return { fh => $fh, t => { } };
1654}
1655
1656sub next_rev_list_entry {
1657        my $rl = shift;
1658        my $fh = $rl->{fh};
1659        my $x = $rl->{t};
1660        while (<$fh>) {
1661                if (/^commit ($sha1)$/o) {
1662                        if ($x->{c}) {
1663                                $rl->{t} = { c => $1 };
1664                                return $x;
1665                        } else {
1666                                $x->{c} = $1;
1667                        }
1668                } elsif (/^parent ($sha1)$/o) {
1669                        $x->{p}->{$1} = 1;
1670                } elsif (s/^    //) {
1671                        $x->{m} ||= '';
1672                        $x->{m} .= $_;
1673                }
1674        }
1675        return ($x != $rl->{t}) ? $x : undef;
1676}
1677
1678# read the entire log into a temporary file (which is removed ASAP)
1679# and store the file handle + parser state
1680sub svn_log_raw {
1681        my (@log_args) = @_;
1682        my $log_fh = IO::File->new_tmpfile or croak $!;
1683        my $pid = fork;
1684        defined $pid or croak $!;
1685        if (!$pid) {
1686                open STDOUT, '>&', $log_fh or croak $!;
1687                exec (qw(svn log), @log_args) or croak $!
1688        }
1689        waitpid $pid, 0;
1690        croak $? if $?;
1691        seek $log_fh, 0, 0 or croak $!;
1692        return { state => 'sep', fh => $log_fh };
1693}
1694
1695sub next_log_entry {
1696        my $log = shift; # retval of svn_log_raw()
1697        my $ret = undef;
1698        my $fh = $log->{fh};
1699
1700        while (<$fh>) {
1701                chomp;
1702                if (/^\-{72}$/) {
1703                        if ($log->{state} eq 'msg') {
1704                                if ($ret->{lines}) {
1705                                        $ret->{msg} .= $_."\n";
1706                                        unless(--$ret->{lines}) {
1707                                                $log->{state} = 'sep';
1708                                        }
1709                                } else {
1710                                        croak "Log parse error at: $_\n",
1711                                                $ret->{revision},
1712                                                "\n";
1713                                }
1714                                next;
1715                        }
1716                        if ($log->{state} ne 'sep') {
1717                                croak "Log parse error at: $_\n",
1718                                        "state: $log->{state}\n",
1719                                        $ret->{revision},
1720                                        "\n";
1721                        }
1722                        $log->{state} = 'rev';
1723
1724                        # if we have an empty log message, put something there:
1725                        if ($ret) {
1726                                $ret->{msg} ||= "\n";
1727                                delete $ret->{lines};
1728                                return $ret;
1729                        }
1730                        next;
1731                }
1732                if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
1733                        my $rev = $1;
1734                        my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1735                        ($lines) = ($lines =~ /(\d+)/);
1736                        my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1737                                        /(\d{4})\-(\d\d)\-(\d\d)\s
1738                                         (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1739                                         or croak "Failed to parse date: $date\n";
1740                        $ret = {        revision => $rev,
1741                                        date => "$tz $Y-$m-$d $H:$M:$S",
1742                                        author => $author,
1743                                        lines => $lines,
1744                                        msg => '' };
1745                        if (defined $_authors && ! defined $users{$author}) {
1746                                die "Author: $author not defined in ",
1747                                                "$_authors file\n";
1748                        }
1749                        $log->{state} = 'msg_start';
1750                        next;
1751                }
1752                # skip the first blank line of the message:
1753                if ($log->{state} eq 'msg_start' && /^$/) {
1754                        $log->{state} = 'msg';
1755                } elsif ($log->{state} eq 'msg') {
1756                        if ($ret->{lines}) {
1757                                $ret->{msg} .= $_."\n";
1758                                unless (--$ret->{lines}) {
1759                                        $log->{state} = 'sep';
1760                                }
1761                        } else {
1762                                croak "Log parse error at: $_\n",
1763                                        $ret->{revision},"\n";
1764                        }
1765                }
1766        }
1767        return $ret;
1768}
1769
1770sub svn_info {
1771        my $url = shift || $SVN_URL;
1772
1773        my $pid = open my $info_fh, '-|';
1774        defined $pid or croak $!;
1775
1776        if ($pid == 0) {
1777                exec(qw(svn info),$url) or croak $!;
1778        }
1779
1780        my $ret = {};
1781        # only single-lines seem to exist in svn info output
1782        while (<$info_fh>) {
1783                chomp $_;
1784                if (m#^([^:]+)\s*:\s*(\S.*)$#) {
1785                        $ret->{$1} = $2;
1786                        push @{$ret->{-order}}, $1;
1787                }
1788        }
1789        close $info_fh or croak $?;
1790        return $ret;
1791}
1792
1793sub sys { system(@_) == 0 or croak $? }
1794
1795sub do_update_index {
1796        my ($z_cmd, $cmd, $no_text_base) = @_;
1797
1798        my $z = open my $p, '-|';
1799        defined $z or croak $!;
1800        unless ($z) { exec @$z_cmd or croak $! }
1801
1802        my $pid = open my $ui, '|-';
1803        defined $pid or croak $!;
1804        unless ($pid) {
1805                exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1806        }
1807        local $/ = "\0";
1808        while (my $x = <$p>) {
1809                chomp $x;
1810                if (!$no_text_base && lstat $x && ! -l _ &&
1811                                svn_propget_base('svn:keywords', $x)) {
1812                        my $mode = -x _ ? 0755 : 0644;
1813                        my ($v,$d,$f) = File::Spec->splitpath($x);
1814                        my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1815                                                'text-base',"$f.svn-base");
1816                        $tb =~ s#^/##;
1817                        unless (-f $tb) {
1818                                $tb = File::Spec->catfile($d, '.svn',
1819                                                'text-base',"$f.svn-base");
1820                                $tb =~ s#^/##;
1821                        }
1822                        my @s = stat($x);
1823                        unlink $x or croak $!;
1824                        copy($tb, $x);
1825                        chmod(($mode &~ umask), $x) or croak $!;
1826                        utime $s[8], $s[9], $x;
1827                }
1828                print $ui $x,"\0";
1829        }
1830        close $ui or croak $?;
1831}
1832
1833sub index_changes {
1834        return if $_use_lib;
1835
1836        if (!-f "$GIT_SVN_DIR/info/exclude") {
1837                open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1838                print $fd '.svn',"\n";
1839                close $fd or croak $!;
1840        }
1841        my $no_text_base = shift;
1842        do_update_index([qw/git-diff-files --name-only -z/],
1843                        'remove',
1844                        $no_text_base);
1845        do_update_index([qw/git-ls-files -z --others/,
1846                                "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1847                        'add',
1848                        $no_text_base);
1849}
1850
1851sub s_to_file {
1852        my ($str, $file, $mode) = @_;
1853        open my $fd,'>',$file or croak $!;
1854        print $fd $str,"\n" or croak $!;
1855        close $fd or croak $!;
1856        chmod ($mode &~ umask, $file) if (defined $mode);
1857}
1858
1859sub file_to_s {
1860        my $file = shift;
1861        open my $fd,'<',$file or croak "$!: file: $file\n";
1862        local $/;
1863        my $ret = <$fd>;
1864        close $fd or croak $!;
1865        $ret =~ s/\s*$//s;
1866        return $ret;
1867}
1868
1869sub assert_revision_unknown {
1870        my $r = shift;
1871        if (my $c = revdb_get($REVDB, $r)) {
1872                croak "$r = $c already exists! Why are we refetching it?";
1873        }
1874}
1875
1876sub trees_eq {
1877        my ($x, $y) = @_;
1878        my @x = safe_qx('git-cat-file','commit',$x);
1879        my @y = safe_qx('git-cat-file','commit',$y);
1880        if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1881                                || $y[0] !~ /^tree $sha1\n$/) {
1882                print STDERR "Trees not equal: $y[0] != $x[0]\n";
1883                return 0
1884        }
1885        return 1;
1886}
1887
1888sub git_commit {
1889        my ($log_msg, @parents) = @_;
1890        assert_revision_unknown($log_msg->{revision});
1891        map_tree_joins() if (@_branch_from && !%tree_map);
1892
1893        my (@tmp_parents, @exec_parents, %seen_parent);
1894        if (my $lparents = $log_msg->{parents}) {
1895                @tmp_parents = @$lparents
1896        }
1897        # commit parents can be conditionally bound to a particular
1898        # svn revision via: "svn_revno=commit_sha1", filter them out here:
1899        foreach my $p (@parents) {
1900                next unless defined $p;
1901                if ($p =~ /^(\d+)=($sha1_short)$/o) {
1902                        if ($1 == $log_msg->{revision}) {
1903                                push @tmp_parents, $2;
1904                        }
1905                } else {
1906                        push @tmp_parents, $p if $p =~ /$sha1_short/o;
1907                }
1908        }
1909        my $tree = $log_msg->{tree};
1910        if (!defined $tree) {
1911                my $index = set_index($GIT_SVN_INDEX);
1912                index_changes();
1913                chomp($tree = `git-write-tree`);
1914                croak $? if $?;
1915                restore_index($index);
1916        }
1917
1918        # just in case we clobber the existing ref, we still want that ref
1919        # as our parent:
1920        if (my $cur = eval { file_to_s("$GIT_DIR/refs/remotes/$GIT_SVN") }) {
1921                push @tmp_parents, $cur;
1922        }
1923
1924        if (exists $tree_map{$tree}) {
1925                foreach my $p (@{$tree_map{$tree}}) {
1926                        my $skip;
1927                        foreach (@tmp_parents) {
1928                                # see if a common parent is found
1929                                my $mb = eval {
1930                                        safe_qx('git-merge-base', $_, $p)
1931                                };
1932                                next if ($@ || $?);
1933                                $skip = 1;
1934                                last;
1935                        }
1936                        next if $skip;
1937                        my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
1938                        next if (($SVN_UUID eq $uuid_p) &&
1939                                                ($log_msg->{revision} > $r_p));
1940                        next if (defined $url_p && defined $SVN_URL &&
1941                                                ($SVN_UUID eq $uuid_p) &&
1942                                                ($url_p eq $SVN_URL));
1943                        push @tmp_parents, $p;
1944                }
1945        }
1946        foreach (@tmp_parents) {
1947                next if $seen_parent{$_};
1948                $seen_parent{$_} = 1;
1949                push @exec_parents, $_;
1950                # MAXPARENT is defined to 16 in commit-tree.c:
1951                last if @exec_parents > 16;
1952        }
1953
1954        set_commit_env($log_msg);
1955        my @exec = ('git-commit-tree', $tree);
1956        push @exec, '-p', $_  foreach @exec_parents;
1957        defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1958                                                                or croak $!;
1959        print $msg_fh $log_msg->{msg} or croak $!;
1960        unless ($_no_metadata) {
1961                print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision}",
1962                                        " $SVN_UUID\n" or croak $!;
1963        }
1964        $msg_fh->flush == 0 or croak $!;
1965        close $msg_fh or croak $!;
1966        chomp(my $commit = do { local $/; <$out_fh> });
1967        close $out_fh or croak $!;
1968        waitpid $pid, 0;
1969        croak $? if $?;
1970        if ($commit !~ /^$sha1$/o) {
1971                die "Failed to commit, invalid sha1: $commit\n";
1972        }
1973        sys('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1974        revdb_set($REVDB, $log_msg->{revision}, $commit);
1975
1976        # this output is read via pipe, do not change:
1977        print "r$log_msg->{revision} = $commit\n";
1978        check_repack();
1979        return $commit;
1980}
1981
1982sub check_repack {
1983        if ($_repack && (--$_repack_nr == 0)) {
1984                $_repack_nr = $_repack;
1985                sys("git repack $_repack_flags");
1986        }
1987}
1988
1989sub set_commit_env {
1990        my ($log_msg) = @_;
1991        my $author = $log_msg->{author};
1992        if (!defined $author || length $author == 0) {
1993                $author = '(no author)';
1994        }
1995        my ($name,$email) = defined $users{$author} ?  @{$users{$author}}
1996                                : ($author,"$author\@$SVN_UUID");
1997        $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1998        $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1999        $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
2000}
2001
2002sub apply_mod_line_blob {
2003        my $m = shift;
2004        if ($m->{mode_b} =~ /^120/) {
2005                blob_to_symlink($m->{sha1_b}, $m->{file_b});
2006        } else {
2007                blob_to_file($m->{sha1_b}, $m->{file_b});
2008        }
2009}
2010
2011sub blob_to_symlink {
2012        my ($blob, $link) = @_;
2013        defined $link or croak "\$link not defined!\n";
2014        croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
2015        if (-l $link || -f _) {
2016                unlink $link or croak $!;
2017        }
2018
2019        my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
2020        symlink $dest, $link or croak $!;
2021}
2022
2023sub blob_to_file {
2024        my ($blob, $file) = @_;
2025        defined $file or croak "\$file not defined!\n";
2026        croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
2027        if (-l $file || -f _) {
2028                unlink $file or croak $!;
2029        }
2030
2031        open my $blob_fh, '>', $file or croak "$!: $file\n";
2032        my $pid = fork;
2033        defined $pid or croak $!;
2034
2035        if ($pid == 0) {
2036                open STDOUT, '>&', $blob_fh or croak $!;
2037                exec('git-cat-file','blob',$blob) or croak $!;
2038        }
2039        waitpid $pid, 0;
2040        croak $? if $?;
2041
2042        close $blob_fh or croak $!;
2043}
2044
2045sub safe_qx {
2046        my $pid = open my $child, '-|';
2047        defined $pid or croak $!;
2048        if ($pid == 0) {
2049                exec(@_) or croak $!;
2050        }
2051        my @ret = (<$child>);
2052        close $child or croak $?;
2053        die $? if $?; # just in case close didn't error out
2054        return wantarray ? @ret : join('',@ret);
2055}
2056
2057sub svn_compat_check {
2058        if ($_follow_parent) {
2059                print STDERR 'E: --follow-parent functionality is only ',
2060                                "available when SVN libraries are used\n";
2061                exit 1;
2062        }
2063        my @co_help = safe_qx(qw(svn co -h));
2064        unless (grep /ignore-externals/,@co_help) {
2065                print STDERR "W: Installed svn version does not support ",
2066                                "--ignore-externals\n";
2067                $_no_ignore_ext = 1;
2068        }
2069        if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
2070                $_svn_co_url_revs = 1;
2071        }
2072        if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
2073                $_svn_pg_peg_revs = 1;
2074        }
2075
2076        # I really, really hope nobody hits this...
2077        unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
2078                print STDERR <<'';
2079W: The installed svn version does not support the --stop-on-copy flag in
2080   the log command.
2081   Lets hope the directory you're tracking is not a branch or tag
2082   and was never moved within the repository...
2083
2084                $_no_stop_copy = 1;
2085        }
2086}
2087
2088# *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
2089# (and they won't honor URL@<rev> without -r<rev>, too!)
2090sub svn_cmd_checkout {
2091        my ($url, $rev, $dir) = @_;
2092        my @cmd = ('svn','co', "-r$rev");
2093        push @cmd, '--ignore-externals' unless $_no_ignore_ext;
2094        $url .= "\@$rev" if $_svn_co_url_revs;
2095        sys(@cmd, $url, $dir);
2096}
2097
2098sub check_upgrade_needed {
2099        if (!-r $REVDB) {
2100                -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
2101                open my $fh, '>>',$REVDB or croak $!;
2102                close $fh;
2103        }
2104        my $old = eval {
2105                my $pid = open my $child, '-|';
2106                defined $pid or croak $!;
2107                if ($pid == 0) {
2108                        close STDERR;
2109                        exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
2110                }
2111                my @ret = (<$child>);
2112                close $child or croak $?;
2113                die $? if $?; # just in case close didn't error out
2114                return wantarray ? @ret : join('',@ret);
2115        };
2116        return unless $old;
2117        my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
2118        if ($@ || !$head) {
2119                print STDERR "Please run: $0 rebuild --upgrade\n";
2120                exit 1;
2121        }
2122}
2123
2124# fills %tree_map with a reverse mapping of trees to commits.  Useful
2125# for finding parents to commit on.
2126sub map_tree_joins {
2127        my %seen;
2128        foreach my $br (@_branch_from) {
2129                my $pid = open my $pipe, '-|';
2130                defined $pid or croak $!;
2131                if ($pid == 0) {
2132                        exec(qw(git-rev-list --topo-order --pretty=raw), $br)
2133                                                                or croak $!;
2134                }
2135                while (<$pipe>) {
2136                        if (/^commit ($sha1)$/o) {
2137                                my $commit = $1;
2138
2139                                # if we've seen a commit,
2140                                # we've seen its parents
2141                                last if $seen{$commit};
2142                                my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
2143                                unless (defined $tree) {
2144                                        die "Failed to parse commit $commit\n";
2145                                }
2146                                push @{$tree_map{$tree}}, $commit;
2147                                $seen{$commit} = 1;
2148                        }
2149                }
2150                close $pipe; # we could be breaking the pipe early
2151        }
2152}
2153
2154sub load_all_refs {
2155        if (@_branch_from) {
2156                print STDERR '--branch|-b parameters are ignored when ',
2157                        "--branch-all-refs|-B is passed\n";
2158        }
2159
2160        # don't worry about rev-list on non-commit objects/tags,
2161        # it shouldn't blow up if a ref is a blob or tree...
2162        chomp(@_branch_from = `git-rev-parse --symbolic --all`);
2163}
2164
2165# '<svn username> = real-name <email address>' mapping based on git-svnimport:
2166sub load_authors {
2167        open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2168        while (<$authors>) {
2169                chomp;
2170                next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2171                my ($user, $name, $email) = ($1, $2, $3);
2172                $users{$user} = [$name, $email];
2173        }
2174        close $authors or croak $!;
2175}
2176
2177sub rload_authors {
2178        open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2179        while (<$authors>) {
2180                chomp;
2181                next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2182                my ($user, $name, $email) = ($1, $2, $3);
2183                $rusers{"$name <$email>"} = $user;
2184        }
2185        close $authors or croak $!;
2186}
2187
2188sub svn_propget_base {
2189        my ($p, $f) = @_;
2190        $f .= '@BASE' if $_svn_pg_peg_revs;
2191        return safe_qx(qw/svn propget/, $p, $f);
2192}
2193
2194sub git_svn_each {
2195        my $sub = shift;
2196        foreach (`git-rev-parse --symbolic --all`) {
2197                next unless s#^refs/remotes/##;
2198                chomp $_;
2199                next unless -f "$GIT_DIR/svn/$_/info/url";
2200                &$sub($_);
2201        }
2202}
2203
2204sub migrate_revdb {
2205        git_svn_each(sub {
2206                my $id = shift;
2207                defined(my $pid = fork) or croak $!;
2208                if (!$pid) {
2209                        $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2210                        init_vars();
2211                        exit 0 if -r $REVDB;
2212                        print "Upgrading svn => git mapping...\n";
2213                        -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
2214                        open my $fh, '>>',$REVDB or croak $!;
2215                        close $fh;
2216                        rebuild();
2217                        print "Done upgrading. You may now delete the ",
2218                                "deprecated $GIT_SVN_DIR/revs directory\n";
2219                        exit 0;
2220                }
2221                waitpid $pid, 0;
2222                croak $? if $?;
2223        });
2224}
2225
2226sub migration_check {
2227        migrate_revdb() unless (-e $REVDB);
2228        return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2229        print "Upgrading repository...\n";
2230        unless (-d "$GIT_DIR/svn") {
2231                mkdir "$GIT_DIR/svn" or croak $!;
2232        }
2233        print "Data from a previous version of git-svn exists, but\n\t",
2234                                "$GIT_SVN_DIR\n\t(required for this version ",
2235                                "($VERSION) of git-svn) does not.\n";
2236
2237        foreach my $x (`git-rev-parse --symbolic --all`) {
2238                next unless $x =~ s#^refs/remotes/##;
2239                chomp $x;
2240                next unless -f "$GIT_DIR/$x/info/url";
2241                my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2242                next unless $u;
2243                my $dn = dirname("$GIT_DIR/svn/$x");
2244                mkpath([$dn]) unless -d $dn;
2245                rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
2246        }
2247        migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
2248        print "Done upgrading.\n";
2249}
2250
2251sub find_rev_before {
2252        my ($r, $id, $eq_ok) = @_;
2253        my $f = "$GIT_DIR/svn/$id/.rev_db";
2254        return (undef,undef) unless -r $f;
2255        --$r unless $eq_ok;
2256        while ($r > 0) {
2257                if (my $c = revdb_get($f, $r)) {
2258                        return ($r, $c);
2259                }
2260                --$r;
2261        }
2262        return (undef, undef);
2263}
2264
2265sub init_vars {
2266        $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2267        $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2268        $REVDB = "$GIT_SVN_DIR/.rev_db";
2269        $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2270        $SVN_URL = undef;
2271        $SVN_WC = "$GIT_SVN_DIR/tree";
2272        %tree_map = ();
2273}
2274
2275# convert GetOpt::Long specs for use by git-repo-config
2276sub read_repo_config {
2277        return unless -d $GIT_DIR;
2278        my $opts = shift;
2279        foreach my $o (keys %$opts) {
2280                my $v = $opts->{$o};
2281                my ($key) = ($o =~ /^([a-z\-]+)/);
2282                $key =~ s/-//g;
2283                my $arg = 'git-repo-config';
2284                $arg .= ' --int' if ($o =~ /[:=]i$/);
2285                $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2286                if (ref $v eq 'ARRAY') {
2287                        chomp(my @tmp = `$arg --get-all svn.$key`);
2288                        @$v = @tmp if @tmp;
2289                } else {
2290                        chomp(my $tmp = `$arg --get svn.$key`);
2291                        if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2292                                $$v = $tmp;
2293                        }
2294                }
2295        }
2296}
2297
2298sub set_default_vals {
2299        if (defined $_repack) {
2300                $_repack = 1000 if ($_repack <= 0);
2301                $_repack_nr = $_repack;
2302                $_repack_flags ||= '-d';
2303        }
2304}
2305
2306sub read_grafts {
2307        my $gr_file = shift;
2308        my ($grafts, $comments) = ({}, {});
2309        if (open my $fh, '<', $gr_file) {
2310                my @tmp;
2311                while (<$fh>) {
2312                        if (/^($sha1)\s+/) {
2313                                my $c = $1;
2314                                if (@tmp) {
2315                                        @{$comments->{$c}} = @tmp;
2316                                        @tmp = ();
2317                                }
2318                                foreach my $p (split /\s+/, $_) {
2319                                        $grafts->{$c}->{$p} = 1;
2320                                }
2321                        } else {
2322                                push @tmp, $_;
2323                        }
2324                }
2325                close $fh or croak $!;
2326                @{$comments->{'END'}} = @tmp if @tmp;
2327        }
2328        return ($grafts, $comments);
2329}
2330
2331sub write_grafts {
2332        my ($grafts, $comments, $gr_file) = @_;
2333
2334        open my $fh, '>', $gr_file or croak $!;
2335        foreach my $c (sort keys %$grafts) {
2336                if ($comments->{$c}) {
2337                        print $fh $_ foreach @{$comments->{$c}};
2338                }
2339                my $p = $grafts->{$c};
2340                my %x; # real parents
2341                delete $p->{$c}; # commits are not self-reproducing...
2342                my $pid = open my $ch, '-|';
2343                defined $pid or croak $!;
2344                if (!$pid) {
2345                        exec(qw/git-cat-file commit/, $c) or croak $!;
2346                }
2347                while (<$ch>) {
2348                        if (/^parent ($sha1)/) {
2349                                $x{$1} = $p->{$1} = 1;
2350                        } else {
2351                                last unless /^\S/;
2352                        }
2353                }
2354                close $ch; # breaking the pipe
2355
2356                # if real parents are the only ones in the grafts, drop it
2357                next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2358
2359                my (@ip, @jp, $mb);
2360                my %del = %x;
2361                @ip = @jp = keys %$p;
2362                foreach my $i (@ip) {
2363                        next if $del{$i} || $p->{$i} == 2;
2364                        foreach my $j (@jp) {
2365                                next if $i eq $j || $del{$j} || $p->{$j} == 2;
2366                                $mb = eval { safe_qx('git-merge-base',$i,$j) };
2367                                next unless $mb;
2368                                chomp $mb;
2369                                next if $x{$mb};
2370                                if ($mb eq $j) {
2371                                        delete $p->{$i};
2372                                        $del{$i} = 1;
2373                                } elsif ($mb eq $i) {
2374                                        delete $p->{$j};
2375                                        $del{$j} = 1;
2376                                }
2377                        }
2378                }
2379
2380                # if real parents are the only ones in the grafts, drop it
2381                next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2382
2383                print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2384        }
2385        if ($comments->{'END'}) {
2386                print $fh $_ foreach @{$comments->{'END'}};
2387        }
2388        close $fh or croak $!;
2389}
2390
2391sub read_url_paths_all {
2392        my ($l_map, $pfx, $p) = @_;
2393        my @dir;
2394        foreach (<$p/*>) {
2395                if (-r "$_/info/url") {
2396                        $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2397                        my $id = $pfx . basename $_;
2398                        my $url = file_to_s("$_/info/url");
2399                        my ($u, $p) = repo_path_split($url);
2400                        $l_map->{$u}->{$p} = $id;
2401                } elsif (-d $_) {
2402                        push @dir, $_;
2403                }
2404        }
2405        foreach (@dir) {
2406                my $x = $_;
2407                $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
2408                read_url_paths_all($l_map, $x, $_);
2409        }
2410}
2411
2412# this one only gets ids that have been imported, not new ones
2413sub read_url_paths {
2414        my $l_map = {};
2415        git_svn_each(sub { my $x = shift;
2416                        my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2417                        my ($u, $p) = repo_path_split($url);
2418                        $l_map->{$u}->{$p} = $x;
2419                        });
2420        return $l_map;
2421}
2422
2423sub extract_metadata {
2424        my $id = shift or return (undef, undef, undef);
2425        my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2426                                                        \s([a-f\d\-]+)$/x);
2427        if (!$rev || !$uuid || !$url) {
2428                # some of the original repositories I made had
2429                # identifiers like this:
2430                ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2431        }
2432        return ($url, $rev, $uuid);
2433}
2434
2435sub cmt_metadata {
2436        return extract_metadata((grep(/^git-svn-id: /,
2437                safe_qx(qw/git-cat-file commit/, shift)))[-1]);
2438}
2439
2440sub get_commit_time {
2441        my $cmt = shift;
2442        defined(my $pid = open my $fh, '-|') or croak $!;
2443        if (!$pid) {
2444                exec qw/git-rev-list --pretty=raw -n1/, $cmt or croak $!;
2445        }
2446        while (<$fh>) {
2447                /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
2448                my ($s, $tz) = ($1, $2);
2449                if ($tz =~ s/^\+//) {
2450                        $s += tz_to_s_offset($tz);
2451                } elsif ($tz =~ s/^\-//) {
2452                        $s -= tz_to_s_offset($tz);
2453                }
2454                close $fh;
2455                return $s;
2456        }
2457        die "Can't get commit time for commit: $cmt\n";
2458}
2459
2460sub tz_to_s_offset {
2461        my ($tz) = @_;
2462        $tz =~ s/(\d\d)$//;
2463        return ($1 * 60) + ($tz * 3600);
2464}
2465
2466sub setup_pager { # translated to Perl from pager.c
2467        return unless (-t *STDOUT);
2468        my $pager = $ENV{PAGER};
2469        if (!defined $pager) {
2470                $pager = 'less';
2471        } elsif (length $pager == 0 || $pager eq 'cat') {
2472                return;
2473        }
2474        pipe my $rfd, my $wfd or return;
2475        defined(my $pid = fork) or croak $!;
2476        if (!$pid) {
2477                open STDOUT, '>&', $wfd or croak $!;
2478                return;
2479        }
2480        open STDIN, '<&', $rfd or croak $!;
2481        $ENV{LESS} ||= '-S';
2482        exec $pager or croak "Can't run pager: $!\n";;
2483}
2484
2485sub get_author_info {
2486        my ($dest, $author, $t, $tz) = @_;
2487        $author =~ s/(?:^\s*|\s*$)//g;
2488        $dest->{a_raw} = $author;
2489        my $_a;
2490        if ($_authors) {
2491                $_a = $rusers{$author} || undef;
2492        }
2493        if (!$_a) {
2494                ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2495        }
2496        $dest->{t} = $t;
2497        $dest->{tz} = $tz;
2498        $dest->{a} = $_a;
2499        # Date::Parse isn't in the standard Perl distro :(
2500        if ($tz =~ s/^\+//) {
2501                $t += tz_to_s_offset($tz);
2502        } elsif ($tz =~ s/^\-//) {
2503                $t -= tz_to_s_offset($tz);
2504        }
2505        $dest->{t_utc} = $t;
2506}
2507
2508sub process_commit {
2509        my ($c, $r_min, $r_max, $defer) = @_;
2510        if (defined $r_min && defined $r_max) {
2511                if ($r_min == $c->{r} && $r_min == $r_max) {
2512                        show_commit($c);
2513                        return 0;
2514                }
2515                return 1 if $r_min == $r_max;
2516                if ($r_min < $r_max) {
2517                        # we need to reverse the print order
2518                        return 0 if (defined $_limit && --$_limit < 0);
2519                        push @$defer, $c;
2520                        return 1;
2521                }
2522                if ($r_min != $r_max) {
2523                        return 1 if ($r_min < $c->{r});
2524                        return 1 if ($r_max > $c->{r});
2525                }
2526        }
2527        return 0 if (defined $_limit && --$_limit < 0);
2528        show_commit($c);
2529        return 1;
2530}
2531
2532sub show_commit {
2533        my $c = shift;
2534        if ($_oneline) {
2535                my $x = "\n";
2536                if (my $l = $c->{l}) {
2537                        while ($l->[0] =~ /^\s*$/) { shift @$l }
2538                        $x = $l->[0];
2539                }
2540                $_l_fmt ||= 'A' . length($c->{r});
2541                print 'r',pack($_l_fmt, $c->{r}),' | ';
2542                print "$c->{c} | " if $_show_commit;
2543                print $x;
2544        } else {
2545                show_commit_normal($c);
2546        }
2547}
2548
2549sub show_commit_normal {
2550        my ($c) = @_;
2551        print '-' x72, "\nr$c->{r} | ";
2552        print "$c->{c} | " if $_show_commit;
2553        print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2554                                 localtime($c->{t_utc})), ' | ';
2555        my $nr_line = 0;
2556
2557        if (my $l = $c->{l}) {
2558                while ($l->[$#$l] eq "\n" && $l->[($#$l - 1)] eq "\n") {
2559                        pop @$l;
2560                }
2561                $nr_line = scalar @$l;
2562                if (!$nr_line) {
2563                        print "1 line\n\n\n";
2564                } else {
2565                        if ($nr_line == 1) {
2566                                $nr_line = '1 line';
2567                        } else {
2568                                $nr_line .= ' lines';
2569                        }
2570                        print $nr_line, "\n\n";
2571                        print $_ foreach @$l;
2572                }
2573        } else {
2574                print "1 line\n\n";
2575
2576        }
2577        foreach my $x (qw/raw diff/) {
2578                if ($c->{$x}) {
2579                        print "\n";
2580                        print $_ foreach @{$c->{$x}}
2581                }
2582        }
2583}
2584
2585sub libsvn_load {
2586        return unless $_use_lib;
2587        $_use_lib = eval {
2588                require SVN::Core;
2589                if ($SVN::Core::VERSION lt '1.1.0') {
2590                        die "Need SVN::Core 1.1.0 or better ",
2591                                        "(got $SVN::Core::VERSION) ",
2592                                        "Falling back to command-line svn\n";
2593                }
2594                require SVN::Ra;
2595                require SVN::Delta;
2596                push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2597                my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2598                                        $SVN::Node::dir.$SVN::Node::unknown.
2599                                        $SVN::Node::none.$SVN::Node::file.
2600                                        $SVN::Node::dir.$SVN::Node::unknown;
2601                1;
2602        };
2603}
2604
2605sub libsvn_connect {
2606        my ($url) = @_;
2607        my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2608                          SVN::Client::get_ssl_server_trust_file_provider(),
2609                          SVN::Client::get_username_provider()]);
2610        my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2611        return $s;
2612}
2613
2614sub libsvn_get_file {
2615        my ($gui, $f, $rev) = @_;
2616        my $p = $f;
2617        if (length $SVN_PATH > 0) {
2618                return unless ($p =~ s#^\Q$SVN_PATH\E/##);
2619        }
2620
2621        my ($hash, $pid, $in, $out);
2622        my $pool = SVN::Pool->new;
2623        defined($pid = open3($in, $out, '>&STDERR',
2624                                qw/git-hash-object -w --stdin/)) or croak $!;
2625        # redirect STDOUT for SVN 1.1.x compatibility
2626        open my $stdout, '>&', \*STDOUT or croak $!;
2627        open STDOUT, '>&', $in or croak $!;
2628        my ($r, $props) = $SVN->get_file($f, $rev, \*STDOUT, $pool);
2629        $in->flush == 0 or croak $!;
2630        open STDOUT, '>&', $stdout or croak $!;
2631        close $in or croak $!;
2632        close $stdout or croak $!;
2633        $pool->clear;
2634        chomp($hash = do { local $/; <$out> });
2635        close $out or croak $!;
2636        waitpid $pid, 0;
2637        $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2638
2639        my $mode = exists $props->{'svn:executable'} ? '100755' : '100644';
2640        if (exists $props->{'svn:special'}) {
2641                $mode = '120000';
2642                my $link = `git-cat-file blob $hash`;
2643                $link =~ s/^link // or die "svn:special file with contents: <",
2644                                                $link, "> is not understood\n";
2645                defined($pid = open3($in, $out, '>&STDERR',
2646                                qw/git-hash-object -w --stdin/)) or croak $!;
2647                print $in $link;
2648                $in->flush == 0 or croak $!;
2649                close $in or croak $!;
2650                chomp($hash = do { local $/; <$out> });
2651                close $out or croak $!;
2652                waitpid $pid, 0;
2653                $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2654        }
2655        print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
2656}
2657
2658sub libsvn_log_entry {
2659        my ($rev, $author, $date, $msg, $parents) = @_;
2660        my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2661                                         (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2662                                or die "Unable to parse date: $date\n";
2663        if (defined $_authors && ! defined $users{$author}) {
2664                die "Author: $author not defined in $_authors file\n";
2665        }
2666        $msg = '' if ($rev == 0 && !defined $msg);
2667        return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2668                author => $author, msg => $msg."\n", parents => $parents || [] }
2669}
2670
2671sub process_rm {
2672        my ($gui, $last_commit, $f) = @_;
2673        $f =~ s#^\Q$SVN_PATH\E/?## or return;
2674        # remove entire directories.
2675        if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2676                defined(my $pid = open my $ls, '-|') or croak $!;
2677                if (!$pid) {
2678                        exec(qw/git-ls-tree -r --name-only -z/,
2679                                $last_commit,'--',$f) or croak $!;
2680                }
2681                local $/ = "\0";
2682                while (<$ls>) {
2683                        print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2684                }
2685                close $ls or croak $?;
2686        } else {
2687                print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2688        }
2689}
2690
2691sub libsvn_fetch {
2692        my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2693        open my $gui, '| git-update-index -z --index-info' or croak $!;
2694        my @amr;
2695        foreach my $f (keys %$paths) {
2696                my $m = $paths->{$f}->action();
2697                $f =~ s#^/+##;
2698                if ($m =~ /^[DR]$/) {
2699                        print "\t$m\t$f\n" unless $_q;
2700                        process_rm($gui, $last_commit, $f);
2701                        next if $m eq 'D';
2702                        # 'R' can be file replacements, too, right?
2703                }
2704                my $pool = SVN::Pool->new;
2705                my $t = $SVN->check_path($f, $rev, $pool);
2706                if ($t == $SVN::Node::file) {
2707                        if ($m =~ /^[AMR]$/) {
2708                                push @amr, [ $m, $f ];
2709                        } else {
2710                                die "Unrecognized action: $m, ($f r$rev)\n";
2711                        }
2712                } elsif ($t == $SVN::Node::dir && $m =~ /^[AR]$/) {
2713                        my @traversed = ();
2714                        libsvn_traverse($gui, '', $f, $rev, \@traversed);
2715                        foreach (@traversed) {
2716                                push @amr, [ $m, $_ ]
2717                        }
2718                }
2719                $pool->clear;
2720        }
2721        foreach (@amr) {
2722                print "\t$_->[0]\t$_->[1]\n" unless $_q;
2723                libsvn_get_file($gui, $_->[1], $rev)
2724        }
2725        close $gui or croak $?;
2726        return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2727}
2728
2729sub svn_grab_base_rev {
2730        defined(my $pid = open my $fh, '-|') or croak $!;
2731        if (!$pid) {
2732                open my $null, '>', '/dev/null' or croak $!;
2733                open STDERR, '>&', $null or croak $!;
2734                exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2735                                                                or croak $!;
2736        }
2737        chomp(my $c = do { local $/; <$fh> });
2738        close $fh;
2739        if (defined $c && length $c) {
2740                my ($url, $rev, $uuid) = cmt_metadata($c);
2741                return ($rev, $c) if defined $rev;
2742        }
2743        if ($_no_metadata) {
2744                my $offset = -41; # from tail
2745                my $rl;
2746                open my $fh, '<', $REVDB or
2747                        die "--no-metadata specified and $REVDB not readable\n";
2748                seek $fh, $offset, 2;
2749                $rl = readline $fh;
2750                defined $rl or return (undef, undef);
2751                chomp $rl;
2752                while ($c ne $rl && tell $fh != 0) {
2753                        $offset -= 41;
2754                        seek $fh, $offset, 2;
2755                        $rl = readline $fh;
2756                        defined $rl or return (undef, undef);
2757                        chomp $rl;
2758                }
2759                my $rev = tell $fh;
2760                croak $! if ($rev < -1);
2761                $rev =  ($rev - 41) / 41;
2762                close $fh or croak $!;
2763                return ($rev, $c);
2764        }
2765        return (undef, undef);
2766}
2767
2768sub libsvn_parse_revision {
2769        my $base = shift;
2770        my $head = $SVN->get_latest_revnum();
2771        if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2772                return ($base + 1, $head) if (defined $base);
2773                return (0, $head);
2774        }
2775        return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2776        return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2777        if ($_revision =~ /^BASE:(\d+)$/) {
2778                return ($base + 1, $1) if (defined $base);
2779                return (0, $head);
2780        }
2781        return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2782        die "revision argument: $_revision not understood by git-svn\n",
2783                "Try using the command-line svn client instead\n";
2784}
2785
2786sub libsvn_traverse {
2787        my ($gui, $pfx, $path, $rev, $files) = @_;
2788        my $cwd = "$pfx/$path";
2789        my $pool = SVN::Pool->new;
2790        $cwd =~ s#^/+##g;
2791        my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2792        foreach my $d (keys %$dirent) {
2793                my $t = $dirent->{$d}->kind;
2794                if ($t == $SVN::Node::dir) {
2795                        libsvn_traverse($gui, $cwd, $d, $rev, $files);
2796                } elsif ($t == $SVN::Node::file) {
2797                        my $file = "$cwd/$d";
2798                        if (defined $files) {
2799                                push @$files, $file;
2800                        } else {
2801                                print "\tA\t$file\n" unless $_q;
2802                                libsvn_get_file($gui, $file, $rev);
2803                        }
2804                }
2805        }
2806        $pool->clear;
2807}
2808
2809sub libsvn_traverse_ignore {
2810        my ($fh, $path, $r) = @_;
2811        $path =~ s#^/+##g;
2812        my $pool = SVN::Pool->new;
2813        my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2814        my $p = $path;
2815        $p =~ s#^\Q$SVN_PATH\E/?##;
2816        print $fh length $p ? "\n# $p\n" : "\n# /\n";
2817        if (my $s = $props->{'svn:ignore'}) {
2818                $s =~ s/[\r\n]+/\n/g;
2819                chomp $s;
2820                if (length $p == 0) {
2821                        $s =~ s#\n#\n/$p#g;
2822                        print $fh "/$s\n";
2823                } else {
2824                        $s =~ s#\n#\n/$p/#g;
2825                        print $fh "/$p/$s\n";
2826                }
2827        }
2828        foreach (sort keys %$dirent) {
2829                next if $dirent->{$_}->kind != $SVN::Node::dir;
2830                libsvn_traverse_ignore($fh, "$path/$_", $r);
2831        }
2832        $pool->clear;
2833}
2834
2835sub revisions_eq {
2836        my ($path, $r0, $r1) = @_;
2837        return 1 if $r0 == $r1;
2838        my $nr = 0;
2839        if ($_use_lib) {
2840                # should be OK to use Pool here (r1 - r0) should be small
2841                my $pool = SVN::Pool->new;
2842                libsvn_get_log($SVN, "/$path", $r0, $r1,
2843                                0, 1, 1, sub {$nr++}, $pool);
2844                $pool->clear;
2845        } else {
2846                my ($url, undef) = repo_path_split($SVN_URL);
2847                my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
2848                while (next_log_entry($svn_log)) { $nr++ }
2849                close $svn_log->{fh};
2850        }
2851        return 0 if ($nr > 1);
2852        return 1;
2853}
2854
2855sub libsvn_find_parent_branch {
2856        my ($paths, $rev, $author, $date, $msg) = @_;
2857        my $svn_path = '/'.$SVN_PATH;
2858
2859        # look for a parent from another branch:
2860        my $i = $paths->{$svn_path} or return;
2861        my $branch_from = $i->copyfrom_path or return;
2862        my $r = $i->copyfrom_rev;
2863        print STDERR  "Found possible branch point: ",
2864                                "$branch_from => $svn_path, $r\n";
2865        $branch_from =~ s#^/##;
2866        my $l_map = {};
2867        read_url_paths_all($l_map, '', "$GIT_DIR/svn");
2868        my $url = $SVN->{url};
2869        defined $l_map->{$url} or return;
2870        my $id = $l_map->{$url}->{$branch_from};
2871        if (!defined $id && $_follow_parent) {
2872                print STDERR "Following parent: $branch_from\@$r\n";
2873                # auto create a new branch and follow it
2874                $id = basename($branch_from);
2875                $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
2876                while (-r "$GIT_DIR/svn/$id") {
2877                        # just grow a tail if we're not unique enough :x
2878                        $id .= '-';
2879                }
2880        }
2881        return unless defined $id;
2882
2883        my ($r0, $parent) = find_rev_before($r,$id,1);
2884        if ($_follow_parent && (!defined $r0 || !defined $parent)) {
2885                defined(my $pid = fork) or croak $!;
2886                if (!$pid) {
2887                        $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2888                        init_vars();
2889                        $SVN_URL = "$url/$branch_from";
2890                        $SVN_LOG = $SVN = undef;
2891                        setup_git_svn();
2892                        # we can't assume SVN_URL exists at r+1:
2893                        $_revision = "0:$r";
2894                        fetch_lib();
2895                        exit 0;
2896                }
2897                waitpid $pid, 0;
2898                croak $? if $?;
2899                ($r0, $parent) = find_rev_before($r,$id,1);
2900        }
2901        return unless (defined $r0 && defined $parent);
2902        if (revisions_eq($branch_from, $r0, $r)) {
2903                unlink $GIT_SVN_INDEX;
2904                print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
2905                sys(qw/git-read-tree/, $parent);
2906                return libsvn_fetch($parent, $paths, $rev,
2907                                        $author, $date, $msg);
2908        }
2909        print STDERR "Nope, branch point not imported or unknown\n";
2910        return undef;
2911}
2912
2913sub libsvn_get_log {
2914        my ($ra, @args) = @_;
2915        if ($SVN::Core::VERSION le '1.2.0') {
2916                splice(@args, 3, 1);
2917        }
2918        $ra->get_log(@args);
2919}
2920
2921sub libsvn_new_tree {
2922        if (my $log_entry = libsvn_find_parent_branch(@_)) {
2923                return $log_entry;
2924        }
2925        my ($paths, $rev, $author, $date, $msg) = @_;
2926        open my $gui, '| git-update-index -z --index-info' or croak $!;
2927        libsvn_traverse($gui, '', $SVN_PATH, $rev);
2928        close $gui or croak $?;
2929        return libsvn_log_entry($rev, $author, $date, $msg);
2930}
2931
2932sub find_graft_path_commit {
2933        my ($tree_paths, $p1, $r1) = @_;
2934        foreach my $x (keys %$tree_paths) {
2935                next unless ($p1 =~ /^\Q$x\E/);
2936                my $i = $tree_paths->{$x};
2937                my ($r0, $parent) = find_rev_before($r1,$i,1);
2938                return $parent if (defined $r0 && $r0 == $r1);
2939                print STDERR "r$r1 of $i not imported\n";
2940                next;
2941        }
2942        return undef;
2943}
2944
2945sub find_graft_path_parents {
2946        my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2947        foreach my $x (keys %$tree_paths) {
2948                next unless ($p0 =~ /^\Q$x\E/);
2949                my $i = $tree_paths->{$x};
2950                my ($r, $parent) = find_rev_before($r0, $i, 1);
2951                if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2952                        my ($url_b, undef, $uuid_b) = cmt_metadata($c);
2953                        my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
2954                        next if ($url_a && $url_b && $url_a eq $url_b &&
2955                                                        $uuid_b eq $uuid_a);
2956                        $grafts->{$c}->{$parent} = 1;
2957                }
2958        }
2959}
2960
2961sub libsvn_graft_file_copies {
2962        my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2963        foreach (keys %$paths) {
2964                my $i = $paths->{$_};
2965                my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2966                                        $i->copyfrom_rev);
2967                next unless (defined $p0 && defined $r0);
2968
2969                my $p1 = $_;
2970                $p1 =~ s#^/##;
2971                $p0 =~ s#^/##;
2972                my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2973                next unless $c;
2974                find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2975        }
2976}
2977
2978sub set_index {
2979        my $old = $ENV{GIT_INDEX_FILE};
2980        $ENV{GIT_INDEX_FILE} = shift;
2981        return $old;
2982}
2983
2984sub restore_index {
2985        my ($old) = @_;
2986        if (defined $old) {
2987                $ENV{GIT_INDEX_FILE} = $old;
2988        } else {
2989                delete $ENV{GIT_INDEX_FILE};
2990        }
2991}
2992
2993sub libsvn_commit_cb {
2994        my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2995        if ($_optimize_commits && $rev == ($r_last + 1)) {
2996                my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2997                $log->{tree} = get_tree_from_treeish($c);
2998                my $cmt = git_commit($log, $cmt_last, $c);
2999                my @diff = safe_qx('git-diff-tree', $cmt, $c);
3000                if (@diff) {
3001                        print STDERR "Trees differ: $cmt $c\n",
3002                                        join('',@diff),"\n";
3003                        exit 1;
3004                }
3005        } else {
3006                fetch("$rev=$c");
3007        }
3008}
3009
3010sub libsvn_ls_fullurl {
3011        my $fullurl = shift;
3012        my ($repo, $path) = repo_path_split($fullurl);
3013        $SVN ||= libsvn_connect($repo);
3014        my @ret;
3015        my $pool = SVN::Pool->new;
3016        my ($dirent, undef, undef) = $SVN->get_dir($path,
3017                                                $SVN->get_latest_revnum, $pool);
3018        foreach my $d (keys %$dirent) {
3019                if ($dirent->{$d}->kind == $SVN::Node::dir) {
3020                        push @ret, "$d/"; # add '/' for compat with cli svn
3021                }
3022        }
3023        $pool->clear;
3024        return @ret;
3025}
3026
3027
3028sub libsvn_skip_unknown_revs {
3029        my $err = shift;
3030        my $errno = $err->apr_err();
3031        # Maybe the branch we're tracking didn't
3032        # exist when the repo started, so it's
3033        # not an error if it doesn't, just continue
3034        #
3035        # Wonderfully consistent library, eh?
3036        # 160013 - svn:// and file://
3037        # 175002 - http(s)://
3038        #   More codes may be discovered later...
3039        if ($errno == 175002 || $errno == 160013) {
3040                return;
3041        }
3042        croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3043};
3044
3045# Tie::File seems to be prone to offset errors if revisions get sparse,
3046# it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
3047# one of my favorite modules is out :<  Next up would be one of the DBM
3048# modules, but I'm not sure which is most portable...  So I'll just
3049# go with something that's plain-text, but still capable of
3050# being randomly accessed.  So here's my ultra-simple fixed-width
3051# database.  All records are 40 characters + "\n", so it's easy to seek
3052# to a revision: (41 * rev) is the byte offset.
3053# A record of 40 0s denotes an empty revision.
3054# And yes, it's still pretty fast (faster than Tie::File).
3055sub revdb_set {
3056        my ($file, $rev, $commit) = @_;
3057        length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
3058        open my $fh, '+<', $file or croak $!;
3059        my $offset = $rev * 41;
3060        # assume that append is the common case:
3061        seek $fh, 0, 2 or croak $!;
3062        my $pos = tell $fh;
3063        if ($pos < $offset) {
3064                print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
3065        }
3066        seek $fh, $offset, 0 or croak $!;
3067        print $fh $commit,"\n";
3068        close $fh or croak $!;
3069}
3070
3071sub revdb_get {
3072        my ($file, $rev) = @_;
3073        my $ret;
3074        my $offset = $rev * 41;
3075        open my $fh, '<', $file or croak $!;
3076        seek $fh, $offset, 0;
3077        if (tell $fh == $offset) {
3078                $ret = readline $fh;
3079                if (defined $ret) {
3080                        chomp $ret;
3081                        $ret = undef if ($ret =~ /^0{40}$/);
3082                }
3083        }
3084        close $fh or croak $!;
3085        return $ret;
3086}
3087
3088sub copy_remote_ref {
3089        my $origin = $_cp_remote ? $_cp_remote : 'origin';
3090        my $ref = "refs/remotes/$GIT_SVN";
3091        if (safe_qx('git-ls-remote', $origin, $ref)) {
3092                sys(qw/git fetch/, $origin, "$ref:$ref");
3093        } else {
3094                die "Unable to find remote reference: ",
3095                                "refs/remotes/$GIT_SVN on $origin\n";
3096        }
3097}
3098
3099package SVN::Git::Editor;
3100use vars qw/@ISA/;
3101use strict;
3102use warnings;
3103use Carp qw/croak/;
3104use IO::File;
3105
3106sub new {
3107        my $class = shift;
3108        my $git_svn = shift;
3109        my $self = SVN::Delta::Editor->new(@_);
3110        bless $self, $class;
3111        foreach (qw/svn_path c r ra /) {
3112                die "$_ required!\n" unless (defined $git_svn->{$_});
3113                $self->{$_} = $git_svn->{$_};
3114        }
3115        $self->{pool} = SVN::Pool->new;
3116        $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3117        $self->{rm} = { };
3118        require Digest::MD5;
3119        return $self;
3120}
3121
3122sub split_path {
3123        return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3124}
3125
3126sub repo_path {
3127        (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
3128                                        : $_[0]->{svn_path}
3129}
3130
3131sub url_path {
3132        my ($self, $path) = @_;
3133        $self->{ra}->{url} . '/' . $self->repo_path($path);
3134}
3135
3136sub rmdirs {
3137        my ($self, $q) = @_;
3138        my $rm = $self->{rm};
3139        delete $rm->{''}; # we never delete the url we're tracking
3140        return unless %$rm;
3141
3142        foreach (keys %$rm) {
3143                my @d = split m#/#, $_;
3144                my $c = shift @d;
3145                $rm->{$c} = 1;
3146                while (@d) {
3147                        $c .= '/' . shift @d;
3148                        $rm->{$c} = 1;
3149                }
3150        }
3151        delete $rm->{$self->{svn_path}};
3152        delete $rm->{''}; # we never delete the url we're tracking
3153        return unless %$rm;
3154
3155        defined(my $pid = open my $fh,'-|') or croak $!;
3156        if (!$pid) {
3157                exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
3158        }
3159        local $/ = "\0";
3160        my @svn_path = split m#/#, $self->{svn_path};
3161        while (<$fh>) {
3162                chomp;
3163                my @dn = (@svn_path, (split m#/#, $_));
3164                while (pop @dn) {
3165                        delete $rm->{join '/', @dn};
3166                }
3167                unless (%$rm) {
3168                        close $fh;
3169                        return;
3170                }
3171        }
3172        close $fh;
3173
3174        my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3175        foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3176                $self->close_directory($bat->{$d}, $p);
3177                my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3178                print "\tD+\t/$d/\n" unless $q;
3179                $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3180                delete $bat->{$d};
3181        }
3182}
3183
3184sub open_or_add_dir {
3185        my ($self, $full_path, $baton) = @_;
3186        my $p = SVN::Pool->new;
3187        my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
3188        $p->clear;
3189        if ($t == $SVN::Node::none) {
3190                return $self->add_directory($full_path, $baton,
3191                                                undef, -1, $self->{pool});
3192        } elsif ($t == $SVN::Node::dir) {
3193                return $self->open_directory($full_path, $baton,
3194                                                $self->{r}, $self->{pool});
3195        }
3196        print STDERR "$full_path already exists in repository at ",
3197                "r$self->{r} and it is not a directory (",
3198                ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3199        exit 1;
3200}
3201
3202sub ensure_path {
3203        my ($self, $path) = @_;
3204        my $bat = $self->{bat};
3205        $path = $self->repo_path($path);
3206        return $bat->{''} unless (length $path);
3207        my @p = split m#/+#, $path;
3208        my $c = shift @p;
3209        $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3210        while (@p) {
3211                my $c0 = $c;
3212                $c .= '/' . shift @p;
3213                $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3214        }
3215        return $bat->{$c};
3216}
3217
3218sub A {
3219        my ($self, $m, $q) = @_;
3220        my ($dir, $file) = split_path($m->{file_b});
3221        my $pbat = $self->ensure_path($dir);
3222        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3223                                        undef, -1);
3224        print "\tA\t$m->{file_b}\n" unless $q;
3225        $self->chg_file($fbat, $m);
3226        $self->close_file($fbat,undef,$self->{pool});
3227}
3228
3229sub C {
3230        my ($self, $m, $q) = @_;
3231        my ($dir, $file) = split_path($m->{file_b});
3232        my $pbat = $self->ensure_path($dir);
3233        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3234                                $self->url_path($m->{file_a}), $self->{r});
3235        print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
3236        $self->chg_file($fbat, $m);
3237        $self->close_file($fbat,undef,$self->{pool});
3238}
3239
3240sub delete_entry {
3241        my ($self, $path, $pbat) = @_;
3242        my $rpath = $self->repo_path($path);
3243        my ($dir, $file) = split_path($rpath);
3244        $self->{rm}->{$dir} = 1;
3245        $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3246}
3247
3248sub R {
3249        my ($self, $m, $q) = @_;
3250        my ($dir, $file) = split_path($m->{file_b});
3251        my $pbat = $self->ensure_path($dir);
3252        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3253                                $self->url_path($m->{file_a}), $self->{r});
3254        print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
3255        $self->chg_file($fbat, $m);
3256        $self->close_file($fbat,undef,$self->{pool});
3257
3258        ($dir, $file) = split_path($m->{file_a});
3259        $pbat = $self->ensure_path($dir);
3260        $self->delete_entry($m->{file_a}, $pbat);
3261}
3262
3263sub M {
3264        my ($self, $m, $q) = @_;
3265        my ($dir, $file) = split_path($m->{file_b});
3266        my $pbat = $self->ensure_path($dir);
3267        my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3268                                $pbat,$self->{r},$self->{pool});
3269        print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
3270        $self->chg_file($fbat, $m);
3271        $self->close_file($fbat,undef,$self->{pool});
3272}
3273
3274sub T { shift->M(@_) }
3275
3276sub change_file_prop {
3277        my ($self, $fbat, $pname, $pval) = @_;
3278        $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3279}
3280
3281sub chg_file {
3282        my ($self, $fbat, $m) = @_;
3283        if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3284                $self->change_file_prop($fbat,'svn:executable','*');
3285        } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3286                $self->change_file_prop($fbat,'svn:executable',undef);
3287        }
3288        my $fh = IO::File->new_tmpfile or croak $!;
3289        if ($m->{mode_b} =~ /^120/) {
3290                print $fh 'link ' or croak $!;
3291                $self->change_file_prop($fbat,'svn:special','*');
3292        } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3293                $self->change_file_prop($fbat,'svn:special',undef);
3294        }
3295        defined(my $pid = fork) or croak $!;
3296        if (!$pid) {
3297                open STDOUT, '>&', $fh or croak $!;
3298                exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3299        }
3300        waitpid $pid, 0;
3301        croak $? if $?;
3302        $fh->flush == 0 or croak $!;
3303        seek $fh, 0, 0 or croak $!;
3304
3305        my $md5 = Digest::MD5->new;
3306        $md5->addfile($fh) or croak $!;
3307        seek $fh, 0, 0 or croak $!;
3308
3309        my $exp = $md5->hexdigest;
3310        my $atd = $self->apply_textdelta($fbat, undef, $self->{pool});
3311        my $got = SVN::TxDelta::send_stream($fh, @$atd, $self->{pool});
3312        die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3313
3314        close $fh or croak $!;
3315}
3316
3317sub D {
3318        my ($self, $m, $q) = @_;
3319        my ($dir, $file) = split_path($m->{file_b});
3320        my $pbat = $self->ensure_path($dir);
3321        print "\tD\t$m->{file_b}\n" unless $q;
3322        $self->delete_entry($m->{file_b}, $pbat);
3323}
3324
3325sub close_edit {
3326        my ($self) = @_;
3327        my ($p,$bat) = ($self->{pool}, $self->{bat});
3328        foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3329                $self->close_directory($bat->{$_}, $p);
3330        }
3331        $self->SUPER::close_edit($p);
3332        $p->clear;
3333}
3334
3335sub abort_edit {
3336        my ($self) = @_;
3337        $self->SUPER::abort_edit($self->{pool});
3338        $self->{pool}->clear;
3339}
3340
3341__END__
3342
3343Data structures:
3344
3345$svn_log hashref (as returned by svn_log_raw)
3346{
3347        fh => file handle of the log file,
3348        state => state of the log file parser (sep/msg/rev/msg_start...)
3349}
3350
3351$log_msg hashref as returned by next_log_entry($svn_log)
3352{
3353        msg => 'whitespace-formatted log entry
3354',                                              # trailing newline is preserved
3355        revision => '8',                        # integer
3356        date => '2004-02-24T17:01:44.108345Z',  # commit date
3357        author => 'committer name'
3358};
3359
3360
3361@mods = array of diff-index line hashes, each element represents one line
3362        of diff-index output
3363
3364diff-index line ($m hash)
3365{
3366        mode_a => first column of diff-index output, no leading ':',
3367        mode_b => second column of diff-index output,
3368        sha1_b => sha1sum of the final blob,
3369        chg => change type [MCRADT],
3370        file_a => original file name of a file (iff chg is 'C' or 'R')
3371        file_b => new/current file name of a file (any chg)
3372}
3373;
3374
3375# retval of read_url_paths{,_all}();
3376$l_map = {
3377        # repository root url
3378        'https://svn.musicpd.org' => {
3379                # repository path               # GIT_SVN_ID
3380                'mpd/trunk'             =>      'trunk',
3381                'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3382        },
3383}
3384
3385Notes:
3386        I don't trust the each() function on unless I created %hash myself
3387        because the internal iterator may not have started at base.