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