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