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