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