8d49959f37ccd29926fd9cc993abd29ef979c4ca
   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 $_authors %users/;
  13$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
  14$VERSION = '@@GIT_VERSION@@';
  15
  16$ENV{GIT_DIR} ||= '.git';
  17$Git::SVN::default_repo_id = $ENV{GIT_SVN_ID} || 'git-svn';
  18
  19my $LC_ALL = $ENV{LC_ALL};
  20$Git::SVN::Log::TZ = $ENV{TZ};
  21# make sure the svn binary gives consistent output between locales and TZs:
  22$ENV{TZ} = 'UTC';
  23$ENV{LC_ALL} = 'C';
  24$| = 1; # unbuffer STDOUT
  25
  26sub fatal (@) { print STDERR @_; exit 1 }
  27require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
  28require SVN::Ra;
  29require SVN::Delta;
  30if ($SVN::Core::VERSION lt '1.1.0') {
  31        fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
  32}
  33push @Git::SVN::Ra::ISA, 'SVN::Ra';
  34push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
  35push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
  36use Carp qw/croak/;
  37use IO::File qw//;
  38use File::Basename qw/dirname basename/;
  39use File::Path qw/mkpath/;
  40use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
  41use IPC::Open3;
  42use Git;
  43
  44BEGIN {
  45        my $s;
  46        foreach (qw/command command_oneline command_noisy command_output_pipe
  47                    command_input_pipe command_close_pipe/) {
  48                $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
  49                      "*Git::SVN::Migration::$_ = ".
  50                      "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
  51        }
  52        eval $s;
  53}
  54
  55my ($SVN);
  56
  57my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
  58$sha1 = qr/[a-f\d]{40}/;
  59$sha1_short = qr/[a-f\d]{4,40}/;
  60my ($_stdin, $_help, $_edit,
  61        $_repack, $_repack_nr, $_repack_flags,
  62        $_message, $_file, $_no_metadata,
  63        $_template, $_shared,
  64        $_version, $_upgrade,
  65        $_merge, $_strategy, $_dry_run,
  66        $_prefix);
  67
  68my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
  69                    'config-dir=s' => \$Git::SVN::Ra::config_dir,
  70                    'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
  71my %fc_opts = ( 'follow-parent|follow' => \$_follow_parent,
  72                'authors-file|A=s' => \$_authors,
  73                'repack:i' => \$_repack,
  74                'no-metadata' => \$_no_metadata,
  75                'quiet|q' => \$_q,
  76                'repack-flags|repack-args|repack-opts=s' => \$_repack_flags,
  77                %remote_opts );
  78
  79my ($_trunk, $_tags, $_branches);
  80my %multi_opts = ( 'trunk|T=s' => \$_trunk,
  81                'tags|t=s' => \$_tags,
  82                'branches|b=s' => \$_branches );
  83my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
  84my %cmt_opts = ( 'edit|e' => \$_edit,
  85                'rmdir' => \$_rmdir,
  86                'find-copies-harder' => \$_find_copies_harder,
  87                'l=i' => \$_l,
  88                'copy-similarity|C=i'=> \$_cp_similarity
  89);
  90
  91my %cmd = (
  92        fetch => [ \&cmd_fetch, "Download new revisions from SVN",
  93                        { 'revision|r=s' => \$_revision, %fc_opts } ],
  94        init => [ \&cmd_init, "Initialize a repo for tracking" .
  95                          " (requires URL argument)",
  96                          \%init_opts ],
  97        dcommit => [ \&cmd_dcommit,
  98                     'Commit several diffs to merge with upstream',
  99                        { 'merge|m|M' => \$_merge,
 100                          'strategy|s=s' => \$_strategy,
 101                          'dry-run|n' => \$_dry_run,
 102                        %cmt_opts, %fc_opts } ],
 103        'set-tree' => [ \&cmd_set_tree,
 104                        "Set an SVN repository to a git tree-ish",
 105                        { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
 106        'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
 107                        { 'revision|r=i' => \$_revision } ],
 108        rebuild => [ \&cmd_rebuild, "Rebuild git-svn metadata (after git clone)",
 109                        { 'copy-remote|remote=s' => \$_cp_remote,
 110                          'upgrade' => \$_upgrade } ],
 111        'multi-init' => [ \&cmd_multi_init,
 112                        'Initialize multiple trees (like git-svnimport)',
 113                        { %multi_opts, %init_opts, %remote_opts,
 114                         'revision|r=i' => \$_revision,
 115                         'prefix=s' => \$_prefix,
 116                        } ],
 117        'multi-fetch' => [ \&cmd_multi_fetch,
 118                        'Fetch multiple trees (like git-svnimport)',
 119                        \%fc_opts ],
 120        'migrate' => [ sub { },
 121                       # no-op, we automatically run this anyways,
 122                       'Migrate configuration/metadata/layout from
 123                        previous versions of git-svn',
 124                        \%remote_opts ],
 125        'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
 126                        { 'limit=i' => \$Git::SVN::Log::limit,
 127                          'revision|r=s' => \$_revision,
 128                          'verbose|v' => \$Git::SVN::Log::verbose,
 129                          'incremental' => \$Git::SVN::Log::incremental,
 130                          'oneline' => \$Git::SVN::Log::oneline,
 131                          'show-commit' => \$Git::SVN::Log::show_commit,
 132                          'non-recursive' => \$Git::SVN::Log::non_recursive,
 133                          'authors-file|A=s' => \$_authors,
 134                          'color' => \$Git::SVN::Log::color,
 135                          'pager=s' => \$Git::SVN::Log::pager,
 136                        } ],
 137        'commit-diff' => [ \&cmd_commit_diff,
 138                           'Commit a diff between two trees',
 139                        { 'message|m=s' => \$_message,
 140                          'file|F=s' => \$_file,
 141                          'revision|r=s' => \$_revision,
 142                        %cmt_opts } ],
 143);
 144
 145my $cmd;
 146for (my $i = 0; $i < @ARGV; $i++) {
 147        if (defined $cmd{$ARGV[$i]}) {
 148                $cmd = $ARGV[$i];
 149                splice @ARGV, $i, 1;
 150                last;
 151        }
 152};
 153
 154my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
 155
 156read_repo_config(\%opts);
 157my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
 158                                'version|V' => \$_version,
 159                                'minimize-connections' =>
 160                                  \$Git::SVN::Migration::_minimize,
 161                                'id|i=s' => \$Git::SVN::default_repo_id);
 162exit 1 if (!$rv && $cmd ne 'log');
 163
 164usage(0) if $_help;
 165version() if $_version;
 166usage(1) unless defined $cmd;
 167load_authors() if $_authors;
 168unless ($cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/) {
 169        Git::SVN::Migration::migration_check();
 170}
 171$cmd{$cmd}->[0]->(@ARGV);
 172exit 0;
 173
 174####################### primary functions ######################
 175sub usage {
 176        my $exit = shift || 0;
 177        my $fd = $exit ? \*STDERR : \*STDOUT;
 178        print $fd <<"";
 179git-svn - bidirectional operations between a single Subversion tree and git
 180Usage: $0 <command> [options] [arguments]\n
 181
 182        print $fd "Available commands:\n" unless $cmd;
 183
 184        foreach (sort keys %cmd) {
 185                next if $cmd && $cmd ne $_;
 186                print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
 187                foreach (keys %{$cmd{$_}->[2]}) {
 188                        # prints out arguments as they should be passed:
 189                        my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
 190                        print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
 191                                                        "--$_" : "-$_" }
 192                                                split /\|/,$_)," $x\n";
 193                }
 194        }
 195        print $fd <<"";
 196\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
 197arbitrary identifier if you're tracking multiple SVN branches/repositories in
 198one git repository and want to keep them separate.  See git-svn(1) for more
 199information.
 200
 201        exit $exit;
 202}
 203
 204sub version {
 205        print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
 206        exit 0;
 207}
 208
 209sub cmd_rebuild {
 210        my $url = shift;
 211        my $gs = $url ? Git::SVN->init($url)
 212                      : eval { Git::SVN->new };
 213        $gs ||= Git::SVN->_new;
 214        if (!verify_ref($gs->refname.'^0')) {
 215                $gs->copy_remote_ref;
 216        }
 217
 218        my ($rev_list, $ctx) = command_output_pipe("rev-list", $gs->refname);
 219        my $latest;
 220        my $svn_uuid;
 221        while (<$rev_list>) {
 222                chomp;
 223                my $c = $_;
 224                fatal "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
 225                my ($url, $rev, $uuid) = cmt_metadata($c);
 226
 227                # ignore merges (from set-tree)
 228                next if (!defined $rev || !$uuid);
 229
 230                # if we merged or otherwise started elsewhere, this is
 231                # how we break out of it
 232                if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
 233                    ($gs->{url} && $url && ($url ne $gs->{url}))) {
 234                        next;
 235                }
 236
 237                unless (defined $latest) {
 238                        if (!$gs->{url} && !$url) {
 239                                fatal "SVN repository location required\n";
 240                        }
 241                        $gs = Git::SVN->init($url);
 242                        $latest = $rev;
 243                }
 244                $gs->rev_db_set($rev, $c);
 245                print "r$rev = $c\n";
 246        }
 247        command_close_pipe($rev_list, $ctx);
 248}
 249
 250sub do_git_init_db {
 251        unless (-d $ENV{GIT_DIR}) {
 252                my @init_db = ('init');
 253                push @init_db, "--template=$_template" if defined $_template;
 254                push @init_db, "--shared" if defined $_shared;
 255                command_noisy(@init_db);
 256        }
 257}
 258
 259sub cmd_init {
 260        my $url = shift or die "SVN repository location required " .
 261                                "as a command-line argument\n";
 262        if (my $repo_path = shift) {
 263                unless (-d $repo_path) {
 264                        mkpath([$repo_path]);
 265                }
 266                chdir $repo_path or croak $!;
 267                $ENV{GIT_DIR} = $repo_path . "/.git";
 268        }
 269        do_git_init_db();
 270
 271        Git::SVN->init($url);
 272}
 273
 274sub cmd_fetch {
 275        my $gs = Git::SVN->new;
 276        $gs->fetch(@_);
 277        if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
 278                command_noisy(qw(update-ref refs/heads/master),
 279                              $gs->{last_commit});
 280        }
 281}
 282
 283sub cmd_set_tree {
 284        my (@commits) = @_;
 285        if ($_stdin || !@commits) {
 286                print "Reading from stdin...\n";
 287                @commits = ();
 288                while (<STDIN>) {
 289                        if (/\b($sha1_short)\b/o) {
 290                                unshift @commits, $1;
 291                        }
 292                }
 293        }
 294        my @revs;
 295        foreach my $c (@commits) {
 296                my @tmp = command('rev-parse',$c);
 297                if (scalar @tmp == 1) {
 298                        push @revs, $tmp[0];
 299                } elsif (scalar @tmp > 1) {
 300                        push @revs, reverse(command('rev-list',@tmp));
 301                } else {
 302                        fatal "Failed to rev-parse $c\n";
 303                }
 304        }
 305        my $gs = Git::SVN->new;
 306        my ($r_last, $cmt_last) = $gs->last_rev_commit;
 307        $gs->fetch;
 308        if ($r_last != $gs->{last_rev}) {
 309                fatal "There are new revisions that were fetched ",
 310                      "and need to be merged (or acknowledged) ",
 311                      "before committing.\nlast rev: $r_last\n",
 312                      " current: $gs->{last_rev}\n";
 313        }
 314        $gs->set_tree($_) foreach @revs;
 315        print "Done committing ",scalar @revs," revisions to SVN\n";
 316}
 317
 318sub cmd_dcommit {
 319        my $head = shift;
 320        my $gs = Git::SVN->new;
 321        $head ||= 'HEAD';
 322        my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
 323        my $last_rev;
 324        foreach my $d (reverse @refs) {
 325                if (!verify_ref("$d~1")) {
 326                        fatal "Commit $d\n",
 327                              "has no parent commit, and therefore ",
 328                              "nothing to diff against.\n",
 329                              "You should be working from a repository ",
 330                              "originally created by git-svn\n";
 331                }
 332                unless (defined $last_rev) {
 333                        (undef, $last_rev, undef) = cmt_metadata("$d~1");
 334                        unless (defined $last_rev) {
 335                                fatal "Unable to extract revision information ",
 336                                      "from commit $d~1\n";
 337                        }
 338                }
 339                if ($_dry_run) {
 340                        print "diff-tree $d~1 $d\n";
 341                } else {
 342                        my $log = get_commit_entry($d)->{log};
 343                        my $ra = $gs->ra;
 344                        my $pool = SVN::Pool->new;
 345                        my %ed_opts = ( r => $last_rev,
 346                                        ra => $ra->dup,
 347                                        svn_path => $ra->{svn_path} );
 348                        my $ed = SVN::Git::Editor->new(\%ed_opts,
 349                                         $ra->get_commit_editor($log,
 350                                         sub { print "Committed r$_[0]\n";
 351                                               $last_rev = $_[0]; }),
 352                                         $pool);
 353                        my $mods = $ed->apply_diff("$d~1", $d);
 354                        if (@$mods == 0) {
 355                                print "No changes\n$d~1 == $d\n";
 356                        }
 357                }
 358        }
 359        return if $_dry_run;
 360        $gs->fetch;
 361        # we always want to rebase against the current HEAD, not any
 362        # head that was passed to us
 363        my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
 364        my @finish;
 365        if (@diff) {
 366                @finish = qw/rebase/;
 367                push @finish, qw/--merge/ if $_merge;
 368                push @finish, "--strategy=$_strategy" if $_strategy;
 369                print STDERR "W: HEAD and ", $gs->refname, " differ, ",
 370                             "using @finish:\n", "@diff";
 371        } else {
 372                print "No changes between current HEAD and ",
 373                      $gs->refname, "\nResetting to the latest ",
 374                      $gs->refname, "\n";
 375                @finish = qw/reset --mixed/;
 376        }
 377        command_noisy(@finish, $gs->refname);
 378}
 379
 380sub cmd_show_ignore {
 381        my $gs = Git::SVN->new;
 382        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
 383        $gs->traverse_ignore(\*STDOUT, '', $r);
 384}
 385
 386sub cmd_multi_init {
 387        my $url = shift;
 388        unless (defined $_trunk || defined $_branches || defined $_tags) {
 389                usage(1);
 390        }
 391        do_git_init_db();
 392        $_prefix = '' unless defined $_prefix;
 393        $url =~ s#/+$## if defined $url;
 394        if (defined $_trunk) {
 395                my $trunk_ref = $_prefix . 'trunk';
 396                # try both old-style and new-style lookups:
 397                my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
 398                unless ($gs_trunk) {
 399                        my ($trunk_url, $trunk_path) =
 400                                              complete_svn_url($url, $_trunk);
 401                        $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
 402                                                   undef, $trunk_ref);
 403                }
 404        }
 405        return unless defined $_branches || defined $_tags;
 406        my $ra = $url ? Git::SVN::Ra->new($url) : undef;
 407        complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
 408        complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
 409}
 410
 411sub cmd_multi_fetch {
 412        my @gs;
 413        foreach (command(qw/config -l/)) {
 414                next unless m!^svn-remote\.(.+)\.fetch=
 415                              \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
 416                my ($repo_id, $path, $ref_id) = ($1, $2, $3);
 417                push @gs, Git::SVN->new($ref_id, $repo_id, $path);
 418        }
 419        foreach (@gs) {
 420                $_->fetch;
 421        }
 422}
 423
 424# this command is special because it requires no metadata
 425sub cmd_commit_diff {
 426        my ($ta, $tb, $url) = @_;
 427        my $usage = "Usage: $0 commit-diff -r<revision> ".
 428                    "<tree-ish> <tree-ish> [<URL>]\n";
 429        fatal($usage) if (!defined $ta || !defined $tb);
 430        if (!defined $url) {
 431                my $gs = eval { Git::SVN->new };
 432                if (!$gs) {
 433                        fatal("Needed URL or usable git-svn --id in ",
 434                              "the command-line\n", $usage);
 435                }
 436                $url = $gs->{url};
 437        }
 438        unless (defined $_revision) {
 439                fatal("-r|--revision is a required argument\n", $usage);
 440        }
 441        if (defined $_message && defined $_file) {
 442                fatal("Both --message/-m and --file/-F specified ",
 443                      "for the commit message.\n",
 444                      "I have no idea what you mean\n");
 445        }
 446        if (defined $_file) {
 447                $_message = file_to_s($_file);
 448        } else {
 449                $_message ||= get_commit_entry($tb)->{log};
 450        }
 451        my $ra ||= Git::SVN::Ra->new($url);
 452        my $r = $_revision;
 453        if ($r eq 'HEAD') {
 454                $r = $ra->get_latest_revnum;
 455        } elsif ($r !~ /^\d+$/) {
 456                die "revision argument: $r not understood by git-svn\n";
 457        }
 458        my $pool = SVN::Pool->new;
 459        my %ed_opts = ( r => $r,
 460                        ra => $ra->dup,
 461                        svn_path => $ra->{svn_path} );
 462        my $ed = SVN::Git::Editor->new(\%ed_opts,
 463                                       $ra->get_commit_editor($_message,
 464                                         sub { print "Committed r$_[0]\n" }),
 465                                       $pool);
 466        my $mods = $ed->apply_diff($ta, $tb);
 467        if (@$mods == 0) {
 468                print "No changes\n$ta == $tb\n";
 469        }
 470        $pool->clear;
 471}
 472
 473########################### utility functions #########################
 474
 475sub complete_svn_url {
 476        my ($url, $path) = @_;
 477        $path =~ s#/+$##;
 478        if ($path !~ m#^[a-z\+]+://#) {
 479                if (!defined $url || $url !~ m#^[a-z\+]+://#) {
 480                        fatal("E: '$path' is not a complete URL ",
 481                              "and a separate URL is not specified\n");
 482                }
 483                return ($url, $path);
 484        }
 485        return ($path, '');
 486}
 487
 488sub complete_url_ls_init {
 489        my ($ra, $repo_path, $switch, $pfx) = @_;
 490        unless ($repo_path) {
 491                print STDERR "W: $switch not specified\n";
 492                return;
 493        }
 494        $repo_path =~ s#/+$##;
 495        if ($repo_path =~ m#^[a-z\+]+://#) {
 496                $ra = Git::SVN::Ra->new($repo_path);
 497                $repo_path = '';
 498        } else {
 499                $repo_path =~ s#^/+##;
 500                unless ($ra) {
 501                        fatal("E: '$repo_path' is not a complete URL ",
 502                              "and a separate URL is not specified\n");
 503                }
 504        }
 505        my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
 506        my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
 507        my $url = $ra->{url};
 508        foreach my $d (sort keys %$dirent) {
 509                next if ($dirent->{$d}->kind != $SVN::Node::dir);
 510                my $path =  "$repo_path/$d";
 511                my $ref = "$pfx$d";
 512                my $gs = eval { Git::SVN->new($ref) };
 513                # don't try to init already existing refs
 514                unless ($gs) {
 515                        print "init $url/$path => $ref\n";
 516                        Git::SVN->init($url, $path, undef, $ref);
 517                }
 518        }
 519}
 520
 521sub verify_ref {
 522        my ($ref) = @_;
 523        eval { command_oneline([ 'rev-parse', '--verify', $ref ],
 524                               { STDERR => 0 }); };
 525}
 526
 527sub get_tree_from_treeish {
 528        my ($treeish) = @_;
 529        # $treeish can be a symbolic ref, too:
 530        my $type = command_oneline(qw/cat-file -t/, $treeish);
 531        my $expected;
 532        while ($type eq 'tag') {
 533                ($treeish, $type) = command(qw/cat-file tag/, $treeish);
 534        }
 535        if ($type eq 'commit') {
 536                $expected = (grep /^tree /, command(qw/cat-file commit/,
 537                                                    $treeish))[0];
 538                ($expected) = ($expected =~ /^tree ($sha1)$/o);
 539                die "Unable to get tree from $treeish\n" unless $expected;
 540        } elsif ($type eq 'tree') {
 541                $expected = $treeish;
 542        } else {
 543                die "$treeish is a $type, expected tree, tag or commit\n";
 544        }
 545        return $expected;
 546}
 547
 548sub get_commit_entry {
 549        my ($treeish) = shift;
 550        my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
 551        my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
 552        my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
 553        open my $log_fh, '>', $commit_editmsg or croak $!;
 554
 555        my $type = command_oneline(qw/cat-file -t/, $treeish);
 556        if ($type eq 'commit' || $type eq 'tag') {
 557                my ($msg_fh, $ctx) = command_output_pipe('cat-file',
 558                                                         $type, $treeish);
 559                my $in_msg = 0;
 560                while (<$msg_fh>) {
 561                        if (!$in_msg) {
 562                                $in_msg = 1 if (/^\s*$/);
 563                        } elsif (/^git-svn-id: /) {
 564                                # skip this for now, we regenerate the
 565                                # correct one on re-fetch anyways
 566                                # TODO: set *:merge properties or like...
 567                        } else {
 568                                print $log_fh $_ or croak $!;
 569                        }
 570                }
 571                command_close_pipe($msg_fh, $ctx);
 572        }
 573        close $log_fh or croak $!;
 574
 575        if ($_edit || ($type eq 'tree')) {
 576                my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
 577                # TODO: strip out spaces, comments, like git-commit.sh
 578                system($editor, $commit_editmsg);
 579        }
 580        rename $commit_editmsg, $commit_msg or croak $!;
 581        open $log_fh, '<', $commit_msg or croak $!;
 582        { local $/; chomp($log_entry{log} = <$log_fh>); }
 583        close $log_fh or croak $!;
 584        unlink $commit_msg;
 585        \%log_entry;
 586}
 587
 588sub s_to_file {
 589        my ($str, $file, $mode) = @_;
 590        open my $fd,'>',$file or croak $!;
 591        print $fd $str,"\n" or croak $!;
 592        close $fd or croak $!;
 593        chmod ($mode &~ umask, $file) if (defined $mode);
 594}
 595
 596sub file_to_s {
 597        my $file = shift;
 598        open my $fd,'<',$file or croak "$!: file: $file\n";
 599        local $/;
 600        my $ret = <$fd>;
 601        close $fd or croak $!;
 602        $ret =~ s/\s*$//s;
 603        return $ret;
 604}
 605
 606# '<svn username> = real-name <email address>' mapping based on git-svnimport:
 607sub load_authors {
 608        open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
 609        my $log = $cmd eq 'log';
 610        while (<$authors>) {
 611                chomp;
 612                next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
 613                my ($user, $name, $email) = ($1, $2, $3);
 614                if ($log) {
 615                        $Git::SVN::Log::rusers{"$name <$email>"} = $user;
 616                } else {
 617                        $users{$user} = [$name, $email];
 618                }
 619        }
 620        close $authors or croak $!;
 621}
 622
 623# convert GetOpt::Long specs for use by git-config
 624sub read_repo_config {
 625        return unless -d $ENV{GIT_DIR};
 626        my $opts = shift;
 627        foreach my $o (keys %$opts) {
 628                my $v = $opts->{$o};
 629                my ($key) = ($o =~ /^([a-z\-]+)/);
 630                $key =~ s/-//g;
 631                my $arg = 'git-config';
 632                $arg .= ' --int' if ($o =~ /[:=]i$/);
 633                $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
 634                if (ref $v eq 'ARRAY') {
 635                        chomp(my @tmp = `$arg --get-all svn.$key`);
 636                        @$v = @tmp if @tmp;
 637                } else {
 638                        chomp(my $tmp = `$arg --get svn.$key`);
 639                        if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
 640                                $$v = $tmp;
 641                        }
 642                }
 643        }
 644}
 645
 646sub extract_metadata {
 647        my $id = shift or return (undef, undef, undef);
 648        my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
 649                                                        \s([a-f\d\-]+)$/x);
 650        if (!defined $rev || !$uuid || !$url) {
 651                # some of the original repositories I made had
 652                # identifiers like this:
 653                ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
 654        }
 655        return ($url, $rev, $uuid);
 656}
 657
 658sub cmt_metadata {
 659        return extract_metadata((grep(/^git-svn-id: /,
 660                command(qw/cat-file commit/, shift)))[-1]);
 661}
 662
 663sub get_commit_time {
 664        my $cmt = shift;
 665        my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
 666        while (<$fh>) {
 667                /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
 668                my ($s, $tz) = ($1, $2);
 669                if ($tz =~ s/^\+//) {
 670                        $s += tz_to_s_offset($tz);
 671                } elsif ($tz =~ s/^\-//) {
 672                        $s -= tz_to_s_offset($tz);
 673                }
 674                close $fh;
 675                return $s;
 676        }
 677        die "Can't get commit time for commit: $cmt\n";
 678}
 679
 680sub tz_to_s_offset {
 681        my ($tz) = @_;
 682        $tz =~ s/(\d\d)$//;
 683        return ($1 * 60) + ($tz * 3600);
 684}
 685
 686package Git::SVN;
 687use strict;
 688use warnings;
 689use vars qw/$default_repo_id/;
 690use Carp qw/croak/;
 691use File::Path qw/mkpath/;
 692use IPC::Open3;
 693
 694# properties that we do not log:
 695my %SKIP_PROP;
 696BEGIN {
 697        %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
 698                                        svn:special svn:executable
 699                                        svn:entry:committed-rev
 700                                        svn:entry:last-author
 701                                        svn:entry:uuid
 702                                        svn:entry:committed-date/;
 703}
 704
 705sub read_all_remotes {
 706        my $r = {};
 707        foreach (grep { s/^svn-remote\.// } command(qw/repo-config -l/)) {
 708                if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
 709                        $r->{$1}->{fetch}->{$2} = $3;
 710                } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
 711                        $r->{$1}->{url} = $2;
 712                }
 713        }
 714        $r;
 715}
 716
 717# we allow more chars than remotes2config.sh...
 718sub sanitize_remote_name {
 719        my ($name) = @_;
 720        $name =~ tr{A-Za-z0-9:,/+-}{.}c;
 721        $name;
 722}
 723
 724sub init {
 725        my ($class, $url, $path, $repo_id, $ref_id) = @_;
 726        my $self = _new($class, $repo_id, $ref_id, $path);
 727        mkpath([$self->{dir}]);
 728        if (defined $url) {
 729                $url =~ s!/+$!!; # strip trailing slash
 730                my $orig_url = eval {
 731                        command_oneline('config', '--get',
 732                                        "svn-remote.$repo_id.url")
 733                };
 734                if ($orig_url) {
 735                        if ($orig_url ne $url) {
 736                                die "svn-remote.$repo_id.url already set: ",
 737                                    "$orig_url\nwanted to set to: $url\n";
 738                        }
 739                } else {
 740                        command_noisy('config',
 741                                      "svn-remote.$repo_id.url", $url);
 742                }
 743                command_noisy('config', '--add',
 744                              "svn-remote.$repo_id.fetch",
 745                              "$path:".$self->refname);
 746        }
 747        $self->{url} = $url;
 748        unless (-f $self->{db_path}) {
 749                open my $fh, '>>', $self->{db_path} or croak $!;
 750                close $fh or croak $!;
 751        }
 752        $self;
 753}
 754
 755sub find_ref {
 756        my ($ref_id) = @_;
 757        foreach (command(qw/config -l/)) {
 758                next unless m!^svn-remote\.(.+)\.fetch=
 759                              \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
 760                my ($repo_id, $path, $ref) = ($1, $2, $3);
 761                if ($ref eq $ref_id) {
 762                        $path = '' if ($path =~ m#^\./?#);
 763                        return ($repo_id, $path);
 764                }
 765        }
 766        (undef, undef, undef);
 767}
 768
 769sub new {
 770        my ($class, $ref_id, $repo_id, $path) = @_;
 771        if (defined $ref_id && !defined $repo_id && !defined $path) {
 772                ($repo_id, $path) = find_ref($ref_id);
 773                if (!defined $repo_id) {
 774                        die "Could not find a \"svn-remote.*.fetch\" key ",
 775                            "in the repository configuration matching: ",
 776                            "refs/remotes/$ref_id\n";
 777                }
 778        }
 779        my $self = _new($class, $repo_id, $ref_id, $path);
 780        $self->{url} = command_oneline('config', '--get',
 781                                       "svn-remote.$repo_id.url") or
 782                  die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
 783        $self;
 784}
 785
 786sub refname { "refs/remotes/$_[0]->{ref_id}" }
 787
 788sub ra {
 789        my ($self) = shift;
 790        $self->{ra} ||= Git::SVN::Ra->new($self->{url});
 791}
 792
 793sub rel_path {
 794        my ($self) = @_;
 795        my $repos_root = $self->ra->{repos_root};
 796        return $self->{path} if ($self->{url} eq $repos_root);
 797        my $url = $self->{url} .
 798                  (length $self->{path} ? "/$self->{path}" : $self->{path});
 799        $url =~ s!^\Q$repos_root\E/*!!g;
 800        $url;
 801}
 802
 803sub copy_remote_ref {
 804        my ($self) = @_;
 805        my $origin = $::_cp_remote ? $::_cp_remote : 'origin';
 806        my $ref = $self->refname;
 807        if (command('ls-remote', $origin, $ref)) {
 808                command_noisy('fetch', $origin, "$ref:$ref");
 809        } elsif ($::_cp_remote && !$::_upgrade) {
 810                die "Unable to find remote reference: $ref on $origin\n";
 811        }
 812}
 813
 814sub traverse_ignore {
 815        my ($self, $fh, $path, $r) = @_;
 816        $path =~ s#^/+##g;
 817        my ($dirent, undef, $props) = $self->ra->get_dir($path, $r);
 818        my $p = $path;
 819        $p =~ s#^\Q$self->{ra}->{svn_path}\E/##;
 820        print $fh length $p ? "\n# $p\n" : "\n# /\n";
 821        if (my $s = $props->{'svn:ignore'}) {
 822                $s =~ s/[\r\n]+/\n/g;
 823                chomp $s;
 824                if (length $p == 0) {
 825                        $s =~ s#\n#\n/$p#g;
 826                        print $fh "/$s\n";
 827                } else {
 828                        $s =~ s#\n#\n/$p/#g;
 829                        print $fh "/$p/$s\n";
 830                }
 831        }
 832        foreach (sort keys %$dirent) {
 833                next if $dirent->{$_}->kind != $SVN::Node::dir;
 834                $self->traverse_ignore($fh, "$path/$_", $r);
 835        }
 836}
 837
 838# returns the newest SVN revision number and newest commit SHA1
 839sub last_rev_commit {
 840        my ($self) = @_;
 841        if (defined $self->{last_rev} && defined $self->{last_commit}) {
 842                return ($self->{last_rev}, $self->{last_commit});
 843        }
 844        my $c = ::verify_ref($self->refname.'^0');
 845        if ($c) {
 846                my $rev = (::cmt_metadata($c))[1];
 847                if (defined $rev) {
 848                        ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
 849                        return ($rev, $c);
 850                }
 851        }
 852        my $offset = -41; # from tail
 853        my $rl;
 854        open my $fh, '<', $self->{db_path} or
 855                                 croak "$self->{db_path} not readable: $!\n";
 856        seek $fh, $offset, 2;
 857        $rl = readline $fh;
 858        defined $rl or return (undef, undef);
 859        chomp $rl;
 860        while ($c ne $rl && tell $fh != 0) {
 861                $offset -= 41;
 862                seek $fh, $offset, 2;
 863                $rl = readline $fh;
 864                defined $rl or return (undef, undef);
 865                chomp $rl;
 866        }
 867        my $rev = tell $fh;
 868        croak $! if ($rev < 0);
 869        $rev =  ($rev - 41) / 41;
 870        close $fh or croak $!;
 871        ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
 872        return ($rev, $c);
 873}
 874
 875sub parse_revision {
 876        my ($self, $base) = @_;
 877        my $head = $self->ra->get_latest_revnum;
 878        if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
 879                return ($base + 1, $head) if (defined $base);
 880                return (0, $head);
 881        }
 882        return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
 883        return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
 884        if ($::_revision =~ /^BASE:(\d+)$/) {
 885                return ($base + 1, $1) if (defined $base);
 886                return (0, $head);
 887        }
 888        return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
 889        die "revision argument: $::_revision not understood by git-svn\n",
 890                "Try using the command-line svn client instead\n";
 891}
 892
 893sub tmp_index_do {
 894        my ($self, $sub) = @_;
 895        my $old_index = $ENV{GIT_INDEX_FILE};
 896        $ENV{GIT_INDEX_FILE} = $self->{index};
 897        my @ret = &$sub;
 898        if ($old_index) {
 899                $ENV{GIT_INDEX_FILE} = $old_index;
 900        } else {
 901                delete $ENV{GIT_INDEX_FILE};
 902        }
 903        wantarray ? @ret : $ret[0];
 904}
 905
 906sub assert_index_clean {
 907        my ($self, $treeish) = @_;
 908
 909        $self->tmp_index_do(sub {
 910                command_noisy('read-tree', $treeish) unless -e $self->{index};
 911                my $x = command_oneline('write-tree');
 912                my ($y) = (command(qw/cat-file commit/, $treeish) =~
 913                           /^tree ($::sha1)/mo);
 914                if ($y ne $x) {
 915                        unlink $self->{index} or croak $!;
 916                        command_noisy('read-tree', $treeish);
 917                }
 918                $x = command_oneline('write-tree');
 919                if ($y ne $x) {
 920                        ::fatal "trees ($treeish) $y != $x\n",
 921                                "Something is seriously wrong...\n";
 922                }
 923        });
 924}
 925
 926sub get_commit_parents {
 927        my ($self, $log_entry, @parents) = @_;
 928        my (%seen, @ret, @tmp);
 929        # commit parents can be conditionally bound to a particular
 930        # svn revision via: "svn_revno=commit_sha1", filter them out here:
 931        foreach my $p (@parents) {
 932                next unless defined $p;
 933                if ($p =~ /^(\d+)=($::sha1_short)$/o) {
 934                        push @tmp, $2 if $1 == $log_entry->{revision};
 935                } else {
 936                        push @tmp, $p if $p =~ /^$::sha1_short$/o;
 937                }
 938        }
 939        if (my $cur = ::verify_ref($self->refname.'^0')) {
 940                push @tmp, $cur;
 941        }
 942        push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
 943        while (my $p = shift @tmp) {
 944                next if $seen{$p};
 945                $seen{$p} = 1;
 946                push @ret, $p;
 947                # MAXPARENT is defined to 16 in commit-tree.c:
 948                last if @ret >= 16;
 949        }
 950        if (@tmp) {
 951                die "r$log_entry->{revision}: No room for parents:\n\t",
 952                    join("\n\t", @tmp), "\n";
 953        }
 954        @ret;
 955}
 956
 957sub full_url {
 958        my ($self) = @_;
 959        $self->ra->{url} . (length $self->{path} ? '/' . $self->{path} : '');
 960}
 961
 962sub do_git_commit {
 963        my ($self, $log_entry, @parents) = @_;
 964        if (my $c = $self->rev_db_get($log_entry->{revision})) {
 965                croak "$log_entry->{revision} = $c already exists! ",
 966                      "Why are we refetching it?\n";
 967        }
 968        my $author = $log_entry->{author};
 969        my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
 970                           : ($author, "$author\@".$self->ra->uuid));
 971        $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
 972        $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
 973        $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
 974
 975        my $tree = $log_entry->{tree};
 976        if (!defined $tree) {
 977                $tree = $self->tmp_index_do(sub {
 978                                            command_oneline('write-tree') });
 979        }
 980        die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
 981
 982        my @exec = ('git-commit-tree', $tree);
 983        foreach ($self->get_commit_parents($log_entry, @parents)) {
 984                push @exec, '-p', $_;
 985        }
 986        defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
 987                                                                   or croak $!;
 988        print $msg_fh $log_entry->{log} or croak $!;
 989        print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
 990                      $log_entry->{revision}, ' ',
 991                      $self->ra->uuid, "\n" or croak $!;
 992        $msg_fh->flush == 0 or croak $!;
 993        close $msg_fh or croak $!;
 994        chomp(my $commit = do { local $/; <$out_fh> });
 995        close $out_fh or croak $!;
 996        waitpid $pid, 0;
 997        croak $? if $?;
 998        if ($commit !~ /^$::sha1$/o) {
 999                die "Failed to commit, invalid sha1: $commit\n";
1000        }
1001
1002        command_noisy('update-ref',$self->refname, $commit);
1003        $self->rev_db_set($log_entry->{revision}, $commit);
1004
1005        $self->{last_rev} = $log_entry->{revision};
1006        $self->{last_commit} = $commit;
1007        print "r$log_entry->{revision} = $commit\n";
1008        return $commit;
1009}
1010
1011sub revisions_eq {
1012        my ($self, $r0, $r1) = @_;
1013        return 1 if $r0 == $r1;
1014        my $nr = 0;
1015        $self->ra->get_log([$self->{path}], $r0, $r1,
1016                           0, 0, 1, sub { $nr++ });
1017        return 0 if ($nr > 1);
1018        return 1;
1019}
1020
1021sub find_parent_branch {
1022        my ($self, $paths, $rev) = @_;
1023
1024        # look for a parent from another branch:
1025        my $i = $paths->{'/'.$self->rel_path} or return;
1026        my $branch_from = $i->copyfrom_path or return;
1027        my $r = $i->copyfrom_rev;
1028        my $repos_root = $self->ra->{repos_root};
1029        my $url = $self->ra->{url};
1030        my $new_url = $repos_root . $branch_from;
1031        print STDERR  "Found possible branch point: ",
1032                      "$new_url => ", $self->full_url, ", $r\n";
1033        $branch_from =~ s#^/##;
1034        my $remotes = read_all_remotes();
1035        my $gs;
1036        foreach my $repo_id (keys %$remotes) {
1037                my $u = $remotes->{$repo_id}->{url} or next;
1038                next if $url ne $u;
1039                my $fetch = $remotes->{$repo_id}->{fetch};
1040                foreach my $f (keys %$fetch) {
1041                        next if $f ne $branch_from;
1042                        $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1043                        last;
1044                }
1045                last if $gs;
1046        }
1047        unless ($gs) {
1048                my $ref_id = $branch_from;
1049                $ref_id .= "\@$r" if find_ref($ref_id);
1050                # just grow a tail if we're not unique enough :x
1051                $ref_id .= '-' while find_ref($ref_id);
1052                $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id);
1053        }
1054        my ($r0, $parent) = $gs->find_rev_before($r, 1);
1055        if ($::_follow_parent && (!defined $r0 || !defined $parent)) {
1056                foreach (0 .. $r) {
1057                        my $log_entry = eval { $gs->do_fetch(undef, $_) };
1058                        $gs->do_git_commit($log_entry) if $log_entry;
1059                }
1060                ($r0, $parent) = $gs->last_rev_commit;
1061        }
1062        if (defined $r0 && defined $parent && $gs->revisions_eq($r0, $r)) {
1063                print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1064                command_noisy('read-tree', $parent);
1065                my $ed;
1066                if ($self->ra->can_do_switch) {
1067                        # do_switch works with svn/trunk >= r22312, but that
1068                        # is not included with SVN 1.4.2 (the latest version
1069                        # at the moment), so we can't rely on it
1070                        $self->{last_commit} = $parent;
1071                        $ed = SVN::Git::Fetcher->new($self);
1072                        $gs->ra->gs_do_switch($r0, $rev, $gs->{path}, 1,
1073                                              $self->full_url, $ed)
1074                          or die "SVN connection failed somewhere...\n";
1075                } else {
1076                        $ed = SVN::Git::Fetcher->new($self);
1077                        $self->ra->gs_do_update($rev, $rev, $self->{path},
1078                                                1, $ed)
1079                          or die "SVN connection failed somewhere...\n";
1080                }
1081                return $self->make_log_entry($rev, [$parent], $ed);
1082        }
1083        print STDERR "Branch parent not found...\n";
1084        return undef;
1085}
1086
1087sub do_fetch {
1088        my ($self, $paths, $rev) = @_;
1089        my $ed;
1090        my ($last_rev, @parents);
1091        if ($self->{last_commit}) {
1092                $ed = SVN::Git::Fetcher->new($self);
1093                $last_rev = $self->{last_rev};
1094                $ed->{c} = $self->{last_commit};
1095                @parents = ($self->{last_commit});
1096        } else {
1097                $last_rev = $rev;
1098                if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1099                        return $log_entry;
1100                }
1101                $ed = SVN::Git::Fetcher->new($self);
1102        }
1103        unless ($self->ra->gs_do_update($last_rev, $rev,
1104                                        $self->{path}, 1, $ed)) {
1105                die "SVN connection failed somewhere...\n";
1106        }
1107        $self->make_log_entry($rev, \@parents, $ed);
1108}
1109
1110sub write_untracked {
1111        my ($self, $rev, $fh, $untracked) = @_;
1112        my $h;
1113        print $fh "r$rev\n" or croak $!;
1114        $h = $untracked->{empty};
1115        foreach (sort keys %$h) {
1116                my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1117                print $fh "  $act: ", uri_encode($_), "\n" or croak $!;
1118                warn "W: $act: $_\n";
1119        }
1120        foreach my $t (qw/dir_prop file_prop/) {
1121                $h = $untracked->{$t} or next;
1122                foreach my $path (sort keys %$h) {
1123                        my $ppath = $path eq '' ? '.' : $path;
1124                        foreach my $prop (sort keys %{$h->{$path}}) {
1125                                next if $SKIP_PROP{$prop};
1126                                my $v = $h->{$path}->{$prop};
1127                                if (defined $v) {
1128                                        print $fh "  +$t: ",
1129                                                  uri_encode($ppath), ' ',
1130                                                  uri_encode($prop), ' ',
1131                                                  uri_encode($v), "\n"
1132                                                  or croak $!;
1133                                } else {
1134                                        print $fh "  -$t: ",
1135                                                  uri_encode($ppath), ' ',
1136                                                  uri_encode($prop), "\n"
1137                                                  or croak $!;
1138                                }
1139                        }
1140                }
1141        }
1142        foreach my $t (qw/absent_file absent_directory/) {
1143                $h = $untracked->{$t} or next;
1144                foreach my $parent (sort keys %$h) {
1145                        foreach my $path (sort @{$h->{$parent}}) {
1146                                print $fh "  $t: ",
1147                                      uri_encode("$parent/$path"), "\n"
1148                                      or croak $!;
1149                                warn "W: $t: $parent/$path ",
1150                                     "Insufficient permissions?\n";
1151                        }
1152                }
1153        }
1154}
1155
1156sub parse_svn_date {
1157        my $date = shift || return '+0000 1970-01-01 00:00:00';
1158        my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1159                                            (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1160                                         croak "Unable to parse date: $date\n";
1161        "+0000 $Y-$m-$d $H:$M:$S";
1162}
1163
1164sub check_author {
1165        my ($author) = @_;
1166        if (!defined $author || length $author == 0) {
1167                $author = '(no author)';
1168        }
1169        if (defined $::_authors && ! defined $::users{$author}) {
1170                die "Author: $author not defined in $::_authors file\n";
1171        }
1172        $author;
1173}
1174
1175sub make_log_entry {
1176        my ($self, $rev, $parents, $untracked) = @_;
1177        my $rp = $self->ra->rev_proplist($rev);
1178        my %log_entry = ( parents => $parents || [], revision => $rev,
1179                          revprops => $rp, log => '');
1180        open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1181        $self->write_untracked($rev, $un, $untracked);
1182        foreach (sort keys %$rp) {
1183                my $v = $rp->{$_};
1184                if (/^svn:(author|date|log)$/) {
1185                        $log_entry{$1} = $v;
1186                } else {
1187                        print $un "  rev_prop: ", uri_encode($_), ' ',
1188                                  uri_encode($v), "\n";
1189                }
1190        }
1191        close $un or croak $!;
1192        $log_entry{date} = parse_svn_date($log_entry{date});
1193        $log_entry{author} = check_author($log_entry{author});
1194        $log_entry{log} .= "\n";
1195        \%log_entry;
1196}
1197
1198sub fetch {
1199        my ($self, @parents) = @_;
1200        my ($last_rev, $last_commit) = $self->last_rev_commit;
1201        my ($base, $head) = $self->parse_revision($last_rev);
1202        return if ($base > $head);
1203        if (defined $last_commit) {
1204                $self->assert_index_clean($last_commit);
1205        }
1206        my $inc = 1000;
1207        my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
1208        my $err_handler = $SVN::Error::handler;
1209        $SVN::Error::handler = \&skip_unknown_revs;
1210        while (1) {
1211                my @revs;
1212                $self->ra->get_log([''], $min, $max, 0, 1, 1, sub {
1213                        my ($paths, $rev, $author, $date, $log) = @_;
1214                        push @revs, [ $paths, $rev ] });
1215                foreach (@revs) {
1216                        my $log_entry = $self->do_fetch(@$_);
1217                        $self->do_git_commit($log_entry, @parents);
1218                }
1219                last if $max >= $head;
1220                $min = $max + 1;
1221                $max += $inc;
1222                $max = $head if ($max > $head);
1223        }
1224        $SVN::Error::handler = $err_handler;
1225}
1226
1227sub set_tree_cb {
1228        my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1229        # TODO: enable and test optimized commits:
1230        if (0 && $rev == ($self->{last_rev} + 1)) {
1231                $log_entry->{revision} = $rev;
1232                $log_entry->{author} = $author;
1233                $self->do_git_commit($log_entry, "$rev=$tree");
1234        } else {
1235                $self->fetch("$rev=$tree");
1236        }
1237}
1238
1239sub set_tree {
1240        my ($self, $tree) = (shift, shift);
1241        my $log_entry = ::get_commit_entry($tree);
1242        unless ($self->{last_rev}) {
1243                fatal("Must have an existing revision to commit\n");
1244        }
1245        my $pool = SVN::Pool->new;
1246        my $ed = SVN::Git::Editor->new({ r => $self->{last_rev},
1247                                         ra => $self->ra->dup,
1248                                         svn_path => $self->ra->{svn_path}
1249                                       },
1250                                       $self->ra->get_commit_editor(
1251                                         $log_entry->{log}, sub {
1252                                           $self->set_tree_cb($log_entry,
1253                                                              $tree, @_);
1254                                       }),
1255                                       $pool);
1256        my $mods = $ed->apply_diff($self->{last_commit}, $tree);
1257        if (@$mods == 0) {
1258                print "No changes\nr$self->{last_rev} = $tree\n";
1259        }
1260        $pool->clear;
1261}
1262
1263sub skip_unknown_revs {
1264        my ($err) = @_;
1265        my $errno = $err->apr_err();
1266        # Maybe the branch we're tracking didn't
1267        # exist when the repo started, so it's
1268        # not an error if it doesn't, just continue
1269        #
1270        # Wonderfully consistent library, eh?
1271        # 160013 - svn:// and file://
1272        # 175002 - http(s)://
1273        # 175007 - http(s):// (this repo required authorization, too...)
1274        #   More codes may be discovered later...
1275        if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
1276                return;
1277        }
1278        croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
1279}
1280
1281# rev_db:
1282# Tie::File seems to be prone to offset errors if revisions get sparse,
1283# it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1284# one of my favorite modules is out :<  Next up would be one of the DBM
1285# modules, but I'm not sure which is most portable...  So I'll just
1286# go with something that's plain-text, but still capable of
1287# being randomly accessed.  So here's my ultra-simple fixed-width
1288# database.  All records are 40 characters + "\n", so it's easy to seek
1289# to a revision: (41 * rev) is the byte offset.
1290# A record of 40 0s denotes an empty revision.
1291# And yes, it's still pretty fast (faster than Tie::File).
1292
1293sub rev_db_set {
1294        my ($self, $rev, $commit) = @_;
1295        length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1296        open my $fh, '+<', $self->{db_path} or croak $!;
1297        my $offset = $rev * 41;
1298        # assume that append is the common case:
1299        seek $fh, 0, 2 or croak $!;
1300        my $pos = tell $fh;
1301        if ($pos < $offset) {
1302                print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
1303                  or croak $!;
1304        }
1305        seek $fh, $offset, 0 or croak $!;
1306        print $fh $commit,"\n" or croak $!;
1307        close $fh or croak $!;
1308}
1309
1310sub rev_db_get {
1311        my ($self, $rev) = @_;
1312        my $ret;
1313        my $offset = $rev * 41;
1314        open my $fh, '<', $self->{db_path} or croak $!;
1315        if (seek $fh, $offset, 0) {
1316                $ret = readline $fh;
1317                if (defined $ret) {
1318                        chomp $ret;
1319                        $ret = undef if ($ret =~ /^0{40}$/);
1320                }
1321        }
1322        close $fh or croak $!;
1323        $ret;
1324}
1325
1326sub find_rev_before {
1327        my ($self, $rev, $eq_ok) = @_;
1328        --$rev unless $eq_ok;
1329        while ($rev > 0) {
1330                if (my $c = $self->rev_db_get($rev)) {
1331                        return ($rev, $c);
1332                }
1333                --$rev;
1334        }
1335        return (undef, undef);
1336}
1337
1338sub _new {
1339        my ($class, $repo_id, $ref_id, $path) = @_;
1340        unless (defined $repo_id && length $repo_id) {
1341                $repo_id = $Git::SVN::default_repo_id;
1342        }
1343        unless (defined $ref_id && length $ref_id) {
1344                $_[2] = $ref_id = $repo_id;
1345        }
1346        $_[1] = $repo_id = sanitize_remote_name($repo_id);
1347        my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1348        $_[3] = $path = '' unless (defined $path);
1349        bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1350                path => $path,
1351                db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1352}
1353
1354sub uri_encode {
1355        my ($f) = @_;
1356        $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1357        $f
1358}
1359
1360package Git::SVN::Prompt;
1361use strict;
1362use warnings;
1363require SVN::Core;
1364use vars qw/$_no_auth_cache $_username/;
1365
1366sub simple {
1367        my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1368        $may_save = undef if $_no_auth_cache;
1369        $default_username = $_username if defined $_username;
1370        if (defined $default_username && length $default_username) {
1371                if (defined $realm && length $realm) {
1372                        print STDERR "Authentication realm: $realm\n";
1373                        STDERR->flush;
1374                }
1375                $cred->username($default_username);
1376        } else {
1377                username($cred, $realm, $may_save, $pool);
1378        }
1379        $cred->password(_read_password("Password for '" .
1380                                       $cred->username . "': ", $realm));
1381        $cred->may_save($may_save);
1382        $SVN::_Core::SVN_NO_ERROR;
1383}
1384
1385sub ssl_server_trust {
1386        my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1387        $may_save = undef if $_no_auth_cache;
1388        print STDERR "Error validating server certificate for '$realm':\n";
1389        if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1390                print STDERR " - The certificate is not issued by a trusted ",
1391                      "authority. Use the\n",
1392                      "   fingerprint to validate the certificate manually!\n";
1393        }
1394        if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1395                print STDERR " - The certificate hostname does not match.\n";
1396        }
1397        if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1398                print STDERR " - The certificate is not yet valid.\n";
1399        }
1400        if ($failures & $SVN::Auth::SSL::EXPIRED) {
1401                print STDERR " - The certificate has expired.\n";
1402        }
1403        if ($failures & $SVN::Auth::SSL::OTHER) {
1404                print STDERR " - The certificate has an unknown error.\n";
1405        }
1406        printf STDERR
1407                "Certificate information:\n".
1408                " - Hostname: %s\n".
1409                " - Valid: from %s until %s\n".
1410                " - Issuer: %s\n".
1411                " - Fingerprint: %s\n",
1412                map $cert_info->$_, qw(hostname valid_from valid_until
1413                                       issuer_dname fingerprint);
1414        my $choice;
1415prompt:
1416        print STDERR $may_save ?
1417              "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1418              "(R)eject or accept (t)emporarily? ";
1419        STDERR->flush;
1420        $choice = lc(substr(<STDIN> || 'R', 0, 1));
1421        if ($choice =~ /^t$/i) {
1422                $cred->may_save(undef);
1423        } elsif ($choice =~ /^r$/i) {
1424                return -1;
1425        } elsif ($may_save && $choice =~ /^p$/i) {
1426                $cred->may_save($may_save);
1427        } else {
1428                goto prompt;
1429        }
1430        $cred->accepted_failures($failures);
1431        $SVN::_Core::SVN_NO_ERROR;
1432}
1433
1434sub ssl_client_cert {
1435        my ($cred, $realm, $may_save, $pool) = @_;
1436        $may_save = undef if $_no_auth_cache;
1437        print STDERR "Client certificate filename: ";
1438        STDERR->flush;
1439        chomp(my $filename = <STDIN>);
1440        $cred->cert_file($filename);
1441        $cred->may_save($may_save);
1442        $SVN::_Core::SVN_NO_ERROR;
1443}
1444
1445sub ssl_client_cert_pw {
1446        my ($cred, $realm, $may_save, $pool) = @_;
1447        $may_save = undef if $_no_auth_cache;
1448        $cred->password(_read_password("Password: ", $realm));
1449        $cred->may_save($may_save);
1450        $SVN::_Core::SVN_NO_ERROR;
1451}
1452
1453sub username {
1454        my ($cred, $realm, $may_save, $pool) = @_;
1455        $may_save = undef if $_no_auth_cache;
1456        if (defined $realm && length $realm) {
1457                print STDERR "Authentication realm: $realm\n";
1458        }
1459        my $username;
1460        if (defined $_username) {
1461                $username = $_username;
1462        } else {
1463                print STDERR "Username: ";
1464                STDERR->flush;
1465                chomp($username = <STDIN>);
1466        }
1467        $cred->username($username);
1468        $cred->may_save($may_save);
1469        $SVN::_Core::SVN_NO_ERROR;
1470}
1471
1472sub _read_password {
1473        my ($prompt, $realm) = @_;
1474        print STDERR $prompt;
1475        STDERR->flush;
1476        require Term::ReadKey;
1477        Term::ReadKey::ReadMode('noecho');
1478        my $password = '';
1479        while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1480                last if $key =~ /[\012\015]/; # \n\r
1481                $password .= $key;
1482        }
1483        Term::ReadKey::ReadMode('restore');
1484        print STDERR "\n";
1485        STDERR->flush;
1486        $password;
1487}
1488
1489package main;
1490
1491sub uri_encode {
1492        my ($f) = @_;
1493        $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1494        $f
1495}
1496
1497sub uri_decode {
1498        my ($f) = @_;
1499        $f =~ tr/+/ /;
1500        $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
1501        $f
1502}
1503
1504{
1505        my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1506                                $SVN::Node::dir.$SVN::Node::unknown.
1507                                $SVN::Node::none.$SVN::Node::file.
1508                                $SVN::Node::dir.$SVN::Node::unknown.
1509                                $SVN::Auth::SSL::CNMISMATCH.
1510                                $SVN::Auth::SSL::NOTYETVALID.
1511                                $SVN::Auth::SSL::EXPIRED.
1512                                $SVN::Auth::SSL::UNKNOWNCA.
1513                                $SVN::Auth::SSL::OTHER;
1514}
1515
1516package SVN::Git::Fetcher;
1517use vars qw/@ISA/;
1518use strict;
1519use warnings;
1520use Carp qw/croak/;
1521use IO::File qw//;
1522
1523# file baton members: path, mode_a, mode_b, pool, fh, blob, base
1524sub new {
1525        my ($class, $git_svn) = @_;
1526        my $self = SVN::Delta::Editor->new;
1527        bless $self, $class;
1528        $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1529        if (length $git_svn->{path}) {
1530                $self->{path_strip} = qr/\Q$git_svn->{path}\E\/?/;
1531        }
1532        $self->{empty} = {};
1533        $self->{dir_prop} = {};
1534        $self->{file_prop} = {};
1535        $self->{absent_dir} = {};
1536        $self->{absent_file} = {};
1537        ($self->{gui}, $self->{ctx}) = $git_svn->tmp_index_do(
1538               sub { command_input_pipe(qw/update-index -z --index-info/) } );
1539        require Digest::MD5;
1540        $self;
1541}
1542
1543sub open_root {
1544        { path => '' };
1545}
1546
1547sub open_directory {
1548        my ($self, $path, $pb, $rev) = @_;
1549        { path => $path };
1550}
1551
1552sub git_path {
1553        my ($self, $path) = @_;
1554        $path =~ s!$self->{path_strip}!! if $self->{path_strip};
1555        $path;
1556}
1557
1558sub delete_entry {
1559        my ($self, $path, $rev, $pb) = @_;
1560        my $gui = $self->{gui};
1561
1562        my $gpath = $self->git_path($path);
1563        # remove entire directories.
1564        if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1565                my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1566                                                     -r --name-only -z/,
1567                                                     $self->{c}, '--', $gpath);
1568                local $/ = "\0";
1569                while (<$ls>) {
1570                        print $gui '0 ',0 x 40,"\t",$_ or croak $!;
1571                        print "\tD\t$_\n" unless $self->{q};
1572                }
1573                print "\tD\t$gpath/\n" unless $self->{q};
1574                command_close_pipe($ls, $ctx);
1575                $self->{empty}->{$path} = 0
1576        } else {
1577                print $gui '0 ',0 x 40,"\t",$gpath,"\0" or croak $!;
1578                print "\tD\t$gpath\n" unless $self->{q};
1579        }
1580        undef;
1581}
1582
1583sub open_file {
1584        my ($self, $path, $pb, $rev) = @_;
1585        my $gpath = $self->git_path($path);
1586        my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1587                             =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1588        unless (defined $mode && defined $blob) {
1589                die "$path was not found in commit $self->{c} (r$rev)\n";
1590        }
1591        { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1592          pool => SVN::Pool->new, action => 'M' };
1593}
1594
1595sub add_file {
1596        my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1597        my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1598        delete $self->{empty}->{$dir};
1599        { path => $path, mode_a => 100644, mode_b => 100644,
1600          pool => SVN::Pool->new, action => 'A' };
1601}
1602
1603sub add_directory {
1604        my ($self, $path, $cp_path, $cp_rev) = @_;
1605        my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1606        delete $self->{empty}->{$dir};
1607        $self->{empty}->{$path} = 1;
1608        { path => $path };
1609}
1610
1611sub change_dir_prop {
1612        my ($self, $db, $prop, $value) = @_;
1613        $self->{dir_prop}->{$db->{path}} ||= {};
1614        $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1615        undef;
1616}
1617
1618sub absent_directory {
1619        my ($self, $path, $pb) = @_;
1620        $self->{absent_dir}->{$pb->{path}} ||= [];
1621        push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1622        undef;
1623}
1624
1625sub absent_file {
1626        my ($self, $path, $pb) = @_;
1627        $self->{absent_file}->{$pb->{path}} ||= [];
1628        push @{$self->{absent_file}->{$pb->{path}}}, $path;
1629        undef;
1630}
1631
1632sub change_file_prop {
1633        my ($self, $fb, $prop, $value) = @_;
1634        if ($prop eq 'svn:executable') {
1635                if ($fb->{mode_b} != 120000) {
1636                        $fb->{mode_b} = defined $value ? 100755 : 100644;
1637                }
1638        } elsif ($prop eq 'svn:special') {
1639                $fb->{mode_b} = defined $value ? 120000 : 100644;
1640        } else {
1641                $self->{file_prop}->{$fb->{path}} ||= {};
1642                $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1643        }
1644        undef;
1645}
1646
1647sub apply_textdelta {
1648        my ($self, $fb, $exp) = @_;
1649        my $fh = IO::File->new_tmpfile;
1650        $fh->autoflush(1);
1651        # $fh gets auto-closed() by SVN::TxDelta::apply(),
1652        # (but $base does not,) so dup() it for reading in close_file
1653        open my $dup, '<&', $fh or croak $!;
1654        my $base = IO::File->new_tmpfile;
1655        $base->autoflush(1);
1656        if ($fb->{blob}) {
1657                defined (my $pid = fork) or croak $!;
1658                if (!$pid) {
1659                        open STDOUT, '>&', $base or croak $!;
1660                        print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1661                        exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1662                }
1663                waitpid $pid, 0;
1664                croak $? if $?;
1665
1666                if (defined $exp) {
1667                        seek $base, 0, 0 or croak $!;
1668                        my $md5 = Digest::MD5->new;
1669                        $md5->addfile($base);
1670                        my $got = $md5->hexdigest;
1671                        die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1672                            "expected: $exp\n",
1673                            "     got: $got\n" if ($got ne $exp);
1674                }
1675        }
1676        seek $base, 0, 0 or croak $!;
1677        $fb->{fh} = $dup;
1678        $fb->{base} = $base;
1679        [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1680}
1681
1682sub close_file {
1683        my ($self, $fb, $exp) = @_;
1684        my $hash;
1685        my $path = $self->git_path($fb->{path});
1686        if (my $fh = $fb->{fh}) {
1687                seek($fh, 0, 0) or croak $!;
1688                my $md5 = Digest::MD5->new;
1689                $md5->addfile($fh);
1690                my $got = $md5->hexdigest;
1691                die "Checksum mismatch: $path\n",
1692                    "expected: $exp\n    got: $got\n" if ($got ne $exp);
1693                seek($fh, 0, 0) or croak $!;
1694                if ($fb->{mode_b} == 120000) {
1695                        read($fh, my $buf, 5) == 5 or croak $!;
1696                        $buf eq 'link ' or die "$path has mode 120000",
1697                                               "but is not a link\n";
1698                }
1699                defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1700                if (!$pid) {
1701                        open STDIN, '<&', $fh or croak $!;
1702                        exec qw/git-hash-object -w --stdin/ or croak $!;
1703                }
1704                chomp($hash = do { local $/; <$out> });
1705                close $out or croak $!;
1706                close $fh or croak $!;
1707                $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1708                close $fb->{base} or croak $!;
1709        } else {
1710                $hash = $fb->{blob} or die "no blob information\n";
1711        }
1712        $fb->{pool}->clear;
1713        my $gui = $self->{gui};
1714        print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
1715        print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
1716        undef;
1717}
1718
1719sub abort_edit {
1720        my $self = shift;
1721        eval { command_close_pipe($self->{gui}, $self->{ctx}) };
1722        $self->SUPER::abort_edit(@_);
1723}
1724
1725sub close_edit {
1726        my $self = shift;
1727        command_close_pipe($self->{gui}, $self->{ctx});
1728        $self->{git_commit_ok} = 1;
1729        $self->SUPER::close_edit(@_);
1730}
1731
1732package SVN::Git::Editor;
1733use vars qw/@ISA/;
1734use strict;
1735use warnings;
1736use Carp qw/croak/;
1737use IO::File;
1738
1739sub new {
1740        my $class = shift;
1741        my $git_svn = shift;
1742        my $self = SVN::Delta::Editor->new(@_);
1743        bless $self, $class;
1744        foreach (qw/svn_path r ra/) {
1745                die "$_ required!\n" unless (defined $git_svn->{$_});
1746                $self->{$_} = $git_svn->{$_};
1747        }
1748        $self->{pool} = SVN::Pool->new;
1749        $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1750        $self->{rm} = { };
1751        require Digest::MD5;
1752        return $self;
1753}
1754
1755sub split_path {
1756        return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
1757}
1758
1759sub repo_path {
1760        (defined $_[1] && length $_[1]) ? $_[1] : ''
1761}
1762
1763sub url_path {
1764        my ($self, $path) = @_;
1765        $self->{ra}->{url} . '/' . $self->repo_path($path);
1766}
1767
1768sub rmdirs {
1769        my ($self, $tree_b) = @_;
1770        my $rm = $self->{rm};
1771        delete $rm->{''}; # we never delete the url we're tracking
1772        return unless %$rm;
1773
1774        foreach (keys %$rm) {
1775                my @d = split m#/#, $_;
1776                my $c = shift @d;
1777                $rm->{$c} = 1;
1778                while (@d) {
1779                        $c .= '/' . shift @d;
1780                        $rm->{$c} = 1;
1781                }
1782        }
1783        delete $rm->{$self->{svn_path}};
1784        delete $rm->{''}; # we never delete the url we're tracking
1785        return unless %$rm;
1786
1787        my ($fh, $ctx) = command_output_pipe(
1788                                   qw/ls-tree --name-only -r -z/, $tree_b);
1789        local $/ = "\0";
1790        while (<$fh>) {
1791                chomp;
1792                my @dn = split m#/#, $_;
1793                while (pop @dn) {
1794                        delete $rm->{join '/', @dn};
1795                }
1796                unless (%$rm) {
1797                        close $fh;
1798                        return;
1799                }
1800        }
1801        command_close_pipe($fh, $ctx);
1802
1803        my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
1804        foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
1805                $self->close_directory($bat->{$d}, $p);
1806                my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
1807                print "\tD+\t$d/\n" unless $::_q;
1808                $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
1809                delete $bat->{$d};
1810        }
1811}
1812
1813sub open_or_add_dir {
1814        my ($self, $full_path, $baton) = @_;
1815        my $t = $self->{ra}->check_path($full_path, $self->{r});
1816        if ($t == $SVN::Node::none) {
1817                return $self->add_directory($full_path, $baton,
1818                                                undef, -1, $self->{pool});
1819        } elsif ($t == $SVN::Node::dir) {
1820                return $self->open_directory($full_path, $baton,
1821                                                $self->{r}, $self->{pool});
1822        }
1823        print STDERR "$full_path already exists in repository at ",
1824                "r$self->{r} and it is not a directory (",
1825                ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
1826        exit 1;
1827}
1828
1829sub ensure_path {
1830        my ($self, $path) = @_;
1831        my $bat = $self->{bat};
1832        $path = $self->repo_path($path);
1833        return $bat->{''} unless (length $path);
1834        my @p = split m#/+#, $path;
1835        my $c = shift @p;
1836        $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
1837        while (@p) {
1838                my $c0 = $c;
1839                $c .= '/' . shift @p;
1840                $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
1841        }
1842        return $bat->{$c};
1843}
1844
1845sub A {
1846        my ($self, $m) = @_;
1847        my ($dir, $file) = split_path($m->{file_b});
1848        my $pbat = $self->ensure_path($dir);
1849        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1850                                        undef, -1);
1851        print "\tA\t$m->{file_b}\n" unless $::_q;
1852        $self->chg_file($fbat, $m);
1853        $self->close_file($fbat,undef,$self->{pool});
1854}
1855
1856sub C {
1857        my ($self, $m) = @_;
1858        my ($dir, $file) = split_path($m->{file_b});
1859        my $pbat = $self->ensure_path($dir);
1860        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1861                                $self->url_path($m->{file_a}), $self->{r});
1862        print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
1863        $self->chg_file($fbat, $m);
1864        $self->close_file($fbat,undef,$self->{pool});
1865}
1866
1867sub delete_entry {
1868        my ($self, $path, $pbat) = @_;
1869        my $rpath = $self->repo_path($path);
1870        my ($dir, $file) = split_path($rpath);
1871        $self->{rm}->{$dir} = 1;
1872        $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
1873}
1874
1875sub R {
1876        my ($self, $m) = @_;
1877        my ($dir, $file) = split_path($m->{file_b});
1878        my $pbat = $self->ensure_path($dir);
1879        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1880                                $self->url_path($m->{file_a}), $self->{r});
1881        print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
1882        $self->chg_file($fbat, $m);
1883        $self->close_file($fbat,undef,$self->{pool});
1884
1885        ($dir, $file) = split_path($m->{file_a});
1886        $pbat = $self->ensure_path($dir);
1887        $self->delete_entry($m->{file_a}, $pbat);
1888}
1889
1890sub M {
1891        my ($self, $m) = @_;
1892        my ($dir, $file) = split_path($m->{file_b});
1893        my $pbat = $self->ensure_path($dir);
1894        my $fbat = $self->open_file($self->repo_path($m->{file_b}),
1895                                $pbat,$self->{r},$self->{pool});
1896        print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
1897        $self->chg_file($fbat, $m);
1898        $self->close_file($fbat,undef,$self->{pool});
1899}
1900
1901sub T { shift->M(@_) }
1902
1903sub change_file_prop {
1904        my ($self, $fbat, $pname, $pval) = @_;
1905        $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
1906}
1907
1908sub chg_file {
1909        my ($self, $fbat, $m) = @_;
1910        if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
1911                $self->change_file_prop($fbat,'svn:executable','*');
1912        } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1913                $self->change_file_prop($fbat,'svn:executable',undef);
1914        }
1915        my $fh = IO::File->new_tmpfile or croak $!;
1916        if ($m->{mode_b} =~ /^120/) {
1917                print $fh 'link ' or croak $!;
1918                $self->change_file_prop($fbat,'svn:special','*');
1919        } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
1920                $self->change_file_prop($fbat,'svn:special',undef);
1921        }
1922        defined(my $pid = fork) or croak $!;
1923        if (!$pid) {
1924                open STDOUT, '>&', $fh or croak $!;
1925                exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
1926        }
1927        waitpid $pid, 0;
1928        croak $? if $?;
1929        $fh->flush == 0 or croak $!;
1930        seek $fh, 0, 0 or croak $!;
1931
1932        my $md5 = Digest::MD5->new;
1933        $md5->addfile($fh) or croak $!;
1934        seek $fh, 0, 0 or croak $!;
1935
1936        my $exp = $md5->hexdigest;
1937        my $pool = SVN::Pool->new;
1938        my $atd = $self->apply_textdelta($fbat, undef, $pool);
1939        my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
1940        die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
1941        $pool->clear;
1942
1943        close $fh or croak $!;
1944}
1945
1946sub D {
1947        my ($self, $m) = @_;
1948        my ($dir, $file) = split_path($m->{file_b});
1949        my $pbat = $self->ensure_path($dir);
1950        print "\tD\t$m->{file_b}\n" unless $::_q;
1951        $self->delete_entry($m->{file_b}, $pbat);
1952}
1953
1954sub close_edit {
1955        my ($self) = @_;
1956        my ($p,$bat) = ($self->{pool}, $self->{bat});
1957        foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
1958                $self->close_directory($bat->{$_}, $p);
1959        }
1960        $self->SUPER::close_edit($p);
1961        $p->clear;
1962}
1963
1964sub abort_edit {
1965        my ($self) = @_;
1966        $self->SUPER::abort_edit($self->{pool});
1967        $self->{pool}->clear;
1968}
1969
1970# this drives the editor
1971sub apply_diff {
1972        my ($self, $tree_a, $tree_b) = @_;
1973        my @diff_tree = qw(diff-tree -z -r);
1974        if ($::_cp_similarity) {
1975                push @diff_tree, "-C$::_cp_similarity";
1976        } else {
1977                push @diff_tree, '-C';
1978        }
1979        push @diff_tree, '--find-copies-harder' if $::_find_copies_harder;
1980        push @diff_tree, "-l$::_l" if defined $::_l;
1981        push @diff_tree, $tree_a, $tree_b;
1982        my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1983        my $nl = $/;
1984        local $/ = "\0";
1985        my $state = 'meta';
1986        my @mods;
1987        while (<$diff_fh>) {
1988                chomp $_; # this gets rid of the trailing "\0"
1989                if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1990                                        $::sha1\s($::sha1)\s
1991                                        ([MTCRAD])\d*$/xo) {
1992                        push @mods, {   mode_a => $1, mode_b => $2,
1993                                        sha1_b => $3, chg => $4 };
1994                        if ($4 =~ /^(?:C|R)$/) {
1995                                $state = 'file_a';
1996                        } else {
1997                                $state = 'file_b';
1998                        }
1999                } elsif ($state eq 'file_a') {
2000                        my $x = $mods[$#mods] or croak "Empty array\n";
2001                        if ($x->{chg} !~ /^(?:C|R)$/) {
2002                                croak "Error parsing $_, $x->{chg}\n";
2003                        }
2004                        $x->{file_a} = $_;
2005                        $state = 'file_b';
2006                } elsif ($state eq 'file_b') {
2007                        my $x = $mods[$#mods] or croak "Empty array\n";
2008                        if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2009                                croak "Error parsing $_, $x->{chg}\n";
2010                        }
2011                        if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2012                                croak "Error parsing $_, $x->{chg}\n";
2013                        }
2014                        $x->{file_b} = $_;
2015                        $state = 'meta';
2016                } else {
2017                        croak "Error parsing $_\n";
2018                }
2019        }
2020        command_close_pipe($diff_fh, $ctx);
2021        $/ = $nl;
2022
2023        my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2024        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @mods) {
2025                my $f = $m->{chg};
2026                if (defined $o{$f}) {
2027                        $self->$f($m);
2028                } else {
2029                        fatal("Invalid change type: $f\n");
2030                }
2031        }
2032        $self->rmdirs($tree_b) if $::_rmdir;
2033        if (@mods == 0) {
2034                $self->abort_edit;
2035        } else {
2036                $self->close_edit;
2037        }
2038        \@mods;
2039}
2040
2041package Git::SVN::Ra;
2042use vars qw/@ISA $config_dir/;
2043use strict;
2044use warnings;
2045my ($can_do_switch);
2046my %RA;
2047
2048BEGIN {
2049        # enforce temporary pool usage for some simple functions
2050        my $e;
2051        foreach (qw/get_latest_revnum rev_proplist get_file
2052                    check_path get_dir get_uuid get_repos_root/) {
2053                $e .= "sub $_ {
2054                        my \$self = shift;
2055                        my \$pool = SVN::Pool->new;
2056                        my \@ret = \$self->SUPER::$_(\@_,\$pool);
2057                        \$pool->clear;
2058                        wantarray ? \@ret : \$ret[0]; }\n";
2059        }
2060        eval $e;
2061}
2062
2063sub new {
2064        my ($class, $url) = @_;
2065        $url =~ s!/+$!!;
2066        return $RA{$url} if $RA{$url};
2067
2068        SVN::_Core::svn_config_ensure($config_dir, undef);
2069        my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2070            SVN::Client::get_simple_provider(),
2071            SVN::Client::get_ssl_server_trust_file_provider(),
2072            SVN::Client::get_simple_prompt_provider(
2073              \&Git::SVN::Prompt::simple, 2),
2074            SVN::Client::get_ssl_client_cert_prompt_provider(
2075              \&Git::SVN::Prompt::ssl_client_cert, 2),
2076            SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2077              \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2078            SVN::Client::get_username_provider(),
2079            SVN::Client::get_ssl_server_trust_prompt_provider(
2080              \&Git::SVN::Prompt::ssl_server_trust),
2081            SVN::Client::get_username_prompt_provider(
2082              \&Git::SVN::Prompt::username, 2),
2083          ]);
2084        my $config = SVN::Core::config_get_config($config_dir);
2085        my $self = SVN::Ra->new(url => $url, auth => $baton,
2086                              config => $config,
2087                              pool => SVN::Pool->new,
2088                              auth_provider_callbacks => $callbacks);
2089        $self->{svn_path} = $url;
2090        $self->{repos_root} = $self->get_repos_root;
2091        $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2092        $RA{$url} = bless $self, $class;
2093}
2094
2095sub DESTROY {
2096        # do not call the real DESTROY since we store ourselves in %RA
2097}
2098
2099sub dup {
2100        my ($self) = @_;
2101        my $dup = SVN::Ra->new(pool => SVN::Pool->new,
2102                                map { $_ => $self->{$_} } qw/config url
2103                     auth auth_provider_callbacks repos_root svn_path/);
2104        bless $dup, ref $self;
2105}
2106
2107sub get_log {
2108        my ($self, @args) = @_;
2109        my $pool = SVN::Pool->new;
2110        $args[4]-- if $args[4] && ! $::_follow_parent;
2111        splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2112        my $ret = $self->SUPER::get_log(@args, $pool);
2113        $pool->clear;
2114        $ret;
2115}
2116
2117sub get_commit_editor {
2118        my ($self, $log, $cb, $pool) = @_;
2119        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2120        $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2121}
2122
2123sub uuid {
2124        my ($self) = @_;
2125        $self->{uuid} ||= $self->get_uuid;
2126}
2127
2128sub gs_do_update {
2129        my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
2130        my $pool = SVN::Pool->new;
2131        my $reporter = $self->do_update($rev_b, $path, $recurse,
2132                                        $editor, $pool);
2133        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2134        my $new = ($rev_a == $rev_b);
2135        $reporter->set_path('', $rev_a, $new, @lock, $pool);
2136        $reporter->finish_report($pool);
2137        $pool->clear;
2138        $editor->{git_commit_ok};
2139}
2140
2141sub gs_do_switch {
2142        my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
2143        my $pool = SVN::Pool->new;
2144        my $reporter = $self->do_switch($rev_b, $path, $recurse,
2145                                        $url_b, $editor, $pool);
2146        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2147        $reporter->set_path($path, $rev_a, 0, @lock, $pool);
2148        $reporter->finish_report($pool);
2149        $pool->clear;
2150        $editor->{git_commit_ok};
2151}
2152
2153sub can_do_switch {
2154        my $self = shift;
2155        unless (defined $can_do_switch) {
2156                my $pool = SVN::Pool->new;
2157                my $rep = eval {
2158                        $self->do_switch(1, '', 0, $self->{url},
2159                                         SVN::Delta::Editor->new, $pool);
2160                };
2161                if ($@) {
2162                        $can_do_switch = 0;
2163                } else {
2164                        $rep->abort_report($pool);
2165                        $can_do_switch = 1;
2166                }
2167                $pool->clear;
2168        }
2169        $can_do_switch;
2170}
2171
2172package Git::SVN::Log;
2173use strict;
2174use warnings;
2175use POSIX qw/strftime/;
2176use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2177            %rusers $show_commit $incremental/;
2178my $l_fmt;
2179
2180sub cmt_showable {
2181        my ($c) = @_;
2182        return 1 if defined $c->{r};
2183        if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2184                                $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2185                my @log = command(qw/cat-file commit/, $c->{c});
2186                shift @log while ($log[0] ne "\n");
2187                shift @log;
2188                @{$c->{l}} = grep !/^git-svn-id: /, @log;
2189
2190                (undef, $c->{r}, undef) = ::extract_metadata(
2191                                (grep(/^git-svn-id: /, @log))[-1]);
2192        }
2193        return defined $c->{r};
2194}
2195
2196sub log_use_color {
2197        return 1 if $color;
2198        my ($dc, $dcvar);
2199        $dcvar = 'color.diff';
2200        $dc = `git-config --get $dcvar`;
2201        if ($dc eq '') {
2202                # nothing at all; fallback to "diff.color"
2203                $dcvar = 'diff.color';
2204                $dc = `git-config --get $dcvar`;
2205        }
2206        chomp($dc);
2207        if ($dc eq 'auto') {
2208                my $pc;
2209                $pc = `git-config --get color.pager`;
2210                if ($pc eq '') {
2211                        # does not have it -- fallback to pager.color
2212                        $pc = `git-config --bool --get pager.color`;
2213                }
2214                else {
2215                        $pc = `git-config --bool --get color.pager`;
2216                        if ($?) {
2217                                $pc = 'false';
2218                        }
2219                }
2220                chomp($pc);
2221                if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2222                        return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2223                }
2224                return 0;
2225        }
2226        return 0 if $dc eq 'never';
2227        return 1 if $dc eq 'always';
2228        chomp($dc = `git-config --bool --get $dcvar`);
2229        return ($dc eq 'true');
2230}
2231
2232sub git_svn_log_cmd {
2233        my ($r_min, $r_max) = @_;
2234        my $gs = Git::SVN->_new;
2235        my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2236                   $gs->refname);
2237        push @cmd, '-r' unless $non_recursive;
2238        push @cmd, qw/--raw --name-status/ if $verbose;
2239        push @cmd, '--color' if log_use_color();
2240        return @cmd unless defined $r_max;
2241        if ($r_max == $r_min) {
2242                push @cmd, '--max-count=1';
2243                if (my $c = $gs->rev_db_get($r_max)) {
2244                        push @cmd, $c;
2245                }
2246        } else {
2247                my ($c_min, $c_max);
2248                $c_max = $gs->rev_db_get($r_max);
2249                $c_min = $gs->rev_db_get($r_min);
2250                if (defined $c_min && defined $c_max) {
2251                        if ($r_max > $r_max) {
2252                                push @cmd, "$c_min..$c_max";
2253                        } else {
2254                                push @cmd, "$c_max..$c_min";
2255                        }
2256                } elsif ($r_max > $r_min) {
2257                        push @cmd, $c_max;
2258                } else {
2259                        push @cmd, $c_min;
2260                }
2261        }
2262        return @cmd;
2263}
2264
2265# adapted from pager.c
2266sub config_pager {
2267        $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2268        if (!defined $pager) {
2269                $pager = 'less';
2270        } elsif (length $pager == 0 || $pager eq 'cat') {
2271                $pager = undef;
2272        }
2273}
2274
2275sub run_pager {
2276        return unless -t *STDOUT;
2277        pipe my $rfd, my $wfd or return;
2278        defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2279        if (!$pid) {
2280                open STDOUT, '>&', $wfd or
2281                                     ::fatal "Can't redirect to stdout: $!\n";
2282                return;
2283        }
2284        open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2285        $ENV{LESS} ||= 'FRSX';
2286        exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2287}
2288
2289sub get_author_info {
2290        my ($dest, $author, $t, $tz) = @_;
2291        $author =~ s/(?:^\s*|\s*$)//g;
2292        $dest->{a_raw} = $author;
2293        my $au;
2294        if ($::_authors) {
2295                $au = $rusers{$author} || undef;
2296        }
2297        if (!$au) {
2298                ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2299        }
2300        $dest->{t} = $t;
2301        $dest->{tz} = $tz;
2302        $dest->{a} = $au;
2303        # Date::Parse isn't in the standard Perl distro :(
2304        if ($tz =~ s/^\+//) {
2305                $t += ::tz_to_s_offset($tz);
2306        } elsif ($tz =~ s/^\-//) {
2307                $t -= ::tz_to_s_offset($tz);
2308        }
2309        $dest->{t_utc} = $t;
2310}
2311
2312sub process_commit {
2313        my ($c, $r_min, $r_max, $defer) = @_;
2314        if (defined $r_min && defined $r_max) {
2315                if ($r_min == $c->{r} && $r_min == $r_max) {
2316                        show_commit($c);
2317                        return 0;
2318                }
2319                return 1 if $r_min == $r_max;
2320                if ($r_min < $r_max) {
2321                        # we need to reverse the print order
2322                        return 0 if (defined $limit && --$limit < 0);
2323                        push @$defer, $c;
2324                        return 1;
2325                }
2326                if ($r_min != $r_max) {
2327                        return 1 if ($r_min < $c->{r});
2328                        return 1 if ($r_max > $c->{r});
2329                }
2330        }
2331        return 0 if (defined $limit && --$limit < 0);
2332        show_commit($c);
2333        return 1;
2334}
2335
2336sub show_commit {
2337        my $c = shift;
2338        if ($oneline) {
2339                my $x = "\n";
2340                if (my $l = $c->{l}) {
2341                        while ($l->[0] =~ /^\s*$/) { shift @$l }
2342                        $x = $l->[0];
2343                }
2344                $l_fmt ||= 'A' . length($c->{r});
2345                print 'r',pack($l_fmt, $c->{r}),' | ';
2346                print "$c->{c} | " if $show_commit;
2347                print $x;
2348        } else {
2349                show_commit_normal($c);
2350        }
2351}
2352
2353sub show_commit_changed_paths {
2354        my ($c) = @_;
2355        return unless $c->{changed};
2356        print "Changed paths:\n", @{$c->{changed}};
2357}
2358
2359sub show_commit_normal {
2360        my ($c) = @_;
2361        print '-' x72, "\nr$c->{r} | ";
2362        print "$c->{c} | " if $show_commit;
2363        print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2364                                 localtime($c->{t_utc})), ' | ';
2365        my $nr_line = 0;
2366
2367        if (my $l = $c->{l}) {
2368                while ($l->[$#$l] eq "\n" && $#$l > 0
2369                                          && $l->[($#$l - 1)] eq "\n") {
2370                        pop @$l;
2371                }
2372                $nr_line = scalar @$l;
2373                if (!$nr_line) {
2374                        print "1 line\n\n\n";
2375                } else {
2376                        if ($nr_line == 1) {
2377                                $nr_line = '1 line';
2378                        } else {
2379                                $nr_line .= ' lines';
2380                        }
2381                        print $nr_line, "\n";
2382                        show_commit_changed_paths($c);
2383                        print "\n";
2384                        print $_ foreach @$l;
2385                }
2386        } else {
2387                print "1 line\n";
2388                show_commit_changed_paths($c);
2389                print "\n";
2390
2391        }
2392        foreach my $x (qw/raw diff/) {
2393                if ($c->{$x}) {
2394                        print "\n";
2395                        print $_ foreach @{$c->{$x}}
2396                }
2397        }
2398}
2399
2400sub cmd_show_log {
2401        my (@args) = @_;
2402        my ($r_min, $r_max);
2403        my $r_last = -1; # prevent dupes
2404        if (defined $TZ) {
2405                $ENV{TZ} = $TZ;
2406        } else {
2407                delete $ENV{TZ};
2408        }
2409        if (defined $::_revision) {
2410                if ($::_revision =~ /^(\d+):(\d+)$/) {
2411                        ($r_min, $r_max) = ($1, $2);
2412                } elsif ($::_revision =~ /^\d+$/) {
2413                        $r_min = $r_max = $::_revision;
2414                } else {
2415                        ::fatal "-r$::_revision is not supported, use ",
2416                                "standard \'git log\' arguments instead\n";
2417                }
2418        }
2419
2420        config_pager();
2421        @args = (git_svn_log_cmd($r_min, $r_max), @args);
2422        my $log = command_output_pipe(@args);
2423        run_pager();
2424        my (@k, $c, $d);
2425        my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2426        while (<$log>) {
2427                if (/^${esc_color}commit ($::sha1_short)/o) {
2428                        my $cmt = $1;
2429                        if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2430                                $r_last = $c->{r};
2431                                process_commit($c, $r_min, $r_max, \@k) or
2432                                                                goto out;
2433                        }
2434                        $d = undef;
2435                        $c = { c => $cmt };
2436                } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2437                        get_author_info($c, $1, $2, $3);
2438                } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2439                        # ignore
2440                } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2441                        push @{$c->{raw}}, $_;
2442                } elsif (/^${esc_color}[ACRMDT]\t/) {
2443                        # we could add $SVN->{svn_path} here, but that requires
2444                        # remote access at the moment (repo_path_split)...
2445                        s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
2446                        push @{$c->{changed}}, $_;
2447                } elsif (/^${esc_color}diff /o) {
2448                        $d = 1;
2449                        push @{$c->{diff}}, $_;
2450                } elsif ($d) {
2451                        push @{$c->{diff}}, $_;
2452                } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
2453                        ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2454                } elsif (s/^${esc_color}    //o) {
2455                        push @{$c->{l}}, $_;
2456                }
2457        }
2458        if ($c && defined $c->{r} && $c->{r} != $r_last) {
2459                $r_last = $c->{r};
2460                process_commit($c, $r_min, $r_max, \@k);
2461        }
2462        if (@k) {
2463                my $swap = $r_max;
2464                $r_max = $r_min;
2465                $r_min = $swap;
2466                process_commit($_, $r_min, $r_max) foreach reverse @k;
2467        }
2468out:
2469        close $log;
2470        print '-' x72,"\n" unless $incremental || $oneline;
2471}
2472
2473package Git::SVN::Migration;
2474# these version numbers do NOT correspond to actual version numbers
2475# of git nor git-svn.  They are just relative.
2476#
2477# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2478#
2479# v1 layout: .git/$id/info/url, refs/remotes/$id
2480#
2481# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2482#
2483# v3 layout: .git/svn/$id, refs/remotes/$id
2484#            - info/url may remain for backwards compatibility
2485#            - this is what we migrate up to this layout automatically,
2486#            - this will be used by git svn init on single branches
2487#
2488# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2489#            - this is only created for newly multi-init-ed
2490#              repositories.  Similar in spirit to the
2491#              --use-separate-remotes option in git-clone (now default)
2492#            - we do not automatically migrate to this (following
2493#              the example set by core git)
2494use strict;
2495use warnings;
2496use Carp qw/croak/;
2497use File::Path qw/mkpath/;
2498use File::Basename qw/dirname basename/;
2499use vars qw/$_minimize/;
2500
2501sub migrate_from_v0 {
2502        my $git_dir = $ENV{GIT_DIR};
2503        return undef unless -d $git_dir;
2504        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2505        my $migrated = 0;
2506        while (<$fh>) {
2507                chomp;
2508                my ($id, $orig_ref) = ($_, $_);
2509                next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2510                next unless -f "$git_dir/$id/info/url";
2511                my $new_ref = "refs/remotes/$id";
2512                if (::verify_ref("$new_ref^0")) {
2513                        print STDERR "W: $orig_ref is probably an old ",
2514                                     "branch used by an ancient version of ",
2515                                     "git-svn.\n",
2516                                     "However, $new_ref also exists.\n",
2517                                     "We will not be able ",
2518                                     "to use this branch until this ",
2519                                     "ambiguity is resolved.\n";
2520                        next;
2521                }
2522                print STDERR "Migrating from v0 layout...\n" if !$migrated;
2523                print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2524                command_noisy('update-ref', $new_ref, $orig_ref);
2525                command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2526                $migrated++;
2527        }
2528        command_close_pipe($fh, $ctx);
2529        print STDERR "Done migrating from v0 layout...\n" if $migrated;
2530        $migrated;
2531}
2532
2533sub migrate_from_v1 {
2534        my $git_dir = $ENV{GIT_DIR};
2535        my $migrated = 0;
2536        return $migrated unless -d $git_dir;
2537        my $svn_dir = "$git_dir/svn";
2538
2539        # just in case somebody used 'svn' as their $id at some point...
2540        return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2541
2542        print STDERR "Migrating from a git-svn v1 layout...\n";
2543        mkpath([$svn_dir]);
2544        print STDERR "Data from a previous version of git-svn exists, but\n\t",
2545                     "$svn_dir\n\t(required for this version ",
2546                     "($::VERSION) of git-svn) does not. exist\n";
2547        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2548        while (<$fh>) {
2549                my $x = $_;
2550                next unless $x =~ s#^refs/remotes/##;
2551                chomp $x;
2552                next unless -f "$git_dir/$x/info/url";
2553                my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2554                next unless $u;
2555                my $dn = dirname("$git_dir/svn/$x");
2556                mkpath([$dn]) unless -d $dn;
2557                if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2558                        mkpath(["$git_dir/svn/svn"]);
2559                        print STDERR " - $git_dir/$x/info => ",
2560                                        "$git_dir/svn/$x/info\n";
2561                        rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2562                               croak "$!: $x";
2563                        # don't worry too much about these, they probably
2564                        # don't exist with repos this old (save for index,
2565                        # and we can easily regenerate that)
2566                        foreach my $f (qw/unhandled.log index .rev_db/) {
2567                                rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2568                        }
2569                } else {
2570                        print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2571                        rename "$git_dir/$x", "$git_dir/svn/$x" or
2572                               croak "$!: $x";
2573                }
2574                $migrated++;
2575        }
2576        command_close_pipe($fh, $ctx);
2577        print STDERR "Done migrating from a git-svn v1 layout\n";
2578        $migrated;
2579}
2580
2581sub read_old_urls {
2582        my ($l_map, $pfx, $path) = @_;
2583        my @dir;
2584        foreach (<$path/*>) {
2585                if (-r "$_/info/url") {
2586                        $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2587                        my $ref_id = $pfx . basename $_;
2588                        my $url = ::file_to_s("$_/info/url");
2589                        $l_map->{$ref_id} = $url;
2590                } elsif (-d $_) {
2591                        push @dir, $_;
2592                }
2593        }
2594        foreach (@dir) {
2595                my $x = $_;
2596                $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2597                read_old_urls($l_map, $x, $_);
2598        }
2599}
2600
2601sub migrate_from_v2 {
2602        my @cfg = command(qw/config -l/);
2603        return if grep /^svn-remote\..+\.url=/, @cfg;
2604        my %l_map;
2605        read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2606        my $migrated = 0;
2607
2608        foreach my $ref_id (sort keys %l_map) {
2609                Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2610                $migrated++;
2611        }
2612        $migrated;
2613}
2614
2615sub minimize_connections {
2616        my $r = Git::SVN::read_all_remotes();
2617        my $new_urls = {};
2618        my $root_repos = {};
2619        foreach my $repo_id (keys %$r) {
2620                my $url = $r->{$repo_id}->{url} or next;
2621                my $fetch = $r->{$repo_id}->{fetch} or next;
2622                my $ra = Git::SVN::Ra->new($url);
2623
2624                # skip existing cases where we already connect to the root
2625                if (($ra->{url} eq $ra->{repos_root}) ||
2626                    (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
2627                     $repo_id)) {
2628                        $root_repos->{$ra->{url}} = $repo_id;
2629                        next;
2630                }
2631
2632                my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
2633                my $root_path = $ra->{url};
2634                $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
2635                foreach my $path (keys %$fetch) {
2636                        my $ref_id = $fetch->{$path};
2637                        my $gs = Git::SVN->new($ref_id, $repo_id, $path);
2638
2639                        # make sure we can read when connecting to
2640                        # a higher level of a repository
2641                        my ($last_rev, undef) = $gs->last_rev_commit;
2642                        if (!defined $last_rev) {
2643                                $last_rev = eval {
2644                                        $root_ra->get_latest_revnum;
2645                                };
2646                                next if $@;
2647                        }
2648                        my $new = $root_path;
2649                        $new .= length $path ? "/$path" : '';
2650                        eval {
2651                                $root_ra->get_log([$new], $last_rev, $last_rev,
2652                                                  0, 0, 1, sub { });
2653                        };
2654                        next if $@;
2655                        $new_urls->{$ra->{repos_root}}->{$new} =
2656                                { ref_id => $ref_id,
2657                                  old_repo_id => $repo_id,
2658                                  old_path => $path };
2659                }
2660        }
2661
2662        my @emptied;
2663        foreach my $url (keys %$new_urls) {
2664                # see if we can re-use an existing [svn-remote "repo_id"]
2665                # instead of creating a(n ugly) new section:
2666                my $repo_id = $root_repos->{$url} ||
2667                              Git::SVN::sanitize_remote_name($url);
2668
2669                my $fetch = $new_urls->{$url};
2670                foreach my $path (keys %$fetch) {
2671                        my $x = $fetch->{$path};
2672                        Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
2673                        my $pfx = "svn-remote.$x->{old_repo_id}";
2674
2675                        my $old_fetch = quotemeta("$x->{old_path}:".
2676                                                  "refs/remotes/$x->{ref_id}");
2677                        command_noisy(qw/repo-config --unset/,
2678                                      "$pfx.fetch", '^'. $old_fetch . '$');
2679                        delete $r->{$x->{old_repo_id}}->
2680                               {fetch}->{$x->{old_path}};
2681                        if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
2682                                command_noisy(qw/repo-config --unset/,
2683                                              "$pfx.url");
2684                                push @emptied, $x->{old_repo_id}
2685                        }
2686                }
2687        }
2688        if (@emptied) {
2689                my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
2690                           "$ENV{GIT_DIR}/config";
2691                print STDERR <<EOF;
2692The following [svn-remote] sections in your config file ($file) are empty
2693and can be safely removed:
2694EOF
2695                print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
2696        }
2697}
2698
2699sub migration_check {
2700        migrate_from_v0();
2701        migrate_from_v1();
2702        migrate_from_v2();
2703        minimize_connections() if $_minimize;
2704}
2705
2706__END__
2707
2708Data structures:
2709
2710$log_entry hashref as returned by libsvn_log_entry()
2711{
2712        log => 'whitespace-formatted log entry
2713',                                              # trailing newline is preserved
2714        revision => '8',                        # integer
2715        date => '2004-02-24T17:01:44.108345Z',  # commit date
2716        author => 'committer name'
2717};
2718
2719@mods = array of diff-index line hashes, each element represents one line
2720        of diff-index output
2721
2722diff-index line ($m hash)
2723{
2724        mode_a => first column of diff-index output, no leading ':',
2725        mode_b => second column of diff-index output,
2726        sha1_b => sha1sum of the final blob,
2727        chg => change type [MCRADT],
2728        file_a => original file name of a file (iff chg is 'C' or 'R')
2729        file_b => new/current file name of a file (any chg)
2730}
2731;
2732
2733# retval of read_url_paths{,_all}();
2734$l_map = {
2735        # repository root url
2736        'https://svn.musicpd.org' => {
2737                # repository path               # GIT_SVN_ID
2738                'mpd/trunk'             =>      'trunk',
2739                'mpd/tags/0.11.5'       =>      'tags/0.11.5',
2740        },
2741}
2742
2743Notes:
2744        I don't trust the each() function on unless I created %hash myself
2745        because the internal iterator may not have started at base.