55c4dfb96879626228c940c06aa6e0a29518f2e9
   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 $_repository
   8                $_q $_authors %users/;
   9$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
  10$VERSION = '@@GIT_VERSION@@';
  11
  12# From which subdir have we been invoked?
  13my $cmd_dir_prefix = eval {
  14        command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
  15} || '';
  16
  17my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
  18$ENV{GIT_DIR} ||= '.git';
  19$Git::SVN::default_repo_id = 'svn';
  20$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
  21$Git::SVN::Ra::_log_window_size = 100;
  22
  23$Git::SVN::Log::TZ = $ENV{TZ};
  24$ENV{TZ} = 'UTC';
  25$| = 1; # unbuffer STDOUT
  26
  27sub fatal (@) { print STDERR "@_\n"; exit 1 }
  28require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
  29require SVN::Ra;
  30require SVN::Delta;
  31if ($SVN::Core::VERSION lt '1.1.0') {
  32        fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
  33}
  34push @Git::SVN::Ra::ISA, 'SVN::Ra';
  35push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
  36push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
  37use Carp qw/croak/;
  38use Digest::MD5;
  39use IO::File qw//;
  40use File::Basename qw/dirname basename/;
  41use File::Path qw/mkpath/;
  42use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
  43use IPC::Open3;
  44use Git;
  45
  46BEGIN {
  47        # import functions from Git into our packages, en masse
  48        no strict 'refs';
  49        foreach (qw/command command_oneline command_noisy command_output_pipe
  50                    command_input_pipe command_close_pipe/) {
  51                for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
  52                        Git::SVN::Migration Git::SVN::Log Git::SVN),
  53                        __PACKAGE__) {
  54                        *{"${package}::$_"} = \&{"Git::$_"};
  55                }
  56        }
  57}
  58
  59my ($SVN);
  60
  61$sha1 = qr/[a-f\d]{40}/;
  62$sha1_short = qr/[a-f\d]{4,40}/;
  63my ($_stdin, $_help, $_edit,
  64        $_message, $_file,
  65        $_template, $_shared,
  66        $_version, $_fetch_all, $_no_rebase,
  67        $_merge, $_strategy, $_dry_run, $_local,
  68        $_prefix, $_no_checkout, $_url, $_verbose,
  69        $_git_format, $_commit_url, $_tag);
  70$Git::SVN::_follow_parent = 1;
  71my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
  72                    'config-dir=s' => \$Git::SVN::Ra::config_dir,
  73                    'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
  74my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
  75                'authors-file|A=s' => \$_authors,
  76                'repack:i' => \$Git::SVN::_repack,
  77                'noMetadata' => \$Git::SVN::_no_metadata,
  78                'useSvmProps' => \$Git::SVN::_use_svm_props,
  79                'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
  80                'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
  81                'no-checkout' => \$_no_checkout,
  82                'quiet|q' => \$_q,
  83                'repack-flags|repack-args|repack-opts=s' =>
  84                   \$Git::SVN::_repack_flags,
  85                'use-log-author' => \$Git::SVN::_use_log_author,
  86                'add-author-from' => \$Git::SVN::_add_author_from,
  87                'localtime' => \$Git::SVN::_localtime,
  88                %remote_opts );
  89
  90my ($_trunk, $_tags, $_branches, $_stdlayout);
  91my %icv;
  92my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
  93                  'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
  94                  'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
  95                  'stdlayout|s' => \$_stdlayout,
  96                  'minimize-url|m' => \$Git::SVN::_minimize_url,
  97                  'no-metadata' => sub { $icv{noMetadata} = 1 },
  98                  'use-svm-props' => sub { $icv{useSvmProps} = 1 },
  99                  'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
 100                  'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
 101                  %remote_opts );
 102my %cmt_opts = ( 'edit|e' => \$_edit,
 103                'rmdir' => \$SVN::Git::Editor::_rmdir,
 104                'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
 105                'l=i' => \$SVN::Git::Editor::_rename_limit,
 106                'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
 107);
 108
 109my %cmd = (
 110        fetch => [ \&cmd_fetch, "Download new revisions from SVN",
 111                        { 'revision|r=s' => \$_revision,
 112                          'fetch-all|all' => \$_fetch_all,
 113                           %fc_opts } ],
 114        clone => [ \&cmd_clone, "Initialize and fetch revisions",
 115                        { 'revision|r=s' => \$_revision,
 116                           %fc_opts, %init_opts } ],
 117        init => [ \&cmd_init, "Initialize a repo for tracking" .
 118                          " (requires URL argument)",
 119                          \%init_opts ],
 120        'multi-init' => [ \&cmd_multi_init,
 121                          "Deprecated alias for ".
 122                          "'$0 init -T<trunk> -b<branches> -t<tags>'",
 123                          \%init_opts ],
 124        dcommit => [ \&cmd_dcommit,
 125                     'Commit several diffs to merge with upstream',
 126                        { 'merge|m|M' => \$_merge,
 127                          'strategy|s=s' => \$_strategy,
 128                          'verbose|v' => \$_verbose,
 129                          'dry-run|n' => \$_dry_run,
 130                          'fetch-all|all' => \$_fetch_all,
 131                          'commit-url=s' => \$_commit_url,
 132                          'revision|r=i' => \$_revision,
 133                          'no-rebase' => \$_no_rebase,
 134                        %cmt_opts, %fc_opts } ],
 135        branch => [ \&cmd_branch,
 136                    'Create a branch in the SVN repository',
 137                    { 'message|m=s' => \$_message,
 138                      'dry-run|n' => \$_dry_run,
 139                      'tag|t' => \$_tag } ],
 140        tag => [ sub { $_tag = 1; cmd_branch(@_) },
 141                 'Create a tag in the SVN repository',
 142                 { 'message|m=s' => \$_message,
 143                   'dry-run|n' => \$_dry_run } ],
 144        'set-tree' => [ \&cmd_set_tree,
 145                        "Set an SVN repository to a git tree-ish",
 146                        { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
 147        'create-ignore' => [ \&cmd_create_ignore,
 148                             'Create a .gitignore per svn:ignore',
 149                             { 'revision|r=i' => \$_revision
 150                             } ],
 151        'propget' => [ \&cmd_propget,
 152                       'Print the value of a property on a file or directory',
 153                       { 'revision|r=i' => \$_revision } ],
 154        'proplist' => [ \&cmd_proplist,
 155                       'List all properties of a file or directory',
 156                       { 'revision|r=i' => \$_revision } ],
 157        'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
 158                        { 'revision|r=i' => \$_revision
 159                        } ],
 160        'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
 161                        { 'revision|r=i' => \$_revision
 162                        } ],
 163        'multi-fetch' => [ \&cmd_multi_fetch,
 164                           "Deprecated alias for $0 fetch --all",
 165                           { 'revision|r=s' => \$_revision, %fc_opts } ],
 166        'migrate' => [ sub { },
 167                       # no-op, we automatically run this anyways,
 168                       'Migrate configuration/metadata/layout from
 169                        previous versions of git-svn',
 170                       { 'minimize' => \$Git::SVN::Migration::_minimize,
 171                         %remote_opts } ],
 172        'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
 173                        { 'limit=i' => \$Git::SVN::Log::limit,
 174                          'revision|r=s' => \$_revision,
 175                          'verbose|v' => \$Git::SVN::Log::verbose,
 176                          'incremental' => \$Git::SVN::Log::incremental,
 177                          'oneline' => \$Git::SVN::Log::oneline,
 178                          'show-commit' => \$Git::SVN::Log::show_commit,
 179                          'non-recursive' => \$Git::SVN::Log::non_recursive,
 180                          'authors-file|A=s' => \$_authors,
 181                          'color' => \$Git::SVN::Log::color,
 182                          'pager=s' => \$Git::SVN::Log::pager
 183                        } ],
 184        'find-rev' => [ \&cmd_find_rev,
 185                        "Translate between SVN revision numbers and tree-ish",
 186                        {} ],
 187        'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
 188                        { 'merge|m|M' => \$_merge,
 189                          'verbose|v' => \$_verbose,
 190                          'strategy|s=s' => \$_strategy,
 191                          'local|l' => \$_local,
 192                          'fetch-all|all' => \$_fetch_all,
 193                          'dry-run|n' => \$_dry_run,
 194                          %fc_opts } ],
 195        'commit-diff' => [ \&cmd_commit_diff,
 196                           'Commit a diff between two trees',
 197                        { 'message|m=s' => \$_message,
 198                          'file|F=s' => \$_file,
 199                          'revision|r=s' => \$_revision,
 200                        %cmt_opts } ],
 201        'info' => [ \&cmd_info,
 202                    "Show info about the latest SVN revision
 203                     on the current branch",
 204                    { 'url' => \$_url, } ],
 205        'blame' => [ \&Git::SVN::Log::cmd_blame,
 206                    "Show what revision and author last modified each line of a file",
 207                    { 'git-format' => \$_git_format } ],
 208);
 209
 210my $cmd;
 211for (my $i = 0; $i < @ARGV; $i++) {
 212        if (defined $cmd{$ARGV[$i]}) {
 213                $cmd = $ARGV[$i];
 214                splice @ARGV, $i, 1;
 215                last;
 216        }
 217};
 218
 219# make sure we're always running at the top-level working directory
 220unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
 221        unless (-d $ENV{GIT_DIR}) {
 222                if ($git_dir_user_set) {
 223                        die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
 224                            "but it is not a directory\n";
 225                }
 226                my $git_dir = delete $ENV{GIT_DIR};
 227                my $cdup = undef;
 228                git_cmd_try {
 229                        $cdup = command_oneline(qw/rev-parse --show-cdup/);
 230                        $git_dir = '.' unless ($cdup);
 231                        chomp $cdup if ($cdup);
 232                        $cdup = "." unless ($cdup && length $cdup);
 233                } "Already at toplevel, but $git_dir not found\n";
 234                chdir $cdup or die "Unable to chdir up to '$cdup'\n";
 235                unless (-d $git_dir) {
 236                        die "$git_dir still not found after going to ",
 237                            "'$cdup'\n";
 238                }
 239                $ENV{GIT_DIR} = $git_dir;
 240        }
 241        $_repository = Git->repository(Repository => $ENV{GIT_DIR});
 242}
 243
 244my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
 245
 246read_repo_config(\%opts);
 247if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
 248        Getopt::Long::Configure('pass_through');
 249}
 250my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
 251                    'minimize-connections' => \$Git::SVN::Migration::_minimize,
 252                    'id|i=s' => \$Git::SVN::default_ref_id,
 253                    'svn-remote|remote|R=s' => sub {
 254                       $Git::SVN::no_reuse_existing = 1;
 255                       $Git::SVN::default_repo_id = $_[1] });
 256exit 1 if (!$rv && $cmd && $cmd ne 'log');
 257
 258usage(0) if $_help;
 259version() if $_version;
 260usage(1) unless defined $cmd;
 261load_authors() if $_authors;
 262
 263unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
 264        Git::SVN::Migration::migration_check();
 265}
 266Git::SVN::init_vars();
 267eval {
 268        Git::SVN::verify_remotes_sanity();
 269        $cmd{$cmd}->[0]->(@ARGV);
 270};
 271fatal $@ if $@;
 272post_fetch_checkout();
 273exit 0;
 274
 275####################### primary functions ######################
 276sub usage {
 277        my $exit = shift || 0;
 278        my $fd = $exit ? \*STDERR : \*STDOUT;
 279        print $fd <<"";
 280git-svn - bidirectional operations between a single Subversion tree and git
 281Usage: git svn <command> [options] [arguments]\n
 282
 283        print $fd "Available commands:\n" unless $cmd;
 284
 285        foreach (sort keys %cmd) {
 286                next if $cmd && $cmd ne $_;
 287                next if /^multi-/; # don't show deprecated commands
 288                print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
 289                foreach (sort keys %{$cmd{$_}->[2]}) {
 290                        # mixed-case options are for .git/config only
 291                        next if /[A-Z]/ && /^[a-z]+$/i;
 292                        # prints out arguments as they should be passed:
 293                        my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
 294                        print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
 295                                                        "--$_" : "-$_" }
 296                                                split /\|/,$_)," $x\n";
 297                }
 298        }
 299        print $fd <<"";
 300\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
 301arbitrary identifier if you're tracking multiple SVN branches/repositories in
 302one git repository and want to keep them separate.  See git-svn(1) for more
 303information.
 304
 305        exit $exit;
 306}
 307
 308sub version {
 309        print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
 310        exit 0;
 311}
 312
 313sub do_git_init_db {
 314        unless (-d $ENV{GIT_DIR}) {
 315                my @init_db = ('init');
 316                push @init_db, "--template=$_template" if defined $_template;
 317                if (defined $_shared) {
 318                        if ($_shared =~ /[a-z]/) {
 319                                push @init_db, "--shared=$_shared";
 320                        } else {
 321                                push @init_db, "--shared";
 322                        }
 323                }
 324                command_noisy(@init_db);
 325                $_repository = Git->repository(Repository => ".git");
 326        }
 327        my $set;
 328        my $pfx = "svn-remote.$Git::SVN::default_repo_id";
 329        foreach my $i (keys %icv) {
 330                die "'$set' and '$i' cannot both be set\n" if $set;
 331                next unless defined $icv{$i};
 332                command_noisy('config', "$pfx.$i", $icv{$i});
 333                $set = $i;
 334        }
 335}
 336
 337sub init_subdir {
 338        my $repo_path = shift or return;
 339        mkpath([$repo_path]) unless -d $repo_path;
 340        chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
 341        $ENV{GIT_DIR} = '.git';
 342        $_repository = Git->repository(Repository => $ENV{GIT_DIR});
 343}
 344
 345sub cmd_clone {
 346        my ($url, $path) = @_;
 347        if (!defined $path &&
 348            (defined $_trunk || defined $_branches || defined $_tags ||
 349             defined $_stdlayout) &&
 350            $url !~ m#^[a-z\+]+://#) {
 351                $path = $url;
 352        }
 353        $path = basename($url) if !defined $path || !length $path;
 354        cmd_init($url, $path);
 355        Git::SVN::fetch_all($Git::SVN::default_repo_id);
 356}
 357
 358sub cmd_init {
 359        if (defined $_stdlayout) {
 360                $_trunk = 'trunk' if (!defined $_trunk);
 361                $_tags = 'tags' if (!defined $_tags);
 362                $_branches = 'branches' if (!defined $_branches);
 363        }
 364        if (defined $_trunk || defined $_branches || defined $_tags) {
 365                return cmd_multi_init(@_);
 366        }
 367        my $url = shift or die "SVN repository location required ",
 368                               "as a command-line argument\n";
 369        init_subdir(@_);
 370        do_git_init_db();
 371
 372        Git::SVN->init($url);
 373}
 374
 375sub cmd_fetch {
 376        if (grep /^\d+=./, @_) {
 377                die "'<rev>=<commit>' fetch arguments are ",
 378                    "no longer supported.\n";
 379        }
 380        my ($remote) = @_;
 381        if (@_ > 1) {
 382                die "Usage: $0 fetch [--all] [svn-remote]\n";
 383        }
 384        $remote ||= $Git::SVN::default_repo_id;
 385        if ($_fetch_all) {
 386                cmd_multi_fetch();
 387        } else {
 388                Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
 389        }
 390}
 391
 392sub cmd_set_tree {
 393        my (@commits) = @_;
 394        if ($_stdin || !@commits) {
 395                print "Reading from stdin...\n";
 396                @commits = ();
 397                while (<STDIN>) {
 398                        if (/\b($sha1_short)\b/o) {
 399                                unshift @commits, $1;
 400                        }
 401                }
 402        }
 403        my @revs;
 404        foreach my $c (@commits) {
 405                my @tmp = command('rev-parse',$c);
 406                if (scalar @tmp == 1) {
 407                        push @revs, $tmp[0];
 408                } elsif (scalar @tmp > 1) {
 409                        push @revs, reverse(command('rev-list',@tmp));
 410                } else {
 411                        fatal "Failed to rev-parse $c";
 412                }
 413        }
 414        my $gs = Git::SVN->new;
 415        my ($r_last, $cmt_last) = $gs->last_rev_commit;
 416        $gs->fetch;
 417        if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
 418                fatal "There are new revisions that were fetched ",
 419                      "and need to be merged (or acknowledged) ",
 420                      "before committing.\nlast rev: $r_last\n",
 421                      " current: $gs->{last_rev}";
 422        }
 423        $gs->set_tree($_) foreach @revs;
 424        print "Done committing ",scalar @revs," revisions to SVN\n";
 425        unlink $gs->{index};
 426}
 427
 428sub cmd_dcommit {
 429        my $head = shift;
 430        git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
 431                'Cannot dcommit with a dirty index.  Commit your changes first, '
 432                . "or stash them with `git stash'.\n";
 433        $head ||= 'HEAD';
 434        my @refs;
 435        my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
 436        unless ($gs) {
 437                die "Unable to determine upstream SVN information from ",
 438                    "$head history.\nPerhaps the repository is empty.";
 439        }
 440        $url = defined $_commit_url ? $_commit_url : $gs->full_url;
 441        my $last_rev = $_revision if defined $_revision;
 442        if ($url) {
 443                print "Committing to $url ...\n";
 444        }
 445        my ($linear_refs, $parents) = linearize_history($gs, \@refs);
 446        if ($_no_rebase && scalar(@$linear_refs) > 1) {
 447                warn "Attempting to commit more than one change while ",
 448                     "--no-rebase is enabled.\n",
 449                     "If these changes depend on each other, re-running ",
 450                     "without --no-rebase may be required."
 451        }
 452        my $expect_url = $url;
 453        Git::SVN::remove_username($expect_url);
 454        while (1) {
 455                my $d = shift @$linear_refs or last;
 456                unless (defined $last_rev) {
 457                        (undef, $last_rev, undef) = cmt_metadata("$d~1");
 458                        unless (defined $last_rev) {
 459                                fatal "Unable to extract revision information ",
 460                                      "from commit $d~1";
 461                        }
 462                }
 463                if ($_dry_run) {
 464                        print "diff-tree $d~1 $d\n";
 465                } else {
 466                        my $cmt_rev;
 467                        my %ed_opts = ( r => $last_rev,
 468                                        log => get_commit_entry($d)->{log},
 469                                        ra => Git::SVN::Ra->new($url),
 470                                        config => SVN::Core::config_get_config(
 471                                                $Git::SVN::Ra::config_dir
 472                                        ),
 473                                        tree_a => "$d~1",
 474                                        tree_b => $d,
 475                                        editor_cb => sub {
 476                                               print "Committed r$_[0]\n";
 477                                               $cmt_rev = $_[0];
 478                                        },
 479                                        svn_path => '');
 480                        if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
 481                                print "No changes\n$d~1 == $d\n";
 482                        } elsif ($parents->{$d} && @{$parents->{$d}}) {
 483                                $gs->{inject_parents_dcommit}->{$cmt_rev} =
 484                                                               $parents->{$d};
 485                        }
 486                        $_fetch_all ? $gs->fetch_all : $gs->fetch;
 487                        $last_rev = $cmt_rev;
 488                        next if $_no_rebase;
 489
 490                        # we always want to rebase against the current HEAD,
 491                        # not any head that was passed to us
 492                        my @diff = command('diff-tree', $d,
 493                                           $gs->refname, '--');
 494                        my @finish;
 495                        if (@diff) {
 496                                @finish = rebase_cmd();
 497                                print STDERR "W: $d and ", $gs->refname,
 498                                             " differ, using @finish:\n",
 499                                             join("\n", @diff), "\n";
 500                        } else {
 501                                print "No changes between current HEAD and ",
 502                                      $gs->refname,
 503                                      "\nResetting to the latest ",
 504                                      $gs->refname, "\n";
 505                                @finish = qw/reset --mixed/;
 506                        }
 507                        command_noisy(@finish, $gs->refname);
 508                        if (@diff) {
 509                                @refs = ();
 510                                my ($url_, $rev_, $uuid_, $gs_) =
 511                                              working_head_info($head, \@refs);
 512                                my ($linear_refs_, $parents_) =
 513                                              linearize_history($gs_, \@refs);
 514                                if (scalar(@$linear_refs) !=
 515                                    scalar(@$linear_refs_)) {
 516                                        fatal "# of revisions changed ",
 517                                          "\nbefore:\n",
 518                                          join("\n", @$linear_refs),
 519                                          "\n\nafter:\n",
 520                                          join("\n", @$linear_refs_), "\n",
 521                                          'If you are attempting to commit ',
 522                                          "merges, try running:\n\t",
 523                                          'git rebase --interactive',
 524                                          '--preserve-merges ',
 525                                          $gs->refname,
 526                                          "\nBefore dcommitting";
 527                                }
 528                                if ($url_ ne $expect_url) {
 529                                        fatal "URL mismatch after rebase: ",
 530                                              "$url_ != $expect_url";
 531                                }
 532                                if ($uuid_ ne $uuid) {
 533                                        fatal "uuid mismatch after rebase: ",
 534                                              "$uuid_ != $uuid";
 535                                }
 536                                # remap parents
 537                                my (%p, @l, $i);
 538                                for ($i = 0; $i < scalar @$linear_refs; $i++) {
 539                                        my $new = $linear_refs_->[$i] or next;
 540                                        $p{$new} =
 541                                                $parents->{$linear_refs->[$i]};
 542                                        push @l, $new;
 543                                }
 544                                $parents = \%p;
 545                                $linear_refs = \@l;
 546                        }
 547                }
 548        }
 549        unlink $gs->{index};
 550}
 551
 552sub cmd_branch {
 553        my ($branch_name, $head) = @_;
 554
 555        unless (defined $branch_name && length $branch_name) {
 556                die(($_tag ? "tag" : "branch") . " name required\n");
 557        }
 558        $head ||= 'HEAD';
 559
 560        my ($src, $rev, undef, $gs) = working_head_info($head);
 561
 562        my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
 563        my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
 564        my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
 565        my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
 566
 567        my $ctx = SVN::Client->new(
 568                auth    => Git::SVN::Ra::_auth_providers(),
 569                log_msg => sub {
 570                        ${ $_[0] } = defined $_message
 571                                ? $_message
 572                                : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
 573                                . $branch_name;
 574                },
 575        );
 576
 577        eval {
 578                $ctx->ls($dst, 'HEAD', 0);
 579        } and die "branch ${branch_name} already exists\n";
 580
 581        print "Copying ${src} at r${rev} to ${dst}...\n";
 582        $ctx->copy($src, $rev, $dst)
 583                unless $_dry_run;
 584
 585        $gs->fetch_all;
 586}
 587
 588sub cmd_find_rev {
 589        my $revision_or_hash = shift or die "SVN or git revision required ",
 590                                            "as a command-line argument\n";
 591        my $result;
 592        if ($revision_or_hash =~ /^r\d+$/) {
 593                my $head = shift;
 594                $head ||= 'HEAD';
 595                my @refs;
 596                my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
 597                unless ($gs) {
 598                        die "Unable to determine upstream SVN information from ",
 599                            "$head history\n";
 600                }
 601                my $desired_revision = substr($revision_or_hash, 1);
 602                $result = $gs->rev_map_get($desired_revision, $uuid);
 603        } else {
 604                my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
 605                $result = $rev;
 606        }
 607        print "$result\n" if $result;
 608}
 609
 610sub cmd_rebase {
 611        command_noisy(qw/update-index --refresh/);
 612        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 613        unless ($gs) {
 614                die "Unable to determine upstream SVN information from ",
 615                    "working tree history\n";
 616        }
 617        if ($_dry_run) {
 618                print "Remote Branch: " . $gs->refname . "\n";
 619                print "SVN URL: " . $url . "\n";
 620                return;
 621        }
 622        if (command(qw/diff-index HEAD --/)) {
 623                print STDERR "Cannot rebase with uncommited changes:\n";
 624                command_noisy('status');
 625                exit 1;
 626        }
 627        unless ($_local) {
 628                # rebase will checkout for us, so no need to do it explicitly
 629                $_no_checkout = 'true';
 630                $_fetch_all ? $gs->fetch_all : $gs->fetch;
 631        }
 632        command_noisy(rebase_cmd(), $gs->refname);
 633}
 634
 635sub cmd_show_ignore {
 636        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 637        $gs ||= Git::SVN->new;
 638        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
 639        $gs->prop_walk($gs->{path}, $r, sub {
 640                my ($gs, $path, $props) = @_;
 641                print STDOUT "\n# $path\n";
 642                my $s = $props->{'svn:ignore'} or return;
 643                $s =~ s/[\r\n]+/\n/g;
 644                chomp $s;
 645                $s =~ s#^#$path#gm;
 646                print STDOUT "$s\n";
 647        });
 648}
 649
 650sub cmd_show_externals {
 651        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 652        $gs ||= Git::SVN->new;
 653        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
 654        $gs->prop_walk($gs->{path}, $r, sub {
 655                my ($gs, $path, $props) = @_;
 656                print STDOUT "\n# $path\n";
 657                my $s = $props->{'svn:externals'} or return;
 658                $s =~ s/[\r\n]+/\n/g;
 659                chomp $s;
 660                $s =~ s#^#$path#gm;
 661                print STDOUT "$s\n";
 662        });
 663}
 664
 665sub cmd_create_ignore {
 666        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 667        $gs ||= Git::SVN->new;
 668        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
 669        $gs->prop_walk($gs->{path}, $r, sub {
 670                my ($gs, $path, $props) = @_;
 671                # $path is of the form /path/to/dir/
 672                my $ignore = '.' . $path . '.gitignore';
 673                my $s = $props->{'svn:ignore'} or return;
 674                open(GITIGNORE, '>', $ignore)
 675                  or fatal("Failed to open `$ignore' for writing: $!");
 676                $s =~ s/[\r\n]+/\n/g;
 677                chomp $s;
 678                # Prefix all patterns so that the ignore doesn't apply
 679                # to sub-directories.
 680                $s =~ s#^#/#gm;
 681                print GITIGNORE "$s\n";
 682                close(GITIGNORE)
 683                  or fatal("Failed to close `$ignore': $!");
 684                command_noisy('add', '-f', $ignore);
 685        });
 686}
 687
 688sub canonicalize_path {
 689        my ($path) = @_;
 690        my $dot_slash_added = 0;
 691        if (substr($path, 0, 1) ne "/") {
 692                $path = "./" . $path;
 693                $dot_slash_added = 1;
 694        }
 695        # File::Spec->canonpath doesn't collapse x/../y into y (for a
 696        # good reason), so let's do this manually.
 697        $path =~ s#/+#/#g;
 698        $path =~ s#/\.(?:/|$)#/#g;
 699        $path =~ s#/[^/]+/\.\.##g;
 700        $path =~ s#/$##g;
 701        $path =~ s#^\./## if $dot_slash_added;
 702        $path =~ s#^/##;
 703        $path =~ s#^\.$##;
 704        return $path;
 705}
 706
 707# get_svnprops(PATH)
 708# ------------------
 709# Helper for cmd_propget and cmd_proplist below.
 710sub get_svnprops {
 711        my $path = shift;
 712        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 713        $gs ||= Git::SVN->new;
 714
 715        # prefix THE PATH by the sub-directory from which the user
 716        # invoked us.
 717        $path = $cmd_dir_prefix . $path;
 718        fatal("No such file or directory: $path") unless -e $path;
 719        my $is_dir = -d $path ? 1 : 0;
 720        $path = $gs->{path} . '/' . $path;
 721
 722        # canonicalize the path (otherwise libsvn will abort or fail to
 723        # find the file)
 724        $path = canonicalize_path($path);
 725
 726        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
 727        my $props;
 728        if ($is_dir) {
 729                (undef, undef, $props) = $gs->ra->get_dir($path, $r);
 730        }
 731        else {
 732                (undef, $props) = $gs->ra->get_file($path, $r, undef);
 733        }
 734        return $props;
 735}
 736
 737# cmd_propget (PROP, PATH)
 738# ------------------------
 739# Print the SVN property PROP for PATH.
 740sub cmd_propget {
 741        my ($prop, $path) = @_;
 742        $path = '.' if not defined $path;
 743        usage(1) if not defined $prop;
 744        my $props = get_svnprops($path);
 745        if (not defined $props->{$prop}) {
 746                fatal("`$path' does not have a `$prop' SVN property.");
 747        }
 748        print $props->{$prop} . "\n";
 749}
 750
 751# cmd_proplist (PATH)
 752# -------------------
 753# Print the list of SVN properties for PATH.
 754sub cmd_proplist {
 755        my $path = shift;
 756        $path = '.' if not defined $path;
 757        my $props = get_svnprops($path);
 758        print "Properties on '$path':\n";
 759        foreach (sort keys %{$props}) {
 760                print "  $_\n";
 761        }
 762}
 763
 764sub cmd_multi_init {
 765        my $url = shift;
 766        unless (defined $_trunk || defined $_branches || defined $_tags) {
 767                usage(1);
 768        }
 769
 770        # there are currently some bugs that prevent multi-init/multi-fetch
 771        # setups from working well without this.
 772        $Git::SVN::_minimize_url = 1;
 773
 774        $_prefix = '' unless defined $_prefix;
 775        if (defined $url) {
 776                $url =~ s#/+$##;
 777                init_subdir(@_);
 778        }
 779        do_git_init_db();
 780        if (defined $_trunk) {
 781                my $trunk_ref = $_prefix . 'trunk';
 782                # try both old-style and new-style lookups:
 783                my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
 784                unless ($gs_trunk) {
 785                        my ($trunk_url, $trunk_path) =
 786                                              complete_svn_url($url, $_trunk);
 787                        $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
 788                                                   undef, $trunk_ref);
 789                }
 790        }
 791        return unless defined $_branches || defined $_tags;
 792        my $ra = $url ? Git::SVN::Ra->new($url) : undef;
 793        complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
 794        complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
 795}
 796
 797sub cmd_multi_fetch {
 798        my $remotes = Git::SVN::read_all_remotes();
 799        foreach my $repo_id (sort keys %$remotes) {
 800                if ($remotes->{$repo_id}->{url}) {
 801                        Git::SVN::fetch_all($repo_id, $remotes);
 802                }
 803        }
 804}
 805
 806# this command is special because it requires no metadata
 807sub cmd_commit_diff {
 808        my ($ta, $tb, $url) = @_;
 809        my $usage = "Usage: $0 commit-diff -r<revision> ".
 810                    "<tree-ish> <tree-ish> [<URL>]";
 811        fatal($usage) if (!defined $ta || !defined $tb);
 812        my $svn_path = '';
 813        if (!defined $url) {
 814                my $gs = eval { Git::SVN->new };
 815                if (!$gs) {
 816                        fatal("Needed URL or usable git-svn --id in ",
 817                              "the command-line\n", $usage);
 818                }
 819                $url = $gs->{url};
 820                $svn_path = $gs->{path};
 821        }
 822        unless (defined $_revision) {
 823                fatal("-r|--revision is a required argument\n", $usage);
 824        }
 825        if (defined $_message && defined $_file) {
 826                fatal("Both --message/-m and --file/-F specified ",
 827                      "for the commit message.\n",
 828                      "I have no idea what you mean");
 829        }
 830        if (defined $_file) {
 831                $_message = file_to_s($_file);
 832        } else {
 833                $_message ||= get_commit_entry($tb)->{log};
 834        }
 835        my $ra ||= Git::SVN::Ra->new($url);
 836        my $r = $_revision;
 837        if ($r eq 'HEAD') {
 838                $r = $ra->get_latest_revnum;
 839        } elsif ($r !~ /^\d+$/) {
 840                die "revision argument: $r not understood by git-svn\n";
 841        }
 842        my %ed_opts = ( r => $r,
 843                        log => $_message,
 844                        ra => $ra,
 845                        tree_a => $ta,
 846                        tree_b => $tb,
 847                        editor_cb => sub { print "Committed r$_[0]\n" },
 848                        svn_path => $svn_path );
 849        if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
 850                print "No changes\n$ta == $tb\n";
 851        }
 852}
 853
 854sub escape_uri_only {
 855        my ($uri) = @_;
 856        my @tmp;
 857        foreach (split m{/}, $uri) {
 858                s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
 859                push @tmp, $_;
 860        }
 861        join('/', @tmp);
 862}
 863
 864sub escape_url {
 865        my ($url) = @_;
 866        if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
 867                my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
 868                $url = "$scheme://$domain$uri";
 869        }
 870        $url;
 871}
 872
 873sub cmd_info {
 874        my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
 875        my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
 876        if (exists $_[1]) {
 877                die "Too many arguments specified\n";
 878        }
 879
 880        my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
 881
 882        if (!$file_type && !$diff_status) {
 883                print STDERR "svn: '$path' is not under version control\n";
 884                exit 1;
 885        }
 886
 887        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 888        unless ($gs) {
 889                die "Unable to determine upstream SVN information from ",
 890                    "working tree history\n";
 891        }
 892
 893        # canonicalize_path() will return "" to make libsvn 1.5.x happy,
 894        $path = "." if $path eq "";
 895
 896        my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
 897
 898        if ($_url) {
 899                print escape_url($full_url), "\n";
 900                return;
 901        }
 902
 903        my $result = "Path: $path\n";
 904        $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
 905        $result .= "URL: " . escape_url($full_url) . "\n";
 906
 907        eval {
 908                my $repos_root = $gs->repos_root;
 909                Git::SVN::remove_username($repos_root);
 910                $result .= "Repository Root: " . escape_url($repos_root) . "\n";
 911        };
 912        if ($@) {
 913                $result .= "Repository Root: (offline)\n";
 914        }
 915        $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
 916        $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
 917
 918        $result .= "Node Kind: " .
 919                   ($file_type eq "dir" ? "directory" : "file") . "\n";
 920
 921        my $schedule = $diff_status eq "A"
 922                       ? "add"
 923                       : ($diff_status eq "D" ? "delete" : "normal");
 924        $result .= "Schedule: $schedule\n";
 925
 926        if ($diff_status eq "A") {
 927                print $result, "\n";
 928                return;
 929        }
 930
 931        my ($lc_author, $lc_rev, $lc_date_utc);
 932        my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
 933        my $log = command_output_pipe(@args);
 934        my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
 935        while (<$log>) {
 936                if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
 937                        $lc_author = $1;
 938                        $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
 939                } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
 940                        (undef, $lc_rev, undef) = ::extract_metadata($1);
 941                }
 942        }
 943        close $log;
 944
 945        Git::SVN::Log::set_local_timezone();
 946
 947        $result .= "Last Changed Author: $lc_author\n";
 948        $result .= "Last Changed Rev: $lc_rev\n";
 949        $result .= "Last Changed Date: " .
 950                   Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
 951
 952        if ($file_type ne "dir") {
 953                my $text_last_updated_date =
 954                    ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
 955                $result .=
 956                    "Text Last Updated: " .
 957                    Git::SVN::Log::format_svn_date($text_last_updated_date) .
 958                    "\n";
 959                my $checksum;
 960                if ($diff_status eq "D") {
 961                        my ($fh, $ctx) =
 962                            command_output_pipe(qw(cat-file blob), "HEAD:$path");
 963                        if ($file_type eq "link") {
 964                                my $file_name = <$fh>;
 965                                $checksum = md5sum("link $file_name");
 966                        } else {
 967                                $checksum = md5sum($fh);
 968                        }
 969                        command_close_pipe($fh, $ctx);
 970                } elsif ($file_type eq "link") {
 971                        my $file_name =
 972                            command(qw(cat-file blob), "HEAD:$path");
 973                        $checksum =
 974                            md5sum("link " . $file_name);
 975                } else {
 976                        open FILE, "<", $path or die $!;
 977                        $checksum = md5sum(\*FILE);
 978                        close FILE or die $!;
 979                }
 980                $result .= "Checksum: " . $checksum . "\n";
 981        }
 982
 983        print $result, "\n";
 984}
 985
 986########################### utility functions #########################
 987
 988sub rebase_cmd {
 989        my @cmd = qw/rebase/;
 990        push @cmd, '-v' if $_verbose;
 991        push @cmd, qw/--merge/ if $_merge;
 992        push @cmd, "--strategy=$_strategy" if $_strategy;
 993        @cmd;
 994}
 995
 996sub post_fetch_checkout {
 997        return if $_no_checkout;
 998        my $gs = $Git::SVN::_head or return;
 999        return if verify_ref('refs/heads/master^0');
1000
1001        my $valid_head = verify_ref('HEAD^0');
1002        command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1003        return if ($valid_head || !verify_ref('HEAD^0'));
1004
1005        return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1006        my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1007        return if -f $index;
1008
1009        return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1010        return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1011        command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1012        print STDERR "Checked out HEAD:\n  ",
1013                     $gs->full_url, " r", $gs->last_rev, "\n";
1014}
1015
1016sub complete_svn_url {
1017        my ($url, $path) = @_;
1018        $path =~ s#/+$##;
1019        if ($path !~ m#^[a-z\+]+://#) {
1020                if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1021                        fatal("E: '$path' is not a complete URL ",
1022                              "and a separate URL is not specified");
1023                }
1024                return ($url, $path);
1025        }
1026        return ($path, '');
1027}
1028
1029sub complete_url_ls_init {
1030        my ($ra, $repo_path, $switch, $pfx) = @_;
1031        unless ($repo_path) {
1032                print STDERR "W: $switch not specified\n";
1033                return;
1034        }
1035        $repo_path =~ s#/+$##;
1036        if ($repo_path =~ m#^[a-z\+]+://#) {
1037                $ra = Git::SVN::Ra->new($repo_path);
1038                $repo_path = '';
1039        } else {
1040                $repo_path =~ s#^/+##;
1041                unless ($ra) {
1042                        fatal("E: '$repo_path' is not a complete URL ",
1043                              "and a separate URL is not specified");
1044                }
1045        }
1046        my $url = $ra->{url};
1047        my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1048        my $k = "svn-remote.$gs->{repo_id}.url";
1049        my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1050        if ($orig_url && ($orig_url ne $gs->{url})) {
1051                die "$k already set: $orig_url\n",
1052                    "wanted to set to: $gs->{url}\n";
1053        }
1054        command_oneline('config', $k, $gs->{url}) unless $orig_url;
1055        my $remote_path = "$ra->{svn_path}/$repo_path";
1056        $remote_path =~ s#/+#/#g;
1057        $remote_path =~ s#^/##g;
1058        $remote_path .= "/*" if $remote_path !~ /\*/;
1059        my ($n) = ($switch =~ /^--(\w+)/);
1060        if (length $pfx && $pfx !~ m#/$#) {
1061                die "--prefix='$pfx' must have a trailing slash '/'\n";
1062        }
1063        command_noisy('config',
1064                      "svn-remote.$gs->{repo_id}.$n",
1065                      "$remote_path:refs/remotes/$pfx*" .
1066                        ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1067}
1068
1069sub verify_ref {
1070        my ($ref) = @_;
1071        eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1072                               { STDERR => 0 }); };
1073}
1074
1075sub get_tree_from_treeish {
1076        my ($treeish) = @_;
1077        # $treeish can be a symbolic ref, too:
1078        my $type = command_oneline(qw/cat-file -t/, $treeish);
1079        my $expected;
1080        while ($type eq 'tag') {
1081                ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1082        }
1083        if ($type eq 'commit') {
1084                $expected = (grep /^tree /, command(qw/cat-file commit/,
1085                                                    $treeish))[0];
1086                ($expected) = ($expected =~ /^tree ($sha1)$/o);
1087                die "Unable to get tree from $treeish\n" unless $expected;
1088        } elsif ($type eq 'tree') {
1089                $expected = $treeish;
1090        } else {
1091                die "$treeish is a $type, expected tree, tag or commit\n";
1092        }
1093        return $expected;
1094}
1095
1096sub get_commit_entry {
1097        my ($treeish) = shift;
1098        my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1099        my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1100        my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1101        open my $log_fh, '>', $commit_editmsg or croak $!;
1102
1103        my $type = command_oneline(qw/cat-file -t/, $treeish);
1104        if ($type eq 'commit' || $type eq 'tag') {
1105                my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1106                                                         $type, $treeish);
1107                my $in_msg = 0;
1108                my $author;
1109                my $saw_from = 0;
1110                my $msgbuf = "";
1111                while (<$msg_fh>) {
1112                        if (!$in_msg) {
1113                                $in_msg = 1 if (/^\s*$/);
1114                                $author = $1 if (/^author (.*>)/);
1115                        } elsif (/^git-svn-id: /) {
1116                                # skip this for now, we regenerate the
1117                                # correct one on re-fetch anyways
1118                                # TODO: set *:merge properties or like...
1119                        } else {
1120                                if (/^From:/ || /^Signed-off-by:/) {
1121                                        $saw_from = 1;
1122                                }
1123                                $msgbuf .= $_;
1124                        }
1125                }
1126                $msgbuf =~ s/\s+$//s;
1127                if ($Git::SVN::_add_author_from && defined($author)
1128                    && !$saw_from) {
1129                        $msgbuf .= "\n\nFrom: $author";
1130                }
1131                print $log_fh $msgbuf or croak $!;
1132                command_close_pipe($msg_fh, $ctx);
1133        }
1134        close $log_fh or croak $!;
1135
1136        if ($_edit || ($type eq 'tree')) {
1137                my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1138                # TODO: strip out spaces, comments, like git-commit.sh
1139                system($editor, $commit_editmsg);
1140        }
1141        rename $commit_editmsg, $commit_msg or croak $!;
1142        {
1143                # SVN requires messages to be UTF-8 when entering the repo
1144                local $/;
1145                open $log_fh, '<', $commit_msg or croak $!;
1146                binmode $log_fh;
1147                chomp($log_entry{log} = <$log_fh>);
1148
1149                if (my $enc = Git::config('i18n.commitencoding')) {
1150                        require Encode;
1151                        Encode::from_to($log_entry{log}, $enc, 'UTF-8');
1152                }
1153                close $log_fh or croak $!;
1154        }
1155        unlink $commit_msg;
1156        \%log_entry;
1157}
1158
1159sub s_to_file {
1160        my ($str, $file, $mode) = @_;
1161        open my $fd,'>',$file or croak $!;
1162        print $fd $str,"\n" or croak $!;
1163        close $fd or croak $!;
1164        chmod ($mode &~ umask, $file) if (defined $mode);
1165}
1166
1167sub file_to_s {
1168        my $file = shift;
1169        open my $fd,'<',$file or croak "$!: file: $file\n";
1170        local $/;
1171        my $ret = <$fd>;
1172        close $fd or croak $!;
1173        $ret =~ s/\s*$//s;
1174        return $ret;
1175}
1176
1177# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1178sub load_authors {
1179        open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1180        my $log = $cmd eq 'log';
1181        while (<$authors>) {
1182                chomp;
1183                next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1184                my ($user, $name, $email) = ($1, $2, $3);
1185                if ($log) {
1186                        $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1187                } else {
1188                        $users{$user} = [$name, $email];
1189                }
1190        }
1191        close $authors or croak $!;
1192}
1193
1194# convert GetOpt::Long specs for use by git-config
1195sub read_repo_config {
1196        return unless -d $ENV{GIT_DIR};
1197        my $opts = shift;
1198        my @config_only;
1199        foreach my $o (keys %$opts) {
1200                # if we have mixedCase and a long option-only, then
1201                # it's a config-only variable that we don't need for
1202                # the command-line.
1203                push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1204                my $v = $opts->{$o};
1205                my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1206                $key =~ s/-//g;
1207                my $arg = 'git config';
1208                $arg .= ' --int' if ($o =~ /[:=]i$/);
1209                $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1210                if (ref $v eq 'ARRAY') {
1211                        chomp(my @tmp = `$arg --get-all svn.$key`);
1212                        @$v = @tmp if @tmp;
1213                } else {
1214                        chomp(my $tmp = `$arg --get svn.$key`);
1215                        if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1216                                $$v = $tmp;
1217                        }
1218                }
1219        }
1220        delete @$opts{@config_only} if @config_only;
1221}
1222
1223sub extract_metadata {
1224        my $id = shift or return (undef, undef, undef);
1225        my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1226                                                        \s([a-f\d\-]+)$/x);
1227        if (!defined $rev || !$uuid || !$url) {
1228                # some of the original repositories I made had
1229                # identifiers like this:
1230                ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1231        }
1232        return ($url, $rev, $uuid);
1233}
1234
1235sub cmt_metadata {
1236        return extract_metadata((grep(/^git-svn-id: /,
1237                command(qw/cat-file commit/, shift)))[-1]);
1238}
1239
1240sub working_head_info {
1241        my ($head, $refs) = @_;
1242        my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1243        my ($fh, $ctx) = command_output_pipe(@args, $head);
1244        my $hash;
1245        my %max;
1246        while (<$fh>) {
1247                if ( m{^commit ($::sha1)$} ) {
1248                        unshift @$refs, $hash if $hash and $refs;
1249                        $hash = $1;
1250                        next;
1251                }
1252                next unless s{^\s*(git-svn-id:)}{$1};
1253                my ($url, $rev, $uuid) = extract_metadata($_);
1254                if (defined $url && defined $rev) {
1255                        next if $max{$url} and $max{$url} < $rev;
1256                        if (my $gs = Git::SVN->find_by_url($url)) {
1257                                my $c = $gs->rev_map_get($rev, $uuid);
1258                                if ($c && $c eq $hash) {
1259                                        close $fh; # break the pipe
1260                                        return ($url, $rev, $uuid, $gs);
1261                                } else {
1262                                        $max{$url} ||= $gs->rev_map_max;
1263                                }
1264                        }
1265                }
1266        }
1267        command_close_pipe($fh, $ctx);
1268        (undef, undef, undef, undef);
1269}
1270
1271sub read_commit_parents {
1272        my ($parents, $c) = @_;
1273        chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1274        $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1275        @{$parents->{$c}} = split(/ /, $p);
1276}
1277
1278sub linearize_history {
1279        my ($gs, $refs) = @_;
1280        my %parents;
1281        foreach my $c (@$refs) {
1282                read_commit_parents(\%parents, $c);
1283        }
1284
1285        my @linear_refs;
1286        my %skip = ();
1287        my $last_svn_commit = $gs->last_commit;
1288        foreach my $c (reverse @$refs) {
1289                next if $c eq $last_svn_commit;
1290                last if $skip{$c};
1291
1292                unshift @linear_refs, $c;
1293                $skip{$c} = 1;
1294
1295                # we only want the first parent to diff against for linear
1296                # history, we save the rest to inject when we finalize the
1297                # svn commit
1298                my $fp_a = verify_ref("$c~1");
1299                my $fp_b = shift @{$parents{$c}} if $parents{$c};
1300                if (!$fp_a || !$fp_b) {
1301                        die "Commit $c\n",
1302                            "has no parent commit, and therefore ",
1303                            "nothing to diff against.\n",
1304                            "You should be working from a repository ",
1305                            "originally created by git-svn\n";
1306                }
1307                if ($fp_a ne $fp_b) {
1308                        die "$c~1 = $fp_a, however parsing commit $c ",
1309                            "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1310                }
1311
1312                foreach my $p (@{$parents{$c}}) {
1313                        $skip{$p} = 1;
1314                }
1315        }
1316        (\@linear_refs, \%parents);
1317}
1318
1319sub find_file_type_and_diff_status {
1320        my ($path) = @_;
1321        return ('dir', '') if $path eq '';
1322
1323        my $diff_output =
1324            command_oneline(qw(diff --cached --name-status --), $path) || "";
1325        my $diff_status = (split(' ', $diff_output))[0] || "";
1326
1327        my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1328
1329        return (undef, undef) if !$diff_status && !$ls_tree;
1330
1331        if ($diff_status eq "A") {
1332                return ("link", $diff_status) if -l $path;
1333                return ("dir", $diff_status) if -d $path;
1334                return ("file", $diff_status);
1335        }
1336
1337        my $mode = (split(' ', $ls_tree))[0] || "";
1338
1339        return ("link", $diff_status) if $mode eq "120000";
1340        return ("dir", $diff_status) if $mode eq "040000";
1341        return ("file", $diff_status);
1342}
1343
1344sub md5sum {
1345        my $arg = shift;
1346        my $ref = ref $arg;
1347        my $md5 = Digest::MD5->new();
1348        if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1349                $md5->addfile($arg) or croak $!;
1350        } elsif ($ref eq 'SCALAR') {
1351                $md5->add($$arg) or croak $!;
1352        } elsif (!$ref) {
1353                $md5->add($arg) or croak $!;
1354        } else {
1355                ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1356        }
1357        return $md5->hexdigest();
1358}
1359
1360package Git::SVN;
1361use strict;
1362use warnings;
1363use Fcntl qw/:DEFAULT :seek/;
1364use constant rev_map_fmt => 'NH40';
1365use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1366            $_repack $_repack_flags $_use_svm_props $_head
1367            $_use_svnsync_props $no_reuse_existing $_minimize_url
1368            $_use_log_author $_add_author_from $_localtime/;
1369use Carp qw/croak/;
1370use File::Path qw/mkpath/;
1371use File::Copy qw/copy/;
1372use IPC::Open3;
1373
1374my ($_gc_nr, $_gc_period);
1375
1376# properties that we do not log:
1377my %SKIP_PROP;
1378BEGIN {
1379        %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1380                                        svn:special svn:executable
1381                                        svn:entry:committed-rev
1382                                        svn:entry:last-author
1383                                        svn:entry:uuid
1384                                        svn:entry:committed-date/;
1385
1386        # some options are read globally, but can be overridden locally
1387        # per [svn-remote "..."] section.  Command-line options will *NOT*
1388        # override options set in an [svn-remote "..."] section
1389        no strict 'refs';
1390        for my $option (qw/follow_parent no_metadata use_svm_props
1391                           use_svnsync_props/) {
1392                my $key = $option;
1393                $key =~ tr/_//d;
1394                my $prop = "-$option";
1395                *$option = sub {
1396                        my ($self) = @_;
1397                        return $self->{$prop} if exists $self->{$prop};
1398                        my $k = "svn-remote.$self->{repo_id}.$key";
1399                        eval { command_oneline(qw/config --get/, $k) };
1400                        if ($@) {
1401                                $self->{$prop} = ${"Git::SVN::_$option"};
1402                        } else {
1403                                my $v = command_oneline(qw/config --bool/,$k);
1404                                $self->{$prop} = $v eq 'false' ? 0 : 1;
1405                        }
1406                        return $self->{$prop};
1407                }
1408        }
1409}
1410
1411
1412my (%LOCKFILES, %INDEX_FILES);
1413END {
1414        unlink keys %LOCKFILES if %LOCKFILES;
1415        unlink keys %INDEX_FILES if %INDEX_FILES;
1416}
1417
1418sub resolve_local_globs {
1419        my ($url, $fetch, $glob_spec) = @_;
1420        return unless defined $glob_spec;
1421        my $ref = $glob_spec->{ref};
1422        my $path = $glob_spec->{path};
1423        foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1424                next unless m#^refs/remotes/$ref->{regex}$#;
1425                my $p = $1;
1426                my $pathname = desanitize_refname($path->full_path($p));
1427                my $refname = desanitize_refname($ref->full_path($p));
1428                if (my $existing = $fetch->{$pathname}) {
1429                        if ($existing ne $refname) {
1430                                die "Refspec conflict:\n",
1431                                    "existing: refs/remotes/$existing\n",
1432                                    " globbed: refs/remotes/$refname\n";
1433                        }
1434                        my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1435                        $u =~ s!^\Q$url\E(/|$)!! or die
1436                          "refs/remotes/$refname: '$url' not found in '$u'\n";
1437                        if ($pathname ne $u) {
1438                                warn "W: Refspec glob conflict ",
1439                                     "(ref: refs/remotes/$refname):\n",
1440                                     "expected path: $pathname\n",
1441                                     "    real path: $u\n",
1442                                     "Continuing ahead with $u\n";
1443                                next;
1444                        }
1445                } else {
1446                        $fetch->{$pathname} = $refname;
1447                }
1448        }
1449}
1450
1451sub parse_revision_argument {
1452        my ($base, $head) = @_;
1453        if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1454                return ($base, $head);
1455        }
1456        return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1457        return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1458        return ($head, $head) if ($::_revision eq 'HEAD');
1459        return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1460        return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1461        die "revision argument: $::_revision not understood by git-svn\n";
1462}
1463
1464sub fetch_all {
1465        my ($repo_id, $remotes) = @_;
1466        if (ref $repo_id) {
1467                my $gs = $repo_id;
1468                $repo_id = undef;
1469                $repo_id = $gs->{repo_id};
1470        }
1471        $remotes ||= read_all_remotes();
1472        my $remote = $remotes->{$repo_id} or
1473                     die "[svn-remote \"$repo_id\"] unknown\n";
1474        my $fetch = $remote->{fetch};
1475        my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1476        my (@gs, @globs);
1477        my $ra = Git::SVN::Ra->new($url);
1478        my $uuid = $ra->get_uuid;
1479        my $head = $ra->get_latest_revnum;
1480        my $base = defined $fetch ? $head : 0;
1481
1482        # read the max revs for wildcard expansion (branches/*, tags/*)
1483        foreach my $t (qw/branches tags/) {
1484                defined $remote->{$t} or next;
1485                push @globs, $remote->{$t};
1486                my $max_rev = eval { tmp_config(qw/--int --get/,
1487                                         "svn-remote.$repo_id.${t}-maxRev") };
1488                if (defined $max_rev && ($max_rev < $base)) {
1489                        $base = $max_rev;
1490                } elsif (!defined $max_rev) {
1491                        $base = 0;
1492                }
1493        }
1494
1495        if ($fetch) {
1496                foreach my $p (sort keys %$fetch) {
1497                        my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1498                        my $lr = $gs->rev_map_max;
1499                        if (defined $lr) {
1500                                $base = $lr if ($lr < $base);
1501                        }
1502                        push @gs, $gs;
1503                }
1504        }
1505
1506        ($base, $head) = parse_revision_argument($base, $head);
1507        $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1508}
1509
1510sub read_all_remotes {
1511        my $r = {};
1512        my $use_svm_props = eval { command_oneline(qw/config --bool
1513            svn.useSvmProps/) };
1514        $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1515        foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1516                if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1517                        my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1518                        die("svn-remote.$remote: remote ref '$_remote_ref' "
1519                            . "must start with 'refs/remotes/'\n")
1520                                unless $_remote_ref =~ m{^refs/remotes/(.+)};
1521                        my $remote_ref = $1;
1522                        $local_ref =~ s{^/}{};
1523                        $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1524                        $r->{$remote}->{svm} = {} if $use_svm_props;
1525                } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1526                        $r->{$1}->{svm} = {};
1527                } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1528                        $r->{$1}->{url} = $2;
1529                } elsif (m!^(.+)\.(branches|tags)=
1530                           (.*):refs/remotes/(.+)\s*$/!x) {
1531                        my ($p, $g) = ($3, $4);
1532                        my $rs = $r->{$1}->{$2} = {
1533                                          t => $2,
1534                                          remote => $1,
1535                                          path => Git::SVN::GlobSpec->new($p),
1536                                          ref => Git::SVN::GlobSpec->new($g) };
1537                        if (length($rs->{ref}->{right}) != 0) {
1538                                die "The '*' glob character must be the last ",
1539                                    "character of '$g'\n";
1540                        }
1541                }
1542        }
1543
1544        map {
1545                if (defined $r->{$_}->{svm}) {
1546                        my $svm;
1547                        eval {
1548                                my $section = "svn-remote.$_";
1549                                $svm = {
1550                                        source => tmp_config('--get',
1551                                            "$section.svm-source"),
1552                                        replace => tmp_config('--get',
1553                                            "$section.svm-replace"),
1554                                }
1555                        };
1556                        $r->{$_}->{svm} = $svm;
1557                }
1558        } keys %$r;
1559
1560        $r;
1561}
1562
1563sub init_vars {
1564        $_gc_nr = $_gc_period = 1000;
1565        if (defined $_repack || defined $_repack_flags) {
1566               warn "Repack options are obsolete; they have no effect.\n";
1567        }
1568}
1569
1570sub verify_remotes_sanity {
1571        return unless -d $ENV{GIT_DIR};
1572        my %seen;
1573        foreach (command(qw/config -l/)) {
1574                if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1575                        if ($seen{$1}) {
1576                                die "Remote ref refs/remote/$1 is tracked by",
1577                                    "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
1578                                    "Please resolve this ambiguity in ",
1579                                    "your git configuration file before ",
1580                                    "continuing\n";
1581                        }
1582                        $seen{$1} = $_;
1583                }
1584        }
1585}
1586
1587sub find_existing_remote {
1588        my ($url, $remotes) = @_;
1589        return undef if $no_reuse_existing;
1590        my $existing;
1591        foreach my $repo_id (keys %$remotes) {
1592                my $u = $remotes->{$repo_id}->{url} or next;
1593                next if $u ne $url;
1594                $existing = $repo_id;
1595                last;
1596        }
1597        $existing;
1598}
1599
1600sub init_remote_config {
1601        my ($self, $url, $no_write) = @_;
1602        $url =~ s!/+$!!; # strip trailing slash
1603        my $r = read_all_remotes();
1604        my $existing = find_existing_remote($url, $r);
1605        if ($existing) {
1606                unless ($no_write) {
1607                        print STDERR "Using existing ",
1608                                     "[svn-remote \"$existing\"]\n";
1609                }
1610                $self->{repo_id} = $existing;
1611        } elsif ($_minimize_url) {
1612                my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1613                $existing = find_existing_remote($min_url, $r);
1614                if ($existing) {
1615                        unless ($no_write) {
1616                                print STDERR "Using existing ",
1617                                             "[svn-remote \"$existing\"]\n";
1618                        }
1619                        $self->{repo_id} = $existing;
1620                }
1621                if ($min_url ne $url) {
1622                        unless ($no_write) {
1623                                print STDERR "Using higher level of URL: ",
1624                                             "$url => $min_url\n";
1625                        }
1626                        my $old_path = $self->{path};
1627                        $self->{path} = $url;
1628                        $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1629                        if (length $old_path) {
1630                                $self->{path} .= "/$old_path";
1631                        }
1632                        $url = $min_url;
1633                }
1634        }
1635        my $orig_url;
1636        if (!$existing) {
1637                # verify that we aren't overwriting anything:
1638                $orig_url = eval {
1639                        command_oneline('config', '--get',
1640                                        "svn-remote.$self->{repo_id}.url")
1641                };
1642                if ($orig_url && ($orig_url ne $url)) {
1643                        die "svn-remote.$self->{repo_id}.url already set: ",
1644                            "$orig_url\nwanted to set to: $url\n";
1645                }
1646        }
1647        my ($xrepo_id, $xpath) = find_ref($self->refname);
1648        if (defined $xpath) {
1649                die "svn-remote.$xrepo_id.fetch already set to track ",
1650                    "$xpath:refs/remotes/", $self->refname, "\n";
1651        }
1652        unless ($no_write) {
1653                command_noisy('config',
1654                              "svn-remote.$self->{repo_id}.url", $url);
1655                $self->{path} =~ s{^/}{};
1656                command_noisy('config', '--add',
1657                              "svn-remote.$self->{repo_id}.fetch",
1658                              "$self->{path}:".$self->refname);
1659        }
1660        $self->{url} = $url;
1661}
1662
1663sub find_by_url { # repos_root and, path are optional
1664        my ($class, $full_url, $repos_root, $path) = @_;
1665
1666        return undef unless defined $full_url;
1667        remove_username($full_url);
1668        remove_username($repos_root) if defined $repos_root;
1669        my $remotes = read_all_remotes();
1670        if (defined $full_url && defined $repos_root && !defined $path) {
1671                $path = $full_url;
1672                $path =~ s#^\Q$repos_root\E(?:/|$)##;
1673        }
1674        foreach my $repo_id (keys %$remotes) {
1675                my $u = $remotes->{$repo_id}->{url} or next;
1676                remove_username($u);
1677                next if defined $repos_root && $repos_root ne $u;
1678
1679                my $fetch = $remotes->{$repo_id}->{fetch} || {};
1680                foreach (qw/branches tags/) {
1681                        resolve_local_globs($u, $fetch,
1682                                            $remotes->{$repo_id}->{$_});
1683                }
1684                my $p = $path;
1685                my $rwr = rewrite_root({repo_id => $repo_id});
1686                my $svm = $remotes->{$repo_id}->{svm}
1687                        if defined $remotes->{$repo_id}->{svm};
1688                unless (defined $p) {
1689                        $p = $full_url;
1690                        my $z = $u;
1691                        my $prefix = '';
1692                        if ($rwr) {
1693                                $z = $rwr;
1694                        } elsif (defined $svm) {
1695                                $z = $svm->{source};
1696                                $prefix = $svm->{replace};
1697                                $prefix =~ s#^\Q$u\E(?:/|$)##;
1698                                $prefix =~ s#/$##;
1699                        }
1700                        $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1701                }
1702                foreach my $f (keys %$fetch) {
1703                        next if $f ne $p;
1704                        return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1705                }
1706        }
1707        undef;
1708}
1709
1710sub init {
1711        my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1712        my $self = _new($class, $repo_id, $ref_id, $path);
1713        if (defined $url) {
1714                $self->init_remote_config($url, $no_write);
1715        }
1716        $self;
1717}
1718
1719sub find_ref {
1720        my ($ref_id) = @_;
1721        foreach (command(qw/config -l/)) {
1722                next unless m!^svn-remote\.(.+)\.fetch=
1723                              \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1724                my ($repo_id, $path, $ref) = ($1, $2, $3);
1725                if ($ref eq $ref_id) {
1726                        $path = '' if ($path =~ m#^\./?#);
1727                        return ($repo_id, $path);
1728                }
1729        }
1730        (undef, undef, undef);
1731}
1732
1733sub new {
1734        my ($class, $ref_id, $repo_id, $path) = @_;
1735        if (defined $ref_id && !defined $repo_id && !defined $path) {
1736                ($repo_id, $path) = find_ref($ref_id);
1737                if (!defined $repo_id) {
1738                        die "Could not find a \"svn-remote.*.fetch\" key ",
1739                            "in the repository configuration matching: ",
1740                            "refs/remotes/$ref_id\n";
1741                }
1742        }
1743        my $self = _new($class, $repo_id, $ref_id, $path);
1744        if (!defined $self->{path} || !length $self->{path}) {
1745                my $fetch = command_oneline('config', '--get',
1746                                            "svn-remote.$repo_id.fetch",
1747                                            ":refs/remotes/$ref_id\$") or
1748                     die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1749                         "\":refs/remotes/$ref_id\$\" in config\n";
1750                ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1751        }
1752        $self->{url} = command_oneline('config', '--get',
1753                                       "svn-remote.$repo_id.url") or
1754                  die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1755        $self->rebuild;
1756        $self;
1757}
1758
1759sub refname {
1760        my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1761
1762        # It cannot end with a slash /, we'll throw up on this because
1763        # SVN can't have directories with a slash in their name, either:
1764        if ($refname =~ m{/$}) {
1765                die "ref: '$refname' ends with a trailing slash, this is ",
1766                    "not permitted by git nor Subversion\n";
1767        }
1768
1769        # It cannot have ASCII control character space, tilde ~, caret ^,
1770        # colon :, question-mark ?, asterisk *, space, or open bracket [
1771        # anywhere.
1772        #
1773        # Additionally, % must be escaped because it is used for escaping
1774        # and we want our escaped refname to be reversible
1775        $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1776
1777        # no slash-separated component can begin with a dot .
1778        # /.* becomes /%2E*
1779        $refname =~ s{/\.}{/%2E}g;
1780
1781        # It cannot have two consecutive dots .. anywhere
1782        # .. becomes %2E%2E
1783        $refname =~ s{\.\.}{%2E%2E}g;
1784
1785        return $refname;
1786}
1787
1788sub desanitize_refname {
1789        my ($refname) = @_;
1790        $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1791        return $refname;
1792}
1793
1794sub svm_uuid {
1795        my ($self) = @_;
1796        return $self->{svm}->{uuid} if $self->svm;
1797        $self->ra;
1798        unless ($self->{svm}) {
1799                die "SVM UUID not cached, and reading remotely failed\n";
1800        }
1801        $self->{svm}->{uuid};
1802}
1803
1804sub svm {
1805        my ($self) = @_;
1806        return $self->{svm} if $self->{svm};
1807        my $svm;
1808        # see if we have it in our config, first:
1809        eval {
1810                my $section = "svn-remote.$self->{repo_id}";
1811                $svm = {
1812                  source => tmp_config('--get', "$section.svm-source"),
1813                  uuid => tmp_config('--get', "$section.svm-uuid"),
1814                  replace => tmp_config('--get', "$section.svm-replace"),
1815                }
1816        };
1817        if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1818                $self->{svm} = $svm;
1819        }
1820        $self->{svm};
1821}
1822
1823sub _set_svm_vars {
1824        my ($self, $ra) = @_;
1825        return $ra if $self->svm;
1826
1827        my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1828                    "(svm:source, svm:uuid) ",
1829                    "from the following URLs:\n" );
1830        sub read_svm_props {
1831                my ($self, $ra, $path, $r) = @_;
1832                my $props = ($ra->get_dir($path, $r))[2];
1833                my $src = $props->{'svm:source'};
1834                my $uuid = $props->{'svm:uuid'};
1835                return undef if (!$src || !$uuid);
1836
1837                chomp($src, $uuid);
1838
1839                $uuid =~ m{^[0-9a-f\-]{30,}$}
1840                    or die "doesn't look right - svm:uuid is '$uuid'\n";
1841
1842                # the '!' is used to mark the repos_root!/relative/path
1843                $src =~ s{/?!/?}{/};
1844                $src =~ s{/+$}{}; # no trailing slashes please
1845                # username is of no interest
1846                $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1847
1848                my $replace = $ra->{url};
1849                $replace .= "/$path" if length $path;
1850
1851                my $section = "svn-remote.$self->{repo_id}";
1852                tmp_config("$section.svm-source", $src);
1853                tmp_config("$section.svm-replace", $replace);
1854                tmp_config("$section.svm-uuid", $uuid);
1855                $self->{svm} = {
1856                        source => $src,
1857                        uuid => $uuid,
1858                        replace => $replace
1859                };
1860        }
1861
1862        my $r = $ra->get_latest_revnum;
1863        my $path = $self->{path};
1864        my %tried;
1865        while (length $path) {
1866                unless ($tried{"$self->{url}/$path"}) {
1867                        return $ra if $self->read_svm_props($ra, $path, $r);
1868                        $tried{"$self->{url}/$path"} = 1;
1869                }
1870                $path =~ s#/?[^/]+$##;
1871        }
1872        die "Path: '$path' should be ''\n" if $path ne '';
1873        return $ra if $self->read_svm_props($ra, $path, $r);
1874        $tried{"$self->{url}/$path"} = 1;
1875
1876        if ($ra->{repos_root} eq $self->{url}) {
1877                die @err, (map { "  $_\n" } keys %tried), "\n";
1878        }
1879
1880        # nope, make sure we're connected to the repository root:
1881        my $ok;
1882        my @tried_b;
1883        $path = $ra->{svn_path};
1884        $ra = Git::SVN::Ra->new($ra->{repos_root});
1885        while (length $path) {
1886                unless ($tried{"$ra->{url}/$path"}) {
1887                        $ok = $self->read_svm_props($ra, $path, $r);
1888                        last if $ok;
1889                        $tried{"$ra->{url}/$path"} = 1;
1890                }
1891                $path =~ s#/?[^/]+$##;
1892        }
1893        die "Path: '$path' should be ''\n" if $path ne '';
1894        $ok ||= $self->read_svm_props($ra, $path, $r);
1895        $tried{"$ra->{url}/$path"} = 1;
1896        if (!$ok) {
1897                die @err, (map { "  $_\n" } keys %tried), "\n";
1898        }
1899        Git::SVN::Ra->new($self->{url});
1900}
1901
1902sub svnsync {
1903        my ($self) = @_;
1904        return $self->{svnsync} if $self->{svnsync};
1905
1906        if ($self->no_metadata) {
1907                die "Can't have both 'noMetadata' and ",
1908                    "'useSvnsyncProps' options set!\n";
1909        }
1910        if ($self->rewrite_root) {
1911                die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1912                    "options set!\n";
1913        }
1914
1915        my $svnsync;
1916        # see if we have it in our config, first:
1917        eval {
1918                my $section = "svn-remote.$self->{repo_id}";
1919
1920                my $url = tmp_config('--get', "$section.svnsync-url");
1921                ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1922                   die "doesn't look right - svn:sync-from-url is '$url'\n";
1923
1924                my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1925                ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1926                   die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1927
1928                $svnsync = { url => $url, uuid => $uuid }
1929        };
1930        if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1931                return $self->{svnsync} = $svnsync;
1932        }
1933
1934        my $err = "useSvnsyncProps set, but failed to read " .
1935                  "svnsync property: svn:sync-from-";
1936        my $rp = $self->ra->rev_proplist(0);
1937
1938        my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1939        ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1940                   die "doesn't look right - svn:sync-from-url is '$url'\n";
1941
1942        my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1943        ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1944                   die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1945
1946        my $section = "svn-remote.$self->{repo_id}";
1947        tmp_config('--add', "$section.svnsync-uuid", $uuid);
1948        tmp_config('--add', "$section.svnsync-url", $url);
1949        return $self->{svnsync} = { url => $url, uuid => $uuid };
1950}
1951
1952# this allows us to memoize our SVN::Ra UUID locally and avoid a
1953# remote lookup (useful for 'git svn log').
1954sub ra_uuid {
1955        my ($self) = @_;
1956        unless ($self->{ra_uuid}) {
1957                my $key = "svn-remote.$self->{repo_id}.uuid";
1958                my $uuid = eval { tmp_config('--get', $key) };
1959                if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1960                        $self->{ra_uuid} = $uuid;
1961                } else {
1962                        die "ra_uuid called without URL\n" unless $self->{url};
1963                        $self->{ra_uuid} = $self->ra->get_uuid;
1964                        tmp_config('--add', $key, $self->{ra_uuid});
1965                }
1966        }
1967        $self->{ra_uuid};
1968}
1969
1970sub _set_repos_root {
1971        my ($self, $repos_root) = @_;
1972        my $k = "svn-remote.$self->{repo_id}.reposRoot";
1973        $repos_root ||= $self->ra->{repos_root};
1974        tmp_config($k, $repos_root);
1975        $repos_root;
1976}
1977
1978sub repos_root {
1979        my ($self) = @_;
1980        my $k = "svn-remote.$self->{repo_id}.reposRoot";
1981        eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1982}
1983
1984sub ra {
1985        my ($self) = shift;
1986        my $ra = Git::SVN::Ra->new($self->{url});
1987        $self->_set_repos_root($ra->{repos_root});
1988        if ($self->use_svm_props && !$self->{svm}) {
1989                if ($self->no_metadata) {
1990                        die "Can't have both 'noMetadata' and ",
1991                            "'useSvmProps' options set!\n";
1992                } elsif ($self->use_svnsync_props) {
1993                        die "Can't have both 'useSvnsyncProps' and ",
1994                            "'useSvmProps' options set!\n";
1995                }
1996                $ra = $self->_set_svm_vars($ra);
1997                $self->{-want_revprops} = 1;
1998        }
1999        $ra;
2000}
2001
2002sub rel_path {
2003        my ($self) = @_;
2004        my $repos_root = $self->ra->{repos_root};
2005        return $self->{path} if ($self->{url} eq $repos_root);
2006        my $url = $self->{url} .
2007                  (length $self->{path} ? "/$self->{path}" : $self->{path});
2008        $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2009        $url;
2010}
2011
2012# prop_walk(PATH, REV, SUB)
2013# -------------------------
2014# Recursively traverse PATH at revision REV and invoke SUB for each
2015# directory that contains a SVN property.  SUB will be invoked as
2016# follows:  &SUB(gs, path, props);  where `gs' is this instance of
2017# Git::SVN, `path' the path to the directory where the properties
2018# `props' were found.  The `path' will be relative to point of checkout,
2019# that is, if url://repo/trunk is the current Git branch, and that
2020# directory contains a sub-directory `d', SUB will be invoked with `/d/'
2021# as `path' (note the trailing `/').
2022sub prop_walk {
2023        my ($self, $path, $rev, $sub) = @_;
2024
2025        $path =~ s#^/##;
2026        my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2027        $path =~ s#^/*#/#g;
2028        my $p = $path;
2029        # Strip the irrelevant part of the path.
2030        $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2031        # Ensure the path is terminated by a `/'.
2032        $p =~ s#/*$#/#;
2033
2034        # The properties contain all the internal SVN stuff nobody
2035        # (usually) cares about.
2036        my $interesting_props = 0;
2037        foreach (keys %{$props}) {
2038                # If it doesn't start with `svn:', it must be a
2039                # user-defined property.
2040                ++$interesting_props and next if $_ !~ /^svn:/;
2041                # FIXME: Fragile, if SVN adds new public properties,
2042                # this needs to be updated.
2043                ++$interesting_props if /^svn:(?:ignore|keywords|executable
2044                                                 |eol-style|mime-type
2045                                                 |externals|needs-lock)$/x;
2046        }
2047        &$sub($self, $p, $props) if $interesting_props;
2048
2049        foreach (sort keys %$dirent) {
2050                next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2051                $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2052        }
2053}
2054
2055sub last_rev { ($_[0]->last_rev_commit)[0] }
2056sub last_commit { ($_[0]->last_rev_commit)[1] }
2057
2058# returns the newest SVN revision number and newest commit SHA1
2059sub last_rev_commit {
2060        my ($self) = @_;
2061        if (defined $self->{last_rev} && defined $self->{last_commit}) {
2062                return ($self->{last_rev}, $self->{last_commit});
2063        }
2064        my $c = ::verify_ref($self->refname.'^0');
2065        if ($c && !$self->use_svm_props && !$self->no_metadata) {
2066                my $rev = (::cmt_metadata($c))[1];
2067                if (defined $rev) {
2068                        ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2069                        return ($rev, $c);
2070                }
2071        }
2072        my $map_path = $self->map_path;
2073        unless (-e $map_path) {
2074                ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2075                return (undef, undef);
2076        }
2077        my ($rev, $commit) = $self->rev_map_max(1);
2078        ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2079        return ($rev, $commit);
2080}
2081
2082sub get_fetch_range {
2083        my ($self, $min, $max) = @_;
2084        $max ||= $self->ra->get_latest_revnum;
2085        $min ||= $self->rev_map_max;
2086        (++$min, $max);
2087}
2088
2089sub tmp_config {
2090        my (@args) = @_;
2091        my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2092        my $config = "$ENV{GIT_DIR}/svn/.metadata";
2093        if (! -f $config && -f $old_def_config) {
2094                rename $old_def_config, $config or
2095                       die "Failed rename $old_def_config => $config: $!\n";
2096        }
2097        my $old_config = $ENV{GIT_CONFIG};
2098        $ENV{GIT_CONFIG} = $config;
2099        $@ = undef;
2100        my @ret = eval {
2101                unless (-f $config) {
2102                        mkfile($config);
2103                        open my $fh, '>', $config or
2104                            die "Can't open $config: $!\n";
2105                        print $fh "; This file is used internally by ",
2106                                  "git-svn\n" or die
2107                                  "Couldn't write to $config: $!\n";
2108                        print $fh "; You should not have to edit it\n" or
2109                              die "Couldn't write to $config: $!\n";
2110                        close $fh or die "Couldn't close $config: $!\n";
2111                }
2112                command('config', @args);
2113        };
2114        my $err = $@;
2115        if (defined $old_config) {
2116                $ENV{GIT_CONFIG} = $old_config;
2117        } else {
2118                delete $ENV{GIT_CONFIG};
2119        }
2120        die $err if $err;
2121        wantarray ? @ret : $ret[0];
2122}
2123
2124sub tmp_index_do {
2125        my ($self, $sub) = @_;
2126        my $old_index = $ENV{GIT_INDEX_FILE};
2127        $ENV{GIT_INDEX_FILE} = $self->{index};
2128        $@ = undef;
2129        my @ret = eval {
2130                my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2131                mkpath([$dir]) unless -d $dir;
2132                &$sub;
2133        };
2134        my $err = $@;
2135        if (defined $old_index) {
2136                $ENV{GIT_INDEX_FILE} = $old_index;
2137        } else {
2138                delete $ENV{GIT_INDEX_FILE};
2139        }
2140        die $err if $err;
2141        wantarray ? @ret : $ret[0];
2142}
2143
2144sub assert_index_clean {
2145        my ($self, $treeish) = @_;
2146
2147        $self->tmp_index_do(sub {
2148                command_noisy('read-tree', $treeish) unless -e $self->{index};
2149                my $x = command_oneline('write-tree');
2150                my ($y) = (command(qw/cat-file commit/, $treeish) =~
2151                           /^tree ($::sha1)/mo);
2152                return if $y eq $x;
2153
2154                warn "Index mismatch: $y != $x\nrereading $treeish\n";
2155                unlink $self->{index} or die "unlink $self->{index}: $!\n";
2156                command_noisy('read-tree', $treeish);
2157                $x = command_oneline('write-tree');
2158                if ($y ne $x) {
2159                        ::fatal "trees ($treeish) $y != $x\n",
2160                                "Something is seriously wrong...";
2161                }
2162        });
2163}
2164
2165sub get_commit_parents {
2166        my ($self, $log_entry) = @_;
2167        my (%seen, @ret, @tmp);
2168        # legacy support for 'set-tree'; this is only used by set_tree_cb:
2169        if (my $ip = $self->{inject_parents}) {
2170                if (my $commit = delete $ip->{$log_entry->{revision}}) {
2171                        push @tmp, $commit;
2172                }
2173        }
2174        if (my $cur = ::verify_ref($self->refname.'^0')) {
2175                push @tmp, $cur;
2176        }
2177        if (my $ipd = $self->{inject_parents_dcommit}) {
2178                if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2179                        push @tmp, @$commit;
2180                }
2181        }
2182        push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2183        while (my $p = shift @tmp) {
2184                next if $seen{$p};
2185                $seen{$p} = 1;
2186                push @ret, $p;
2187                # MAXPARENT is defined to 16 in commit-tree.c:
2188                last if @ret >= 16;
2189        }
2190        if (@tmp) {
2191                die "r$log_entry->{revision}: No room for parents:\n\t",
2192                    join("\n\t", @tmp), "\n";
2193        }
2194        @ret;
2195}
2196
2197sub rewrite_root {
2198        my ($self) = @_;
2199        return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2200        my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2201        my $rwr = eval { command_oneline(qw/config --get/, $k) };
2202        if ($rwr) {
2203                $rwr =~ s#/+$##;
2204                if ($rwr !~ m#^[a-z\+]+://#) {
2205                        die "$rwr is not a valid URL (key: $k)\n";
2206                }
2207        }
2208        $self->{-rewrite_root} = $rwr;
2209}
2210
2211sub metadata_url {
2212        my ($self) = @_;
2213        ($self->rewrite_root || $self->{url}) .
2214           (length $self->{path} ? '/' . $self->{path} : '');
2215}
2216
2217sub full_url {
2218        my ($self) = @_;
2219        $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2220}
2221
2222
2223sub set_commit_header_env {
2224        my ($log_entry) = @_;
2225        my %env;
2226        foreach my $ned (qw/NAME EMAIL DATE/) {
2227                foreach my $ac (qw/AUTHOR COMMITTER/) {
2228                        $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2229                }
2230        }
2231
2232        $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2233        $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2234        $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2235
2236        $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2237                                                ? $log_entry->{commit_name}
2238                                                : $log_entry->{name};
2239        $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2240                                                ? $log_entry->{commit_email}
2241                                                : $log_entry->{email};
2242        \%env;
2243}
2244
2245sub restore_commit_header_env {
2246        my ($env) = @_;
2247        foreach my $ned (qw/NAME EMAIL DATE/) {
2248                foreach my $ac (qw/AUTHOR COMMITTER/) {
2249                        my $k = "GIT_${ac}_${ned}";
2250                        if (defined $env->{$k}) {
2251                                $ENV{$k} = $env->{$k};
2252                        } else {
2253                                delete $ENV{$k};
2254                        }
2255                }
2256        }
2257}
2258
2259sub gc {
2260        command_noisy('gc', '--auto');
2261};
2262
2263sub do_git_commit {
2264        my ($self, $log_entry) = @_;
2265        my $lr = $self->last_rev;
2266        if (defined $lr && $lr >= $log_entry->{revision}) {
2267                die "Last fetched revision of ", $self->refname,
2268                    " was r$lr, but we are about to fetch: ",
2269                    "r$log_entry->{revision}!\n";
2270        }
2271        if (my $c = $self->rev_map_get($log_entry->{revision})) {
2272                croak "$log_entry->{revision} = $c already exists! ",
2273                      "Why are we refetching it?\n";
2274        }
2275        my $old_env = set_commit_header_env($log_entry);
2276        my $tree = $log_entry->{tree};
2277        if (!defined $tree) {
2278                $tree = $self->tmp_index_do(sub {
2279                                            command_oneline('write-tree') });
2280        }
2281        die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2282
2283        my @exec = ('git', 'commit-tree', $tree);
2284        foreach ($self->get_commit_parents($log_entry)) {
2285                push @exec, '-p', $_;
2286        }
2287        defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2288                                                                   or croak $!;
2289        binmode $msg_fh;
2290
2291        # we always get UTF-8 from SVN, but we may want our commits in
2292        # a different encoding.
2293        if (my $enc = Git::config('i18n.commitencoding')) {
2294                require Encode;
2295                Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2296        }
2297        print $msg_fh $log_entry->{log} or croak $!;
2298        restore_commit_header_env($old_env);
2299        unless ($self->no_metadata) {
2300                print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2301                              or croak $!;
2302        }
2303        $msg_fh->flush == 0 or croak $!;
2304        close $msg_fh or croak $!;
2305        chomp(my $commit = do { local $/; <$out_fh> });
2306        close $out_fh or croak $!;
2307        waitpid $pid, 0;
2308        croak $? if $?;
2309        if ($commit !~ /^$::sha1$/o) {
2310                die "Failed to commit, invalid sha1: $commit\n";
2311        }
2312
2313        $self->rev_map_set($log_entry->{revision}, $commit, 1);
2314
2315        $self->{last_rev} = $log_entry->{revision};
2316        $self->{last_commit} = $commit;
2317        print "r$log_entry->{revision}";
2318        if (defined $log_entry->{svm_revision}) {
2319                 print " (\@$log_entry->{svm_revision})";
2320                 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2321                                   0, $self->svm_uuid);
2322        }
2323        print " = $commit ($self->{ref_id})\n";
2324        if (--$_gc_nr == 0) {
2325                $_gc_nr = $_gc_period;
2326                gc();
2327        }
2328        return $commit;
2329}
2330
2331sub match_paths {
2332        my ($self, $paths, $r) = @_;
2333        return 1 if $self->{path} eq '';
2334        if (my $path = $paths->{"/$self->{path}"}) {
2335                return ($path->{action} eq 'D') ? 0 : 1;
2336        }
2337        $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2338        if (grep /$self->{path_regex}/, keys %$paths) {
2339                return 1;
2340        }
2341        my $c = '';
2342        foreach (split m#/#, $self->{path}) {
2343                $c .= "/$_";
2344                next unless ($paths->{$c} &&
2345                             ($paths->{$c}->{action} =~ /^[AR]$/));
2346                if ($self->ra->check_path($self->{path}, $r) ==
2347                    $SVN::Node::dir) {
2348                        return 1;
2349                }
2350        }
2351        return 0;
2352}
2353
2354sub find_parent_branch {
2355        my ($self, $paths, $rev) = @_;
2356        return undef unless $self->follow_parent;
2357        unless (defined $paths) {
2358                my $err_handler = $SVN::Error::handler;
2359                $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2360                $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2361                                   $paths =
2362                                      Git::SVN::Ra::dup_changed_paths($_[0]) });
2363                $SVN::Error::handler = $err_handler;
2364        }
2365        return undef unless defined $paths;
2366
2367        # look for a parent from another branch:
2368        my @b_path_components = split m#/#, $self->rel_path;
2369        my @a_path_components;
2370        my $i;
2371        while (@b_path_components) {
2372                $i = $paths->{'/'.join('/', @b_path_components)};
2373                last if $i && defined $i->{copyfrom_path};
2374                unshift(@a_path_components, pop(@b_path_components));
2375        }
2376        return undef unless defined $i && defined $i->{copyfrom_path};
2377        my $branch_from = $i->{copyfrom_path};
2378        if (@a_path_components) {
2379                print STDERR "branch_from: $branch_from => ";
2380                $branch_from .= '/'.join('/', @a_path_components);
2381                print STDERR $branch_from, "\n";
2382        }
2383        my $r = $i->{copyfrom_rev};
2384        my $repos_root = $self->ra->{repos_root};
2385        my $url = $self->ra->{url};
2386        my $new_url = $repos_root . $branch_from;
2387        print STDERR  "Found possible branch point: ",
2388                      "$new_url => ", $self->full_url, ", $r\n";
2389        $branch_from =~ s#^/##;
2390        my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2391        unless ($gs) {
2392                my $ref_id = $self->{ref_id};
2393                $ref_id =~ s/\@\d+$//;
2394                $ref_id .= "\@$r";
2395                # just grow a tail if we're not unique enough :x
2396                $ref_id .= '-' while find_ref($ref_id);
2397                print STDERR "Initializing parent: $ref_id\n";
2398                my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2399                if ($u =~ s#^\Q$url\E(/|$)##) {
2400                        $p = $u;
2401                        $u = $url;
2402                        $repo_id = $self->{repo_id};
2403                }
2404                $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2405        }
2406        my ($r0, $parent) = $gs->find_rev_before($r, 1);
2407        {
2408                my ($base, $head);
2409                if (!defined $r0 || !defined $parent) {
2410                        ($base, $head) = parse_revision_argument(0, $r);
2411                } else {
2412                        if ($r0 < $r) {
2413                                $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2414                                        0, 1, sub { $base = $_[1] - 1 });
2415                        }
2416                }
2417                if (defined $base && $base <= $r) {
2418                        $gs->fetch($base, $r);
2419                }
2420                ($r0, $parent) = $gs->find_rev_before($r, 1);
2421        }
2422        if (defined $r0 && defined $parent) {
2423                print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2424                my $ed;
2425                if ($self->ra->can_do_switch) {
2426                        $self->assert_index_clean($parent);
2427                        print STDERR "Following parent with do_switch\n";
2428                        # do_switch works with svn/trunk >= r22312, but that
2429                        # is not included with SVN 1.4.3 (the latest version
2430                        # at the moment), so we can't rely on it
2431                        $self->{last_commit} = $parent;
2432                        $ed = SVN::Git::Fetcher->new($self);
2433                        $gs->ra->gs_do_switch($r0, $rev, $gs,
2434                                              $self->full_url, $ed)
2435                          or die "SVN connection failed somewhere...\n";
2436                } elsif ($self->ra->trees_match($new_url, $r0,
2437                                                $self->full_url, $rev)) {
2438                        print STDERR "Trees match:\n",
2439                                     "  $new_url\@$r0\n",
2440                                     "  ${\$self->full_url}\@$rev\n",
2441                                     "Following parent with no changes\n";
2442                        $self->tmp_index_do(sub {
2443                            command_noisy('read-tree', $parent);
2444                        });
2445                        $self->{last_commit} = $parent;
2446                } else {
2447                        print STDERR "Following parent with do_update\n";
2448                        $ed = SVN::Git::Fetcher->new($self);
2449                        $self->ra->gs_do_update($rev, $rev, $self, $ed)
2450                          or die "SVN connection failed somewhere...\n";
2451                }
2452                print STDERR "Successfully followed parent\n";
2453                return $self->make_log_entry($rev, [$parent], $ed);
2454        }
2455        return undef;
2456}
2457
2458sub do_fetch {
2459        my ($self, $paths, $rev) = @_;
2460        my $ed;
2461        my ($last_rev, @parents);
2462        if (my $lc = $self->last_commit) {
2463                # we can have a branch that was deleted, then re-added
2464                # under the same name but copied from another path, in
2465                # which case we'll have multiple parents (we don't
2466                # want to break the original ref, nor lose copypath info):
2467                if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2468                        push @{$log_entry->{parents}}, $lc;
2469                        return $log_entry;
2470                }
2471                $ed = SVN::Git::Fetcher->new($self);
2472                $last_rev = $self->{last_rev};
2473                $ed->{c} = $lc;
2474                @parents = ($lc);
2475        } else {
2476                $last_rev = $rev;
2477                if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2478                        return $log_entry;
2479                }
2480                $ed = SVN::Git::Fetcher->new($self);
2481        }
2482        unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2483                die "SVN connection failed somewhere...\n";
2484        }
2485        $self->make_log_entry($rev, \@parents, $ed);
2486}
2487
2488sub get_untracked {
2489        my ($self, $ed) = @_;
2490        my @out;
2491        my $h = $ed->{empty};
2492        foreach (sort keys %$h) {
2493                my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2494                push @out, "  $act: " . uri_encode($_);
2495                warn "W: $act: $_\n";
2496        }
2497        foreach my $t (qw/dir_prop file_prop/) {
2498                $h = $ed->{$t} or next;
2499                foreach my $path (sort keys %$h) {
2500                        my $ppath = $path eq '' ? '.' : $path;
2501                        foreach my $prop (sort keys %{$h->{$path}}) {
2502                                next if $SKIP_PROP{$prop};
2503                                my $v = $h->{$path}->{$prop};
2504                                my $t_ppath_prop = "$t: " .
2505                                                    uri_encode($ppath) . ' ' .
2506                                                    uri_encode($prop);
2507                                if (defined $v) {
2508                                        push @out, "  +$t_ppath_prop " .
2509                                                   uri_encode($v);
2510                                } else {
2511                                        push @out, "  -$t_ppath_prop";
2512                                }
2513                        }
2514                }
2515        }
2516        foreach my $t (qw/absent_file absent_directory/) {
2517                $h = $ed->{$t} or next;
2518                foreach my $parent (sort keys %$h) {
2519                        foreach my $path (sort @{$h->{$parent}}) {
2520                                push @out, "  $t: " .
2521                                           uri_encode("$parent/$path");
2522                                warn "W: $t: $parent/$path ",
2523                                     "Insufficient permissions?\n";
2524                        }
2525                }
2526        }
2527        \@out;
2528}
2529
2530# parse_svn_date(DATE)
2531# --------------------
2532# Given a date (in UTC) from Subversion, return a string in the format
2533# "<TZ Offset> <local date/time>" that Git will use.
2534#
2535# By default the parsed date will be in UTC; if $Git::SVN::_localtime
2536# is true we'll convert it to the local timezone instead.
2537sub parse_svn_date {
2538        my $date = shift || return '+0000 1970-01-01 00:00:00';
2539        my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2540                                            (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2541                                         croak "Unable to parse date: $date\n";
2542        my $parsed_date;    # Set next.
2543
2544        if ($Git::SVN::_localtime) {
2545                # Translate the Subversion datetime to an epoch time.
2546                # Begin by switching ourselves to $date's timezone, UTC.
2547                my $old_env_TZ = $ENV{TZ};
2548                $ENV{TZ} = 'UTC';
2549
2550                my $epoch_in_UTC =
2551                    POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2552
2553                # Determine our local timezone (including DST) at the
2554                # time of $epoch_in_UTC.  $Git::SVN::Log::TZ stored the
2555                # value of TZ, if any, at the time we were run.
2556                if (defined $Git::SVN::Log::TZ) {
2557                        $ENV{TZ} = $Git::SVN::Log::TZ;
2558                } else {
2559                        delete $ENV{TZ};
2560                }
2561
2562                my $our_TZ =
2563                    POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2564
2565                # This converts $epoch_in_UTC into our local timezone.
2566                my ($sec, $min, $hour, $mday, $mon, $year,
2567                    $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2568
2569                $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2570                                       $our_TZ, $year + 1900, $mon + 1,
2571                                       $mday, $hour, $min, $sec);
2572
2573                # Reset us to the timezone in effect when we entered
2574                # this routine.
2575                if (defined $old_env_TZ) {
2576                        $ENV{TZ} = $old_env_TZ;
2577                } else {
2578                        delete $ENV{TZ};
2579                }
2580        } else {
2581                $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2582        }
2583
2584        return $parsed_date;
2585}
2586
2587sub check_author {
2588        my ($author) = @_;
2589        if (!defined $author || length $author == 0) {
2590                $author = '(no author)';
2591        } elsif (defined $::_authors && ! defined $::users{$author}) {
2592                die "Author: $author not defined in $::_authors file\n";
2593        }
2594        $author;
2595}
2596
2597sub make_log_entry {
2598        my ($self, $rev, $parents, $ed) = @_;
2599        my $untracked = $self->get_untracked($ed);
2600
2601        open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2602        print $un "r$rev\n" or croak $!;
2603        print $un $_, "\n" foreach @$untracked;
2604        my %log_entry = ( parents => $parents || [], revision => $rev,
2605                          log => '');
2606
2607        my $headrev;
2608        my $logged = delete $self->{logged_rev_props};
2609        if (!$logged || $self->{-want_revprops}) {
2610                my $rp = $self->ra->rev_proplist($rev);
2611                foreach (sort keys %$rp) {
2612                        my $v = $rp->{$_};
2613                        if (/^svn:(author|date|log)$/) {
2614                                $log_entry{$1} = $v;
2615                        } elsif ($_ eq 'svm:headrev') {
2616                                $headrev = $v;
2617                        } else {
2618                                print $un "  rev_prop: ", uri_encode($_), ' ',
2619                                          uri_encode($v), "\n";
2620                        }
2621                }
2622        } else {
2623                map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2624        }
2625        close $un or croak $!;
2626
2627        $log_entry{date} = parse_svn_date($log_entry{date});
2628        $log_entry{log} .= "\n";
2629        my $author = $log_entry{author} = check_author($log_entry{author});
2630        my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2631                                                       : ($author, undef);
2632
2633        my ($commit_name, $commit_email) = ($name, $email);
2634        if ($_use_log_author) {
2635                my $name_field;
2636                if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2637                        $name_field = $1;
2638                } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2639                        $name_field = $1;
2640                }
2641                if (!defined $name_field) {
2642                        if (!defined $email) {
2643                                $email = $name;
2644                        }
2645                } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2646                        ($name, $email) = ($1, $2);
2647                } elsif ($name_field =~ /(.*)@/) {
2648                        ($name, $email) = ($1, $name_field);
2649                } else {
2650                        ($name, $email) = ($name_field, $name_field);
2651                }
2652        }
2653        if (defined $headrev && $self->use_svm_props) {
2654                if ($self->rewrite_root) {
2655                        die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2656                            "options set!\n";
2657                }
2658                my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2659                # we don't want "SVM: initializing mirror for junk" ...
2660                return undef if $r == 0;
2661                my $svm = $self->svm;
2662                if ($uuid ne $svm->{uuid}) {
2663                        die "UUID mismatch on SVM path:\n",
2664                            "expected: $svm->{uuid}\n",
2665                            "     got: $uuid\n";
2666                }
2667                my $full_url = $self->full_url;
2668                $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2669                             die "Failed to replace '$svm->{replace}' with ",
2670                                 "'$svm->{source}' in $full_url\n";
2671                # throw away username for storing in records
2672                remove_username($full_url);
2673                $log_entry{metadata} = "$full_url\@$r $uuid";
2674                $log_entry{svm_revision} = $r;
2675                $email ||= "$author\@$uuid";
2676                $commit_email ||= "$author\@$uuid";
2677        } elsif ($self->use_svnsync_props) {
2678                my $full_url = $self->svnsync->{url};
2679                $full_url .= "/$self->{path}" if length $self->{path};
2680                remove_username($full_url);
2681                my $uuid = $self->svnsync->{uuid};
2682                $log_entry{metadata} = "$full_url\@$rev $uuid";
2683                $email ||= "$author\@$uuid";
2684                $commit_email ||= "$author\@$uuid";
2685        } else {
2686                my $url = $self->metadata_url;
2687                remove_username($url);
2688                $log_entry{metadata} = "$url\@$rev " .
2689                                       $self->ra->get_uuid;
2690                $email ||= "$author\@" . $self->ra->get_uuid;
2691                $commit_email ||= "$author\@" . $self->ra->get_uuid;
2692        }
2693        $log_entry{name} = $name;
2694        $log_entry{email} = $email;
2695        $log_entry{commit_name} = $commit_name;
2696        $log_entry{commit_email} = $commit_email;
2697        \%log_entry;
2698}
2699
2700sub fetch {
2701        my ($self, $min_rev, $max_rev, @parents) = @_;
2702        my ($last_rev, $last_commit) = $self->last_rev_commit;
2703        my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2704        $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2705}
2706
2707sub set_tree_cb {
2708        my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2709        $self->{inject_parents} = { $rev => $tree };
2710        $self->fetch(undef, undef);
2711}
2712
2713sub set_tree {
2714        my ($self, $tree) = (shift, shift);
2715        my $log_entry = ::get_commit_entry($tree);
2716        unless ($self->{last_rev}) {
2717                ::fatal("Must have an existing revision to commit");
2718        }
2719        my %ed_opts = ( r => $self->{last_rev},
2720                        log => $log_entry->{log},
2721                        ra => $self->ra,
2722                        tree_a => $self->{last_commit},
2723                        tree_b => $tree,
2724                        editor_cb => sub {
2725                               $self->set_tree_cb($log_entry, $tree, @_) },
2726                        svn_path => $self->{path} );
2727        if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2728                print "No changes\nr$self->{last_rev} = $tree\n";
2729        }
2730}
2731
2732sub rebuild_from_rev_db {
2733        my ($self, $path) = @_;
2734        my $r = -1;
2735        open my $fh, '<', $path or croak "open: $!";
2736        binmode $fh or croak "binmode: $!";
2737        while (<$fh>) {
2738                length($_) == 41 or croak "inconsistent size in ($_) != 41";
2739                chomp($_);
2740                ++$r;
2741                next if $_ eq ('0' x 40);
2742                $self->rev_map_set($r, $_);
2743                print "r$r = $_\n";
2744        }
2745        close $fh or croak "close: $!";
2746        unlink $path or croak "unlink: $!";
2747}
2748
2749sub rebuild {
2750        my ($self) = @_;
2751        my $map_path = $self->map_path;
2752        my $partial = (-e $map_path && ! -z $map_path);
2753        return unless ::verify_ref($self->refname.'^0');
2754        if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2755                my $rev_db = $self->rev_db_path;
2756                $self->rebuild_from_rev_db($rev_db);
2757                if ($self->use_svm_props) {
2758                        my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2759                        $self->rebuild_from_rev_db($svm_rev_db);
2760                }
2761                $self->unlink_rev_db_symlink;
2762                return;
2763        }
2764        print "Rebuilding $map_path ...\n" if (!$partial);
2765        my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2766                (undef, undef));
2767        my ($log, $ctx) =
2768            command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2769                                ($head ? "$head.." : "") . $self->refname,
2770                                '--');
2771        my $metadata_url = $self->metadata_url;
2772        remove_username($metadata_url);
2773        my $svn_uuid = $self->ra_uuid;
2774        my $c;
2775        while (<$log>) {
2776                if ( m{^commit ($::sha1)$} ) {
2777                        $c = $1;
2778                        next;
2779                }
2780                next unless s{^\s*(git-svn-id:)}{$1};
2781                my ($url, $rev, $uuid) = ::extract_metadata($_);
2782                remove_username($url);
2783
2784                # ignore merges (from set-tree)
2785                next if (!defined $rev || !$uuid);
2786
2787                # if we merged or otherwise started elsewhere, this is
2788                # how we break out of it
2789                if (($uuid ne $svn_uuid) ||
2790                    ($metadata_url && $url && ($url ne $metadata_url))) {
2791                        next;
2792                }
2793                if ($partial && $head) {
2794                        print "Partial-rebuilding $map_path ...\n";
2795                        print "Currently at $base_rev = $head\n";
2796                        $head = undef;
2797                }
2798
2799                $self->rev_map_set($rev, $c);
2800                print "r$rev = $c\n";
2801        }
2802        command_close_pipe($log, $ctx);
2803        print "Done rebuilding $map_path\n" if (!$partial || !$head);
2804        my $rev_db_path = $self->rev_db_path;
2805        if (-f $self->rev_db_path) {
2806                unlink $self->rev_db_path or croak "unlink: $!";
2807        }
2808        $self->unlink_rev_db_symlink;
2809}
2810
2811# rev_map:
2812# Tie::File seems to be prone to offset errors if revisions get sparse,
2813# it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2814# one of my favorite modules is out :<  Next up would be one of the DBM
2815# modules, but I'm not sure which is most portable...
2816#
2817# This is the replacement for the rev_db format, which was too big
2818# and inefficient for large repositories with a lot of sparse history
2819# (mainly tags)
2820#
2821# The format is this:
2822#   - 24 bytes for every record,
2823#     * 4 bytes for the integer representing an SVN revision number
2824#     * 20 bytes representing the sha1 of a git commit
2825#   - No empty padding records like the old format
2826#     (except the last record, which can be overwritten)
2827#   - new records are written append-only since SVN revision numbers
2828#     increase monotonically
2829#   - lookups on SVN revision number are done via a binary search
2830#   - Piping the file to xxd -c24 is a good way of dumping it for
2831#     viewing or editing (piped back through xxd -r), should the need
2832#     ever arise.
2833#   - The last record can be padding revision with an all-zero sha1
2834#     This is used to optimize fetch performance when using multiple
2835#     "fetch" directives in .git/config
2836#
2837# These files are disposable unless noMetadata or useSvmProps is set
2838
2839sub _rev_map_set {
2840        my ($fh, $rev, $commit) = @_;
2841
2842        binmode $fh or croak "binmode: $!";
2843        my $size = (stat($fh))[7];
2844        ($size % 24) == 0 or croak "inconsistent size: $size";
2845
2846        my $wr_offset = 0;
2847        if ($size > 0) {
2848                sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2849                my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2850                $read == 24 or croak "read only $read bytes (!= 24)";
2851                my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2852                if ($last_commit eq ('0' x40)) {
2853                        if ($size >= 48) {
2854                                sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2855                                $read = sysread($fh, $buf, 24) or
2856                                    croak "read: $!";
2857                                $read == 24 or
2858                                    croak "read only $read bytes (!= 24)";
2859                                ($last_rev, $last_commit) =
2860                                    unpack(rev_map_fmt, $buf);
2861                                if ($last_commit eq ('0' x40)) {
2862                                        croak "inconsistent .rev_map\n";
2863                                }
2864                        }
2865                        if ($last_rev >= $rev) {
2866                                croak "last_rev is higher!: $last_rev >= $rev";
2867                        }
2868                        $wr_offset = -24;
2869                }
2870        }
2871        sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2872        syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2873          croak "write: $!";
2874}
2875
2876sub mkfile {
2877        my ($path) = @_;
2878        unless (-e $path) {
2879                my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2880                mkpath([$dir]) unless -d $dir;
2881                open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2882                close $fh or die "Couldn't close (create) $path: $!\n";
2883        }
2884}
2885
2886sub rev_map_set {
2887        my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2888        length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2889        my $db = $self->map_path($uuid);
2890        my $db_lock = "$db.lock";
2891        my $sig;
2892        if ($update_ref) {
2893                $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2894                            $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2895        }
2896        mkfile($db);
2897
2898        $LOCKFILES{$db_lock} = 1;
2899        my $sync;
2900        # both of these options make our .rev_db file very, very important
2901        # and we can't afford to lose it because rebuild() won't work
2902        if ($self->use_svm_props || $self->no_metadata) {
2903                $sync = 1;
2904                copy($db, $db_lock) or die "rev_map_set(@_): ",
2905                                           "Failed to copy: ",
2906                                           "$db => $db_lock ($!)\n";
2907        } else {
2908                rename $db, $db_lock or die "rev_map_set(@_): ",
2909                                            "Failed to rename: ",
2910                                            "$db => $db_lock ($!)\n";
2911        }
2912
2913        sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2914             or croak "Couldn't open $db_lock: $!\n";
2915        _rev_map_set($fh, $rev, $commit);
2916        if ($sync) {
2917                $fh->flush or die "Couldn't flush $db_lock: $!\n";
2918                $fh->sync or die "Couldn't sync $db_lock: $!\n";
2919        }
2920        close $fh or croak $!;
2921        if ($update_ref) {
2922                $_head = $self;
2923                command_noisy('update-ref', '-m', "r$rev",
2924                              $self->refname, $commit);
2925        }
2926        rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2927                                    "$db_lock => $db ($!)\n";
2928        delete $LOCKFILES{$db_lock};
2929        if ($update_ref) {
2930                $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2931                            $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2932                kill $sig, $$ if defined $sig;
2933        }
2934}
2935
2936# If want_commit, this will return an array of (rev, commit) where
2937# commit _must_ be a valid commit in the archive.
2938# Otherwise, it'll return the max revision (whether or not the
2939# commit is valid or just a 0x40 placeholder).
2940sub rev_map_max {
2941        my ($self, $want_commit) = @_;
2942        $self->rebuild;
2943        my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2944        $want_commit ? ($r, $c) : $r;
2945}
2946
2947sub rev_map_max_norebuild {
2948        my ($self, $want_commit) = @_;
2949        my $map_path = $self->map_path;
2950        stat $map_path or return $want_commit ? (0, undef) : 0;
2951        sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2952        binmode $fh or croak "binmode: $!";
2953        my $size = (stat($fh))[7];
2954        ($size % 24) == 0 or croak "inconsistent size: $size";
2955
2956        if ($size == 0) {
2957                close $fh or croak "close: $!";
2958                return $want_commit ? (0, undef) : 0;
2959        }
2960
2961        sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2962        sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2963        my ($r, $c) = unpack(rev_map_fmt, $buf);
2964        if ($want_commit && $c eq ('0' x40)) {
2965                if ($size < 48) {
2966                        return $want_commit ? (0, undef) : 0;
2967                }
2968                sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2969                sysread($fh, $buf, 24) == 24 or croak "read: $!";
2970                ($r, $c) = unpack(rev_map_fmt, $buf);
2971                if ($c eq ('0'x40)) {
2972                        croak "Penultimate record is all-zeroes in $map_path";
2973                }
2974        }
2975        close $fh or croak "close: $!";
2976        $want_commit ? ($r, $c) : $r;
2977}
2978
2979sub rev_map_get {
2980        my ($self, $rev, $uuid) = @_;
2981        my $map_path = $self->map_path($uuid);
2982        return undef unless -e $map_path;
2983
2984        sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2985        binmode $fh or croak "binmode: $!";
2986        my $size = (stat($fh))[7];
2987        ($size % 24) == 0 or croak "inconsistent size: $size";
2988
2989        if ($size == 0) {
2990                close $fh or croak "close: $fh";
2991                return undef;
2992        }
2993
2994        my ($l, $u) = (0, $size - 24);
2995        my ($r, $c, $buf);
2996
2997        while ($l <= $u) {
2998                my $i = int(($l/24 + $u/24) / 2) * 24;
2999                sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3000                sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3001                my ($r, $c) = unpack('NH40', $buf);
3002
3003                if ($r < $rev) {
3004                        $l = $i + 24;
3005                } elsif ($r > $rev) {
3006                        $u = $i - 24;
3007                } else { # $r == $rev
3008                        close($fh) or croak "close: $!";
3009                        return $c eq ('0' x 40) ? undef : $c;
3010                }
3011        }
3012        close($fh) or croak "close: $!";
3013        undef;
3014}
3015
3016# Finds the first svn revision that exists on (if $eq_ok is true) or
3017# before $rev for the current branch.  It will not search any lower
3018# than $min_rev.  Returns the git commit hash and svn revision number
3019# if found, else (undef, undef).
3020sub find_rev_before {
3021        my ($self, $rev, $eq_ok, $min_rev) = @_;
3022        --$rev unless $eq_ok;
3023        $min_rev ||= 1;
3024        while ($rev >= $min_rev) {
3025                if (my $c = $self->rev_map_get($rev)) {
3026                        return ($rev, $c);
3027                }
3028                --$rev;
3029        }
3030        return (undef, undef);
3031}
3032
3033# Finds the first svn revision that exists on (if $eq_ok is true) or
3034# after $rev for the current branch.  It will not search any higher
3035# than $max_rev.  Returns the git commit hash and svn revision number
3036# if found, else (undef, undef).
3037sub find_rev_after {
3038        my ($self, $rev, $eq_ok, $max_rev) = @_;
3039        ++$rev unless $eq_ok;
3040        $max_rev ||= $self->rev_map_max;
3041        while ($rev <= $max_rev) {
3042                if (my $c = $self->rev_map_get($rev)) {
3043                        return ($rev, $c);
3044                }
3045                ++$rev;
3046        }
3047        return (undef, undef);
3048}
3049
3050sub _new {
3051        my ($class, $repo_id, $ref_id, $path) = @_;
3052        unless (defined $repo_id && length $repo_id) {
3053                $repo_id = $Git::SVN::default_repo_id;
3054        }
3055        unless (defined $ref_id && length $ref_id) {
3056                $_[2] = $ref_id = $Git::SVN::default_ref_id;
3057        }
3058        $_[1] = $repo_id;
3059        my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3060        $_[3] = $path = '' unless (defined $path);
3061        mkpath(["$ENV{GIT_DIR}/svn"]);
3062        bless {
3063                ref_id => $ref_id, dir => $dir, index => "$dir/index",
3064                path => $path, config => "$ENV{GIT_DIR}/svn/config",
3065                map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3066}
3067
3068# for read-only access of old .rev_db formats
3069sub unlink_rev_db_symlink {
3070        my ($self) = @_;
3071        my $link = $self->rev_db_path;
3072        $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3073        if (-l $link) {
3074                unlink $link or croak "unlink: $link failed!";
3075        }
3076}
3077
3078sub rev_db_path {
3079        my ($self, $uuid) = @_;
3080        my $db_path = $self->map_path($uuid);
3081        $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3082            or croak "map_path: $db_path does not contain '/.rev_map.' !";
3083        $db_path;
3084}
3085
3086# the new replacement for .rev_db
3087sub map_path {
3088        my ($self, $uuid) = @_;
3089        $uuid ||= $self->ra_uuid;
3090        "$self->{map_root}.$uuid";
3091}
3092
3093sub uri_encode {
3094        my ($f) = @_;
3095        $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3096        $f
3097}
3098
3099sub remove_username {
3100        $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3101}
3102
3103package Git::SVN::Prompt;
3104use strict;
3105use warnings;
3106require SVN::Core;
3107use vars qw/$_no_auth_cache $_username/;
3108
3109sub simple {
3110        my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3111        $may_save = undef if $_no_auth_cache;
3112        $default_username = $_username if defined $_username;
3113        if (defined $default_username && length $default_username) {
3114                if (defined $realm && length $realm) {
3115                        print STDERR "Authentication realm: $realm\n";
3116                        STDERR->flush;
3117                }
3118                $cred->username($default_username);
3119        } else {
3120                username($cred, $realm, $may_save, $pool);
3121        }
3122        $cred->password(_read_password("Password for '" .
3123                                       $cred->username . "': ", $realm));
3124        $cred->may_save($may_save);
3125        $SVN::_Core::SVN_NO_ERROR;
3126}
3127
3128sub ssl_server_trust {
3129        my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3130        $may_save = undef if $_no_auth_cache;
3131        print STDERR "Error validating server certificate for '$realm':\n";
3132        {
3133                no warnings 'once';
3134                # All variables SVN::Auth::SSL::* are used only once,
3135                # so we're shutting up Perl warnings about this.
3136                if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3137                        print STDERR " - The certificate is not issued ",
3138                            "by a trusted authority. Use the\n",
3139                            "   fingerprint to validate ",
3140                            "the certificate manually!\n";
3141                }
3142                if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3143                        print STDERR " - The certificate hostname ",
3144                            "does not match.\n";
3145                }
3146                if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3147                        print STDERR " - The certificate is not yet valid.\n";
3148                }
3149                if ($failures & $SVN::Auth::SSL::EXPIRED) {
3150                        print STDERR " - The certificate has expired.\n";
3151                }
3152                if ($failures & $SVN::Auth::SSL::OTHER) {
3153                        print STDERR " - The certificate has ",
3154                            "an unknown error.\n";
3155                }
3156        } # no warnings 'once'
3157        printf STDERR
3158                "Certificate information:\n".
3159                " - Hostname: %s\n".
3160                " - Valid: from %s until %s\n".
3161                " - Issuer: %s\n".
3162                " - Fingerprint: %s\n",
3163                map $cert_info->$_, qw(hostname valid_from valid_until
3164                                       issuer_dname fingerprint);
3165        my $choice;
3166prompt:
3167        print STDERR $may_save ?
3168              "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3169              "(R)eject or accept (t)emporarily? ";
3170        STDERR->flush;
3171        $choice = lc(substr(<STDIN> || 'R', 0, 1));
3172        if ($choice =~ /^t$/i) {
3173                $cred->may_save(undef);
3174        } elsif ($choice =~ /^r$/i) {
3175                return -1;
3176        } elsif ($may_save && $choice =~ /^p$/i) {
3177                $cred->may_save($may_save);
3178        } else {
3179                goto prompt;
3180        }
3181        $cred->accepted_failures($failures);
3182        $SVN::_Core::SVN_NO_ERROR;
3183}
3184
3185sub ssl_client_cert {
3186        my ($cred, $realm, $may_save, $pool) = @_;
3187        $may_save = undef if $_no_auth_cache;
3188        print STDERR "Client certificate filename: ";
3189        STDERR->flush;
3190        chomp(my $filename = <STDIN>);
3191        $cred->cert_file($filename);
3192        $cred->may_save($may_save);
3193        $SVN::_Core::SVN_NO_ERROR;
3194}
3195
3196sub ssl_client_cert_pw {
3197        my ($cred, $realm, $may_save, $pool) = @_;
3198        $may_save = undef if $_no_auth_cache;
3199        $cred->password(_read_password("Password: ", $realm));
3200        $cred->may_save($may_save);
3201        $SVN::_Core::SVN_NO_ERROR;
3202}
3203
3204sub username {
3205        my ($cred, $realm, $may_save, $pool) = @_;
3206        $may_save = undef if $_no_auth_cache;
3207        if (defined $realm && length $realm) {
3208                print STDERR "Authentication realm: $realm\n";
3209        }
3210        my $username;
3211        if (defined $_username) {
3212                $username = $_username;
3213        } else {
3214                print STDERR "Username: ";
3215                STDERR->flush;
3216                chomp($username = <STDIN>);
3217        }
3218        $cred->username($username);
3219        $cred->may_save($may_save);
3220        $SVN::_Core::SVN_NO_ERROR;
3221}
3222
3223sub _read_password {
3224        my ($prompt, $realm) = @_;
3225        print STDERR $prompt;
3226        STDERR->flush;
3227        require Term::ReadKey;
3228        Term::ReadKey::ReadMode('noecho');
3229        my $password = '';
3230        while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3231                last if $key =~ /[\012\015]/; # \n\r
3232                $password .= $key;
3233        }
3234        Term::ReadKey::ReadMode('restore');
3235        print STDERR "\n";
3236        STDERR->flush;
3237        $password;
3238}
3239
3240package SVN::Git::Fetcher;
3241use vars qw/@ISA/;
3242use strict;
3243use warnings;
3244use Carp qw/croak/;
3245use File::Temp qw/tempfile/;
3246use IO::File qw//;
3247
3248# file baton members: path, mode_a, mode_b, pool, fh, blob, base
3249sub new {
3250        my ($class, $git_svn) = @_;
3251        my $self = SVN::Delta::Editor->new;
3252        bless $self, $class;
3253        if (exists $git_svn->{last_commit}) {
3254                $self->{c} = $git_svn->{last_commit};
3255                $self->{empty_symlinks} = _mark_empty_symlinks($git_svn);
3256        }
3257        $self->{empty} = {};
3258        $self->{dir_prop} = {};
3259        $self->{file_prop} = {};
3260        $self->{absent_dir} = {};
3261        $self->{absent_file} = {};
3262        $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3263        $self;
3264}
3265
3266# this uses the Ra object, so it must be called before do_{switch,update},
3267# not inside them (when the Git::SVN::Fetcher object is passed) to
3268# do_{switch,update}
3269sub _mark_empty_symlinks {
3270        my ($git_svn) = @_;
3271        my %ret;
3272        my ($rev, $cmt) = $git_svn->last_rev_commit;
3273        return {} unless ($rev && $cmt);
3274
3275        chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3276        my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3277        local $/ = "\0";
3278        my $pfx = $git_svn->{path};
3279        $pfx .= '/' if length($pfx);
3280        while (<$ls>) {
3281                chomp;
3282                s/\A100644 blob $empty_blob\t//o or next;
3283                my $path = $_;
3284                my (undef, $props) =
3285                               $git_svn->ra->get_file($pfx.$path, $rev, undef);
3286                if ($props->{'svn:special'}) {
3287                        $ret{$path} = 1;
3288                }
3289        }
3290        command_close_pipe($ls, $ctx);
3291        \%ret;
3292}
3293
3294# returns true if a given path is inside a ".git" directory
3295sub in_dot_git {
3296        $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3297}
3298
3299sub set_path_strip {
3300        my ($self, $path) = @_;
3301        $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3302}
3303
3304sub open_root {
3305        { path => '' };
3306}
3307
3308sub open_directory {
3309        my ($self, $path, $pb, $rev) = @_;
3310        { path => $path };
3311}
3312
3313sub git_path {
3314        my ($self, $path) = @_;
3315        if ($self->{path_strip}) {
3316                $path =~ s!$self->{path_strip}!! or
3317                  die "Failed to strip path '$path' ($self->{path_strip})\n";
3318        }
3319        $path;
3320}
3321
3322sub delete_entry {
3323        my ($self, $path, $rev, $pb) = @_;
3324        return undef if in_dot_git($path);
3325
3326        my $gpath = $self->git_path($path);
3327        return undef if ($gpath eq '');
3328
3329        # remove entire directories.
3330        if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3331                my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3332                                                     -r --name-only -z/,
3333                                                     $self->{c}, '--', $gpath);
3334                local $/ = "\0";
3335                while (<$ls>) {
3336                        chomp;
3337                        $self->{gii}->remove($_);
3338                        print "\tD\t$_\n" unless $::_q;
3339                }
3340                print "\tD\t$gpath/\n" unless $::_q;
3341                command_close_pipe($ls, $ctx);
3342                $self->{empty}->{$path} = 0
3343        } else {
3344                $self->{gii}->remove($gpath);
3345                print "\tD\t$gpath\n" unless $::_q;
3346        }
3347        undef;
3348}
3349
3350sub open_file {
3351        my ($self, $path, $pb, $rev) = @_;
3352        my ($mode, $blob);
3353
3354        goto out if in_dot_git($path);
3355
3356        my $gpath = $self->git_path($path);
3357        ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3358                             =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3359        unless (defined $mode && defined $blob) {
3360                die "$path was not found in commit $self->{c} (r$rev)\n";
3361        }
3362        if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3363                $mode = '120000';
3364        }
3365out:
3366        { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3367          pool => SVN::Pool->new, action => 'M' };
3368}
3369
3370sub add_file {
3371        my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3372        my $mode;
3373
3374        if (!in_dot_git($path)) {
3375                my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3376                delete $self->{empty}->{$dir};
3377                $mode = '100644';
3378        }
3379        { path => $path, mode_a => $mode, mode_b => $mode,
3380          pool => SVN::Pool->new, action => 'A' };
3381}
3382
3383sub add_directory {
3384        my ($self, $path, $cp_path, $cp_rev) = @_;
3385        goto out if in_dot_git($path);
3386        my $gpath = $self->git_path($path);
3387        if ($gpath eq '') {
3388                my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3389                                                     -r --name-only -z/,
3390                                                     $self->{c});
3391                local $/ = "\0";
3392                while (<$ls>) {
3393                        chomp;
3394                        $self->{gii}->remove($_);
3395                        print "\tD\t$_\n" unless $::_q;
3396                }
3397                command_close_pipe($ls, $ctx);
3398                $self->{empty}->{$path} = 0;
3399        }
3400        my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3401        delete $self->{empty}->{$dir};
3402        $self->{empty}->{$path} = 1;
3403out:
3404        { path => $path };
3405}
3406
3407sub change_dir_prop {
3408        my ($self, $db, $prop, $value) = @_;
3409        return undef if in_dot_git($db->{path});
3410        $self->{dir_prop}->{$db->{path}} ||= {};
3411        $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3412        undef;
3413}
3414
3415sub absent_directory {
3416        my ($self, $path, $pb) = @_;
3417        return undef if in_dot_git($pb->{path});
3418        $self->{absent_dir}->{$pb->{path}} ||= [];
3419        push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3420        undef;
3421}
3422
3423sub absent_file {
3424        my ($self, $path, $pb) = @_;
3425        return undef if in_dot_git($pb->{path});
3426        $self->{absent_file}->{$pb->{path}} ||= [];
3427        push @{$self->{absent_file}->{$pb->{path}}}, $path;
3428        undef;
3429}
3430
3431sub change_file_prop {
3432        my ($self, $fb, $prop, $value) = @_;
3433        return undef if in_dot_git($fb->{path});
3434        if ($prop eq 'svn:executable') {
3435                if ($fb->{mode_b} != 120000) {
3436                        $fb->{mode_b} = defined $value ? 100755 : 100644;
3437                }
3438        } elsif ($prop eq 'svn:special') {
3439                $fb->{mode_b} = defined $value ? 120000 : 100644;
3440        } else {
3441                $self->{file_prop}->{$fb->{path}} ||= {};
3442                $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3443        }
3444        undef;
3445}
3446
3447sub apply_textdelta {
3448        my ($self, $fb, $exp) = @_;
3449        return undef if (in_dot_git($fb->{path}));
3450        my $fh = $::_repository->temp_acquire('svn_delta');
3451        # $fh gets auto-closed() by SVN::TxDelta::apply(),
3452        # (but $base does not,) so dup() it for reading in close_file
3453        open my $dup, '<&', $fh or croak $!;
3454        my $base = $::_repository->temp_acquire('git_blob');
3455
3456        if ($fb->{blob}) {
3457                my ($base_is_link, $size);
3458
3459                if ($fb->{mode_a} eq '120000' &&
3460                    ! $self->{empty_symlinks}->{$fb->{path}}) {
3461                        print $base 'link ' or die "print $!\n";
3462                        $base_is_link = 1;
3463                }
3464        retry:
3465                $size = $::_repository->cat_blob($fb->{blob}, $base);
3466                die "Failed to read object $fb->{blob}" if ($size < 0);
3467
3468                if (defined $exp) {
3469                        seek $base, 0, 0 or croak $!;
3470                        my $got = ::md5sum($base);
3471                        if ($got ne $exp) {
3472                                my $err = "Checksum mismatch: ".
3473                                       "$fb->{path} $fb->{blob}\n" .
3474                                       "expected: $exp\n" .
3475                                       "     got: $got\n";
3476                                if ($base_is_link) {
3477                                        warn $err,
3478                                             "Retrying... (possibly ",
3479                                             "a bad symlink from SVN)\n";
3480                                        $::_repository->temp_reset($base);
3481                                        $base_is_link = 0;
3482                                        goto retry;
3483                                }
3484                                die $err;
3485                        }
3486                }
3487        }
3488        seek $base, 0, 0 or croak $!;
3489        $fb->{fh} = $fh;
3490        $fb->{base} = $base;
3491        [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3492}
3493
3494sub close_file {
3495        my ($self, $fb, $exp) = @_;
3496        return undef if (in_dot_git($fb->{path}));
3497
3498        my $hash;
3499        my $path = $self->git_path($fb->{path});
3500        if (my $fh = $fb->{fh}) {
3501                if (defined $exp) {
3502                        seek($fh, 0, 0) or croak $!;
3503                        my $got = ::md5sum($fh);
3504                        if ($got ne $exp) {
3505                                die "Checksum mismatch: $path\n",
3506                                    "expected: $exp\n    got: $got\n";
3507                        }
3508                }
3509                if ($fb->{mode_b} == 120000) {
3510                        sysseek($fh, 0, 0) or croak $!;
3511                        my $rd = sysread($fh, my $buf, 5);
3512
3513                        if (!defined $rd) {
3514                                croak "sysread: $!\n";
3515                        } elsif ($rd == 0) {
3516                                warn "$path has mode 120000",
3517                                     " but it points to nothing\n",
3518                                     "converting to an empty file with mode",
3519                                     " 100644\n";
3520                                $fb->{mode_b} = '100644';
3521                        } elsif ($buf ne 'link ') {
3522                                warn "$path has mode 120000",
3523                                     " but is not a link\n";
3524                        } else {
3525                                my $tmp_fh = $::_repository->temp_acquire(
3526                                        'svn_hash');
3527                                my $res;
3528                                while ($res = sysread($fh, my $str, 1024)) {
3529                                        my $out = syswrite($tmp_fh, $str, $res);
3530                                        defined($out) && $out == $res
3531                                                or croak("write ",
3532                                                        Git::temp_path($tmp_fh),
3533                                                        ": $!\n");
3534                                }
3535                                defined $res or croak $!;
3536
3537                                ($fh, $tmp_fh) = ($tmp_fh, $fh);
3538                                Git::temp_release($tmp_fh, 1);
3539                        }
3540                }
3541
3542                $hash = $::_repository->hash_and_insert_object(
3543                                Git::temp_path($fh));
3544                $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3545
3546                Git::temp_release($fb->{base}, 1);
3547                Git::temp_release($fh, 1);
3548        } else {
3549                $hash = $fb->{blob} or die "no blob information\n";
3550        }
3551        $fb->{pool}->clear;
3552        $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3553        print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3554        undef;
3555}
3556
3557sub abort_edit {
3558        my $self = shift;
3559        $self->{nr} = $self->{gii}->{nr};
3560        delete $self->{gii};
3561        $self->SUPER::abort_edit(@_);
3562}
3563
3564sub close_edit {
3565        my $self = shift;
3566        $self->{git_commit_ok} = 1;
3567        $self->{nr} = $self->{gii}->{nr};
3568        delete $self->{gii};
3569        $self->SUPER::close_edit(@_);
3570}
3571
3572package SVN::Git::Editor;
3573use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3574use strict;
3575use warnings;
3576use Carp qw/croak/;
3577use IO::File;
3578
3579sub new {
3580        my ($class, $opts) = @_;
3581        foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3582                die "$_ required!\n" unless (defined $opts->{$_});
3583        }
3584
3585        my $pool = SVN::Pool->new;
3586        my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3587        my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3588                                     $opts->{r}, $mods);
3589
3590        # $opts->{ra} functions should not be used after this:
3591        my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
3592                                                $opts->{editor_cb}, $pool);
3593        my $self = SVN::Delta::Editor->new(@ce, $pool);
3594        bless $self, $class;
3595        foreach (qw/svn_path r tree_a tree_b/) {
3596                $self->{$_} = $opts->{$_};
3597        }
3598        $self->{url} = $opts->{ra}->{url};
3599        $self->{mods} = $mods;
3600        $self->{types} = $types;
3601        $self->{pool} = $pool;
3602        $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3603        $self->{rm} = { };
3604        $self->{path_prefix} = length $self->{svn_path} ?
3605                               "$self->{svn_path}/" : '';
3606        $self->{config} = $opts->{config};
3607        return $self;
3608}
3609
3610sub generate_diff {
3611        my ($tree_a, $tree_b) = @_;
3612        my @diff_tree = qw(diff-tree -z -r);
3613        if ($_cp_similarity) {
3614                push @diff_tree, "-C$_cp_similarity";
3615        } else {
3616                push @diff_tree, '-C';
3617        }
3618        push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3619        push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3620        push @diff_tree, $tree_a, $tree_b;
3621        my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3622        local $/ = "\0";
3623        my $state = 'meta';
3624        my @mods;
3625        while (<$diff_fh>) {
3626                chomp $_; # this gets rid of the trailing "\0"
3627                if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3628                                        ($::sha1)\s($::sha1)\s
3629                                        ([MTCRAD])\d*$/xo) {
3630                        push @mods, {   mode_a => $1, mode_b => $2,
3631                                        sha1_a => $3, sha1_b => $4,
3632                                        chg => $5 };
3633                        if ($5 =~ /^(?:C|R)$/) {
3634                                $state = 'file_a';
3635                        } else {
3636                                $state = 'file_b';
3637                        }
3638                } elsif ($state eq 'file_a') {
3639                        my $x = $mods[$#mods] or croak "Empty array\n";
3640                        if ($x->{chg} !~ /^(?:C|R)$/) {
3641                                croak "Error parsing $_, $x->{chg}\n";
3642                        }
3643                        $x->{file_a} = $_;
3644                        $state = 'file_b';
3645                } elsif ($state eq 'file_b') {
3646                        my $x = $mods[$#mods] or croak "Empty array\n";
3647                        if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3648                                croak "Error parsing $_, $x->{chg}\n";
3649                        }
3650                        if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3651                                croak "Error parsing $_, $x->{chg}\n";
3652                        }
3653                        $x->{file_b} = $_;
3654                        $state = 'meta';
3655                } else {
3656                        croak "Error parsing $_\n";
3657                }
3658        }
3659        command_close_pipe($diff_fh, $ctx);
3660        \@mods;
3661}
3662
3663sub check_diff_paths {
3664        my ($ra, $pfx, $rev, $mods) = @_;
3665        my %types;
3666        $pfx .= '/' if length $pfx;
3667
3668        sub type_diff_paths {
3669                my ($ra, $types, $path, $rev) = @_;
3670                my @p = split m#/+#, $path;
3671                my $c = shift @p;
3672                unless (defined $types->{$c}) {
3673                        $types->{$c} = $ra->check_path($c, $rev);
3674                }
3675                while (@p) {
3676                        $c .= '/' . shift @p;
3677                        next if defined $types->{$c};
3678                        $types->{$c} = $ra->check_path($c, $rev);
3679                }
3680        }
3681
3682        foreach my $m (@$mods) {
3683                foreach my $f (qw/file_a file_b/) {
3684                        next unless defined $m->{$f};
3685                        my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3686                        if (length $pfx.$dir && ! defined $types{$dir}) {
3687                                type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3688                        }
3689                }
3690        }
3691        \%types;
3692}
3693
3694sub split_path {
3695        return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3696}
3697
3698sub repo_path {
3699        my ($self, $path) = @_;
3700        $self->{path_prefix}.(defined $path ? $path : '');
3701}
3702
3703sub url_path {
3704        my ($self, $path) = @_;
3705        if ($self->{url} =~ m#^https?://#) {
3706                $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3707        }
3708        $self->{url} . '/' . $self->repo_path($path);
3709}
3710
3711sub rmdirs {
3712        my ($self) = @_;
3713        my $rm = $self->{rm};
3714        delete $rm->{''}; # we never delete the url we're tracking
3715        return unless %$rm;
3716
3717        foreach (keys %$rm) {
3718                my @d = split m#/#, $_;
3719                my $c = shift @d;
3720                $rm->{$c} = 1;
3721                while (@d) {
3722                        $c .= '/' . shift @d;
3723                        $rm->{$c} = 1;
3724                }
3725        }
3726        delete $rm->{$self->{svn_path}};
3727        delete $rm->{''}; # we never delete the url we're tracking
3728        return unless %$rm;
3729
3730        my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3731                                             $self->{tree_b});
3732        local $/ = "\0";
3733        while (<$fh>) {
3734                chomp;
3735                my @dn = split m#/#, $_;
3736                while (pop @dn) {
3737                        delete $rm->{join '/', @dn};
3738                }
3739                unless (%$rm) {
3740                        close $fh;
3741                        return;
3742                }
3743        }
3744        command_close_pipe($fh, $ctx);
3745
3746        my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3747        foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3748                $self->close_directory($bat->{$d}, $p);
3749                my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3750                print "\tD+\t$d/\n" unless $::_q;
3751                $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3752                delete $bat->{$d};
3753        }
3754}
3755
3756sub open_or_add_dir {
3757        my ($self, $full_path, $baton) = @_;
3758        my $t = $self->{types}->{$full_path};
3759        if (!defined $t) {
3760                die "$full_path not known in r$self->{r} or we have a bug!\n";
3761        }
3762        {
3763                no warnings 'once';
3764                # SVN::Node::none and SVN::Node::file are used only once,
3765                # so we're shutting up Perl's warnings about them.
3766                if ($t == $SVN::Node::none) {
3767                        return $self->add_directory($full_path, $baton,
3768                            undef, -1, $self->{pool});
3769                } elsif ($t == $SVN::Node::dir) {
3770                        return $self->open_directory($full_path, $baton,
3771                            $self->{r}, $self->{pool});
3772                } # no warnings 'once'
3773                print STDERR "$full_path already exists in repository at ",
3774                    "r$self->{r} and it is not a directory (",
3775                    ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3776        } # no warnings 'once'
3777        exit 1;
3778}
3779
3780sub ensure_path {
3781        my ($self, $path) = @_;
3782        my $bat = $self->{bat};
3783        my $repo_path = $self->repo_path($path);
3784        return $bat->{''} unless (length $repo_path);
3785        my @p = split m#/+#, $repo_path;
3786        my $c = shift @p;
3787        $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3788        while (@p) {
3789                my $c0 = $c;
3790                $c .= '/' . shift @p;
3791                $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3792        }
3793        return $bat->{$c};
3794}
3795
3796# Subroutine to convert a globbing pattern to a regular expression.
3797# From perl cookbook.
3798sub glob2pat {
3799        my $globstr = shift;
3800        my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3801        $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3802        return '^' . $globstr . '$';
3803}
3804
3805sub check_autoprop {
3806        my ($self, $pattern, $properties, $file, $fbat) = @_;
3807        # Convert the globbing pattern to a regular expression.
3808        my $regex = glob2pat($pattern);
3809        # Check if the pattern matches the file name.
3810        if($file =~ m/($regex)/) {
3811                # Parse the list of properties to set.
3812                my @props = split(/;/, $properties);
3813                foreach my $prop (@props) {
3814                        # Parse 'name=value' syntax and set the property.
3815                        if ($prop =~ /([^=]+)=(.*)/) {
3816                                my ($n,$v) = ($1,$2);
3817                                for ($n, $v) {
3818                                        s/^\s+//; s/\s+$//;
3819                                }
3820                                $self->change_file_prop($fbat, $n, $v);
3821                        }
3822                }
3823        }
3824}
3825
3826sub apply_autoprops {
3827        my ($self, $file, $fbat) = @_;
3828        my $conf_t = ${$self->{config}}{'config'};
3829        no warnings 'once';
3830        # Check [miscellany]/enable-auto-props in svn configuration.
3831        if (SVN::_Core::svn_config_get_bool(
3832                $conf_t,
3833                $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3834                $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3835                0)) {
3836                # Auto-props are enabled.  Enumerate them to look for matches.
3837                my $callback = sub {
3838                        $self->check_autoprop($_[0], $_[1], $file, $fbat);
3839                };
3840                SVN::_Core::svn_config_enumerate(
3841                        $conf_t,
3842                        $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3843                        $callback);
3844        }
3845}
3846
3847sub A {
3848        my ($self, $m) = @_;
3849        my ($dir, $file) = split_path($m->{file_b});
3850        my $pbat = $self->ensure_path($dir);
3851        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3852                                        undef, -1);
3853        print "\tA\t$m->{file_b}\n" unless $::_q;
3854        $self->apply_autoprops($file, $fbat);
3855        $self->chg_file($fbat, $m);
3856        $self->close_file($fbat,undef,$self->{pool});
3857}
3858
3859sub C {
3860        my ($self, $m) = @_;
3861        my ($dir, $file) = split_path($m->{file_b});
3862        my $pbat = $self->ensure_path($dir);
3863        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3864                                $self->url_path($m->{file_a}), $self->{r});
3865        print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3866        $self->chg_file($fbat, $m);
3867        $self->close_file($fbat,undef,$self->{pool});
3868}
3869
3870sub delete_entry {
3871        my ($self, $path, $pbat) = @_;
3872        my $rpath = $self->repo_path($path);
3873        my ($dir, $file) = split_path($rpath);
3874        $self->{rm}->{$dir} = 1;
3875        $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3876}
3877
3878sub R {
3879        my ($self, $m) = @_;
3880        my ($dir, $file) = split_path($m->{file_b});
3881        my $pbat = $self->ensure_path($dir);
3882        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3883                                $self->url_path($m->{file_a}), $self->{r});
3884        print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3885        $self->apply_autoprops($file, $fbat);
3886        $self->chg_file($fbat, $m);
3887        $self->close_file($fbat,undef,$self->{pool});
3888
3889        ($dir, $file) = split_path($m->{file_a});
3890        $pbat = $self->ensure_path($dir);
3891        $self->delete_entry($m->{file_a}, $pbat);
3892}
3893
3894sub M {
3895        my ($self, $m) = @_;
3896        my ($dir, $file) = split_path($m->{file_b});
3897        my $pbat = $self->ensure_path($dir);
3898        my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3899                                $pbat,$self->{r},$self->{pool});
3900        print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3901        $self->chg_file($fbat, $m);
3902        $self->close_file($fbat,undef,$self->{pool});
3903}
3904
3905sub T { shift->M(@_) }
3906
3907sub change_file_prop {
3908        my ($self, $fbat, $pname, $pval) = @_;
3909        $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3910}
3911
3912sub _chg_file_get_blob ($$$$) {
3913        my ($self, $fbat, $m, $which) = @_;
3914        my $fh = $::_repository->temp_acquire("git_blob_$which");
3915        if ($m->{"mode_$which"} =~ /^120/) {
3916                print $fh 'link ' or croak $!;
3917                $self->change_file_prop($fbat,'svn:special','*');
3918        } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
3919                $self->change_file_prop($fbat,'svn:special',undef);
3920        }
3921        my $blob = $m->{"sha1_$which"};
3922        return ($fh,) if ($blob =~ /^0{40}$/);
3923        my $size = $::_repository->cat_blob($blob, $fh);
3924        croak "Failed to read object $blob" if ($size < 0);
3925        $fh->flush == 0 or croak $!;
3926        seek $fh, 0, 0 or croak $!;
3927
3928        my $exp = ::md5sum($fh);
3929        seek $fh, 0, 0 or croak $!;
3930        return ($fh, $exp);
3931}
3932
3933sub chg_file {
3934        my ($self, $fbat, $m) = @_;
3935        if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3936                $self->change_file_prop($fbat,'svn:executable','*');
3937        } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3938                $self->change_file_prop($fbat,'svn:executable',undef);
3939        }
3940        my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
3941        my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
3942        my $pool = SVN::Pool->new;
3943        my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
3944        if (-s $fh_a) {
3945                my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
3946                my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
3947                if (defined $res) {
3948                        die "Unexpected result from send_txstream: $res\n",
3949                            "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
3950                }
3951        } else {
3952                my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
3953                die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
3954                    if ($got ne $exp_b);
3955        }
3956        Git::temp_release($fh_b, 1);
3957        Git::temp_release($fh_a, 1);
3958        $pool->clear;
3959}
3960
3961sub D {
3962        my ($self, $m) = @_;
3963        my ($dir, $file) = split_path($m->{file_b});
3964        my $pbat = $self->ensure_path($dir);
3965        print "\tD\t$m->{file_b}\n" unless $::_q;
3966        $self->delete_entry($m->{file_b}, $pbat);
3967}
3968
3969sub close_edit {
3970        my ($self) = @_;
3971        my ($p,$bat) = ($self->{pool}, $self->{bat});
3972        foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3973                next if $_ eq '';
3974                $self->close_directory($bat->{$_}, $p);
3975        }
3976        $self->close_directory($bat->{''}, $p);
3977        $self->SUPER::close_edit($p);
3978        $p->clear;
3979}
3980
3981sub abort_edit {
3982        my ($self) = @_;
3983        $self->SUPER::abort_edit($self->{pool});
3984}
3985
3986sub DESTROY {
3987        my $self = shift;
3988        $self->SUPER::DESTROY(@_);
3989        $self->{pool}->clear;
3990}
3991
3992# this drives the editor
3993sub apply_diff {
3994        my ($self) = @_;
3995        my $mods = $self->{mods};
3996        my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3997        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3998                my $f = $m->{chg};
3999                if (defined $o{$f}) {
4000                        $self->$f($m);
4001                } else {
4002                        fatal("Invalid change type: $f");
4003                }
4004        }
4005        $self->rmdirs if $_rmdir;
4006        if (@$mods == 0) {
4007                $self->abort_edit;
4008        } else {
4009                $self->close_edit;
4010        }
4011        return scalar @$mods;
4012}
4013
4014package Git::SVN::Ra;
4015use vars qw/@ISA $config_dir $_log_window_size/;
4016use strict;
4017use warnings;
4018my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4019
4020BEGIN {
4021        # enforce temporary pool usage for some simple functions
4022        no strict 'refs';
4023        for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
4024                my $SUPER = "SUPER::$f";
4025                *$f = sub {
4026                        my $self = shift;
4027                        my $pool = SVN::Pool->new;
4028                        my @ret = $self->$SUPER(@_,$pool);
4029                        $pool->clear;
4030                        wantarray ? @ret : $ret[0];
4031                };
4032        }
4033}
4034
4035sub _auth_providers () {
4036        [
4037          SVN::Client::get_simple_provider(),
4038          SVN::Client::get_ssl_server_trust_file_provider(),
4039          SVN::Client::get_simple_prompt_provider(
4040            \&Git::SVN::Prompt::simple, 2),
4041          SVN::Client::get_ssl_client_cert_file_provider(),
4042          SVN::Client::get_ssl_client_cert_prompt_provider(
4043            \&Git::SVN::Prompt::ssl_client_cert, 2),
4044          SVN::Client::get_ssl_client_cert_pw_file_provider(),
4045          SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4046            \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4047          SVN::Client::get_username_provider(),
4048          SVN::Client::get_ssl_server_trust_prompt_provider(
4049            \&Git::SVN::Prompt::ssl_server_trust),
4050          SVN::Client::get_username_prompt_provider(
4051            \&Git::SVN::Prompt::username, 2)
4052        ]
4053}
4054
4055sub escape_uri_only {
4056        my ($uri) = @_;
4057        my @tmp;
4058        foreach (split m{/}, $uri) {
4059                s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4060                push @tmp, $_;
4061        }
4062        join('/', @tmp);
4063}
4064
4065sub escape_url {
4066        my ($url) = @_;
4067        if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4068                my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4069                $url = "$scheme://$domain$uri";
4070        }
4071        $url;
4072}
4073
4074sub new {
4075        my ($class, $url) = @_;
4076        $url =~ s!/+$!!;
4077        return $RA if ($RA && $RA->{url} eq $url);
4078
4079        SVN::_Core::svn_config_ensure($config_dir, undef);
4080        my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4081        my $config = SVN::Core::config_get_config($config_dir);
4082        $RA = undef;
4083        my $dont_store_passwords = 1;
4084        my $conf_t = ${$config}{'config'};
4085        {
4086                no warnings 'once';
4087                # The usage of $SVN::_Core::SVN_CONFIG_* variables
4088                # produces warnings that variables are used only once.
4089                # I had not found the better way to shut them up, so
4090                # the warnings of type 'once' are disabled in this block.
4091                if (SVN::_Core::svn_config_get_bool($conf_t,
4092                    $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4093                    $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4094                    1) == 0) {
4095                        SVN::_Core::svn_auth_set_parameter($baton,
4096                            $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4097                            bless (\$dont_store_passwords, "_p_void"));
4098                }
4099                if (SVN::_Core::svn_config_get_bool($conf_t,
4100                    $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4101                    $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4102                    1) == 0) {
4103                        $Git::SVN::Prompt::_no_auth_cache = 1;
4104                }
4105        } # no warnings 'once'
4106        my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4107                              config => $config,
4108                              pool => SVN::Pool->new,
4109                              auth_provider_callbacks => $callbacks);
4110        $self->{url} = $url;
4111        $self->{svn_path} = $url;
4112        $self->{repos_root} = $self->get_repos_root;
4113        $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4114        $self->{cache} = { check_path => { r => 0, data => {} },
4115                           get_dir => { r => 0, data => {} } };
4116        $RA = bless $self, $class;
4117}
4118
4119sub check_path {
4120        my ($self, $path, $r) = @_;
4121        my $cache = $self->{cache}->{check_path};
4122        if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4123                return $cache->{data}->{$path};
4124        }
4125        my $pool = SVN::Pool->new;
4126        my $t = $self->SUPER::check_path($path, $r, $pool);
4127        $pool->clear;
4128        if ($r != $cache->{r}) {
4129                %{$cache->{data}} = ();
4130                $cache->{r} = $r;
4131        }
4132        $cache->{data}->{$path} = $t;
4133}
4134
4135sub get_dir {
4136        my ($self, $dir, $r) = @_;
4137        my $cache = $self->{cache}->{get_dir};
4138        if ($r == $cache->{r}) {
4139                if (my $x = $cache->{data}->{$dir}) {
4140                        return wantarray ? @$x : $x->[0];
4141                }
4142        }
4143        my $pool = SVN::Pool->new;
4144        my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4145        my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4146        $pool->clear;
4147        if ($r != $cache->{r}) {
4148                %{$cache->{data}} = ();
4149                $cache->{r} = $r;
4150        }
4151        $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4152        wantarray ? (\%dirents, $r, $props) : \%dirents;
4153}
4154
4155sub DESTROY {
4156        # do not call the real DESTROY since we store ourselves in $RA
4157}
4158
4159# get_log(paths, start, end, limit,
4160#         discover_changed_paths, strict_node_history, receiver)
4161sub get_log {
4162        my ($self, @args) = @_;
4163        my $pool = SVN::Pool->new;
4164
4165        # the limit parameter was not supported in SVN 1.1.x, so we
4166        # drop it.  Therefore, the receiver callback passed to it
4167        # is made aware of this limitation by being wrapped if
4168        # the limit passed to is being wrapped.
4169        if ($SVN::Core::VERSION le '1.2.0') {
4170                my $limit = splice(@args, 3, 1);
4171                if ($limit > 0) {
4172                        my $receiver = pop @args;
4173                        push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4174                }
4175        }
4176        my $ret = $self->SUPER::get_log(@args, $pool);
4177        $pool->clear;
4178        $ret;
4179}
4180
4181sub trees_match {
4182        my ($self, $url1, $rev1, $url2, $rev2) = @_;
4183        my $ctx = SVN::Client->new(auth => _auth_providers);
4184        my $out = IO::File->new_tmpfile;
4185
4186        # older SVN (1.1.x) doesn't take $pool as the last parameter for
4187        # $ctx->diff(), so we'll create a default one
4188        my $pool = SVN::Pool->new_default_sub;
4189
4190        $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4191        $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4192        $out->flush;
4193        my $ret = (($out->stat)[7] == 0);
4194        close $out or croak $!;
4195
4196        $ret;
4197}
4198
4199sub get_commit_editor {
4200        my ($self, $log, $cb, $pool) = @_;
4201        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4202        $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4203}
4204
4205sub gs_do_update {
4206        my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4207        my $new = ($rev_a == $rev_b);
4208        my $path = $gs->{path};
4209
4210        if ($new && -e $gs->{index}) {
4211                unlink $gs->{index} or die
4212                  "Couldn't unlink index: $gs->{index}: $!\n";
4213        }
4214        my $pool = SVN::Pool->new;
4215        $editor->set_path_strip($path);
4216        my (@pc) = split m#/#, $path;
4217        my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4218                                        1, $editor, $pool);
4219        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4220
4221        # Since we can't rely on svn_ra_reparent being available, we'll
4222        # just have to do some magic with set_path to make it so
4223        # we only want a partial path.
4224        my $sp = '';
4225        my $final = join('/', @pc);
4226        while (@pc) {
4227                $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4228                $sp .= '/' if length $sp;
4229                $sp .= shift @pc;
4230        }
4231        die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4232
4233        $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4234
4235        $reporter->finish_report($pool);
4236        $pool->clear;
4237        $editor->{git_commit_ok};
4238}
4239
4240# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4241# svn_ra_reparent didn't work before 1.4)
4242sub gs_do_switch {
4243        my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4244        my $path = $gs->{path};
4245        my $pool = SVN::Pool->new;
4246
4247        my $full_url = $self->{url};
4248        my $old_url = $full_url;
4249        $full_url .= '/' . escape_uri_only($path) if length $path;
4250        my ($ra, $reparented);
4251
4252        if ($old_url =~ m#^svn(\+ssh)?://#) {
4253                $_[0] = undef;
4254                $self = undef;
4255                $RA = undef;
4256                $ra = Git::SVN::Ra->new($full_url);
4257                $ra_invalid = 1;
4258        } elsif ($old_url ne $full_url) {
4259                SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4260                $self->{url} = $full_url;
4261                $reparented = 1;
4262        }
4263
4264        $ra ||= $self;
4265        $url_b = escape_url($url_b);
4266        my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4267        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4268        $reporter->set_path('', $rev_a, 0, @lock, $pool);
4269        $reporter->finish_report($pool);
4270
4271        if ($reparented) {
4272                SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4273                $self->{url} = $old_url;
4274        }
4275
4276        $pool->clear;
4277        $editor->{git_commit_ok};
4278}
4279
4280sub longest_common_path {
4281        my ($gsv, $globs) = @_;
4282        my %common;
4283        my $common_max = scalar @$gsv;
4284
4285        foreach my $gs (@$gsv) {
4286                my @tmp = split m#/#, $gs->{path};
4287                my $p = '';
4288                foreach (@tmp) {
4289                        $p .= length($p) ? "/$_" : $_;
4290                        $common{$p} ||= 0;
4291                        $common{$p}++;
4292                }
4293        }
4294        $globs ||= [];
4295        $common_max += scalar @$globs;
4296        foreach my $glob (@$globs) {
4297                my @tmp = split m#/#, $glob->{path}->{left};
4298                my $p = '';
4299                foreach (@tmp) {
4300                        $p .= length($p) ? "/$_" : $_;
4301                        $common{$p} ||= 0;
4302                        $common{$p}++;
4303                }
4304        }
4305
4306        my $longest_path = '';
4307        foreach (sort {length $b <=> length $a} keys %common) {
4308                if ($common{$_} == $common_max) {
4309                        $longest_path = $_;
4310                        last;
4311                }
4312        }
4313        $longest_path;
4314}
4315
4316sub gs_fetch_loop_common {
4317        my ($self, $base, $head, $gsv, $globs) = @_;
4318        return if ($base > $head);
4319        my $inc = $_log_window_size;
4320        my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4321        my $longest_path = longest_common_path($gsv, $globs);
4322        my $ra_url = $self->{url};
4323        while (1) {
4324                my %revs;
4325                my $err;
4326                my $err_handler = $SVN::Error::handler;
4327                $SVN::Error::handler = sub {
4328                        ($err) = @_;
4329                        skip_unknown_revs($err);
4330                };
4331                sub _cb {
4332                        my ($paths, $r, $author, $date, $log) = @_;
4333                        [ dup_changed_paths($paths),
4334                          { author => $author, date => $date, log => $log } ];
4335                }
4336                $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4337                               sub { $revs{$_[1]} = _cb(@_) });
4338                if ($err && $max >= $head) {
4339                        print STDERR "Path '$longest_path' ",
4340                                     "was probably deleted:\n",
4341                                     $err->expanded_message,
4342                                     "\nWill attempt to follow ",
4343                                     "revisions r$min .. r$max ",
4344                                     "committed before the deletion\n";
4345                        my $hi = $max;
4346                        while (--$hi >= $min) {
4347                                my $ok;
4348                                $self->get_log([$longest_path], $min, $hi,
4349                                               0, 1, 1, sub {
4350                                               $ok ||= $_[1];
4351                                               $revs{$_[1]} = _cb(@_) });
4352                                if ($ok) {
4353                                        print STDERR "r$min .. r$ok OK\n";
4354                                        last;
4355                                }
4356                        }
4357                }
4358                $SVN::Error::handler = $err_handler;
4359
4360                my %exists = map { $_->{path} => $_ } @$gsv;
4361                foreach my $r (sort {$a <=> $b} keys %revs) {
4362                        my ($paths, $logged) = @{$revs{$r}};
4363
4364                        foreach my $gs ($self->match_globs(\%exists, $paths,
4365                                                           $globs, $r)) {
4366                                if ($gs->rev_map_max >= $r) {
4367                                        next;
4368                                }
4369                                next unless $gs->match_paths($paths, $r);
4370                                $gs->{logged_rev_props} = $logged;
4371                                if (my $last_commit = $gs->last_commit) {
4372                                        $gs->assert_index_clean($last_commit);
4373                                }
4374                                my $log_entry = $gs->do_fetch($paths, $r);
4375                                if ($log_entry) {
4376                                        $gs->do_git_commit($log_entry);
4377                                }
4378                                $INDEX_FILES{$gs->{index}} = 1;
4379                        }
4380                        foreach my $g (@$globs) {
4381                                my $k = "svn-remote.$g->{remote}." .
4382                                        "$g->{t}-maxRev";
4383                                Git::SVN::tmp_config($k, $r);
4384                        }
4385                        if ($ra_invalid) {
4386                                $_[0] = undef;
4387                                $self = undef;
4388                                $RA = undef;
4389                                $self = Git::SVN::Ra->new($ra_url);
4390                                $ra_invalid = undef;
4391                        }
4392                }
4393                # pre-fill the .rev_db since it'll eventually get filled in
4394                # with '0' x40 if something new gets committed
4395                foreach my $gs (@$gsv) {
4396                        next if $gs->rev_map_max >= $max;
4397                        next if defined $gs->rev_map_get($max);
4398                        $gs->rev_map_set($max, 0 x40);
4399                }
4400                foreach my $g (@$globs) {
4401                        my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4402                        Git::SVN::tmp_config($k, $max);
4403                }
4404                last if $max >= $head;
4405                $min = $max + 1;
4406                $max += $inc;
4407                $max = $head if ($max > $head);
4408        }
4409        Git::SVN::gc();
4410}
4411
4412sub get_dir_globbed {
4413        my ($self, $left, $depth, $r) = @_;
4414
4415        my @x = eval { $self->get_dir($left, $r) };
4416        return unless scalar @x == 3;
4417        my $dirents = $x[0];
4418        my @finalents;
4419        foreach my $de (keys %$dirents) {
4420                next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4421                if ($depth > 1) {
4422                        my @args = ("$left/$de", $depth - 1, $r);
4423                        foreach my $dir ($self->get_dir_globbed(@args)) {
4424                                push @finalents, "$de/$dir";
4425                        }
4426                } else {
4427                        push @finalents, $de;
4428                }
4429        }
4430        @finalents;
4431}
4432
4433sub match_globs {
4434        my ($self, $exists, $paths, $globs, $r) = @_;
4435
4436        sub get_dir_check {
4437                my ($self, $exists, $g, $r) = @_;
4438
4439                my @dirs = $self->get_dir_globbed($g->{path}->{left},
4440                                                  $g->{path}->{depth},
4441                                                  $r);
4442
4443                foreach my $de (@dirs) {
4444                        my $p = $g->{path}->full_path($de);
4445                        next if $exists->{$p};
4446                        next if (length $g->{path}->{right} &&
4447                                 ($self->check_path($p, $r) !=
4448                                  $SVN::Node::dir));
4449                        $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4450                                         $g->{ref}->full_path($de), 1);
4451                }
4452        }
4453        foreach my $g (@$globs) {
4454                if (my $path = $paths->{"/$g->{path}->{left}"}) {
4455                        if ($path->{action} =~ /^[AR]$/) {
4456                                get_dir_check($self, $exists, $g, $r);
4457                        }
4458                }
4459                foreach (keys %$paths) {
4460                        if (/$g->{path}->{left_regex}/ &&
4461                            !/$g->{path}->{regex}/) {
4462                                next if $paths->{$_}->{action} !~ /^[AR]$/;
4463                                get_dir_check($self, $exists, $g, $r);
4464                        }
4465                        next unless /$g->{path}->{regex}/;
4466                        my $p = $1;
4467                        my $pathname = $g->{path}->full_path($p);
4468                        next if $exists->{$pathname};
4469                        next if ($self->check_path($pathname, $r) !=
4470                                 $SVN::Node::dir);
4471                        $exists->{$pathname} = Git::SVN->init(
4472                                              $self->{url}, $pathname, undef,
4473                                              $g->{ref}->full_path($p), 1);
4474                }
4475                my $c = '';
4476                foreach (split m#/#, $g->{path}->{left}) {
4477                        $c .= "/$_";
4478                        next unless ($paths->{$c} &&
4479                                     ($paths->{$c}->{action} =~ /^[AR]$/));
4480                        get_dir_check($self, $exists, $g, $r);
4481                }
4482        }
4483        values %$exists;
4484}
4485
4486sub minimize_url {
4487        my ($self) = @_;
4488        return $self->{url} if ($self->{url} eq $self->{repos_root});
4489        my $url = $self->{repos_root};
4490        my @components = split(m!/!, $self->{svn_path});
4491        my $c = '';
4492        do {
4493                $url .= "/$c" if length $c;
4494                eval { (ref $self)->new($url)->get_latest_revnum };
4495        } while ($@ && ($c = shift @components));
4496        $url;
4497}
4498
4499sub can_do_switch {
4500        my $self = shift;
4501        unless (defined $can_do_switch) {
4502                my $pool = SVN::Pool->new;
4503                my $rep = eval {
4504                        $self->do_switch(1, '', 0, $self->{url},
4505                                         SVN::Delta::Editor->new, $pool);
4506                };
4507                if ($@) {
4508                        $can_do_switch = 0;
4509                } else {
4510                        $rep->abort_report($pool);
4511                        $can_do_switch = 1;
4512                }
4513                $pool->clear;
4514        }
4515        $can_do_switch;
4516}
4517
4518sub skip_unknown_revs {
4519        my ($err) = @_;
4520        my $errno = $err->apr_err();
4521        # Maybe the branch we're tracking didn't
4522        # exist when the repo started, so it's
4523        # not an error if it doesn't, just continue
4524        #
4525        # Wonderfully consistent library, eh?
4526        # 160013 - svn:// and file://
4527        # 175002 - http(s)://
4528        # 175007 - http(s):// (this repo required authorization, too...)
4529        #   More codes may be discovered later...
4530        if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4531                my $err_key = $err->expanded_message;
4532                # revision numbers change every time, filter them out
4533                $err_key =~ s/\d+/\0/g;
4534                $err_key = "$errno\0$err_key";
4535                unless ($ignored_err{$err_key}) {
4536                        warn "W: Ignoring error from SVN, path probably ",
4537                             "does not exist: ($errno): ",
4538                             $err->expanded_message,"\n";
4539                        warn "W: Do not be alarmed at the above message ",
4540                             "git-svn is just searching aggressively for ",
4541                             "old history.\n",
4542                             "This may take a while on large repositories\n";
4543                        $ignored_err{$err_key} = 1;
4544                }
4545                return;
4546        }
4547        die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4548}
4549
4550# svn_log_changed_path_t objects passed to get_log are likely to be
4551# overwritten even if only the refs are copied to an external variable,
4552# so we should dup the structures in their entirety.  Using an externally
4553# passed pool (instead of our temporary and quickly cleared pool in
4554# Git::SVN::Ra) does not help matters at all...
4555sub dup_changed_paths {
4556        my ($paths) = @_;
4557        return undef unless $paths;
4558        my %ret;
4559        foreach my $p (keys %$paths) {
4560                my $i = $paths->{$p};
4561                my %s = map { $_ => $i->$_ }
4562                              qw/copyfrom_path copyfrom_rev action/;
4563                $ret{$p} = \%s;
4564        }
4565        \%ret;
4566}
4567
4568package Git::SVN::Log;
4569use strict;
4570use warnings;
4571use POSIX qw/strftime/;
4572use constant commit_log_separator => ('-' x 72) . "\n";
4573use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4574            %rusers $show_commit $incremental/;
4575my $l_fmt;
4576
4577sub cmt_showable {
4578        my ($c) = @_;
4579        return 1 if defined $c->{r};
4580
4581        # big commit message got truncated by the 16k pretty buffer in rev-list
4582        if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4583                                $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4584                @{$c->{l}} = ();
4585                my @log = command(qw/cat-file commit/, $c->{c});
4586
4587                # shift off the headers
4588                shift @log while ($log[0] ne '');
4589                shift @log;
4590
4591                # TODO: make $c->{l} not have a trailing newline in the future
4592                @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4593
4594                (undef, $c->{r}, undef) = ::extract_metadata(
4595                                (grep(/^git-svn-id: /, @log))[-1]);
4596        }
4597        return defined $c->{r};
4598}
4599
4600sub log_use_color {
4601        return $color || Git->repository->get_colorbool('color.diff');
4602}
4603
4604sub git_svn_log_cmd {
4605        my ($r_min, $r_max, @args) = @_;
4606        my $head = 'HEAD';
4607        my (@files, @log_opts);
4608        foreach my $x (@args) {
4609                if ($x eq '--' || @files) {
4610                        push @files, $x;
4611                } else {
4612                        if (::verify_ref("$x^0")) {
4613                                $head = $x;
4614                        } else {
4615                                push @log_opts, $x;
4616                        }
4617                }
4618        }
4619
4620        my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4621        $gs ||= Git::SVN->_new;
4622        my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4623                   $gs->refname);
4624        push @cmd, '-r' unless $non_recursive;
4625        push @cmd, qw/--raw --name-status/ if $verbose;
4626        push @cmd, '--color' if log_use_color();
4627        push @cmd, @log_opts;
4628        if (defined $r_max && $r_max == $r_min) {
4629                push @cmd, '--max-count=1';
4630                if (my $c = $gs->rev_map_get($r_max)) {
4631                        push @cmd, $c;
4632                }
4633        } elsif (defined $r_max) {
4634                if ($r_max < $r_min) {
4635                        ($r_min, $r_max) = ($r_max, $r_min);
4636                }
4637                my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4638                my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4639                # If there are no commits in the range, both $c_max and $c_min
4640                # will be undefined.  If there is at least 1 commit in the
4641                # range, both will be defined.
4642                return () if !defined $c_min || !defined $c_max;
4643                if ($c_min eq $c_max) {
4644                        push @cmd, '--max-count=1', $c_min;
4645                } else {
4646                        push @cmd, '--boundary', "$c_min..$c_max";
4647                }
4648        }
4649        return (@cmd, @files);
4650}
4651
4652# adapted from pager.c
4653sub config_pager {
4654        $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4655        if (!defined $pager) {
4656                $pager = 'less';
4657        } elsif (length $pager == 0 || $pager eq 'cat') {
4658                $pager = undef;
4659        }
4660        $ENV{GIT_PAGER_IN_USE} = defined($pager);
4661}
4662
4663sub run_pager {
4664        return unless -t *STDOUT && defined $pager;
4665        pipe my ($rfd, $wfd) or return;
4666        defined(my $pid = fork) or ::fatal "Can't fork: $!";
4667        if (!$pid) {
4668                open STDOUT, '>&', $wfd or
4669                                     ::fatal "Can't redirect to stdout: $!";
4670                return;
4671        }
4672        open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4673        $ENV{LESS} ||= 'FRSX';
4674        exec $pager or ::fatal "Can't run pager: $! ($pager)";
4675}
4676
4677sub format_svn_date {
4678        return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4679}
4680
4681sub parse_git_date {
4682        my ($t, $tz) = @_;
4683        # Date::Parse isn't in the standard Perl distro :(
4684        if ($tz =~ s/^\+//) {
4685                $t += tz_to_s_offset($tz);
4686        } elsif ($tz =~ s/^\-//) {
4687                $t -= tz_to_s_offset($tz);
4688        }
4689        return $t;
4690}
4691
4692sub set_local_timezone {
4693        if (defined $TZ) {
4694                $ENV{TZ} = $TZ;
4695        } else {
4696                delete $ENV{TZ};
4697        }
4698}
4699
4700sub tz_to_s_offset {
4701        my ($tz) = @_;
4702        $tz =~ s/(\d\d)$//;
4703        return ($1 * 60) + ($tz * 3600);
4704}
4705
4706sub get_author_info {
4707        my ($dest, $author, $t, $tz) = @_;
4708        $author =~ s/(?:^\s*|\s*$)//g;
4709        $dest->{a_raw} = $author;
4710        my $au;
4711        if ($::_authors) {
4712                $au = $rusers{$author} || undef;
4713        }
4714        if (!$au) {
4715                ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4716        }
4717        $dest->{t} = $t;
4718        $dest->{tz} = $tz;
4719        $dest->{a} = $au;
4720        $dest->{t_utc} = parse_git_date($t, $tz);
4721}
4722
4723sub process_commit {
4724        my ($c, $r_min, $r_max, $defer) = @_;
4725        if (defined $r_min && defined $r_max) {
4726                if ($r_min == $c->{r} && $r_min == $r_max) {
4727                        show_commit($c);
4728                        return 0;
4729                }
4730                return 1 if $r_min == $r_max;
4731                if ($r_min < $r_max) {
4732                        # we need to reverse the print order
4733                        return 0 if (defined $limit && --$limit < 0);
4734                        push @$defer, $c;
4735                        return 1;
4736                }
4737                if ($r_min != $r_max) {
4738                        return 1 if ($r_min < $c->{r});
4739                        return 1 if ($r_max > $c->{r});
4740                }
4741        }
4742        return 0 if (defined $limit && --$limit < 0);
4743        show_commit($c);
4744        return 1;
4745}
4746
4747sub show_commit {
4748        my $c = shift;
4749        if ($oneline) {
4750                my $x = "\n";
4751                if (my $l = $c->{l}) {
4752                        while ($l->[0] =~ /^\s*$/) { shift @$l }
4753                        $x = $l->[0];
4754                }
4755                $l_fmt ||= 'A' . length($c->{r});
4756                print 'r',pack($l_fmt, $c->{r}),' | ';
4757                print "$c->{c} | " if $show_commit;
4758                print $x;
4759        } else {
4760                show_commit_normal($c);
4761        }
4762}
4763
4764sub show_commit_changed_paths {
4765        my ($c) = @_;
4766        return unless $c->{changed};
4767        print "Changed paths:\n", @{$c->{changed}};
4768}
4769
4770sub show_commit_normal {
4771        my ($c) = @_;
4772        print commit_log_separator, "r$c->{r} | ";
4773        print "$c->{c} | " if $show_commit;
4774        print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4775        my $nr_line = 0;
4776
4777        if (my $l = $c->{l}) {
4778                while ($l->[$#$l] eq "\n" && $#$l > 0
4779                                          && $l->[($#$l - 1)] eq "\n") {
4780                        pop @$l;
4781                }
4782                $nr_line = scalar @$l;
4783                if (!$nr_line) {
4784                        print "1 line\n\n\n";
4785                } else {
4786                        if ($nr_line == 1) {
4787                                $nr_line = '1 line';
4788                        } else {
4789                                $nr_line .= ' lines';
4790                        }
4791                        print $nr_line, "\n";
4792                        show_commit_changed_paths($c);
4793                        print "\n";
4794                        print $_ foreach @$l;
4795                }
4796        } else {
4797                print "1 line\n";
4798                show_commit_changed_paths($c);
4799                print "\n";
4800
4801        }
4802        foreach my $x (qw/raw stat diff/) {
4803                if ($c->{$x}) {
4804                        print "\n";
4805                        print $_ foreach @{$c->{$x}}
4806                }
4807        }
4808}
4809
4810sub cmd_show_log {
4811        my (@args) = @_;
4812        my ($r_min, $r_max);
4813        my $r_last = -1; # prevent dupes
4814        set_local_timezone();
4815        if (defined $::_revision) {
4816                if ($::_revision =~ /^(\d+):(\d+)$/) {
4817                        ($r_min, $r_max) = ($1, $2);
4818                } elsif ($::_revision =~ /^\d+$/) {
4819                        $r_min = $r_max = $::_revision;
4820                } else {
4821                        ::fatal "-r$::_revision is not supported, use ",
4822                                "standard 'git log' arguments instead";
4823                }
4824        }
4825
4826        config_pager();
4827        @args = git_svn_log_cmd($r_min, $r_max, @args);
4828        if (!@args) {
4829                print commit_log_separator unless $incremental || $oneline;
4830                return;
4831        }
4832        my $log = command_output_pipe(@args);
4833        run_pager();
4834        my (@k, $c, $d, $stat);
4835        my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4836        while (<$log>) {
4837                if (/^${esc_color}commit -?($::sha1_short)/o) {
4838                        my $cmt = $1;
4839                        if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4840                                $r_last = $c->{r};
4841                                process_commit($c, $r_min, $r_max, \@k) or
4842                                                                goto out;
4843                        }
4844                        $d = undef;
4845                        $c = { c => $cmt };
4846                } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4847                        get_author_info($c, $1, $2, $3);
4848                } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4849                        # ignore
4850                } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4851                        push @{$c->{raw}}, $_;
4852                } elsif (/^${esc_color}[ACRMDT]\t/) {
4853                        # we could add $SVN->{svn_path} here, but that requires
4854                        # remote access at the moment (repo_path_split)...
4855                        s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
4856                        push @{$c->{changed}}, $_;
4857                } elsif (/^${esc_color}diff /o) {
4858                        $d = 1;
4859                        push @{$c->{diff}}, $_;
4860                } elsif ($d) {
4861                        push @{$c->{diff}}, $_;
4862                } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4863                          $esc_color*[\+\-]*$esc_color$/x) {
4864                        $stat = 1;
4865                        push @{$c->{stat}}, $_;
4866                } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4867                        push @{$c->{stat}}, $_;
4868                        $stat = undef;
4869                } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
4870                        ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4871                } elsif (s/^${esc_color}    //o) {
4872                        push @{$c->{l}}, $_;
4873                }
4874        }
4875        if ($c && defined $c->{r} && $c->{r} != $r_last) {
4876                $r_last = $c->{r};
4877                process_commit($c, $r_min, $r_max, \@k);
4878        }
4879        if (@k) {
4880                ($r_min, $r_max) = ($r_max, $r_min);
4881                process_commit($_, $r_min, $r_max) foreach reverse @k;
4882        }
4883out:
4884        close $log;
4885        print commit_log_separator unless $incremental || $oneline;
4886}
4887
4888sub cmd_blame {
4889        my $path = pop;
4890
4891        config_pager();
4892        run_pager();
4893
4894        my ($fh, $ctx, $rev);
4895
4896        if ($_git_format) {
4897                ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4898                while (my $line = <$fh>) {
4899                        if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4900                                # Uncommitted edits show up as a rev ID of
4901                                # all zeros, which we can't look up with
4902                                # cmt_metadata
4903                                if ($1 !~ /^0+$/) {
4904                                        (undef, $rev, undef) =
4905                                                ::cmt_metadata($1);
4906                                        $rev = '0' if (!$rev);
4907                                } else {
4908                                        $rev = '0';
4909                                }
4910                                $rev = sprintf('%-10s', $rev);
4911                                $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4912                        }
4913                        print $line;
4914                }
4915        } else {
4916                ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4917                                                  '--', $path);
4918                my ($sha1);
4919                my %authors;
4920                while (my $line = <$fh>) {
4921                        if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4922                                $sha1 = $1;
4923                                (undef, $rev, undef) = ::cmt_metadata($1);
4924                                $rev = '0' if (!$rev);
4925                        }
4926                        elsif ($line =~ /^author (.*)/) {
4927                                $authors{$rev} = $1;
4928                                $authors{$rev} =~ s/\s/_/g;
4929                        }
4930                        elsif ($line =~ /^\t(.*)$/) {
4931                                printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4932                        }
4933                }
4934        }
4935        command_close_pipe($fh, $ctx);
4936}
4937
4938package Git::SVN::Migration;
4939# these version numbers do NOT correspond to actual version numbers
4940# of git nor git-svn.  They are just relative.
4941#
4942# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4943#
4944# v1 layout: .git/$id/info/url, refs/remotes/$id
4945#
4946# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4947#
4948# v3 layout: .git/svn/$id, refs/remotes/$id
4949#            - info/url may remain for backwards compatibility
4950#            - this is what we migrate up to this layout automatically,
4951#            - this will be used by git svn init on single branches
4952# v3.1 layout (auto migrated):
4953#            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4954#              for backwards compatibility
4955#
4956# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4957#            - this is only created for newly multi-init-ed
4958#              repositories.  Similar in spirit to the
4959#              --use-separate-remotes option in git-clone (now default)
4960#            - we do not automatically migrate to this (following
4961#              the example set by core git)
4962#
4963# v5 layout: .rev_db.$UUID => .rev_map.$UUID
4964#            - newer, more-efficient format that uses 24-bytes per record
4965#              with no filler space.
4966#            - use xxd -c24 < .rev_map.$UUID to view and debug
4967#            - This is a one-way migration, repositories updated to the
4968#              new format will not be able to use old git-svn without
4969#              rebuilding the .rev_db.  Rebuilding the rev_db is not
4970#              possible if noMetadata or useSvmProps are set; but should
4971#              be no problem for users that use the (sensible) defaults.
4972use strict;
4973use warnings;
4974use Carp qw/croak/;
4975use File::Path qw/mkpath/;
4976use File::Basename qw/dirname basename/;
4977use vars qw/$_minimize/;
4978
4979sub migrate_from_v0 {
4980        my $git_dir = $ENV{GIT_DIR};
4981        return undef unless -d $git_dir;
4982        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4983        my $migrated = 0;
4984        while (<$fh>) {
4985                chomp;
4986                my ($id, $orig_ref) = ($_, $_);
4987                next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4988                next unless -f "$git_dir/$id/info/url";
4989                my $new_ref = "refs/remotes/$id";
4990                if (::verify_ref("$new_ref^0")) {
4991                        print STDERR "W: $orig_ref is probably an old ",
4992                                     "branch used by an ancient version of ",
4993                                     "git-svn.\n",
4994                                     "However, $new_ref also exists.\n",
4995                                     "We will not be able ",
4996                                     "to use this branch until this ",
4997                                     "ambiguity is resolved.\n";
4998                        next;
4999                }
5000                print STDERR "Migrating from v0 layout...\n" if !$migrated;
5001                print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5002                command_noisy('update-ref', $new_ref, $orig_ref);
5003                command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5004                $migrated++;
5005        }
5006        command_close_pipe($fh, $ctx);
5007        print STDERR "Done migrating from v0 layout...\n" if $migrated;
5008        $migrated;
5009}
5010
5011sub migrate_from_v1 {
5012        my $git_dir = $ENV{GIT_DIR};
5013        my $migrated = 0;
5014        return $migrated unless -d $git_dir;
5015        my $svn_dir = "$git_dir/svn";
5016
5017        # just in case somebody used 'svn' as their $id at some point...
5018        return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5019
5020        print STDERR "Migrating from a git-svn v1 layout...\n";
5021        mkpath([$svn_dir]);
5022        print STDERR "Data from a previous version of git-svn exists, but\n\t",
5023                     "$svn_dir\n\t(required for this version ",
5024                     "($::VERSION) of git-svn) does not exist.\n";
5025        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5026        while (<$fh>) {
5027                my $x = $_;
5028                next unless $x =~ s#^refs/remotes/##;
5029                chomp $x;
5030                next unless -f "$git_dir/$x/info/url";
5031                my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5032                next unless $u;
5033                my $dn = dirname("$git_dir/svn/$x");
5034                mkpath([$dn]) unless -d $dn;
5035                if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5036                        mkpath(["$git_dir/svn/svn"]);
5037                        print STDERR " - $git_dir/$x/info => ",
5038                                        "$git_dir/svn/$x/info\n";
5039                        rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5040                               croak "$!: $x";
5041                        # don't worry too much about these, they probably
5042                        # don't exist with repos this old (save for index,
5043                        # and we can easily regenerate that)
5044                        foreach my $f (qw/unhandled.log index .rev_db/) {
5045                                rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5046                        }
5047                } else {
5048                        print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5049                        rename "$git_dir/$x", "$git_dir/svn/$x" or
5050                               croak "$!: $x";
5051                }
5052                $migrated++;
5053        }
5054        command_close_pipe($fh, $ctx);
5055        print STDERR "Done migrating from a git-svn v1 layout\n";
5056        $migrated;
5057}
5058
5059sub read_old_urls {
5060        my ($l_map, $pfx, $path) = @_;
5061        my @dir;
5062        foreach (<$path/*>) {
5063                if (-r "$_/info/url") {
5064                        $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5065                        my $ref_id = $pfx . basename $_;
5066                        my $url = ::file_to_s("$_/info/url");
5067                        $l_map->{$ref_id} = $url;
5068                } elsif (-d $_) {
5069                        push @dir, $_;
5070                }
5071        }
5072        foreach (@dir) {
5073                my $x = $_;
5074                $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5075                read_old_urls($l_map, $x, $_);
5076        }
5077}
5078
5079sub migrate_from_v2 {
5080        my @cfg = command(qw/config -l/);
5081        return if grep /^svn-remote\..+\.url=/, @cfg;
5082        my %l_map;
5083        read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5084        my $migrated = 0;
5085
5086        foreach my $ref_id (sort keys %l_map) {
5087                eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5088                if ($@) {
5089                        Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5090                }
5091                $migrated++;
5092        }
5093        $migrated;
5094}
5095
5096sub minimize_connections {
5097        my $r = Git::SVN::read_all_remotes();
5098        my $new_urls = {};
5099        my $root_repos = {};
5100        foreach my $repo_id (keys %$r) {
5101                my $url = $r->{$repo_id}->{url} or next;
5102                my $fetch = $r->{$repo_id}->{fetch} or next;
5103                my $ra = Git::SVN::Ra->new($url);
5104
5105                # skip existing cases where we already connect to the root
5106                if (($ra->{url} eq $ra->{repos_root}) ||
5107                    ($ra->{repos_root} eq $repo_id)) {
5108                        $root_repos->{$ra->{url}} = $repo_id;
5109                        next;
5110                }
5111
5112                my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5113                my $root_path = $ra->{url};
5114                $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5115                foreach my $path (keys %$fetch) {
5116                        my $ref_id = $fetch->{$path};
5117                        my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5118
5119                        # make sure we can read when connecting to
5120                        # a higher level of a repository
5121                        my ($last_rev, undef) = $gs->last_rev_commit;
5122                        if (!defined $last_rev) {
5123                                $last_rev = eval {
5124                                        $root_ra->get_latest_revnum;
5125                                };
5126                                next if $@;
5127                        }
5128                        my $new = $root_path;
5129                        $new .= length $path ? "/$path" : '';
5130                        eval {
5131                                $root_ra->get_log([$new], $last_rev, $last_rev,
5132                                                  0, 0, 1, sub { });
5133                        };
5134                        next if $@;
5135                        $new_urls->{$ra->{repos_root}}->{$new} =
5136                                { ref_id => $ref_id,
5137                                  old_repo_id => $repo_id,
5138                                  old_path => $path };
5139                }
5140        }
5141
5142        my @emptied;
5143        foreach my $url (keys %$new_urls) {
5144                # see if we can re-use an existing [svn-remote "repo_id"]
5145                # instead of creating a(n ugly) new section:
5146                my $repo_id = $root_repos->{$url} || $url;
5147
5148                my $fetch = $new_urls->{$url};
5149                foreach my $path (keys %$fetch) {
5150                        my $x = $fetch->{$path};
5151                        Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5152                        my $pfx = "svn-remote.$x->{old_repo_id}";
5153
5154                        my $old_fetch = quotemeta("$x->{old_path}:".
5155                                                  "refs/remotes/$x->{ref_id}");
5156                        command_noisy(qw/config --unset/,
5157                                      "$pfx.fetch", '^'. $old_fetch . '$');
5158                        delete $r->{$x->{old_repo_id}}->
5159                               {fetch}->{$x->{old_path}};
5160                        if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5161                                command_noisy(qw/config --unset/,
5162                                              "$pfx.url");
5163                                push @emptied, $x->{old_repo_id}
5164                        }
5165                }
5166        }
5167        if (@emptied) {
5168                my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5169                print STDERR <<EOF;
5170The following [svn-remote] sections in your config file ($file) are empty
5171and can be safely removed:
5172EOF
5173                print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5174        }
5175}
5176
5177sub migration_check {
5178        migrate_from_v0();
5179        migrate_from_v1();
5180        migrate_from_v2();
5181        minimize_connections() if $_minimize;
5182}
5183
5184package Git::IndexInfo;
5185use strict;
5186use warnings;
5187use Git qw/command_input_pipe command_close_pipe/;
5188
5189sub new {
5190        my ($class) = @_;
5191        my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5192        bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5193}
5194
5195sub remove {
5196        my ($self, $path) = @_;
5197        if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5198                return ++$self->{nr};
5199        }
5200        undef;
5201}
5202
5203sub update {
5204        my ($self, $mode, $hash, $path) = @_;
5205        if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5206                return ++$self->{nr};
5207        }
5208        undef;
5209}
5210
5211sub DESTROY {
5212        my ($self) = @_;
5213        command_close_pipe($self->{gui}, $self->{ctx});
5214}
5215
5216package Git::SVN::GlobSpec;
5217use strict;
5218use warnings;
5219
5220sub new {
5221        my ($class, $glob) = @_;
5222        my $re = $glob;
5223        $re =~ s!/+$!!g; # no need for trailing slashes
5224        $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5225        my $temp = $re;
5226        my ($left, $right) = ($1, $3);
5227        $re = $2;
5228        my $depth = $re =~ tr/*/*/;
5229        if ($depth != $temp =~ tr/*/*/) {
5230                die "Only one set of wildcard directories " .
5231                        "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5232        }
5233        if ($depth == 0) {
5234                die "One '*' is needed for glob: '$glob'\n";
5235        }
5236        $re =~ s!\*!\[^/\]*!g;
5237        $re = quotemeta($left) . "($re)" . quotemeta($right);
5238        if (length $left && !($left =~ s!/+$!!g)) {
5239                die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5240        }
5241        if (length $right && !($right =~ s!^/+!!g)) {
5242                die "Missing leading '/' on right side of: '$glob' ($right)\n";
5243        }
5244        my $left_re = qr/^\/\Q$left\E(\/|$)/;
5245        bless { left => $left, right => $right, left_regex => $left_re,
5246                regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5247}
5248
5249sub full_path {
5250        my ($self, $path) = @_;
5251        return (length $self->{left} ? "$self->{left}/" : '') .
5252               $path . (length $self->{right} ? "/$self->{right}" : '');
5253}
5254
5255__END__
5256
5257Data structures:
5258
5259
5260$remotes = { # returned by read_all_remotes()
5261        'svn' => {
5262                # svn-remote.svn.url=https://svn.musicpd.org
5263                url => 'https://svn.musicpd.org',
5264                # svn-remote.svn.fetch=mpd/trunk:trunk
5265                fetch => {
5266                        'mpd/trunk' => 'trunk',
5267                },
5268                # svn-remote.svn.tags=mpd/tags/*:tags/*
5269                tags => {
5270                        path => {
5271                                left => 'mpd/tags',
5272                                right => '',
5273                                regex => qr!mpd/tags/([^/]+)$!,
5274                                glob => 'tags/*',
5275                        },
5276                        ref => {
5277                                left => 'tags',
5278                                right => '',
5279                                regex => qr!tags/([^/]+)$!,
5280                                glob => 'tags/*',
5281                        },
5282                }
5283        }
5284};
5285
5286$log_entry hashref as returned by libsvn_log_entry()
5287{
5288        log => 'whitespace-formatted log entry
5289',                                              # trailing newline is preserved
5290        revision => '8',                        # integer
5291        date => '2004-02-24T17:01:44.108345Z',  # commit date
5292        author => 'committer name'
5293};
5294
5295
5296# this is generated by generate_diff();
5297@mods = array of diff-index line hashes, each element represents one line
5298        of diff-index output
5299
5300diff-index line ($m hash)
5301{
5302        mode_a => first column of diff-index output, no leading ':',
5303        mode_b => second column of diff-index output,
5304        sha1_b => sha1sum of the final blob,
5305        chg => change type [MCRADT],
5306        file_a => original file name of a file (iff chg is 'C' or 'R')
5307        file_b => new/current file name of a file (any chg)
5308}
5309;
5310
5311# retval of read_url_paths{,_all}();
5312$l_map = {
5313        # repository root url
5314        'https://svn.musicpd.org' => {
5315                # repository path               # GIT_SVN_ID
5316                'mpd/trunk'             =>      'trunk',
5317                'mpd/tags/0.11.5'       =>      'tags/0.11.5',
5318        },
5319}
5320
5321Notes:
5322        I don't trust the each() function on unless I created %hash myself
5323        because the internal iterator may not have started at base.