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