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