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