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