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