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