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