beebe3d9545fe0de03c968ada149cd906c43808e
   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->get_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 || ! -e $self->db_path) &&
 941            ::verify_ref($self->refname.'^0')) {
 942                $self->rebuild;
 943        }
 944        $self;
 945}
 946
 947sub refname { "refs/remotes/$_[0]->{ref_id}" }
 948
 949sub svm_uuid {
 950        my ($self) = @_;
 951        return $self->{svm}->{uuid} if $self->svm;
 952        $self->ra;
 953        unless ($self->{svm}) {
 954                die "SVM UUID not cached, and reading remotely failed\n";
 955        }
 956        $self->{svm}->{uuid};
 957}
 958
 959sub svm {
 960        my ($self) = @_;
 961        return $self->{svm} if $self->{svm};
 962        my $svm;
 963        # see if we have it in our config, first:
 964        eval {
 965                my $section = "svn-remote.$self->{repo_id}";
 966                $svm = {
 967                  source => tmp_config('--get', "$section.svm-source"),
 968                  uuid => tmp_config('--get', "$section.svm-uuid"),
 969                }
 970        };
 971        $self->{svm} = $svm if ($svm && $svm->{source} && $svm->{uuid});
 972        $self->{svm};
 973}
 974
 975sub _set_svm_vars {
 976        my ($self, $ra) = @_;
 977
 978        return $ra if ($self->svm);
 979
 980        # nope, make sure we're connected to the repository root:
 981        if ($ra->{repos_root} ne $self->{url}) {
 982                $ra = Git::SVN::Ra->new($ra->{repos_root});
 983        }
 984        my $r = $ra->get_latest_revnum;
 985        my ($props) = ($ra->get_dir('', $r))[2];
 986        if (my $src = $props->{'svm:source'}) {
 987                my $section = "svn-remote.$self->{repo_id}";
 988
 989                # don't know what a '!' is there for, also the
 990                # username is of no interest
 991                $src =~ s{!$}{};
 992                $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
 993                tmp_config('--add', "$section.svm-source", $src);
 994
 995                my $uuid = $props->{'svm:uuid'};
 996                $uuid =~ m{^[0-9a-f\-]{30,}$}
 997                    or die "doesn't look right - svm:uuid is '$uuid'\n";
 998                tmp_config('--add', "$section.svm-uuid", $uuid);
 999
1000                $self->{svm} = { source => $src , uuid => $uuid };
1001        }
1002        if ($ra->{repos_root} ne $self->{url}) {
1003                $ra = Git::SVN::Ra->new($self->{url});
1004        }
1005        $ra;
1006}
1007
1008# this allows us to memoize our SVN::Ra UUID locally and avoid a
1009# remote lookup (useful for 'git svn log').
1010sub ra_uuid {
1011        my ($self) = @_;
1012        unless ($self->{ra_uuid}) {
1013                my $key = "svn-remote.$self->{repo_id}.uuid";
1014                my $uuid = eval { tmp_config('--get', $key) };
1015                if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1016                        $self->{ra_uuid} = $uuid;
1017                } else {
1018                        die "ra_uuid called without URL\n" unless $self->{url};
1019                        $self->{ra_uuid} = $self->ra->get_uuid;
1020                        tmp_config('--add', $key, $self->{ra_uuid});
1021                }
1022        }
1023        $self->{ra_uuid};
1024}
1025
1026sub ra {
1027        my ($self) = shift;
1028        my $ra = Git::SVN::Ra->new($self->{url});
1029        if ($self->use_svm_props && !$self->{svm}) {
1030                if ($self->no_metadata) {
1031                        die "Can't have both 'noMetadata' and ",
1032                            "'useSvmProps' options set!\n";
1033                }
1034                $ra = $self->_set_svm_vars($ra);
1035                $self->{-want_revprops} = 1;
1036        }
1037        $ra;
1038}
1039
1040sub rel_path {
1041        my ($self) = @_;
1042        my $repos_root = $self->ra->{repos_root};
1043        return $self->{path} if ($self->{url} eq $repos_root);
1044        die "BUG: rel_path failed! repos_root: $repos_root, Ra URL: ",
1045            $self->ra->{url}, " path: $self->{path},  URL: $self->{url}\n";
1046}
1047
1048sub traverse_ignore {
1049        my ($self, $fh, $path, $r) = @_;
1050        $path =~ s#^/+##g;
1051        my $ra = $self->ra;
1052        my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1053        my $p = $path;
1054        $p =~ s#^\Q$ra->{svn_path}\E/##;
1055        print $fh length $p ? "\n# $p\n" : "\n# /\n";
1056        if (my $s = $props->{'svn:ignore'}) {
1057                $s =~ s/[\r\n]+/\n/g;
1058                chomp $s;
1059                if (length $p == 0) {
1060                        $s =~ s#\n#\n/$p#g;
1061                        print $fh "/$s\n";
1062                } else {
1063                        $s =~ s#\n#\n/$p/#g;
1064                        print $fh "/$p/$s\n";
1065                }
1066        }
1067        foreach (sort keys %$dirent) {
1068                next if $dirent->{$_}->kind != $SVN::Node::dir;
1069                $self->traverse_ignore($fh, "$path/$_", $r);
1070        }
1071}
1072
1073sub last_rev { ($_[0]->last_rev_commit)[0] }
1074sub last_commit { ($_[0]->last_rev_commit)[1] }
1075
1076# returns the newest SVN revision number and newest commit SHA1
1077sub last_rev_commit {
1078        my ($self) = @_;
1079        if (defined $self->{last_rev} && defined $self->{last_commit}) {
1080                return ($self->{last_rev}, $self->{last_commit});
1081        }
1082        my $c = ::verify_ref($self->refname.'^0');
1083        if ($c && !$self->use_svm_props && !$self->no_metadata) {
1084                my $rev = (::cmt_metadata($c))[1];
1085                if (defined $rev) {
1086                        ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1087                        return ($rev, $c);
1088                }
1089        }
1090        my $db_path = $self->db_path;
1091        unless (-e $db_path) {
1092                ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1093                return (undef, undef);
1094        }
1095        my $offset = -41; # from tail
1096        my $rl;
1097        open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1098        sysseek($fh, $offset, 2); # don't care for errors
1099        sysread($fh, $rl, 41) == 41 or return (undef, undef);
1100        chomp $rl;
1101        while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1102                $offset -= 41;
1103                sysseek($fh, $offset, 2); # don't care for errors
1104                sysread($fh, $rl, 41) == 41 or return (undef, undef);
1105                chomp $rl;
1106        }
1107        if ($c && $c ne $rl) {
1108                die "$db_path and ", $self->refname,
1109                    " inconsistent!:\n$c != $rl\n";
1110        }
1111        my $rev = sysseek($fh, 0, 1) or croak $!;
1112        $rev =  ($rev - 41) / 41;
1113        close $fh or croak $!;
1114        ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1115        return ($rev, $c);
1116}
1117
1118sub get_fetch_range {
1119        my ($self, $min, $max) = @_;
1120        $max ||= $self->ra->get_latest_revnum;
1121        $min ||= $self->rev_db_max;
1122        (++$min, $max);
1123}
1124
1125sub tmp_config {
1126        my (@args) = @_;
1127        my $config = "$ENV{GIT_DIR}/svn/config";
1128        unless (-f $config) {
1129                open my $fh, '>', $config or
1130                    die "Can't open $config: $!\n";
1131                print $fh "; This file is used internally by git-svn\n" or
1132                      die "Couldn't write to $config: $!\n";
1133                print $fh "; You should not have to edit it\n" or
1134                      die "Couldn't write to $config: $!\n";
1135                close $fh or die "Couldn't close $config: $!\n";
1136        }
1137        my $old_config = $ENV{GIT_CONFIG};
1138        $ENV{GIT_CONFIG} = $config;
1139        $@ = undef;
1140        my @ret = eval { command('config', @args) };
1141        my $err = $@;
1142        if (defined $old_config) {
1143                $ENV{GIT_CONFIG} = $old_config;
1144        } else {
1145                delete $ENV{GIT_CONFIG};
1146        }
1147        die $err if $err;
1148        wantarray ? @ret : $ret[0];
1149}
1150
1151sub tmp_index_do {
1152        my ($self, $sub) = @_;
1153        my $old_index = $ENV{GIT_INDEX_FILE};
1154        $ENV{GIT_INDEX_FILE} = $self->{index};
1155        $@ = undef;
1156        my @ret = eval { &$sub };
1157        my $err = $@;
1158        if (defined $old_index) {
1159                $ENV{GIT_INDEX_FILE} = $old_index;
1160        } else {
1161                delete $ENV{GIT_INDEX_FILE};
1162        }
1163        die $err if $err;
1164        wantarray ? @ret : $ret[0];
1165}
1166
1167sub assert_index_clean {
1168        my ($self, $treeish) = @_;
1169
1170        $self->tmp_index_do(sub {
1171                command_noisy('read-tree', $treeish) unless -e $self->{index};
1172                my $x = command_oneline('write-tree');
1173                my ($y) = (command(qw/cat-file commit/, $treeish) =~
1174                           /^tree ($::sha1)/mo);
1175                if ($y ne $x) {
1176                        unlink $self->{index} or croak $!;
1177                        command_noisy('read-tree', $treeish);
1178                }
1179                $x = command_oneline('write-tree');
1180                if ($y ne $x) {
1181                        ::fatal "trees ($treeish) $y != $x\n",
1182                                "Something is seriously wrong...\n";
1183                }
1184        });
1185}
1186
1187sub get_commit_parents {
1188        my ($self, $log_entry) = @_;
1189        my (%seen, @ret, @tmp);
1190        # legacy support for 'set-tree'; this is only used by set_tree_cb:
1191        if (my $ip = $self->{inject_parents}) {
1192                if (my $commit = delete $ip->{$log_entry->{revision}}) {
1193                        push @tmp, $commit;
1194                }
1195        }
1196        if (my $cur = ::verify_ref($self->refname.'^0')) {
1197                push @tmp, $cur;
1198        }
1199        push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1200        while (my $p = shift @tmp) {
1201                next if $seen{$p};
1202                $seen{$p} = 1;
1203                push @ret, $p;
1204                # MAXPARENT is defined to 16 in commit-tree.c:
1205                last if @ret >= 16;
1206        }
1207        if (@tmp) {
1208                die "r$log_entry->{revision}: No room for parents:\n\t",
1209                    join("\n\t", @tmp), "\n";
1210        }
1211        @ret;
1212}
1213
1214sub full_url {
1215        my ($self) = @_;
1216        $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1217}
1218
1219sub do_git_commit {
1220        my ($self, $log_entry) = @_;
1221        my $lr = $self->last_rev;
1222        if (defined $lr && $lr >= $log_entry->{revision}) {
1223                die "Last fetched revision of ", $self->refname,
1224                    " was r$lr, but we are about to fetch: ",
1225                    "r$log_entry->{revision}!\n";
1226        }
1227        if (my $c = $self->rev_db_get($log_entry->{revision})) {
1228                croak "$log_entry->{revision} = $c already exists! ",
1229                      "Why are we refetching it?\n";
1230        }
1231        my $author = $log_entry->{author};
1232        my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
1233                           : ($author, "$author\@".$self->ra->get_uuid));
1234        $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1235        $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1236        $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1237
1238        my $tree = $log_entry->{tree};
1239        if (!defined $tree) {
1240                $tree = $self->tmp_index_do(sub {
1241                                            command_oneline('write-tree') });
1242        }
1243        die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1244
1245        my @exec = ('git-commit-tree', $tree);
1246        foreach ($self->get_commit_parents($log_entry)) {
1247                push @exec, '-p', $_;
1248        }
1249        defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1250                                                                   or croak $!;
1251        print $msg_fh $log_entry->{log} or croak $!;
1252        unless ($self->no_metadata) {
1253                print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1254                              or croak $!;
1255        }
1256        $msg_fh->flush == 0 or croak $!;
1257        close $msg_fh or croak $!;
1258        chomp(my $commit = do { local $/; <$out_fh> });
1259        close $out_fh or croak $!;
1260        waitpid $pid, 0;
1261        croak $? if $?;
1262        if ($commit !~ /^$::sha1$/o) {
1263                die "Failed to commit, invalid sha1: $commit\n";
1264        }
1265
1266        $self->rev_db_set($log_entry->{revision}, $commit, 1);
1267
1268        $self->{last_rev} = $log_entry->{revision};
1269        $self->{last_commit} = $commit;
1270        print "r$log_entry->{revision}";
1271        if (defined $log_entry->{svm_revision}) {
1272                 print " (\@$log_entry->{svm_revision})";
1273                 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1274                                   0, $self->svm_uuid);
1275        }
1276        print " = $commit ($self->{ref_id})\n";
1277        if (defined $_repack && (--$_repack_nr == 0)) {
1278                $_repack_nr = $_repack;
1279                # repack doesn't use any arguments with spaces in them, does it?
1280                print "Running git repack $_repack_flags ...\n";
1281                command_noisy('repack', split(/\s+/, $_repack_flags));
1282                print "Done repacking\n";
1283        }
1284        return $commit;
1285}
1286
1287sub match_paths {
1288        my ($self, $paths, $r) = @_;
1289        return 1 if $self->{path} eq '';
1290        if (my $path = $paths->{"/$self->{path}"}) {
1291                return ($path->{action} eq 'D') ? 0 : 1;
1292        }
1293        $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1294        if (grep /$self->{path_regex}/, keys %$paths) {
1295                return 1;
1296        }
1297        my $c = '';
1298        foreach (split m#/#, $self->{path}) {
1299                $c .= "/$_";
1300                next unless ($paths->{$c} &&
1301                             ($paths->{$c}->{action} =~ /^[AR]$/));
1302                if ($self->ra->check_path($self->{path}, $r) ==
1303                    $SVN::Node::dir) {
1304                        return 1;
1305                }
1306        }
1307        return 0;
1308}
1309
1310sub find_parent_branch {
1311        my ($self, $paths, $rev) = @_;
1312        return undef unless $self->follow_parent;
1313        unless (defined $paths) {
1314                my $err_handler = $SVN::Error::handler;
1315                $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1316                $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1317                                   $paths =
1318                                      Git::SVN::Ra::dup_changed_paths($_[0]) });
1319                $SVN::Error::handler = $err_handler;
1320        }
1321        return undef unless defined $paths;
1322
1323        # look for a parent from another branch:
1324        my @b_path_components = split m#/#, $self->rel_path;
1325        my @a_path_components;
1326        my $i;
1327        while (@b_path_components) {
1328                $i = $paths->{'/'.join('/', @b_path_components)};
1329                last if $i && defined $i->{copyfrom_path};
1330                unshift(@a_path_components, pop(@b_path_components));
1331        }
1332        return undef unless defined $i && defined $i->{copyfrom_path};
1333        my $branch_from = $i->{copyfrom_path};
1334        if (@a_path_components) {
1335                print STDERR "branch_from: $branch_from => ";
1336                $branch_from .= '/'.join('/', @a_path_components);
1337                print STDERR $branch_from, "\n";
1338        }
1339        my $r = $i->{copyfrom_rev};
1340        my $repos_root = $self->ra->{repos_root};
1341        my $url = $self->ra->{url};
1342        my $new_url = $repos_root . $branch_from;
1343        print STDERR  "Found possible branch point: ",
1344                      "$new_url => ", $self->full_url, ", $r\n";
1345        $branch_from =~ s#^/##;
1346        my $remotes = read_all_remotes();
1347        my $gs;
1348        foreach my $repo_id (keys %$remotes) {
1349                my $u = $remotes->{$repo_id}->{url} or next;
1350                next if $url ne $u;
1351                my $fetch = $remotes->{$repo_id}->{fetch};
1352                foreach (qw/branches tags/) {
1353                        resolve_local_globs($url, $fetch,
1354                                            $remotes->{$repo_id}->{$_});
1355                }
1356                foreach my $f (keys %$fetch) {
1357                        next if $f ne $branch_from;
1358                        $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1359                        last;
1360                }
1361                last if $gs;
1362        }
1363        unless ($gs) {
1364                my $ref_id = $self->{ref_id};
1365                $ref_id =~ s/\@\d+$//;
1366                $ref_id .= "\@$r";
1367                # just grow a tail if we're not unique enough :x
1368                $ref_id .= '-' while find_ref($ref_id);
1369                print STDERR "Initializing parent: $ref_id\n";
1370                $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1371        }
1372        my ($r0, $parent) = $gs->find_rev_before($r, 1);
1373        if (!defined $r0 || !defined $parent) {
1374                $gs->fetch(0, $r);
1375                ($r0, $parent) = $gs->last_rev_commit;
1376        }
1377        if (defined $r0 && defined $parent) {
1378                print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1379                $self->assert_index_clean($parent);
1380                my $ed;
1381                if ($self->ra->can_do_switch) {
1382                        print STDERR "Following parent with do_switch\n";
1383                        # do_switch works with svn/trunk >= r22312, but that
1384                        # is not included with SVN 1.4.3 (the latest version
1385                        # at the moment), so we can't rely on it
1386                        $self->{last_commit} = $parent;
1387                        $ed = SVN::Git::Fetcher->new($self);
1388                        $gs->ra->gs_do_switch($r0, $rev, $gs,
1389                                              $self->full_url, $ed)
1390                          or die "SVN connection failed somewhere...\n";
1391                } else {
1392                        print STDERR "Following parent with do_update\n";
1393                        $ed = SVN::Git::Fetcher->new($self);
1394                        $self->ra->gs_do_update($rev, $rev, $self, $ed)
1395                          or die "SVN connection failed somewhere...\n";
1396                }
1397                print STDERR "Successfully followed parent\n";
1398                return $self->make_log_entry($rev, [$parent], $ed);
1399        }
1400        return undef;
1401}
1402
1403sub do_fetch {
1404        my ($self, $paths, $rev) = @_;
1405        my $ed;
1406        my ($last_rev, @parents);
1407        if (my $lc = $self->last_commit) {
1408                # we can have a branch that was deleted, then re-added
1409                # under the same name but copied from another path, in
1410                # which case we'll have multiple parents (we don't
1411                # want to break the original ref, nor lose copypath info):
1412                if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1413                        push @{$log_entry->{parents}}, $lc;
1414                        return $log_entry;
1415                }
1416                $ed = SVN::Git::Fetcher->new($self);
1417                $last_rev = $self->{last_rev};
1418                $ed->{c} = $lc;
1419                @parents = ($lc);
1420        } else {
1421                $last_rev = $rev;
1422                if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1423                        return $log_entry;
1424                }
1425                $ed = SVN::Git::Fetcher->new($self);
1426        }
1427        unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1428                die "SVN connection failed somewhere...\n";
1429        }
1430        $self->make_log_entry($rev, \@parents, $ed);
1431}
1432
1433sub get_untracked {
1434        my ($self, $ed) = @_;
1435        my @out;
1436        my $h = $ed->{empty};
1437        foreach (sort keys %$h) {
1438                my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1439                push @out, "  $act: " . uri_encode($_);
1440                warn "W: $act: $_\n";
1441        }
1442        foreach my $t (qw/dir_prop file_prop/) {
1443                $h = $ed->{$t} or next;
1444                foreach my $path (sort keys %$h) {
1445                        my $ppath = $path eq '' ? '.' : $path;
1446                        foreach my $prop (sort keys %{$h->{$path}}) {
1447                                next if $SKIP_PROP{$prop};
1448                                my $v = $h->{$path}->{$prop};
1449                                my $t_ppath_prop = "$t: " .
1450                                                    uri_encode($ppath) . ' ' .
1451                                                    uri_encode($prop);
1452                                if (defined $v) {
1453                                        push @out, "  +$t_ppath_prop " .
1454                                                   uri_encode($v);
1455                                } else {
1456                                        push @out, "  -$t_ppath_prop";
1457                                }
1458                        }
1459                }
1460        }
1461        foreach my $t (qw/absent_file absent_directory/) {
1462                $h = $ed->{$t} or next;
1463                foreach my $parent (sort keys %$h) {
1464                        foreach my $path (sort @{$h->{$parent}}) {
1465                                push @out, "  $t: " .
1466                                           uri_encode("$parent/$path");
1467                                warn "W: $t: $parent/$path ",
1468                                     "Insufficient permissions?\n";
1469                        }
1470                }
1471        }
1472        \@out;
1473}
1474
1475sub parse_svn_date {
1476        my $date = shift || return '+0000 1970-01-01 00:00:00';
1477        my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1478                                            (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1479                                         croak "Unable to parse date: $date\n";
1480        "+0000 $Y-$m-$d $H:$M:$S";
1481}
1482
1483sub check_author {
1484        my ($author) = @_;
1485        if (!defined $author || length $author == 0) {
1486                $author = '(no author)';
1487        }
1488        if (defined $::_authors && ! defined $::users{$author}) {
1489                die "Author: $author not defined in $::_authors file\n";
1490        }
1491        $author;
1492}
1493
1494sub make_log_entry {
1495        my ($self, $rev, $parents, $ed) = @_;
1496        my $untracked = $self->get_untracked($ed);
1497
1498        open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1499        print $un "r$rev\n" or croak $!;
1500        print $un $_, "\n" foreach @$untracked;
1501        my %log_entry = ( parents => $parents || [], revision => $rev,
1502                          log => '');
1503
1504        my $headrev;
1505        my $logged = delete $self->{logged_rev_props};
1506        if (!$logged || $self->{-want_revprops}) {
1507                my $rp = $self->ra->rev_proplist($rev);
1508                foreach (sort keys %$rp) {
1509                        my $v = $rp->{$_};
1510                        if (/^svn:(author|date|log)$/) {
1511                                $log_entry{$1} = $v;
1512                        } elsif ($_ eq 'svm:headrev') {
1513                                $headrev = $v;
1514                        } else {
1515                                print $un "  rev_prop: ", uri_encode($_), ' ',
1516                                          uri_encode($v), "\n";
1517                        }
1518                }
1519        } else {
1520                map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1521        }
1522        close $un or croak $!;
1523
1524        $log_entry{date} = parse_svn_date($log_entry{date});
1525        $log_entry{author} = check_author($log_entry{author});
1526        $log_entry{log} .= "\n";
1527        if (defined $headrev && $self->use_svm_props) {
1528                my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1529                if ($uuid ne $self->{svm}->{uuid}) {
1530                        die "UUID mismatch on SVM path:\n",
1531                            "expected: $self->{svm}->{uuid}\n",
1532                            "     got: $uuid\n";
1533                }
1534                my $full_url = $self->{svm}->{source};
1535                $full_url .= "/$self->{path}" if length $self->{path};
1536                $log_entry{metadata} = "$full_url\@$r $uuid";
1537                $log_entry{svm_revision} = $r;
1538        } else {
1539                $log_entry{metadata} = $self->full_url . "\@$rev " .
1540                                       $self->ra->get_uuid;
1541        }
1542        \%log_entry;
1543}
1544
1545sub fetch {
1546        my ($self, $min_rev, $max_rev, @parents) = @_;
1547        my ($last_rev, $last_commit) = $self->last_rev_commit;
1548        my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1549        $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1550}
1551
1552sub set_tree_cb {
1553        my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1554        $self->{inject_parents} = { $rev => $tree };
1555        $self->fetch(undef, undef);
1556}
1557
1558sub set_tree {
1559        my ($self, $tree) = (shift, shift);
1560        my $log_entry = ::get_commit_entry($tree);
1561        unless ($self->{last_rev}) {
1562                fatal("Must have an existing revision to commit\n");
1563        }
1564        my %ed_opts = ( r => $self->{last_rev},
1565                        log => $log_entry->{log},
1566                        ra => $self->ra,
1567                        tree_a => $self->{last_commit},
1568                        tree_b => $tree,
1569                        editor_cb => sub {
1570                               $self->set_tree_cb($log_entry, $tree, @_) },
1571                        svn_path => $self->{path} );
1572        if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1573                print "No changes\nr$self->{last_rev} = $tree\n";
1574        }
1575}
1576
1577sub rebuild {
1578        my ($self) = @_;
1579        my $db_path = $self->db_path;
1580        if (-f $self->{db_root}) {
1581                rename $self->{db_root}, $db_path or die
1582                     "rename $self->{db_root} => $db_path failed: $!\n";
1583                my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1584                symlink $base, $self->{db_root} or die
1585                     "symlink $base => $self->{db_root} failed: $!\n";
1586                return;
1587        }
1588        print "Rebuilding $db_path ...\n";
1589        my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1590        my $latest;
1591        my $full_url = $self->full_url;
1592        my $svn_uuid;
1593        while (<$rev_list>) {
1594                chomp;
1595                my $c = $_;
1596                die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1597                my ($url, $rev, $uuid) = ::cmt_metadata($c);
1598
1599                # ignore merges (from set-tree)
1600                next if (!defined $rev || !$uuid);
1601
1602                # if we merged or otherwise started elsewhere, this is
1603                # how we break out of it
1604                if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1605                    ($full_url && $url && ($url ne $full_url))) {
1606                        next;
1607                }
1608                $latest ||= $rev;
1609                $svn_uuid ||= $uuid;
1610
1611                $self->rev_db_set($rev, $c);
1612                print "r$rev = $c\n";
1613        }
1614        command_close_pipe($rev_list, $ctx);
1615        print "Done rebuilding $db_path\n";
1616}
1617
1618# rev_db:
1619# Tie::File seems to be prone to offset errors if revisions get sparse,
1620# it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1621# one of my favorite modules is out :<  Next up would be one of the DBM
1622# modules, but I'm not sure which is most portable...  So I'll just
1623# go with something that's plain-text, but still capable of
1624# being randomly accessed.  So here's my ultra-simple fixed-width
1625# database.  All records are 40 characters + "\n", so it's easy to seek
1626# to a revision: (41 * rev) is the byte offset.
1627# A record of 40 0s denotes an empty revision.
1628# And yes, it's still pretty fast (faster than Tie::File).
1629# These files are disposable unless noMetadata or useSvmProps is set
1630
1631sub _rev_db_set {
1632        my ($fh, $rev, $commit) = @_;
1633        my $offset = $rev * 41;
1634        # assume that append is the common case:
1635        seek $fh, 0, 2 or croak $!;
1636        my $pos = tell $fh;
1637        if ($pos < $offset) {
1638                for (1 .. (($offset - $pos) / 41)) {
1639                        print $fh (('0' x 40),"\n") or croak $!;
1640                }
1641        }
1642        seek $fh, $offset, 0 or croak $!;
1643        print $fh $commit,"\n" or croak $!;
1644}
1645
1646sub mkfile {
1647        my ($path) = @_;
1648        unless (-e $path) {
1649                my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
1650                mkpath([$dir]) unless -d $dir;
1651                open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
1652                close $fh or die "Couldn't close (create) $path: $!\n";
1653        }
1654}
1655
1656sub rev_db_set {
1657        my ($self, $rev, $commit, $update_ref, $uuid) = @_;
1658        length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
1659        my $db = $self->db_path($uuid);
1660        my $db_lock = "$db.lock";
1661        my $sig;
1662        if ($update_ref) {
1663                $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1664                            $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1665        }
1666        mkfile($db);
1667
1668        $LOCKFILES{$db_lock} = 1;
1669        my $sync;
1670        # both of these options make our .rev_db file very, very important
1671        # and we can't afford to lose it because rebuild() won't work
1672        if ($self->use_svm_props || $self->no_metadata) {
1673                $sync = 1;
1674                copy($db, $db_lock) or die "rev_db_set(@_): ",
1675                                           "Failed to copy: ",
1676                                           "$db => $db_lock ($!)\n";
1677        } else {
1678                rename $db, $db_lock or die "rev_db_set(@_): ",
1679                                            "Failed to rename: ",
1680                                            "$db => $db_lock ($!)\n";
1681        }
1682        open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
1683        _rev_db_set($fh, $rev, $commit);
1684        if ($sync) {
1685                $fh->flush or die "Couldn't flush $db_lock: $!\n";
1686                $fh->sync or die "Couldn't sync $db_lock: $!\n";
1687        }
1688        close $fh or croak $!;
1689        if ($update_ref) {
1690                command_noisy('update-ref', '-m', "r$rev",
1691                              $self->refname, $commit);
1692        }
1693        rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1694                                    "$db_lock => $db ($!)\n";
1695        delete $LOCKFILES{$db_lock};
1696        if ($update_ref) {
1697                $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1698                            $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1699                kill $sig, $$ if defined $sig;
1700        }
1701}
1702
1703sub rev_db_max {
1704        my ($self) = @_;
1705        my $db_path = $self->db_path;
1706        my @stat = stat $db_path or return 0;
1707        ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
1708        my $max = $stat[7] / 41;
1709        (($max > 0) ? $max - 1 : 0);
1710}
1711
1712sub rev_db_get {
1713        my ($self, $rev, $uuid) = @_;
1714        my $ret;
1715        my $offset = $rev * 41;
1716        my $db_path = $self->db_path($uuid);
1717        return undef unless -e $db_path;
1718        open my $fh, '<', $db_path or croak $!;
1719        if (sysseek($fh, $offset, 0) == $offset) {
1720                my $read = sysread($fh, $ret, 40);
1721                $ret = undef if ($read != 40 || $ret eq ('0'x40));
1722        }
1723        close $fh or croak $!;
1724        $ret;
1725}
1726
1727sub find_rev_before {
1728        my ($self, $rev, $eq_ok) = @_;
1729        --$rev unless $eq_ok;
1730        while ($rev > 0) {
1731                if (my $c = $self->rev_db_get($rev)) {
1732                        return ($rev, $c);
1733                }
1734                --$rev;
1735        }
1736        return (undef, undef);
1737}
1738
1739sub _new {
1740        my ($class, $repo_id, $ref_id, $path) = @_;
1741        unless (defined $repo_id && length $repo_id) {
1742                $repo_id = $Git::SVN::default_repo_id;
1743        }
1744        unless (defined $ref_id && length $ref_id) {
1745                $_[2] = $ref_id = $Git::SVN::default_ref_id;
1746        }
1747        $_[1] = $repo_id = sanitize_remote_name($repo_id);
1748        my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1749        $_[3] = $path = '' unless (defined $path);
1750        mkpath([$dir]);
1751        bless {
1752                ref_id => $ref_id, dir => $dir, index => "$dir/index",
1753                path => $path, config => "$ENV{GIT_DIR}/svn/config",
1754                db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
1755}
1756
1757sub db_path {
1758        my ($self, $uuid) = @_;
1759        $uuid ||= $self->ra_uuid;
1760        "$self->{db_root}.$uuid";
1761}
1762
1763sub uri_encode {
1764        my ($f) = @_;
1765        $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1766        $f
1767}
1768
1769package Git::SVN::Prompt;
1770use strict;
1771use warnings;
1772require SVN::Core;
1773use vars qw/$_no_auth_cache $_username/;
1774
1775sub simple {
1776        my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1777        $may_save = undef if $_no_auth_cache;
1778        $default_username = $_username if defined $_username;
1779        if (defined $default_username && length $default_username) {
1780                if (defined $realm && length $realm) {
1781                        print STDERR "Authentication realm: $realm\n";
1782                        STDERR->flush;
1783                }
1784                $cred->username($default_username);
1785        } else {
1786                username($cred, $realm, $may_save, $pool);
1787        }
1788        $cred->password(_read_password("Password for '" .
1789                                       $cred->username . "': ", $realm));
1790        $cred->may_save($may_save);
1791        $SVN::_Core::SVN_NO_ERROR;
1792}
1793
1794sub ssl_server_trust {
1795        my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1796        $may_save = undef if $_no_auth_cache;
1797        print STDERR "Error validating server certificate for '$realm':\n";
1798        if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1799                print STDERR " - The certificate is not issued by a trusted ",
1800                      "authority. Use the\n",
1801                      "   fingerprint to validate the certificate manually!\n";
1802        }
1803        if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1804                print STDERR " - The certificate hostname does not match.\n";
1805        }
1806        if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1807                print STDERR " - The certificate is not yet valid.\n";
1808        }
1809        if ($failures & $SVN::Auth::SSL::EXPIRED) {
1810                print STDERR " - The certificate has expired.\n";
1811        }
1812        if ($failures & $SVN::Auth::SSL::OTHER) {
1813                print STDERR " - The certificate has an unknown error.\n";
1814        }
1815        printf STDERR
1816                "Certificate information:\n".
1817                " - Hostname: %s\n".
1818                " - Valid: from %s until %s\n".
1819                " - Issuer: %s\n".
1820                " - Fingerprint: %s\n",
1821                map $cert_info->$_, qw(hostname valid_from valid_until
1822                                       issuer_dname fingerprint);
1823        my $choice;
1824prompt:
1825        print STDERR $may_save ?
1826              "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1827              "(R)eject or accept (t)emporarily? ";
1828        STDERR->flush;
1829        $choice = lc(substr(<STDIN> || 'R', 0, 1));
1830        if ($choice =~ /^t$/i) {
1831                $cred->may_save(undef);
1832        } elsif ($choice =~ /^r$/i) {
1833                return -1;
1834        } elsif ($may_save && $choice =~ /^p$/i) {
1835                $cred->may_save($may_save);
1836        } else {
1837                goto prompt;
1838        }
1839        $cred->accepted_failures($failures);
1840        $SVN::_Core::SVN_NO_ERROR;
1841}
1842
1843sub ssl_client_cert {
1844        my ($cred, $realm, $may_save, $pool) = @_;
1845        $may_save = undef if $_no_auth_cache;
1846        print STDERR "Client certificate filename: ";
1847        STDERR->flush;
1848        chomp(my $filename = <STDIN>);
1849        $cred->cert_file($filename);
1850        $cred->may_save($may_save);
1851        $SVN::_Core::SVN_NO_ERROR;
1852}
1853
1854sub ssl_client_cert_pw {
1855        my ($cred, $realm, $may_save, $pool) = @_;
1856        $may_save = undef if $_no_auth_cache;
1857        $cred->password(_read_password("Password: ", $realm));
1858        $cred->may_save($may_save);
1859        $SVN::_Core::SVN_NO_ERROR;
1860}
1861
1862sub username {
1863        my ($cred, $realm, $may_save, $pool) = @_;
1864        $may_save = undef if $_no_auth_cache;
1865        if (defined $realm && length $realm) {
1866                print STDERR "Authentication realm: $realm\n";
1867        }
1868        my $username;
1869        if (defined $_username) {
1870                $username = $_username;
1871        } else {
1872                print STDERR "Username: ";
1873                STDERR->flush;
1874                chomp($username = <STDIN>);
1875        }
1876        $cred->username($username);
1877        $cred->may_save($may_save);
1878        $SVN::_Core::SVN_NO_ERROR;
1879}
1880
1881sub _read_password {
1882        my ($prompt, $realm) = @_;
1883        print STDERR $prompt;
1884        STDERR->flush;
1885        require Term::ReadKey;
1886        Term::ReadKey::ReadMode('noecho');
1887        my $password = '';
1888        while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1889                last if $key =~ /[\012\015]/; # \n\r
1890                $password .= $key;
1891        }
1892        Term::ReadKey::ReadMode('restore');
1893        print STDERR "\n";
1894        STDERR->flush;
1895        $password;
1896}
1897
1898package main;
1899
1900{
1901        my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1902                                $SVN::Node::dir.$SVN::Node::unknown.
1903                                $SVN::Node::none.$SVN::Node::file.
1904                                $SVN::Node::dir.$SVN::Node::unknown.
1905                                $SVN::Auth::SSL::CNMISMATCH.
1906                                $SVN::Auth::SSL::NOTYETVALID.
1907                                $SVN::Auth::SSL::EXPIRED.
1908                                $SVN::Auth::SSL::UNKNOWNCA.
1909                                $SVN::Auth::SSL::OTHER;
1910}
1911
1912package SVN::Git::Fetcher;
1913use vars qw/@ISA/;
1914use strict;
1915use warnings;
1916use Carp qw/croak/;
1917use IO::File qw//;
1918use Digest::MD5;
1919
1920# file baton members: path, mode_a, mode_b, pool, fh, blob, base
1921sub new {
1922        my ($class, $git_svn) = @_;
1923        my $self = SVN::Delta::Editor->new;
1924        bless $self, $class;
1925        $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1926        $self->{empty} = {};
1927        $self->{dir_prop} = {};
1928        $self->{file_prop} = {};
1929        $self->{absent_dir} = {};
1930        $self->{absent_file} = {};
1931        $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
1932        $self;
1933}
1934
1935sub set_path_strip {
1936        my ($self, $path) = @_;
1937        $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
1938}
1939
1940sub open_root {
1941        { path => '' };
1942}
1943
1944sub open_directory {
1945        my ($self, $path, $pb, $rev) = @_;
1946        { path => $path };
1947}
1948
1949sub git_path {
1950        my ($self, $path) = @_;
1951        if ($self->{path_strip}) {
1952                $path =~ s!$self->{path_strip}!! or
1953                  die "Failed to strip path '$path' ($self->{path_strip})\n";
1954        }
1955        $path;
1956}
1957
1958sub delete_entry {
1959        my ($self, $path, $rev, $pb) = @_;
1960
1961        my $gpath = $self->git_path($path);
1962        return undef if ($gpath eq '');
1963
1964        # remove entire directories.
1965        if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1966                my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1967                                                     -r --name-only -z/,
1968                                                     $self->{c}, '--', $gpath);
1969                local $/ = "\0";
1970                while (<$ls>) {
1971                        chomp;
1972                        $self->{gii}->remove($_);
1973                        print "\tD\t$_\n" unless $::_q;
1974                }
1975                print "\tD\t$gpath/\n" unless $::_q;
1976                command_close_pipe($ls, $ctx);
1977                $self->{empty}->{$path} = 0
1978        } else {
1979                $self->{gii}->remove($gpath);
1980                print "\tD\t$gpath\n" unless $::_q;
1981        }
1982        undef;
1983}
1984
1985sub open_file {
1986        my ($self, $path, $pb, $rev) = @_;
1987        my $gpath = $self->git_path($path);
1988        my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1989                             =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1990        unless (defined $mode && defined $blob) {
1991                die "$path was not found in commit $self->{c} (r$rev)\n";
1992        }
1993        { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1994          pool => SVN::Pool->new, action => 'M' };
1995}
1996
1997sub add_file {
1998        my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1999        my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2000        delete $self->{empty}->{$dir};
2001        { path => $path, mode_a => 100644, mode_b => 100644,
2002          pool => SVN::Pool->new, action => 'A' };
2003}
2004
2005sub add_directory {
2006        my ($self, $path, $cp_path, $cp_rev) = @_;
2007        my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2008        delete $self->{empty}->{$dir};
2009        $self->{empty}->{$path} = 1;
2010        { path => $path };
2011}
2012
2013sub change_dir_prop {
2014        my ($self, $db, $prop, $value) = @_;
2015        $self->{dir_prop}->{$db->{path}} ||= {};
2016        $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2017        undef;
2018}
2019
2020sub absent_directory {
2021        my ($self, $path, $pb) = @_;
2022        $self->{absent_dir}->{$pb->{path}} ||= [];
2023        push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2024        undef;
2025}
2026
2027sub absent_file {
2028        my ($self, $path, $pb) = @_;
2029        $self->{absent_file}->{$pb->{path}} ||= [];
2030        push @{$self->{absent_file}->{$pb->{path}}}, $path;
2031        undef;
2032}
2033
2034sub change_file_prop {
2035        my ($self, $fb, $prop, $value) = @_;
2036        if ($prop eq 'svn:executable') {
2037                if ($fb->{mode_b} != 120000) {
2038                        $fb->{mode_b} = defined $value ? 100755 : 100644;
2039                }
2040        } elsif ($prop eq 'svn:special') {
2041                $fb->{mode_b} = defined $value ? 120000 : 100644;
2042        } else {
2043                $self->{file_prop}->{$fb->{path}} ||= {};
2044                $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2045        }
2046        undef;
2047}
2048
2049sub apply_textdelta {
2050        my ($self, $fb, $exp) = @_;
2051        my $fh = IO::File->new_tmpfile;
2052        $fh->autoflush(1);
2053        # $fh gets auto-closed() by SVN::TxDelta::apply(),
2054        # (but $base does not,) so dup() it for reading in close_file
2055        open my $dup, '<&', $fh or croak $!;
2056        my $base = IO::File->new_tmpfile;
2057        $base->autoflush(1);
2058        if ($fb->{blob}) {
2059                defined (my $pid = fork) or croak $!;
2060                if (!$pid) {
2061                        open STDOUT, '>&', $base or croak $!;
2062                        print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2063                        exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2064                }
2065                waitpid $pid, 0;
2066                croak $? if $?;
2067
2068                if (defined $exp) {
2069                        seek $base, 0, 0 or croak $!;
2070                        my $md5 = Digest::MD5->new;
2071                        $md5->addfile($base);
2072                        my $got = $md5->hexdigest;
2073                        die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2074                            "expected: $exp\n",
2075                            "     got: $got\n" if ($got ne $exp);
2076                }
2077        }
2078        seek $base, 0, 0 or croak $!;
2079        $fb->{fh} = $dup;
2080        $fb->{base} = $base;
2081        [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2082}
2083
2084sub close_file {
2085        my ($self, $fb, $exp) = @_;
2086        my $hash;
2087        my $path = $self->git_path($fb->{path});
2088        if (my $fh = $fb->{fh}) {
2089                seek($fh, 0, 0) or croak $!;
2090                my $md5 = Digest::MD5->new;
2091                $md5->addfile($fh);
2092                my $got = $md5->hexdigest;
2093                die "Checksum mismatch: $path\n",
2094                    "expected: $exp\n    got: $got\n" if ($got ne $exp);
2095                seek($fh, 0, 0) or croak $!;
2096                if ($fb->{mode_b} == 120000) {
2097                        read($fh, my $buf, 5) == 5 or croak $!;
2098                        $buf eq 'link ' or die "$path has mode 120000",
2099                                               "but is not a link\n";
2100                }
2101                defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2102                if (!$pid) {
2103                        open STDIN, '<&', $fh or croak $!;
2104                        exec qw/git-hash-object -w --stdin/ or croak $!;
2105                }
2106                chomp($hash = do { local $/; <$out> });
2107                close $out or croak $!;
2108                close $fh or croak $!;
2109                $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2110                close $fb->{base} or croak $!;
2111        } else {
2112                $hash = $fb->{blob} or die "no blob information\n";
2113        }
2114        $fb->{pool}->clear;
2115        $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2116        print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2117        undef;
2118}
2119
2120sub abort_edit {
2121        my $self = shift;
2122        $self->{nr} = $self->{gii}->{nr};
2123        delete $self->{gii};
2124        $self->SUPER::abort_edit(@_);
2125}
2126
2127sub close_edit {
2128        my $self = shift;
2129        $self->{git_commit_ok} = 1;
2130        $self->{nr} = $self->{gii}->{nr};
2131        delete $self->{gii};
2132        $self->SUPER::close_edit(@_);
2133}
2134
2135package SVN::Git::Editor;
2136use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2137use strict;
2138use warnings;
2139use Carp qw/croak/;
2140use IO::File;
2141use Digest::MD5;
2142
2143sub new {
2144        my ($class, $opts) = @_;
2145        foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2146                die "$_ required!\n" unless (defined $opts->{$_});
2147        }
2148
2149        my $pool = SVN::Pool->new;
2150        my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2151        my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2152                                     $opts->{r}, $mods);
2153
2154        # $opts->{ra} functions should not be used after this:
2155        my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
2156                                                $opts->{editor_cb}, $pool);
2157        my $self = SVN::Delta::Editor->new(@ce, $pool);
2158        bless $self, $class;
2159        foreach (qw/svn_path r tree_a tree_b/) {
2160                $self->{$_} = $opts->{$_};
2161        }
2162        $self->{url} = $opts->{ra}->{url};
2163        $self->{mods} = $mods;
2164        $self->{types} = $types;
2165        $self->{pool} = $pool;
2166        $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2167        $self->{rm} = { };
2168        $self->{path_prefix} = length $self->{svn_path} ?
2169                               "$self->{svn_path}/" : '';
2170        return $self;
2171}
2172
2173sub generate_diff {
2174        my ($tree_a, $tree_b) = @_;
2175        my @diff_tree = qw(diff-tree -z -r);
2176        if ($_cp_similarity) {
2177                push @diff_tree, "-C$_cp_similarity";
2178        } else {
2179                push @diff_tree, '-C';
2180        }
2181        push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2182        push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2183        push @diff_tree, $tree_a, $tree_b;
2184        my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2185        local $/ = "\0";
2186        my $state = 'meta';
2187        my @mods;
2188        while (<$diff_fh>) {
2189                chomp $_; # this gets rid of the trailing "\0"
2190                if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2191                                        $::sha1\s($::sha1)\s
2192                                        ([MTCRAD])\d*$/xo) {
2193                        push @mods, {   mode_a => $1, mode_b => $2,
2194                                        sha1_b => $3, chg => $4 };
2195                        if ($4 =~ /^(?:C|R)$/) {
2196                                $state = 'file_a';
2197                        } else {
2198                                $state = 'file_b';
2199                        }
2200                } elsif ($state eq 'file_a') {
2201                        my $x = $mods[$#mods] or croak "Empty array\n";
2202                        if ($x->{chg} !~ /^(?:C|R)$/) {
2203                                croak "Error parsing $_, $x->{chg}\n";
2204                        }
2205                        $x->{file_a} = $_;
2206                        $state = 'file_b';
2207                } elsif ($state eq 'file_b') {
2208                        my $x = $mods[$#mods] or croak "Empty array\n";
2209                        if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2210                                croak "Error parsing $_, $x->{chg}\n";
2211                        }
2212                        if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2213                                croak "Error parsing $_, $x->{chg}\n";
2214                        }
2215                        $x->{file_b} = $_;
2216                        $state = 'meta';
2217                } else {
2218                        croak "Error parsing $_\n";
2219                }
2220        }
2221        command_close_pipe($diff_fh, $ctx);
2222        \@mods;
2223}
2224
2225sub check_diff_paths {
2226        my ($ra, $pfx, $rev, $mods) = @_;
2227        my %types;
2228        $pfx .= '/' if length $pfx;
2229
2230        sub type_diff_paths {
2231                my ($ra, $types, $path, $rev) = @_;
2232                my @p = split m#/+#, $path;
2233                my $c = shift @p;
2234                unless (defined $types->{$c}) {
2235                        $types->{$c} = $ra->check_path($c, $rev);
2236                }
2237                while (@p) {
2238                        $c .= '/' . shift @p;
2239                        next if defined $types->{$c};
2240                        $types->{$c} = $ra->check_path($c, $rev);
2241                }
2242        }
2243
2244        foreach my $m (@$mods) {
2245                foreach my $f (qw/file_a file_b/) {
2246                        next unless defined $m->{$f};
2247                        my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2248                        if (length $pfx.$dir && ! defined $types{$dir}) {
2249                                type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2250                        }
2251                }
2252        }
2253        \%types;
2254}
2255
2256sub split_path {
2257        return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2258}
2259
2260sub repo_path {
2261        my ($self, $path) = @_;
2262        $self->{path_prefix}.(defined $path ? $path : '');
2263}
2264
2265sub url_path {
2266        my ($self, $path) = @_;
2267        $self->{url} . '/' . $self->repo_path($path);
2268}
2269
2270sub rmdirs {
2271        my ($self) = @_;
2272        my $rm = $self->{rm};
2273        delete $rm->{''}; # we never delete the url we're tracking
2274        return unless %$rm;
2275
2276        foreach (keys %$rm) {
2277                my @d = split m#/#, $_;
2278                my $c = shift @d;
2279                $rm->{$c} = 1;
2280                while (@d) {
2281                        $c .= '/' . shift @d;
2282                        $rm->{$c} = 1;
2283                }
2284        }
2285        delete $rm->{$self->{svn_path}};
2286        delete $rm->{''}; # we never delete the url we're tracking
2287        return unless %$rm;
2288
2289        my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2290                                             $self->{tree_b});
2291        local $/ = "\0";
2292        while (<$fh>) {
2293                chomp;
2294                my @dn = split m#/#, $_;
2295                while (pop @dn) {
2296                        delete $rm->{join '/', @dn};
2297                }
2298                unless (%$rm) {
2299                        close $fh;
2300                        return;
2301                }
2302        }
2303        command_close_pipe($fh, $ctx);
2304
2305        my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2306        foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2307                $self->close_directory($bat->{$d}, $p);
2308                my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2309                print "\tD+\t$d/\n" unless $::_q;
2310                $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2311                delete $bat->{$d};
2312        }
2313}
2314
2315sub open_or_add_dir {
2316        my ($self, $full_path, $baton) = @_;
2317        my $t = $self->{types}->{$full_path};
2318        if (!defined $t) {
2319                die "$full_path not known in r$self->{r} or we have a bug!\n";
2320        }
2321        if ($t == $SVN::Node::none) {
2322                return $self->add_directory($full_path, $baton,
2323                                                undef, -1, $self->{pool});
2324        } elsif ($t == $SVN::Node::dir) {
2325                return $self->open_directory($full_path, $baton,
2326                                                $self->{r}, $self->{pool});
2327        }
2328        print STDERR "$full_path already exists in repository at ",
2329                "r$self->{r} and it is not a directory (",
2330                ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2331        exit 1;
2332}
2333
2334sub ensure_path {
2335        my ($self, $path) = @_;
2336        my $bat = $self->{bat};
2337        my $repo_path = $self->repo_path($path);
2338        return $bat->{''} unless (length $repo_path);
2339        my @p = split m#/+#, $repo_path;
2340        my $c = shift @p;
2341        $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2342        while (@p) {
2343                my $c0 = $c;
2344                $c .= '/' . shift @p;
2345                $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2346        }
2347        return $bat->{$c};
2348}
2349
2350sub A {
2351        my ($self, $m) = @_;
2352        my ($dir, $file) = split_path($m->{file_b});
2353        my $pbat = $self->ensure_path($dir);
2354        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2355                                        undef, -1);
2356        print "\tA\t$m->{file_b}\n" unless $::_q;
2357        $self->chg_file($fbat, $m);
2358        $self->close_file($fbat,undef,$self->{pool});
2359}
2360
2361sub C {
2362        my ($self, $m) = @_;
2363        my ($dir, $file) = split_path($m->{file_b});
2364        my $pbat = $self->ensure_path($dir);
2365        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2366                                $self->url_path($m->{file_a}), $self->{r});
2367        print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2368        $self->chg_file($fbat, $m);
2369        $self->close_file($fbat,undef,$self->{pool});
2370}
2371
2372sub delete_entry {
2373        my ($self, $path, $pbat) = @_;
2374        my $rpath = $self->repo_path($path);
2375        my ($dir, $file) = split_path($rpath);
2376        $self->{rm}->{$dir} = 1;
2377        $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2378}
2379
2380sub R {
2381        my ($self, $m) = @_;
2382        my ($dir, $file) = split_path($m->{file_b});
2383        my $pbat = $self->ensure_path($dir);
2384        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2385                                $self->url_path($m->{file_a}), $self->{r});
2386        print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2387        $self->chg_file($fbat, $m);
2388        $self->close_file($fbat,undef,$self->{pool});
2389
2390        ($dir, $file) = split_path($m->{file_a});
2391        $pbat = $self->ensure_path($dir);
2392        $self->delete_entry($m->{file_a}, $pbat);
2393}
2394
2395sub M {
2396        my ($self, $m) = @_;
2397        my ($dir, $file) = split_path($m->{file_b});
2398        my $pbat = $self->ensure_path($dir);
2399        my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2400                                $pbat,$self->{r},$self->{pool});
2401        print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2402        $self->chg_file($fbat, $m);
2403        $self->close_file($fbat,undef,$self->{pool});
2404}
2405
2406sub T { shift->M(@_) }
2407
2408sub change_file_prop {
2409        my ($self, $fbat, $pname, $pval) = @_;
2410        $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2411}
2412
2413sub chg_file {
2414        my ($self, $fbat, $m) = @_;
2415        if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2416                $self->change_file_prop($fbat,'svn:executable','*');
2417        } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2418                $self->change_file_prop($fbat,'svn:executable',undef);
2419        }
2420        my $fh = IO::File->new_tmpfile or croak $!;
2421        if ($m->{mode_b} =~ /^120/) {
2422                print $fh 'link ' or croak $!;
2423                $self->change_file_prop($fbat,'svn:special','*');
2424        } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2425                $self->change_file_prop($fbat,'svn:special',undef);
2426        }
2427        defined(my $pid = fork) or croak $!;
2428        if (!$pid) {
2429                open STDOUT, '>&', $fh or croak $!;
2430                exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2431        }
2432        waitpid $pid, 0;
2433        croak $? if $?;
2434        $fh->flush == 0 or croak $!;
2435        seek $fh, 0, 0 or croak $!;
2436
2437        my $md5 = Digest::MD5->new;
2438        $md5->addfile($fh) or croak $!;
2439        seek $fh, 0, 0 or croak $!;
2440
2441        my $exp = $md5->hexdigest;
2442        my $pool = SVN::Pool->new;
2443        my $atd = $self->apply_textdelta($fbat, undef, $pool);
2444        my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2445        die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2446        $pool->clear;
2447
2448        close $fh or croak $!;
2449}
2450
2451sub D {
2452        my ($self, $m) = @_;
2453        my ($dir, $file) = split_path($m->{file_b});
2454        my $pbat = $self->ensure_path($dir);
2455        print "\tD\t$m->{file_b}\n" unless $::_q;
2456        $self->delete_entry($m->{file_b}, $pbat);
2457}
2458
2459sub close_edit {
2460        my ($self) = @_;
2461        my ($p,$bat) = ($self->{pool}, $self->{bat});
2462        foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2463                $self->close_directory($bat->{$_}, $p);
2464        }
2465        $self->SUPER::close_edit($p);
2466        $p->clear;
2467}
2468
2469sub abort_edit {
2470        my ($self) = @_;
2471        $self->SUPER::abort_edit($self->{pool});
2472}
2473
2474sub DESTROY {
2475        my $self = shift;
2476        $self->SUPER::DESTROY(@_);
2477        $self->{pool}->clear;
2478}
2479
2480# this drives the editor
2481sub apply_diff {
2482        my ($self) = @_;
2483        my $mods = $self->{mods};
2484        my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2485        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2486                my $f = $m->{chg};
2487                if (defined $o{$f}) {
2488                        $self->$f($m);
2489                } else {
2490                        fatal("Invalid change type: $f\n");
2491                }
2492        }
2493        $self->rmdirs if $_rmdir;
2494        if (@$mods == 0) {
2495                $self->abort_edit;
2496        } else {
2497                $self->close_edit;
2498        }
2499        return scalar @$mods;
2500}
2501
2502package Git::SVN::Ra;
2503use vars qw/@ISA $config_dir/;
2504use strict;
2505use warnings;
2506my ($can_do_switch);
2507my $RA;
2508
2509BEGIN {
2510        # enforce temporary pool usage for some simple functions
2511        my $e;
2512        foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
2513                $e .= "sub $_ {
2514                        my \$self = shift;
2515                        my \$pool = SVN::Pool->new;
2516                        my \@ret = \$self->SUPER::$_(\@_,\$pool);
2517                        \$pool->clear;
2518                        wantarray ? \@ret : \$ret[0]; }\n";
2519        }
2520
2521        # get_dir needs $pool held in cache for dirents to work,
2522        # check_path is cacheable and rev_proplist is close enough
2523        # for our purposes.
2524        foreach (qw/check_path get_dir rev_proplist/) {
2525                $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2526                        my \$self = shift;
2527                        my \$r = pop;
2528                        my \$k = join(\"\\0\", \@_);
2529                        if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2530                                return wantarray ? \@\$x : \$x->[0];
2531                        }
2532                        my \$pool = SVN::Pool->new;
2533                        my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2534                        if (\$r != \$${_}_rev) {
2535                                \%${_}_cache = ( pool => [] );
2536                                \$${_}_rev = \$r;
2537                        }
2538                        \$${_}_cache{\$r}->{\$k} = \\\@ret;
2539                        push \@{\$${_}_cache{pool}}, \$pool;
2540                        wantarray ? \@ret : \$ret[0]; }\n";
2541        }
2542        $e .= "\n1;";
2543        eval $e or die $@;
2544}
2545
2546sub new {
2547        my ($class, $url) = @_;
2548        $url =~ s!/+$!!;
2549        return $RA if ($RA && $RA->{url} eq $url);
2550
2551        SVN::_Core::svn_config_ensure($config_dir, undef);
2552        my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2553            SVN::Client::get_simple_provider(),
2554            SVN::Client::get_ssl_server_trust_file_provider(),
2555            SVN::Client::get_simple_prompt_provider(
2556              \&Git::SVN::Prompt::simple, 2),
2557            SVN::Client::get_ssl_client_cert_prompt_provider(
2558              \&Git::SVN::Prompt::ssl_client_cert, 2),
2559            SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2560              \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2561            SVN::Client::get_username_provider(),
2562            SVN::Client::get_ssl_server_trust_prompt_provider(
2563              \&Git::SVN::Prompt::ssl_server_trust),
2564            SVN::Client::get_username_prompt_provider(
2565              \&Git::SVN::Prompt::username, 2),
2566          ]);
2567        my $config = SVN::Core::config_get_config($config_dir);
2568        my $self = SVN::Ra->new(url => $url, auth => $baton,
2569                              config => $config,
2570                              pool => SVN::Pool->new,
2571                              auth_provider_callbacks => $callbacks);
2572        $self->{svn_path} = $url;
2573        $self->{repos_root} = $self->get_repos_root;
2574        $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2575        $RA = bless $self, $class;
2576}
2577
2578sub DESTROY {
2579        # do not call the real DESTROY since we store ourselves in $RA
2580}
2581
2582sub get_log {
2583        my ($self, @args) = @_;
2584        my $pool = SVN::Pool->new;
2585        splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2586        my $ret = $self->SUPER::get_log(@args, $pool);
2587        $pool->clear;
2588        $ret;
2589}
2590
2591sub get_commit_editor {
2592        my ($self, $log, $cb, $pool) = @_;
2593        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2594        $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2595}
2596
2597sub gs_do_update {
2598        my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2599        my $new = ($rev_a == $rev_b);
2600        my $path = $gs->{path};
2601
2602        my $pool = SVN::Pool->new;
2603        $editor->set_path_strip($path);
2604        my (@pc) = split m#/#, $path;
2605        my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2606                                        1, $editor, $pool);
2607        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2608
2609        # Since we can't rely on svn_ra_reparent being available, we'll
2610        # just have to do some magic with set_path to make it so
2611        # we only want a partial path.
2612        my $sp = '';
2613        my $final = join('/', @pc);
2614        while (@pc) {
2615                $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2616                $sp .= '/' if length $sp;
2617                $sp .= shift @pc;
2618        }
2619        die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2620
2621        $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2622
2623        $reporter->finish_report($pool);
2624        $pool->clear;
2625        $editor->{git_commit_ok};
2626}
2627
2628# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2629# svn_ra_reparent didn't work before 1.4)
2630sub gs_do_switch {
2631        my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2632        my $path = $gs->{path};
2633        my $pool = SVN::Pool->new;
2634
2635        my $full_url = $self->{url};
2636        my $old_url = $full_url;
2637        $full_url .= "/$path" if length $path;
2638        my ($ra, $reparented);
2639        if ($old_url ne $full_url) {
2640                if ($old_url !~ m#^svn(\+ssh)?://#) {
2641                        SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2642                                                  $pool);
2643                        $self->{url} = $full_url;
2644                        $reparented = 1;
2645                } else {
2646                        $ra = Git::SVN::Ra->new($full_url);
2647                }
2648        }
2649        $ra ||= $self;
2650        my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2651        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2652        $reporter->set_path('', $rev_a, 0, @lock, $pool);
2653        $reporter->finish_report($pool);
2654
2655        if ($reparented) {
2656                SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2657                $self->{url} = $old_url;
2658        }
2659
2660        $pool->clear;
2661        $editor->{git_commit_ok};
2662}
2663
2664sub gs_fetch_loop_common {
2665        my ($self, $base, $head, $gsv, $globs) = @_;
2666        return if ($base > $head);
2667        my $inc = 1000;
2668        my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2669        my %common;
2670        my $common_max = scalar @$gsv;
2671
2672        foreach my $gs (@$gsv) {
2673                if (my $last_commit = $gs->last_commit) {
2674                        $gs->assert_index_clean($last_commit);
2675                }
2676                my @tmp = split m#/#, $gs->{path};
2677                my $p = '';
2678                foreach (@tmp) {
2679                        $p .= length($p) ? "/$_" : $_;
2680                        $common{$p} ||= 0;
2681                        $common{$p}++;
2682                }
2683        }
2684        $globs ||= [];
2685        $common_max += scalar @$globs;
2686        foreach my $glob (@$globs) {
2687                my @tmp = split m#/#, $glob->{path}->{left};
2688                my $p = '';
2689                foreach (@tmp) {
2690                        $p .= length($p) ? "/$_" : $_;
2691                        $common{$p} ||= 0;
2692                        $common{$p}++;
2693                }
2694        }
2695
2696        my $longest_path = '';
2697        foreach (sort {length $b <=> length $a} keys %common) {
2698                if ($common{$_} == $common_max) {
2699                        $longest_path = $_;
2700                        last;
2701                }
2702        }
2703        while (1) {
2704                my %revs;
2705                my $err;
2706                my $err_handler = $SVN::Error::handler;
2707                $SVN::Error::handler = sub {
2708                        ($err) = @_;
2709                        skip_unknown_revs($err);
2710                };
2711                sub _cb {
2712                        my ($paths, $r, $author, $date, $log) = @_;
2713                        [ dup_changed_paths($paths),
2714                          { author => $author, date => $date, log => $log } ];
2715                }
2716                $self->get_log([$longest_path], $min, $max, 0, 1, 1,
2717                               sub { $revs{$_[1]} = _cb(@_) });
2718                if ($err && $max >= $head) {
2719                        print STDERR "Path '$longest_path' ",
2720                                     "was probably deleted:\n",
2721                                     $err->expanded_message,
2722                                     "\nWill attempt to follow ",
2723                                     "revisions r$min .. r$max ",
2724                                     "committed before the deletion\n";
2725                        my $hi = $max;
2726                        while (--$hi >= $min) {
2727                                my $ok;
2728                                $self->get_log([$longest_path], $min, $hi,
2729                                               0, 1, 1, sub {
2730                                               $ok ||= $_[1];
2731                                               $revs{$_[1]} = _cb(@_) });
2732                                if ($ok) {
2733                                        print STDERR "r$min .. r$ok OK\n";
2734                                        last;
2735                                }
2736                        }
2737                }
2738                $SVN::Error::handler = $err_handler;
2739
2740                my %exists = map { $_->{path} => $_ } @$gsv;
2741                foreach my $r (sort {$a <=> $b} keys %revs) {
2742                        my ($paths, $logged) = @{$revs{$r}};
2743
2744                        foreach my $gs ($self->match_globs(\%exists, $paths,
2745                                                           $globs, $r)) {
2746                                if ($gs->rev_db_max >= $r) {
2747                                        next;
2748                                }
2749                                next unless $gs->match_paths($paths, $r);
2750                                $gs->{logged_rev_props} = $logged;
2751                                my $log_entry = $gs->do_fetch($paths, $r);
2752                                if ($log_entry) {
2753                                        $gs->do_git_commit($log_entry);
2754                                }
2755                        }
2756                        foreach my $g (@$globs) {
2757                                my $k = "svn-remote.$g->{remote}." .
2758                                        "$g->{t}-maxRev";
2759                                Git::SVN::tmp_config($k, $r);
2760                        }
2761                }
2762                # pre-fill the .rev_db since it'll eventually get filled in
2763                # with '0' x40 if something new gets committed
2764                foreach my $gs (@$gsv) {
2765                        next if defined $gs->rev_db_get($max);
2766                        $gs->rev_db_set($max, 0 x40);
2767                }
2768                last if $max >= $head;
2769                $min = $max + 1;
2770                $max += $inc;
2771                $max = $head if ($max > $head);
2772        }
2773}
2774
2775sub match_globs {
2776        my ($self, $exists, $paths, $globs, $r) = @_;
2777
2778        sub get_dir_check {
2779                my ($self, $exists, $g, $r) = @_;
2780                my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
2781                return unless scalar @x == 3;
2782                my $dirents = $x[0];
2783                foreach my $de (keys %$dirents) {
2784                        next if $dirents->{$de}->kind != $SVN::Node::dir;
2785                        my $p = $g->{path}->full_path($de);
2786                        next if $exists->{$p};
2787                        next if (length $g->{path}->{right} &&
2788                                 ($self->check_path($p, $r) !=
2789                                  $SVN::Node::dir));
2790                        $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
2791                                         $g->{ref}->full_path($de), 1);
2792                }
2793        }
2794        foreach my $g (@$globs) {
2795                if (my $path = $paths->{"/$g->{path}->{left}"}) {
2796                        if ($path->{action} =~ /^[AR]$/) {
2797                                get_dir_check($self, $exists, $g, $r);
2798                        }
2799                }
2800                foreach (keys %$paths) {
2801                        if (/$g->{path}->{left_regex}/) {
2802                                next if $paths->{$_}->{action} !~ /^[AR]$/;
2803                                get_dir_check($self, $exists, $g, $r);
2804                        }
2805                        next unless /$g->{path}->{regex}/;
2806                        my $p = $1;
2807                        my $pathname = $g->{path}->full_path($p);
2808                        next if $exists->{$pathname};
2809                        $exists->{$pathname} = Git::SVN->init(
2810                                              $self->{url}, $pathname, undef,
2811                                              $g->{ref}->full_path($p), 1);
2812                }
2813                my $c = '';
2814                foreach (split m#/#, $g->{path}->{left}) {
2815                        $c .= "/$_";
2816                        next unless ($paths->{$c} &&
2817                                     ($paths->{$c}->{action} =~ /^[AR]$/));
2818                        get_dir_check($self, $exists, $g, $r);
2819                }
2820        }
2821        values %$exists;
2822}
2823
2824sub minimize_url {
2825        my ($self) = @_;
2826        return $self->{url} if ($self->{url} eq $self->{repos_root});
2827        my $url = $self->{repos_root};
2828        my @components = split(m!/!, $self->{svn_path});
2829        my $c = '';
2830        do {
2831                $url .= "/$c" if length $c;
2832                eval { (ref $self)->new($url)->get_latest_revnum };
2833        } while ($@ && ($c = shift @components));
2834        $url;
2835}
2836
2837sub can_do_switch {
2838        my $self = shift;
2839        unless (defined $can_do_switch) {
2840                my $pool = SVN::Pool->new;
2841                my $rep = eval {
2842                        $self->do_switch(1, '', 0, $self->{url},
2843                                         SVN::Delta::Editor->new, $pool);
2844                };
2845                if ($@) {
2846                        $can_do_switch = 0;
2847                } else {
2848                        $rep->abort_report($pool);
2849                        $can_do_switch = 1;
2850                }
2851                $pool->clear;
2852        }
2853        $can_do_switch;
2854}
2855
2856sub skip_unknown_revs {
2857        my ($err) = @_;
2858        my $errno = $err->apr_err();
2859        # Maybe the branch we're tracking didn't
2860        # exist when the repo started, so it's
2861        # not an error if it doesn't, just continue
2862        #
2863        # Wonderfully consistent library, eh?
2864        # 160013 - svn:// and file://
2865        # 175002 - http(s)://
2866        # 175007 - http(s):// (this repo required authorization, too...)
2867        #   More codes may be discovered later...
2868        if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2869                return;
2870        }
2871        die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2872}
2873
2874# svn_log_changed_path_t objects passed to get_log are likely to be
2875# overwritten even if only the refs are copied to an external variable,
2876# so we should dup the structures in their entirety.  Using an externally
2877# passed pool (instead of our temporary and quickly cleared pool in
2878# Git::SVN::Ra) does not help matters at all...
2879sub dup_changed_paths {
2880        my ($paths) = @_;
2881        return undef unless $paths;
2882        my %ret;
2883        foreach my $p (keys %$paths) {
2884                my $i = $paths->{$p};
2885                my %s = map { $_ => $i->$_ }
2886                              qw/copyfrom_path copyfrom_rev action/;
2887                $ret{$p} = \%s;
2888        }
2889        \%ret;
2890}
2891
2892package Git::SVN::Log;
2893use strict;
2894use warnings;
2895use POSIX qw/strftime/;
2896use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2897            %rusers $show_commit $incremental/;
2898my $l_fmt;
2899
2900sub cmt_showable {
2901        my ($c) = @_;
2902        return 1 if defined $c->{r};
2903        if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2904                                $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2905                my @log = command(qw/cat-file commit/, $c->{c});
2906                shift @log while ($log[0] ne "\n");
2907                shift @log;
2908                @{$c->{l}} = grep !/^git-svn-id: /, @log;
2909
2910                (undef, $c->{r}, undef) = ::extract_metadata(
2911                                (grep(/^git-svn-id: /, @log))[-1]);
2912        }
2913        return defined $c->{r};
2914}
2915
2916sub log_use_color {
2917        return 1 if $color;
2918        my ($dc, $dcvar);
2919        $dcvar = 'color.diff';
2920        $dc = `git-config --get $dcvar`;
2921        if ($dc eq '') {
2922                # nothing at all; fallback to "diff.color"
2923                $dcvar = 'diff.color';
2924                $dc = `git-config --get $dcvar`;
2925        }
2926        chomp($dc);
2927        if ($dc eq 'auto') {
2928                my $pc;
2929                $pc = `git-config --get color.pager`;
2930                if ($pc eq '') {
2931                        # does not have it -- fallback to pager.color
2932                        $pc = `git-config --bool --get pager.color`;
2933                }
2934                else {
2935                        $pc = `git-config --bool --get color.pager`;
2936                        if ($?) {
2937                                $pc = 'false';
2938                        }
2939                }
2940                chomp($pc);
2941                if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2942                        return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2943                }
2944                return 0;
2945        }
2946        return 0 if $dc eq 'never';
2947        return 1 if $dc eq 'always';
2948        chomp($dc = `git-config --bool --get $dcvar`);
2949        return ($dc eq 'true');
2950}
2951
2952sub git_svn_log_cmd {
2953        my ($r_min, $r_max) = @_;
2954        my $gs = Git::SVN->_new;
2955        my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2956                   $gs->refname);
2957        push @cmd, '-r' unless $non_recursive;
2958        push @cmd, qw/--raw --name-status/ if $verbose;
2959        push @cmd, '--color' if log_use_color();
2960        return @cmd unless defined $r_max;
2961        if ($r_max == $r_min) {
2962                push @cmd, '--max-count=1';
2963                if (my $c = $gs->rev_db_get($r_max)) {
2964                        push @cmd, $c;
2965                }
2966        } else {
2967                my ($c_min, $c_max);
2968                $c_max = $gs->rev_db_get($r_max);
2969                $c_min = $gs->rev_db_get($r_min);
2970                if (defined $c_min && defined $c_max) {
2971                        if ($r_max > $r_max) {
2972                                push @cmd, "$c_min..$c_max";
2973                        } else {
2974                                push @cmd, "$c_max..$c_min";
2975                        }
2976                } elsif ($r_max > $r_min) {
2977                        push @cmd, $c_max;
2978                } else {
2979                        push @cmd, $c_min;
2980                }
2981        }
2982        return @cmd;
2983}
2984
2985# adapted from pager.c
2986sub config_pager {
2987        $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2988        if (!defined $pager) {
2989                $pager = 'less';
2990        } elsif (length $pager == 0 || $pager eq 'cat') {
2991                $pager = undef;
2992        }
2993}
2994
2995sub run_pager {
2996        return unless -t *STDOUT;
2997        pipe my $rfd, my $wfd or return;
2998        defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2999        if (!$pid) {
3000                open STDOUT, '>&', $wfd or
3001                                     ::fatal "Can't redirect to stdout: $!\n";
3002                return;
3003        }
3004        open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3005        $ENV{LESS} ||= 'FRSX';
3006        exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3007}
3008
3009sub tz_to_s_offset {
3010        my ($tz) = @_;
3011        $tz =~ s/(\d\d)$//;
3012        return ($1 * 60) + ($tz * 3600);
3013}
3014
3015sub get_author_info {
3016        my ($dest, $author, $t, $tz) = @_;
3017        $author =~ s/(?:^\s*|\s*$)//g;
3018        $dest->{a_raw} = $author;
3019        my $au;
3020        if ($::_authors) {
3021                $au = $rusers{$author} || undef;
3022        }
3023        if (!$au) {
3024                ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3025        }
3026        $dest->{t} = $t;
3027        $dest->{tz} = $tz;
3028        $dest->{a} = $au;
3029        # Date::Parse isn't in the standard Perl distro :(
3030        if ($tz =~ s/^\+//) {
3031                $t += tz_to_s_offset($tz);
3032        } elsif ($tz =~ s/^\-//) {
3033                $t -= tz_to_s_offset($tz);
3034        }
3035        $dest->{t_utc} = $t;
3036}
3037
3038sub process_commit {
3039        my ($c, $r_min, $r_max, $defer) = @_;
3040        if (defined $r_min && defined $r_max) {
3041                if ($r_min == $c->{r} && $r_min == $r_max) {
3042                        show_commit($c);
3043                        return 0;
3044                }
3045                return 1 if $r_min == $r_max;
3046                if ($r_min < $r_max) {
3047                        # we need to reverse the print order
3048                        return 0 if (defined $limit && --$limit < 0);
3049                        push @$defer, $c;
3050                        return 1;
3051                }
3052                if ($r_min != $r_max) {
3053                        return 1 if ($r_min < $c->{r});
3054                        return 1 if ($r_max > $c->{r});
3055                }
3056        }
3057        return 0 if (defined $limit && --$limit < 0);
3058        show_commit($c);
3059        return 1;
3060}
3061
3062sub show_commit {
3063        my $c = shift;
3064        if ($oneline) {
3065                my $x = "\n";
3066                if (my $l = $c->{l}) {
3067                        while ($l->[0] =~ /^\s*$/) { shift @$l }
3068                        $x = $l->[0];
3069                }
3070                $l_fmt ||= 'A' . length($c->{r});
3071                print 'r',pack($l_fmt, $c->{r}),' | ';
3072                print "$c->{c} | " if $show_commit;
3073                print $x;
3074        } else {
3075                show_commit_normal($c);
3076        }
3077}
3078
3079sub show_commit_changed_paths {
3080        my ($c) = @_;
3081        return unless $c->{changed};
3082        print "Changed paths:\n", @{$c->{changed}};
3083}
3084
3085sub show_commit_normal {
3086        my ($c) = @_;
3087        print '-' x72, "\nr$c->{r} | ";
3088        print "$c->{c} | " if $show_commit;
3089        print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3090                                 localtime($c->{t_utc})), ' | ';
3091        my $nr_line = 0;
3092
3093        if (my $l = $c->{l}) {
3094                while ($l->[$#$l] eq "\n" && $#$l > 0
3095                                          && $l->[($#$l - 1)] eq "\n") {
3096                        pop @$l;
3097                }
3098                $nr_line = scalar @$l;
3099                if (!$nr_line) {
3100                        print "1 line\n\n\n";
3101                } else {
3102                        if ($nr_line == 1) {
3103                                $nr_line = '1 line';
3104                        } else {
3105                                $nr_line .= ' lines';
3106                        }
3107                        print $nr_line, "\n";
3108                        show_commit_changed_paths($c);
3109                        print "\n";
3110                        print $_ foreach @$l;
3111                }
3112        } else {
3113                print "1 line\n";
3114                show_commit_changed_paths($c);
3115                print "\n";
3116
3117        }
3118        foreach my $x (qw/raw diff/) {
3119                if ($c->{$x}) {
3120                        print "\n";
3121                        print $_ foreach @{$c->{$x}}
3122                }
3123        }
3124}
3125
3126sub cmd_show_log {
3127        my (@args) = @_;
3128        my ($r_min, $r_max);
3129        my $r_last = -1; # prevent dupes
3130        if (defined $TZ) {
3131                $ENV{TZ} = $TZ;
3132        } else {
3133                delete $ENV{TZ};
3134        }
3135        if (defined $::_revision) {
3136                if ($::_revision =~ /^(\d+):(\d+)$/) {
3137                        ($r_min, $r_max) = ($1, $2);
3138                } elsif ($::_revision =~ /^\d+$/) {
3139                        $r_min = $r_max = $::_revision;
3140                } else {
3141                        ::fatal "-r$::_revision is not supported, use ",
3142                                "standard \'git log\' arguments instead\n";
3143                }
3144        }
3145
3146        config_pager();
3147        @args = (git_svn_log_cmd($r_min, $r_max), @args);
3148        my $log = command_output_pipe(@args);
3149        run_pager();
3150        my (@k, $c, $d);
3151        my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3152        while (<$log>) {
3153                if (/^${esc_color}commit ($::sha1_short)/o) {
3154                        my $cmt = $1;
3155                        if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3156                                $r_last = $c->{r};
3157                                process_commit($c, $r_min, $r_max, \@k) or
3158                                                                goto out;
3159                        }
3160                        $d = undef;
3161                        $c = { c => $cmt };
3162                } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3163                        get_author_info($c, $1, $2, $3);
3164                } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3165                        # ignore
3166                } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3167                        push @{$c->{raw}}, $_;
3168                } elsif (/^${esc_color}[ACRMDT]\t/) {
3169                        # we could add $SVN->{svn_path} here, but that requires
3170                        # remote access at the moment (repo_path_split)...
3171                        s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
3172                        push @{$c->{changed}}, $_;
3173                } elsif (/^${esc_color}diff /o) {
3174                        $d = 1;
3175                        push @{$c->{diff}}, $_;
3176                } elsif ($d) {
3177                        push @{$c->{diff}}, $_;
3178                } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
3179                        ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3180                } elsif (s/^${esc_color}    //o) {
3181                        push @{$c->{l}}, $_;
3182                }
3183        }
3184        if ($c && defined $c->{r} && $c->{r} != $r_last) {
3185                $r_last = $c->{r};
3186                process_commit($c, $r_min, $r_max, \@k);
3187        }
3188        if (@k) {
3189                my $swap = $r_max;
3190                $r_max = $r_min;
3191                $r_min = $swap;
3192                process_commit($_, $r_min, $r_max) foreach reverse @k;
3193        }
3194out:
3195        close $log;
3196        print '-' x72,"\n" unless $incremental || $oneline;
3197}
3198
3199package Git::SVN::Migration;
3200# these version numbers do NOT correspond to actual version numbers
3201# of git nor git-svn.  They are just relative.
3202#
3203# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3204#
3205# v1 layout: .git/$id/info/url, refs/remotes/$id
3206#
3207# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3208#
3209# v3 layout: .git/svn/$id, refs/remotes/$id
3210#            - info/url may remain for backwards compatibility
3211#            - this is what we migrate up to this layout automatically,
3212#            - this will be used by git svn init on single branches
3213# v3.1 layout (auto migrated):
3214#            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3215#              for backwards compatibility
3216#
3217# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3218#            - this is only created for newly multi-init-ed
3219#              repositories.  Similar in spirit to the
3220#              --use-separate-remotes option in git-clone (now default)
3221#            - we do not automatically migrate to this (following
3222#              the example set by core git)
3223use strict;
3224use warnings;
3225use Carp qw/croak/;
3226use File::Path qw/mkpath/;
3227use File::Basename qw/dirname basename/;
3228use vars qw/$_minimize/;
3229
3230sub migrate_from_v0 {
3231        my $git_dir = $ENV{GIT_DIR};
3232        return undef unless -d $git_dir;
3233        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3234        my $migrated = 0;
3235        while (<$fh>) {
3236                chomp;
3237                my ($id, $orig_ref) = ($_, $_);
3238                next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3239                next unless -f "$git_dir/$id/info/url";
3240                my $new_ref = "refs/remotes/$id";
3241                if (::verify_ref("$new_ref^0")) {
3242                        print STDERR "W: $orig_ref is probably an old ",
3243                                     "branch used by an ancient version of ",
3244                                     "git-svn.\n",
3245                                     "However, $new_ref also exists.\n",
3246                                     "We will not be able ",
3247                                     "to use this branch until this ",
3248                                     "ambiguity is resolved.\n";
3249                        next;
3250                }
3251                print STDERR "Migrating from v0 layout...\n" if !$migrated;
3252                print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3253                command_noisy('update-ref', $new_ref, $orig_ref);
3254                command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3255                $migrated++;
3256        }
3257        command_close_pipe($fh, $ctx);
3258        print STDERR "Done migrating from v0 layout...\n" if $migrated;
3259        $migrated;
3260}
3261
3262sub migrate_from_v1 {
3263        my $git_dir = $ENV{GIT_DIR};
3264        my $migrated = 0;
3265        return $migrated unless -d $git_dir;
3266        my $svn_dir = "$git_dir/svn";
3267
3268        # just in case somebody used 'svn' as their $id at some point...
3269        return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3270
3271        print STDERR "Migrating from a git-svn v1 layout...\n";
3272        mkpath([$svn_dir]);
3273        print STDERR "Data from a previous version of git-svn exists, but\n\t",
3274                     "$svn_dir\n\t(required for this version ",
3275                     "($::VERSION) of git-svn) does not. exist\n";
3276        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3277        while (<$fh>) {
3278                my $x = $_;
3279                next unless $x =~ s#^refs/remotes/##;
3280                chomp $x;
3281                next unless -f "$git_dir/$x/info/url";
3282                my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3283                next unless $u;
3284                my $dn = dirname("$git_dir/svn/$x");
3285                mkpath([$dn]) unless -d $dn;
3286                if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3287                        mkpath(["$git_dir/svn/svn"]);
3288                        print STDERR " - $git_dir/$x/info => ",
3289                                        "$git_dir/svn/$x/info\n";
3290                        rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3291                               croak "$!: $x";
3292                        # don't worry too much about these, they probably
3293                        # don't exist with repos this old (save for index,
3294                        # and we can easily regenerate that)
3295                        foreach my $f (qw/unhandled.log index .rev_db/) {
3296                                rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3297                        }
3298                } else {
3299                        print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3300                        rename "$git_dir/$x", "$git_dir/svn/$x" or
3301                               croak "$!: $x";
3302                }
3303                $migrated++;
3304        }
3305        command_close_pipe($fh, $ctx);
3306        print STDERR "Done migrating from a git-svn v1 layout\n";
3307        $migrated;
3308}
3309
3310sub read_old_urls {
3311        my ($l_map, $pfx, $path) = @_;
3312        my @dir;
3313        foreach (<$path/*>) {
3314                if (-r "$_/info/url") {
3315                        $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3316                        my $ref_id = $pfx . basename $_;
3317                        my $url = ::file_to_s("$_/info/url");
3318                        $l_map->{$ref_id} = $url;
3319                } elsif (-d $_) {
3320                        push @dir, $_;
3321                }
3322        }
3323        foreach (@dir) {
3324                my $x = $_;
3325                $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3326                read_old_urls($l_map, $x, $_);
3327        }
3328}
3329
3330sub migrate_from_v2 {
3331        my @cfg = command(qw/config -l/);
3332        return if grep /^svn-remote\..+\.url=/, @cfg;
3333        my %l_map;
3334        read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3335        my $migrated = 0;
3336
3337        foreach my $ref_id (sort keys %l_map) {
3338                eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3339                if ($@) {
3340                        Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3341                }
3342                $migrated++;
3343        }
3344        $migrated;
3345}
3346
3347sub minimize_connections {
3348        my $r = Git::SVN::read_all_remotes();
3349        my $new_urls = {};
3350        my $root_repos = {};
3351        foreach my $repo_id (keys %$r) {
3352                my $url = $r->{$repo_id}->{url} or next;
3353                my $fetch = $r->{$repo_id}->{fetch} or next;
3354                my $ra = Git::SVN::Ra->new($url);
3355
3356                # skip existing cases where we already connect to the root
3357                if (($ra->{url} eq $ra->{repos_root}) ||
3358                    (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3359                     $repo_id)) {
3360                        $root_repos->{$ra->{url}} = $repo_id;
3361                        next;
3362                }
3363
3364                my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3365                my $root_path = $ra->{url};
3366                $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3367                foreach my $path (keys %$fetch) {
3368                        my $ref_id = $fetch->{$path};
3369                        my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3370
3371                        # make sure we can read when connecting to
3372                        # a higher level of a repository
3373                        my ($last_rev, undef) = $gs->last_rev_commit;
3374                        if (!defined $last_rev) {
3375                                $last_rev = eval {
3376                                        $root_ra->get_latest_revnum;
3377                                };
3378                                next if $@;
3379                        }
3380                        my $new = $root_path;
3381                        $new .= length $path ? "/$path" : '';
3382                        eval {
3383                                $root_ra->get_log([$new], $last_rev, $last_rev,
3384                                                  0, 0, 1, sub { });
3385                        };
3386                        next if $@;
3387                        $new_urls->{$ra->{repos_root}}->{$new} =
3388                                { ref_id => $ref_id,
3389                                  old_repo_id => $repo_id,
3390                                  old_path => $path };
3391                }
3392        }
3393
3394        my @emptied;
3395        foreach my $url (keys %$new_urls) {
3396                # see if we can re-use an existing [svn-remote "repo_id"]
3397                # instead of creating a(n ugly) new section:
3398                my $repo_id = $root_repos->{$url} ||
3399                              Git::SVN::sanitize_remote_name($url);
3400
3401                my $fetch = $new_urls->{$url};
3402                foreach my $path (keys %$fetch) {
3403                        my $x = $fetch->{$path};
3404                        Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3405                        my $pfx = "svn-remote.$x->{old_repo_id}";
3406
3407                        my $old_fetch = quotemeta("$x->{old_path}:".
3408                                                  "refs/remotes/$x->{ref_id}");
3409                        command_noisy(qw/config --unset/,
3410                                      "$pfx.fetch", '^'. $old_fetch . '$');
3411                        delete $r->{$x->{old_repo_id}}->
3412                               {fetch}->{$x->{old_path}};
3413                        if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3414                                command_noisy(qw/config --unset/,
3415                                              "$pfx.url");
3416                                push @emptied, $x->{old_repo_id}
3417                        }
3418                }
3419        }
3420        if (@emptied) {
3421                my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3422                           "$ENV{GIT_DIR}/config";
3423                print STDERR <<EOF;
3424The following [svn-remote] sections in your config file ($file) are empty
3425and can be safely removed:
3426EOF
3427                print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3428        }
3429}
3430
3431sub migration_check {
3432        migrate_from_v0();
3433        migrate_from_v1();
3434        migrate_from_v2();
3435        minimize_connections() if $_minimize;
3436}
3437
3438package Git::IndexInfo;
3439use strict;
3440use warnings;
3441use Git qw/command_input_pipe command_close_pipe/;
3442
3443sub new {
3444        my ($class) = @_;
3445        my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3446        bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3447}
3448
3449sub remove {
3450        my ($self, $path) = @_;
3451        if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3452                return ++$self->{nr};
3453        }
3454        undef;
3455}
3456
3457sub update {
3458        my ($self, $mode, $hash, $path) = @_;
3459        if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3460                return ++$self->{nr};
3461        }
3462        undef;
3463}
3464
3465sub DESTROY {
3466        my ($self) = @_;
3467        command_close_pipe($self->{gui}, $self->{ctx});
3468}
3469
3470package Git::SVN::GlobSpec;
3471use strict;
3472use warnings;
3473
3474sub new {
3475        my ($class, $glob) = @_;
3476        my $re = $glob;
3477        $re =~ s!/+$!!g; # no need for trailing slashes
3478        my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3479        my ($left, $right) = ($1, $2);
3480        if ($nr > 1) {
3481                die "Only one '*' wildcard expansion ",
3482                    "is supported (got $nr): '$glob'\n";
3483        } elsif ($nr == 0) {
3484                die "One '*' is needed for glob: '$glob'\n";
3485        }
3486        $re = quotemeta($left) . $re . quotemeta($right);
3487        if (length $left && !($left =~ s!/+$!!g)) {
3488                die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3489        }
3490        if (length $right && !($right =~ s!^/+!!g)) {
3491                die "Missing leading '/' on right side of: '$glob' ($right)\n";
3492        }
3493        my $left_re = qr/^\/\Q$left\E(\/|$)/;
3494        bless { left => $left, right => $right, left_regex => $left_re,
3495                regex => qr/$re/, glob => $glob }, $class;
3496}
3497
3498sub full_path {
3499        my ($self, $path) = @_;
3500        return (length $self->{left} ? "$self->{left}/" : '') .
3501               $path . (length $self->{right} ? "/$self->{right}" : '');
3502}
3503
3504__END__
3505
3506Data structures:
3507
3508
3509$remotes = { # returned by read_all_remotes()
3510        'svn' => {
3511                # svn-remote.svn.url=https://svn.musicpd.org
3512                url => 'https://svn.musicpd.org',
3513                # svn-remote.svn.fetch=mpd/trunk:trunk
3514                fetch => {
3515                        'mpd/trunk' => 'trunk',
3516                },
3517                # svn-remote.svn.tags=mpd/tags/*:tags/*
3518                tags => {
3519                        path => {
3520                                left => 'mpd/tags',
3521                                right => '',
3522                                regex => qr!mpd/tags/([^/]+)$!,
3523                                glob => 'tags/*',
3524                        },
3525                        ref => {
3526                                left => 'tags',
3527                                right => '',
3528                                regex => qr!tags/([^/]+)$!,
3529                                glob => 'tags/*',
3530                        },
3531                }
3532        }
3533};
3534
3535$log_entry hashref as returned by libsvn_log_entry()
3536{
3537        log => 'whitespace-formatted log entry
3538',                                              # trailing newline is preserved
3539        revision => '8',                        # integer
3540        date => '2004-02-24T17:01:44.108345Z',  # commit date
3541        author => 'committer name'
3542};
3543
3544
3545# this is generated by generate_diff();
3546@mods = array of diff-index line hashes, each element represents one line
3547        of diff-index output
3548
3549diff-index line ($m hash)
3550{
3551        mode_a => first column of diff-index output, no leading ':',
3552        mode_b => second column of diff-index output,
3553        sha1_b => sha1sum of the final blob,
3554        chg => change type [MCRADT],
3555        file_a => original file name of a file (iff chg is 'C' or 'R')
3556        file_b => new/current file name of a file (any chg)
3557}
3558;
3559
3560# retval of read_url_paths{,_all}();
3561$l_map = {
3562        # repository root url
3563        'https://svn.musicpd.org' => {
3564                # repository path               # GIT_SVN_ID
3565                'mpd/trunk'             =>      'trunk',
3566                'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3567        },
3568}
3569
3570Notes:
3571        I don't trust the each() function on unless I created %hash myself
3572        because the internal iterator may not have started at base.