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