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