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