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