git-svn.perlon commit Add tests for git push'es mirror mode (8e806ad)
   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# From which subdir have we been invoked?
  13my $cmd_dir_prefix = eval {
  14        command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
  15} || '';
  16
  17my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
  18$ENV{GIT_DIR} ||= '.git';
  19$Git::SVN::default_repo_id = 'svn';
  20$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
  21$Git::SVN::Ra::_log_window_size = 100;
  22
  23$Git::SVN::Log::TZ = $ENV{TZ};
  24$ENV{TZ} = 'UTC';
  25$| = 1; # unbuffer STDOUT
  26
  27sub fatal (@) { print STDERR "@_\n"; exit 1 }
  28require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
  29require SVN::Ra;
  30require SVN::Delta;
  31if ($SVN::Core::VERSION lt '1.1.0') {
  32        fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
  33}
  34push @Git::SVN::Ra::ISA, 'SVN::Ra';
  35push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
  36push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
  37use Carp qw/croak/;
  38use IO::File qw//;
  39use File::Basename qw/dirname basename/;
  40use File::Path qw/mkpath/;
  41use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
  42use IPC::Open3;
  43use Git;
  44
  45BEGIN {
  46        # import functions from Git into our packages, en masse
  47        no strict 'refs';
  48        foreach (qw/command command_oneline command_noisy command_output_pipe
  49                    command_input_pipe command_close_pipe/) {
  50                for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
  51                        Git::SVN::Migration Git::SVN::Log Git::SVN),
  52                        __PACKAGE__) {
  53                        *{"${package}::$_"} = \&{"Git::$_"};
  54                }
  55        }
  56}
  57
  58my ($SVN);
  59
  60$sha1 = qr/[a-f\d]{40}/;
  61$sha1_short = qr/[a-f\d]{4,40}/;
  62my ($_stdin, $_help, $_edit,
  63        $_message, $_file,
  64        $_template, $_shared,
  65        $_version, $_fetch_all, $_no_rebase,
  66        $_merge, $_strategy, $_dry_run, $_local,
  67        $_prefix, $_no_checkout, $_verbose);
  68$Git::SVN::_follow_parent = 1;
  69my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
  70                    'config-dir=s' => \$Git::SVN::Ra::config_dir,
  71                    'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
  72my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
  73                'authors-file|A=s' => \$_authors,
  74                'repack:i' => \$Git::SVN::_repack,
  75                'noMetadata' => \$Git::SVN::_no_metadata,
  76                'useSvmProps' => \$Git::SVN::_use_svm_props,
  77                'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
  78                'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
  79                'no-checkout' => \$_no_checkout,
  80                'quiet|q' => \$_q,
  81                'repack-flags|repack-args|repack-opts=s' =>
  82                   \$Git::SVN::_repack_flags,
  83                %remote_opts );
  84
  85my ($_trunk, $_tags, $_branches, $_stdlayout);
  86my %icv;
  87my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
  88                  'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
  89                  'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
  90                  'stdlayout|s' => \$_stdlayout,
  91                  'minimize-url|m' => \$Git::SVN::_minimize_url,
  92                  'no-metadata' => sub { $icv{noMetadata} = 1 },
  93                  'use-svm-props' => sub { $icv{useSvmProps} = 1 },
  94                  'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
  95                  'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
  96                  %remote_opts );
  97my %cmt_opts = ( 'edit|e' => \$_edit,
  98                'rmdir' => \$SVN::Git::Editor::_rmdir,
  99                'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
 100                'l=i' => \$SVN::Git::Editor::_rename_limit,
 101                'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
 102);
 103
 104my %cmd = (
 105        fetch => [ \&cmd_fetch, "Download new revisions from SVN",
 106                        { 'revision|r=s' => \$_revision,
 107                          'fetch-all|all' => \$_fetch_all,
 108                           %fc_opts } ],
 109        clone => [ \&cmd_clone, "Initialize and fetch revisions",
 110                        { 'revision|r=s' => \$_revision,
 111                           %fc_opts, %init_opts } ],
 112        init => [ \&cmd_init, "Initialize a repo for tracking" .
 113                          " (requires URL argument)",
 114                          \%init_opts ],
 115        'multi-init' => [ \&cmd_multi_init,
 116                          "Deprecated alias for ".
 117                          "'$0 init -T<trunk> -b<branches> -t<tags>'",
 118                          \%init_opts ],
 119        dcommit => [ \&cmd_dcommit,
 120                     'Commit several diffs to merge with upstream',
 121                        { 'merge|m|M' => \$_merge,
 122                          'strategy|s=s' => \$_strategy,
 123                          'verbose|v' => \$_verbose,
 124                          'dry-run|n' => \$_dry_run,
 125                          'fetch-all|all' => \$_fetch_all,
 126                          'no-rebase' => \$_no_rebase,
 127                        %cmt_opts, %fc_opts } ],
 128        'set-tree' => [ \&cmd_set_tree,
 129                        "Set an SVN repository to a git tree-ish",
 130                        { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
 131        'create-ignore' => [ \&cmd_create_ignore,
 132                             'Create a .gitignore per svn:ignore',
 133                             { 'revision|r=i' => \$_revision
 134                             } ],
 135        'propget' => [ \&cmd_propget,
 136                       'Print the value of a property on a file or directory',
 137                       { 'revision|r=i' => \$_revision } ],
 138        'proplist' => [ \&cmd_proplist,
 139                       'List all properties of a file or directory',
 140                       { 'revision|r=i' => \$_revision } ],
 141        'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
 142                        { 'revision|r=i' => \$_revision
 143                        } ],
 144        'multi-fetch' => [ \&cmd_multi_fetch,
 145                           "Deprecated alias for $0 fetch --all",
 146                           { 'revision|r=s' => \$_revision, %fc_opts } ],
 147        'migrate' => [ sub { },
 148                       # no-op, we automatically run this anyways,
 149                       'Migrate configuration/metadata/layout from
 150                        previous versions of git-svn',
 151                       { 'minimize' => \$Git::SVN::Migration::_minimize,
 152                         %remote_opts } ],
 153        'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
 154                        { 'limit=i' => \$Git::SVN::Log::limit,
 155                          'revision|r=s' => \$_revision,
 156                          'verbose|v' => \$Git::SVN::Log::verbose,
 157                          'incremental' => \$Git::SVN::Log::incremental,
 158                          'oneline' => \$Git::SVN::Log::oneline,
 159                          'show-commit' => \$Git::SVN::Log::show_commit,
 160                          'non-recursive' => \$Git::SVN::Log::non_recursive,
 161                          'authors-file|A=s' => \$_authors,
 162                          'color' => \$Git::SVN::Log::color,
 163                          'pager=s' => \$Git::SVN::Log::pager
 164                        } ],
 165        'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
 166                        {} ],
 167        'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
 168                        { 'merge|m|M' => \$_merge,
 169                          'verbose|v' => \$_verbose,
 170                          'strategy|s=s' => \$_strategy,
 171                          'local|l' => \$_local,
 172                          'fetch-all|all' => \$_fetch_all,
 173                          %fc_opts } ],
 174        'commit-diff' => [ \&cmd_commit_diff,
 175                           'Commit a diff between two trees',
 176                        { 'message|m=s' => \$_message,
 177                          'file|F=s' => \$_file,
 178                          'revision|r=s' => \$_revision,
 179                        %cmt_opts } ],
 180);
 181
 182my $cmd;
 183for (my $i = 0; $i < @ARGV; $i++) {
 184        if (defined $cmd{$ARGV[$i]}) {
 185                $cmd = $ARGV[$i];
 186                splice @ARGV, $i, 1;
 187                last;
 188        }
 189};
 190
 191my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
 192
 193read_repo_config(\%opts);
 194Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
 195my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
 196                    'minimize-connections' => \$Git::SVN::Migration::_minimize,
 197                    'id|i=s' => \$Git::SVN::default_ref_id,
 198                    'svn-remote|remote|R=s' => sub {
 199                       $Git::SVN::no_reuse_existing = 1;
 200                       $Git::SVN::default_repo_id = $_[1] });
 201exit 1 if (!$rv && $cmd && $cmd ne 'log');
 202
 203usage(0) if $_help;
 204version() if $_version;
 205usage(1) unless defined $cmd;
 206load_authors() if $_authors;
 207
 208# make sure we're always running
 209unless ($cmd =~ /(?:clone|init|multi-init)$/) {
 210        unless (-d $ENV{GIT_DIR}) {
 211                if ($git_dir_user_set) {
 212                        die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
 213                            "but it is not a directory\n";
 214                }
 215                my $git_dir = delete $ENV{GIT_DIR};
 216                chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
 217                unless (length $cdup) {
 218                        die "Already at toplevel, but $git_dir ",
 219                            "not found '$cdup'\n";
 220                }
 221                chdir $cdup or die "Unable to chdir up to '$cdup'\n";
 222                unless (-d $git_dir) {
 223                        die "$git_dir still not found after going to ",
 224                            "'$cdup'\n";
 225                }
 226                $ENV{GIT_DIR} = $git_dir;
 227        }
 228}
 229unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
 230        Git::SVN::Migration::migration_check();
 231}
 232Git::SVN::init_vars();
 233eval {
 234        Git::SVN::verify_remotes_sanity();
 235        $cmd{$cmd}->[0]->(@ARGV);
 236};
 237fatal $@ if $@;
 238post_fetch_checkout();
 239exit 0;
 240
 241####################### primary functions ######################
 242sub usage {
 243        my $exit = shift || 0;
 244        my $fd = $exit ? \*STDERR : \*STDOUT;
 245        print $fd <<"";
 246git-svn - bidirectional operations between a single Subversion tree and git
 247Usage: $0 <command> [options] [arguments]\n
 248
 249        print $fd "Available commands:\n" unless $cmd;
 250
 251        foreach (sort keys %cmd) {
 252                next if $cmd && $cmd ne $_;
 253                next if /^multi-/; # don't show deprecated commands
 254                print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
 255                foreach (sort keys %{$cmd{$_}->[2]}) {
 256                        # mixed-case options are for .git/config only
 257                        next if /[A-Z]/ && /^[a-z]+$/i;
 258                        # prints out arguments as they should be passed:
 259                        my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
 260                        print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
 261                                                        "--$_" : "-$_" }
 262                                                split /\|/,$_)," $x\n";
 263                }
 264        }
 265        print $fd <<"";
 266\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
 267arbitrary identifier if you're tracking multiple SVN branches/repositories in
 268one git repository and want to keep them separate.  See git-svn(1) for more
 269information.
 270
 271        exit $exit;
 272}
 273
 274sub version {
 275        print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
 276        exit 0;
 277}
 278
 279sub do_git_init_db {
 280        unless (-d $ENV{GIT_DIR}) {
 281                my @init_db = ('init');
 282                push @init_db, "--template=$_template" if defined $_template;
 283                if (defined $_shared) {
 284                        if ($_shared =~ /[a-z]/) {
 285                                push @init_db, "--shared=$_shared";
 286                        } else {
 287                                push @init_db, "--shared";
 288                        }
 289                }
 290                command_noisy(@init_db);
 291        }
 292        my $set;
 293        my $pfx = "svn-remote.$Git::SVN::default_repo_id";
 294        foreach my $i (keys %icv) {
 295                die "'$set' and '$i' cannot both be set\n" if $set;
 296                next unless defined $icv{$i};
 297                command_noisy('config', "$pfx.$i", $icv{$i});
 298                $set = $i;
 299        }
 300}
 301
 302sub init_subdir {
 303        my $repo_path = shift or return;
 304        mkpath([$repo_path]) unless -d $repo_path;
 305        chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
 306        $ENV{GIT_DIR} = '.git';
 307}
 308
 309sub cmd_clone {
 310        my ($url, $path) = @_;
 311        if (!defined $path &&
 312            (defined $_trunk || defined $_branches || defined $_tags ||
 313             defined $_stdlayout) &&
 314            $url !~ m#^[a-z\+]+://#) {
 315                $path = $url;
 316        }
 317        $path = basename($url) if !defined $path || !length $path;
 318        cmd_init($url, $path);
 319        Git::SVN::fetch_all($Git::SVN::default_repo_id);
 320}
 321
 322sub cmd_init {
 323        if (defined $_stdlayout) {
 324                $_trunk = 'trunk' if (!defined $_trunk);
 325                $_tags = 'tags' if (!defined $_tags);
 326                $_branches = 'branches' if (!defined $_branches);
 327        }
 328        if (defined $_trunk || defined $_branches || defined $_tags) {
 329                return cmd_multi_init(@_);
 330        }
 331        my $url = shift or die "SVN repository location required ",
 332                               "as a command-line argument\n";
 333        init_subdir(@_);
 334        do_git_init_db();
 335
 336        Git::SVN->init($url);
 337}
 338
 339sub cmd_fetch {
 340        if (grep /^\d+=./, @_) {
 341                die "'<rev>=<commit>' fetch arguments are ",
 342                    "no longer supported.\n";
 343        }
 344        my ($remote) = @_;
 345        if (@_ > 1) {
 346                die "Usage: $0 fetch [--all] [svn-remote]\n";
 347        }
 348        $remote ||= $Git::SVN::default_repo_id;
 349        if ($_fetch_all) {
 350                cmd_multi_fetch();
 351        } else {
 352                Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
 353        }
 354}
 355
 356sub cmd_set_tree {
 357        my (@commits) = @_;
 358        if ($_stdin || !@commits) {
 359                print "Reading from stdin...\n";
 360                @commits = ();
 361                while (<STDIN>) {
 362                        if (/\b($sha1_short)\b/o) {
 363                                unshift @commits, $1;
 364                        }
 365                }
 366        }
 367        my @revs;
 368        foreach my $c (@commits) {
 369                my @tmp = command('rev-parse',$c);
 370                if (scalar @tmp == 1) {
 371                        push @revs, $tmp[0];
 372                } elsif (scalar @tmp > 1) {
 373                        push @revs, reverse(command('rev-list',@tmp));
 374                } else {
 375                        fatal "Failed to rev-parse $c";
 376                }
 377        }
 378        my $gs = Git::SVN->new;
 379        my ($r_last, $cmt_last) = $gs->last_rev_commit;
 380        $gs->fetch;
 381        if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
 382                fatal "There are new revisions that were fetched ",
 383                      "and need to be merged (or acknowledged) ",
 384                      "before committing.\nlast rev: $r_last\n",
 385                      " current: $gs->{last_rev}";
 386        }
 387        $gs->set_tree($_) foreach @revs;
 388        print "Done committing ",scalar @revs," revisions to SVN\n";
 389}
 390
 391sub cmd_dcommit {
 392        my $head = shift;
 393        $head ||= 'HEAD';
 394        my @refs;
 395        my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
 396        print "Committing to $url ...\n";
 397        unless ($gs) {
 398                die "Unable to determine upstream SVN information from ",
 399                    "$head history\n";
 400        }
 401        my $last_rev;
 402        my ($linear_refs, $parents) = linearize_history($gs, \@refs);
 403        if ($_no_rebase && scalar(@$linear_refs) > 1) {
 404                warn "Attempting to commit more than one change while ",
 405                     "--no-rebase is enabled.\n",
 406                     "If these changes depend on each other, re-running ",
 407                     "without --no-rebase will be required."
 408        }
 409        while (1) {
 410                my $d = shift @$linear_refs or last;
 411                unless (defined $last_rev) {
 412                        (undef, $last_rev, undef) = cmt_metadata("$d~1");
 413                        unless (defined $last_rev) {
 414                                fatal "Unable to extract revision information ",
 415                                      "from commit $d~1";
 416                        }
 417                }
 418                if ($_dry_run) {
 419                        print "diff-tree $d~1 $d\n";
 420                } else {
 421                        my $cmt_rev;
 422                        my %ed_opts = ( r => $last_rev,
 423                                        log => get_commit_entry($d)->{log},
 424                                        ra => Git::SVN::Ra->new($gs->full_url),
 425                                        tree_a => "$d~1",
 426                                        tree_b => $d,
 427                                        editor_cb => sub {
 428                                               print "Committed r$_[0]\n";
 429                                               $cmt_rev = $_[0];
 430                                        },
 431                                        svn_path => '');
 432                        if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
 433                                print "No changes\n$d~1 == $d\n";
 434                        } elsif ($parents->{$d} && @{$parents->{$d}}) {
 435                                $gs->{inject_parents_dcommit}->{$cmt_rev} =
 436                                                               $parents->{$d};
 437                        }
 438                        $_fetch_all ? $gs->fetch_all : $gs->fetch;
 439                        next if $_no_rebase;
 440
 441                        # we always want to rebase against the current HEAD,
 442                        # not any head that was passed to us
 443                        my @diff = command('diff-tree', $d,
 444                                           $gs->refname, '--');
 445                        my @finish;
 446                        if (@diff) {
 447                                @finish = rebase_cmd();
 448                                print STDERR "W: $d and ", $gs->refname,
 449                                             " differ, using @finish:\n",
 450                                             join("\n", @diff), "\n";
 451                        } else {
 452                                print "No changes between current HEAD and ",
 453                                      $gs->refname,
 454                                      "\nResetting to the latest ",
 455                                      $gs->refname, "\n";
 456                                @finish = qw/reset --mixed/;
 457                        }
 458                        command_noisy(@finish, $gs->refname);
 459                        if (@diff) {
 460                                @refs = ();
 461                                my ($url_, $rev_, $uuid_, $gs_) =
 462                                              working_head_info($head, \@refs);
 463                                my ($linear_refs_, $parents_) =
 464                                              linearize_history($gs_, \@refs);
 465                                if (scalar(@$linear_refs) !=
 466                                    scalar(@$linear_refs_)) {
 467                                        fatal "# of revisions changed ",
 468                                          "\nbefore:\n",
 469                                          join("\n", @$linear_refs),
 470                                          "\n\nafter:\n",
 471                                          join("\n", @$linear_refs_), "\n",
 472                                          'If you are attempting to commit ',
 473                                          "merges, try running:\n\t",
 474                                          'git rebase --interactive',
 475                                          '--preserve-merges ',
 476                                          $gs->refname,
 477                                          "\nBefore dcommitting";
 478                                }
 479                                if ($url_ ne $url) {
 480                                        fatal "URL mismatch after rebase: ",
 481                                              "$url_ != $url";
 482                                }
 483                                if ($uuid_ ne $uuid) {
 484                                        fatal "uuid mismatch after rebase: ",
 485                                              "$uuid_ != $uuid";
 486                                }
 487                                # remap parents
 488                                my (%p, @l, $i);
 489                                for ($i = 0; $i < scalar @$linear_refs; $i++) {
 490                                        my $new = $linear_refs_->[$i] or next;
 491                                        $p{$new} =
 492                                                $parents->{$linear_refs->[$i]};
 493                                        push @l, $new;
 494                                }
 495                                $parents = \%p;
 496                                $linear_refs = \@l;
 497                        }
 498                        $last_rev = $cmt_rev;
 499                }
 500        }
 501}
 502
 503sub cmd_find_rev {
 504        my $revision_or_hash = shift;
 505        my $result;
 506        if ($revision_or_hash =~ /^r\d+$/) {
 507                my $head = shift;
 508                $head ||= 'HEAD';
 509                my @refs;
 510                my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
 511                unless ($gs) {
 512                        die "Unable to determine upstream SVN information from ",
 513                            "$head history\n";
 514                }
 515                my $desired_revision = substr($revision_or_hash, 1);
 516                $result = $gs->rev_db_get($desired_revision);
 517        } else {
 518                my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
 519                $result = $rev;
 520        }
 521        print "$result\n" if $result;
 522}
 523
 524sub cmd_rebase {
 525        command_noisy(qw/update-index --refresh/);
 526        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 527        unless ($gs) {
 528                die "Unable to determine upstream SVN information from ",
 529                    "working tree history\n";
 530        }
 531        if (command(qw/diff-index HEAD --/)) {
 532                print STDERR "Cannot rebase with uncommited changes:\n";
 533                command_noisy('status');
 534                exit 1;
 535        }
 536        unless ($_local) {
 537                $_fetch_all ? $gs->fetch_all : $gs->fetch;
 538        }
 539        command_noisy(rebase_cmd(), $gs->refname);
 540}
 541
 542sub cmd_show_ignore {
 543        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 544        $gs ||= Git::SVN->new;
 545        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
 546        $gs->prop_walk($gs->{path}, $r, sub {
 547                my ($gs, $path, $props) = @_;
 548                print STDOUT "\n# $path\n";
 549                my $s = $props->{'svn:ignore'} or return;
 550                $s =~ s/[\r\n]+/\n/g;
 551                chomp $s;
 552                $s =~ s#^#$path#gm;
 553                print STDOUT "$s\n";
 554        });
 555}
 556
 557sub cmd_create_ignore {
 558        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 559        $gs ||= Git::SVN->new;
 560        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
 561        $gs->prop_walk($gs->{path}, $r, sub {
 562                my ($gs, $path, $props) = @_;
 563                # $path is of the form /path/to/dir/
 564                my $ignore = '.' . $path . '.gitignore';
 565                my $s = $props->{'svn:ignore'} or return;
 566                open(GITIGNORE, '>', $ignore)
 567                  or fatal("Failed to open `$ignore' for writing: $!");
 568                $s =~ s/[\r\n]+/\n/g;
 569                chomp $s;
 570                # Prefix all patterns so that the ignore doesn't apply
 571                # to sub-directories.
 572                $s =~ s#^#/#gm;
 573                print GITIGNORE "$s\n";
 574                close(GITIGNORE)
 575                  or fatal("Failed to close `$ignore': $!");
 576                command_noisy('add', $ignore);
 577        });
 578}
 579
 580# get_svnprops(PATH)
 581# ------------------
 582# Helper for cmd_propget and cmd_proplist below.
 583sub get_svnprops {
 584        my $path = shift;
 585        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 586        $gs ||= Git::SVN->new;
 587
 588        # prefix THE PATH by the sub-directory from which the user
 589        # invoked us.
 590        $path = $cmd_dir_prefix . $path;
 591        fatal("No such file or directory: $path") unless -e $path;
 592        my $is_dir = -d $path ? 1 : 0;
 593        $path = $gs->{path} . '/' . $path;
 594
 595        # canonicalize the path (otherwise libsvn will abort or fail to
 596        # find the file)
 597        # File::Spec->canonpath doesn't collapse x/../y into y (for a
 598        # good reason), so let's do this manually.
 599        $path =~ s#/+#/#g;
 600        $path =~ s#/\.(?:/|$)#/#g;
 601        $path =~ s#/[^/]+/\.\.##g;
 602        $path =~ s#/$##g;
 603
 604        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
 605        my $props;
 606        if ($is_dir) {
 607                (undef, undef, $props) = $gs->ra->get_dir($path, $r);
 608        }
 609        else {
 610                (undef, $props) = $gs->ra->get_file($path, $r, undef);
 611        }
 612        return $props;
 613}
 614
 615# cmd_propget (PROP, PATH)
 616# ------------------------
 617# Print the SVN property PROP for PATH.
 618sub cmd_propget {
 619        my ($prop, $path) = @_;
 620        $path = '.' if not defined $path;
 621        usage(1) if not defined $prop;
 622        my $props = get_svnprops($path);
 623        if (not defined $props->{$prop}) {
 624                fatal("`$path' does not have a `$prop' SVN property.");
 625        }
 626        print $props->{$prop} . "\n";
 627}
 628
 629# cmd_proplist (PATH)
 630# -------------------
 631# Print the list of SVN properties for PATH.
 632sub cmd_proplist {
 633        my $path = shift;
 634        $path = '.' if not defined $path;
 635        my $props = get_svnprops($path);
 636        print "Properties on '$path':\n";
 637        foreach (sort keys %{$props}) {
 638                print "  $_\n";
 639        }
 640}
 641
 642sub cmd_multi_init {
 643        my $url = shift;
 644        unless (defined $_trunk || defined $_branches || defined $_tags) {
 645                usage(1);
 646        }
 647
 648        # there are currently some bugs that prevent multi-init/multi-fetch
 649        # setups from working well without this.
 650        $Git::SVN::_minimize_url = 1;
 651
 652        $_prefix = '' unless defined $_prefix;
 653        if (defined $url) {
 654                $url =~ s#/+$##;
 655                init_subdir(@_);
 656        }
 657        do_git_init_db();
 658        if (defined $_trunk) {
 659                my $trunk_ref = $_prefix . 'trunk';
 660                # try both old-style and new-style lookups:
 661                my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
 662                unless ($gs_trunk) {
 663                        my ($trunk_url, $trunk_path) =
 664                                              complete_svn_url($url, $_trunk);
 665                        $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
 666                                                   undef, $trunk_ref);
 667                }
 668        }
 669        return unless defined $_branches || defined $_tags;
 670        my $ra = $url ? Git::SVN::Ra->new($url) : undef;
 671        complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
 672        complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
 673}
 674
 675sub cmd_multi_fetch {
 676        my $remotes = Git::SVN::read_all_remotes();
 677        foreach my $repo_id (sort keys %$remotes) {
 678                if ($remotes->{$repo_id}->{url}) {
 679                        Git::SVN::fetch_all($repo_id, $remotes);
 680                }
 681        }
 682}
 683
 684# this command is special because it requires no metadata
 685sub cmd_commit_diff {
 686        my ($ta, $tb, $url) = @_;
 687        my $usage = "Usage: $0 commit-diff -r<revision> ".
 688                    "<tree-ish> <tree-ish> [<URL>]";
 689        fatal($usage) if (!defined $ta || !defined $tb);
 690        my $svn_path;
 691        if (!defined $url) {
 692                my $gs = eval { Git::SVN->new };
 693                if (!$gs) {
 694                        fatal("Needed URL or usable git-svn --id in ",
 695                              "the command-line\n", $usage);
 696                }
 697                $url = $gs->{url};
 698                $svn_path = $gs->{path};
 699        }
 700        unless (defined $_revision) {
 701                fatal("-r|--revision is a required argument\n", $usage);
 702        }
 703        if (defined $_message && defined $_file) {
 704                fatal("Both --message/-m and --file/-F specified ",
 705                      "for the commit message.\n",
 706                      "I have no idea what you mean");
 707        }
 708        if (defined $_file) {
 709                $_message = file_to_s($_file);
 710        } else {
 711                $_message ||= get_commit_entry($tb)->{log};
 712        }
 713        my $ra ||= Git::SVN::Ra->new($url);
 714        $svn_path ||= $ra->{svn_path};
 715        my $r = $_revision;
 716        if ($r eq 'HEAD') {
 717                $r = $ra->get_latest_revnum;
 718        } elsif ($r !~ /^\d+$/) {
 719                die "revision argument: $r not understood by git-svn\n";
 720        }
 721        my %ed_opts = ( r => $r,
 722                        log => $_message,
 723                        ra => $ra,
 724                        tree_a => $ta,
 725                        tree_b => $tb,
 726                        editor_cb => sub { print "Committed r$_[0]\n" },
 727                        svn_path => $svn_path );
 728        if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
 729                print "No changes\n$ta == $tb\n";
 730        }
 731}
 732
 733########################### utility functions #########################
 734
 735sub rebase_cmd {
 736        my @cmd = qw/rebase/;
 737        push @cmd, '-v' if $_verbose;
 738        push @cmd, qw/--merge/ if $_merge;
 739        push @cmd, "--strategy=$_strategy" if $_strategy;
 740        @cmd;
 741}
 742
 743sub post_fetch_checkout {
 744        return if $_no_checkout;
 745        my $gs = $Git::SVN::_head or return;
 746        return if verify_ref('refs/heads/master^0');
 747
 748        my $valid_head = verify_ref('HEAD^0');
 749        command_noisy(qw(update-ref refs/heads/master), $gs->refname);
 750        return if ($valid_head || !verify_ref('HEAD^0'));
 751
 752        return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
 753        my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
 754        return if -f $index;
 755
 756        return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
 757        return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
 758        command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
 759        print STDERR "Checked out HEAD:\n  ",
 760                     $gs->full_url, " r", $gs->last_rev, "\n";
 761}
 762
 763sub complete_svn_url {
 764        my ($url, $path) = @_;
 765        $path =~ s#/+$##;
 766        if ($path !~ m#^[a-z\+]+://#) {
 767                if (!defined $url || $url !~ m#^[a-z\+]+://#) {
 768                        fatal("E: '$path' is not a complete URL ",
 769                              "and a separate URL is not specified");
 770                }
 771                return ($url, $path);
 772        }
 773        return ($path, '');
 774}
 775
 776sub complete_url_ls_init {
 777        my ($ra, $repo_path, $switch, $pfx) = @_;
 778        unless ($repo_path) {
 779                print STDERR "W: $switch not specified\n";
 780                return;
 781        }
 782        $repo_path =~ s#/+$##;
 783        if ($repo_path =~ m#^[a-z\+]+://#) {
 784                $ra = Git::SVN::Ra->new($repo_path);
 785                $repo_path = '';
 786        } else {
 787                $repo_path =~ s#^/+##;
 788                unless ($ra) {
 789                        fatal("E: '$repo_path' is not a complete URL ",
 790                              "and a separate URL is not specified");
 791                }
 792        }
 793        my $url = $ra->{url};
 794        my $gs = Git::SVN->init($url, undef, undef, undef, 1);
 795        my $k = "svn-remote.$gs->{repo_id}.url";
 796        my $orig_url = eval { command_oneline(qw/config --get/, $k) };
 797        if ($orig_url && ($orig_url ne $gs->{url})) {
 798                die "$k already set: $orig_url\n",
 799                    "wanted to set to: $gs->{url}\n";
 800        }
 801        command_oneline('config', $k, $gs->{url}) unless $orig_url;
 802        my $remote_path = "$ra->{svn_path}/$repo_path/*";
 803        $remote_path =~ s#/+#/#g;
 804        $remote_path =~ s#^/##g;
 805        my ($n) = ($switch =~ /^--(\w+)/);
 806        if (length $pfx && $pfx !~ m#/$#) {
 807                die "--prefix='$pfx' must have a trailing slash '/'\n";
 808        }
 809        command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
 810                                "$remote_path:refs/remotes/$pfx*");
 811}
 812
 813sub verify_ref {
 814        my ($ref) = @_;
 815        eval { command_oneline([ 'rev-parse', '--verify', $ref ],
 816                               { STDERR => 0 }); };
 817}
 818
 819sub get_tree_from_treeish {
 820        my ($treeish) = @_;
 821        # $treeish can be a symbolic ref, too:
 822        my $type = command_oneline(qw/cat-file -t/, $treeish);
 823        my $expected;
 824        while ($type eq 'tag') {
 825                ($treeish, $type) = command(qw/cat-file tag/, $treeish);
 826        }
 827        if ($type eq 'commit') {
 828                $expected = (grep /^tree /, command(qw/cat-file commit/,
 829                                                    $treeish))[0];
 830                ($expected) = ($expected =~ /^tree ($sha1)$/o);
 831                die "Unable to get tree from $treeish\n" unless $expected;
 832        } elsif ($type eq 'tree') {
 833                $expected = $treeish;
 834        } else {
 835                die "$treeish is a $type, expected tree, tag or commit\n";
 836        }
 837        return $expected;
 838}
 839
 840sub get_commit_entry {
 841        my ($treeish) = shift;
 842        my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
 843        my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
 844        my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
 845        open my $log_fh, '>', $commit_editmsg or croak $!;
 846
 847        my $type = command_oneline(qw/cat-file -t/, $treeish);
 848        if ($type eq 'commit' || $type eq 'tag') {
 849                my ($msg_fh, $ctx) = command_output_pipe('cat-file',
 850                                                         $type, $treeish);
 851                my $in_msg = 0;
 852                while (<$msg_fh>) {
 853                        if (!$in_msg) {
 854                                $in_msg = 1 if (/^\s*$/);
 855                        } elsif (/^git-svn-id: /) {
 856                                # skip this for now, we regenerate the
 857                                # correct one on re-fetch anyways
 858                                # TODO: set *:merge properties or like...
 859                        } else {
 860                                print $log_fh $_ or croak $!;
 861                        }
 862                }
 863                command_close_pipe($msg_fh, $ctx);
 864        }
 865        close $log_fh or croak $!;
 866
 867        if ($_edit || ($type eq 'tree')) {
 868                my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
 869                # TODO: strip out spaces, comments, like git-commit.sh
 870                system($editor, $commit_editmsg);
 871        }
 872        rename $commit_editmsg, $commit_msg or croak $!;
 873        open $log_fh, '<', $commit_msg or croak $!;
 874        { local $/; chomp($log_entry{log} = <$log_fh>); }
 875        close $log_fh or croak $!;
 876        unlink $commit_msg;
 877        \%log_entry;
 878}
 879
 880sub s_to_file {
 881        my ($str, $file, $mode) = @_;
 882        open my $fd,'>',$file or croak $!;
 883        print $fd $str,"\n" or croak $!;
 884        close $fd or croak $!;
 885        chmod ($mode &~ umask, $file) if (defined $mode);
 886}
 887
 888sub file_to_s {
 889        my $file = shift;
 890        open my $fd,'<',$file or croak "$!: file: $file\n";
 891        local $/;
 892        my $ret = <$fd>;
 893        close $fd or croak $!;
 894        $ret =~ s/\s*$//s;
 895        return $ret;
 896}
 897
 898# '<svn username> = real-name <email address>' mapping based on git-svnimport:
 899sub load_authors {
 900        open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
 901        my $log = $cmd eq 'log';
 902        while (<$authors>) {
 903                chomp;
 904                next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
 905                my ($user, $name, $email) = ($1, $2, $3);
 906                if ($log) {
 907                        $Git::SVN::Log::rusers{"$name <$email>"} = $user;
 908                } else {
 909                        $users{$user} = [$name, $email];
 910                }
 911        }
 912        close $authors or croak $!;
 913}
 914
 915# convert GetOpt::Long specs for use by git-config
 916sub read_repo_config {
 917        return unless -d $ENV{GIT_DIR};
 918        my $opts = shift;
 919        my @config_only;
 920        foreach my $o (keys %$opts) {
 921                # if we have mixedCase and a long option-only, then
 922                # it's a config-only variable that we don't need for
 923                # the command-line.
 924                push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
 925                my $v = $opts->{$o};
 926                my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
 927                $key =~ s/-//g;
 928                my $arg = 'git-config';
 929                $arg .= ' --int' if ($o =~ /[:=]i$/);
 930                $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
 931                if (ref $v eq 'ARRAY') {
 932                        chomp(my @tmp = `$arg --get-all svn.$key`);
 933                        @$v = @tmp if @tmp;
 934                } else {
 935                        chomp(my $tmp = `$arg --get svn.$key`);
 936                        if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
 937                                $$v = $tmp;
 938                        }
 939                }
 940        }
 941        delete @$opts{@config_only} if @config_only;
 942}
 943
 944sub extract_metadata {
 945        my $id = shift or return (undef, undef, undef);
 946        my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
 947                                                        \s([a-f\d\-]+)$/x);
 948        if (!defined $rev || !$uuid || !$url) {
 949                # some of the original repositories I made had
 950                # identifiers like this:
 951                ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
 952        }
 953        return ($url, $rev, $uuid);
 954}
 955
 956sub cmt_metadata {
 957        return extract_metadata((grep(/^git-svn-id: /,
 958                command(qw/cat-file commit/, shift)))[-1]);
 959}
 960
 961sub working_head_info {
 962        my ($head, $refs) = @_;
 963        my @args = ('log', '--no-color', '--first-parent');
 964        my ($fh, $ctx) = command_output_pipe(@args, $head);
 965        my $hash;
 966        my %max;
 967        while (<$fh>) {
 968                if ( m{^commit ($::sha1)$} ) {
 969                        unshift @$refs, $hash if $hash and $refs;
 970                        $hash = $1;
 971                        next;
 972                }
 973                next unless s{^\s*(git-svn-id:)}{$1};
 974                my ($url, $rev, $uuid) = extract_metadata($_);
 975                if (defined $url && defined $rev) {
 976                        next if $max{$url} and $max{$url} < $rev;
 977                        if (my $gs = Git::SVN->find_by_url($url)) {
 978                                my $c = $gs->rev_db_get($rev);
 979                                if ($c && $c eq $hash) {
 980                                        close $fh; # break the pipe
 981                                        return ($url, $rev, $uuid, $gs);
 982                                } else {
 983                                        $max{$url} ||= $gs->rev_db_max;
 984                                }
 985                        }
 986                }
 987        }
 988        command_close_pipe($fh, $ctx);
 989        (undef, undef, undef, undef);
 990}
 991
 992sub read_commit_parents {
 993        my ($parents, $c) = @_;
 994        chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
 995        $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
 996        @{$parents->{$c}} = split(/ /, $p);
 997}
 998
 999sub linearize_history {
1000        my ($gs, $refs) = @_;
1001        my %parents;
1002        foreach my $c (@$refs) {
1003                read_commit_parents(\%parents, $c);
1004        }
1005
1006        my @linear_refs;
1007        my %skip = ();
1008        my $last_svn_commit = $gs->last_commit;
1009        foreach my $c (reverse @$refs) {
1010                next if $c eq $last_svn_commit;
1011                last if $skip{$c};
1012
1013                unshift @linear_refs, $c;
1014                $skip{$c} = 1;
1015
1016                # we only want the first parent to diff against for linear
1017                # history, we save the rest to inject when we finalize the
1018                # svn commit
1019                my $fp_a = verify_ref("$c~1");
1020                my $fp_b = shift @{$parents{$c}} if $parents{$c};
1021                if (!$fp_a || !$fp_b) {
1022                        die "Commit $c\n",
1023                            "has no parent commit, and therefore ",
1024                            "nothing to diff against.\n",
1025                            "You should be working from a repository ",
1026                            "originally created by git-svn\n";
1027                }
1028                if ($fp_a ne $fp_b) {
1029                        die "$c~1 = $fp_a, however parsing commit $c ",
1030                            "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1031                }
1032
1033                foreach my $p (@{$parents{$c}}) {
1034                        $skip{$p} = 1;
1035                }
1036        }
1037        (\@linear_refs, \%parents);
1038}
1039
1040package Git::SVN;
1041use strict;
1042use warnings;
1043use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1044            $_repack $_repack_flags $_use_svm_props $_head
1045            $_use_svnsync_props $no_reuse_existing $_minimize_url/;
1046use Carp qw/croak/;
1047use File::Path qw/mkpath/;
1048use File::Copy qw/copy/;
1049use IPC::Open3;
1050
1051my $_repack_nr;
1052# properties that we do not log:
1053my %SKIP_PROP;
1054BEGIN {
1055        %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1056                                        svn:special svn:executable
1057                                        svn:entry:committed-rev
1058                                        svn:entry:last-author
1059                                        svn:entry:uuid
1060                                        svn:entry:committed-date/;
1061
1062        # some options are read globally, but can be overridden locally
1063        # per [svn-remote "..."] section.  Command-line options will *NOT*
1064        # override options set in an [svn-remote "..."] section
1065        no strict 'refs';
1066        for my $option (qw/follow_parent no_metadata use_svm_props
1067                           use_svnsync_props/) {
1068                my $key = $option;
1069                $key =~ tr/_//d;
1070                my $prop = "-$option";
1071                *$option = sub {
1072                        my ($self) = @_;
1073                        return $self->{$prop} if exists $self->{$prop};
1074                        my $k = "svn-remote.$self->{repo_id}.$key";
1075                        eval { command_oneline(qw/config --get/, $k) };
1076                        if ($@) {
1077                                $self->{$prop} = ${"Git::SVN::_$option"};
1078                        } else {
1079                                my $v = command_oneline(qw/config --bool/,$k);
1080                                $self->{$prop} = $v eq 'false' ? 0 : 1;
1081                        }
1082                        return $self->{$prop};
1083                }
1084        }
1085}
1086
1087my %LOCKFILES;
1088END { unlink keys %LOCKFILES if %LOCKFILES }
1089
1090sub resolve_local_globs {
1091        my ($url, $fetch, $glob_spec) = @_;
1092        return unless defined $glob_spec;
1093        my $ref = $glob_spec->{ref};
1094        my $path = $glob_spec->{path};
1095        foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1096                next unless m#^refs/remotes/$ref->{regex}$#;
1097                my $p = $1;
1098                my $pathname = desanitize_refname($path->full_path($p));
1099                my $refname = desanitize_refname($ref->full_path($p));
1100                if (my $existing = $fetch->{$pathname}) {
1101                        if ($existing ne $refname) {
1102                                die "Refspec conflict:\n",
1103                                    "existing: refs/remotes/$existing\n",
1104                                    " globbed: refs/remotes/$refname\n";
1105                        }
1106                        my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1107                        $u =~ s!^\Q$url\E(/|$)!! or die
1108                          "refs/remotes/$refname: '$url' not found in '$u'\n";
1109                        if ($pathname ne $u) {
1110                                warn "W: Refspec glob conflict ",
1111                                     "(ref: refs/remotes/$refname):\n",
1112                                     "expected path: $pathname\n",
1113                                     "    real path: $u\n",
1114                                     "Continuing ahead with $u\n";
1115                                next;
1116                        }
1117                } else {
1118                        $fetch->{$pathname} = $refname;
1119                }
1120        }
1121}
1122
1123sub parse_revision_argument {
1124        my ($base, $head) = @_;
1125        if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1126                return ($base, $head);
1127        }
1128        return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1129        return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1130        return ($head, $head) if ($::_revision eq 'HEAD');
1131        return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1132        return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1133        die "revision argument: $::_revision not understood by git-svn\n";
1134}
1135
1136sub fetch_all {
1137        my ($repo_id, $remotes) = @_;
1138        if (ref $repo_id) {
1139                my $gs = $repo_id;
1140                $repo_id = undef;
1141                $repo_id = $gs->{repo_id};
1142        }
1143        $remotes ||= read_all_remotes();
1144        my $remote = $remotes->{$repo_id} or
1145                     die "[svn-remote \"$repo_id\"] unknown\n";
1146        my $fetch = $remote->{fetch};
1147        my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1148        my (@gs, @globs);
1149        my $ra = Git::SVN::Ra->new($url);
1150        my $uuid = $ra->get_uuid;
1151        my $head = $ra->get_latest_revnum;
1152        my $base = defined $fetch ? $head : 0;
1153
1154        # read the max revs for wildcard expansion (branches/*, tags/*)
1155        foreach my $t (qw/branches tags/) {
1156                defined $remote->{$t} or next;
1157                push @globs, $remote->{$t};
1158                my $max_rev = eval { tmp_config(qw/--int --get/,
1159                                         "svn-remote.$repo_id.${t}-maxRev") };
1160                if (defined $max_rev && ($max_rev < $base)) {
1161                        $base = $max_rev;
1162                } elsif (!defined $max_rev) {
1163                        $base = 0;
1164                }
1165        }
1166
1167        if ($fetch) {
1168                foreach my $p (sort keys %$fetch) {
1169                        my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1170                        my $lr = $gs->rev_db_max;
1171                        if (defined $lr) {
1172                                $base = $lr if ($lr < $base);
1173                        }
1174                        push @gs, $gs;
1175                }
1176        }
1177
1178        ($base, $head) = parse_revision_argument($base, $head);
1179        $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1180}
1181
1182sub read_all_remotes {
1183        my $r = {};
1184        foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1185                if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1186                        my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1187                        $local_ref =~ s{^/}{};
1188                        $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1189                } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1190                        $r->{$1}->{url} = $2;
1191                } elsif (m!^(.+)\.(branches|tags)=
1192                           (.*):refs/remotes/(.+)\s*$/!x) {
1193                        my ($p, $g) = ($3, $4);
1194                        my $rs = $r->{$1}->{$2} = {
1195                                          t => $2,
1196                                          remote => $1,
1197                                          path => Git::SVN::GlobSpec->new($p),
1198                                          ref => Git::SVN::GlobSpec->new($g) };
1199                        if (length($rs->{ref}->{right}) != 0) {
1200                                die "The '*' glob character must be the last ",
1201                                    "character of '$g'\n";
1202                        }
1203                }
1204        }
1205        $r;
1206}
1207
1208sub init_vars {
1209        if (defined $_repack) {
1210                $_repack = 1000 if ($_repack <= 0);
1211                $_repack_nr = $_repack;
1212                $_repack_flags ||= '-d';
1213        }
1214}
1215
1216sub verify_remotes_sanity {
1217        return unless -d $ENV{GIT_DIR};
1218        my %seen;
1219        foreach (command(qw/config -l/)) {
1220                if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1221                        if ($seen{$1}) {
1222                                die "Remote ref refs/remote/$1 is tracked by",
1223                                    "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
1224                                    "Please resolve this ambiguity in ",
1225                                    "your git configuration file before ",
1226                                    "continuing\n";
1227                        }
1228                        $seen{$1} = $_;
1229                }
1230        }
1231}
1232
1233# we allow more chars than remotes2config.sh...
1234sub sanitize_remote_name {
1235        my ($name) = @_;
1236        $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1237        $name;
1238}
1239
1240sub find_existing_remote {
1241        my ($url, $remotes) = @_;
1242        return undef if $no_reuse_existing;
1243        my $existing;
1244        foreach my $repo_id (keys %$remotes) {
1245                my $u = $remotes->{$repo_id}->{url} or next;
1246                next if $u ne $url;
1247                $existing = $repo_id;
1248                last;
1249        }
1250        $existing;
1251}
1252
1253sub init_remote_config {
1254        my ($self, $url, $no_write) = @_;
1255        $url =~ s!/+$!!; # strip trailing slash
1256        my $r = read_all_remotes();
1257        my $existing = find_existing_remote($url, $r);
1258        if ($existing) {
1259                unless ($no_write) {
1260                        print STDERR "Using existing ",
1261                                     "[svn-remote \"$existing\"]\n";
1262                }
1263                $self->{repo_id} = $existing;
1264        } elsif ($_minimize_url) {
1265                my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1266                $existing = find_existing_remote($min_url, $r);
1267                if ($existing) {
1268                        unless ($no_write) {
1269                                print STDERR "Using existing ",
1270                                             "[svn-remote \"$existing\"]\n";
1271                        }
1272                        $self->{repo_id} = $existing;
1273                }
1274                if ($min_url ne $url) {
1275                        unless ($no_write) {
1276                                print STDERR "Using higher level of URL: ",
1277                                             "$url => $min_url\n";
1278                        }
1279                        my $old_path = $self->{path};
1280                        $self->{path} = $url;
1281                        $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1282                        if (length $old_path) {
1283                                $self->{path} .= "/$old_path";
1284                        }
1285                        $url = $min_url;
1286                }
1287        }
1288        my $orig_url;
1289        if (!$existing) {
1290                # verify that we aren't overwriting anything:
1291                $orig_url = eval {
1292                        command_oneline('config', '--get',
1293                                        "svn-remote.$self->{repo_id}.url")
1294                };
1295                if ($orig_url && ($orig_url ne $url)) {
1296                        die "svn-remote.$self->{repo_id}.url already set: ",
1297                            "$orig_url\nwanted to set to: $url\n";
1298                }
1299        }
1300        my ($xrepo_id, $xpath) = find_ref($self->refname);
1301        if (defined $xpath) {
1302                die "svn-remote.$xrepo_id.fetch already set to track ",
1303                    "$xpath:refs/remotes/", $self->refname, "\n";
1304        }
1305        unless ($no_write) {
1306                command_noisy('config',
1307                              "svn-remote.$self->{repo_id}.url", $url);
1308                $self->{path} =~ s{^/}{};
1309                command_noisy('config', '--add',
1310                              "svn-remote.$self->{repo_id}.fetch",
1311                              "$self->{path}:".$self->refname);
1312        }
1313        $self->{url} = $url;
1314}
1315
1316sub find_by_url { # repos_root and, path are optional
1317        my ($class, $full_url, $repos_root, $path) = @_;
1318
1319        return undef unless defined $full_url;
1320        remove_username($full_url);
1321        remove_username($repos_root) if defined $repos_root;
1322        my $remotes = read_all_remotes();
1323        if (defined $full_url && defined $repos_root && !defined $path) {
1324                $path = $full_url;
1325                $path =~ s#^\Q$repos_root\E(?:/|$)##;
1326        }
1327        foreach my $repo_id (keys %$remotes) {
1328                my $u = $remotes->{$repo_id}->{url} or next;
1329                remove_username($u);
1330                next if defined $repos_root && $repos_root ne $u;
1331
1332                my $fetch = $remotes->{$repo_id}->{fetch} || {};
1333                foreach (qw/branches tags/) {
1334                        resolve_local_globs($u, $fetch,
1335                                            $remotes->{$repo_id}->{$_});
1336                }
1337                my $p = $path;
1338                unless (defined $p) {
1339                        $p = $full_url;
1340                        $p =~ s#^\Q$u\E(?:/|$)## or next;
1341                }
1342                foreach my $f (keys %$fetch) {
1343                        next if $f ne $p;
1344                        return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1345                }
1346        }
1347        undef;
1348}
1349
1350sub init {
1351        my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1352        my $self = _new($class, $repo_id, $ref_id, $path);
1353        if (defined $url) {
1354                $self->init_remote_config($url, $no_write);
1355        }
1356        $self;
1357}
1358
1359sub find_ref {
1360        my ($ref_id) = @_;
1361        foreach (command(qw/config -l/)) {
1362                next unless m!^svn-remote\.(.+)\.fetch=
1363                              \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1364                my ($repo_id, $path, $ref) = ($1, $2, $3);
1365                if ($ref eq $ref_id) {
1366                        $path = '' if ($path =~ m#^\./?#);
1367                        return ($repo_id, $path);
1368                }
1369        }
1370        (undef, undef, undef);
1371}
1372
1373sub new {
1374        my ($class, $ref_id, $repo_id, $path) = @_;
1375        if (defined $ref_id && !defined $repo_id && !defined $path) {
1376                ($repo_id, $path) = find_ref($ref_id);
1377                if (!defined $repo_id) {
1378                        die "Could not find a \"svn-remote.*.fetch\" key ",
1379                            "in the repository configuration matching: ",
1380                            "refs/remotes/$ref_id\n";
1381                }
1382        }
1383        my $self = _new($class, $repo_id, $ref_id, $path);
1384        if (!defined $self->{path} || !length $self->{path}) {
1385                my $fetch = command_oneline('config', '--get',
1386                                            "svn-remote.$repo_id.fetch",
1387                                            ":refs/remotes/$ref_id\$") or
1388                     die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1389                         "\":refs/remotes/$ref_id\$\" in config\n";
1390                ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1391        }
1392        $self->{url} = command_oneline('config', '--get',
1393                                       "svn-remote.$repo_id.url") or
1394                  die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1395        $self->rebuild;
1396        $self;
1397}
1398
1399sub refname {
1400        my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1401
1402        # It cannot end with a slash /, we'll throw up on this because
1403        # SVN can't have directories with a slash in their name, either:
1404        if ($refname =~ m{/$}) {
1405                die "ref: '$refname' ends with a trailing slash, this is ",
1406                    "not permitted by git nor Subversion\n";
1407        }
1408
1409        # It cannot have ASCII control character space, tilde ~, caret ^,
1410        # colon :, question-mark ?, asterisk *, space, or open bracket [
1411        # anywhere.
1412        #
1413        # Additionally, % must be escaped because it is used for escaping
1414        # and we want our escaped refname to be reversible
1415        $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1416
1417        # no slash-separated component can begin with a dot .
1418        # /.* becomes /%2E*
1419        $refname =~ s{/\.}{/%2E}g;
1420
1421        # It cannot have two consecutive dots .. anywhere
1422        # .. becomes %2E%2E
1423        $refname =~ s{\.\.}{%2E%2E}g;
1424
1425        return $refname;
1426}
1427
1428sub desanitize_refname {
1429        my ($refname) = @_;
1430        $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1431        return $refname;
1432}
1433
1434sub svm_uuid {
1435        my ($self) = @_;
1436        return $self->{svm}->{uuid} if $self->svm;
1437        $self->ra;
1438        unless ($self->{svm}) {
1439                die "SVM UUID not cached, and reading remotely failed\n";
1440        }
1441        $self->{svm}->{uuid};
1442}
1443
1444sub svm {
1445        my ($self) = @_;
1446        return $self->{svm} if $self->{svm};
1447        my $svm;
1448        # see if we have it in our config, first:
1449        eval {
1450                my $section = "svn-remote.$self->{repo_id}";
1451                $svm = {
1452                  source => tmp_config('--get', "$section.svm-source"),
1453                  uuid => tmp_config('--get', "$section.svm-uuid"),
1454                  replace => tmp_config('--get', "$section.svm-replace"),
1455                }
1456        };
1457        if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1458                $self->{svm} = $svm;
1459        }
1460        $self->{svm};
1461}
1462
1463sub _set_svm_vars {
1464        my ($self, $ra) = @_;
1465        return $ra if $self->svm;
1466
1467        my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1468                    "(svm:source, svm:uuid) ",
1469                    "from the following URLs:\n" );
1470        sub read_svm_props {
1471                my ($self, $ra, $path, $r) = @_;
1472                my $props = ($ra->get_dir($path, $r))[2];
1473                my $src = $props->{'svm:source'};
1474                my $uuid = $props->{'svm:uuid'};
1475                return undef if (!$src || !$uuid);
1476
1477                chomp($src, $uuid);
1478
1479                $uuid =~ m{^[0-9a-f\-]{30,}$}
1480                    or die "doesn't look right - svm:uuid is '$uuid'\n";
1481
1482                # the '!' is used to mark the repos_root!/relative/path
1483                $src =~ s{/?!/?}{/};
1484                $src =~ s{/+$}{}; # no trailing slashes please
1485                # username is of no interest
1486                $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1487
1488                my $replace = $ra->{url};
1489                $replace .= "/$path" if length $path;
1490
1491                my $section = "svn-remote.$self->{repo_id}";
1492                tmp_config("$section.svm-source", $src);
1493                tmp_config("$section.svm-replace", $replace);
1494                tmp_config("$section.svm-uuid", $uuid);
1495                $self->{svm} = {
1496                        source => $src,
1497                        uuid => $uuid,
1498                        replace => $replace
1499                };
1500        }
1501
1502        my $r = $ra->get_latest_revnum;
1503        my $path = $self->{path};
1504        my %tried;
1505        while (length $path) {
1506                unless ($tried{"$self->{url}/$path"}) {
1507                        return $ra if $self->read_svm_props($ra, $path, $r);
1508                        $tried{"$self->{url}/$path"} = 1;
1509                }
1510                $path =~ s#/?[^/]+$##;
1511        }
1512        die "Path: '$path' should be ''\n" if $path ne '';
1513        return $ra if $self->read_svm_props($ra, $path, $r);
1514        $tried{"$self->{url}/$path"} = 1;
1515
1516        if ($ra->{repos_root} eq $self->{url}) {
1517                die @err, (map { "  $_\n" } keys %tried), "\n";
1518        }
1519
1520        # nope, make sure we're connected to the repository root:
1521        my $ok;
1522        my @tried_b;
1523        $path = $ra->{svn_path};
1524        $ra = Git::SVN::Ra->new($ra->{repos_root});
1525        while (length $path) {
1526                unless ($tried{"$ra->{url}/$path"}) {
1527                        $ok = $self->read_svm_props($ra, $path, $r);
1528                        last if $ok;
1529                        $tried{"$ra->{url}/$path"} = 1;
1530                }
1531                $path =~ s#/?[^/]+$##;
1532        }
1533        die "Path: '$path' should be ''\n" if $path ne '';
1534        $ok ||= $self->read_svm_props($ra, $path, $r);
1535        $tried{"$ra->{url}/$path"} = 1;
1536        if (!$ok) {
1537                die @err, (map { "  $_\n" } keys %tried), "\n";
1538        }
1539        Git::SVN::Ra->new($self->{url});
1540}
1541
1542sub svnsync {
1543        my ($self) = @_;
1544        return $self->{svnsync} if $self->{svnsync};
1545
1546        if ($self->no_metadata) {
1547                die "Can't have both 'noMetadata' and ",
1548                    "'useSvnsyncProps' options set!\n";
1549        }
1550        if ($self->rewrite_root) {
1551                die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1552                    "options set!\n";
1553        }
1554
1555        my $svnsync;
1556        # see if we have it in our config, first:
1557        eval {
1558                my $section = "svn-remote.$self->{repo_id}";
1559                $svnsync = {
1560                  url => tmp_config('--get', "$section.svnsync-url"),
1561                  uuid => tmp_config('--get', "$section.svnsync-uuid"),
1562                }
1563        };
1564        if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1565                return $self->{svnsync} = $svnsync;
1566        }
1567
1568        my $err = "useSvnsyncProps set, but failed to read " .
1569                  "svnsync property: svn:sync-from-";
1570        my $rp = $self->ra->rev_proplist(0);
1571
1572        my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1573        $url =~ m{^[a-z\+]+://} or
1574                   die "doesn't look right - svn:sync-from-url is '$url'\n";
1575
1576        my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1577        $uuid =~ m{^[0-9a-f\-]{30,}$} or
1578                   die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1579
1580        my $section = "svn-remote.$self->{repo_id}";
1581        tmp_config('--add', "$section.svnsync-uuid", $uuid);
1582        tmp_config('--add', "$section.svnsync-url", $url);
1583        return $self->{svnsync} = { url => $url, uuid => $uuid };
1584}
1585
1586# this allows us to memoize our SVN::Ra UUID locally and avoid a
1587# remote lookup (useful for 'git svn log').
1588sub ra_uuid {
1589        my ($self) = @_;
1590        unless ($self->{ra_uuid}) {
1591                my $key = "svn-remote.$self->{repo_id}.uuid";
1592                my $uuid = eval { tmp_config('--get', $key) };
1593                if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1594                        $self->{ra_uuid} = $uuid;
1595                } else {
1596                        die "ra_uuid called without URL\n" unless $self->{url};
1597                        $self->{ra_uuid} = $self->ra->get_uuid;
1598                        tmp_config('--add', $key, $self->{ra_uuid});
1599                }
1600        }
1601        $self->{ra_uuid};
1602}
1603
1604sub ra {
1605        my ($self) = shift;
1606        my $ra = Git::SVN::Ra->new($self->{url});
1607        if ($self->use_svm_props && !$self->{svm}) {
1608                if ($self->no_metadata) {
1609                        die "Can't have both 'noMetadata' and ",
1610                            "'useSvmProps' options set!\n";
1611                } elsif ($self->use_svnsync_props) {
1612                        die "Can't have both 'useSvnsyncProps' and ",
1613                            "'useSvmProps' options set!\n";
1614                }
1615                $ra = $self->_set_svm_vars($ra);
1616                $self->{-want_revprops} = 1;
1617        }
1618        $ra;
1619}
1620
1621sub rel_path {
1622        my ($self) = @_;
1623        my $repos_root = $self->ra->{repos_root};
1624        return $self->{path} if ($self->{url} eq $repos_root);
1625        my $url = $self->{url} .
1626                  (length $self->{path} ? "/$self->{path}" : $self->{path});
1627        $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1628        $url;
1629}
1630
1631# prop_walk(PATH, REV, SUB)
1632# -------------------------
1633# Recursively traverse PATH at revision REV and invoke SUB for each
1634# directory that contains a SVN property.  SUB will be invoked as
1635# follows:  &SUB(gs, path, props);  where `gs' is this instance of
1636# Git::SVN, `path' the path to the directory where the properties
1637# `props' were found.  The `path' will be relative to point of checkout,
1638# that is, if url://repo/trunk is the current Git branch, and that
1639# directory contains a sub-directory `d', SUB will be invoked with `/d/'
1640# as `path' (note the trailing `/').
1641sub prop_walk {
1642        my ($self, $path, $rev, $sub) = @_;
1643
1644        my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1645        $path =~ s#^/*#/#g;
1646        my $p = $path;
1647        # Strip the irrelevant part of the path.
1648        $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1649        # Ensure the path is terminated by a `/'.
1650        $p =~ s#/*$#/#;
1651
1652        # The properties contain all the internal SVN stuff nobody
1653        # (usually) cares about.
1654        my $interesting_props = 0;
1655        foreach (keys %{$props}) {
1656                # If it doesn't start with `svn:', it must be a
1657                # user-defined property.
1658                ++$interesting_props and next if $_ !~ /^svn:/;
1659                # FIXME: Fragile, if SVN adds new public properties,
1660                # this needs to be updated.
1661                ++$interesting_props if /^svn:(?:ignore|keywords|executable
1662                                                 |eol-style|mime-type
1663                                                 |externals|needs-lock)$/x;
1664        }
1665        &$sub($self, $p, $props) if $interesting_props;
1666
1667        foreach (sort keys %$dirent) {
1668                next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1669                $self->prop_walk($path . '/' . $_, $rev, $sub);
1670        }
1671}
1672
1673sub last_rev { ($_[0]->last_rev_commit)[0] }
1674sub last_commit { ($_[0]->last_rev_commit)[1] }
1675
1676# returns the newest SVN revision number and newest commit SHA1
1677sub last_rev_commit {
1678        my ($self) = @_;
1679        if (defined $self->{last_rev} && defined $self->{last_commit}) {
1680                return ($self->{last_rev}, $self->{last_commit});
1681        }
1682        my $c = ::verify_ref($self->refname.'^0');
1683        if ($c && !$self->use_svm_props && !$self->no_metadata) {
1684                my $rev = (::cmt_metadata($c))[1];
1685                if (defined $rev) {
1686                        ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1687                        return ($rev, $c);
1688                }
1689        }
1690        my $db_path = $self->db_path;
1691        unless (-e $db_path) {
1692                ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1693                return (undef, undef);
1694        }
1695        my $offset = -41; # from tail
1696        my $rl;
1697        open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1698        sysseek($fh, $offset, 2); # don't care for errors
1699        sysread($fh, $rl, 41) == 41 or return (undef, undef);
1700        chomp $rl;
1701        while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1702                $offset -= 41;
1703                sysseek($fh, $offset, 2); # don't care for errors
1704                sysread($fh, $rl, 41) == 41 or return (undef, undef);
1705                chomp $rl;
1706        }
1707        if ($c && $c ne $rl) {
1708                die "$db_path and ", $self->refname,
1709                    " inconsistent!:\n$c != $rl\n";
1710        }
1711        my $rev = sysseek($fh, 0, 1) or croak $!;
1712        $rev =  ($rev - 41) / 41;
1713        close $fh or croak $!;
1714        ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1715        return ($rev, $c);
1716}
1717
1718sub get_fetch_range {
1719        my ($self, $min, $max) = @_;
1720        $max ||= $self->ra->get_latest_revnum;
1721        $min ||= $self->rev_db_max;
1722        (++$min, $max);
1723}
1724
1725sub tmp_config {
1726        my (@args) = @_;
1727        my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1728        my $config = "$ENV{GIT_DIR}/svn/.metadata";
1729        if (! -f $config && -f $old_def_config) {
1730                rename $old_def_config, $config or
1731                       die "Failed rename $old_def_config => $config: $!\n";
1732        }
1733        my $old_config = $ENV{GIT_CONFIG};
1734        $ENV{GIT_CONFIG} = $config;
1735        $@ = undef;
1736        my @ret = eval {
1737                unless (-f $config) {
1738                        mkfile($config);
1739                        open my $fh, '>', $config or
1740                            die "Can't open $config: $!\n";
1741                        print $fh "; This file is used internally by ",
1742                                  "git-svn\n" or die
1743                                  "Couldn't write to $config: $!\n";
1744                        print $fh "; You should not have to edit it\n" or
1745                              die "Couldn't write to $config: $!\n";
1746                        close $fh or die "Couldn't close $config: $!\n";
1747                }
1748                command('config', @args);
1749        };
1750        my $err = $@;
1751        if (defined $old_config) {
1752                $ENV{GIT_CONFIG} = $old_config;
1753        } else {
1754                delete $ENV{GIT_CONFIG};
1755        }
1756        die $err if $err;
1757        wantarray ? @ret : $ret[0];
1758}
1759
1760sub tmp_index_do {
1761        my ($self, $sub) = @_;
1762        my $old_index = $ENV{GIT_INDEX_FILE};
1763        $ENV{GIT_INDEX_FILE} = $self->{index};
1764        $@ = undef;
1765        my @ret = eval {
1766                my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1767                mkpath([$dir]) unless -d $dir;
1768                &$sub;
1769        };
1770        my $err = $@;
1771        if (defined $old_index) {
1772                $ENV{GIT_INDEX_FILE} = $old_index;
1773        } else {
1774                delete $ENV{GIT_INDEX_FILE};
1775        }
1776        die $err if $err;
1777        wantarray ? @ret : $ret[0];
1778}
1779
1780sub assert_index_clean {
1781        my ($self, $treeish) = @_;
1782
1783        $self->tmp_index_do(sub {
1784                command_noisy('read-tree', $treeish) unless -e $self->{index};
1785                my $x = command_oneline('write-tree');
1786                my ($y) = (command(qw/cat-file commit/, $treeish) =~
1787                           /^tree ($::sha1)/mo);
1788                return if $y eq $x;
1789
1790                warn "Index mismatch: $y != $x\nrereading $treeish\n";
1791                unlink $self->{index} or die "unlink $self->{index}: $!\n";
1792                command_noisy('read-tree', $treeish);
1793                $x = command_oneline('write-tree');
1794                if ($y ne $x) {
1795                        ::fatal "trees ($treeish) $y != $x\n",
1796                                "Something is seriously wrong...";
1797                }
1798        });
1799}
1800
1801sub get_commit_parents {
1802        my ($self, $log_entry) = @_;
1803        my (%seen, @ret, @tmp);
1804        # legacy support for 'set-tree'; this is only used by set_tree_cb:
1805        if (my $ip = $self->{inject_parents}) {
1806                if (my $commit = delete $ip->{$log_entry->{revision}}) {
1807                        push @tmp, $commit;
1808                }
1809        }
1810        if (my $cur = ::verify_ref($self->refname.'^0')) {
1811                push @tmp, $cur;
1812        }
1813        if (my $ipd = $self->{inject_parents_dcommit}) {
1814                if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1815                        push @tmp, @$commit;
1816                }
1817        }
1818        push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1819        while (my $p = shift @tmp) {
1820                next if $seen{$p};
1821                $seen{$p} = 1;
1822                push @ret, $p;
1823                # MAXPARENT is defined to 16 in commit-tree.c:
1824                last if @ret >= 16;
1825        }
1826        if (@tmp) {
1827                die "r$log_entry->{revision}: No room for parents:\n\t",
1828                    join("\n\t", @tmp), "\n";
1829        }
1830        @ret;
1831}
1832
1833sub rewrite_root {
1834        my ($self) = @_;
1835        return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1836        my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1837        my $rwr = eval { command_oneline(qw/config --get/, $k) };
1838        if ($rwr) {
1839                $rwr =~ s#/+$##;
1840                if ($rwr !~ m#^[a-z\+]+://#) {
1841                        die "$rwr is not a valid URL (key: $k)\n";
1842                }
1843        }
1844        $self->{-rewrite_root} = $rwr;
1845}
1846
1847sub metadata_url {
1848        my ($self) = @_;
1849        ($self->rewrite_root || $self->{url}) .
1850           (length $self->{path} ? '/' . $self->{path} : '');
1851}
1852
1853sub full_url {
1854        my ($self) = @_;
1855        $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1856}
1857
1858sub do_git_commit {
1859        my ($self, $log_entry) = @_;
1860        my $lr = $self->last_rev;
1861        if (defined $lr && $lr >= $log_entry->{revision}) {
1862                die "Last fetched revision of ", $self->refname,
1863                    " was r$lr, but we are about to fetch: ",
1864                    "r$log_entry->{revision}!\n";
1865        }
1866        if (my $c = $self->rev_db_get($log_entry->{revision})) {
1867                croak "$log_entry->{revision} = $c already exists! ",
1868                      "Why are we refetching it?\n";
1869        }
1870        $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1871        $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1872                                                          $log_entry->{email};
1873        $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1874
1875        my $tree = $log_entry->{tree};
1876        if (!defined $tree) {
1877                $tree = $self->tmp_index_do(sub {
1878                                            command_oneline('write-tree') });
1879        }
1880        die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1881
1882        my @exec = ('git-commit-tree', $tree);
1883        foreach ($self->get_commit_parents($log_entry)) {
1884                push @exec, '-p', $_;
1885        }
1886        defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1887                                                                   or croak $!;
1888        print $msg_fh $log_entry->{log} or croak $!;
1889        unless ($self->no_metadata) {
1890                print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1891                              or croak $!;
1892        }
1893        $msg_fh->flush == 0 or croak $!;
1894        close $msg_fh or croak $!;
1895        chomp(my $commit = do { local $/; <$out_fh> });
1896        close $out_fh or croak $!;
1897        waitpid $pid, 0;
1898        croak $? if $?;
1899        if ($commit !~ /^$::sha1$/o) {
1900                die "Failed to commit, invalid sha1: $commit\n";
1901        }
1902
1903        $self->rev_db_set($log_entry->{revision}, $commit, 1);
1904
1905        $self->{last_rev} = $log_entry->{revision};
1906        $self->{last_commit} = $commit;
1907        print "r$log_entry->{revision}";
1908        if (defined $log_entry->{svm_revision}) {
1909                 print " (\@$log_entry->{svm_revision})";
1910                 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1911                                   0, $self->svm_uuid);
1912        }
1913        print " = $commit ($self->{ref_id})\n";
1914        if (defined $_repack && (--$_repack_nr == 0)) {
1915                $_repack_nr = $_repack;
1916                # repack doesn't use any arguments with spaces in them, does it?
1917                print "Running git repack $_repack_flags ...\n";
1918                command_noisy('repack', split(/\s+/, $_repack_flags));
1919                print "Done repacking\n";
1920        }
1921        return $commit;
1922}
1923
1924sub match_paths {
1925        my ($self, $paths, $r) = @_;
1926        return 1 if $self->{path} eq '';
1927        if (my $path = $paths->{"/$self->{path}"}) {
1928                return ($path->{action} eq 'D') ? 0 : 1;
1929        }
1930        $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1931        if (grep /$self->{path_regex}/, keys %$paths) {
1932                return 1;
1933        }
1934        my $c = '';
1935        foreach (split m#/#, $self->{path}) {
1936                $c .= "/$_";
1937                next unless ($paths->{$c} &&
1938                             ($paths->{$c}->{action} =~ /^[AR]$/));
1939                if ($self->ra->check_path($self->{path}, $r) ==
1940                    $SVN::Node::dir) {
1941                        return 1;
1942                }
1943        }
1944        return 0;
1945}
1946
1947sub find_parent_branch {
1948        my ($self, $paths, $rev) = @_;
1949        return undef unless $self->follow_parent;
1950        unless (defined $paths) {
1951                my $err_handler = $SVN::Error::handler;
1952                $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1953                $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1954                                   $paths =
1955                                      Git::SVN::Ra::dup_changed_paths($_[0]) });
1956                $SVN::Error::handler = $err_handler;
1957        }
1958        return undef unless defined $paths;
1959
1960        # look for a parent from another branch:
1961        my @b_path_components = split m#/#, $self->rel_path;
1962        my @a_path_components;
1963        my $i;
1964        while (@b_path_components) {
1965                $i = $paths->{'/'.join('/', @b_path_components)};
1966                last if $i && defined $i->{copyfrom_path};
1967                unshift(@a_path_components, pop(@b_path_components));
1968        }
1969        return undef unless defined $i && defined $i->{copyfrom_path};
1970        my $branch_from = $i->{copyfrom_path};
1971        if (@a_path_components) {
1972                print STDERR "branch_from: $branch_from => ";
1973                $branch_from .= '/'.join('/', @a_path_components);
1974                print STDERR $branch_from, "\n";
1975        }
1976        my $r = $i->{copyfrom_rev};
1977        my $repos_root = $self->ra->{repos_root};
1978        my $url = $self->ra->{url};
1979        my $new_url = $repos_root . $branch_from;
1980        print STDERR  "Found possible branch point: ",
1981                      "$new_url => ", $self->full_url, ", $r\n";
1982        $branch_from =~ s#^/##;
1983        my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1984        unless ($gs) {
1985                my $ref_id = $self->{ref_id};
1986                $ref_id =~ s/\@\d+$//;
1987                $ref_id .= "\@$r";
1988                # just grow a tail if we're not unique enough :x
1989                $ref_id .= '-' while find_ref($ref_id);
1990                print STDERR "Initializing parent: $ref_id\n";
1991                $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1992        }
1993        my ($r0, $parent) = $gs->find_rev_before($r, 1);
1994        if (!defined $r0 || !defined $parent) {
1995                my ($base, $head) = parse_revision_argument(0, $r);
1996                if ($base <= $r) {
1997                        $gs->fetch($base, $r);
1998                }
1999                ($r0, $parent) = $gs->last_rev_commit;
2000        }
2001        if (defined $r0 && defined $parent) {
2002                print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2003                my $ed;
2004                if ($self->ra->can_do_switch) {
2005                        $self->assert_index_clean($parent);
2006                        print STDERR "Following parent with do_switch\n";
2007                        # do_switch works with svn/trunk >= r22312, but that
2008                        # is not included with SVN 1.4.3 (the latest version
2009                        # at the moment), so we can't rely on it
2010                        $self->{last_commit} = $parent;
2011                        $ed = SVN::Git::Fetcher->new($self);
2012                        $gs->ra->gs_do_switch($r0, $rev, $gs,
2013                                              $self->full_url, $ed)
2014                          or die "SVN connection failed somewhere...\n";
2015                } elsif ($self->ra->trees_match($new_url, $r0,
2016                                                $self->full_url, $rev)) {
2017                        print STDERR "Trees match:\n",
2018                                     "  $new_url\@$r0\n",
2019                                     "  ${\$self->full_url}\@$rev\n",
2020                                     "Following parent with no changes\n";
2021                        $self->tmp_index_do(sub {
2022                            command_noisy('read-tree', $parent);
2023                        });
2024                        $self->{last_commit} = $parent;
2025                } else {
2026                        print STDERR "Following parent with do_update\n";
2027                        $ed = SVN::Git::Fetcher->new($self);
2028                        $self->ra->gs_do_update($rev, $rev, $self, $ed)
2029                          or die "SVN connection failed somewhere...\n";
2030                }
2031                print STDERR "Successfully followed parent\n";
2032                return $self->make_log_entry($rev, [$parent], $ed);
2033        }
2034        return undef;
2035}
2036
2037sub do_fetch {
2038        my ($self, $paths, $rev) = @_;
2039        my $ed;
2040        my ($last_rev, @parents);
2041        if (my $lc = $self->last_commit) {
2042                # we can have a branch that was deleted, then re-added
2043                # under the same name but copied from another path, in
2044                # which case we'll have multiple parents (we don't
2045                # want to break the original ref, nor lose copypath info):
2046                if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2047                        push @{$log_entry->{parents}}, $lc;
2048                        return $log_entry;
2049                }
2050                $ed = SVN::Git::Fetcher->new($self);
2051                $last_rev = $self->{last_rev};
2052                $ed->{c} = $lc;
2053                @parents = ($lc);
2054        } else {
2055                $last_rev = $rev;
2056                if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2057                        return $log_entry;
2058                }
2059                $ed = SVN::Git::Fetcher->new($self);
2060        }
2061        unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2062                die "SVN connection failed somewhere...\n";
2063        }
2064        $self->make_log_entry($rev, \@parents, $ed);
2065}
2066
2067sub get_untracked {
2068        my ($self, $ed) = @_;
2069        my @out;
2070        my $h = $ed->{empty};
2071        foreach (sort keys %$h) {
2072                my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2073                push @out, "  $act: " . uri_encode($_);
2074                warn "W: $act: $_\n";
2075        }
2076        foreach my $t (qw/dir_prop file_prop/) {
2077                $h = $ed->{$t} or next;
2078                foreach my $path (sort keys %$h) {
2079                        my $ppath = $path eq '' ? '.' : $path;
2080                        foreach my $prop (sort keys %{$h->{$path}}) {
2081                                next if $SKIP_PROP{$prop};
2082                                my $v = $h->{$path}->{$prop};
2083                                my $t_ppath_prop = "$t: " .
2084                                                    uri_encode($ppath) . ' ' .
2085                                                    uri_encode($prop);
2086                                if (defined $v) {
2087                                        push @out, "  +$t_ppath_prop " .
2088                                                   uri_encode($v);
2089                                } else {
2090                                        push @out, "  -$t_ppath_prop";
2091                                }
2092                        }
2093                }
2094        }
2095        foreach my $t (qw/absent_file absent_directory/) {
2096                $h = $ed->{$t} or next;
2097                foreach my $parent (sort keys %$h) {
2098                        foreach my $path (sort @{$h->{$parent}}) {
2099                                push @out, "  $t: " .
2100                                           uri_encode("$parent/$path");
2101                                warn "W: $t: $parent/$path ",
2102                                     "Insufficient permissions?\n";
2103                        }
2104                }
2105        }
2106        \@out;
2107}
2108
2109sub parse_svn_date {
2110        my $date = shift || return '+0000 1970-01-01 00:00:00';
2111        my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2112                                            (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2113                                         croak "Unable to parse date: $date\n";
2114        "+0000 $Y-$m-$d $H:$M:$S";
2115}
2116
2117sub check_author {
2118        my ($author) = @_;
2119        if (!defined $author || length $author == 0) {
2120                $author = '(no author)';
2121        }
2122        if (defined $::_authors && ! defined $::users{$author}) {
2123                die "Author: $author not defined in $::_authors file\n";
2124        }
2125        $author;
2126}
2127
2128sub make_log_entry {
2129        my ($self, $rev, $parents, $ed) = @_;
2130        my $untracked = $self->get_untracked($ed);
2131
2132        open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2133        print $un "r$rev\n" or croak $!;
2134        print $un $_, "\n" foreach @$untracked;
2135        my %log_entry = ( parents => $parents || [], revision => $rev,
2136                          log => '');
2137
2138        my $headrev;
2139        my $logged = delete $self->{logged_rev_props};
2140        if (!$logged || $self->{-want_revprops}) {
2141                my $rp = $self->ra->rev_proplist($rev);
2142                foreach (sort keys %$rp) {
2143                        my $v = $rp->{$_};
2144                        if (/^svn:(author|date|log)$/) {
2145                                $log_entry{$1} = $v;
2146                        } elsif ($_ eq 'svm:headrev') {
2147                                $headrev = $v;
2148                        } else {
2149                                print $un "  rev_prop: ", uri_encode($_), ' ',
2150                                          uri_encode($v), "\n";
2151                        }
2152                }
2153        } else {
2154                map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2155        }
2156        close $un or croak $!;
2157
2158        $log_entry{date} = parse_svn_date($log_entry{date});
2159        $log_entry{log} .= "\n";
2160        my $author = $log_entry{author} = check_author($log_entry{author});
2161        my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2162                                                       : ($author, undef);
2163        if (defined $headrev && $self->use_svm_props) {
2164                if ($self->rewrite_root) {
2165                        die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2166                            "options set!\n";
2167                }
2168                my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2169                # we don't want "SVM: initializing mirror for junk" ...
2170                return undef if $r == 0;
2171                my $svm = $self->svm;
2172                if ($uuid ne $svm->{uuid}) {
2173                        die "UUID mismatch on SVM path:\n",
2174                            "expected: $svm->{uuid}\n",
2175                            "     got: $uuid\n";
2176                }
2177                my $full_url = $self->full_url;
2178                $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2179                             die "Failed to replace '$svm->{replace}' with ",
2180                                 "'$svm->{source}' in $full_url\n";
2181                # throw away username for storing in records
2182                remove_username($full_url);
2183                $log_entry{metadata} = "$full_url\@$r $uuid";
2184                $log_entry{svm_revision} = $r;
2185                $email ||= "$author\@$uuid"
2186        } elsif ($self->use_svnsync_props) {
2187                my $full_url = $self->svnsync->{url};
2188                $full_url .= "/$self->{path}" if length $self->{path};
2189                remove_username($full_url);
2190                my $uuid = $self->svnsync->{uuid};
2191                $log_entry{metadata} = "$full_url\@$rev $uuid";
2192                $email ||= "$author\@$uuid"
2193        } else {
2194                my $url = $self->metadata_url;
2195                remove_username($url);
2196                $log_entry{metadata} = "$url\@$rev " .
2197                                       $self->ra->get_uuid;
2198                $email ||= "$author\@" . $self->ra->get_uuid;
2199        }
2200        $log_entry{name} = $name;
2201        $log_entry{email} = $email;
2202        \%log_entry;
2203}
2204
2205sub fetch {
2206        my ($self, $min_rev, $max_rev, @parents) = @_;
2207        my ($last_rev, $last_commit) = $self->last_rev_commit;
2208        my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2209        $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2210}
2211
2212sub set_tree_cb {
2213        my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2214        $self->{inject_parents} = { $rev => $tree };
2215        $self->fetch(undef, undef);
2216}
2217
2218sub set_tree {
2219        my ($self, $tree) = (shift, shift);
2220        my $log_entry = ::get_commit_entry($tree);
2221        unless ($self->{last_rev}) {
2222                fatal("Must have an existing revision to commit");
2223        }
2224        my %ed_opts = ( r => $self->{last_rev},
2225                        log => $log_entry->{log},
2226                        ra => $self->ra,
2227                        tree_a => $self->{last_commit},
2228                        tree_b => $tree,
2229                        editor_cb => sub {
2230                               $self->set_tree_cb($log_entry, $tree, @_) },
2231                        svn_path => $self->{path} );
2232        if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2233                print "No changes\nr$self->{last_rev} = $tree\n";
2234        }
2235}
2236
2237sub rebuild {
2238        my ($self) = @_;
2239        my $db_path = $self->db_path;
2240        return if (-e $db_path && ! -z $db_path);
2241        return unless ::verify_ref($self->refname.'^0');
2242        if (-f $self->{db_root}) {
2243                rename $self->{db_root}, $db_path or die
2244                     "rename $self->{db_root} => $db_path failed: $!\n";
2245                my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2246                symlink $base, $self->{db_root} or die
2247                     "symlink $base => $self->{db_root} failed: $!\n";
2248                return;
2249        }
2250        print "Rebuilding $db_path ...\n";
2251        my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2252        my $latest;
2253        my $full_url = $self->full_url;
2254        remove_username($full_url);
2255        my $svn_uuid;
2256        my $c;
2257        while (<$log>) {
2258                if ( m{^commit ($::sha1)$} ) {
2259                        $c = $1;
2260                        next;
2261                }
2262                next unless s{^\s*(git-svn-id:)}{$1};
2263                my ($url, $rev, $uuid) = ::extract_metadata($_);
2264                remove_username($url);
2265
2266                # ignore merges (from set-tree)
2267                next if (!defined $rev || !$uuid);
2268
2269                # if we merged or otherwise started elsewhere, this is
2270                # how we break out of it
2271                if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2272                    ($full_url && $url && ($url ne $full_url))) {
2273                        next;
2274                }
2275                $latest ||= $rev;
2276                $svn_uuid ||= $uuid;
2277
2278                $self->rev_db_set($rev, $c);
2279                print "r$rev = $c\n";
2280        }
2281        command_close_pipe($log, $ctx);
2282        print "Done rebuilding $db_path\n";
2283}
2284
2285# rev_db:
2286# Tie::File seems to be prone to offset errors if revisions get sparse,
2287# it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2288# one of my favorite modules is out :<  Next up would be one of the DBM
2289# modules, but I'm not sure which is most portable...  So I'll just
2290# go with something that's plain-text, but still capable of
2291# being randomly accessed.  So here's my ultra-simple fixed-width
2292# database.  All records are 40 characters + "\n", so it's easy to seek
2293# to a revision: (41 * rev) is the byte offset.
2294# A record of 40 0s denotes an empty revision.
2295# And yes, it's still pretty fast (faster than Tie::File).
2296# These files are disposable unless noMetadata or useSvmProps is set
2297
2298sub _rev_db_set {
2299        my ($fh, $rev, $commit) = @_;
2300        my $offset = $rev * 41;
2301        # assume that append is the common case:
2302        seek $fh, 0, 2 or croak $!;
2303        my $pos = tell $fh;
2304        if ($pos < $offset) {
2305                for (1 .. (($offset - $pos) / 41)) {
2306                        print $fh (('0' x 40),"\n") or croak $!;
2307                }
2308        }
2309        seek $fh, $offset, 0 or croak $!;
2310        print $fh $commit,"\n" or croak $!;
2311}
2312
2313sub mkfile {
2314        my ($path) = @_;
2315        unless (-e $path) {
2316                my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2317                mkpath([$dir]) unless -d $dir;
2318                open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2319                close $fh or die "Couldn't close (create) $path: $!\n";
2320        }
2321}
2322
2323sub rev_db_set {
2324        my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2325        length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2326        my $db = $self->db_path($uuid);
2327        my $db_lock = "$db.lock";
2328        my $sig;
2329        if ($update_ref) {
2330                $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2331                            $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2332        }
2333        mkfile($db);
2334
2335        $LOCKFILES{$db_lock} = 1;
2336        my $sync;
2337        # both of these options make our .rev_db file very, very important
2338        # and we can't afford to lose it because rebuild() won't work
2339        if ($self->use_svm_props || $self->no_metadata) {
2340                $sync = 1;
2341                copy($db, $db_lock) or die "rev_db_set(@_): ",
2342                                           "Failed to copy: ",
2343                                           "$db => $db_lock ($!)\n";
2344        } else {
2345                rename $db, $db_lock or die "rev_db_set(@_): ",
2346                                            "Failed to rename: ",
2347                                            "$db => $db_lock ($!)\n";
2348        }
2349        open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2350        _rev_db_set($fh, $rev, $commit);
2351        if ($sync) {
2352                $fh->flush or die "Couldn't flush $db_lock: $!\n";
2353                $fh->sync or die "Couldn't sync $db_lock: $!\n";
2354        }
2355        close $fh or croak $!;
2356        if ($update_ref) {
2357                $_head = $self;
2358                command_noisy('update-ref', '-m', "r$rev",
2359                              $self->refname, $commit);
2360        }
2361        rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2362                                    "$db_lock => $db ($!)\n";
2363        delete $LOCKFILES{$db_lock};
2364        if ($update_ref) {
2365                $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2366                            $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2367                kill $sig, $$ if defined $sig;
2368        }
2369}
2370
2371sub rev_db_max {
2372        my ($self) = @_;
2373        $self->rebuild;
2374        my $db_path = $self->db_path;
2375        my @stat = stat $db_path or return 0;
2376        ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2377        my $max = $stat[7] / 41;
2378        (($max > 0) ? $max - 1 : 0);
2379}
2380
2381sub rev_db_get {
2382        my ($self, $rev, $uuid) = @_;
2383        my $ret;
2384        my $offset = $rev * 41;
2385        my $db_path = $self->db_path($uuid);
2386        return undef unless -e $db_path;
2387        open my $fh, '<', $db_path or croak $!;
2388        if (sysseek($fh, $offset, 0) == $offset) {
2389                my $read = sysread($fh, $ret, 40);
2390                $ret = undef if ($read != 40 || $ret eq ('0'x40));
2391        }
2392        close $fh or croak $!;
2393        $ret;
2394}
2395
2396sub find_rev_before {
2397        my ($self, $rev, $eq_ok) = @_;
2398        --$rev unless $eq_ok;
2399        while ($rev > 0) {
2400                if (my $c = $self->rev_db_get($rev)) {
2401                        return ($rev, $c);
2402                }
2403                --$rev;
2404        }
2405        return (undef, undef);
2406}
2407
2408sub _new {
2409        my ($class, $repo_id, $ref_id, $path) = @_;
2410        unless (defined $repo_id && length $repo_id) {
2411                $repo_id = $Git::SVN::default_repo_id;
2412        }
2413        unless (defined $ref_id && length $ref_id) {
2414                $_[2] = $ref_id = $Git::SVN::default_ref_id;
2415        }
2416        $_[1] = $repo_id = sanitize_remote_name($repo_id);
2417        my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2418        $_[3] = $path = '' unless (defined $path);
2419        mkpath(["$ENV{GIT_DIR}/svn"]);
2420        bless {
2421                ref_id => $ref_id, dir => $dir, index => "$dir/index",
2422                path => $path, config => "$ENV{GIT_DIR}/svn/config",
2423                db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2424}
2425
2426sub db_path {
2427        my ($self, $uuid) = @_;
2428        $uuid ||= $self->ra_uuid;
2429        "$self->{db_root}.$uuid";
2430}
2431
2432sub uri_encode {
2433        my ($f) = @_;
2434        $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2435        $f
2436}
2437
2438sub remove_username {
2439        $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2440}
2441
2442package Git::SVN::Prompt;
2443use strict;
2444use warnings;
2445require SVN::Core;
2446use vars qw/$_no_auth_cache $_username/;
2447
2448sub simple {
2449        my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2450        $may_save = undef if $_no_auth_cache;
2451        $default_username = $_username if defined $_username;
2452        if (defined $default_username && length $default_username) {
2453                if (defined $realm && length $realm) {
2454                        print STDERR "Authentication realm: $realm\n";
2455                        STDERR->flush;
2456                }
2457                $cred->username($default_username);
2458        } else {
2459                username($cred, $realm, $may_save, $pool);
2460        }
2461        $cred->password(_read_password("Password for '" .
2462                                       $cred->username . "': ", $realm));
2463        $cred->may_save($may_save);
2464        $SVN::_Core::SVN_NO_ERROR;
2465}
2466
2467sub ssl_server_trust {
2468        my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2469        $may_save = undef if $_no_auth_cache;
2470        print STDERR "Error validating server certificate for '$realm':\n";
2471        {
2472                no warnings 'once';
2473                # All variables SVN::Auth::SSL::* are used only once,
2474                # so we're shutting up Perl warnings about this.
2475                if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2476                        print STDERR " - The certificate is not issued ",
2477                            "by a trusted authority. Use the\n",
2478                            "   fingerprint to validate ",
2479                            "the certificate manually!\n";
2480                }
2481                if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2482                        print STDERR " - The certificate hostname ",
2483                            "does not match.\n";
2484                }
2485                if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2486                        print STDERR " - The certificate is not yet valid.\n";
2487                }
2488                if ($failures & $SVN::Auth::SSL::EXPIRED) {
2489                        print STDERR " - The certificate has expired.\n";
2490                }
2491                if ($failures & $SVN::Auth::SSL::OTHER) {
2492                        print STDERR " - The certificate has ",
2493                            "an unknown error.\n";
2494                }
2495        } # no warnings 'once'
2496        printf STDERR
2497                "Certificate information:\n".
2498                " - Hostname: %s\n".
2499                " - Valid: from %s until %s\n".
2500                " - Issuer: %s\n".
2501                " - Fingerprint: %s\n",
2502                map $cert_info->$_, qw(hostname valid_from valid_until
2503                                       issuer_dname fingerprint);
2504        my $choice;
2505prompt:
2506        print STDERR $may_save ?
2507              "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2508              "(R)eject or accept (t)emporarily? ";
2509        STDERR->flush;
2510        $choice = lc(substr(<STDIN> || 'R', 0, 1));
2511        if ($choice =~ /^t$/i) {
2512                $cred->may_save(undef);
2513        } elsif ($choice =~ /^r$/i) {
2514                return -1;
2515        } elsif ($may_save && $choice =~ /^p$/i) {
2516                $cred->may_save($may_save);
2517        } else {
2518                goto prompt;
2519        }
2520        $cred->accepted_failures($failures);
2521        $SVN::_Core::SVN_NO_ERROR;
2522}
2523
2524sub ssl_client_cert {
2525        my ($cred, $realm, $may_save, $pool) = @_;
2526        $may_save = undef if $_no_auth_cache;
2527        print STDERR "Client certificate filename: ";
2528        STDERR->flush;
2529        chomp(my $filename = <STDIN>);
2530        $cred->cert_file($filename);
2531        $cred->may_save($may_save);
2532        $SVN::_Core::SVN_NO_ERROR;
2533}
2534
2535sub ssl_client_cert_pw {
2536        my ($cred, $realm, $may_save, $pool) = @_;
2537        $may_save = undef if $_no_auth_cache;
2538        $cred->password(_read_password("Password: ", $realm));
2539        $cred->may_save($may_save);
2540        $SVN::_Core::SVN_NO_ERROR;
2541}
2542
2543sub username {
2544        my ($cred, $realm, $may_save, $pool) = @_;
2545        $may_save = undef if $_no_auth_cache;
2546        if (defined $realm && length $realm) {
2547                print STDERR "Authentication realm: $realm\n";
2548        }
2549        my $username;
2550        if (defined $_username) {
2551                $username = $_username;
2552        } else {
2553                print STDERR "Username: ";
2554                STDERR->flush;
2555                chomp($username = <STDIN>);
2556        }
2557        $cred->username($username);
2558        $cred->may_save($may_save);
2559        $SVN::_Core::SVN_NO_ERROR;
2560}
2561
2562sub _read_password {
2563        my ($prompt, $realm) = @_;
2564        print STDERR $prompt;
2565        STDERR->flush;
2566        require Term::ReadKey;
2567        Term::ReadKey::ReadMode('noecho');
2568        my $password = '';
2569        while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2570                last if $key =~ /[\012\015]/; # \n\r
2571                $password .= $key;
2572        }
2573        Term::ReadKey::ReadMode('restore');
2574        print STDERR "\n";
2575        STDERR->flush;
2576        $password;
2577}
2578
2579package SVN::Git::Fetcher;
2580use vars qw/@ISA/;
2581use strict;
2582use warnings;
2583use Carp qw/croak/;
2584use IO::File qw//;
2585use Digest::MD5;
2586
2587# file baton members: path, mode_a, mode_b, pool, fh, blob, base
2588sub new {
2589        my ($class, $git_svn) = @_;
2590        my $self = SVN::Delta::Editor->new;
2591        bless $self, $class;
2592        $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2593        $self->{empty} = {};
2594        $self->{dir_prop} = {};
2595        $self->{file_prop} = {};
2596        $self->{absent_dir} = {};
2597        $self->{absent_file} = {};
2598        $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2599        $self;
2600}
2601
2602sub set_path_strip {
2603        my ($self, $path) = @_;
2604        $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2605}
2606
2607sub open_root {
2608        { path => '' };
2609}
2610
2611sub open_directory {
2612        my ($self, $path, $pb, $rev) = @_;
2613        { path => $path };
2614}
2615
2616sub git_path {
2617        my ($self, $path) = @_;
2618        if ($self->{path_strip}) {
2619                $path =~ s!$self->{path_strip}!! or
2620                  die "Failed to strip path '$path' ($self->{path_strip})\n";
2621        }
2622        $path;
2623}
2624
2625sub delete_entry {
2626        my ($self, $path, $rev, $pb) = @_;
2627
2628        my $gpath = $self->git_path($path);
2629        return undef if ($gpath eq '');
2630
2631        # remove entire directories.
2632        if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2633                my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2634                                                     -r --name-only -z/,
2635                                                     $self->{c}, '--', $gpath);
2636                local $/ = "\0";
2637                while (<$ls>) {
2638                        chomp;
2639                        $self->{gii}->remove($_);
2640                        print "\tD\t$_\n" unless $::_q;
2641                }
2642                print "\tD\t$gpath/\n" unless $::_q;
2643                command_close_pipe($ls, $ctx);
2644                $self->{empty}->{$path} = 0
2645        } else {
2646                $self->{gii}->remove($gpath);
2647                print "\tD\t$gpath\n" unless $::_q;
2648        }
2649        undef;
2650}
2651
2652sub open_file {
2653        my ($self, $path, $pb, $rev) = @_;
2654        my $gpath = $self->git_path($path);
2655        my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2656                             =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2657        unless (defined $mode && defined $blob) {
2658                die "$path was not found in commit $self->{c} (r$rev)\n";
2659        }
2660        { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2661          pool => SVN::Pool->new, action => 'M' };
2662}
2663
2664sub add_file {
2665        my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2666        my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2667        delete $self->{empty}->{$dir};
2668        { path => $path, mode_a => 100644, mode_b => 100644,
2669          pool => SVN::Pool->new, action => 'A' };
2670}
2671
2672sub add_directory {
2673        my ($self, $path, $cp_path, $cp_rev) = @_;
2674        my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2675        delete $self->{empty}->{$dir};
2676        $self->{empty}->{$path} = 1;
2677        { path => $path };
2678}
2679
2680sub change_dir_prop {
2681        my ($self, $db, $prop, $value) = @_;
2682        $self->{dir_prop}->{$db->{path}} ||= {};
2683        $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2684        undef;
2685}
2686
2687sub absent_directory {
2688        my ($self, $path, $pb) = @_;
2689        $self->{absent_dir}->{$pb->{path}} ||= [];
2690        push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2691        undef;
2692}
2693
2694sub absent_file {
2695        my ($self, $path, $pb) = @_;
2696        $self->{absent_file}->{$pb->{path}} ||= [];
2697        push @{$self->{absent_file}->{$pb->{path}}}, $path;
2698        undef;
2699}
2700
2701sub change_file_prop {
2702        my ($self, $fb, $prop, $value) = @_;
2703        if ($prop eq 'svn:executable') {
2704                if ($fb->{mode_b} != 120000) {
2705                        $fb->{mode_b} = defined $value ? 100755 : 100644;
2706                }
2707        } elsif ($prop eq 'svn:special') {
2708                $fb->{mode_b} = defined $value ? 120000 : 100644;
2709        } else {
2710                $self->{file_prop}->{$fb->{path}} ||= {};
2711                $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2712        }
2713        undef;
2714}
2715
2716sub apply_textdelta {
2717        my ($self, $fb, $exp) = @_;
2718        my $fh = IO::File->new_tmpfile;
2719        $fh->autoflush(1);
2720        # $fh gets auto-closed() by SVN::TxDelta::apply(),
2721        # (but $base does not,) so dup() it for reading in close_file
2722        open my $dup, '<&', $fh or croak $!;
2723        my $base = IO::File->new_tmpfile;
2724        $base->autoflush(1);
2725        if ($fb->{blob}) {
2726                defined (my $pid = fork) or croak $!;
2727                if (!$pid) {
2728                        open STDOUT, '>&', $base or croak $!;
2729                        print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2730                        exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2731                }
2732                waitpid $pid, 0;
2733                croak $? if $?;
2734
2735                if (defined $exp) {
2736                        seek $base, 0, 0 or croak $!;
2737                        my $md5 = Digest::MD5->new;
2738                        $md5->addfile($base);
2739                        my $got = $md5->hexdigest;
2740                        die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2741                            "expected: $exp\n",
2742                            "     got: $got\n" if ($got ne $exp);
2743                }
2744        }
2745        seek $base, 0, 0 or croak $!;
2746        $fb->{fh} = $dup;
2747        $fb->{base} = $base;
2748        [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2749}
2750
2751sub close_file {
2752        my ($self, $fb, $exp) = @_;
2753        my $hash;
2754        my $path = $self->git_path($fb->{path});
2755        if (my $fh = $fb->{fh}) {
2756                if (defined $exp) {
2757                        seek($fh, 0, 0) or croak $!;
2758                        my $md5 = Digest::MD5->new;
2759                        $md5->addfile($fh);
2760                        my $got = $md5->hexdigest;
2761                        if ($got ne $exp) {
2762                                die "Checksum mismatch: $path\n",
2763                                    "expected: $exp\n    got: $got\n";
2764                        }
2765                }
2766                sysseek($fh, 0, 0) or croak $!;
2767                if ($fb->{mode_b} == 120000) {
2768                        sysread($fh, my $buf, 5) == 5 or croak $!;
2769                        $buf eq 'link ' or die "$path has mode 120000",
2770                                               "but is not a link\n";
2771                }
2772                defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2773                if (!$pid) {
2774                        open STDIN, '<&', $fh or croak $!;
2775                        exec qw/git-hash-object -w --stdin/ or croak $!;
2776                }
2777                chomp($hash = do { local $/; <$out> });
2778                close $out or croak $!;
2779                close $fh or croak $!;
2780                $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2781                close $fb->{base} or croak $!;
2782        } else {
2783                $hash = $fb->{blob} or die "no blob information\n";
2784        }
2785        $fb->{pool}->clear;
2786        $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2787        print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2788        undef;
2789}
2790
2791sub abort_edit {
2792        my $self = shift;
2793        $self->{nr} = $self->{gii}->{nr};
2794        delete $self->{gii};
2795        $self->SUPER::abort_edit(@_);
2796}
2797
2798sub close_edit {
2799        my $self = shift;
2800        $self->{git_commit_ok} = 1;
2801        $self->{nr} = $self->{gii}->{nr};
2802        delete $self->{gii};
2803        $self->SUPER::close_edit(@_);
2804}
2805
2806package SVN::Git::Editor;
2807use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2808use strict;
2809use warnings;
2810use Carp qw/croak/;
2811use IO::File;
2812use Digest::MD5;
2813
2814sub new {
2815        my ($class, $opts) = @_;
2816        foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2817                die "$_ required!\n" unless (defined $opts->{$_});
2818        }
2819
2820        my $pool = SVN::Pool->new;
2821        my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2822        my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2823                                     $opts->{r}, $mods);
2824
2825        # $opts->{ra} functions should not be used after this:
2826        my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
2827                                                $opts->{editor_cb}, $pool);
2828        my $self = SVN::Delta::Editor->new(@ce, $pool);
2829        bless $self, $class;
2830        foreach (qw/svn_path r tree_a tree_b/) {
2831                $self->{$_} = $opts->{$_};
2832        }
2833        $self->{url} = $opts->{ra}->{url};
2834        $self->{mods} = $mods;
2835        $self->{types} = $types;
2836        $self->{pool} = $pool;
2837        $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2838        $self->{rm} = { };
2839        $self->{path_prefix} = length $self->{svn_path} ?
2840                               "$self->{svn_path}/" : '';
2841        return $self;
2842}
2843
2844sub generate_diff {
2845        my ($tree_a, $tree_b) = @_;
2846        my @diff_tree = qw(diff-tree -z -r);
2847        if ($_cp_similarity) {
2848                push @diff_tree, "-C$_cp_similarity";
2849        } else {
2850                push @diff_tree, '-C';
2851        }
2852        push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2853        push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2854        push @diff_tree, $tree_a, $tree_b;
2855        my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2856        local $/ = "\0";
2857        my $state = 'meta';
2858        my @mods;
2859        while (<$diff_fh>) {
2860                chomp $_; # this gets rid of the trailing "\0"
2861                if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2862                                        $::sha1\s($::sha1)\s
2863                                        ([MTCRAD])\d*$/xo) {
2864                        push @mods, {   mode_a => $1, mode_b => $2,
2865                                        sha1_b => $3, chg => $4 };
2866                        if ($4 =~ /^(?:C|R)$/) {
2867                                $state = 'file_a';
2868                        } else {
2869                                $state = 'file_b';
2870                        }
2871                } elsif ($state eq 'file_a') {
2872                        my $x = $mods[$#mods] or croak "Empty array\n";
2873                        if ($x->{chg} !~ /^(?:C|R)$/) {
2874                                croak "Error parsing $_, $x->{chg}\n";
2875                        }
2876                        $x->{file_a} = $_;
2877                        $state = 'file_b';
2878                } elsif ($state eq 'file_b') {
2879                        my $x = $mods[$#mods] or croak "Empty array\n";
2880                        if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2881                                croak "Error parsing $_, $x->{chg}\n";
2882                        }
2883                        if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2884                                croak "Error parsing $_, $x->{chg}\n";
2885                        }
2886                        $x->{file_b} = $_;
2887                        $state = 'meta';
2888                } else {
2889                        croak "Error parsing $_\n";
2890                }
2891        }
2892        command_close_pipe($diff_fh, $ctx);
2893        \@mods;
2894}
2895
2896sub check_diff_paths {
2897        my ($ra, $pfx, $rev, $mods) = @_;
2898        my %types;
2899        $pfx .= '/' if length $pfx;
2900
2901        sub type_diff_paths {
2902                my ($ra, $types, $path, $rev) = @_;
2903                my @p = split m#/+#, $path;
2904                my $c = shift @p;
2905                unless (defined $types->{$c}) {
2906                        $types->{$c} = $ra->check_path($c, $rev);
2907                }
2908                while (@p) {
2909                        $c .= '/' . shift @p;
2910                        next if defined $types->{$c};
2911                        $types->{$c} = $ra->check_path($c, $rev);
2912                }
2913        }
2914
2915        foreach my $m (@$mods) {
2916                foreach my $f (qw/file_a file_b/) {
2917                        next unless defined $m->{$f};
2918                        my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2919                        if (length $pfx.$dir && ! defined $types{$dir}) {
2920                                type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2921                        }
2922                }
2923        }
2924        \%types;
2925}
2926
2927sub split_path {
2928        return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2929}
2930
2931sub repo_path {
2932        my ($self, $path) = @_;
2933        $self->{path_prefix}.(defined $path ? $path : '');
2934}
2935
2936sub url_path {
2937        my ($self, $path) = @_;
2938        if ($self->{url} =~ m#^https?://#) {
2939                $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2940        }
2941        $self->{url} . '/' . $self->repo_path($path);
2942}
2943
2944sub rmdirs {
2945        my ($self) = @_;
2946        my $rm = $self->{rm};
2947        delete $rm->{''}; # we never delete the url we're tracking
2948        return unless %$rm;
2949
2950        foreach (keys %$rm) {
2951                my @d = split m#/#, $_;
2952                my $c = shift @d;
2953                $rm->{$c} = 1;
2954                while (@d) {
2955                        $c .= '/' . shift @d;
2956                        $rm->{$c} = 1;
2957                }
2958        }
2959        delete $rm->{$self->{svn_path}};
2960        delete $rm->{''}; # we never delete the url we're tracking
2961        return unless %$rm;
2962
2963        my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2964                                             $self->{tree_b});
2965        local $/ = "\0";
2966        while (<$fh>) {
2967                chomp;
2968                my @dn = split m#/#, $_;
2969                while (pop @dn) {
2970                        delete $rm->{join '/', @dn};
2971                }
2972                unless (%$rm) {
2973                        close $fh;
2974                        return;
2975                }
2976        }
2977        command_close_pipe($fh, $ctx);
2978
2979        my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2980        foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2981                $self->close_directory($bat->{$d}, $p);
2982                my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2983                print "\tD+\t$d/\n" unless $::_q;
2984                $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2985                delete $bat->{$d};
2986        }
2987}
2988
2989sub open_or_add_dir {
2990        my ($self, $full_path, $baton) = @_;
2991        my $t = $self->{types}->{$full_path};
2992        if (!defined $t) {
2993                die "$full_path not known in r$self->{r} or we have a bug!\n";
2994        }
2995        {
2996                no warnings 'once';
2997                # SVN::Node::none and SVN::Node::file are used only once,
2998                # so we're shutting up Perl's warnings about them.
2999                if ($t == $SVN::Node::none) {
3000                        return $self->add_directory($full_path, $baton,
3001                            undef, -1, $self->{pool});
3002                } elsif ($t == $SVN::Node::dir) {
3003                        return $self->open_directory($full_path, $baton,
3004                            $self->{r}, $self->{pool});
3005                } # no warnings 'once'
3006                print STDERR "$full_path already exists in repository at ",
3007                    "r$self->{r} and it is not a directory (",
3008                    ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3009        } # no warnings 'once'
3010        exit 1;
3011}
3012
3013sub ensure_path {
3014        my ($self, $path) = @_;
3015        my $bat = $self->{bat};
3016        my $repo_path = $self->repo_path($path);
3017        return $bat->{''} unless (length $repo_path);
3018        my @p = split m#/+#, $repo_path;
3019        my $c = shift @p;
3020        $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3021        while (@p) {
3022                my $c0 = $c;
3023                $c .= '/' . shift @p;
3024                $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3025        }
3026        return $bat->{$c};
3027}
3028
3029sub A {
3030        my ($self, $m) = @_;
3031        my ($dir, $file) = split_path($m->{file_b});
3032        my $pbat = $self->ensure_path($dir);
3033        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3034                                        undef, -1);
3035        print "\tA\t$m->{file_b}\n" unless $::_q;
3036        $self->chg_file($fbat, $m);
3037        $self->close_file($fbat,undef,$self->{pool});
3038}
3039
3040sub C {
3041        my ($self, $m) = @_;
3042        my ($dir, $file) = split_path($m->{file_b});
3043        my $pbat = $self->ensure_path($dir);
3044        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3045                                $self->url_path($m->{file_a}), $self->{r});
3046        print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3047        $self->chg_file($fbat, $m);
3048        $self->close_file($fbat,undef,$self->{pool});
3049}
3050
3051sub delete_entry {
3052        my ($self, $path, $pbat) = @_;
3053        my $rpath = $self->repo_path($path);
3054        my ($dir, $file) = split_path($rpath);
3055        $self->{rm}->{$dir} = 1;
3056        $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3057}
3058
3059sub R {
3060        my ($self, $m) = @_;
3061        my ($dir, $file) = split_path($m->{file_b});
3062        my $pbat = $self->ensure_path($dir);
3063        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3064                                $self->url_path($m->{file_a}), $self->{r});
3065        print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3066        $self->chg_file($fbat, $m);
3067        $self->close_file($fbat,undef,$self->{pool});
3068
3069        ($dir, $file) = split_path($m->{file_a});
3070        $pbat = $self->ensure_path($dir);
3071        $self->delete_entry($m->{file_a}, $pbat);
3072}
3073
3074sub M {
3075        my ($self, $m) = @_;
3076        my ($dir, $file) = split_path($m->{file_b});
3077        my $pbat = $self->ensure_path($dir);
3078        my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3079                                $pbat,$self->{r},$self->{pool});
3080        print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3081        $self->chg_file($fbat, $m);
3082        $self->close_file($fbat,undef,$self->{pool});
3083}
3084
3085sub T { shift->M(@_) }
3086
3087sub change_file_prop {
3088        my ($self, $fbat, $pname, $pval) = @_;
3089        $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3090}
3091
3092sub chg_file {
3093        my ($self, $fbat, $m) = @_;
3094        if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3095                $self->change_file_prop($fbat,'svn:executable','*');
3096        } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3097                $self->change_file_prop($fbat,'svn:executable',undef);
3098        }
3099        my $fh = IO::File->new_tmpfile or croak $!;
3100        if ($m->{mode_b} =~ /^120/) {
3101                print $fh 'link ' or croak $!;
3102                $self->change_file_prop($fbat,'svn:special','*');
3103        } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3104                $self->change_file_prop($fbat,'svn:special',undef);
3105        }
3106        defined(my $pid = fork) or croak $!;
3107        if (!$pid) {
3108                open STDOUT, '>&', $fh or croak $!;
3109                exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3110        }
3111        waitpid $pid, 0;
3112        croak $? if $?;
3113        $fh->flush == 0 or croak $!;
3114        seek $fh, 0, 0 or croak $!;
3115
3116        my $md5 = Digest::MD5->new;
3117        $md5->addfile($fh) or croak $!;
3118        seek $fh, 0, 0 or croak $!;
3119
3120        my $exp = $md5->hexdigest;
3121        my $pool = SVN::Pool->new;
3122        my $atd = $self->apply_textdelta($fbat, undef, $pool);
3123        my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3124        die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3125        $pool->clear;
3126
3127        close $fh or croak $!;
3128}
3129
3130sub D {
3131        my ($self, $m) = @_;
3132        my ($dir, $file) = split_path($m->{file_b});
3133        my $pbat = $self->ensure_path($dir);
3134        print "\tD\t$m->{file_b}\n" unless $::_q;
3135        $self->delete_entry($m->{file_b}, $pbat);
3136}
3137
3138sub close_edit {
3139        my ($self) = @_;
3140        my ($p,$bat) = ($self->{pool}, $self->{bat});
3141        foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3142                next if $_ eq '';
3143                $self->close_directory($bat->{$_}, $p);
3144        }
3145        $self->close_directory($bat->{''}, $p);
3146        $self->SUPER::close_edit($p);
3147        $p->clear;
3148}
3149
3150sub abort_edit {
3151        my ($self) = @_;
3152        $self->SUPER::abort_edit($self->{pool});
3153}
3154
3155sub DESTROY {
3156        my $self = shift;
3157        $self->SUPER::DESTROY(@_);
3158        $self->{pool}->clear;
3159}
3160
3161# this drives the editor
3162sub apply_diff {
3163        my ($self) = @_;
3164        my $mods = $self->{mods};
3165        my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3166        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3167                my $f = $m->{chg};
3168                if (defined $o{$f}) {
3169                        $self->$f($m);
3170                } else {
3171                        fatal("Invalid change type: $f");
3172                }
3173        }
3174        $self->rmdirs if $_rmdir;
3175        if (@$mods == 0) {
3176                $self->abort_edit;
3177        } else {
3178                $self->close_edit;
3179        }
3180        return scalar @$mods;
3181}
3182
3183package Git::SVN::Ra;
3184use vars qw/@ISA $config_dir $_log_window_size/;
3185use strict;
3186use warnings;
3187my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3188
3189BEGIN {
3190        # enforce temporary pool usage for some simple functions
3191        no strict 'refs';
3192        for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3193                my $SUPER = "SUPER::$f";
3194                *$f = sub {
3195                        my $self = shift;
3196                        my $pool = SVN::Pool->new;
3197                        my @ret = $self->$SUPER(@_,$pool);
3198                        $pool->clear;
3199                        wantarray ? @ret : $ret[0];
3200                };
3201        }
3202}
3203
3204sub _auth_providers () {
3205        [
3206          SVN::Client::get_simple_provider(),
3207          SVN::Client::get_ssl_server_trust_file_provider(),
3208          SVN::Client::get_simple_prompt_provider(
3209            \&Git::SVN::Prompt::simple, 2),
3210          SVN::Client::get_ssl_client_cert_file_provider(),
3211          SVN::Client::get_ssl_client_cert_prompt_provider(
3212            \&Git::SVN::Prompt::ssl_client_cert, 2),
3213          SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3214            \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3215          SVN::Client::get_username_provider(),
3216          SVN::Client::get_ssl_server_trust_prompt_provider(
3217            \&Git::SVN::Prompt::ssl_server_trust),
3218          SVN::Client::get_username_prompt_provider(
3219            \&Git::SVN::Prompt::username, 2)
3220        ]
3221}
3222
3223sub new {
3224        my ($class, $url) = @_;
3225        $url =~ s!/+$!!;
3226        return $RA if ($RA && $RA->{url} eq $url);
3227
3228        SVN::_Core::svn_config_ensure($config_dir, undef);
3229        my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3230        my $config = SVN::Core::config_get_config($config_dir);
3231        $RA = undef;
3232        my $dont_store_passwords = 1;
3233        my $conf_t = ${$config}{'config'};
3234        {
3235                no warnings 'once';
3236                # The usage of $SVN::_Core::SVN_CONFIG_* variables
3237                # produces warnings that variables are used only once.
3238                # I had not found the better way to shut them up, so
3239                # the warnings of type 'once' are disabled in this block.
3240                if (SVN::_Core::svn_config_get_bool($conf_t,
3241                    $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3242                    $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3243                    1) == 0) {
3244                        SVN::_Core::svn_auth_set_parameter($baton,
3245                            $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3246                            bless (\$dont_store_passwords, "_p_void"));
3247                }
3248                if (SVN::_Core::svn_config_get_bool($conf_t,
3249                    $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3250                    $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3251                    1) == 0) {
3252                        $Git::SVN::Prompt::_no_auth_cache = 1;
3253                }
3254        } # no warnings 'once'
3255        my $self = SVN::Ra->new(url => $url, auth => $baton,
3256                              config => $config,
3257                              pool => SVN::Pool->new,
3258                              auth_provider_callbacks => $callbacks);
3259        $self->{svn_path} = $url;
3260        $self->{repos_root} = $self->get_repos_root;
3261        $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3262        $self->{cache} = { check_path => { r => 0, data => {} },
3263                           get_dir => { r => 0, data => {} } };
3264        $RA = bless $self, $class;
3265}
3266
3267sub check_path {
3268        my ($self, $path, $r) = @_;
3269        my $cache = $self->{cache}->{check_path};
3270        if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3271                return $cache->{data}->{$path};
3272        }
3273        my $pool = SVN::Pool->new;
3274        my $t = $self->SUPER::check_path($path, $r, $pool);
3275        $pool->clear;
3276        if ($r != $cache->{r}) {
3277                %{$cache->{data}} = ();
3278                $cache->{r} = $r;
3279        }
3280        $cache->{data}->{$path} = $t;
3281}
3282
3283sub get_dir {
3284        my ($self, $dir, $r) = @_;
3285        my $cache = $self->{cache}->{get_dir};
3286        if ($r == $cache->{r}) {
3287                if (my $x = $cache->{data}->{$dir}) {
3288                        return wantarray ? @$x : $x->[0];
3289                }
3290        }
3291        my $pool = SVN::Pool->new;
3292        my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3293        my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3294        $pool->clear;
3295        if ($r != $cache->{r}) {
3296                %{$cache->{data}} = ();
3297                $cache->{r} = $r;
3298        }
3299        $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3300        wantarray ? (\%dirents, $r, $props) : \%dirents;
3301}
3302
3303sub DESTROY {
3304        # do not call the real DESTROY since we store ourselves in $RA
3305}
3306
3307sub get_log {
3308        my ($self, @args) = @_;
3309        my $pool = SVN::Pool->new;
3310        splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3311        my $ret = $self->SUPER::get_log(@args, $pool);
3312        $pool->clear;
3313        $ret;
3314}
3315
3316sub trees_match {
3317        my ($self, $url1, $rev1, $url2, $rev2) = @_;
3318        my $ctx = SVN::Client->new(auth => _auth_providers);
3319        my $out = IO::File->new_tmpfile;
3320
3321        # older SVN (1.1.x) doesn't take $pool as the last parameter for
3322        # $ctx->diff(), so we'll create a default one
3323        my $pool = SVN::Pool->new_default_sub;
3324
3325        $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3326        $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3327        $out->flush;
3328        my $ret = (($out->stat)[7] == 0);
3329        close $out or croak $!;
3330
3331        $ret;
3332}
3333
3334sub get_commit_editor {
3335        my ($self, $log, $cb, $pool) = @_;
3336        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3337        $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3338}
3339
3340sub gs_do_update {
3341        my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3342        my $new = ($rev_a == $rev_b);
3343        my $path = $gs->{path};
3344
3345        if ($new && -e $gs->{index}) {
3346                unlink $gs->{index} or die
3347                  "Couldn't unlink index: $gs->{index}: $!\n";
3348        }
3349        my $pool = SVN::Pool->new;
3350        $editor->set_path_strip($path);
3351        my (@pc) = split m#/#, $path;
3352        my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3353                                        1, $editor, $pool);
3354        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3355
3356        # Since we can't rely on svn_ra_reparent being available, we'll
3357        # just have to do some magic with set_path to make it so
3358        # we only want a partial path.
3359        my $sp = '';
3360        my $final = join('/', @pc);
3361        while (@pc) {
3362                $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3363                $sp .= '/' if length $sp;
3364                $sp .= shift @pc;
3365        }
3366        die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3367
3368        $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3369
3370        $reporter->finish_report($pool);
3371        $pool->clear;
3372        $editor->{git_commit_ok};
3373}
3374
3375# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3376# svn_ra_reparent didn't work before 1.4)
3377sub gs_do_switch {
3378        my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3379        my $path = $gs->{path};
3380        my $pool = SVN::Pool->new;
3381
3382        my $full_url = $self->{url};
3383        my $old_url = $full_url;
3384        $full_url .= "/$path" if length $path;
3385        my ($ra, $reparented);
3386        if ($old_url ne $full_url) {
3387                if ($old_url !~ m#^svn(\+ssh)?://#) {
3388                        SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3389                                                  $pool);
3390                        $self->{url} = $full_url;
3391                        $reparented = 1;
3392                } else {
3393                        $_[0] = undef;
3394                        $self = undef;
3395                        $RA = undef;
3396                        $ra = Git::SVN::Ra->new($full_url);
3397                        $ra_invalid = 1;
3398                }
3399        }
3400        $ra ||= $self;
3401        my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3402        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3403        $reporter->set_path('', $rev_a, 0, @lock, $pool);
3404        $reporter->finish_report($pool);
3405
3406        if ($reparented) {
3407                SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3408                $self->{url} = $old_url;
3409        }
3410
3411        $pool->clear;
3412        $editor->{git_commit_ok};
3413}
3414
3415sub longest_common_path {
3416        my ($gsv, $globs) = @_;
3417        my %common;
3418        my $common_max = scalar @$gsv;
3419
3420        foreach my $gs (@$gsv) {
3421                my @tmp = split m#/#, $gs->{path};
3422                my $p = '';
3423                foreach (@tmp) {
3424                        $p .= length($p) ? "/$_" : $_;
3425                        $common{$p} ||= 0;
3426                        $common{$p}++;
3427                }
3428        }
3429        $globs ||= [];
3430        $common_max += scalar @$globs;
3431        foreach my $glob (@$globs) {
3432                my @tmp = split m#/#, $glob->{path}->{left};
3433                my $p = '';
3434                foreach (@tmp) {
3435                        $p .= length($p) ? "/$_" : $_;
3436                        $common{$p} ||= 0;
3437                        $common{$p}++;
3438                }
3439        }
3440
3441        my $longest_path = '';
3442        foreach (sort {length $b <=> length $a} keys %common) {
3443                if ($common{$_} == $common_max) {
3444                        $longest_path = $_;
3445                        last;
3446                }
3447        }
3448        $longest_path;
3449}
3450
3451sub gs_fetch_loop_common {
3452        my ($self, $base, $head, $gsv, $globs) = @_;
3453        return if ($base > $head);
3454        my $inc = $_log_window_size;
3455        my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3456        my $longest_path = longest_common_path($gsv, $globs);
3457        my $ra_url = $self->{url};
3458        while (1) {
3459                my %revs;
3460                my $err;
3461                my $err_handler = $SVN::Error::handler;
3462                $SVN::Error::handler = sub {
3463                        ($err) = @_;
3464                        skip_unknown_revs($err);
3465                };
3466                sub _cb {
3467                        my ($paths, $r, $author, $date, $log) = @_;
3468                        [ dup_changed_paths($paths),
3469                          { author => $author, date => $date, log => $log } ];
3470                }
3471                $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3472                               sub { $revs{$_[1]} = _cb(@_) });
3473                if ($err && $max >= $head) {
3474                        print STDERR "Path '$longest_path' ",
3475                                     "was probably deleted:\n",
3476                                     $err->expanded_message,
3477                                     "\nWill attempt to follow ",
3478                                     "revisions r$min .. r$max ",
3479                                     "committed before the deletion\n";
3480                        my $hi = $max;
3481                        while (--$hi >= $min) {
3482                                my $ok;
3483                                $self->get_log([$longest_path], $min, $hi,
3484                                               0, 1, 1, sub {
3485                                               $ok ||= $_[1];
3486                                               $revs{$_[1]} = _cb(@_) });
3487                                if ($ok) {
3488                                        print STDERR "r$min .. r$ok OK\n";
3489                                        last;
3490                                }
3491                        }
3492                }
3493                $SVN::Error::handler = $err_handler;
3494
3495                my %exists = map { $_->{path} => $_ } @$gsv;
3496                foreach my $r (sort {$a <=> $b} keys %revs) {
3497                        my ($paths, $logged) = @{$revs{$r}};
3498
3499                        foreach my $gs ($self->match_globs(\%exists, $paths,
3500                                                           $globs, $r)) {
3501                                if ($gs->rev_db_max >= $r) {
3502                                        next;
3503                                }
3504                                next unless $gs->match_paths($paths, $r);
3505                                $gs->{logged_rev_props} = $logged;
3506                                if (my $last_commit = $gs->last_commit) {
3507                                        $gs->assert_index_clean($last_commit);
3508                                }
3509                                my $log_entry = $gs->do_fetch($paths, $r);
3510                                if ($log_entry) {
3511                                        $gs->do_git_commit($log_entry);
3512                                }
3513                        }
3514                        foreach my $g (@$globs) {
3515                                my $k = "svn-remote.$g->{remote}." .
3516                                        "$g->{t}-maxRev";
3517                                Git::SVN::tmp_config($k, $r);
3518                        }
3519                        if ($ra_invalid) {
3520                                $_[0] = undef;
3521                                $self = undef;
3522                                $RA = undef;
3523                                $self = Git::SVN::Ra->new($ra_url);
3524                                $ra_invalid = undef;
3525                        }
3526                }
3527                # pre-fill the .rev_db since it'll eventually get filled in
3528                # with '0' x40 if something new gets committed
3529                foreach my $gs (@$gsv) {
3530                        next if defined $gs->rev_db_get($max);
3531                        $gs->rev_db_set($max, 0 x40);
3532                }
3533                foreach my $g (@$globs) {
3534                        my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3535                        Git::SVN::tmp_config($k, $max);
3536                }
3537                last if $max >= $head;
3538                $min = $max + 1;
3539                $max += $inc;
3540                $max = $head if ($max > $head);
3541        }
3542}
3543
3544sub match_globs {
3545        my ($self, $exists, $paths, $globs, $r) = @_;
3546
3547        sub get_dir_check {
3548                my ($self, $exists, $g, $r) = @_;
3549                my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3550                return unless scalar @x == 3;
3551                my $dirents = $x[0];
3552                foreach my $de (keys %$dirents) {
3553                        next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3554                        my $p = $g->{path}->full_path($de);
3555                        next if $exists->{$p};
3556                        next if (length $g->{path}->{right} &&
3557                                 ($self->check_path($p, $r) !=
3558                                  $SVN::Node::dir));
3559                        $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3560                                         $g->{ref}->full_path($de), 1);
3561                }
3562        }
3563        foreach my $g (@$globs) {
3564                if (my $path = $paths->{"/$g->{path}->{left}"}) {
3565                        if ($path->{action} =~ /^[AR]$/) {
3566                                get_dir_check($self, $exists, $g, $r);
3567                        }
3568                }
3569                foreach (keys %$paths) {
3570                        if (/$g->{path}->{left_regex}/ &&
3571                            !/$g->{path}->{regex}/) {
3572                                next if $paths->{$_}->{action} !~ /^[AR]$/;
3573                                get_dir_check($self, $exists, $g, $r);
3574                        }
3575                        next unless /$g->{path}->{regex}/;
3576                        my $p = $1;
3577                        my $pathname = $g->{path}->full_path($p);
3578                        next if $exists->{$pathname};
3579                        next if ($self->check_path($pathname, $r) !=
3580                                 $SVN::Node::dir);
3581                        $exists->{$pathname} = Git::SVN->init(
3582                                              $self->{url}, $pathname, undef,
3583                                              $g->{ref}->full_path($p), 1);
3584                }
3585                my $c = '';
3586                foreach (split m#/#, $g->{path}->{left}) {
3587                        $c .= "/$_";
3588                        next unless ($paths->{$c} &&
3589                                     ($paths->{$c}->{action} =~ /^[AR]$/));
3590                        get_dir_check($self, $exists, $g, $r);
3591                }
3592        }
3593        values %$exists;
3594}
3595
3596sub minimize_url {
3597        my ($self) = @_;
3598        return $self->{url} if ($self->{url} eq $self->{repos_root});
3599        my $url = $self->{repos_root};
3600        my @components = split(m!/!, $self->{svn_path});
3601        my $c = '';
3602        do {
3603                $url .= "/$c" if length $c;
3604                eval { (ref $self)->new($url)->get_latest_revnum };
3605        } while ($@ && ($c = shift @components));
3606        $url;
3607}
3608
3609sub can_do_switch {
3610        my $self = shift;
3611        unless (defined $can_do_switch) {
3612                my $pool = SVN::Pool->new;
3613                my $rep = eval {
3614                        $self->do_switch(1, '', 0, $self->{url},
3615                                         SVN::Delta::Editor->new, $pool);
3616                };
3617                if ($@) {
3618                        $can_do_switch = 0;
3619                } else {
3620                        $rep->abort_report($pool);
3621                        $can_do_switch = 1;
3622                }
3623                $pool->clear;
3624        }
3625        $can_do_switch;
3626}
3627
3628sub skip_unknown_revs {
3629        my ($err) = @_;
3630        my $errno = $err->apr_err();
3631        # Maybe the branch we're tracking didn't
3632        # exist when the repo started, so it's
3633        # not an error if it doesn't, just continue
3634        #
3635        # Wonderfully consistent library, eh?
3636        # 160013 - svn:// and file://
3637        # 175002 - http(s)://
3638        # 175007 - http(s):// (this repo required authorization, too...)
3639        #   More codes may be discovered later...
3640        if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3641                my $err_key = $err->expanded_message;
3642                # revision numbers change every time, filter them out
3643                $err_key =~ s/\d+/\0/g;
3644                $err_key = "$errno\0$err_key";
3645                unless ($ignored_err{$err_key}) {
3646                        warn "W: Ignoring error from SVN, path probably ",
3647                             "does not exist: ($errno): ",
3648                             $err->expanded_message,"\n";
3649                        $ignored_err{$err_key} = 1;
3650                }
3651                return;
3652        }
3653        die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3654}
3655
3656# svn_log_changed_path_t objects passed to get_log are likely to be
3657# overwritten even if only the refs are copied to an external variable,
3658# so we should dup the structures in their entirety.  Using an externally
3659# passed pool (instead of our temporary and quickly cleared pool in
3660# Git::SVN::Ra) does not help matters at all...
3661sub dup_changed_paths {
3662        my ($paths) = @_;
3663        return undef unless $paths;
3664        my %ret;
3665        foreach my $p (keys %$paths) {
3666                my $i = $paths->{$p};
3667                my %s = map { $_ => $i->$_ }
3668                              qw/copyfrom_path copyfrom_rev action/;
3669                $ret{$p} = \%s;
3670        }
3671        \%ret;
3672}
3673
3674package Git::SVN::Log;
3675use strict;
3676use warnings;
3677use POSIX qw/strftime/;
3678use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3679            %rusers $show_commit $incremental/;
3680my $l_fmt;
3681
3682sub cmt_showable {
3683        my ($c) = @_;
3684        return 1 if defined $c->{r};
3685
3686        # big commit message got truncated by the 16k pretty buffer in rev-list
3687        if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3688                                $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3689                @{$c->{l}} = ();
3690                my @log = command(qw/cat-file commit/, $c->{c});
3691
3692                # shift off the headers
3693                shift @log while ($log[0] ne '');
3694                shift @log;
3695
3696                # TODO: make $c->{l} not have a trailing newline in the future
3697                @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3698
3699                (undef, $c->{r}, undef) = ::extract_metadata(
3700                                (grep(/^git-svn-id: /, @log))[-1]);
3701        }
3702        return defined $c->{r};
3703}
3704
3705sub log_use_color {
3706        return 1 if $color;
3707        my ($dc, $dcvar);
3708        $dcvar = 'color.diff';
3709        $dc = `git-config --get $dcvar`;
3710        if ($dc eq '') {
3711                # nothing at all; fallback to "diff.color"
3712                $dcvar = 'diff.color';
3713                $dc = `git-config --get $dcvar`;
3714        }
3715        chomp($dc);
3716        if ($dc eq 'auto') {
3717                my $pc;
3718                $pc = `git-config --get color.pager`;
3719                if ($pc eq '') {
3720                        # does not have it -- fallback to pager.color
3721                        $pc = `git-config --bool --get pager.color`;
3722                }
3723                else {
3724                        $pc = `git-config --bool --get color.pager`;
3725                        if ($?) {
3726                                $pc = 'false';
3727                        }
3728                }
3729                chomp($pc);
3730                if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3731                        return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3732                }
3733                return 0;
3734        }
3735        return 0 if $dc eq 'never';
3736        return 1 if $dc eq 'always';
3737        chomp($dc = `git-config --bool --get $dcvar`);
3738        return ($dc eq 'true');
3739}
3740
3741sub git_svn_log_cmd {
3742        my ($r_min, $r_max, @args) = @_;
3743        my $head = 'HEAD';
3744        my (@files, @log_opts);
3745        foreach my $x (@args) {
3746                if ($x eq '--' || @files) {
3747                        push @files, $x;
3748                } else {
3749                        if (::verify_ref("$x^0")) {
3750                                $head = $x;
3751                        } else {
3752                                push @log_opts, $x;
3753                        }
3754                }
3755        }
3756
3757        my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3758        $gs ||= Git::SVN->_new;
3759        my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3760                   $gs->refname);
3761        push @cmd, '-r' unless $non_recursive;
3762        push @cmd, qw/--raw --name-status/ if $verbose;
3763        push @cmd, '--color' if log_use_color();
3764        push @cmd, @log_opts;
3765        if (defined $r_max && $r_max == $r_min) {
3766                push @cmd, '--max-count=1';
3767                if (my $c = $gs->rev_db_get($r_max)) {
3768                        push @cmd, $c;
3769                }
3770        } elsif (defined $r_max) {
3771                my ($c_min, $c_max);
3772                $c_max = $gs->rev_db_get($r_max);
3773                $c_min = $gs->rev_db_get($r_min);
3774                if (defined $c_min && defined $c_max) {
3775                        if ($r_max > $r_max) {
3776                                push @cmd, "$c_min..$c_max";
3777                        } else {
3778                                push @cmd, "$c_max..$c_min";
3779                        }
3780                } elsif ($r_max > $r_min) {
3781                        push @cmd, $c_max;
3782                } else {
3783                        push @cmd, $c_min;
3784                }
3785        }
3786        return (@cmd, @files);
3787}
3788
3789# adapted from pager.c
3790sub config_pager {
3791        $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3792        if (!defined $pager) {
3793                $pager = 'less';
3794        } elsif (length $pager == 0 || $pager eq 'cat') {
3795                $pager = undef;
3796        }
3797}
3798
3799sub run_pager {
3800        return unless -t *STDOUT && defined $pager;
3801        pipe my $rfd, my $wfd or return;
3802        defined(my $pid = fork) or ::fatal "Can't fork: $!";
3803        if (!$pid) {
3804                open STDOUT, '>&', $wfd or
3805                                     ::fatal "Can't redirect to stdout: $!";
3806                return;
3807        }
3808        open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
3809        $ENV{LESS} ||= 'FRSX';
3810        exec $pager or ::fatal "Can't run pager: $! ($pager)";
3811}
3812
3813sub tz_to_s_offset {
3814        my ($tz) = @_;
3815        $tz =~ s/(\d\d)$//;
3816        return ($1 * 60) + ($tz * 3600);
3817}
3818
3819sub get_author_info {
3820        my ($dest, $author, $t, $tz) = @_;
3821        $author =~ s/(?:^\s*|\s*$)//g;
3822        $dest->{a_raw} = $author;
3823        my $au;
3824        if ($::_authors) {
3825                $au = $rusers{$author} || undef;
3826        }
3827        if (!$au) {
3828                ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3829        }
3830        $dest->{t} = $t;
3831        $dest->{tz} = $tz;
3832        $dest->{a} = $au;
3833        # Date::Parse isn't in the standard Perl distro :(
3834        if ($tz =~ s/^\+//) {
3835                $t += tz_to_s_offset($tz);
3836        } elsif ($tz =~ s/^\-//) {
3837                $t -= tz_to_s_offset($tz);
3838        }
3839        $dest->{t_utc} = $t;
3840}
3841
3842sub process_commit {
3843        my ($c, $r_min, $r_max, $defer) = @_;
3844        if (defined $r_min && defined $r_max) {
3845                if ($r_min == $c->{r} && $r_min == $r_max) {
3846                        show_commit($c);
3847                        return 0;
3848                }
3849                return 1 if $r_min == $r_max;
3850                if ($r_min < $r_max) {
3851                        # we need to reverse the print order
3852                        return 0 if (defined $limit && --$limit < 0);
3853                        push @$defer, $c;
3854                        return 1;
3855                }
3856                if ($r_min != $r_max) {
3857                        return 1 if ($r_min < $c->{r});
3858                        return 1 if ($r_max > $c->{r});
3859                }
3860        }
3861        return 0 if (defined $limit && --$limit < 0);
3862        show_commit($c);
3863        return 1;
3864}
3865
3866sub show_commit {
3867        my $c = shift;
3868        if ($oneline) {
3869                my $x = "\n";
3870                if (my $l = $c->{l}) {
3871                        while ($l->[0] =~ /^\s*$/) { shift @$l }
3872                        $x = $l->[0];
3873                }
3874                $l_fmt ||= 'A' . length($c->{r});
3875                print 'r',pack($l_fmt, $c->{r}),' | ';
3876                print "$c->{c} | " if $show_commit;
3877                print $x;
3878        } else {
3879                show_commit_normal($c);
3880        }
3881}
3882
3883sub show_commit_changed_paths {
3884        my ($c) = @_;
3885        return unless $c->{changed};
3886        print "Changed paths:\n", @{$c->{changed}};
3887}
3888
3889sub show_commit_normal {
3890        my ($c) = @_;
3891        print '-' x72, "\nr$c->{r} | ";
3892        print "$c->{c} | " if $show_commit;
3893        print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3894                                 localtime($c->{t_utc})), ' | ';
3895        my $nr_line = 0;
3896
3897        if (my $l = $c->{l}) {
3898                while ($l->[$#$l] eq "\n" && $#$l > 0
3899                                          && $l->[($#$l - 1)] eq "\n") {
3900                        pop @$l;
3901                }
3902                $nr_line = scalar @$l;
3903                if (!$nr_line) {
3904                        print "1 line\n\n\n";
3905                } else {
3906                        if ($nr_line == 1) {
3907                                $nr_line = '1 line';
3908                        } else {
3909                                $nr_line .= ' lines';
3910                        }
3911                        print $nr_line, "\n";
3912                        show_commit_changed_paths($c);
3913                        print "\n";
3914                        print $_ foreach @$l;
3915                }
3916        } else {
3917                print "1 line\n";
3918                show_commit_changed_paths($c);
3919                print "\n";
3920
3921        }
3922        foreach my $x (qw/raw stat diff/) {
3923                if ($c->{$x}) {
3924                        print "\n";
3925                        print $_ foreach @{$c->{$x}}
3926                }
3927        }
3928}
3929
3930sub cmd_show_log {
3931        my (@args) = @_;
3932        my ($r_min, $r_max);
3933        my $r_last = -1; # prevent dupes
3934        if (defined $TZ) {
3935                $ENV{TZ} = $TZ;
3936        } else {
3937                delete $ENV{TZ};
3938        }
3939        if (defined $::_revision) {
3940                if ($::_revision =~ /^(\d+):(\d+)$/) {
3941                        ($r_min, $r_max) = ($1, $2);
3942                } elsif ($::_revision =~ /^\d+$/) {
3943                        $r_min = $r_max = $::_revision;
3944                } else {
3945                        ::fatal "-r$::_revision is not supported, use ",
3946                                "standard 'git log' arguments instead";
3947                }
3948        }
3949
3950        config_pager();
3951        @args = git_svn_log_cmd($r_min, $r_max, @args);
3952        my $log = command_output_pipe(@args);
3953        run_pager();
3954        my (@k, $c, $d, $stat);
3955        my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3956        while (<$log>) {
3957                if (/^${esc_color}commit ($::sha1_short)/o) {
3958                        my $cmt = $1;
3959                        if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3960                                $r_last = $c->{r};
3961                                process_commit($c, $r_min, $r_max, \@k) or
3962                                                                goto out;
3963                        }
3964                        $d = undef;
3965                        $c = { c => $cmt };
3966                } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3967                        get_author_info($c, $1, $2, $3);
3968                } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3969                        # ignore
3970                } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3971                        push @{$c->{raw}}, $_;
3972                } elsif (/^${esc_color}[ACRMDT]\t/) {
3973                        # we could add $SVN->{svn_path} here, but that requires
3974                        # remote access at the moment (repo_path_split)...
3975                        s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
3976                        push @{$c->{changed}}, $_;
3977                } elsif (/^${esc_color}diff /o) {
3978                        $d = 1;
3979                        push @{$c->{diff}}, $_;
3980                } elsif ($d) {
3981                        push @{$c->{diff}}, $_;
3982                } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3983                          $esc_color*[\+\-]*$esc_color$/x) {
3984                        $stat = 1;
3985                        push @{$c->{stat}}, $_;
3986                } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3987                        push @{$c->{stat}}, $_;
3988                        $stat = undef;
3989                } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
3990                        ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3991                } elsif (s/^${esc_color}    //o) {
3992                        push @{$c->{l}}, $_;
3993                }
3994        }
3995        if ($c && defined $c->{r} && $c->{r} != $r_last) {
3996                $r_last = $c->{r};
3997                process_commit($c, $r_min, $r_max, \@k);
3998        }
3999        if (@k) {
4000                my $swap = $r_max;
4001                $r_max = $r_min;
4002                $r_min = $swap;
4003                process_commit($_, $r_min, $r_max) foreach reverse @k;
4004        }
4005out:
4006        close $log;
4007        print '-' x72,"\n" unless $incremental || $oneline;
4008}
4009
4010package Git::SVN::Migration;
4011# these version numbers do NOT correspond to actual version numbers
4012# of git nor git-svn.  They are just relative.
4013#
4014# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4015#
4016# v1 layout: .git/$id/info/url, refs/remotes/$id
4017#
4018# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4019#
4020# v3 layout: .git/svn/$id, refs/remotes/$id
4021#            - info/url may remain for backwards compatibility
4022#            - this is what we migrate up to this layout automatically,
4023#            - this will be used by git svn init on single branches
4024# v3.1 layout (auto migrated):
4025#            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4026#              for backwards compatibility
4027#
4028# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4029#            - this is only created for newly multi-init-ed
4030#              repositories.  Similar in spirit to the
4031#              --use-separate-remotes option in git-clone (now default)
4032#            - we do not automatically migrate to this (following
4033#              the example set by core git)
4034use strict;
4035use warnings;
4036use Carp qw/croak/;
4037use File::Path qw/mkpath/;
4038use File::Basename qw/dirname basename/;
4039use vars qw/$_minimize/;
4040
4041sub migrate_from_v0 {
4042        my $git_dir = $ENV{GIT_DIR};
4043        return undef unless -d $git_dir;
4044        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4045        my $migrated = 0;
4046        while (<$fh>) {
4047                chomp;
4048                my ($id, $orig_ref) = ($_, $_);
4049                next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4050                next unless -f "$git_dir/$id/info/url";
4051                my $new_ref = "refs/remotes/$id";
4052                if (::verify_ref("$new_ref^0")) {
4053                        print STDERR "W: $orig_ref is probably an old ",
4054                                     "branch used by an ancient version of ",
4055                                     "git-svn.\n",
4056                                     "However, $new_ref also exists.\n",
4057                                     "We will not be able ",
4058                                     "to use this branch until this ",
4059                                     "ambiguity is resolved.\n";
4060                        next;
4061                }
4062                print STDERR "Migrating from v0 layout...\n" if !$migrated;
4063                print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4064                command_noisy('update-ref', $new_ref, $orig_ref);
4065                command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4066                $migrated++;
4067        }
4068        command_close_pipe($fh, $ctx);
4069        print STDERR "Done migrating from v0 layout...\n" if $migrated;
4070        $migrated;
4071}
4072
4073sub migrate_from_v1 {
4074        my $git_dir = $ENV{GIT_DIR};
4075        my $migrated = 0;
4076        return $migrated unless -d $git_dir;
4077        my $svn_dir = "$git_dir/svn";
4078
4079        # just in case somebody used 'svn' as their $id at some point...
4080        return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4081
4082        print STDERR "Migrating from a git-svn v1 layout...\n";
4083        mkpath([$svn_dir]);
4084        print STDERR "Data from a previous version of git-svn exists, but\n\t",
4085                     "$svn_dir\n\t(required for this version ",
4086                     "($::VERSION) of git-svn) does not. exist\n";
4087        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4088        while (<$fh>) {
4089                my $x = $_;
4090                next unless $x =~ s#^refs/remotes/##;
4091                chomp $x;
4092                next unless -f "$git_dir/$x/info/url";
4093                my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4094                next unless $u;
4095                my $dn = dirname("$git_dir/svn/$x");
4096                mkpath([$dn]) unless -d $dn;
4097                if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4098                        mkpath(["$git_dir/svn/svn"]);
4099                        print STDERR " - $git_dir/$x/info => ",
4100                                        "$git_dir/svn/$x/info\n";
4101                        rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4102                               croak "$!: $x";
4103                        # don't worry too much about these, they probably
4104                        # don't exist with repos this old (save for index,
4105                        # and we can easily regenerate that)
4106                        foreach my $f (qw/unhandled.log index .rev_db/) {
4107                                rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4108                        }
4109                } else {
4110                        print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4111                        rename "$git_dir/$x", "$git_dir/svn/$x" or
4112                               croak "$!: $x";
4113                }
4114                $migrated++;
4115        }
4116        command_close_pipe($fh, $ctx);
4117        print STDERR "Done migrating from a git-svn v1 layout\n";
4118        $migrated;
4119}
4120
4121sub read_old_urls {
4122        my ($l_map, $pfx, $path) = @_;
4123        my @dir;
4124        foreach (<$path/*>) {
4125                if (-r "$_/info/url") {
4126                        $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4127                        my $ref_id = $pfx . basename $_;
4128                        my $url = ::file_to_s("$_/info/url");
4129                        $l_map->{$ref_id} = $url;
4130                } elsif (-d $_) {
4131                        push @dir, $_;
4132                }
4133        }
4134        foreach (@dir) {
4135                my $x = $_;
4136                $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4137                read_old_urls($l_map, $x, $_);
4138        }
4139}
4140
4141sub migrate_from_v2 {
4142        my @cfg = command(qw/config -l/);
4143        return if grep /^svn-remote\..+\.url=/, @cfg;
4144        my %l_map;
4145        read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4146        my $migrated = 0;
4147
4148        foreach my $ref_id (sort keys %l_map) {
4149                eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4150                if ($@) {
4151                        Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4152                }
4153                $migrated++;
4154        }
4155        $migrated;
4156}
4157
4158sub minimize_connections {
4159        my $r = Git::SVN::read_all_remotes();
4160        my $new_urls = {};
4161        my $root_repos = {};
4162        foreach my $repo_id (keys %$r) {
4163                my $url = $r->{$repo_id}->{url} or next;
4164                my $fetch = $r->{$repo_id}->{fetch} or next;
4165                my $ra = Git::SVN::Ra->new($url);
4166
4167                # skip existing cases where we already connect to the root
4168                if (($ra->{url} eq $ra->{repos_root}) ||
4169                    (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4170                     $repo_id)) {
4171                        $root_repos->{$ra->{url}} = $repo_id;
4172                        next;
4173                }
4174
4175                my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4176                my $root_path = $ra->{url};
4177                $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4178                foreach my $path (keys %$fetch) {
4179                        my $ref_id = $fetch->{$path};
4180                        my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4181
4182                        # make sure we can read when connecting to
4183                        # a higher level of a repository
4184                        my ($last_rev, undef) = $gs->last_rev_commit;
4185                        if (!defined $last_rev) {
4186                                $last_rev = eval {
4187                                        $root_ra->get_latest_revnum;
4188                                };
4189                                next if $@;
4190                        }
4191                        my $new = $root_path;
4192                        $new .= length $path ? "/$path" : '';
4193                        eval {
4194                                $root_ra->get_log([$new], $last_rev, $last_rev,
4195                                                  0, 0, 1, sub { });
4196                        };
4197                        next if $@;
4198                        $new_urls->{$ra->{repos_root}}->{$new} =
4199                                { ref_id => $ref_id,
4200                                  old_repo_id => $repo_id,
4201                                  old_path => $path };
4202                }
4203        }
4204
4205        my @emptied;
4206        foreach my $url (keys %$new_urls) {
4207                # see if we can re-use an existing [svn-remote "repo_id"]
4208                # instead of creating a(n ugly) new section:
4209                my $repo_id = $root_repos->{$url} ||
4210                              Git::SVN::sanitize_remote_name($url);
4211
4212                my $fetch = $new_urls->{$url};
4213                foreach my $path (keys %$fetch) {
4214                        my $x = $fetch->{$path};
4215                        Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4216                        my $pfx = "svn-remote.$x->{old_repo_id}";
4217
4218                        my $old_fetch = quotemeta("$x->{old_path}:".
4219                                                  "refs/remotes/$x->{ref_id}");
4220                        command_noisy(qw/config --unset/,
4221                                      "$pfx.fetch", '^'. $old_fetch . '$');
4222                        delete $r->{$x->{old_repo_id}}->
4223                               {fetch}->{$x->{old_path}};
4224                        if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4225                                command_noisy(qw/config --unset/,
4226                                              "$pfx.url");
4227                                push @emptied, $x->{old_repo_id}
4228                        }
4229                }
4230        }
4231        if (@emptied) {
4232                my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4233                           "$ENV{GIT_DIR}/config";
4234                print STDERR <<EOF;
4235The following [svn-remote] sections in your config file ($file) are empty
4236and can be safely removed:
4237EOF
4238                print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4239        }
4240}
4241
4242sub migration_check {
4243        migrate_from_v0();
4244        migrate_from_v1();
4245        migrate_from_v2();
4246        minimize_connections() if $_minimize;
4247}
4248
4249package Git::IndexInfo;
4250use strict;
4251use warnings;
4252use Git qw/command_input_pipe command_close_pipe/;
4253
4254sub new {
4255        my ($class) = @_;
4256        my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4257        bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4258}
4259
4260sub remove {
4261        my ($self, $path) = @_;
4262        if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4263                return ++$self->{nr};
4264        }
4265        undef;
4266}
4267
4268sub update {
4269        my ($self, $mode, $hash, $path) = @_;
4270        if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4271                return ++$self->{nr};
4272        }
4273        undef;
4274}
4275
4276sub DESTROY {
4277        my ($self) = @_;
4278        command_close_pipe($self->{gui}, $self->{ctx});
4279}
4280
4281package Git::SVN::GlobSpec;
4282use strict;
4283use warnings;
4284
4285sub new {
4286        my ($class, $glob) = @_;
4287        my $re = $glob;
4288        $re =~ s!/+$!!g; # no need for trailing slashes
4289        my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4290        my ($left, $right) = ($1, $2);
4291        if ($nr > 1) {
4292                die "Only one '*' wildcard expansion ",
4293                    "is supported (got $nr): '$glob'\n";
4294        } elsif ($nr == 0) {
4295                die "One '*' is needed for glob: '$glob'\n";
4296        }
4297        $re = quotemeta($left) . $re . quotemeta($right);
4298        if (length $left && !($left =~ s!/+$!!g)) {
4299                die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4300        }
4301        if (length $right && !($right =~ s!^/+!!g)) {
4302                die "Missing leading '/' on right side of: '$glob' ($right)\n";
4303        }
4304        my $left_re = qr/^\/\Q$left\E(\/|$)/;
4305        bless { left => $left, right => $right, left_regex => $left_re,
4306                regex => qr/$re/, glob => $glob }, $class;
4307}
4308
4309sub full_path {
4310        my ($self, $path) = @_;
4311        return (length $self->{left} ? "$self->{left}/" : '') .
4312               $path . (length $self->{right} ? "/$self->{right}" : '');
4313}
4314
4315__END__
4316
4317Data structures:
4318
4319
4320$remotes = { # returned by read_all_remotes()
4321        'svn' => {
4322                # svn-remote.svn.url=https://svn.musicpd.org
4323                url => 'https://svn.musicpd.org',
4324                # svn-remote.svn.fetch=mpd/trunk:trunk
4325                fetch => {
4326                        'mpd/trunk' => 'trunk',
4327                },
4328                # svn-remote.svn.tags=mpd/tags/*:tags/*
4329                tags => {
4330                        path => {
4331                                left => 'mpd/tags',
4332                                right => '',
4333                                regex => qr!mpd/tags/([^/]+)$!,
4334                                glob => 'tags/*',
4335                        },
4336                        ref => {
4337                                left => 'tags',
4338                                right => '',
4339                                regex => qr!tags/([^/]+)$!,
4340                                glob => 'tags/*',
4341                        },
4342                }
4343        }
4344};
4345
4346$log_entry hashref as returned by libsvn_log_entry()
4347{
4348        log => 'whitespace-formatted log entry
4349',                                              # trailing newline is preserved
4350        revision => '8',                        # integer
4351        date => '2004-02-24T17:01:44.108345Z',  # commit date
4352        author => 'committer name'
4353};
4354
4355
4356# this is generated by generate_diff();
4357@mods = array of diff-index line hashes, each element represents one line
4358        of diff-index output
4359
4360diff-index line ($m hash)
4361{
4362        mode_a => first column of diff-index output, no leading ':',
4363        mode_b => second column of diff-index output,
4364        sha1_b => sha1sum of the final blob,
4365        chg => change type [MCRADT],
4366        file_a => original file name of a file (iff chg is 'C' or 'R')
4367        file_b => new/current file name of a file (any chg)
4368}
4369;
4370
4371# retval of read_url_paths{,_all}();
4372$l_map = {
4373        # repository root url
4374        'https://svn.musicpd.org' => {
4375                # repository path               # GIT_SVN_ID
4376                'mpd/trunk'             =>      'trunk',
4377                'mpd/tags/0.11.5'       =>      'tags/0.11.5',
4378        },
4379}
4380
4381Notes:
4382        I don't trust the each() function on unless I created %hash myself
4383        because the internal iterator may not have started at base.