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