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