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