81d034ae51a522cb5ddea234df16612ff07401bb
   1#!/usr/bin/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
  13use Git::SVN;
  14use Git::SVN::Utils qw(fatal can_compress);
  15
  16# From which subdir have we been invoked?
  17my $cmd_dir_prefix = eval {
  18        command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
  19} || '';
  20
  21my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
  22$ENV{GIT_DIR} ||= '.git';
  23$Git::SVN::default_repo_id = 'svn';
  24$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
  25$Git::SVN::Ra::_log_window_size = 100;
  26$Git::SVN::_minimize_url = 'unset';
  27
  28if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
  29        $ENV{SVN_SSH} = $ENV{GIT_SSH};
  30}
  31
  32if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
  33        $ENV{SVN_SSH} =~ s/\\/\\\\/g;
  34        $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
  35}
  36
  37$Git::SVN::Log::TZ = $ENV{TZ};
  38$ENV{TZ} = 'UTC';
  39$| = 1; # unbuffer STDOUT
  40
  41# All SVN commands do it.  Otherwise we may die on SIGPIPE when the remote
  42# repository decides to close the connection which we expect to be kept alive.
  43$SIG{PIPE} = 'IGNORE';
  44
  45# Given a dot separated version number, "subtract" it from
  46# the SVN::Core::VERSION; non-negaitive return means the SVN::Core
  47# is at least at the version the caller asked for.
  48sub compare_svn_version {
  49        my (@ours) = split(/\./, $SVN::Core::VERSION);
  50        my (@theirs) = split(/\./, $_[0]);
  51        my ($i, $diff);
  52
  53        for ($i = 0; $i < @ours && $i < @theirs; $i++) {
  54                $diff = $ours[$i] - $theirs[$i];
  55                return $diff if ($diff);
  56        }
  57        return 1 if ($i < @ours);
  58        return -1 if ($i < @theirs);
  59        return 0;
  60}
  61
  62sub _req_svn {
  63        require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
  64        require SVN::Ra;
  65        require SVN::Delta;
  66        if (::compare_svn_version('1.1.0') < 0) {
  67                fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
  68        }
  69}
  70
  71use Carp qw/croak/;
  72use Digest::MD5;
  73use IO::File qw//;
  74use File::Basename qw/dirname basename/;
  75use File::Path qw/mkpath/;
  76use File::Spec;
  77use File::Find;
  78use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
  79use IPC::Open3;
  80use Git;
  81use Git::SVN::Editor qw//;
  82use Git::SVN::Fetcher qw//;
  83use Git::SVN::Ra qw//;
  84use Git::SVN::Prompt qw//;
  85use Memoize;  # core since 5.8.0, Jul 2002
  86
  87BEGIN {
  88        # import functions from Git into our packages, en masse
  89        no strict 'refs';
  90        foreach (qw/command command_oneline command_noisy command_output_pipe
  91                    command_input_pipe command_close_pipe
  92                    command_bidi_pipe command_close_bidi_pipe/) {
  93                for my $package ( qw(Git::SVN::Migration Git::SVN::Log),
  94                        __PACKAGE__) {
  95                        *{"${package}::$_"} = \&{"Git::$_"};
  96                }
  97        }
  98        Memoize::memoize 'Git::config';
  99        Memoize::memoize 'Git::config_bool';
 100}
 101
 102my ($SVN);
 103
 104$sha1 = qr/[a-f\d]{40}/;
 105$sha1_short = qr/[a-f\d]{4,40}/;
 106my ($_stdin, $_help, $_edit,
 107        $_message, $_file, $_branch_dest,
 108        $_template, $_shared,
 109        $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
 110        $_merge, $_strategy, $_preserve_merges, $_dry_run, $_local,
 111        $_prefix, $_no_checkout, $_url, $_verbose,
 112        $_git_format, $_commit_url, $_tag, $_merge_info, $_interactive);
 113
 114# This is a refactoring artifact so Git::SVN can get at this git-svn switch.
 115sub opt_prefix { return $_prefix || '' }
 116
 117$Git::SVN::_follow_parent = 1;
 118$Git::SVN::Fetcher::_placeholder_filename = ".gitignore";
 119$_q ||= 0;
 120my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
 121                    'config-dir=s' => \$Git::SVN::Ra::config_dir,
 122                    'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
 123                    'ignore-paths=s' => \$Git::SVN::Fetcher::_ignore_regex,
 124                    'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
 125my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
 126                'authors-file|A=s' => \$_authors,
 127                'authors-prog=s' => \$_authors_prog,
 128                'repack:i' => \$Git::SVN::_repack,
 129                'noMetadata' => \$Git::SVN::_no_metadata,
 130                'useSvmProps' => \$Git::SVN::_use_svm_props,
 131                'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
 132                'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
 133                'no-checkout' => \$_no_checkout,
 134                'quiet|q+' => \$_q,
 135                'repack-flags|repack-args|repack-opts=s' =>
 136                   \$Git::SVN::_repack_flags,
 137                'use-log-author' => \$Git::SVN::_use_log_author,
 138                'add-author-from' => \$Git::SVN::_add_author_from,
 139                'localtime' => \$Git::SVN::_localtime,
 140                %remote_opts );
 141
 142my ($_trunk, @_tags, @_branches, $_stdlayout);
 143my %icv;
 144my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
 145                  'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
 146                  'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
 147                  'stdlayout|s' => \$_stdlayout,
 148                  'minimize-url|m!' => \$Git::SVN::_minimize_url,
 149                  'no-metadata' => sub { $icv{noMetadata} = 1 },
 150                  'use-svm-props' => sub { $icv{useSvmProps} = 1 },
 151                  'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
 152                  'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
 153                  'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
 154                  %remote_opts );
 155my %cmt_opts = ( 'edit|e' => \$_edit,
 156                'rmdir' => \$Git::SVN::Editor::_rmdir,
 157                'find-copies-harder' => \$Git::SVN::Editor::_find_copies_harder,
 158                'l=i' => \$Git::SVN::Editor::_rename_limit,
 159                'copy-similarity|C=i'=> \$Git::SVN::Editor::_cp_similarity
 160);
 161
 162my %cmd = (
 163        fetch => [ \&cmd_fetch, "Download new revisions from SVN",
 164                        { 'revision|r=s' => \$_revision,
 165                          'fetch-all|all' => \$_fetch_all,
 166                          'parent|p' => \$_fetch_parent,
 167                           %fc_opts } ],
 168        clone => [ \&cmd_clone, "Initialize and fetch revisions",
 169                        { 'revision|r=s' => \$_revision,
 170                          'preserve-empty-dirs' =>
 171                                \$Git::SVN::Fetcher::_preserve_empty_dirs,
 172                          'placeholder-filename=s' =>
 173                                \$Git::SVN::Fetcher::_placeholder_filename,
 174                           %fc_opts, %init_opts } ],
 175        init => [ \&cmd_init, "Initialize a repo for tracking" .
 176                          " (requires URL argument)",
 177                          \%init_opts ],
 178        'multi-init' => [ \&cmd_multi_init,
 179                          "Deprecated alias for ".
 180                          "'$0 init -T<trunk> -b<branches> -t<tags>'",
 181                          \%init_opts ],
 182        dcommit => [ \&cmd_dcommit,
 183                     'Commit several diffs to merge with upstream',
 184                        { 'merge|m|M' => \$_merge,
 185                          'strategy|s=s' => \$_strategy,
 186                          'verbose|v' => \$_verbose,
 187                          'dry-run|n' => \$_dry_run,
 188                          'fetch-all|all' => \$_fetch_all,
 189                          'commit-url=s' => \$_commit_url,
 190                          'revision|r=i' => \$_revision,
 191                          'no-rebase' => \$_no_rebase,
 192                          'mergeinfo=s' => \$_merge_info,
 193                          'interactive|i' => \$_interactive,
 194                        %cmt_opts, %fc_opts } ],
 195        branch => [ \&cmd_branch,
 196                    'Create a branch in the SVN repository',
 197                    { 'message|m=s' => \$_message,
 198                      'destination|d=s' => \$_branch_dest,
 199                      'dry-run|n' => \$_dry_run,
 200                      'tag|t' => \$_tag,
 201                      'username=s' => \$Git::SVN::Prompt::_username,
 202                      'commit-url=s' => \$_commit_url } ],
 203        tag => [ sub { $_tag = 1; cmd_branch(@_) },
 204                 'Create a tag in the SVN repository',
 205                 { 'message|m=s' => \$_message,
 206                   'destination|d=s' => \$_branch_dest,
 207                   'dry-run|n' => \$_dry_run,
 208                   'username=s' => \$Git::SVN::Prompt::_username,
 209                   'commit-url=s' => \$_commit_url } ],
 210        'set-tree' => [ \&cmd_set_tree,
 211                        "Set an SVN repository to a git tree-ish",
 212                        { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
 213        'create-ignore' => [ \&cmd_create_ignore,
 214                             'Create a .gitignore per svn:ignore',
 215                             { 'revision|r=i' => \$_revision
 216                             } ],
 217        'mkdirs' => [ \&cmd_mkdirs ,
 218                      "recreate empty directories after a checkout",
 219                      { 'revision|r=i' => \$_revision } ],
 220        'propget' => [ \&cmd_propget,
 221                       'Print the value of a property on a file or directory',
 222                       { 'revision|r=i' => \$_revision } ],
 223        'proplist' => [ \&cmd_proplist,
 224                       'List all properties of a file or directory',
 225                       { 'revision|r=i' => \$_revision } ],
 226        'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
 227                        { 'revision|r=i' => \$_revision
 228                        } ],
 229        'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
 230                        { 'revision|r=i' => \$_revision
 231                        } ],
 232        'multi-fetch' => [ \&cmd_multi_fetch,
 233                           "Deprecated alias for $0 fetch --all",
 234                           { 'revision|r=s' => \$_revision, %fc_opts } ],
 235        'migrate' => [ sub { },
 236                       # no-op, we automatically run this anyways,
 237                       'Migrate configuration/metadata/layout from
 238                        previous versions of git-svn',
 239                       { 'minimize' => \$Git::SVN::Migration::_minimize,
 240                         %remote_opts } ],
 241        'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
 242                        { 'limit=i' => \$Git::SVN::Log::limit,
 243                          'revision|r=s' => \$_revision,
 244                          'verbose|v' => \$Git::SVN::Log::verbose,
 245                          'incremental' => \$Git::SVN::Log::incremental,
 246                          'oneline' => \$Git::SVN::Log::oneline,
 247                          'show-commit' => \$Git::SVN::Log::show_commit,
 248                          'non-recursive' => \$Git::SVN::Log::non_recursive,
 249                          'authors-file|A=s' => \$_authors,
 250                          'color' => \$Git::SVN::Log::color,
 251                          'pager=s' => \$Git::SVN::Log::pager
 252                        } ],
 253        'find-rev' => [ \&cmd_find_rev,
 254                        "Translate between SVN revision numbers and tree-ish",
 255                        {} ],
 256        'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
 257                        { 'merge|m|M' => \$_merge,
 258                          'verbose|v' => \$_verbose,
 259                          'strategy|s=s' => \$_strategy,
 260                          'local|l' => \$_local,
 261                          'fetch-all|all' => \$_fetch_all,
 262                          'dry-run|n' => \$_dry_run,
 263                          'preserve-merges|p' => \$_preserve_merges,
 264                          %fc_opts } ],
 265        'commit-diff' => [ \&cmd_commit_diff,
 266                           'Commit a diff between two trees',
 267                        { 'message|m=s' => \$_message,
 268                          'file|F=s' => \$_file,
 269                          'revision|r=s' => \$_revision,
 270                        %cmt_opts } ],
 271        'info' => [ \&cmd_info,
 272                    "Show info about the latest SVN revision
 273                     on the current branch",
 274                    { 'url' => \$_url, } ],
 275        'blame' => [ \&Git::SVN::Log::cmd_blame,
 276                    "Show what revision and author last modified each line of a file",
 277                    { 'git-format' => \$_git_format } ],
 278        'reset' => [ \&cmd_reset,
 279                     "Undo fetches back to the specified SVN revision",
 280                     { 'revision|r=s' => \$_revision,
 281                       'parent|p' => \$_fetch_parent } ],
 282        'gc' => [ \&cmd_gc,
 283                  "Compress unhandled.log files in .git/svn and remove " .
 284                  "index files in .git/svn",
 285                {} ],
 286);
 287
 288use Term::ReadLine;
 289package FakeTerm;
 290sub new {
 291        my ($class, $reason) = @_;
 292        return bless \$reason, shift;
 293}
 294sub readline {
 295        my $self = shift;
 296        die "Cannot use readline on FakeTerm: $$self";
 297}
 298package main;
 299
 300my $term = eval {
 301        $ENV{"GIT_SVN_NOTTY"}
 302                ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
 303                : new Term::ReadLine 'git-svn';
 304};
 305if ($@) {
 306        $term = new FakeTerm "$@: going non-interactive";
 307}
 308
 309my $cmd;
 310for (my $i = 0; $i < @ARGV; $i++) {
 311        if (defined $cmd{$ARGV[$i]}) {
 312                $cmd = $ARGV[$i];
 313                splice @ARGV, $i, 1;
 314                last;
 315        } elsif ($ARGV[$i] eq 'help') {
 316                $cmd = $ARGV[$i+1];
 317                usage(0);
 318        }
 319};
 320
 321# make sure we're always running at the top-level working directory
 322unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
 323        unless (-d $ENV{GIT_DIR}) {
 324                if ($git_dir_user_set) {
 325                        die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
 326                            "but it is not a directory\n";
 327                }
 328                my $git_dir = delete $ENV{GIT_DIR};
 329                my $cdup = undef;
 330                git_cmd_try {
 331                        $cdup = command_oneline(qw/rev-parse --show-cdup/);
 332                        $git_dir = '.' unless ($cdup);
 333                        chomp $cdup if ($cdup);
 334                        $cdup = "." unless ($cdup && length $cdup);
 335                } "Already at toplevel, but $git_dir not found\n";
 336                chdir $cdup or die "Unable to chdir up to '$cdup'\n";
 337                unless (-d $git_dir) {
 338                        die "$git_dir still not found after going to ",
 339                            "'$cdup'\n";
 340                }
 341                $ENV{GIT_DIR} = $git_dir;
 342        }
 343        $_repository = Git->repository(Repository => $ENV{GIT_DIR});
 344}
 345
 346my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
 347
 348read_git_config(\%opts);
 349if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
 350        Getopt::Long::Configure('pass_through');
 351}
 352my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
 353                    'minimize-connections' => \$Git::SVN::Migration::_minimize,
 354                    'id|i=s' => \$Git::SVN::default_ref_id,
 355                    'svn-remote|remote|R=s' => sub {
 356                       $Git::SVN::no_reuse_existing = 1;
 357                       $Git::SVN::default_repo_id = $_[1] });
 358exit 1 if (!$rv && $cmd && $cmd ne 'log');
 359
 360usage(0) if $_help;
 361version() if $_version;
 362usage(1) unless defined $cmd;
 363load_authors() if $_authors;
 364if (defined $_authors_prog) {
 365        $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
 366}
 367
 368unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
 369        Git::SVN::Migration::migration_check();
 370}
 371Git::SVN::init_vars();
 372eval {
 373        Git::SVN::verify_remotes_sanity();
 374        $cmd{$cmd}->[0]->(@ARGV);
 375        post_fetch_checkout();
 376};
 377fatal $@ if $@;
 378exit 0;
 379
 380####################### primary functions ######################
 381sub usage {
 382        my $exit = shift || 0;
 383        my $fd = $exit ? \*STDERR : \*STDOUT;
 384        print $fd <<"";
 385git-svn - bidirectional operations between a single Subversion tree and git
 386Usage: git svn <command> [options] [arguments]\n
 387
 388        print $fd "Available commands:\n" unless $cmd;
 389
 390        foreach (sort keys %cmd) {
 391                next if $cmd && $cmd ne $_;
 392                next if /^multi-/; # don't show deprecated commands
 393                print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
 394                foreach (sort keys %{$cmd{$_}->[2]}) {
 395                        # mixed-case options are for .git/config only
 396                        next if /[A-Z]/ && /^[a-z]+$/i;
 397                        # prints out arguments as they should be passed:
 398                        my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
 399                        print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
 400                                                        "--$_" : "-$_" }
 401                                                split /\|/,$_)," $x\n";
 402                }
 403        }
 404        print $fd <<"";
 405\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
 406arbitrary identifier if you're tracking multiple SVN branches/repositories in
 407one git repository and want to keep them separate.  See git-svn(1) for more
 408information.
 409
 410        exit $exit;
 411}
 412
 413sub version {
 414        ::_req_svn();
 415        print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
 416        exit 0;
 417}
 418
 419sub ask {
 420        my ($prompt, %arg) = @_;
 421        my $valid_re = $arg{valid_re};
 422        my $default = $arg{default};
 423        my $resp;
 424        my $i = 0;
 425
 426        if ( !( defined($term->IN)
 427            && defined( fileno($term->IN) )
 428            && defined( $term->OUT )
 429            && defined( fileno($term->OUT) ) ) ){
 430                return defined($default) ? $default : undef;
 431        }
 432
 433        while ($i++ < 10) {
 434                $resp = $term->readline($prompt);
 435                if (!defined $resp) { # EOF
 436                        print "\n";
 437                        return defined $default ? $default : undef;
 438                }
 439                if ($resp eq '' and defined $default) {
 440                        return $default;
 441                }
 442                if (!defined $valid_re or $resp =~ /$valid_re/) {
 443                        return $resp;
 444                }
 445        }
 446        return undef;
 447}
 448
 449sub do_git_init_db {
 450        unless (-d $ENV{GIT_DIR}) {
 451                my @init_db = ('init');
 452                push @init_db, "--template=$_template" if defined $_template;
 453                if (defined $_shared) {
 454                        if ($_shared =~ /[a-z]/) {
 455                                push @init_db, "--shared=$_shared";
 456                        } else {
 457                                push @init_db, "--shared";
 458                        }
 459                }
 460                command_noisy(@init_db);
 461                $_repository = Git->repository(Repository => ".git");
 462        }
 463        my $set;
 464        my $pfx = "svn-remote.$Git::SVN::default_repo_id";
 465        foreach my $i (keys %icv) {
 466                die "'$set' and '$i' cannot both be set\n" if $set;
 467                next unless defined $icv{$i};
 468                command_noisy('config', "$pfx.$i", $icv{$i});
 469                $set = $i;
 470        }
 471        my $ignore_paths_regex = \$Git::SVN::Fetcher::_ignore_regex;
 472        command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
 473                if defined $$ignore_paths_regex;
 474        my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
 475        command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
 476                if defined $$ignore_refs_regex;
 477
 478        if (defined $Git::SVN::Fetcher::_preserve_empty_dirs) {
 479                my $fname = \$Git::SVN::Fetcher::_placeholder_filename;
 480                command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
 481                command_noisy('config', "$pfx.placeholder-filename", $$fname);
 482        }
 483}
 484
 485sub init_subdir {
 486        my $repo_path = shift or return;
 487        mkpath([$repo_path]) unless -d $repo_path;
 488        chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
 489        $ENV{GIT_DIR} = '.git';
 490        $_repository = Git->repository(Repository => $ENV{GIT_DIR});
 491}
 492
 493sub cmd_clone {
 494        my ($url, $path) = @_;
 495        if (!defined $path &&
 496            (defined $_trunk || @_branches || @_tags ||
 497             defined $_stdlayout) &&
 498            $url !~ m#^[a-z\+]+://#) {
 499                $path = $url;
 500        }
 501        $path = basename($url) if !defined $path || !length $path;
 502        my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
 503        cmd_init($url, $path);
 504        command_oneline('config', 'svn.authorsfile', $authors_absolute)
 505            if $_authors;
 506        Git::SVN::fetch_all($Git::SVN::default_repo_id);
 507}
 508
 509sub cmd_init {
 510        if (defined $_stdlayout) {
 511                $_trunk = 'trunk' if (!defined $_trunk);
 512                @_tags = 'tags' if (! @_tags);
 513                @_branches = 'branches' if (! @_branches);
 514        }
 515        if (defined $_trunk || @_branches || @_tags) {
 516                return cmd_multi_init(@_);
 517        }
 518        my $url = shift or die "SVN repository location required ",
 519                               "as a command-line argument\n";
 520        $url = canonicalize_url($url);
 521        init_subdir(@_);
 522        do_git_init_db();
 523
 524        if ($Git::SVN::_minimize_url eq 'unset') {
 525                $Git::SVN::_minimize_url = 0;
 526        }
 527
 528        Git::SVN->init($url);
 529}
 530
 531sub cmd_fetch {
 532        if (grep /^\d+=./, @_) {
 533                die "'<rev>=<commit>' fetch arguments are ",
 534                    "no longer supported.\n";
 535        }
 536        my ($remote) = @_;
 537        if (@_ > 1) {
 538                die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
 539        }
 540        $Git::SVN::no_reuse_existing = undef;
 541        if ($_fetch_parent) {
 542                my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 543                unless ($gs) {
 544                        die "Unable to determine upstream SVN information from ",
 545                            "working tree history\n";
 546                }
 547                # just fetch, don't checkout.
 548                $_no_checkout = 'true';
 549                $_fetch_all ? $gs->fetch_all : $gs->fetch;
 550        } elsif ($_fetch_all) {
 551                cmd_multi_fetch();
 552        } else {
 553                $remote ||= $Git::SVN::default_repo_id;
 554                Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
 555        }
 556}
 557
 558sub cmd_set_tree {
 559        my (@commits) = @_;
 560        if ($_stdin || !@commits) {
 561                print "Reading from stdin...\n";
 562                @commits = ();
 563                while (<STDIN>) {
 564                        if (/\b($sha1_short)\b/o) {
 565                                unshift @commits, $1;
 566                        }
 567                }
 568        }
 569        my @revs;
 570        foreach my $c (@commits) {
 571                my @tmp = command('rev-parse',$c);
 572                if (scalar @tmp == 1) {
 573                        push @revs, $tmp[0];
 574                } elsif (scalar @tmp > 1) {
 575                        push @revs, reverse(command('rev-list',@tmp));
 576                } else {
 577                        fatal "Failed to rev-parse $c";
 578                }
 579        }
 580        my $gs = Git::SVN->new;
 581        my ($r_last, $cmt_last) = $gs->last_rev_commit;
 582        $gs->fetch;
 583        if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
 584                fatal "There are new revisions that were fetched ",
 585                      "and need to be merged (or acknowledged) ",
 586                      "before committing.\nlast rev: $r_last\n",
 587                      " current: $gs->{last_rev}";
 588        }
 589        $gs->set_tree($_) foreach @revs;
 590        print "Done committing ",scalar @revs," revisions to SVN\n";
 591        unlink $gs->{index};
 592}
 593
 594sub split_merge_info_range {
 595        my ($range) = @_;
 596        if ($range =~ /(\d+)-(\d+)/) {
 597                return (int($1), int($2));
 598        } else {
 599                return (int($range), int($range));
 600        }
 601}
 602
 603sub combine_ranges {
 604        my ($in) = @_;
 605
 606        my @fnums = ();
 607        my @arr = split(/,/, $in);
 608        for my $element (@arr) {
 609                my ($start, $end) = split_merge_info_range($element);
 610                push @fnums, $start;
 611        }
 612
 613        my @sorted = @arr [ sort {
 614                $fnums[$a] <=> $fnums[$b]
 615        } 0..$#arr ];
 616
 617        my @return = ();
 618        my $last = -1;
 619        my $first = -1;
 620        for my $element (@sorted) {
 621                my ($start, $end) = split_merge_info_range($element);
 622
 623                if ($last == -1) {
 624                        $first = $start;
 625                        $last = $end;
 626                        next;
 627                }
 628                if ($start <= $last+1) {
 629                        if ($end > $last) {
 630                                $last = $end;
 631                        }
 632                        next;
 633                }
 634                if ($first == $last) {
 635                        push @return, "$first";
 636                } else {
 637                        push @return, "$first-$last";
 638                }
 639                $first = $start;
 640                $last = $end;
 641        }
 642
 643        if ($first != -1) {
 644                if ($first == $last) {
 645                        push @return, "$first";
 646                } else {
 647                        push @return, "$first-$last";
 648                }
 649        }
 650
 651        return join(',', @return);
 652}
 653
 654sub merge_revs_into_hash {
 655        my ($hash, $minfo) = @_;
 656        my @lines = split(' ', $minfo);
 657
 658        for my $line (@lines) {
 659                my ($branchpath, $revs) = split(/:/, $line);
 660
 661                if (exists($hash->{$branchpath})) {
 662                        # Merge the two revision sets
 663                        my $combined = "$hash->{$branchpath},$revs";
 664                        $hash->{$branchpath} = combine_ranges($combined);
 665                } else {
 666                        # Just do range combining for consolidation
 667                        $hash->{$branchpath} = combine_ranges($revs);
 668                }
 669        }
 670}
 671
 672sub merge_merge_info {
 673        my ($mergeinfo_one, $mergeinfo_two) = @_;
 674        my %result_hash = ();
 675
 676        merge_revs_into_hash(\%result_hash, $mergeinfo_one);
 677        merge_revs_into_hash(\%result_hash, $mergeinfo_two);
 678
 679        my $result = '';
 680        # Sort below is for consistency's sake
 681        for my $branchname (sort keys(%result_hash)) {
 682                my $revlist = $result_hash{$branchname};
 683                $result .= "$branchname:$revlist\n"
 684        }
 685        return $result;
 686}
 687
 688sub populate_merge_info {
 689        my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
 690
 691        my %parentshash;
 692        read_commit_parents(\%parentshash, $d);
 693        my @parents = @{$parentshash{$d}};
 694        if ($#parents > 0) {
 695                # Merge commit
 696                my $all_parents_ok = 1;
 697                my $aggregate_mergeinfo = '';
 698                my $rooturl = $gs->repos_root;
 699
 700                if (defined($rewritten_parent)) {
 701                        # Replace first parent with newly-rewritten version
 702                        shift @parents;
 703                        unshift @parents, $rewritten_parent;
 704                }
 705
 706                foreach my $parent (@parents) {
 707                        my ($branchurl, $svnrev, $paruuid) =
 708                                cmt_metadata($parent);
 709
 710                        unless (defined($svnrev)) {
 711                                # Should have been caught be preflight check
 712                                fatal "merge commit $d has ancestor $parent, but that change "
 713                     ."does not have git-svn metadata!";
 714                        }
 715                        unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
 716                                fatal "commit $parent git-svn metadata changed mid-run!";
 717                        }
 718                        my $branchpath = $1;
 719
 720                        my $ra = Git::SVN::Ra->new($branchurl);
 721                        my (undef, undef, $props) =
 722                                $ra->get_dir(canonicalize_path("."), $svnrev);
 723                        my $par_mergeinfo = $props->{'svn:mergeinfo'};
 724                        unless (defined $par_mergeinfo) {
 725                                $par_mergeinfo = '';
 726                        }
 727                        # Merge previous mergeinfo values
 728                        $aggregate_mergeinfo =
 729                                merge_merge_info($aggregate_mergeinfo,
 730                                                                 $par_mergeinfo, 0);
 731
 732                        next if $parent eq $parents[0]; # Skip first parent
 733                        # Add new changes being placed in tree by merge
 734                        my @cmd = (qw/rev-list --reverse/,
 735                                           $parent, qw/--not/);
 736                        foreach my $par (@parents) {
 737                                unless ($par eq $parent) {
 738                                        push @cmd, $par;
 739                                }
 740                        }
 741                        my @revsin = ();
 742                        my ($revlist, $ctx) = command_output_pipe(@cmd);
 743                        while (<$revlist>) {
 744                                my $irev = $_;
 745                                chomp $irev;
 746                                my (undef, $csvnrev, undef) =
 747                                        cmt_metadata($irev);
 748                                unless (defined $csvnrev) {
 749                                        # A child is missing SVN annotations...
 750                                        # this might be OK, or might not be.
 751                                        warn "W:child $irev is merged into revision "
 752                                                 ."$d but does not have git-svn metadata. "
 753                                                 ."This means git-svn cannot determine the "
 754                                                 ."svn revision numbers to place into the "
 755                                                 ."svn:mergeinfo property. You must ensure "
 756                                                 ."a branch is entirely committed to "
 757                                                 ."SVN before merging it in order for "
 758                                                 ."svn:mergeinfo population to function "
 759                                                 ."properly";
 760                                }
 761                                push @revsin, $csvnrev;
 762                        }
 763                        command_close_pipe($revlist, $ctx);
 764
 765                        last unless $all_parents_ok;
 766
 767                        # We now have a list of all SVN revnos which are
 768                        # merged by this particular parent. Integrate them.
 769                        next if $#revsin == -1;
 770                        my $newmergeinfo = "$branchpath:" . join(',', @revsin);
 771                        $aggregate_mergeinfo =
 772                                merge_merge_info($aggregate_mergeinfo,
 773                                                                 $newmergeinfo, 1);
 774                }
 775                if ($all_parents_ok and $aggregate_mergeinfo) {
 776                        return $aggregate_mergeinfo;
 777                }
 778        }
 779
 780        return undef;
 781}
 782
 783sub cmd_dcommit {
 784        my $head = shift;
 785        command_noisy(qw/update-index --refresh/);
 786        git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
 787                'Cannot dcommit with a dirty index.  Commit your changes first, '
 788                . "or stash them with `git stash'.\n";
 789        $head ||= 'HEAD';
 790
 791        my $old_head;
 792        if ($head ne 'HEAD') {
 793                $old_head = eval {
 794                        command_oneline([qw/symbolic-ref -q HEAD/])
 795                };
 796                if ($old_head) {
 797                        $old_head =~ s{^refs/heads/}{};
 798                } else {
 799                        $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
 800                }
 801                command(['checkout', $head], STDERR => 0);
 802        }
 803
 804        my @refs;
 805        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
 806        unless ($gs) {
 807                die "Unable to determine upstream SVN information from ",
 808                    "$head history.\nPerhaps the repository is empty.";
 809        }
 810
 811        if (defined $_commit_url) {
 812                $url = $_commit_url;
 813        } else {
 814                $url = eval { command_oneline('config', '--get',
 815                              "svn-remote.$gs->{repo_id}.commiturl") };
 816                if (!$url) {
 817                        $url = $gs->full_pushurl
 818                }
 819        }
 820
 821        my $last_rev = $_revision if defined $_revision;
 822        if ($url) {
 823                print "Committing to $url ...\n";
 824        }
 825        my ($linear_refs, $parents) = linearize_history($gs, \@refs);
 826        if ($_no_rebase && scalar(@$linear_refs) > 1) {
 827                warn "Attempting to commit more than one change while ",
 828                     "--no-rebase is enabled.\n",
 829                     "If these changes depend on each other, re-running ",
 830                     "without --no-rebase may be required."
 831        }
 832
 833        if (defined $_interactive){
 834                my $ask_default = "y";
 835                foreach my $d (@$linear_refs){
 836                        my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
 837                        while (<$fh>){
 838                                print $_;
 839                        }
 840                        command_close_pipe($fh, $ctx);
 841                        $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
 842                                 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
 843                                 default => $ask_default);
 844                        die "Commit this patch reply required" unless defined $_;
 845                        if (/^[nq]/i) {
 846                                exit(0);
 847                        } elsif (/^a/i) {
 848                                last;
 849                        }
 850                }
 851        }
 852
 853        my $expect_url = $url;
 854
 855        my $push_merge_info = eval {
 856                command_oneline(qw/config --get svn.pushmergeinfo/)
 857                };
 858        if (not defined($push_merge_info)
 859                        or $push_merge_info eq "false"
 860                        or $push_merge_info eq "no"
 861                        or $push_merge_info eq "never") {
 862                $push_merge_info = 0;
 863        }
 864
 865        unless (defined($_merge_info) || ! $push_merge_info) {
 866                # Preflight check of changes to ensure no issues with mergeinfo
 867                # This includes check for uncommitted-to-SVN parents
 868                # (other than the first parent, which we will handle),
 869                # information from different SVN repos, and paths
 870                # which are not underneath this repository root.
 871                my $rooturl = $gs->repos_root;
 872                foreach my $d (@$linear_refs) {
 873                        my %parentshash;
 874                        read_commit_parents(\%parentshash, $d);
 875                        my @realparents = @{$parentshash{$d}};
 876                        if ($#realparents > 0) {
 877                                # Merge commit
 878                                shift @realparents; # Remove/ignore first parent
 879                                foreach my $parent (@realparents) {
 880                                        my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
 881                                        unless (defined $paruuid) {
 882                                                # A parent is missing SVN annotations...
 883                                                # abort the whole operation.
 884                                                fatal "$parent is merged into revision $d, "
 885                                                         ."but does not have git-svn metadata. "
 886                                                         ."Either dcommit the branch or use a "
 887                                                         ."local cherry-pick, FF merge, or rebase "
 888                                                         ."instead of an explicit merge commit.";
 889                                        }
 890
 891                                        unless ($paruuid eq $uuid) {
 892                                                # Parent has SVN metadata from different repository
 893                                                fatal "merge parent $parent for change $d has "
 894                                                         ."git-svn uuid $paruuid, while current change "
 895                                                         ."has uuid $uuid!";
 896                                        }
 897
 898                                        unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
 899                                                # This branch is very strange indeed.
 900                                                fatal "merge parent $parent for $d is on branch "
 901                                                         ."$branchurl, which is not under the "
 902                                                         ."git-svn root $rooturl!";
 903                                        }
 904                                }
 905                        }
 906                }
 907        }
 908
 909        my $rewritten_parent;
 910        Git::SVN::remove_username($expect_url);
 911        if (defined($_merge_info)) {
 912                $_merge_info =~ tr{ }{\n};
 913        }
 914        while (1) {
 915                my $d = shift @$linear_refs or last;
 916                unless (defined $last_rev) {
 917                        (undef, $last_rev, undef) = cmt_metadata("$d~1");
 918                        unless (defined $last_rev) {
 919                                fatal "Unable to extract revision information ",
 920                                      "from commit $d~1";
 921                        }
 922                }
 923                if ($_dry_run) {
 924                        print "diff-tree $d~1 $d\n";
 925                } else {
 926                        my $cmt_rev;
 927
 928                        unless (defined($_merge_info) || ! $push_merge_info) {
 929                                $_merge_info = populate_merge_info($d, $gs,
 930                                                             $uuid,
 931                                                             $linear_refs,
 932                                                             $rewritten_parent);
 933                        }
 934
 935                        my %ed_opts = ( r => $last_rev,
 936                                        log => get_commit_entry($d)->{log},
 937                                        ra => Git::SVN::Ra->new($url),
 938                                        config => SVN::Core::config_get_config(
 939                                                $Git::SVN::Ra::config_dir
 940                                        ),
 941                                        tree_a => "$d~1",
 942                                        tree_b => $d,
 943                                        editor_cb => sub {
 944                                               print "Committed r$_[0]\n";
 945                                               $cmt_rev = $_[0];
 946                                        },
 947                                        mergeinfo => $_merge_info,
 948                                        svn_path => '');
 949                        if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
 950                                print "No changes\n$d~1 == $d\n";
 951                        } elsif ($parents->{$d} && @{$parents->{$d}}) {
 952                                $gs->{inject_parents_dcommit}->{$cmt_rev} =
 953                                                               $parents->{$d};
 954                        }
 955                        $_fetch_all ? $gs->fetch_all : $gs->fetch;
 956                        $last_rev = $cmt_rev;
 957                        next if $_no_rebase;
 958
 959                        # we always want to rebase against the current HEAD,
 960                        # not any head that was passed to us
 961                        my @diff = command('diff-tree', $d,
 962                                           $gs->refname, '--');
 963                        my @finish;
 964                        if (@diff) {
 965                                @finish = rebase_cmd();
 966                                print STDERR "W: $d and ", $gs->refname,
 967                                             " differ, using @finish:\n",
 968                                             join("\n", @diff), "\n";
 969                        } else {
 970                                print "No changes between current HEAD and ",
 971                                      $gs->refname,
 972                                      "\nResetting to the latest ",
 973                                      $gs->refname, "\n";
 974                                @finish = qw/reset --mixed/;
 975                        }
 976                        command_noisy(@finish, $gs->refname);
 977
 978                        $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
 979
 980                        if (@diff) {
 981                                @refs = ();
 982                                my ($url_, $rev_, $uuid_, $gs_) =
 983                                              working_head_info('HEAD', \@refs);
 984                                my ($linear_refs_, $parents_) =
 985                                              linearize_history($gs_, \@refs);
 986                                if (scalar(@$linear_refs) !=
 987                                    scalar(@$linear_refs_)) {
 988                                        fatal "# of revisions changed ",
 989                                          "\nbefore:\n",
 990                                          join("\n", @$linear_refs),
 991                                          "\n\nafter:\n",
 992                                          join("\n", @$linear_refs_), "\n",
 993                                          'If you are attempting to commit ',
 994                                          "merges, try running:\n\t",
 995                                          'git rebase --interactive',
 996                                          '--preserve-merges ',
 997                                          $gs->refname,
 998                                          "\nBefore dcommitting";
 999                                }
1000                                if ($url_ ne $expect_url) {
1001                                        if ($url_ eq $gs->metadata_url) {
1002                                                print
1003                                                  "Accepting rewritten URL:",
1004                                                  " $url_\n";
1005                                        } else {
1006                                                fatal
1007                                                  "URL mismatch after rebase:",
1008                                                  " $url_ != $expect_url";
1009                                        }
1010                                }
1011                                if ($uuid_ ne $uuid) {
1012                                        fatal "uuid mismatch after rebase: ",
1013                                              "$uuid_ != $uuid";
1014                                }
1015                                # remap parents
1016                                my (%p, @l, $i);
1017                                for ($i = 0; $i < scalar @$linear_refs; $i++) {
1018                                        my $new = $linear_refs_->[$i] or next;
1019                                        $p{$new} =
1020                                                $parents->{$linear_refs->[$i]};
1021                                        push @l, $new;
1022                                }
1023                                $parents = \%p;
1024                                $linear_refs = \@l;
1025                        }
1026                }
1027        }
1028
1029        if ($old_head) {
1030                my $new_head = command_oneline(qw/rev-parse HEAD/);
1031                my $new_is_symbolic = eval {
1032                        command_oneline(qw/symbolic-ref -q HEAD/);
1033                };
1034                if ($new_is_symbolic) {
1035                        print "dcommitted the branch ", $head, "\n";
1036                } else {
1037                        print "dcommitted on a detached HEAD because you gave ",
1038                              "a revision argument.\n",
1039                              "The rewritten commit is: ", $new_head, "\n";
1040                }
1041                command(['checkout', $old_head], STDERR => 0);
1042        }
1043
1044        unlink $gs->{index};
1045}
1046
1047sub cmd_branch {
1048        my ($branch_name, $head) = @_;
1049
1050        unless (defined $branch_name && length $branch_name) {
1051                die(($_tag ? "tag" : "branch") . " name required\n");
1052        }
1053        $head ||= 'HEAD';
1054
1055        my (undef, $rev, undef, $gs) = working_head_info($head);
1056        my $src = $gs->full_pushurl;
1057
1058        my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1059        my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1060        my $glob;
1061        if ($#{$allglobs} == 0) {
1062                $glob = $allglobs->[0];
1063        } else {
1064                unless(defined $_branch_dest) {
1065                        die "Multiple ",
1066                            $_tag ? "tag" : "branch",
1067                            " paths defined for Subversion repository.\n",
1068                            "You must specify where you want to create the ",
1069                            $_tag ? "tag" : "branch",
1070                            " with the --destination argument.\n";
1071                }
1072                foreach my $g (@{$allglobs}) {
1073                        my $re = Git::SVN::Editor::glob2pat($g->{path}->{left});
1074                        if ($_branch_dest =~ /$re/) {
1075                                $glob = $g;
1076                                last;
1077                        }
1078                }
1079                unless (defined $glob) {
1080                        my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1081                        foreach my $g (@{$allglobs}) {
1082                                $g->{path}->{left} =~ /$dest_re/ or next;
1083                                if (defined $glob) {
1084                                        die "Ambiguous destination: ",
1085                                            $_branch_dest, "\nmatches both '",
1086                                            $glob->{path}->{left}, "' and '",
1087                                            $g->{path}->{left}, "'\n";
1088                                }
1089                                $glob = $g;
1090                        }
1091                        unless (defined $glob) {
1092                                die "Unknown ",
1093                                    $_tag ? "tag" : "branch",
1094                                    " destination $_branch_dest\n";
1095                        }
1096                }
1097        }
1098        my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1099        my $url;
1100        if (defined $_commit_url) {
1101                $url = $_commit_url;
1102        } else {
1103                $url = eval { command_oneline('config', '--get',
1104                        "svn-remote.$gs->{repo_id}.commiturl") };
1105                if (!$url) {
1106                        $url = $remote->{pushurl} || $remote->{url};
1107                }
1108        }
1109        my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1110
1111        if ($dst =~ /^https:/ && $src =~ /^http:/) {
1112                $src=~s/^http:/https:/;
1113        }
1114
1115        ::_req_svn();
1116
1117        my $ctx = SVN::Client->new(
1118                auth    => Git::SVN::Ra::_auth_providers(),
1119                log_msg => sub {
1120                        ${ $_[0] } = defined $_message
1121                                ? $_message
1122                                : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1123                                . $branch_name;
1124                },
1125        );
1126
1127        eval {
1128                $ctx->ls($dst, 'HEAD', 0);
1129        } and die "branch ${branch_name} already exists\n";
1130
1131        print "Copying ${src} at r${rev} to ${dst}...\n";
1132        $ctx->copy($src, $rev, $dst)
1133                unless $_dry_run;
1134
1135        $gs->fetch_all;
1136}
1137
1138sub cmd_find_rev {
1139        my $revision_or_hash = shift or die "SVN or git revision required ",
1140                                            "as a command-line argument\n";
1141        my $result;
1142        if ($revision_or_hash =~ /^r\d+$/) {
1143                my $head = shift;
1144                $head ||= 'HEAD';
1145                my @refs;
1146                my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1147                unless ($gs) {
1148                        die "Unable to determine upstream SVN information from ",
1149                            "$head history\n";
1150                }
1151                my $desired_revision = substr($revision_or_hash, 1);
1152                $result = $gs->rev_map_get($desired_revision, $uuid);
1153        } else {
1154                my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1155                $result = $rev;
1156        }
1157        print "$result\n" if $result;
1158}
1159
1160sub auto_create_empty_directories {
1161        my ($gs) = @_;
1162        my $var = eval { command_oneline('config', '--get', '--bool',
1163                                         "svn-remote.$gs->{repo_id}.automkdirs") };
1164        # By default, create empty directories by consulting the unhandled log,
1165        # but allow setting it to 'false' to skip it.
1166        return !($var && $var eq 'false');
1167}
1168
1169sub cmd_rebase {
1170        command_noisy(qw/update-index --refresh/);
1171        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1172        unless ($gs) {
1173                die "Unable to determine upstream SVN information from ",
1174                    "working tree history\n";
1175        }
1176        if ($_dry_run) {
1177                print "Remote Branch: " . $gs->refname . "\n";
1178                print "SVN URL: " . $url . "\n";
1179                return;
1180        }
1181        if (command(qw/diff-index HEAD --/)) {
1182                print STDERR "Cannot rebase with uncommited changes:\n";
1183                command_noisy('status');
1184                exit 1;
1185        }
1186        unless ($_local) {
1187                # rebase will checkout for us, so no need to do it explicitly
1188                $_no_checkout = 'true';
1189                $_fetch_all ? $gs->fetch_all : $gs->fetch;
1190        }
1191        command_noisy(rebase_cmd(), $gs->refname);
1192        if (auto_create_empty_directories($gs)) {
1193                $gs->mkemptydirs;
1194        }
1195}
1196
1197sub cmd_show_ignore {
1198        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1199        $gs ||= Git::SVN->new;
1200        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1201        $gs->prop_walk($gs->{path}, $r, sub {
1202                my ($gs, $path, $props) = @_;
1203                print STDOUT "\n# $path\n";
1204                my $s = $props->{'svn:ignore'} or return;
1205                $s =~ s/[\r\n]+/\n/g;
1206                $s =~ s/^\n+//;
1207                chomp $s;
1208                $s =~ s#^#$path#gm;
1209                print STDOUT "$s\n";
1210        });
1211}
1212
1213sub cmd_show_externals {
1214        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1215        $gs ||= Git::SVN->new;
1216        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1217        $gs->prop_walk($gs->{path}, $r, sub {
1218                my ($gs, $path, $props) = @_;
1219                print STDOUT "\n# $path\n";
1220                my $s = $props->{'svn:externals'} or return;
1221                $s =~ s/[\r\n]+/\n/g;
1222                chomp $s;
1223                $s =~ s#^#$path#gm;
1224                print STDOUT "$s\n";
1225        });
1226}
1227
1228sub cmd_create_ignore {
1229        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1230        $gs ||= Git::SVN->new;
1231        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1232        $gs->prop_walk($gs->{path}, $r, sub {
1233                my ($gs, $path, $props) = @_;
1234                # $path is of the form /path/to/dir/
1235                $path = '.' . $path;
1236                # SVN can have attributes on empty directories,
1237                # which git won't track
1238                mkpath([$path]) unless -d $path;
1239                my $ignore = $path . '.gitignore';
1240                my $s = $props->{'svn:ignore'} or return;
1241                open(GITIGNORE, '>', $ignore)
1242                  or fatal("Failed to open `$ignore' for writing: $!");
1243                $s =~ s/[\r\n]+/\n/g;
1244                $s =~ s/^\n+//;
1245                chomp $s;
1246                # Prefix all patterns so that the ignore doesn't apply
1247                # to sub-directories.
1248                $s =~ s#^#/#gm;
1249                print GITIGNORE "$s\n";
1250                close(GITIGNORE)
1251                  or fatal("Failed to close `$ignore': $!");
1252                command_noisy('add', '-f', $ignore);
1253        });
1254}
1255
1256sub cmd_mkdirs {
1257        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1258        $gs ||= Git::SVN->new;
1259        $gs->mkemptydirs($_revision);
1260}
1261
1262sub canonicalize_path {
1263        my ($path) = @_;
1264        my $dot_slash_added = 0;
1265        if (substr($path, 0, 1) ne "/") {
1266                $path = "./" . $path;
1267                $dot_slash_added = 1;
1268        }
1269        # File::Spec->canonpath doesn't collapse x/../y into y (for a
1270        # good reason), so let's do this manually.
1271        $path =~ s#/+#/#g;
1272        $path =~ s#/\.(?:/|$)#/#g;
1273        $path =~ s#/[^/]+/\.\.##g;
1274        $path =~ s#/$##g;
1275        $path =~ s#^\./## if $dot_slash_added;
1276        $path =~ s#^/##;
1277        $path =~ s#^\.$##;
1278        return $path;
1279}
1280
1281sub canonicalize_url {
1282        my ($url) = @_;
1283        $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1284        return $url;
1285}
1286
1287# get_svnprops(PATH)
1288# ------------------
1289# Helper for cmd_propget and cmd_proplist below.
1290sub get_svnprops {
1291        my $path = shift;
1292        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1293        $gs ||= Git::SVN->new;
1294
1295        # prefix THE PATH by the sub-directory from which the user
1296        # invoked us.
1297        $path = $cmd_dir_prefix . $path;
1298        fatal("No such file or directory: $path") unless -e $path;
1299        my $is_dir = -d $path ? 1 : 0;
1300        $path = $gs->{path} . '/' . $path;
1301
1302        # canonicalize the path (otherwise libsvn will abort or fail to
1303        # find the file)
1304        $path = canonicalize_path($path);
1305
1306        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1307        my $props;
1308        if ($is_dir) {
1309                (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1310        }
1311        else {
1312                (undef, $props) = $gs->ra->get_file($path, $r, undef);
1313        }
1314        return $props;
1315}
1316
1317# cmd_propget (PROP, PATH)
1318# ------------------------
1319# Print the SVN property PROP for PATH.
1320sub cmd_propget {
1321        my ($prop, $path) = @_;
1322        $path = '.' if not defined $path;
1323        usage(1) if not defined $prop;
1324        my $props = get_svnprops($path);
1325        if (not defined $props->{$prop}) {
1326                fatal("`$path' does not have a `$prop' SVN property.");
1327        }
1328        print $props->{$prop} . "\n";
1329}
1330
1331# cmd_proplist (PATH)
1332# -------------------
1333# Print the list of SVN properties for PATH.
1334sub cmd_proplist {
1335        my $path = shift;
1336        $path = '.' if not defined $path;
1337        my $props = get_svnprops($path);
1338        print "Properties on '$path':\n";
1339        foreach (sort keys %{$props}) {
1340                print "  $_\n";
1341        }
1342}
1343
1344sub cmd_multi_init {
1345        my $url = shift;
1346        unless (defined $_trunk || @_branches || @_tags) {
1347                usage(1);
1348        }
1349
1350        $_prefix = '' unless defined $_prefix;
1351        if (defined $url) {
1352                $url = canonicalize_url($url);
1353                init_subdir(@_);
1354        }
1355        do_git_init_db();
1356        if (defined $_trunk) {
1357                $_trunk =~ s#^/+##;
1358                my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1359                # try both old-style and new-style lookups:
1360                my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1361                unless ($gs_trunk) {
1362                        my ($trunk_url, $trunk_path) =
1363                                              complete_svn_url($url, $_trunk);
1364                        $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1365                                                   undef, $trunk_ref);
1366                }
1367        }
1368        return unless @_branches || @_tags;
1369        my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1370        foreach my $path (@_branches) {
1371                complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1372        }
1373        foreach my $path (@_tags) {
1374                complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1375        }
1376}
1377
1378sub cmd_multi_fetch {
1379        $Git::SVN::no_reuse_existing = undef;
1380        my $remotes = Git::SVN::read_all_remotes();
1381        foreach my $repo_id (sort keys %$remotes) {
1382                if ($remotes->{$repo_id}->{url}) {
1383                        Git::SVN::fetch_all($repo_id, $remotes);
1384                }
1385        }
1386}
1387
1388# this command is special because it requires no metadata
1389sub cmd_commit_diff {
1390        my ($ta, $tb, $url) = @_;
1391        my $usage = "Usage: $0 commit-diff -r<revision> ".
1392                    "<tree-ish> <tree-ish> [<URL>]";
1393        fatal($usage) if (!defined $ta || !defined $tb);
1394        my $svn_path = '';
1395        if (!defined $url) {
1396                my $gs = eval { Git::SVN->new };
1397                if (!$gs) {
1398                        fatal("Needed URL or usable git-svn --id in ",
1399                              "the command-line\n", $usage);
1400                }
1401                $url = $gs->{url};
1402                $svn_path = $gs->{path};
1403        }
1404        unless (defined $_revision) {
1405                fatal("-r|--revision is a required argument\n", $usage);
1406        }
1407        if (defined $_message && defined $_file) {
1408                fatal("Both --message/-m and --file/-F specified ",
1409                      "for the commit message.\n",
1410                      "I have no idea what you mean");
1411        }
1412        if (defined $_file) {
1413                $_message = file_to_s($_file);
1414        } else {
1415                $_message ||= get_commit_entry($tb)->{log};
1416        }
1417        my $ra ||= Git::SVN::Ra->new($url);
1418        my $r = $_revision;
1419        if ($r eq 'HEAD') {
1420                $r = $ra->get_latest_revnum;
1421        } elsif ($r !~ /^\d+$/) {
1422                die "revision argument: $r not understood by git-svn\n";
1423        }
1424        my %ed_opts = ( r => $r,
1425                        log => $_message,
1426                        ra => $ra,
1427                        tree_a => $ta,
1428                        tree_b => $tb,
1429                        editor_cb => sub { print "Committed r$_[0]\n" },
1430                        svn_path => $svn_path );
1431        if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1432                print "No changes\n$ta == $tb\n";
1433        }
1434}
1435
1436sub escape_uri_only {
1437        my ($uri) = @_;
1438        my @tmp;
1439        foreach (split m{/}, $uri) {
1440                s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1441                push @tmp, $_;
1442        }
1443        join('/', @tmp);
1444}
1445
1446sub escape_url {
1447        my ($url) = @_;
1448        if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1449                my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1450                $url = "$scheme://$domain$uri";
1451        }
1452        $url;
1453}
1454
1455sub cmd_info {
1456        my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1457        my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1458        if (exists $_[1]) {
1459                die "Too many arguments specified\n";
1460        }
1461
1462        my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1463
1464        if (!$file_type && !$diff_status) {
1465                print STDERR "svn: '$path' is not under version control\n";
1466                exit 1;
1467        }
1468
1469        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1470        unless ($gs) {
1471                die "Unable to determine upstream SVN information from ",
1472                    "working tree history\n";
1473        }
1474
1475        # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1476        $path = "." if $path eq "";
1477
1478        my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1479
1480        if ($_url) {
1481                print escape_url($full_url), "\n";
1482                return;
1483        }
1484
1485        my $result = "Path: $path\n";
1486        $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1487        $result .= "URL: " . escape_url($full_url) . "\n";
1488
1489        eval {
1490                my $repos_root = $gs->repos_root;
1491                Git::SVN::remove_username($repos_root);
1492                $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1493        };
1494        if ($@) {
1495                $result .= "Repository Root: (offline)\n";
1496        }
1497        ::_req_svn();
1498        $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1499                (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
1500        $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1501
1502        $result .= "Node Kind: " .
1503                   ($file_type eq "dir" ? "directory" : "file") . "\n";
1504
1505        my $schedule = $diff_status eq "A"
1506                       ? "add"
1507                       : ($diff_status eq "D" ? "delete" : "normal");
1508        $result .= "Schedule: $schedule\n";
1509
1510        if ($diff_status eq "A") {
1511                print $result, "\n";
1512                return;
1513        }
1514
1515        my ($lc_author, $lc_rev, $lc_date_utc);
1516        my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1517        my $log = command_output_pipe(@args);
1518        my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1519        while (<$log>) {
1520                if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1521                        $lc_author = $1;
1522                        $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1523                } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
1524                        (undef, $lc_rev, undef) = ::extract_metadata($1);
1525                }
1526        }
1527        close $log;
1528
1529        Git::SVN::Log::set_local_timezone();
1530
1531        $result .= "Last Changed Author: $lc_author\n";
1532        $result .= "Last Changed Rev: $lc_rev\n";
1533        $result .= "Last Changed Date: " .
1534                   Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1535
1536        if ($file_type ne "dir") {
1537                my $text_last_updated_date =
1538                    ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1539                $result .=
1540                    "Text Last Updated: " .
1541                    Git::SVN::Log::format_svn_date($text_last_updated_date) .
1542                    "\n";
1543                my $checksum;
1544                if ($diff_status eq "D") {
1545                        my ($fh, $ctx) =
1546                            command_output_pipe(qw(cat-file blob), "HEAD:$path");
1547                        if ($file_type eq "link") {
1548                                my $file_name = <$fh>;
1549                                $checksum = md5sum("link $file_name");
1550                        } else {
1551                                $checksum = md5sum($fh);
1552                        }
1553                        command_close_pipe($fh, $ctx);
1554                } elsif ($file_type eq "link") {
1555                        my $file_name =
1556                            command(qw(cat-file blob), "HEAD:$path");
1557                        $checksum =
1558                            md5sum("link " . $file_name);
1559                } else {
1560                        open FILE, "<", $path or die $!;
1561                        $checksum = md5sum(\*FILE);
1562                        close FILE or die $!;
1563                }
1564                $result .= "Checksum: " . $checksum . "\n";
1565        }
1566
1567        print $result, "\n";
1568}
1569
1570sub cmd_reset {
1571        my $target = shift || $_revision or die "SVN revision required\n";
1572        $target = $1 if $target =~ /^r(\d+)$/;
1573        $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1574        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1575        unless ($gs) {
1576                die "Unable to determine upstream SVN information from ".
1577                    "history\n";
1578        }
1579        my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1580        die "Cannot find SVN revision $target\n" unless defined($c);
1581        $gs->rev_map_set($r, $c, 'reset', $uuid);
1582        print "r$r = $c ($gs->{ref_id})\n";
1583}
1584
1585sub cmd_gc {
1586        if (!can_compress()) {
1587                warn "Compress::Zlib could not be found; unhandled.log " .
1588                     "files will not be compressed.\n";
1589        }
1590        find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1591}
1592
1593########################### utility functions #########################
1594
1595sub rebase_cmd {
1596        my @cmd = qw/rebase/;
1597        push @cmd, '-v' if $_verbose;
1598        push @cmd, qw/--merge/ if $_merge;
1599        push @cmd, "--strategy=$_strategy" if $_strategy;
1600        push @cmd, "--preserve-merges" if $_preserve_merges;
1601        @cmd;
1602}
1603
1604sub post_fetch_checkout {
1605        return if $_no_checkout;
1606        return if verify_ref('HEAD^0');
1607        my $gs = $Git::SVN::_head or return;
1608
1609        # look for "trunk" ref if it exists
1610        my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1611        my $fetch = $remote->{fetch};
1612        if ($fetch) {
1613                foreach my $p (keys %$fetch) {
1614                        basename($fetch->{$p}) eq 'trunk' or next;
1615                        $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1616                        last;
1617                }
1618        }
1619
1620        command_noisy(qw(update-ref HEAD), $gs->refname);
1621        return unless verify_ref('HEAD^0');
1622
1623        return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1624        my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1625        return if -f $index;
1626
1627        return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1628        return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1629        command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1630        print STDERR "Checked out HEAD:\n  ",
1631                     $gs->full_url, " r", $gs->last_rev, "\n";
1632        if (auto_create_empty_directories($gs)) {
1633                $gs->mkemptydirs($gs->last_rev);
1634        }
1635}
1636
1637sub complete_svn_url {
1638        my ($url, $path) = @_;
1639        $path =~ s#/+$##;
1640        if ($path !~ m#^[a-z\+]+://#) {
1641                if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1642                        fatal("E: '$path' is not a complete URL ",
1643                              "and a separate URL is not specified");
1644                }
1645                return ($url, $path);
1646        }
1647        return ($path, '');
1648}
1649
1650sub complete_url_ls_init {
1651        my ($ra, $repo_path, $switch, $pfx) = @_;
1652        unless ($repo_path) {
1653                print STDERR "W: $switch not specified\n";
1654                return;
1655        }
1656        $repo_path =~ s#/+$##;
1657        if ($repo_path =~ m#^[a-z\+]+://#) {
1658                $ra = Git::SVN::Ra->new($repo_path);
1659                $repo_path = '';
1660        } else {
1661                $repo_path =~ s#^/+##;
1662                unless ($ra) {
1663                        fatal("E: '$repo_path' is not a complete URL ",
1664                              "and a separate URL is not specified");
1665                }
1666        }
1667        my $url = $ra->{url};
1668        my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1669        my $k = "svn-remote.$gs->{repo_id}.url";
1670        my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1671        if ($orig_url && ($orig_url ne $gs->{url})) {
1672                die "$k already set: $orig_url\n",
1673                    "wanted to set to: $gs->{url}\n";
1674        }
1675        command_oneline('config', $k, $gs->{url}) unless $orig_url;
1676        my $remote_path = "$gs->{path}/$repo_path";
1677        $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1678        $remote_path =~ s#/+#/#g;
1679        $remote_path =~ s#^/##g;
1680        $remote_path .= "/*" if $remote_path !~ /\*/;
1681        my ($n) = ($switch =~ /^--(\w+)/);
1682        if (length $pfx && $pfx !~ m#/$#) {
1683                die "--prefix='$pfx' must have a trailing slash '/'\n";
1684        }
1685        command_noisy('config',
1686                      '--add',
1687                      "svn-remote.$gs->{repo_id}.$n",
1688                      "$remote_path:refs/remotes/$pfx*" .
1689                        ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1690}
1691
1692sub verify_ref {
1693        my ($ref) = @_;
1694        eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1695                               { STDERR => 0 }); };
1696}
1697
1698sub get_tree_from_treeish {
1699        my ($treeish) = @_;
1700        # $treeish can be a symbolic ref, too:
1701        my $type = command_oneline(qw/cat-file -t/, $treeish);
1702        my $expected;
1703        while ($type eq 'tag') {
1704                ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1705        }
1706        if ($type eq 'commit') {
1707                $expected = (grep /^tree /, command(qw/cat-file commit/,
1708                                                    $treeish))[0];
1709                ($expected) = ($expected =~ /^tree ($sha1)$/o);
1710                die "Unable to get tree from $treeish\n" unless $expected;
1711        } elsif ($type eq 'tree') {
1712                $expected = $treeish;
1713        } else {
1714                die "$treeish is a $type, expected tree, tag or commit\n";
1715        }
1716        return $expected;
1717}
1718
1719sub get_commit_entry {
1720        my ($treeish) = shift;
1721        my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1722        my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1723        my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1724        open my $log_fh, '>', $commit_editmsg or croak $!;
1725
1726        my $type = command_oneline(qw/cat-file -t/, $treeish);
1727        if ($type eq 'commit' || $type eq 'tag') {
1728                my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1729                                                         $type, $treeish);
1730                my $in_msg = 0;
1731                my $author;
1732                my $saw_from = 0;
1733                my $msgbuf = "";
1734                while (<$msg_fh>) {
1735                        if (!$in_msg) {
1736                                $in_msg = 1 if (/^\s*$/);
1737                                $author = $1 if (/^author (.*>)/);
1738                        } elsif (/^git-svn-id: /) {
1739                                # skip this for now, we regenerate the
1740                                # correct one on re-fetch anyways
1741                                # TODO: set *:merge properties or like...
1742                        } else {
1743                                if (/^From:/ || /^Signed-off-by:/) {
1744                                        $saw_from = 1;
1745                                }
1746                                $msgbuf .= $_;
1747                        }
1748                }
1749                $msgbuf =~ s/\s+$//s;
1750                if ($Git::SVN::_add_author_from && defined($author)
1751                    && !$saw_from) {
1752                        $msgbuf .= "\n\nFrom: $author";
1753                }
1754                print $log_fh $msgbuf or croak $!;
1755                command_close_pipe($msg_fh, $ctx);
1756        }
1757        close $log_fh or croak $!;
1758
1759        if ($_edit || ($type eq 'tree')) {
1760                chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1761                system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1762        }
1763        rename $commit_editmsg, $commit_msg or croak $!;
1764        {
1765                require Encode;
1766                # SVN requires messages to be UTF-8 when entering the repo
1767                local $/;
1768                open $log_fh, '<', $commit_msg or croak $!;
1769                binmode $log_fh;
1770                chomp($log_entry{log} = <$log_fh>);
1771
1772                my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1773                my $msg = $log_entry{log};
1774
1775                eval { $msg = Encode::decode($enc, $msg, 1) };
1776                if ($@) {
1777                        die "Could not decode as $enc:\n", $msg,
1778                            "\nPerhaps you need to set i18n.commitencoding\n";
1779                }
1780
1781                eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1782                die "Could not encode as UTF-8:\n$msg\n" if $@;
1783
1784                $log_entry{log} = $msg;
1785
1786                close $log_fh or croak $!;
1787        }
1788        unlink $commit_msg;
1789        \%log_entry;
1790}
1791
1792sub s_to_file {
1793        my ($str, $file, $mode) = @_;
1794        open my $fd,'>',$file or croak $!;
1795        print $fd $str,"\n" or croak $!;
1796        close $fd or croak $!;
1797        chmod ($mode &~ umask, $file) if (defined $mode);
1798}
1799
1800sub file_to_s {
1801        my $file = shift;
1802        open my $fd,'<',$file or croak "$!: file: $file\n";
1803        local $/;
1804        my $ret = <$fd>;
1805        close $fd or croak $!;
1806        $ret =~ s/\s*$//s;
1807        return $ret;
1808}
1809
1810# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1811sub load_authors {
1812        open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1813        my $log = $cmd eq 'log';
1814        while (<$authors>) {
1815                chomp;
1816                next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1817                my ($user, $name, $email) = ($1, $2, $3);
1818                if ($log) {
1819                        $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1820                } else {
1821                        $users{$user} = [$name, $email];
1822                }
1823        }
1824        close $authors or croak $!;
1825}
1826
1827# convert GetOpt::Long specs for use by git-config
1828sub read_git_config {
1829        my $opts = shift;
1830        my @config_only;
1831        foreach my $o (keys %$opts) {
1832                # if we have mixedCase and a long option-only, then
1833                # it's a config-only variable that we don't need for
1834                # the command-line.
1835                push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1836                my $v = $opts->{$o};
1837                my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1838                $key =~ s/-//g;
1839                my $arg = 'git config';
1840                $arg .= ' --int' if ($o =~ /[:=]i$/);
1841                $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1842                if (ref $v eq 'ARRAY') {
1843                        chomp(my @tmp = `$arg --get-all svn.$key`);
1844                        @$v = @tmp if @tmp;
1845                } else {
1846                        chomp(my $tmp = `$arg --get svn.$key`);
1847                        if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1848                                $$v = $tmp;
1849                        }
1850                }
1851        }
1852        delete @$opts{@config_only} if @config_only;
1853}
1854
1855sub extract_metadata {
1856        my $id = shift or return (undef, undef, undef);
1857        my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1858                                                        \s([a-f\d\-]+)$/ix);
1859        if (!defined $rev || !$uuid || !$url) {
1860                # some of the original repositories I made had
1861                # identifiers like this:
1862                ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1863        }
1864        return ($url, $rev, $uuid);
1865}
1866
1867sub cmt_metadata {
1868        return extract_metadata((grep(/^git-svn-id: /,
1869                command(qw/cat-file commit/, shift)))[-1]);
1870}
1871
1872sub cmt_sha2rev_batch {
1873        my %s2r;
1874        my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1875        my $list = shift;
1876
1877        foreach my $sha (@{$list}) {
1878                my $first = 1;
1879                my $size = 0;
1880                print $out $sha, "\n";
1881
1882                while (my $line = <$in>) {
1883                        if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1884                                last;
1885                        } elsif ($first &&
1886                               $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1887                                $first = 0;
1888                                $size = $1;
1889                                next;
1890                        } elsif ($line =~ /^(git-svn-id: )/) {
1891                                my (undef, $rev, undef) =
1892                                                      extract_metadata($line);
1893                                $s2r{$sha} = $rev;
1894                        }
1895
1896                        $size -= length($line);
1897                        last if ($size == 0);
1898                }
1899        }
1900
1901        command_close_bidi_pipe($pid, $in, $out, $ctx);
1902
1903        return \%s2r;
1904}
1905
1906sub working_head_info {
1907        my ($head, $refs) = @_;
1908        my @args = qw/rev-list --first-parent --pretty=medium/;
1909        my ($fh, $ctx) = command_output_pipe(@args, $head);
1910        my $hash;
1911        my %max;
1912        while (<$fh>) {
1913                if ( m{^commit ($::sha1)$} ) {
1914                        unshift @$refs, $hash if $hash and $refs;
1915                        $hash = $1;
1916                        next;
1917                }
1918                next unless s{^\s*(git-svn-id:)}{$1};
1919                my ($url, $rev, $uuid) = extract_metadata($_);
1920                if (defined $url && defined $rev) {
1921                        next if $max{$url} and $max{$url} < $rev;
1922                        if (my $gs = Git::SVN->find_by_url($url)) {
1923                                my $c = $gs->rev_map_get($rev, $uuid);
1924                                if ($c && $c eq $hash) {
1925                                        close $fh; # break the pipe
1926                                        return ($url, $rev, $uuid, $gs);
1927                                } else {
1928                                        $max{$url} ||= $gs->rev_map_max;
1929                                }
1930                        }
1931                }
1932        }
1933        command_close_pipe($fh, $ctx);
1934        (undef, undef, undef, undef);
1935}
1936
1937sub read_commit_parents {
1938        my ($parents, $c) = @_;
1939        chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1940        $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1941        @{$parents->{$c}} = split(/ /, $p);
1942}
1943
1944sub linearize_history {
1945        my ($gs, $refs) = @_;
1946        my %parents;
1947        foreach my $c (@$refs) {
1948                read_commit_parents(\%parents, $c);
1949        }
1950
1951        my @linear_refs;
1952        my %skip = ();
1953        my $last_svn_commit = $gs->last_commit;
1954        foreach my $c (reverse @$refs) {
1955                next if $c eq $last_svn_commit;
1956                last if $skip{$c};
1957
1958                unshift @linear_refs, $c;
1959                $skip{$c} = 1;
1960
1961                # we only want the first parent to diff against for linear
1962                # history, we save the rest to inject when we finalize the
1963                # svn commit
1964                my $fp_a = verify_ref("$c~1");
1965                my $fp_b = shift @{$parents{$c}} if $parents{$c};
1966                if (!$fp_a || !$fp_b) {
1967                        die "Commit $c\n",
1968                            "has no parent commit, and therefore ",
1969                            "nothing to diff against.\n",
1970                            "You should be working from a repository ",
1971                            "originally created by git-svn\n";
1972                }
1973                if ($fp_a ne $fp_b) {
1974                        die "$c~1 = $fp_a, however parsing commit $c ",
1975                            "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1976                }
1977
1978                foreach my $p (@{$parents{$c}}) {
1979                        $skip{$p} = 1;
1980                }
1981        }
1982        (\@linear_refs, \%parents);
1983}
1984
1985sub find_file_type_and_diff_status {
1986        my ($path) = @_;
1987        return ('dir', '') if $path eq '';
1988
1989        my $diff_output =
1990            command_oneline(qw(diff --cached --name-status --), $path) || "";
1991        my $diff_status = (split(' ', $diff_output))[0] || "";
1992
1993        my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1994
1995        return (undef, undef) if !$diff_status && !$ls_tree;
1996
1997        if ($diff_status eq "A") {
1998                return ("link", $diff_status) if -l $path;
1999                return ("dir", $diff_status) if -d $path;
2000                return ("file", $diff_status);
2001        }
2002
2003        my $mode = (split(' ', $ls_tree))[0] || "";
2004
2005        return ("link", $diff_status) if $mode eq "120000";
2006        return ("dir", $diff_status) if $mode eq "040000";
2007        return ("file", $diff_status);
2008}
2009
2010sub md5sum {
2011        my $arg = shift;
2012        my $ref = ref $arg;
2013        my $md5 = Digest::MD5->new();
2014        if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
2015                $md5->addfile($arg) or croak $!;
2016        } elsif ($ref eq 'SCALAR') {
2017                $md5->add($$arg) or croak $!;
2018        } elsif (!$ref) {
2019                $md5->add($arg) or croak $!;
2020        } else {
2021                fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2022        }
2023        return $md5->hexdigest();
2024}
2025
2026sub gc_directory {
2027        if (can_compress() && -f $_ && basename($_) eq "unhandled.log") {
2028                my $out_filename = $_ . ".gz";
2029                open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2030                binmode $in_fh;
2031                my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2032                                die "Unable to open $out_filename: $!\n";
2033
2034                my $res;
2035                while ($res = sysread($in_fh, my $str, 1024)) {
2036                        $gz->gzwrite($str) or
2037                                die "Unable to write: ".$gz->gzerror()."!\n";
2038                }
2039                unlink $_ or die "unlink $File::Find::name: $!\n";
2040        } elsif (-f $_ && basename($_) eq "index") {
2041                unlink $_ or die "unlink $_: $!\n";
2042        }
2043}
2044
2045
2046package Git::SVN::Log;
2047use strict;
2048use warnings;
2049use Git::SVN::Utils qw(fatal);
2050use POSIX qw/strftime/;
2051use constant commit_log_separator => ('-' x 72) . "\n";
2052use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2053            %rusers $show_commit $incremental/;
2054my $l_fmt;
2055
2056sub cmt_showable {
2057        my ($c) = @_;
2058        return 1 if defined $c->{r};
2059
2060        # big commit message got truncated by the 16k pretty buffer in rev-list
2061        if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2062                                $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2063                @{$c->{l}} = ();
2064                my @log = command(qw/cat-file commit/, $c->{c});
2065
2066                # shift off the headers
2067                shift @log while ($log[0] ne '');
2068                shift @log;
2069
2070                # TODO: make $c->{l} not have a trailing newline in the future
2071                @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
2072
2073                (undef, $c->{r}, undef) = ::extract_metadata(
2074                                (grep(/^git-svn-id: /, @log))[-1]);
2075        }
2076        return defined $c->{r};
2077}
2078
2079sub log_use_color {
2080        return $color || Git->repository->get_colorbool('color.diff');
2081}
2082
2083sub git_svn_log_cmd {
2084        my ($r_min, $r_max, @args) = @_;
2085        my $head = 'HEAD';
2086        my (@files, @log_opts);
2087        foreach my $x (@args) {
2088                if ($x eq '--' || @files) {
2089                        push @files, $x;
2090                } else {
2091                        if (::verify_ref("$x^0")) {
2092                                $head = $x;
2093                        } else {
2094                                push @log_opts, $x;
2095                        }
2096                }
2097        }
2098
2099        my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
2100        $gs ||= Git::SVN->_new;
2101        my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2102                   $gs->refname);
2103        push @cmd, '-r' unless $non_recursive;
2104        push @cmd, qw/--raw --name-status/ if $verbose;
2105        push @cmd, '--color' if log_use_color();
2106        push @cmd, @log_opts;
2107        if (defined $r_max && $r_max == $r_min) {
2108                push @cmd, '--max-count=1';
2109                if (my $c = $gs->rev_map_get($r_max)) {
2110                        push @cmd, $c;
2111                }
2112        } elsif (defined $r_max) {
2113                if ($r_max < $r_min) {
2114                        ($r_min, $r_max) = ($r_max, $r_min);
2115                }
2116                my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
2117                my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
2118                # If there are no commits in the range, both $c_max and $c_min
2119                # will be undefined.  If there is at least 1 commit in the
2120                # range, both will be defined.
2121                return () if !defined $c_min || !defined $c_max;
2122                if ($c_min eq $c_max) {
2123                        push @cmd, '--max-count=1', $c_min;
2124                } else {
2125                        push @cmd, '--boundary', "$c_min..$c_max";
2126                }
2127        }
2128        return (@cmd, @files);
2129}
2130
2131# adapted from pager.c
2132sub config_pager {
2133        if (! -t *STDOUT) {
2134                $ENV{GIT_PAGER_IN_USE} = 'false';
2135                $pager = undef;
2136                return;
2137        }
2138        chomp($pager = command_oneline(qw(var GIT_PAGER)));
2139        if ($pager eq 'cat') {
2140                $pager = undef;
2141        }
2142        $ENV{GIT_PAGER_IN_USE} = defined($pager);
2143}
2144
2145sub run_pager {
2146        return unless defined $pager;
2147        pipe my ($rfd, $wfd) or return;
2148        defined(my $pid = fork) or fatal "Can't fork: $!";
2149        if (!$pid) {
2150                open STDOUT, '>&', $wfd or
2151                                     fatal "Can't redirect to stdout: $!";
2152                return;
2153        }
2154        open STDIN, '<&', $rfd or fatal "Can't redirect stdin: $!";
2155        $ENV{LESS} ||= 'FRSX';
2156        exec $pager or fatal "Can't run pager: $! ($pager)";
2157}
2158
2159sub format_svn_date {
2160        my $t = shift || time;
2161        my $gmoff = Git::SVN::get_tz($t);
2162        return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
2163}
2164
2165sub parse_git_date {
2166        my ($t, $tz) = @_;
2167        # Date::Parse isn't in the standard Perl distro :(
2168        if ($tz =~ s/^\+//) {
2169                $t += tz_to_s_offset($tz);
2170        } elsif ($tz =~ s/^\-//) {
2171                $t -= tz_to_s_offset($tz);
2172        }
2173        return $t;
2174}
2175
2176sub set_local_timezone {
2177        if (defined $TZ) {
2178                $ENV{TZ} = $TZ;
2179        } else {
2180                delete $ENV{TZ};
2181        }
2182}
2183
2184sub tz_to_s_offset {
2185        my ($tz) = @_;
2186        $tz =~ s/(\d\d)$//;
2187        return ($1 * 60) + ($tz * 3600);
2188}
2189
2190sub get_author_info {
2191        my ($dest, $author, $t, $tz) = @_;
2192        $author =~ s/(?:^\s*|\s*$)//g;
2193        $dest->{a_raw} = $author;
2194        my $au;
2195        if ($::_authors) {
2196                $au = $rusers{$author} || undef;
2197        }
2198        if (!$au) {
2199                ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2200        }
2201        $dest->{t} = $t;
2202        $dest->{tz} = $tz;
2203        $dest->{a} = $au;
2204        $dest->{t_utc} = parse_git_date($t, $tz);
2205}
2206
2207sub process_commit {
2208        my ($c, $r_min, $r_max, $defer) = @_;
2209        if (defined $r_min && defined $r_max) {
2210                if ($r_min == $c->{r} && $r_min == $r_max) {
2211                        show_commit($c);
2212                        return 0;
2213                }
2214                return 1 if $r_min == $r_max;
2215                if ($r_min < $r_max) {
2216                        # we need to reverse the print order
2217                        return 0 if (defined $limit && --$limit < 0);
2218                        push @$defer, $c;
2219                        return 1;
2220                }
2221                if ($r_min != $r_max) {
2222                        return 1 if ($r_min < $c->{r});
2223                        return 1 if ($r_max > $c->{r});
2224                }
2225        }
2226        return 0 if (defined $limit && --$limit < 0);
2227        show_commit($c);
2228        return 1;
2229}
2230
2231sub show_commit {
2232        my $c = shift;
2233        if ($oneline) {
2234                my $x = "\n";
2235                if (my $l = $c->{l}) {
2236                        while ($l->[0] =~ /^\s*$/) { shift @$l }
2237                        $x = $l->[0];
2238                }
2239                $l_fmt ||= 'A' . length($c->{r});
2240                print 'r',pack($l_fmt, $c->{r}),' | ';
2241                print "$c->{c} | " if $show_commit;
2242                print $x;
2243        } else {
2244                show_commit_normal($c);
2245        }
2246}
2247
2248sub show_commit_changed_paths {
2249        my ($c) = @_;
2250        return unless $c->{changed};
2251        print "Changed paths:\n", @{$c->{changed}};
2252}
2253
2254sub show_commit_normal {
2255        my ($c) = @_;
2256        print commit_log_separator, "r$c->{r} | ";
2257        print "$c->{c} | " if $show_commit;
2258        print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
2259        my $nr_line = 0;
2260
2261        if (my $l = $c->{l}) {
2262                while ($l->[$#$l] eq "\n" && $#$l > 0
2263                                          && $l->[($#$l - 1)] eq "\n") {
2264                        pop @$l;
2265                }
2266                $nr_line = scalar @$l;
2267                if (!$nr_line) {
2268                        print "1 line\n\n\n";
2269                } else {
2270                        if ($nr_line == 1) {
2271                                $nr_line = '1 line';
2272                        } else {
2273                                $nr_line .= ' lines';
2274                        }
2275                        print $nr_line, "\n";
2276                        show_commit_changed_paths($c);
2277                        print "\n";
2278                        print $_ foreach @$l;
2279                }
2280        } else {
2281                print "1 line\n";
2282                show_commit_changed_paths($c);
2283                print "\n";
2284
2285        }
2286        foreach my $x (qw/raw stat diff/) {
2287                if ($c->{$x}) {
2288                        print "\n";
2289                        print $_ foreach @{$c->{$x}}
2290                }
2291        }
2292}
2293
2294sub cmd_show_log {
2295        my (@args) = @_;
2296        my ($r_min, $r_max);
2297        my $r_last = -1; # prevent dupes
2298        set_local_timezone();
2299        if (defined $::_revision) {
2300                if ($::_revision =~ /^(\d+):(\d+)$/) {
2301                        ($r_min, $r_max) = ($1, $2);
2302                } elsif ($::_revision =~ /^\d+$/) {
2303                        $r_min = $r_max = $::_revision;
2304                } else {
2305                        fatal "-r$::_revision is not supported, use ",
2306                                "standard 'git log' arguments instead";
2307                }
2308        }
2309
2310        config_pager();
2311        @args = git_svn_log_cmd($r_min, $r_max, @args);
2312        if (!@args) {
2313                print commit_log_separator unless $incremental || $oneline;
2314                return;
2315        }
2316        my $log = command_output_pipe(@args);
2317        run_pager();
2318        my (@k, $c, $d, $stat);
2319        my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2320        while (<$log>) {
2321                if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
2322                        my $cmt = $1;
2323                        if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2324                                $r_last = $c->{r};
2325                                process_commit($c, $r_min, $r_max, \@k) or
2326                                                                goto out;
2327                        }
2328                        $d = undef;
2329                        $c = { c => $cmt };
2330                } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2331                        get_author_info($c, $1, $2, $3);
2332                } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2333                        # ignore
2334                } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2335                        push @{$c->{raw}}, $_;
2336                } elsif (/^${esc_color}[ACRMDT]\t/) {
2337                        # we could add $SVN->{svn_path} here, but that requires
2338                        # remote access at the moment (repo_path_split)...
2339                        s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
2340                        push @{$c->{changed}}, $_;
2341                } elsif (/^${esc_color}diff /o) {
2342                        $d = 1;
2343                        push @{$c->{diff}}, $_;
2344                } elsif ($d) {
2345                        push @{$c->{diff}}, $_;
2346                } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
2347                          $esc_color*[\+\-]*$esc_color$/x) {
2348                        $stat = 1;
2349                        push @{$c->{stat}}, $_;
2350                } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
2351                        push @{$c->{stat}}, $_;
2352                        $stat = undef;
2353                } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
2354                        ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2355                } elsif (s/^${esc_color}    //o) {
2356                        push @{$c->{l}}, $_;
2357                }
2358        }
2359        if ($c && defined $c->{r} && $c->{r} != $r_last) {
2360                $r_last = $c->{r};
2361                process_commit($c, $r_min, $r_max, \@k);
2362        }
2363        if (@k) {
2364                ($r_min, $r_max) = ($r_max, $r_min);
2365                process_commit($_, $r_min, $r_max) foreach reverse @k;
2366        }
2367out:
2368        close $log;
2369        print commit_log_separator unless $incremental || $oneline;
2370}
2371
2372sub cmd_blame {
2373        my $path = pop;
2374
2375        config_pager();
2376        run_pager();
2377
2378        my ($fh, $ctx, $rev);
2379
2380        if ($_git_format) {
2381                ($fh, $ctx) = command_output_pipe('blame', @_, $path);
2382                while (my $line = <$fh>) {
2383                        if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
2384                                # Uncommitted edits show up as a rev ID of
2385                                # all zeros, which we can't look up with
2386                                # cmt_metadata
2387                                if ($1 !~ /^0+$/) {
2388                                        (undef, $rev, undef) =
2389                                                ::cmt_metadata($1);
2390                                        $rev = '0' if (!$rev);
2391                                } else {
2392                                        $rev = '0';
2393                                }
2394                                $rev = sprintf('%-10s', $rev);
2395                                $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
2396                        }
2397                        print $line;
2398                }
2399        } else {
2400                ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
2401                                                  '--', $path);
2402                my ($sha1);
2403                my %authors;
2404                my @buffer;
2405                my %dsha; #distinct sha keys
2406
2407                while (my $line = <$fh>) {
2408                        push @buffer, $line;
2409                        if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
2410                                $dsha{$1} = 1;
2411                        }
2412                }
2413
2414                my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
2415
2416                foreach my $line (@buffer) {
2417                        if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
2418                                $rev = $s2r->{$1};
2419                                $rev = '0' if (!$rev)
2420                        }
2421                        elsif ($line =~ /^author (.*)/) {
2422                                $authors{$rev} = $1;
2423                                $authors{$rev} =~ s/\s/_/g;
2424                        }
2425                        elsif ($line =~ /^\t(.*)$/) {
2426                                printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
2427                        }
2428                }
2429        }
2430        command_close_pipe($fh, $ctx);
2431}
2432
2433package Git::SVN::Migration;
2434# these version numbers do NOT correspond to actual version numbers
2435# of git nor git-svn.  They are just relative.
2436#
2437# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2438#
2439# v1 layout: .git/$id/info/url, refs/remotes/$id
2440#
2441# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2442#
2443# v3 layout: .git/svn/$id, refs/remotes/$id
2444#            - info/url may remain for backwards compatibility
2445#            - this is what we migrate up to this layout automatically,
2446#            - this will be used by git svn init on single branches
2447# v3.1 layout (auto migrated):
2448#            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
2449#              for backwards compatibility
2450#
2451# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2452#            - this is only created for newly multi-init-ed
2453#              repositories.  Similar in spirit to the
2454#              --use-separate-remotes option in git-clone (now default)
2455#            - we do not automatically migrate to this (following
2456#              the example set by core git)
2457#
2458# v5 layout: .rev_db.$UUID => .rev_map.$UUID
2459#            - newer, more-efficient format that uses 24-bytes per record
2460#              with no filler space.
2461#            - use xxd -c24 < .rev_map.$UUID to view and debug
2462#            - This is a one-way migration, repositories updated to the
2463#              new format will not be able to use old git-svn without
2464#              rebuilding the .rev_db.  Rebuilding the rev_db is not
2465#              possible if noMetadata or useSvmProps are set; but should
2466#              be no problem for users that use the (sensible) defaults.
2467use strict;
2468use warnings;
2469use Carp qw/croak/;
2470use File::Path qw/mkpath/;
2471use File::Basename qw/dirname basename/;
2472use vars qw/$_minimize/;
2473
2474sub migrate_from_v0 {
2475        my $git_dir = $ENV{GIT_DIR};
2476        return undef unless -d $git_dir;
2477        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2478        my $migrated = 0;
2479        while (<$fh>) {
2480                chomp;
2481                my ($id, $orig_ref) = ($_, $_);
2482                next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2483                next unless -f "$git_dir/$id/info/url";
2484                my $new_ref = "refs/remotes/$id";
2485                if (::verify_ref("$new_ref^0")) {
2486                        print STDERR "W: $orig_ref is probably an old ",
2487                                     "branch used by an ancient version of ",
2488                                     "git-svn.\n",
2489                                     "However, $new_ref also exists.\n",
2490                                     "We will not be able ",
2491                                     "to use this branch until this ",
2492                                     "ambiguity is resolved.\n";
2493                        next;
2494                }
2495                print STDERR "Migrating from v0 layout...\n" if !$migrated;
2496                print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2497                command_noisy('update-ref', $new_ref, $orig_ref);
2498                command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2499                $migrated++;
2500        }
2501        command_close_pipe($fh, $ctx);
2502        print STDERR "Done migrating from v0 layout...\n" if $migrated;
2503        $migrated;
2504}
2505
2506sub migrate_from_v1 {
2507        my $git_dir = $ENV{GIT_DIR};
2508        my $migrated = 0;
2509        return $migrated unless -d $git_dir;
2510        my $svn_dir = "$git_dir/svn";
2511
2512        # just in case somebody used 'svn' as their $id at some point...
2513        return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2514
2515        print STDERR "Migrating from a git-svn v1 layout...\n";
2516        mkpath([$svn_dir]);
2517        print STDERR "Data from a previous version of git-svn exists, but\n\t",
2518                     "$svn_dir\n\t(required for this version ",
2519                     "($::VERSION) of git-svn) does not exist.\n";
2520        my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2521        while (<$fh>) {
2522                my $x = $_;
2523                next unless $x =~ s#^refs/remotes/##;
2524                chomp $x;
2525                next unless -f "$git_dir/$x/info/url";
2526                my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2527                next unless $u;
2528                my $dn = dirname("$git_dir/svn/$x");
2529                mkpath([$dn]) unless -d $dn;
2530                if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2531                        mkpath(["$git_dir/svn/svn"]);
2532                        print STDERR " - $git_dir/$x/info => ",
2533                                        "$git_dir/svn/$x/info\n";
2534                        rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2535                               croak "$!: $x";
2536                        # don't worry too much about these, they probably
2537                        # don't exist with repos this old (save for index,
2538                        # and we can easily regenerate that)
2539                        foreach my $f (qw/unhandled.log index .rev_db/) {
2540                                rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2541                        }
2542                } else {
2543                        print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2544                        rename "$git_dir/$x", "$git_dir/svn/$x" or
2545                               croak "$!: $x";
2546                }
2547                $migrated++;
2548        }
2549        command_close_pipe($fh, $ctx);
2550        print STDERR "Done migrating from a git-svn v1 layout\n";
2551        $migrated;
2552}
2553
2554sub read_old_urls {
2555        my ($l_map, $pfx, $path) = @_;
2556        my @dir;
2557        foreach (<$path/*>) {
2558                if (-r "$_/info/url") {
2559                        $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2560                        my $ref_id = $pfx . basename $_;
2561                        my $url = ::file_to_s("$_/info/url");
2562                        $l_map->{$ref_id} = $url;
2563                } elsif (-d $_) {
2564                        push @dir, $_;
2565                }
2566        }
2567        foreach (@dir) {
2568                my $x = $_;
2569                $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2570                read_old_urls($l_map, $x, $_);
2571        }
2572}
2573
2574sub migrate_from_v2 {
2575        my @cfg = command(qw/config -l/);
2576        return if grep /^svn-remote\..+\.url=/, @cfg;
2577        my %l_map;
2578        read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2579        my $migrated = 0;
2580
2581        foreach my $ref_id (sort keys %l_map) {
2582                eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
2583                if ($@) {
2584                        Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2585                }
2586                $migrated++;
2587        }
2588        $migrated;
2589}
2590
2591sub minimize_connections {
2592        my $r = Git::SVN::read_all_remotes();
2593        my $new_urls = {};
2594        my $root_repos = {};
2595        foreach my $repo_id (keys %$r) {
2596                my $url = $r->{$repo_id}->{url} or next;
2597                my $fetch = $r->{$repo_id}->{fetch} or next;
2598                my $ra = Git::SVN::Ra->new($url);
2599
2600                # skip existing cases where we already connect to the root
2601                if (($ra->{url} eq $ra->{repos_root}) ||
2602                    ($ra->{repos_root} eq $repo_id)) {
2603                        $root_repos->{$ra->{url}} = $repo_id;
2604                        next;
2605                }
2606
2607                my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
2608                my $root_path = $ra->{url};
2609                $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
2610                foreach my $path (keys %$fetch) {
2611                        my $ref_id = $fetch->{$path};
2612                        my $gs = Git::SVN->new($ref_id, $repo_id, $path);
2613
2614                        # make sure we can read when connecting to
2615                        # a higher level of a repository
2616                        my ($last_rev, undef) = $gs->last_rev_commit;
2617                        if (!defined $last_rev) {
2618                                $last_rev = eval {
2619                                        $root_ra->get_latest_revnum;
2620                                };
2621                                next if $@;
2622                        }
2623                        my $new = $root_path;
2624                        $new .= length $path ? "/$path" : '';
2625                        eval {
2626                                $root_ra->get_log([$new], $last_rev, $last_rev,
2627                                                  0, 0, 1, sub { });
2628                        };
2629                        next if $@;
2630                        $new_urls->{$ra->{repos_root}}->{$new} =
2631                                { ref_id => $ref_id,
2632                                  old_repo_id => $repo_id,
2633                                  old_path => $path };
2634                }
2635        }
2636
2637        my @emptied;
2638        foreach my $url (keys %$new_urls) {
2639                # see if we can re-use an existing [svn-remote "repo_id"]
2640                # instead of creating a(n ugly) new section:
2641                my $repo_id = $root_repos->{$url} || $url;
2642
2643                my $fetch = $new_urls->{$url};
2644                foreach my $path (keys %$fetch) {
2645                        my $x = $fetch->{$path};
2646                        Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
2647                        my $pfx = "svn-remote.$x->{old_repo_id}";
2648
2649                        my $old_fetch = quotemeta("$x->{old_path}:".
2650                                                  "$x->{ref_id}");
2651                        command_noisy(qw/config --unset/,
2652                                      "$pfx.fetch", '^'. $old_fetch . '$');
2653                        delete $r->{$x->{old_repo_id}}->
2654                               {fetch}->{$x->{old_path}};
2655                        if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
2656                                command_noisy(qw/config --unset/,
2657                                              "$pfx.url");
2658                                push @emptied, $x->{old_repo_id}
2659                        }
2660                }
2661        }
2662        if (@emptied) {
2663                my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
2664                print STDERR <<EOF;
2665The following [svn-remote] sections in your config file ($file) are empty
2666and can be safely removed:
2667EOF
2668                print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
2669        }
2670}
2671
2672sub migration_check {
2673        migrate_from_v0();
2674        migrate_from_v1();
2675        migrate_from_v2();
2676        minimize_connections() if $_minimize;
2677}
2678
2679package Git::IndexInfo;
2680use strict;
2681use warnings;
2682use Git qw/command_input_pipe command_close_pipe/;
2683
2684sub new {
2685        my ($class) = @_;
2686        my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
2687        bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
2688}
2689
2690sub remove {
2691        my ($self, $path) = @_;
2692        if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
2693                return ++$self->{nr};
2694        }
2695        undef;
2696}
2697
2698sub update {
2699        my ($self, $mode, $hash, $path) = @_;
2700        if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
2701                return ++$self->{nr};
2702        }
2703        undef;
2704}
2705
2706sub DESTROY {
2707        my ($self) = @_;
2708        command_close_pipe($self->{gui}, $self->{ctx});
2709}
2710
2711package Git::SVN::GlobSpec;
2712use strict;
2713use warnings;
2714
2715sub new {
2716        my ($class, $glob, $pattern_ok) = @_;
2717        my $re = $glob;
2718        $re =~ s!/+$!!g; # no need for trailing slashes
2719        my (@left, @right, @patterns);
2720        my $state = "left";
2721        my $die_msg = "Only one set of wildcard directories " .
2722                                "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
2723        for my $part (split(m|/|, $glob)) {
2724                if ($part =~ /\*/ && $part ne "*") {
2725                        die "Invalid pattern in '$glob': $part\n";
2726                } elsif ($pattern_ok && $part =~ /[{}]/ &&
2727                         $part !~ /^\{[^{}]+\}/) {
2728                        die "Invalid pattern in '$glob': $part\n";
2729                }
2730                if ($part eq "*") {
2731                        die $die_msg if $state eq "right";
2732                        $state = "pattern";
2733                        push(@patterns, "[^/]*");
2734                } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
2735                        die $die_msg if $state eq "right";
2736                        $state = "pattern";
2737                        my $p = quotemeta($1);
2738                        $p =~ s/\\,/|/g;
2739                        push(@patterns, "(?:$p)");
2740                } else {
2741                        if ($state eq "left") {
2742                                push(@left, $part);
2743                        } else {
2744                                push(@right, $part);
2745                                $state = "right";
2746                        }
2747                }
2748        }
2749        my $depth = @patterns;
2750        if ($depth == 0) {
2751                die "One '*' is needed in glob: '$glob'\n";
2752        }
2753        my $left = join('/', @left);
2754        my $right = join('/', @right);
2755        $re = join('/', @patterns);
2756        $re = join('\/',
2757                   grep(length, quotemeta($left), "($re)", quotemeta($right)));
2758        my $left_re = qr/^\/\Q$left\E(\/|$)/;
2759        bless { left => $left, right => $right, left_regex => $left_re,
2760                regex => qr/$re/, glob => $glob, depth => $depth }, $class;
2761}
2762
2763sub full_path {
2764        my ($self, $path) = @_;
2765        return (length $self->{left} ? "$self->{left}/" : '') .
2766               $path . (length $self->{right} ? "/$self->{right}" : '');
2767}
2768
2769__END__
2770
2771Data structures:
2772
2773
2774$remotes = { # returned by read_all_remotes()
2775        'svn' => {
2776                # svn-remote.svn.url=https://svn.musicpd.org
2777                url => 'https://svn.musicpd.org',
2778                # svn-remote.svn.fetch=mpd/trunk:trunk
2779                fetch => {
2780                        'mpd/trunk' => 'trunk',
2781                },
2782                # svn-remote.svn.tags=mpd/tags/*:tags/*
2783                tags => {
2784                        path => {
2785                                left => 'mpd/tags',
2786                                right => '',
2787                                regex => qr!mpd/tags/([^/]+)$!,
2788                                glob => 'tags/*',
2789                        },
2790                        ref => {
2791                                left => 'tags',
2792                                right => '',
2793                                regex => qr!tags/([^/]+)$!,
2794                                glob => 'tags/*',
2795                        },
2796                }
2797        }
2798};
2799
2800$log_entry hashref as returned by libsvn_log_entry()
2801{
2802        log => 'whitespace-formatted log entry
2803',                                              # trailing newline is preserved
2804        revision => '8',                        # integer
2805        date => '2004-02-24T17:01:44.108345Z',  # commit date
2806        author => 'committer name'
2807};
2808
2809
2810# this is generated by generate_diff();
2811@mods = array of diff-index line hashes, each element represents one line
2812        of diff-index output
2813
2814diff-index line ($m hash)
2815{
2816        mode_a => first column of diff-index output, no leading ':',
2817        mode_b => second column of diff-index output,
2818        sha1_b => sha1sum of the final blob,
2819        chg => change type [MCRADT],
2820        file_a => original file name of a file (iff chg is 'C' or 'R')
2821        file_b => new/current file name of a file (any chg)
2822}
2823;
2824
2825# retval of read_url_paths{,_all}();
2826$l_map = {
2827        # repository root url
2828        'https://svn.musicpd.org' => {
2829                # repository path               # GIT_SVN_ID
2830                'mpd/trunk'             =>      'trunk',
2831                'mpd/tags/0.11.5'       =>      'tags/0.11.5',
2832        },
2833}
2834
2835Notes:
2836        I don't trust the each() function on unless I created %hash myself
2837        because the internal iterator may not have started at base.