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