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