71b8ef426500019f9a2687b6c420bdbff0b625eb
   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
3294sub set_path_strip {
3295        my ($self, $path) = @_;
3296        $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3297}
3298
3299sub open_root {
3300        { path => '' };
3301}
3302
3303sub open_directory {
3304        my ($self, $path, $pb, $rev) = @_;
3305        { path => $path };
3306}
3307
3308sub git_path {
3309        my ($self, $path) = @_;
3310        if ($self->{path_strip}) {
3311                $path =~ s!$self->{path_strip}!! or
3312                  die "Failed to strip path '$path' ($self->{path_strip})\n";
3313        }
3314        $path;
3315}
3316
3317sub delete_entry {
3318        my ($self, $path, $rev, $pb) = @_;
3319
3320        my $gpath = $self->git_path($path);
3321        return undef if ($gpath eq '');
3322
3323        # remove entire directories.
3324        if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3325                my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3326                                                     -r --name-only -z/,
3327                                                     $self->{c}, '--', $gpath);
3328                local $/ = "\0";
3329                while (<$ls>) {
3330                        chomp;
3331                        $self->{gii}->remove($_);
3332                        print "\tD\t$_\n" unless $::_q;
3333                }
3334                print "\tD\t$gpath/\n" unless $::_q;
3335                command_close_pipe($ls, $ctx);
3336                $self->{empty}->{$path} = 0
3337        } else {
3338                $self->{gii}->remove($gpath);
3339                print "\tD\t$gpath\n" unless $::_q;
3340        }
3341        undef;
3342}
3343
3344sub open_file {
3345        my ($self, $path, $pb, $rev) = @_;
3346        my $gpath = $self->git_path($path);
3347        my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3348                             =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3349        unless (defined $mode && defined $blob) {
3350                die "$path was not found in commit $self->{c} (r$rev)\n";
3351        }
3352        if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3353                $mode = '120000';
3354        }
3355        { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3356          pool => SVN::Pool->new, action => 'M' };
3357}
3358
3359sub add_file {
3360        my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3361        my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3362        delete $self->{empty}->{$dir};
3363        { path => $path, mode_a => 100644, mode_b => 100644,
3364          pool => SVN::Pool->new, action => 'A' };
3365}
3366
3367sub add_directory {
3368        my ($self, $path, $cp_path, $cp_rev) = @_;
3369        my $gpath = $self->git_path($path);
3370        if ($gpath eq '') {
3371                my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3372                                                     -r --name-only -z/,
3373                                                     $self->{c});
3374                local $/ = "\0";
3375                while (<$ls>) {
3376                        chomp;
3377                        $self->{gii}->remove($_);
3378                        print "\tD\t$_\n" unless $::_q;
3379                }
3380                command_close_pipe($ls, $ctx);
3381                $self->{empty}->{$path} = 0;
3382        }
3383        my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3384        delete $self->{empty}->{$dir};
3385        $self->{empty}->{$path} = 1;
3386        { path => $path };
3387}
3388
3389sub change_dir_prop {
3390        my ($self, $db, $prop, $value) = @_;
3391        $self->{dir_prop}->{$db->{path}} ||= {};
3392        $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3393        undef;
3394}
3395
3396sub absent_directory {
3397        my ($self, $path, $pb) = @_;
3398        $self->{absent_dir}->{$pb->{path}} ||= [];
3399        push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3400        undef;
3401}
3402
3403sub absent_file {
3404        my ($self, $path, $pb) = @_;
3405        $self->{absent_file}->{$pb->{path}} ||= [];
3406        push @{$self->{absent_file}->{$pb->{path}}}, $path;
3407        undef;
3408}
3409
3410sub change_file_prop {
3411        my ($self, $fb, $prop, $value) = @_;
3412        if ($prop eq 'svn:executable') {
3413                if ($fb->{mode_b} != 120000) {
3414                        $fb->{mode_b} = defined $value ? 100755 : 100644;
3415                }
3416        } elsif ($prop eq 'svn:special') {
3417                $fb->{mode_b} = defined $value ? 120000 : 100644;
3418        } else {
3419                $self->{file_prop}->{$fb->{path}} ||= {};
3420                $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3421        }
3422        undef;
3423}
3424
3425sub apply_textdelta {
3426        my ($self, $fb, $exp) = @_;
3427        my $fh = $::_repository->temp_acquire('svn_delta');
3428        # $fh gets auto-closed() by SVN::TxDelta::apply(),
3429        # (but $base does not,) so dup() it for reading in close_file
3430        open my $dup, '<&', $fh or croak $!;
3431        my $base = $::_repository->temp_acquire('git_blob');
3432        if ($fb->{blob}) {
3433                my ($base_is_link, $size);
3434
3435                if ($fb->{mode_a} eq '120000' &&
3436                    ! $self->{empty_symlinks}->{$fb->{path}}) {
3437                        print $base 'link ' or die "print $!\n";
3438                        $base_is_link = 1;
3439                }
3440        retry:
3441                $size = $::_repository->cat_blob($fb->{blob}, $base);
3442                die "Failed to read object $fb->{blob}" if ($size < 0);
3443
3444                if (defined $exp) {
3445                        seek $base, 0, 0 or croak $!;
3446                        my $got = ::md5sum($base);
3447                        if ($got ne $exp) {
3448                                my $err = "Checksum mismatch: ".
3449                                       "$fb->{path} $fb->{blob}\n" .
3450                                       "expected: $exp\n" .
3451                                       "     got: $got\n";
3452                                if ($base_is_link) {
3453                                        warn $err,
3454                                             "Retrying... (possibly ",
3455                                             "a bad symlink from SVN)\n";
3456                                        $::_repository->temp_reset($base);
3457                                        $base_is_link = 0;
3458                                        goto retry;
3459                                }
3460                                die $err;
3461                        }
3462                }
3463        }
3464        seek $base, 0, 0 or croak $!;
3465        $fb->{fh} = $fh;
3466        $fb->{base} = $base;
3467        [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3468}
3469
3470sub close_file {
3471        my ($self, $fb, $exp) = @_;
3472        my $hash;
3473        my $path = $self->git_path($fb->{path});
3474        if (my $fh = $fb->{fh}) {
3475                if (defined $exp) {
3476                        seek($fh, 0, 0) or croak $!;
3477                        my $got = ::md5sum($fh);
3478                        if ($got ne $exp) {
3479                                die "Checksum mismatch: $path\n",
3480                                    "expected: $exp\n    got: $got\n";
3481                        }
3482                }
3483                if ($fb->{mode_b} == 120000) {
3484                        sysseek($fh, 0, 0) or croak $!;
3485                        my $rd = sysread($fh, my $buf, 5);
3486
3487                        if (!defined $rd) {
3488                                croak "sysread: $!\n";
3489                        } elsif ($rd == 0) {
3490                                warn "$path has mode 120000",
3491                                     " but it points to nothing\n",
3492                                     "converting to an empty file with mode",
3493                                     " 100644\n";
3494                                $fb->{mode_b} = '100644';
3495                        } elsif ($buf ne 'link ') {
3496                                warn "$path has mode 120000",
3497                                     " but is not a link\n";
3498                        } else {
3499                                my $tmp_fh = $::_repository->temp_acquire(
3500                                        'svn_hash');
3501                                my $res;
3502                                while ($res = sysread($fh, my $str, 1024)) {
3503                                        my $out = syswrite($tmp_fh, $str, $res);
3504                                        defined($out) && $out == $res
3505                                                or croak("write ",
3506                                                        Git::temp_path($tmp_fh),
3507                                                        ": $!\n");
3508                                }
3509                                defined $res or croak $!;
3510
3511                                ($fh, $tmp_fh) = ($tmp_fh, $fh);
3512                                Git::temp_release($tmp_fh, 1);
3513                        }
3514                }
3515
3516                $hash = $::_repository->hash_and_insert_object(
3517                                Git::temp_path($fh));
3518                $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3519
3520                Git::temp_release($fb->{base}, 1);
3521                Git::temp_release($fh, 1);
3522        } else {
3523                $hash = $fb->{blob} or die "no blob information\n";
3524        }
3525        $fb->{pool}->clear;
3526        $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3527        print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3528        undef;
3529}
3530
3531sub abort_edit {
3532        my $self = shift;
3533        $self->{nr} = $self->{gii}->{nr};
3534        delete $self->{gii};
3535        $self->SUPER::abort_edit(@_);
3536}
3537
3538sub close_edit {
3539        my $self = shift;
3540        $self->{git_commit_ok} = 1;
3541        $self->{nr} = $self->{gii}->{nr};
3542        delete $self->{gii};
3543        $self->SUPER::close_edit(@_);
3544}
3545
3546package SVN::Git::Editor;
3547use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3548use strict;
3549use warnings;
3550use Carp qw/croak/;
3551use IO::File;
3552
3553sub new {
3554        my ($class, $opts) = @_;
3555        foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3556                die "$_ required!\n" unless (defined $opts->{$_});
3557        }
3558
3559        my $pool = SVN::Pool->new;
3560        my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3561        my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3562                                     $opts->{r}, $mods);
3563
3564        # $opts->{ra} functions should not be used after this:
3565        my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
3566                                                $opts->{editor_cb}, $pool);
3567        my $self = SVN::Delta::Editor->new(@ce, $pool);
3568        bless $self, $class;
3569        foreach (qw/svn_path r tree_a tree_b/) {
3570                $self->{$_} = $opts->{$_};
3571        }
3572        $self->{url} = $opts->{ra}->{url};
3573        $self->{mods} = $mods;
3574        $self->{types} = $types;
3575        $self->{pool} = $pool;
3576        $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3577        $self->{rm} = { };
3578        $self->{path_prefix} = length $self->{svn_path} ?
3579                               "$self->{svn_path}/" : '';
3580        $self->{config} = $opts->{config};
3581        return $self;
3582}
3583
3584sub generate_diff {
3585        my ($tree_a, $tree_b) = @_;
3586        my @diff_tree = qw(diff-tree -z -r);
3587        if ($_cp_similarity) {
3588                push @diff_tree, "-C$_cp_similarity";
3589        } else {
3590                push @diff_tree, '-C';
3591        }
3592        push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3593        push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3594        push @diff_tree, $tree_a, $tree_b;
3595        my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3596        local $/ = "\0";
3597        my $state = 'meta';
3598        my @mods;
3599        while (<$diff_fh>) {
3600                chomp $_; # this gets rid of the trailing "\0"
3601                if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3602                                        ($::sha1)\s($::sha1)\s
3603                                        ([MTCRAD])\d*$/xo) {
3604                        push @mods, {   mode_a => $1, mode_b => $2,
3605                                        sha1_a => $3, sha1_b => $4,
3606                                        chg => $5 };
3607                        if ($5 =~ /^(?:C|R)$/) {
3608                                $state = 'file_a';
3609                        } else {
3610                                $state = 'file_b';
3611                        }
3612                } elsif ($state eq 'file_a') {
3613                        my $x = $mods[$#mods] or croak "Empty array\n";
3614                        if ($x->{chg} !~ /^(?:C|R)$/) {
3615                                croak "Error parsing $_, $x->{chg}\n";
3616                        }
3617                        $x->{file_a} = $_;
3618                        $state = 'file_b';
3619                } elsif ($state eq 'file_b') {
3620                        my $x = $mods[$#mods] or croak "Empty array\n";
3621                        if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3622                                croak "Error parsing $_, $x->{chg}\n";
3623                        }
3624                        if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3625                                croak "Error parsing $_, $x->{chg}\n";
3626                        }
3627                        $x->{file_b} = $_;
3628                        $state = 'meta';
3629                } else {
3630                        croak "Error parsing $_\n";
3631                }
3632        }
3633        command_close_pipe($diff_fh, $ctx);
3634        \@mods;
3635}
3636
3637sub check_diff_paths {
3638        my ($ra, $pfx, $rev, $mods) = @_;
3639        my %types;
3640        $pfx .= '/' if length $pfx;
3641
3642        sub type_diff_paths {
3643                my ($ra, $types, $path, $rev) = @_;
3644                my @p = split m#/+#, $path;
3645                my $c = shift @p;
3646                unless (defined $types->{$c}) {
3647                        $types->{$c} = $ra->check_path($c, $rev);
3648                }
3649                while (@p) {
3650                        $c .= '/' . shift @p;
3651                        next if defined $types->{$c};
3652                        $types->{$c} = $ra->check_path($c, $rev);
3653                }
3654        }
3655
3656        foreach my $m (@$mods) {
3657                foreach my $f (qw/file_a file_b/) {
3658                        next unless defined $m->{$f};
3659                        my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3660                        if (length $pfx.$dir && ! defined $types{$dir}) {
3661                                type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3662                        }
3663                }
3664        }
3665        \%types;
3666}
3667
3668sub split_path {
3669        return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3670}
3671
3672sub repo_path {
3673        my ($self, $path) = @_;
3674        $self->{path_prefix}.(defined $path ? $path : '');
3675}
3676
3677sub url_path {
3678        my ($self, $path) = @_;
3679        if ($self->{url} =~ m#^https?://#) {
3680                $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3681        }
3682        $self->{url} . '/' . $self->repo_path($path);
3683}
3684
3685sub rmdirs {
3686        my ($self) = @_;
3687        my $rm = $self->{rm};
3688        delete $rm->{''}; # we never delete the url we're tracking
3689        return unless %$rm;
3690
3691        foreach (keys %$rm) {
3692                my @d = split m#/#, $_;
3693                my $c = shift @d;
3694                $rm->{$c} = 1;
3695                while (@d) {
3696                        $c .= '/' . shift @d;
3697                        $rm->{$c} = 1;
3698                }
3699        }
3700        delete $rm->{$self->{svn_path}};
3701        delete $rm->{''}; # we never delete the url we're tracking
3702        return unless %$rm;
3703
3704        my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3705                                             $self->{tree_b});
3706        local $/ = "\0";
3707        while (<$fh>) {
3708                chomp;
3709                my @dn = split m#/#, $_;
3710                while (pop @dn) {
3711                        delete $rm->{join '/', @dn};
3712                }
3713                unless (%$rm) {
3714                        close $fh;
3715                        return;
3716                }
3717        }
3718        command_close_pipe($fh, $ctx);
3719
3720        my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3721        foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3722                $self->close_directory($bat->{$d}, $p);
3723                my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3724                print "\tD+\t$d/\n" unless $::_q;
3725                $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3726                delete $bat->{$d};
3727        }
3728}
3729
3730sub open_or_add_dir {
3731        my ($self, $full_path, $baton) = @_;
3732        my $t = $self->{types}->{$full_path};
3733        if (!defined $t) {
3734                die "$full_path not known in r$self->{r} or we have a bug!\n";
3735        }
3736        {
3737                no warnings 'once';
3738                # SVN::Node::none and SVN::Node::file are used only once,
3739                # so we're shutting up Perl's warnings about them.
3740                if ($t == $SVN::Node::none) {
3741                        return $self->add_directory($full_path, $baton,
3742                            undef, -1, $self->{pool});
3743                } elsif ($t == $SVN::Node::dir) {
3744                        return $self->open_directory($full_path, $baton,
3745                            $self->{r}, $self->{pool});
3746                } # no warnings 'once'
3747                print STDERR "$full_path already exists in repository at ",
3748                    "r$self->{r} and it is not a directory (",
3749                    ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3750        } # no warnings 'once'
3751        exit 1;
3752}
3753
3754sub ensure_path {
3755        my ($self, $path) = @_;
3756        my $bat = $self->{bat};
3757        my $repo_path = $self->repo_path($path);
3758        return $bat->{''} unless (length $repo_path);
3759        my @p = split m#/+#, $repo_path;
3760        my $c = shift @p;
3761        $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3762        while (@p) {
3763                my $c0 = $c;
3764                $c .= '/' . shift @p;
3765                $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3766        }
3767        return $bat->{$c};
3768}
3769
3770# Subroutine to convert a globbing pattern to a regular expression.
3771# From perl cookbook.
3772sub glob2pat {
3773        my $globstr = shift;
3774        my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3775        $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3776        return '^' . $globstr . '$';
3777}
3778
3779sub check_autoprop {
3780        my ($self, $pattern, $properties, $file, $fbat) = @_;
3781        # Convert the globbing pattern to a regular expression.
3782        my $regex = glob2pat($pattern);
3783        # Check if the pattern matches the file name.
3784        if($file =~ m/($regex)/) {
3785                # Parse the list of properties to set.
3786                my @props = split(/;/, $properties);
3787                foreach my $prop (@props) {
3788                        # Parse 'name=value' syntax and set the property.
3789                        if ($prop =~ /([^=]+)=(.*)/) {
3790                                my ($n,$v) = ($1,$2);
3791                                for ($n, $v) {
3792                                        s/^\s+//; s/\s+$//;
3793                                }
3794                                $self->change_file_prop($fbat, $n, $v);
3795                        }
3796                }
3797        }
3798}
3799
3800sub apply_autoprops {
3801        my ($self, $file, $fbat) = @_;
3802        my $conf_t = ${$self->{config}}{'config'};
3803        no warnings 'once';
3804        # Check [miscellany]/enable-auto-props in svn configuration.
3805        if (SVN::_Core::svn_config_get_bool(
3806                $conf_t,
3807                $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3808                $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3809                0)) {
3810                # Auto-props are enabled.  Enumerate them to look for matches.
3811                my $callback = sub {
3812                        $self->check_autoprop($_[0], $_[1], $file, $fbat);
3813                };
3814                SVN::_Core::svn_config_enumerate(
3815                        $conf_t,
3816                        $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3817                        $callback);
3818        }
3819}
3820
3821sub A {
3822        my ($self, $m) = @_;
3823        my ($dir, $file) = split_path($m->{file_b});
3824        my $pbat = $self->ensure_path($dir);
3825        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3826                                        undef, -1);
3827        print "\tA\t$m->{file_b}\n" unless $::_q;
3828        $self->apply_autoprops($file, $fbat);
3829        $self->chg_file($fbat, $m);
3830        $self->close_file($fbat,undef,$self->{pool});
3831}
3832
3833sub C {
3834        my ($self, $m) = @_;
3835        my ($dir, $file) = split_path($m->{file_b});
3836        my $pbat = $self->ensure_path($dir);
3837        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3838                                $self->url_path($m->{file_a}), $self->{r});
3839        print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3840        $self->chg_file($fbat, $m);
3841        $self->close_file($fbat,undef,$self->{pool});
3842}
3843
3844sub delete_entry {
3845        my ($self, $path, $pbat) = @_;
3846        my $rpath = $self->repo_path($path);
3847        my ($dir, $file) = split_path($rpath);
3848        $self->{rm}->{$dir} = 1;
3849        $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3850}
3851
3852sub R {
3853        my ($self, $m) = @_;
3854        my ($dir, $file) = split_path($m->{file_b});
3855        my $pbat = $self->ensure_path($dir);
3856        my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3857                                $self->url_path($m->{file_a}), $self->{r});
3858        print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3859        $self->apply_autoprops($file, $fbat);
3860        $self->chg_file($fbat, $m);
3861        $self->close_file($fbat,undef,$self->{pool});
3862
3863        ($dir, $file) = split_path($m->{file_a});
3864        $pbat = $self->ensure_path($dir);
3865        $self->delete_entry($m->{file_a}, $pbat);
3866}
3867
3868sub M {
3869        my ($self, $m) = @_;
3870        my ($dir, $file) = split_path($m->{file_b});
3871        my $pbat = $self->ensure_path($dir);
3872        my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3873                                $pbat,$self->{r},$self->{pool});
3874        print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3875        $self->chg_file($fbat, $m);
3876        $self->close_file($fbat,undef,$self->{pool});
3877}
3878
3879sub T { shift->M(@_) }
3880
3881sub change_file_prop {
3882        my ($self, $fbat, $pname, $pval) = @_;
3883        $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3884}
3885
3886sub _chg_file_get_blob ($$$$) {
3887        my ($self, $fbat, $m, $which) = @_;
3888        my $fh = $::_repository->temp_acquire("git_blob_$which");
3889        if ($m->{"mode_$which"} =~ /^120/) {
3890                print $fh 'link ' or croak $!;
3891                $self->change_file_prop($fbat,'svn:special','*');
3892        } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
3893                $self->change_file_prop($fbat,'svn:special',undef);
3894        }
3895        my $blob = $m->{"sha1_$which"};
3896        return ($fh,) if ($blob =~ /^0{40}$/);
3897        my $size = $::_repository->cat_blob($blob, $fh);
3898        croak "Failed to read object $blob" if ($size < 0);
3899        $fh->flush == 0 or croak $!;
3900        seek $fh, 0, 0 or croak $!;
3901
3902        my $exp = ::md5sum($fh);
3903        seek $fh, 0, 0 or croak $!;
3904        return ($fh, $exp);
3905}
3906
3907sub chg_file {
3908        my ($self, $fbat, $m) = @_;
3909        if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3910                $self->change_file_prop($fbat,'svn:executable','*');
3911        } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3912                $self->change_file_prop($fbat,'svn:executable',undef);
3913        }
3914        my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
3915        my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
3916        my $pool = SVN::Pool->new;
3917        my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
3918        if (-s $fh_a) {
3919                my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
3920                my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
3921                if (defined $res) {
3922                        die "Unexpected result from send_txstream: $res\n",
3923                            "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
3924                }
3925        } else {
3926                my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
3927                die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
3928                    if ($got ne $exp_b);
3929        }
3930        Git::temp_release($fh_b, 1);
3931        Git::temp_release($fh_a, 1);
3932        $pool->clear;
3933}
3934
3935sub D {
3936        my ($self, $m) = @_;
3937        my ($dir, $file) = split_path($m->{file_b});
3938        my $pbat = $self->ensure_path($dir);
3939        print "\tD\t$m->{file_b}\n" unless $::_q;
3940        $self->delete_entry($m->{file_b}, $pbat);
3941}
3942
3943sub close_edit {
3944        my ($self) = @_;
3945        my ($p,$bat) = ($self->{pool}, $self->{bat});
3946        foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3947                next if $_ eq '';
3948                $self->close_directory($bat->{$_}, $p);
3949        }
3950        $self->close_directory($bat->{''}, $p);
3951        $self->SUPER::close_edit($p);
3952        $p->clear;
3953}
3954
3955sub abort_edit {
3956        my ($self) = @_;
3957        $self->SUPER::abort_edit($self->{pool});
3958}
3959
3960sub DESTROY {
3961        my $self = shift;
3962        $self->SUPER::DESTROY(@_);
3963        $self->{pool}->clear;
3964}
3965
3966# this drives the editor
3967sub apply_diff {
3968        my ($self) = @_;
3969        my $mods = $self->{mods};
3970        my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3971        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3972                my $f = $m->{chg};
3973                if (defined $o{$f}) {
3974                        $self->$f($m);
3975                } else {
3976                        fatal("Invalid change type: $f");
3977                }
3978        }
3979        $self->rmdirs if $_rmdir;
3980        if (@$mods == 0) {
3981                $self->abort_edit;
3982        } else {
3983                $self->close_edit;
3984        }
3985        return scalar @$mods;
3986}
3987
3988package Git::SVN::Ra;
3989use vars qw/@ISA $config_dir $_log_window_size/;
3990use strict;
3991use warnings;
3992my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3993
3994BEGIN {
3995        # enforce temporary pool usage for some simple functions
3996        no strict 'refs';
3997        for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3998                my $SUPER = "SUPER::$f";
3999                *$f = sub {
4000                        my $self = shift;
4001                        my $pool = SVN::Pool->new;
4002                        my @ret = $self->$SUPER(@_,$pool);
4003                        $pool->clear;
4004                        wantarray ? @ret : $ret[0];
4005                };
4006        }
4007}
4008
4009sub _auth_providers () {
4010        [
4011          SVN::Client::get_simple_provider(),
4012          SVN::Client::get_ssl_server_trust_file_provider(),
4013          SVN::Client::get_simple_prompt_provider(
4014            \&Git::SVN::Prompt::simple, 2),
4015          SVN::Client::get_ssl_client_cert_file_provider(),
4016          SVN::Client::get_ssl_client_cert_prompt_provider(
4017            \&Git::SVN::Prompt::ssl_client_cert, 2),
4018          SVN::Client::get_ssl_client_cert_pw_file_provider(),
4019          SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4020            \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4021          SVN::Client::get_username_provider(),
4022          SVN::Client::get_ssl_server_trust_prompt_provider(
4023            \&Git::SVN::Prompt::ssl_server_trust),
4024          SVN::Client::get_username_prompt_provider(
4025            \&Git::SVN::Prompt::username, 2)
4026        ]
4027}
4028
4029sub escape_uri_only {
4030        my ($uri) = @_;
4031        my @tmp;
4032        foreach (split m{/}, $uri) {
4033                s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4034                push @tmp, $_;
4035        }
4036        join('/', @tmp);
4037}
4038
4039sub escape_url {
4040        my ($url) = @_;
4041        if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4042                my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4043                $url = "$scheme://$domain$uri";
4044        }
4045        $url;
4046}
4047
4048sub new {
4049        my ($class, $url) = @_;
4050        $url =~ s!/+$!!;
4051        return $RA if ($RA && $RA->{url} eq $url);
4052
4053        SVN::_Core::svn_config_ensure($config_dir, undef);
4054        my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4055        my $config = SVN::Core::config_get_config($config_dir);
4056        $RA = undef;
4057        my $dont_store_passwords = 1;
4058        my $conf_t = ${$config}{'config'};
4059        {
4060                no warnings 'once';
4061                # The usage of $SVN::_Core::SVN_CONFIG_* variables
4062                # produces warnings that variables are used only once.
4063                # I had not found the better way to shut them up, so
4064                # the warnings of type 'once' are disabled in this block.
4065                if (SVN::_Core::svn_config_get_bool($conf_t,
4066                    $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4067                    $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4068                    1) == 0) {
4069                        SVN::_Core::svn_auth_set_parameter($baton,
4070                            $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4071                            bless (\$dont_store_passwords, "_p_void"));
4072                }
4073                if (SVN::_Core::svn_config_get_bool($conf_t,
4074                    $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4075                    $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4076                    1) == 0) {
4077                        $Git::SVN::Prompt::_no_auth_cache = 1;
4078                }
4079        } # no warnings 'once'
4080        my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4081                              config => $config,
4082                              pool => SVN::Pool->new,
4083                              auth_provider_callbacks => $callbacks);
4084        $self->{url} = $url;
4085        $self->{svn_path} = $url;
4086        $self->{repos_root} = $self->get_repos_root;
4087        $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4088        $self->{cache} = { check_path => { r => 0, data => {} },
4089                           get_dir => { r => 0, data => {} } };
4090        $RA = bless $self, $class;
4091}
4092
4093sub check_path {
4094        my ($self, $path, $r) = @_;
4095        my $cache = $self->{cache}->{check_path};
4096        if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4097                return $cache->{data}->{$path};
4098        }
4099        my $pool = SVN::Pool->new;
4100        my $t = $self->SUPER::check_path($path, $r, $pool);
4101        $pool->clear;
4102        if ($r != $cache->{r}) {
4103                %{$cache->{data}} = ();
4104                $cache->{r} = $r;
4105        }
4106        $cache->{data}->{$path} = $t;
4107}
4108
4109sub get_dir {
4110        my ($self, $dir, $r) = @_;
4111        my $cache = $self->{cache}->{get_dir};
4112        if ($r == $cache->{r}) {
4113                if (my $x = $cache->{data}->{$dir}) {
4114                        return wantarray ? @$x : $x->[0];
4115                }
4116        }
4117        my $pool = SVN::Pool->new;
4118        my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4119        my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4120        $pool->clear;
4121        if ($r != $cache->{r}) {
4122                %{$cache->{data}} = ();
4123                $cache->{r} = $r;
4124        }
4125        $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4126        wantarray ? (\%dirents, $r, $props) : \%dirents;
4127}
4128
4129sub DESTROY {
4130        # do not call the real DESTROY since we store ourselves in $RA
4131}
4132
4133# get_log(paths, start, end, limit,
4134#         discover_changed_paths, strict_node_history, receiver)
4135sub get_log {
4136        my ($self, @args) = @_;
4137        my $pool = SVN::Pool->new;
4138
4139        # the limit parameter was not supported in SVN 1.1.x, so we
4140        # drop it.  Therefore, the receiver callback passed to it
4141        # is made aware of this limitation by being wrapped if
4142        # the limit passed to is being wrapped.
4143        if ($SVN::Core::VERSION le '1.2.0') {
4144                my $limit = splice(@args, 3, 1);
4145                if ($limit > 0) {
4146                        my $receiver = pop @args;
4147                        push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4148                }
4149        }
4150        my $ret = $self->SUPER::get_log(@args, $pool);
4151        $pool->clear;
4152        $ret;
4153}
4154
4155sub trees_match {
4156        my ($self, $url1, $rev1, $url2, $rev2) = @_;
4157        my $ctx = SVN::Client->new(auth => _auth_providers);
4158        my $out = IO::File->new_tmpfile;
4159
4160        # older SVN (1.1.x) doesn't take $pool as the last parameter for
4161        # $ctx->diff(), so we'll create a default one
4162        my $pool = SVN::Pool->new_default_sub;
4163
4164        $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4165        $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4166        $out->flush;
4167        my $ret = (($out->stat)[7] == 0);
4168        close $out or croak $!;
4169
4170        $ret;
4171}
4172
4173sub get_commit_editor {
4174        my ($self, $log, $cb, $pool) = @_;
4175        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4176        $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4177}
4178
4179sub gs_do_update {
4180        my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4181        my $new = ($rev_a == $rev_b);
4182        my $path = $gs->{path};
4183
4184        if ($new && -e $gs->{index}) {
4185                unlink $gs->{index} or die
4186                  "Couldn't unlink index: $gs->{index}: $!\n";
4187        }
4188        my $pool = SVN::Pool->new;
4189        $editor->set_path_strip($path);
4190        my (@pc) = split m#/#, $path;
4191        my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4192                                        1, $editor, $pool);
4193        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4194
4195        # Since we can't rely on svn_ra_reparent being available, we'll
4196        # just have to do some magic with set_path to make it so
4197        # we only want a partial path.
4198        my $sp = '';
4199        my $final = join('/', @pc);
4200        while (@pc) {
4201                $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4202                $sp .= '/' if length $sp;
4203                $sp .= shift @pc;
4204        }
4205        die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4206
4207        $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4208
4209        $reporter->finish_report($pool);
4210        $pool->clear;
4211        $editor->{git_commit_ok};
4212}
4213
4214# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4215# svn_ra_reparent didn't work before 1.4)
4216sub gs_do_switch {
4217        my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4218        my $path = $gs->{path};
4219        my $pool = SVN::Pool->new;
4220
4221        my $full_url = $self->{url};
4222        my $old_url = $full_url;
4223        $full_url .= '/' . escape_uri_only($path) if length $path;
4224        my ($ra, $reparented);
4225
4226        if ($old_url =~ m#^svn(\+ssh)?://#) {
4227                $_[0] = undef;
4228                $self = undef;
4229                $RA = undef;
4230                $ra = Git::SVN::Ra->new($full_url);
4231                $ra_invalid = 1;
4232        } elsif ($old_url ne $full_url) {
4233                SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4234                $self->{url} = $full_url;
4235                $reparented = 1;
4236        }
4237
4238        $ra ||= $self;
4239        $url_b = escape_url($url_b);
4240        my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4241        my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4242        $reporter->set_path('', $rev_a, 0, @lock, $pool);
4243        $reporter->finish_report($pool);
4244
4245        if ($reparented) {
4246                SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4247                $self->{url} = $old_url;
4248        }
4249
4250        $pool->clear;
4251        $editor->{git_commit_ok};
4252}
4253
4254sub longest_common_path {
4255        my ($gsv, $globs) = @_;
4256        my %common;
4257        my $common_max = scalar @$gsv;
4258
4259        foreach my $gs (@$gsv) {
4260                my @tmp = split m#/#, $gs->{path};
4261                my $p = '';
4262                foreach (@tmp) {
4263                        $p .= length($p) ? "/$_" : $_;
4264                        $common{$p} ||= 0;
4265                        $common{$p}++;
4266                }
4267        }
4268        $globs ||= [];
4269        $common_max += scalar @$globs;
4270        foreach my $glob (@$globs) {
4271                my @tmp = split m#/#, $glob->{path}->{left};
4272                my $p = '';
4273                foreach (@tmp) {
4274                        $p .= length($p) ? "/$_" : $_;
4275                        $common{$p} ||= 0;
4276                        $common{$p}++;
4277                }
4278        }
4279
4280        my $longest_path = '';
4281        foreach (sort {length $b <=> length $a} keys %common) {
4282                if ($common{$_} == $common_max) {
4283                        $longest_path = $_;
4284                        last;
4285                }
4286        }
4287        $longest_path;
4288}
4289
4290sub gs_fetch_loop_common {
4291        my ($self, $base, $head, $gsv, $globs) = @_;
4292        return if ($base > $head);
4293        my $inc = $_log_window_size;
4294        my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4295        my $longest_path = longest_common_path($gsv, $globs);
4296        my $ra_url = $self->{url};
4297        while (1) {
4298                my %revs;
4299                my $err;
4300                my $err_handler = $SVN::Error::handler;
4301                $SVN::Error::handler = sub {
4302                        ($err) = @_;
4303                        skip_unknown_revs($err);
4304                };
4305                sub _cb {
4306                        my ($paths, $r, $author, $date, $log) = @_;
4307                        [ dup_changed_paths($paths),
4308                          { author => $author, date => $date, log => $log } ];
4309                }
4310                $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4311                               sub { $revs{$_[1]} = _cb(@_) });
4312                if ($err && $max >= $head) {
4313                        print STDERR "Path '$longest_path' ",
4314                                     "was probably deleted:\n",
4315                                     $err->expanded_message,
4316                                     "\nWill attempt to follow ",
4317                                     "revisions r$min .. r$max ",
4318                                     "committed before the deletion\n";
4319                        my $hi = $max;
4320                        while (--$hi >= $min) {
4321                                my $ok;
4322                                $self->get_log([$longest_path], $min, $hi,
4323                                               0, 1, 1, sub {
4324                                               $ok ||= $_[1];
4325                                               $revs{$_[1]} = _cb(@_) });
4326                                if ($ok) {
4327                                        print STDERR "r$min .. r$ok OK\n";
4328                                        last;
4329                                }
4330                        }
4331                }
4332                $SVN::Error::handler = $err_handler;
4333
4334                my %exists = map { $_->{path} => $_ } @$gsv;
4335                foreach my $r (sort {$a <=> $b} keys %revs) {
4336                        my ($paths, $logged) = @{$revs{$r}};
4337
4338                        foreach my $gs ($self->match_globs(\%exists, $paths,
4339                                                           $globs, $r)) {
4340                                if ($gs->rev_map_max >= $r) {
4341                                        next;
4342                                }
4343                                next unless $gs->match_paths($paths, $r);
4344                                $gs->{logged_rev_props} = $logged;
4345                                if (my $last_commit = $gs->last_commit) {
4346                                        $gs->assert_index_clean($last_commit);
4347                                }
4348                                my $log_entry = $gs->do_fetch($paths, $r);
4349                                if ($log_entry) {
4350                                        $gs->do_git_commit($log_entry);
4351                                }
4352                                $INDEX_FILES{$gs->{index}} = 1;
4353                        }
4354                        foreach my $g (@$globs) {
4355                                my $k = "svn-remote.$g->{remote}." .
4356                                        "$g->{t}-maxRev";
4357                                Git::SVN::tmp_config($k, $r);
4358                        }
4359                        if ($ra_invalid) {
4360                                $_[0] = undef;
4361                                $self = undef;
4362                                $RA = undef;
4363                                $self = Git::SVN::Ra->new($ra_url);
4364                                $ra_invalid = undef;
4365                        }
4366                }
4367                # pre-fill the .rev_db since it'll eventually get filled in
4368                # with '0' x40 if something new gets committed
4369                foreach my $gs (@$gsv) {
4370                        next if $gs->rev_map_max >= $max;
4371                        next if defined $gs->rev_map_get($max);
4372                        $gs->rev_map_set($max, 0 x40);
4373                }
4374                foreach my $g (@$globs) {
4375                        my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4376                        Git::SVN::tmp_config($k, $max);
4377                }
4378                last if $max >= $head;
4379                $min = $max + 1;
4380                $max += $inc;
4381                $max = $head if ($max > $head);
4382        }
4383        Git::SVN::gc();
4384}
4385
4386sub get_dir_globbed {
4387        my ($self, $left, $depth, $r) = @_;
4388
4389        my @x = eval { $self->get_dir($left, $r) };
4390        return unless scalar @x == 3;
4391        my $dirents = $x[0];
4392        my @finalents;
4393        foreach my $de (keys %$dirents) {
4394                next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4395                if ($depth > 1) {
4396                        my @args = ("$left/$de", $depth - 1, $r);
4397                        foreach my $dir ($self->get_dir_globbed(@args)) {
4398                                push @finalents, "$de/$dir";
4399                        }
4400                } else {
4401                        push @finalents, $de;
4402                }
4403        }
4404        @finalents;
4405}
4406
4407sub match_globs {
4408        my ($self, $exists, $paths, $globs, $r) = @_;
4409
4410        sub get_dir_check {
4411                my ($self, $exists, $g, $r) = @_;
4412
4413                my @dirs = $self->get_dir_globbed($g->{path}->{left},
4414                                                  $g->{path}->{depth},
4415                                                  $r);
4416
4417                foreach my $de (@dirs) {
4418                        my $p = $g->{path}->full_path($de);
4419                        next if $exists->{$p};
4420                        next if (length $g->{path}->{right} &&
4421                                 ($self->check_path($p, $r) !=
4422                                  $SVN::Node::dir));
4423                        $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4424                                         $g->{ref}->full_path($de), 1);
4425                }
4426        }
4427        foreach my $g (@$globs) {
4428                if (my $path = $paths->{"/$g->{path}->{left}"}) {
4429                        if ($path->{action} =~ /^[AR]$/) {
4430                                get_dir_check($self, $exists, $g, $r);
4431                        }
4432                }
4433                foreach (keys %$paths) {
4434                        if (/$g->{path}->{left_regex}/ &&
4435                            !/$g->{path}->{regex}/) {
4436                                next if $paths->{$_}->{action} !~ /^[AR]$/;
4437                                get_dir_check($self, $exists, $g, $r);
4438                        }
4439                        next unless /$g->{path}->{regex}/;
4440                        my $p = $1;
4441                        my $pathname = $g->{path}->full_path($p);
4442                        next if $exists->{$pathname};
4443                        next if ($self->check_path($pathname, $r) !=
4444                                 $SVN::Node::dir);
4445                        $exists->{$pathname} = Git::SVN->init(
4446                                              $self->{url}, $pathname, undef,
4447                                              $g->{ref}->full_path($p), 1);
4448                }
4449                my $c = '';
4450                foreach (split m#/#, $g->{path}->{left}) {
4451                        $c .= "/$_";
4452                        next unless ($paths->{$c} &&
4453                                     ($paths->{$c}->{action} =~ /^[AR]$/));
4454                        get_dir_check($self, $exists, $g, $r);
4455                }
4456        }
4457        values %$exists;
4458}
4459
4460sub minimize_url {
4461        my ($self) = @_;
4462        return $self->{url} if ($self->{url} eq $self->{repos_root});
4463        my $url = $self->{repos_root};
4464        my @components = split(m!/!, $self->{svn_path});
4465        my $c = '';
4466        do {
4467                $url .= "/$c" if length $c;
4468                eval { (ref $self)->new($url)->get_latest_revnum };
4469        } while ($@ && ($c = shift @components));
4470        $url;
4471}
4472
4473sub can_do_switch {
4474        my $self = shift;
4475        unless (defined $can_do_switch) {
4476                my $pool = SVN::Pool->new;
4477                my $rep = eval {
4478                        $self->do_switch(1, '', 0, $self->{url},
4479                                         SVN::Delta::Editor->new, $pool);
4480                };
4481                if ($@) {
4482                        $can_do_switch = 0;
4483                } else {
4484                        $rep->abort_report($pool);
4485                        $can_do_switch = 1;
4486                }
4487                $pool->clear;
4488        }
4489        $can_do_switch;
4490}
4491
4492sub skip_unknown_revs {
4493        my ($err) = @_;
4494        my $errno = $err->apr_err();
4495        # Maybe the branch we're tracking didn't
4496        # exist when the repo started, so it's
4497        # not an error if it doesn't, just continue
4498        #
4499        # Wonderfully consistent library, eh?
4500        # 160013 - svn:// and file://
4501        # 175002 - http(s)://
4502        # 175007 - http(s):// (this repo required authorization, too...)
4503        #   More codes may be discovered later...
4504        if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4505                my $err_key = $err->expanded_message;
4506                # revision numbers change every time, filter them out
4507                $err_key =~ s/\d+/\0/g;
4508                $err_key = "$errno\0$err_key";
4509                unless ($ignored_err{$err_key}) {
4510                        warn "W: Ignoring error from SVN, path probably ",
4511                             "does not exist: ($errno): ",
4512                             $err->expanded_message,"\n";
4513                        warn "W: Do not be alarmed at the above message ",
4514                             "git-svn is just searching aggressively for ",
4515                             "old history.\n",
4516                             "This may take a while on large repositories\n";
4517                        $ignored_err{$err_key} = 1;
4518                }
4519                return;
4520        }
4521        die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4522}
4523
4524# svn_log_changed_path_t objects passed to get_log are likely to be
4525# overwritten even if only the refs are copied to an external variable,
4526# so we should dup the structures in their entirety.  Using an externally
4527# passed pool (instead of our temporary and quickly cleared pool in
4528# Git::SVN::Ra) does not help matters at all...
4529sub dup_changed_paths {
4530        my ($paths) = @_;
4531        return undef unless $paths;
4532        my %ret;
4533        foreach my $p (keys %$paths) {
4534                my $i = $paths->{$p};
4535                my %s = map { $_ => $i->$_ }
4536                              qw/copyfrom_path copyfrom_rev action/;
4537                $ret{$p} = \%s;
4538        }
4539        \%ret;
4540}
4541
4542package Git::SVN::Log;
4543use strict;
4544use warnings;
4545use POSIX qw/strftime/;
4546use constant commit_log_separator => ('-' x 72) . "\n";
4547use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4548            %rusers $show_commit $incremental/;
4549my $l_fmt;
4550
4551sub cmt_showable {
4552        my ($c) = @_;
4553        return 1 if defined $c->{r};
4554
4555        # big commit message got truncated by the 16k pretty buffer in rev-list
4556        if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4557                                $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4558                @{$c->{l}} = ();
4559                my @log = command(qw/cat-file commit/, $c->{c});
4560
4561                # shift off the headers
4562                shift @log while ($log[0] ne '');
4563                shift @log;
4564
4565                # TODO: make $c->{l} not have a trailing newline in the future
4566                @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4567
4568                (undef, $c->{r}, undef) = ::extract_metadata(
4569                                (grep(/^git-svn-id: /, @log))[-1]);
4570        }
4571        return defined $c->{r};
4572}
4573
4574sub log_use_color {
4575        return $color || Git->repository->get_colorbool('color.diff');
4576}
4577
4578sub git_svn_log_cmd {
4579        my ($r_min, $r_max, @args) = @_;
4580        my $head = 'HEAD';
4581        my (@files, @log_opts);
4582        foreach my $x (@args) {
4583                if ($x eq '--' || @files) {
4584                        push @files, $x;
4585                } else {
4586                        if (::verify_ref("$x^0")) {
4587                                $head = $x;
4588                        } else {
4589                                push @log_opts, $x;
4590                        }
4591                }
4592        }
4593
4594        my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4595        $gs ||= Git::SVN->_new;
4596        my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4597                   $gs->refname);
4598        push @cmd, '-r' unless $non_recursive;
4599        push @cmd, qw/--raw --name-status/ if $verbose;
4600        push @cmd, '--color' if log_use_color();
4601        push @cmd, @log_opts;
4602        if (defined $r_max && $r_max == $r_min) {
4603                push @cmd, '--max-count=1';
4604                if (my $c = $gs->rev_map_get($r_max)) {
4605                        push @cmd, $c;
4606                }
4607        } elsif (defined $r_max) {
4608                if ($r_max < $r_min) {
4609                        ($r_min, $r_max) = ($r_max, $r_min);
4610                }
4611                my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4612                my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4613                # If there are no commits in the range, both $c_max and $c_min
4614                # will be undefined.  If there is at least 1 commit in the
4615                # range, both will be defined.
4616                return () if !defined $c_min || !defined $c_max;
4617                if ($c_min eq $c_max) {
4618                        push @cmd, '--max-count=1', $c_min;
4619                } else {
4620                        push @cmd, '--boundary', "$c_min..$c_max";
4621                }
4622        }
4623        return (@cmd, @files);
4624}
4625
4626# adapted from pager.c
4627sub config_pager {
4628        $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4629        if (!defined $pager) {
4630                $pager = 'less';
4631        } elsif (length $pager == 0 || $pager eq 'cat') {
4632                $pager = undef;
4633        }
4634        $ENV{GIT_PAGER_IN_USE} = defined($pager);
4635}
4636
4637sub run_pager {
4638        return unless -t *STDOUT && defined $pager;
4639        pipe my ($rfd, $wfd) or return;
4640        defined(my $pid = fork) or ::fatal "Can't fork: $!";
4641        if (!$pid) {
4642                open STDOUT, '>&', $wfd or
4643                                     ::fatal "Can't redirect to stdout: $!";
4644                return;
4645        }
4646        open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4647        $ENV{LESS} ||= 'FRSX';
4648        exec $pager or ::fatal "Can't run pager: $! ($pager)";
4649}
4650
4651sub format_svn_date {
4652        return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4653}
4654
4655sub parse_git_date {
4656        my ($t, $tz) = @_;
4657        # Date::Parse isn't in the standard Perl distro :(
4658        if ($tz =~ s/^\+//) {
4659                $t += tz_to_s_offset($tz);
4660        } elsif ($tz =~ s/^\-//) {
4661                $t -= tz_to_s_offset($tz);
4662        }
4663        return $t;
4664}
4665
4666sub set_local_timezone {
4667        if (defined $TZ) {
4668                $ENV{TZ} = $TZ;
4669        } else {
4670                delete $ENV{TZ};
4671        }
4672}
4673
4674sub tz_to_s_offset {
4675        my ($tz) = @_;
4676        $tz =~ s/(\d\d)$//;
4677        return ($1 * 60) + ($tz * 3600);
4678}
4679
4680sub get_author_info {
4681        my ($dest, $author, $t, $tz) = @_;
4682        $author =~ s/(?:^\s*|\s*$)//g;
4683        $dest->{a_raw} = $author;
4684        my $au;
4685        if ($::_authors) {
4686                $au = $rusers{$author} || undef;
4687        }
4688        if (!$au) {
4689                ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4690        }
4691        $dest->{t} = $t;
4692        $dest->{tz} = $tz;
4693        $dest->{a} = $au;
4694        $dest->{t_utc} = parse_git_date($t, $tz);
4695}
4696
4697sub process_commit {
4698        my ($c, $r_min, $r_max, $defer) = @_;
4699        if (defined $r_min && defined $r_max) {
4700                if ($r_min == $c->{r} && $r_min == $r_max) {
4701                        show_commit($c);
4702                        return 0;
4703                }
4704                return 1 if $r_min == $r_max;
4705                if ($r_min < $r_max) {
4706                        # we need to reverse the print order
4707                        return 0 if (defined $limit && --$limit < 0);
4708                        push @$defer, $c;
4709                        return 1;
4710                }
4711                if ($r_min != $r_max) {
4712                        return 1 if ($r_min < $c->{r});
4713                        return 1 if ($r_max > $c->{r});
4714                }
4715        }
4716        return 0 if (defined $limit && --$limit < 0);
4717        show_commit($c);
4718        return 1;
4719}
4720
4721sub show_commit {
4722        my $c = shift;
4723        if ($oneline) {
4724                my $x = "\n";
4725                if (my $l = $c->{l}) {
4726                        while ($l->[0] =~ /^\s*$/) { shift @$l }
4727                        $x = $l->[0];
4728                }
4729                $l_fmt ||= 'A' . length($c->{r});
4730                print 'r',pack($l_fmt, $c->{r}),' | ';
4731                print "$c->{c} | " if $show_commit;
4732                print $x;
4733        } else {
4734                show_commit_normal($c);
4735        }
4736}
4737
4738sub show_commit_changed_paths {
4739        my ($c) = @_;
4740        return unless $c->{changed};
4741        print "Changed paths:\n", @{$c->{changed}};
4742}
4743
4744sub show_commit_normal {
4745        my ($c) = @_;
4746        print commit_log_separator, "r$c->{r} | ";
4747        print "$c->{c} | " if $show_commit;
4748        print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4749        my $nr_line = 0;
4750
4751        if (my $l = $c->{l}) {
4752                while ($l->[$#$l] eq "\n" && $#$l > 0
4753                                          && $l->[($#$l - 1)] eq "\n") {
4754                        pop @$l;
4755                }
4756                $nr_line = scalar @$l;
4757                if (!$nr_line) {
4758                        print "1 line\n\n\n";
4759                } else {
4760                        if ($nr_line == 1) {
4761                                $nr_line = '1 line';
4762                        } else {
4763                                $nr_line .= ' lines';
4764                        }
4765                        print $nr_line, "\n";
4766                        show_commit_changed_paths($c);
4767                        print "\n";
4768                        print $_ foreach @$l;
4769                }
4770        } else {
4771                print "1 line\n";
4772                show_commit_changed_paths($c);
4773                print "\n";
4774
4775        }
4776        foreach my $x (qw/raw stat diff/) {
4777                if ($c->{$x}) {
4778                        print "\n";
4779                        print $_ foreach @{$c->{$x}}
4780                }
4781        }
4782}
4783
4784sub cmd_show_log {
4785        my (@args) = @_;
4786        my ($r_min, $r_max);
4787        my $r_last = -1; # prevent dupes
4788        set_local_timezone();
4789        if (defined $::_revision) {
4790                if ($::_revision =~ /^(\d+):(\d+)$/) {
4791                        ($r_min, $r_max) = ($1, $2);
4792                } elsif ($::_revision =~ /^\d+$/) {
4793                        $r_min = $r_max = $::_revision;
4794                } else {
4795                        ::fatal "-r$::_revision is not supported, use ",
4796                                "standard 'git log' arguments instead";
4797                }
4798        }
4799
4800        config_pager();
4801        @args = git_svn_log_cmd($r_min, $r_max, @args);
4802        if (!@args) {
4803                print commit_log_separator unless $incremental || $oneline;
4804                return;
4805        }
4806        my $log = command_output_pipe(@args);
4807        run_pager();
4808        my (@k, $c, $d, $stat);
4809        my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4810        while (<$log>) {
4811                if (/^${esc_color}commit -?($::sha1_short)/o) {
4812                        my $cmt = $1;
4813                        if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4814                                $r_last = $c->{r};
4815                                process_commit($c, $r_min, $r_max, \@k) or
4816                                                                goto out;
4817                        }
4818                        $d = undef;
4819                        $c = { c => $cmt };
4820                } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4821                        get_author_info($c, $1, $2, $3);
4822                } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4823                        # ignore
4824                } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4825                        push @{$c->{raw}}, $_;
4826                } elsif (/^${esc_color}[ACRMDT]\t/) {
4827                        # we could add $SVN->{svn_path} here, but that requires
4828                        # remote access at the moment (repo_path_split)...
4829                        s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
4830                        push @{$c->{changed}}, $_;
4831                } elsif (/^${esc_color}diff /o) {
4832                        $d = 1;
4833                        push @{$c->{diff}}, $_;
4834                } elsif ($d) {
4835                        push @{$c->{diff}}, $_;
4836                } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4837                          $esc_color*[\+\-]*$esc_color$/x) {
4838                        $stat = 1;
4839                        push @{$c->{stat}}, $_;
4840                } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4841                        push @{$c->{stat}}, $_;
4842                        $stat = undef;
4843                } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
4844                        ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4845                } elsif (s/^${esc_color}    //o) {
4846                        push @{$c->{l}}, $_;
4847                }
4848        }
4849        if ($c && defined $c->{r} && $c->{r} != $r_last) {
4850                $r_last = $c->{r};
4851                process_commit($c, $r_min, $r_max, \@k);
4852        }
4853        if (@k) {
4854                ($r_min, $r_max) = ($r_max, $r_min);
4855                process_commit($_, $r_min, $r_max) foreach reverse @k;
4856        }
4857out:
4858        close $log;
4859        print commit_log_separator unless $incremental || $oneline;
4860}
4861
4862sub cmd_blame {
4863        my $path = pop;
4864
4865        config_pager();
4866        run_pager();
4867
4868        my ($fh, $ctx, $rev);
4869
4870        if ($_git_format) {
4871                ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4872                while (my $line = <$fh>) {
4873                        if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4874                                # Uncommitted edits show up as a rev ID of
4875                                # all zeros, which we can't look up with
4876                                # cmt_metadata
4877                                if ($1 !~ /^0+$/) {
4878                                        (undef, $rev, undef) =
4879                                                ::cmt_metadata($1);
4880                                        $rev = '0' if (!$rev);
4881                                } else {
4882                                        $rev = '0';
4883                                }
4884                                $rev = sprintf('%-10s', $rev);
4885                                $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4886                        }
4887                        print $line;
4888                }
4889        } else {
4890                ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4891                                                  '--', $path);
4892                my ($sha1);
4893                my %authors;
4894                while (my $line = <$fh>) {
4895                        if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4896                                $sha1 = $1;
4897                                (undef, $rev, undef) = ::cmt_metadata($1);
4898                                $rev = '0' if (!$rev);
4899                        }
4900                        elsif ($line =~ /^author (.*)/) {
4901                                $authors{$rev} = $1;
4902                                $authors{$rev} =~ s/\s/_/g;
4903                        }
4904                        elsif ($line =~ /^\t(.*)$/) {
4905                                printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4906                        }
4907                }
4908        }
4909        command_close_pipe($fh, $ctx);
4910}
4911
4912package Git::SVN::Migration;
4913# these version numbers do NOT correspond to actual version numbers
4914# of git nor git-svn.  They are just relative.
4915#
4916# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4917#
4918# v1 layout: .git/$id/info/url, refs/remotes/$id
4919#
4920# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4921#
4922# v3 layout: .git/svn/$id, refs/remotes/$id
4923#            - info/url may remain for backwards compatibility
4924#            - this is what we migrate up to this layout automatically,
4925#            - this will be used by git svn init on single branches
4926# v3.1 layout (auto migrated):
4927#            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4928#              for backwards compatibility
4929#
4930# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4931#            - this is only created for newly multi-init-ed
4932#              repositories.  Similar in spirit to the
4933#              --use-separate-remotes option in git-clone (now default)
4934#            - we do not automatically migrate to this (following
4935#              the example set by core git)
4936#
4937# v5 layout: .rev_db.$UUID => .rev_map.$UUID
4938#            - newer, more-efficient format that uses 24-bytes per record
4939#              with no filler space.
4940#            - use xxd -c24 < .rev_map.$UUID to view and debug
4941#            - This is a one-way migration, repositories updated to the
4942#              new format will not be able to use old git-svn without
4943#              rebuilding the .rev_db.  Rebuilding the rev_db is not
4944#              possible if noMetadata or useSvmProps are set; but should
4945#              be no problem for users that use the (sensible) defaults.
4946use strict;
4947use warnings;
4948use Carp qw/croak/;
4949use File::Path qw/mkpath/;
4950use File::Basename qw/dirname basename/;
4951use vars qw/$_minimize/;
4952
4953sub migrate_from_v0 {
4954        my $git_dir = $ENV{GIT_DIR};
4955        return undef unless -d $git_dir;
4956        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4957        my $migrated = 0;
4958        while (<$fh>) {
4959                chomp;
4960                my ($id, $orig_ref) = ($_, $_);
4961                next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4962                next unless -f "$git_dir/$id/info/url";
4963                my $new_ref = "refs/remotes/$id";
4964                if (::verify_ref("$new_ref^0")) {
4965                        print STDERR "W: $orig_ref is probably an old ",
4966                                     "branch used by an ancient version of ",
4967                                     "git-svn.\n",
4968                                     "However, $new_ref also exists.\n",
4969                                     "We will not be able ",
4970                                     "to use this branch until this ",
4971                                     "ambiguity is resolved.\n";
4972                        next;
4973                }
4974                print STDERR "Migrating from v0 layout...\n" if !$migrated;
4975                print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4976                command_noisy('update-ref', $new_ref, $orig_ref);
4977                command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4978                $migrated++;
4979        }
4980        command_close_pipe($fh, $ctx);
4981        print STDERR "Done migrating from v0 layout...\n" if $migrated;
4982        $migrated;
4983}
4984
4985sub migrate_from_v1 {
4986        my $git_dir = $ENV{GIT_DIR};
4987        my $migrated = 0;
4988        return $migrated unless -d $git_dir;
4989        my $svn_dir = "$git_dir/svn";
4990
4991        # just in case somebody used 'svn' as their $id at some point...
4992        return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4993
4994        print STDERR "Migrating from a git-svn v1 layout...\n";
4995        mkpath([$svn_dir]);
4996        print STDERR "Data from a previous version of git-svn exists, but\n\t",
4997                     "$svn_dir\n\t(required for this version ",
4998                     "($::VERSION) of git-svn) does not exist.\n";
4999        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5000        while (<$fh>) {
5001                my $x = $_;
5002                next unless $x =~ s#^refs/remotes/##;
5003                chomp $x;
5004                next unless -f "$git_dir/$x/info/url";
5005                my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5006                next unless $u;
5007                my $dn = dirname("$git_dir/svn/$x");
5008                mkpath([$dn]) unless -d $dn;
5009                if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5010                        mkpath(["$git_dir/svn/svn"]);
5011                        print STDERR " - $git_dir/$x/info => ",
5012                                        "$git_dir/svn/$x/info\n";
5013                        rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5014                               croak "$!: $x";
5015                        # don't worry too much about these, they probably
5016                        # don't exist with repos this old (save for index,
5017                        # and we can easily regenerate that)
5018                        foreach my $f (qw/unhandled.log index .rev_db/) {
5019                                rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5020                        }
5021                } else {
5022                        print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5023                        rename "$git_dir/$x", "$git_dir/svn/$x" or
5024                               croak "$!: $x";
5025                }
5026                $migrated++;
5027        }
5028        command_close_pipe($fh, $ctx);
5029        print STDERR "Done migrating from a git-svn v1 layout\n";
5030        $migrated;
5031}
5032
5033sub read_old_urls {
5034        my ($l_map, $pfx, $path) = @_;
5035        my @dir;
5036        foreach (<$path/*>) {
5037                if (-r "$_/info/url") {
5038                        $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5039                        my $ref_id = $pfx . basename $_;
5040                        my $url = ::file_to_s("$_/info/url");
5041                        $l_map->{$ref_id} = $url;
5042                } elsif (-d $_) {
5043                        push @dir, $_;
5044                }
5045        }
5046        foreach (@dir) {
5047                my $x = $_;
5048                $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5049                read_old_urls($l_map, $x, $_);
5050        }
5051}
5052
5053sub migrate_from_v2 {
5054        my @cfg = command(qw/config -l/);
5055        return if grep /^svn-remote\..+\.url=/, @cfg;
5056        my %l_map;
5057        read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5058        my $migrated = 0;
5059
5060        foreach my $ref_id (sort keys %l_map) {
5061                eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5062                if ($@) {
5063                        Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5064                }
5065                $migrated++;
5066        }
5067        $migrated;
5068}
5069
5070sub minimize_connections {
5071        my $r = Git::SVN::read_all_remotes();
5072        my $new_urls = {};
5073        my $root_repos = {};
5074        foreach my $repo_id (keys %$r) {
5075                my $url = $r->{$repo_id}->{url} or next;
5076                my $fetch = $r->{$repo_id}->{fetch} or next;
5077                my $ra = Git::SVN::Ra->new($url);
5078
5079                # skip existing cases where we already connect to the root
5080                if (($ra->{url} eq $ra->{repos_root}) ||
5081                    ($ra->{repos_root} eq $repo_id)) {
5082                        $root_repos->{$ra->{url}} = $repo_id;
5083                        next;
5084                }
5085
5086                my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5087                my $root_path = $ra->{url};
5088                $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5089                foreach my $path (keys %$fetch) {
5090                        my $ref_id = $fetch->{$path};
5091                        my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5092
5093                        # make sure we can read when connecting to
5094                        # a higher level of a repository
5095                        my ($last_rev, undef) = $gs->last_rev_commit;
5096                        if (!defined $last_rev) {
5097                                $last_rev = eval {
5098                                        $root_ra->get_latest_revnum;
5099                                };
5100                                next if $@;
5101                        }
5102                        my $new = $root_path;
5103                        $new .= length $path ? "/$path" : '';
5104                        eval {
5105                                $root_ra->get_log([$new], $last_rev, $last_rev,
5106                                                  0, 0, 1, sub { });
5107                        };
5108                        next if $@;
5109                        $new_urls->{$ra->{repos_root}}->{$new} =
5110                                { ref_id => $ref_id,
5111                                  old_repo_id => $repo_id,
5112                                  old_path => $path };
5113                }
5114        }
5115
5116        my @emptied;
5117        foreach my $url (keys %$new_urls) {
5118                # see if we can re-use an existing [svn-remote "repo_id"]
5119                # instead of creating a(n ugly) new section:
5120                my $repo_id = $root_repos->{$url} || $url;
5121
5122                my $fetch = $new_urls->{$url};
5123                foreach my $path (keys %$fetch) {
5124                        my $x = $fetch->{$path};
5125                        Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5126                        my $pfx = "svn-remote.$x->{old_repo_id}";
5127
5128                        my $old_fetch = quotemeta("$x->{old_path}:".
5129                                                  "refs/remotes/$x->{ref_id}");
5130                        command_noisy(qw/config --unset/,
5131                                      "$pfx.fetch", '^'. $old_fetch . '$');
5132                        delete $r->{$x->{old_repo_id}}->
5133                               {fetch}->{$x->{old_path}};
5134                        if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5135                                command_noisy(qw/config --unset/,
5136                                              "$pfx.url");
5137                                push @emptied, $x->{old_repo_id}
5138                        }
5139                }
5140        }
5141        if (@emptied) {
5142                my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5143                print STDERR <<EOF;
5144The following [svn-remote] sections in your config file ($file) are empty
5145and can be safely removed:
5146EOF
5147                print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5148        }
5149}
5150
5151sub migration_check {
5152        migrate_from_v0();
5153        migrate_from_v1();
5154        migrate_from_v2();
5155        minimize_connections() if $_minimize;
5156}
5157
5158package Git::IndexInfo;
5159use strict;
5160use warnings;
5161use Git qw/command_input_pipe command_close_pipe/;
5162
5163sub new {
5164        my ($class) = @_;
5165        my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5166        bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5167}
5168
5169sub remove {
5170        my ($self, $path) = @_;
5171        if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5172                return ++$self->{nr};
5173        }
5174        undef;
5175}
5176
5177sub update {
5178        my ($self, $mode, $hash, $path) = @_;
5179        if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5180                return ++$self->{nr};
5181        }
5182        undef;
5183}
5184
5185sub DESTROY {
5186        my ($self) = @_;
5187        command_close_pipe($self->{gui}, $self->{ctx});
5188}
5189
5190package Git::SVN::GlobSpec;
5191use strict;
5192use warnings;
5193
5194sub new {
5195        my ($class, $glob) = @_;
5196        my $re = $glob;
5197        $re =~ s!/+$!!g; # no need for trailing slashes
5198        $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5199        my $temp = $re;
5200        my ($left, $right) = ($1, $3);
5201        $re = $2;
5202        my $depth = $re =~ tr/*/*/;
5203        if ($depth != $temp =~ tr/*/*/) {
5204                die "Only one set of wildcard directories " .
5205                        "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5206        }
5207        if ($depth == 0) {
5208                die "One '*' is needed for glob: '$glob'\n";
5209        }
5210        $re =~ s!\*!\[^/\]*!g;
5211        $re = quotemeta($left) . "($re)" . quotemeta($right);
5212        if (length $left && !($left =~ s!/+$!!g)) {
5213                die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5214        }
5215        if (length $right && !($right =~ s!^/+!!g)) {
5216                die "Missing leading '/' on right side of: '$glob' ($right)\n";
5217        }
5218        my $left_re = qr/^\/\Q$left\E(\/|$)/;
5219        bless { left => $left, right => $right, left_regex => $left_re,
5220                regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5221}
5222
5223sub full_path {
5224        my ($self, $path) = @_;
5225        return (length $self->{left} ? "$self->{left}/" : '') .
5226               $path . (length $self->{right} ? "/$self->{right}" : '');
5227}
5228
5229__END__
5230
5231Data structures:
5232
5233
5234$remotes = { # returned by read_all_remotes()
5235        'svn' => {
5236                # svn-remote.svn.url=https://svn.musicpd.org
5237                url => 'https://svn.musicpd.org',
5238                # svn-remote.svn.fetch=mpd/trunk:trunk
5239                fetch => {
5240                        'mpd/trunk' => 'trunk',
5241                },
5242                # svn-remote.svn.tags=mpd/tags/*:tags/*
5243                tags => {
5244                        path => {
5245                                left => 'mpd/tags',
5246                                right => '',
5247                                regex => qr!mpd/tags/([^/]+)$!,
5248                                glob => 'tags/*',
5249                        },
5250                        ref => {
5251                                left => 'tags',
5252                                right => '',
5253                                regex => qr!tags/([^/]+)$!,
5254                                glob => 'tags/*',
5255                        },
5256                }
5257        }
5258};
5259
5260$log_entry hashref as returned by libsvn_log_entry()
5261{
5262        log => 'whitespace-formatted log entry
5263',                                              # trailing newline is preserved
5264        revision => '8',                        # integer
5265        date => '2004-02-24T17:01:44.108345Z',  # commit date
5266        author => 'committer name'
5267};
5268
5269
5270# this is generated by generate_diff();
5271@mods = array of diff-index line hashes, each element represents one line
5272        of diff-index output
5273
5274diff-index line ($m hash)
5275{
5276        mode_a => first column of diff-index output, no leading ':',
5277        mode_b => second column of diff-index output,
5278        sha1_b => sha1sum of the final blob,
5279        chg => change type [MCRADT],
5280        file_a => original file name of a file (iff chg is 'C' or 'R')
5281        file_b => new/current file name of a file (any chg)
5282}
5283;
5284
5285# retval of read_url_paths{,_all}();
5286$l_map = {
5287        # repository root url
5288        'https://svn.musicpd.org' => {
5289                # repository path               # GIT_SVN_ID
5290                'mpd/trunk'             =>      'trunk',
5291                'mpd/tags/0.11.5'       =>      'tags/0.11.5',
5292        },
5293}
5294
5295Notes:
5296        I don't trust the each() function on unless I created %hash myself
5297        because the internal iterator may not have started at base.