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