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