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