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