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