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