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