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