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