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