git-svn.perlon commit git-svn: canonicalize earlier (8266fc8)
   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 Carp qw/croak/;
  14use Digest::MD5;
  15use IO::File qw//;
  16use File::Basename qw/dirname basename/;
  17use File::Path qw/mkpath/;
  18use File::Spec;
  19use File::Find;
  20use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
  21use IPC::Open3;
  22use Memoize;
  23
  24use Git::SVN;
  25use Git::SVN::Editor;
  26use Git::SVN::Fetcher;
  27use Git::SVN::Ra;
  28use Git::SVN::Prompt;
  29use Git::SVN::Log;
  30use Git::SVN::Migration;
  31
  32use Git::SVN::Utils qw(
  33        fatal
  34        can_compress
  35        canonicalize_path
  36        canonicalize_url
  37        join_paths
  38);
  39
  40use Git qw(
  41        git_cmd_try
  42        command
  43        command_oneline
  44        command_noisy
  45        command_output_pipe
  46        command_close_pipe
  47        command_bidi_pipe
  48        command_close_bidi_pipe
  49);
  50
  51BEGIN {
  52        Memoize::memoize 'Git::config';
  53        Memoize::memoize 'Git::config_bool';
  54}
  55
  56
  57# From which subdir have we been invoked?
  58my $cmd_dir_prefix = eval {
  59        command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
  60} || '';
  61
  62my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
  63$ENV{GIT_DIR} ||= '.git';
  64$Git::SVN::Ra::_log_window_size = 100;
  65
  66if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
  67        $ENV{SVN_SSH} = $ENV{GIT_SSH};
  68}
  69
  70if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
  71        $ENV{SVN_SSH} =~ s/\\/\\\\/g;
  72        $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
  73}
  74
  75$Git::SVN::Log::TZ = $ENV{TZ};
  76$ENV{TZ} = 'UTC';
  77$| = 1; # unbuffer STDOUT
  78
  79# All SVN commands do it.  Otherwise we may die on SIGPIPE when the remote
  80# repository decides to close the connection which we expect to be kept alive.
  81$SIG{PIPE} = 'IGNORE';
  82
  83# Given a dot separated version number, "subtract" it from
  84# the SVN::Core::VERSION; non-negaitive return means the SVN::Core
  85# is at least at the version the caller asked for.
  86sub compare_svn_version {
  87        my (@ours) = split(/\./, $SVN::Core::VERSION);
  88        my (@theirs) = split(/\./, $_[0]);
  89        my ($i, $diff);
  90
  91        for ($i = 0; $i < @ours && $i < @theirs; $i++) {
  92                $diff = $ours[$i] - $theirs[$i];
  93                return $diff if ($diff);
  94        }
  95        return 1 if ($i < @ours);
  96        return -1 if ($i < @theirs);
  97        return 0;
  98}
  99
 100sub _req_svn {
 101        require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
 102        require SVN::Ra;
 103        require SVN::Delta;
 104        if (::compare_svn_version('1.1.0') < 0) {
 105                fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
 106        }
 107}
 108
 109$sha1 = qr/[a-f\d]{40}/;
 110$sha1_short = qr/[a-f\d]{4,40}/;
 111my ($_stdin, $_help, $_edit,
 112        $_message, $_file, $_branch_dest,
 113        $_template, $_shared,
 114        $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
 115        $_merge, $_strategy, $_preserve_merges, $_dry_run, $_local,
 116        $_prefix, $_no_checkout, $_url, $_verbose,
 117        $_commit_url, $_tag, $_merge_info, $_interactive);
 118
 119# This is a refactoring artifact so Git::SVN can get at this git-svn switch.
 120sub opt_prefix { return $_prefix || '' }
 121
 122$Git::SVN::Fetcher::_placeholder_filename = ".gitignore";
 123$_q ||= 0;
 124my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
 125                    'config-dir=s' => \$Git::SVN::Ra::config_dir,
 126                    'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
 127                    'ignore-paths=s' => \$Git::SVN::Fetcher::_ignore_regex,
 128                    'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
 129my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
 130                'authors-file|A=s' => \$_authors,
 131                'authors-prog=s' => \$_authors_prog,
 132                'repack:i' => \$Git::SVN::_repack,
 133                'noMetadata' => \$Git::SVN::_no_metadata,
 134                'useSvmProps' => \$Git::SVN::_use_svm_props,
 135                'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
 136                'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
 137                'no-checkout' => \$_no_checkout,
 138                'quiet|q+' => \$_q,
 139                'repack-flags|repack-args|repack-opts=s' =>
 140                   \$Git::SVN::_repack_flags,
 141                'use-log-author' => \$Git::SVN::_use_log_author,
 142                'add-author-from' => \$Git::SVN::_add_author_from,
 143                'localtime' => \$Git::SVN::_localtime,
 144                %remote_opts );
 145
 146my ($_trunk, @_tags, @_branches, $_stdlayout);
 147my %icv;
 148my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
 149                  'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
 150                  'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
 151                  'stdlayout|s' => \$_stdlayout,
 152                  'minimize-url|m!' => \$Git::SVN::_minimize_url,
 153                  'no-metadata' => sub { $icv{noMetadata} = 1 },
 154                  'use-svm-props' => sub { $icv{useSvmProps} = 1 },
 155                  'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
 156                  'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
 157                  'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
 158                  %remote_opts );
 159my %cmt_opts = ( 'edit|e' => \$_edit,
 160                'rmdir' => \$Git::SVN::Editor::_rmdir,
 161                'find-copies-harder' => \$Git::SVN::Editor::_find_copies_harder,
 162                'l=i' => \$Git::SVN::Editor::_rename_limit,
 163                'copy-similarity|C=i'=> \$Git::SVN::Editor::_cp_similarity
 164);
 165
 166my %cmd = (
 167        fetch => [ \&cmd_fetch, "Download new revisions from SVN",
 168                        { 'revision|r=s' => \$_revision,
 169                          'fetch-all|all' => \$_fetch_all,
 170                          'parent|p' => \$_fetch_parent,
 171                           %fc_opts } ],
 172        clone => [ \&cmd_clone, "Initialize and fetch revisions",
 173                        { 'revision|r=s' => \$_revision,
 174                          'preserve-empty-dirs' =>
 175                                \$Git::SVN::Fetcher::_preserve_empty_dirs,
 176                          'placeholder-filename=s' =>
 177                                \$Git::SVN::Fetcher::_placeholder_filename,
 178                           %fc_opts, %init_opts } ],
 179        init => [ \&cmd_init, "Initialize a repo for tracking" .
 180                          " (requires URL argument)",
 181                          \%init_opts ],
 182        'multi-init' => [ \&cmd_multi_init,
 183                          "Deprecated alias for ".
 184                          "'$0 init -T<trunk> -b<branches> -t<tags>'",
 185                          \%init_opts ],
 186        dcommit => [ \&cmd_dcommit,
 187                     'Commit several diffs to merge with upstream',
 188                        { 'merge|m|M' => \$_merge,
 189                          'strategy|s=s' => \$_strategy,
 190                          'verbose|v' => \$_verbose,
 191                          'dry-run|n' => \$_dry_run,
 192                          'fetch-all|all' => \$_fetch_all,
 193                          'commit-url=s' => \$_commit_url,
 194                          'revision|r=i' => \$_revision,
 195                          'no-rebase' => \$_no_rebase,
 196                          'mergeinfo=s' => \$_merge_info,
 197                          'interactive|i' => \$_interactive,
 198                        %cmt_opts, %fc_opts } ],
 199        branch => [ \&cmd_branch,
 200                    'Create a branch in the SVN repository',
 201                    { 'message|m=s' => \$_message,
 202                      'destination|d=s' => \$_branch_dest,
 203                      'dry-run|n' => \$_dry_run,
 204                      'tag|t' => \$_tag,
 205                      'username=s' => \$Git::SVN::Prompt::_username,
 206                      'commit-url=s' => \$_commit_url } ],
 207        tag => [ sub { $_tag = 1; cmd_branch(@_) },
 208                 'Create a tag in the SVN repository',
 209                 { 'message|m=s' => \$_message,
 210                   'destination|d=s' => \$_branch_dest,
 211                   'dry-run|n' => \$_dry_run,
 212                   'username=s' => \$Git::SVN::Prompt::_username,
 213                   'commit-url=s' => \$_commit_url } ],
 214        'set-tree' => [ \&cmd_set_tree,
 215                        "Set an SVN repository to a git tree-ish",
 216                        { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
 217        'create-ignore' => [ \&cmd_create_ignore,
 218                             'Create a .gitignore per svn:ignore',
 219                             { 'revision|r=i' => \$_revision
 220                             } ],
 221        'mkdirs' => [ \&cmd_mkdirs ,
 222                      "recreate empty directories after a checkout",
 223                      { 'revision|r=i' => \$_revision } ],
 224        'propget' => [ \&cmd_propget,
 225                       'Print the value of a property on a file or directory',
 226                       { 'revision|r=i' => \$_revision } ],
 227        'proplist' => [ \&cmd_proplist,
 228                       'List all properties of a file or directory',
 229                       { 'revision|r=i' => \$_revision } ],
 230        'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
 231                        { 'revision|r=i' => \$_revision
 232                        } ],
 233        'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
 234                        { 'revision|r=i' => \$_revision
 235                        } ],
 236        'multi-fetch' => [ \&cmd_multi_fetch,
 237                           "Deprecated alias for $0 fetch --all",
 238                           { 'revision|r=s' => \$_revision, %fc_opts } ],
 239        'migrate' => [ sub { },
 240                       # no-op, we automatically run this anyways,
 241                       'Migrate configuration/metadata/layout from
 242                        previous versions of git-svn',
 243                       { 'minimize' => \$Git::SVN::Migration::_minimize,
 244                         %remote_opts } ],
 245        'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
 246                        { 'limit=i' => \$Git::SVN::Log::limit,
 247                          'revision|r=s' => \$_revision,
 248                          'verbose|v' => \$Git::SVN::Log::verbose,
 249                          'incremental' => \$Git::SVN::Log::incremental,
 250                          'oneline' => \$Git::SVN::Log::oneline,
 251                          'show-commit' => \$Git::SVN::Log::show_commit,
 252                          'non-recursive' => \$Git::SVN::Log::non_recursive,
 253                          'authors-file|A=s' => \$_authors,
 254                          'color' => \$Git::SVN::Log::color,
 255                          'pager=s' => \$Git::SVN::Log::pager
 256                        } ],
 257        'find-rev' => [ \&cmd_find_rev,
 258                        "Translate between SVN revision numbers and tree-ish",
 259                        {} ],
 260        'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
 261                        { 'merge|m|M' => \$_merge,
 262                          'verbose|v' => \$_verbose,
 263                          'strategy|s=s' => \$_strategy,
 264                          'local|l' => \$_local,
 265                          'fetch-all|all' => \$_fetch_all,
 266                          'dry-run|n' => \$_dry_run,
 267                          'preserve-merges|p' => \$_preserve_merges,
 268                          %fc_opts } ],
 269        'commit-diff' => [ \&cmd_commit_diff,
 270                           'Commit a diff between two trees',
 271                        { 'message|m=s' => \$_message,
 272                          'file|F=s' => \$_file,
 273                          'revision|r=s' => \$_revision,
 274                        %cmt_opts } ],
 275        'info' => [ \&cmd_info,
 276                    "Show info about the latest SVN revision
 277                     on the current branch",
 278                    { 'url' => \$_url, } ],
 279        'blame' => [ \&Git::SVN::Log::cmd_blame,
 280                    "Show what revision and author last modified each line of a file",
 281                    { 'git-format' => \$Git::SVN::Log::_git_format } ],
 282        'reset' => [ \&cmd_reset,
 283                     "Undo fetches back to the specified SVN revision",
 284                     { 'revision|r=s' => \$_revision,
 285                       'parent|p' => \$_fetch_parent } ],
 286        'gc' => [ \&cmd_gc,
 287                  "Compress unhandled.log files in .git/svn and remove " .
 288                  "index files in .git/svn",
 289                {} ],
 290);
 291
 292use Term::ReadLine;
 293package FakeTerm;
 294sub new {
 295        my ($class, $reason) = @_;
 296        return bless \$reason, shift;
 297}
 298sub readline {
 299        my $self = shift;
 300        die "Cannot use readline on FakeTerm: $$self";
 301}
 302package main;
 303
 304my $term = eval {
 305        $ENV{"GIT_SVN_NOTTY"}
 306                ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
 307                : new Term::ReadLine 'git-svn';
 308};
 309if ($@) {
 310        $term = new FakeTerm "$@: going non-interactive";
 311}
 312
 313my $cmd;
 314for (my $i = 0; $i < @ARGV; $i++) {
 315        if (defined $cmd{$ARGV[$i]}) {
 316                $cmd = $ARGV[$i];
 317                splice @ARGV, $i, 1;
 318                last;
 319        } elsif ($ARGV[$i] eq 'help') {
 320                $cmd = $ARGV[$i+1];
 321                usage(0);
 322        }
 323};
 324
 325# make sure we're always running at the top-level working directory
 326unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
 327        unless (-d $ENV{GIT_DIR}) {
 328                if ($git_dir_user_set) {
 329                        die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
 330                            "but it is not a directory\n";
 331                }
 332                my $git_dir = delete $ENV{GIT_DIR};
 333                my $cdup = undef;
 334                git_cmd_try {
 335                        $cdup = command_oneline(qw/rev-parse --show-cdup/);
 336                        $git_dir = '.' unless ($cdup);
 337                        chomp $cdup if ($cdup);
 338                        $cdup = "." unless ($cdup && length $cdup);
 339                } "Already at toplevel, but $git_dir not found\n";
 340                chdir $cdup or die "Unable to chdir up to '$cdup'\n";
 341                unless (-d $git_dir) {
 342                        die "$git_dir still not found after going to ",
 343                            "'$cdup'\n";
 344                }
 345                $ENV{GIT_DIR} = $git_dir;
 346        }
 347        $_repository = Git->repository(Repository => $ENV{GIT_DIR});
 348}
 349
 350my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
 351
 352read_git_config(\%opts);
 353if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
 354        Getopt::Long::Configure('pass_through');
 355}
 356my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
 357                    'minimize-connections' => \$Git::SVN::Migration::_minimize,
 358                    'id|i=s' => \$Git::SVN::default_ref_id,
 359                    'svn-remote|remote|R=s' => sub {
 360                       $Git::SVN::no_reuse_existing = 1;
 361                       $Git::SVN::default_repo_id = $_[1] });
 362exit 1 if (!$rv && $cmd && $cmd ne 'log');
 363
 364usage(0) if $_help;
 365version() if $_version;
 366usage(1) unless defined $cmd;
 367load_authors() if $_authors;
 368if (defined $_authors_prog) {
 369        $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
 370}
 371
 372unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
 373        Git::SVN::Migration::migration_check();
 374}
 375Git::SVN::init_vars();
 376eval {
 377        Git::SVN::verify_remotes_sanity();
 378        $cmd{$cmd}->[0]->(@ARGV);
 379        post_fetch_checkout();
 380};
 381fatal $@ if $@;
 382exit 0;
 383
 384####################### primary functions ######################
 385sub usage {
 386        my $exit = shift || 0;
 387        my $fd = $exit ? \*STDERR : \*STDOUT;
 388        print $fd <<"";
 389git-svn - bidirectional operations between a single Subversion tree and git
 390Usage: git svn <command> [options] [arguments]\n
 391
 392        print $fd "Available commands:\n" unless $cmd;
 393
 394        foreach (sort keys %cmd) {
 395                next if $cmd && $cmd ne $_;
 396                next if /^multi-/; # don't show deprecated commands
 397                print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
 398                foreach (sort keys %{$cmd{$_}->[2]}) {
 399                        # mixed-case options are for .git/config only
 400                        next if /[A-Z]/ && /^[a-z]+$/i;
 401                        # prints out arguments as they should be passed:
 402                        my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
 403                        print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
 404                                                        "--$_" : "-$_" }
 405                                                split /\|/,$_)," $x\n";
 406                }
 407        }
 408        print $fd <<"";
 409\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
 410arbitrary identifier if you're tracking multiple SVN branches/repositories in
 411one git repository and want to keep them separate.  See git-svn(1) for more
 412information.
 413
 414        exit $exit;
 415}
 416
 417sub version {
 418        ::_req_svn();
 419        print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
 420        exit 0;
 421}
 422
 423sub ask {
 424        my ($prompt, %arg) = @_;
 425        my $valid_re = $arg{valid_re};
 426        my $default = $arg{default};
 427        my $resp;
 428        my $i = 0;
 429
 430        if ( !( defined($term->IN)
 431            && defined( fileno($term->IN) )
 432            && defined( $term->OUT )
 433            && defined( fileno($term->OUT) ) ) ){
 434                return defined($default) ? $default : undef;
 435        }
 436
 437        while ($i++ < 10) {
 438                $resp = $term->readline($prompt);
 439                if (!defined $resp) { # EOF
 440                        print "\n";
 441                        return defined $default ? $default : undef;
 442                }
 443                if ($resp eq '' and defined $default) {
 444                        return $default;
 445                }
 446                if (!defined $valid_re or $resp =~ /$valid_re/) {
 447                        return $resp;
 448                }
 449        }
 450        return undef;
 451}
 452
 453sub do_git_init_db {
 454        unless (-d $ENV{GIT_DIR}) {
 455                my @init_db = ('init');
 456                push @init_db, "--template=$_template" if defined $_template;
 457                if (defined $_shared) {
 458                        if ($_shared =~ /[a-z]/) {
 459                                push @init_db, "--shared=$_shared";
 460                        } else {
 461                                push @init_db, "--shared";
 462                        }
 463                }
 464                command_noisy(@init_db);
 465                $_repository = Git->repository(Repository => ".git");
 466        }
 467        my $set;
 468        my $pfx = "svn-remote.$Git::SVN::default_repo_id";
 469        foreach my $i (keys %icv) {
 470                die "'$set' and '$i' cannot both be set\n" if $set;
 471                next unless defined $icv{$i};
 472                command_noisy('config', "$pfx.$i", $icv{$i});
 473                $set = $i;
 474        }
 475        my $ignore_paths_regex = \$Git::SVN::Fetcher::_ignore_regex;
 476        command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
 477                if defined $$ignore_paths_regex;
 478        my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
 479        command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
 480                if defined $$ignore_refs_regex;
 481
 482        if (defined $Git::SVN::Fetcher::_preserve_empty_dirs) {
 483                my $fname = \$Git::SVN::Fetcher::_placeholder_filename;
 484                command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
 485                command_noisy('config', "$pfx.placeholder-filename", $$fname);
 486        }
 487}
 488
 489sub init_subdir {
 490        my $repo_path = shift or return;
 491        mkpath([$repo_path]) unless -d $repo_path;
 492        chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
 493        $ENV{GIT_DIR} = '.git';
 494        $_repository = Git->repository(Repository => $ENV{GIT_DIR});
 495}
 496
 497sub cmd_clone {
 498        my ($url, $path) = @_;
 499        if (!defined $path &&
 500            (defined $_trunk || @_branches || @_tags ||
 501             defined $_stdlayout) &&
 502            $url !~ m#^[a-z\+]+://#) {
 503                $path = $url;
 504        }
 505        $path = basename($url) if !defined $path || !length $path;
 506        my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
 507        cmd_init($url, $path);
 508        command_oneline('config', 'svn.authorsfile', $authors_absolute)
 509            if $_authors;
 510        Git::SVN::fetch_all($Git::SVN::default_repo_id);
 511}
 512
 513sub cmd_init {
 514        if (defined $_stdlayout) {
 515                $_trunk = 'trunk' if (!defined $_trunk);
 516                @_tags = 'tags' if (! @_tags);
 517                @_branches = 'branches' if (! @_branches);
 518        }
 519        if (defined $_trunk || @_branches || @_tags) {
 520                return cmd_multi_init(@_);
 521        }
 522        my $url = shift or die "SVN repository location required ",
 523                               "as a command-line argument\n";
 524        $url = canonicalize_url($url);
 525        init_subdir(@_);
 526        do_git_init_db();
 527
 528        if ($Git::SVN::_minimize_url eq 'unset') {
 529                $Git::SVN::_minimize_url = 0;
 530        }
 531
 532        Git::SVN->init($url);
 533}
 534
 535sub cmd_fetch {
 536        if (grep /^\d+=./, @_) {
 537                die "'<rev>=<commit>' fetch arguments are ",
 538                    "no longer supported.\n";
 539        }
 540        my ($remote) = @_;
 541        if (@_ > 1) {
 542                die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
 543        }
 544        $Git::SVN::no_reuse_existing = undef;
 545        if ($_fetch_parent) {
 546                my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
 547                unless ($gs) {
 548                        die "Unable to determine upstream SVN information from ",
 549                            "working tree history\n";
 550                }
 551                # just fetch, don't checkout.
 552                $_no_checkout = 'true';
 553                $_fetch_all ? $gs->fetch_all : $gs->fetch;
 554        } elsif ($_fetch_all) {
 555                cmd_multi_fetch();
 556        } else {
 557                $remote ||= $Git::SVN::default_repo_id;
 558                Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
 559        }
 560}
 561
 562sub cmd_set_tree {
 563        my (@commits) = @_;
 564        if ($_stdin || !@commits) {
 565                print "Reading from stdin...\n";
 566                @commits = ();
 567                while (<STDIN>) {
 568                        if (/\b($sha1_short)\b/o) {
 569                                unshift @commits, $1;
 570                        }
 571                }
 572        }
 573        my @revs;
 574        foreach my $c (@commits) {
 575                my @tmp = command('rev-parse',$c);
 576                if (scalar @tmp == 1) {
 577                        push @revs, $tmp[0];
 578                } elsif (scalar @tmp > 1) {
 579                        push @revs, reverse(command('rev-list',@tmp));
 580                } else {
 581                        fatal "Failed to rev-parse $c";
 582                }
 583        }
 584        my $gs = Git::SVN->new;
 585        my ($r_last, $cmt_last) = $gs->last_rev_commit;
 586        $gs->fetch;
 587        if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
 588                fatal "There are new revisions that were fetched ",
 589                      "and need to be merged (or acknowledged) ",
 590                      "before committing.\nlast rev: $r_last\n",
 591                      " current: $gs->{last_rev}";
 592        }
 593        $gs->set_tree($_) foreach @revs;
 594        print "Done committing ",scalar @revs," revisions to SVN\n";
 595        unlink $gs->{index};
 596}
 597
 598sub split_merge_info_range {
 599        my ($range) = @_;
 600        if ($range =~ /(\d+)-(\d+)/) {
 601                return (int($1), int($2));
 602        } else {
 603                return (int($range), int($range));
 604        }
 605}
 606
 607sub combine_ranges {
 608        my ($in) = @_;
 609
 610        my @fnums = ();
 611        my @arr = split(/,/, $in);
 612        for my $element (@arr) {
 613                my ($start, $end) = split_merge_info_range($element);
 614                push @fnums, $start;
 615        }
 616
 617        my @sorted = @arr [ sort {
 618                $fnums[$a] <=> $fnums[$b]
 619        } 0..$#arr ];
 620
 621        my @return = ();
 622        my $last = -1;
 623        my $first = -1;
 624        for my $element (@sorted) {
 625                my ($start, $end) = split_merge_info_range($element);
 626
 627                if ($last == -1) {
 628                        $first = $start;
 629                        $last = $end;
 630                        next;
 631                }
 632                if ($start <= $last+1) {
 633                        if ($end > $last) {
 634                                $last = $end;
 635                        }
 636                        next;
 637                }
 638                if ($first == $last) {
 639                        push @return, "$first";
 640                } else {
 641                        push @return, "$first-$last";
 642                }
 643                $first = $start;
 644                $last = $end;
 645        }
 646
 647        if ($first != -1) {
 648                if ($first == $last) {
 649                        push @return, "$first";
 650                } else {
 651                        push @return, "$first-$last";
 652                }
 653        }
 654
 655        return join(',', @return);
 656}
 657
 658sub merge_revs_into_hash {
 659        my ($hash, $minfo) = @_;
 660        my @lines = split(' ', $minfo);
 661
 662        for my $line (@lines) {
 663                my ($branchpath, $revs) = split(/:/, $line);
 664
 665                if (exists($hash->{$branchpath})) {
 666                        # Merge the two revision sets
 667                        my $combined = "$hash->{$branchpath},$revs";
 668                        $hash->{$branchpath} = combine_ranges($combined);
 669                } else {
 670                        # Just do range combining for consolidation
 671                        $hash->{$branchpath} = combine_ranges($revs);
 672                }
 673        }
 674}
 675
 676sub merge_merge_info {
 677        my ($mergeinfo_one, $mergeinfo_two) = @_;
 678        my %result_hash = ();
 679
 680        merge_revs_into_hash(\%result_hash, $mergeinfo_one);
 681        merge_revs_into_hash(\%result_hash, $mergeinfo_two);
 682
 683        my $result = '';
 684        # Sort below is for consistency's sake
 685        for my $branchname (sort keys(%result_hash)) {
 686                my $revlist = $result_hash{$branchname};
 687                $result .= "$branchname:$revlist\n"
 688        }
 689        return $result;
 690}
 691
 692sub populate_merge_info {
 693        my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
 694
 695        my %parentshash;
 696        read_commit_parents(\%parentshash, $d);
 697        my @parents = @{$parentshash{$d}};
 698        if ($#parents > 0) {
 699                # Merge commit
 700                my $all_parents_ok = 1;
 701                my $aggregate_mergeinfo = '';
 702                my $rooturl = $gs->repos_root;
 703
 704                if (defined($rewritten_parent)) {
 705                        # Replace first parent with newly-rewritten version
 706                        shift @parents;
 707                        unshift @parents, $rewritten_parent;
 708                }
 709
 710                foreach my $parent (@parents) {
 711                        my ($branchurl, $svnrev, $paruuid) =
 712                                cmt_metadata($parent);
 713
 714                        unless (defined($svnrev)) {
 715                                # Should have been caught be preflight check
 716                                fatal "merge commit $d has ancestor $parent, but that change "
 717                     ."does not have git-svn metadata!";
 718                        }
 719                        unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
 720                                fatal "commit $parent git-svn metadata changed mid-run!";
 721                        }
 722                        my $branchpath = $1;
 723
 724                        my $ra = Git::SVN::Ra->new($branchurl);
 725                        my (undef, undef, $props) =
 726                                $ra->get_dir(canonicalize_path("."), $svnrev);
 727                        my $par_mergeinfo = $props->{'svn:mergeinfo'};
 728                        unless (defined $par_mergeinfo) {
 729                                $par_mergeinfo = '';
 730                        }
 731                        # Merge previous mergeinfo values
 732                        $aggregate_mergeinfo =
 733                                merge_merge_info($aggregate_mergeinfo,
 734                                                                 $par_mergeinfo, 0);
 735
 736                        next if $parent eq $parents[0]; # Skip first parent
 737                        # Add new changes being placed in tree by merge
 738                        my @cmd = (qw/rev-list --reverse/,
 739                                           $parent, qw/--not/);
 740                        foreach my $par (@parents) {
 741                                unless ($par eq $parent) {
 742                                        push @cmd, $par;
 743                                }
 744                        }
 745                        my @revsin = ();
 746                        my ($revlist, $ctx) = command_output_pipe(@cmd);
 747                        while (<$revlist>) {
 748                                my $irev = $_;
 749                                chomp $irev;
 750                                my (undef, $csvnrev, undef) =
 751                                        cmt_metadata($irev);
 752                                unless (defined $csvnrev) {
 753                                        # A child is missing SVN annotations...
 754                                        # this might be OK, or might not be.
 755                                        warn "W:child $irev is merged into revision "
 756                                                 ."$d but does not have git-svn metadata. "
 757                                                 ."This means git-svn cannot determine the "
 758                                                 ."svn revision numbers to place into the "
 759                                                 ."svn:mergeinfo property. You must ensure "
 760                                                 ."a branch is entirely committed to "
 761                                                 ."SVN before merging it in order for "
 762                                                 ."svn:mergeinfo population to function "
 763                                                 ."properly";
 764                                }
 765                                push @revsin, $csvnrev;
 766                        }
 767                        command_close_pipe($revlist, $ctx);
 768
 769                        last unless $all_parents_ok;
 770
 771                        # We now have a list of all SVN revnos which are
 772                        # merged by this particular parent. Integrate them.
 773                        next if $#revsin == -1;
 774                        my $newmergeinfo = "$branchpath:" . join(',', @revsin);
 775                        $aggregate_mergeinfo =
 776                                merge_merge_info($aggregate_mergeinfo,
 777                                                                 $newmergeinfo, 1);
 778                }
 779                if ($all_parents_ok and $aggregate_mergeinfo) {
 780                        return $aggregate_mergeinfo;
 781                }
 782        }
 783
 784        return undef;
 785}
 786
 787sub cmd_dcommit {
 788        my $head = shift;
 789        command_noisy(qw/update-index --refresh/);
 790        git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
 791                'Cannot dcommit with a dirty index.  Commit your changes first, '
 792                . "or stash them with `git stash'.\n";
 793        $head ||= 'HEAD';
 794
 795        my $old_head;
 796        if ($head ne 'HEAD') {
 797                $old_head = eval {
 798                        command_oneline([qw/symbolic-ref -q HEAD/])
 799                };
 800                if ($old_head) {
 801                        $old_head =~ s{^refs/heads/}{};
 802                } else {
 803                        $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
 804                }
 805                command(['checkout', $head], STDERR => 0);
 806        }
 807
 808        my @refs;
 809        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
 810        unless ($gs) {
 811                die "Unable to determine upstream SVN information from ",
 812                    "$head history.\nPerhaps the repository is empty.";
 813        }
 814
 815        if (defined $_commit_url) {
 816                $url = $_commit_url;
 817        } else {
 818                $url = eval { command_oneline('config', '--get',
 819                              "svn-remote.$gs->{repo_id}.commiturl") };
 820                if (!$url) {
 821                        $url = $gs->full_pushurl
 822                }
 823        }
 824
 825        my $last_rev = $_revision if defined $_revision;
 826        if ($url) {
 827                print "Committing to $url ...\n";
 828        }
 829        my ($linear_refs, $parents) = linearize_history($gs, \@refs);
 830        if ($_no_rebase && scalar(@$linear_refs) > 1) {
 831                warn "Attempting to commit more than one change while ",
 832                     "--no-rebase is enabled.\n",
 833                     "If these changes depend on each other, re-running ",
 834                     "without --no-rebase may be required."
 835        }
 836
 837        if (defined $_interactive){
 838                my $ask_default = "y";
 839                foreach my $d (@$linear_refs){
 840                        my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
 841                        while (<$fh>){
 842                                print $_;
 843                        }
 844                        command_close_pipe($fh, $ctx);
 845                        $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
 846                                 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
 847                                 default => $ask_default);
 848                        die "Commit this patch reply required" unless defined $_;
 849                        if (/^[nq]/i) {
 850                                exit(0);
 851                        } elsif (/^a/i) {
 852                                last;
 853                        }
 854                }
 855        }
 856
 857        my $expect_url = $url;
 858
 859        my $push_merge_info = eval {
 860                command_oneline(qw/config --get svn.pushmergeinfo/)
 861                };
 862        if (not defined($push_merge_info)
 863                        or $push_merge_info eq "false"
 864                        or $push_merge_info eq "no"
 865                        or $push_merge_info eq "never") {
 866                $push_merge_info = 0;
 867        }
 868
 869        unless (defined($_merge_info) || ! $push_merge_info) {
 870                # Preflight check of changes to ensure no issues with mergeinfo
 871                # This includes check for uncommitted-to-SVN parents
 872                # (other than the first parent, which we will handle),
 873                # information from different SVN repos, and paths
 874                # which are not underneath this repository root.
 875                my $rooturl = $gs->repos_root;
 876                foreach my $d (@$linear_refs) {
 877                        my %parentshash;
 878                        read_commit_parents(\%parentshash, $d);
 879                        my @realparents = @{$parentshash{$d}};
 880                        if ($#realparents > 0) {
 881                                # Merge commit
 882                                shift @realparents; # Remove/ignore first parent
 883                                foreach my $parent (@realparents) {
 884                                        my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
 885                                        unless (defined $paruuid) {
 886                                                # A parent is missing SVN annotations...
 887                                                # abort the whole operation.
 888                                                fatal "$parent is merged into revision $d, "
 889                                                         ."but does not have git-svn metadata. "
 890                                                         ."Either dcommit the branch or use a "
 891                                                         ."local cherry-pick, FF merge, or rebase "
 892                                                         ."instead of an explicit merge commit.";
 893                                        }
 894
 895                                        unless ($paruuid eq $uuid) {
 896                                                # Parent has SVN metadata from different repository
 897                                                fatal "merge parent $parent for change $d has "
 898                                                         ."git-svn uuid $paruuid, while current change "
 899                                                         ."has uuid $uuid!";
 900                                        }
 901
 902                                        unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
 903                                                # This branch is very strange indeed.
 904                                                fatal "merge parent $parent for $d is on branch "
 905                                                         ."$branchurl, which is not under the "
 906                                                         ."git-svn root $rooturl!";
 907                                        }
 908                                }
 909                        }
 910                }
 911        }
 912
 913        my $rewritten_parent;
 914        Git::SVN::remove_username($expect_url);
 915        if (defined($_merge_info)) {
 916                $_merge_info =~ tr{ }{\n};
 917        }
 918        while (1) {
 919                my $d = shift @$linear_refs or last;
 920                unless (defined $last_rev) {
 921                        (undef, $last_rev, undef) = cmt_metadata("$d~1");
 922                        unless (defined $last_rev) {
 923                                fatal "Unable to extract revision information ",
 924                                      "from commit $d~1";
 925                        }
 926                }
 927                if ($_dry_run) {
 928                        print "diff-tree $d~1 $d\n";
 929                } else {
 930                        my $cmt_rev;
 931
 932                        unless (defined($_merge_info) || ! $push_merge_info) {
 933                                $_merge_info = populate_merge_info($d, $gs,
 934                                                             $uuid,
 935                                                             $linear_refs,
 936                                                             $rewritten_parent);
 937                        }
 938
 939                        my %ed_opts = ( r => $last_rev,
 940                                        log => get_commit_entry($d)->{log},
 941                                        ra => Git::SVN::Ra->new($url),
 942                                        config => SVN::Core::config_get_config(
 943                                                $Git::SVN::Ra::config_dir
 944                                        ),
 945                                        tree_a => "$d~1",
 946                                        tree_b => $d,
 947                                        editor_cb => sub {
 948                                               print "Committed r$_[0]\n";
 949                                               $cmt_rev = $_[0];
 950                                        },
 951                                        mergeinfo => $_merge_info,
 952                                        svn_path => '');
 953                        if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
 954                                print "No changes\n$d~1 == $d\n";
 955                        } elsif ($parents->{$d} && @{$parents->{$d}}) {
 956                                $gs->{inject_parents_dcommit}->{$cmt_rev} =
 957                                                               $parents->{$d};
 958                        }
 959                        $_fetch_all ? $gs->fetch_all : $gs->fetch;
 960                        $last_rev = $cmt_rev;
 961                        next if $_no_rebase;
 962
 963                        # we always want to rebase against the current HEAD,
 964                        # not any head that was passed to us
 965                        my @diff = command('diff-tree', $d,
 966                                           $gs->refname, '--');
 967                        my @finish;
 968                        if (@diff) {
 969                                @finish = rebase_cmd();
 970                                print STDERR "W: $d and ", $gs->refname,
 971                                             " differ, using @finish:\n",
 972                                             join("\n", @diff), "\n";
 973                        } else {
 974                                print "No changes between current HEAD and ",
 975                                      $gs->refname,
 976                                      "\nResetting to the latest ",
 977                                      $gs->refname, "\n";
 978                                @finish = qw/reset --mixed/;
 979                        }
 980                        command_noisy(@finish, $gs->refname);
 981
 982                        $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
 983
 984                        if (@diff) {
 985                                @refs = ();
 986                                my ($url_, $rev_, $uuid_, $gs_) =
 987                                              working_head_info('HEAD', \@refs);
 988                                my ($linear_refs_, $parents_) =
 989                                              linearize_history($gs_, \@refs);
 990                                if (scalar(@$linear_refs) !=
 991                                    scalar(@$linear_refs_)) {
 992                                        fatal "# of revisions changed ",
 993                                          "\nbefore:\n",
 994                                          join("\n", @$linear_refs),
 995                                          "\n\nafter:\n",
 996                                          join("\n", @$linear_refs_), "\n",
 997                                          'If you are attempting to commit ',
 998                                          "merges, try running:\n\t",
 999                                          'git rebase --interactive',
1000                                          '--preserve-merges ',
1001                                          $gs->refname,
1002                                          "\nBefore dcommitting";
1003                                }
1004                                if ($url_ ne $expect_url) {
1005                                        if ($url_ eq $gs->metadata_url) {
1006                                                print
1007                                                  "Accepting rewritten URL:",
1008                                                  " $url_\n";
1009                                        } else {
1010                                                fatal
1011                                                  "URL mismatch after rebase:",
1012                                                  " $url_ != $expect_url";
1013                                        }
1014                                }
1015                                if ($uuid_ ne $uuid) {
1016                                        fatal "uuid mismatch after rebase: ",
1017                                              "$uuid_ != $uuid";
1018                                }
1019                                # remap parents
1020                                my (%p, @l, $i);
1021                                for ($i = 0; $i < scalar @$linear_refs; $i++) {
1022                                        my $new = $linear_refs_->[$i] or next;
1023                                        $p{$new} =
1024                                                $parents->{$linear_refs->[$i]};
1025                                        push @l, $new;
1026                                }
1027                                $parents = \%p;
1028                                $linear_refs = \@l;
1029                        }
1030                }
1031        }
1032
1033        if ($old_head) {
1034                my $new_head = command_oneline(qw/rev-parse HEAD/);
1035                my $new_is_symbolic = eval {
1036                        command_oneline(qw/symbolic-ref -q HEAD/);
1037                };
1038                if ($new_is_symbolic) {
1039                        print "dcommitted the branch ", $head, "\n";
1040                } else {
1041                        print "dcommitted on a detached HEAD because you gave ",
1042                              "a revision argument.\n",
1043                              "The rewritten commit is: ", $new_head, "\n";
1044                }
1045                command(['checkout', $old_head], STDERR => 0);
1046        }
1047
1048        unlink $gs->{index};
1049}
1050
1051sub cmd_branch {
1052        my ($branch_name, $head) = @_;
1053
1054        unless (defined $branch_name && length $branch_name) {
1055                die(($_tag ? "tag" : "branch") . " name required\n");
1056        }
1057        $head ||= 'HEAD';
1058
1059        my (undef, $rev, undef, $gs) = working_head_info($head);
1060        my $src = $gs->full_pushurl;
1061
1062        my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1063        my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1064        my $glob;
1065        if ($#{$allglobs} == 0) {
1066                $glob = $allglobs->[0];
1067        } else {
1068                unless(defined $_branch_dest) {
1069                        die "Multiple ",
1070                            $_tag ? "tag" : "branch",
1071                            " paths defined for Subversion repository.\n",
1072                            "You must specify where you want to create the ",
1073                            $_tag ? "tag" : "branch",
1074                            " with the --destination argument.\n";
1075                }
1076                foreach my $g (@{$allglobs}) {
1077                        my $re = Git::SVN::Editor::glob2pat($g->{path}->{left});
1078                        if ($_branch_dest =~ /$re/) {
1079                                $glob = $g;
1080                                last;
1081                        }
1082                }
1083                unless (defined $glob) {
1084                        my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1085                        foreach my $g (@{$allglobs}) {
1086                                $g->{path}->{left} =~ /$dest_re/ or next;
1087                                if (defined $glob) {
1088                                        die "Ambiguous destination: ",
1089                                            $_branch_dest, "\nmatches both '",
1090                                            $glob->{path}->{left}, "' and '",
1091                                            $g->{path}->{left}, "'\n";
1092                                }
1093                                $glob = $g;
1094                        }
1095                        unless (defined $glob) {
1096                                die "Unknown ",
1097                                    $_tag ? "tag" : "branch",
1098                                    " destination $_branch_dest\n";
1099                        }
1100                }
1101        }
1102        my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1103        my $url;
1104        if (defined $_commit_url) {
1105                $url = $_commit_url;
1106        } else {
1107                $url = eval { command_oneline('config', '--get',
1108                        "svn-remote.$gs->{repo_id}.commiturl") };
1109                if (!$url) {
1110                        $url = $remote->{pushurl} || $remote->{url};
1111                }
1112        }
1113        my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1114
1115        if ($dst =~ /^https:/ && $src =~ /^http:/) {
1116                $src=~s/^http:/https:/;
1117        }
1118
1119        ::_req_svn();
1120
1121        my $ctx = SVN::Client->new(
1122                auth    => Git::SVN::Ra::_auth_providers(),
1123                log_msg => sub {
1124                        ${ $_[0] } = defined $_message
1125                                ? $_message
1126                                : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1127                                . $branch_name;
1128                },
1129        );
1130
1131        eval {
1132                $ctx->ls($dst, 'HEAD', 0);
1133        } and die "branch ${branch_name} already exists\n";
1134
1135        print "Copying ${src} at r${rev} to ${dst}...\n";
1136        $ctx->copy($src, $rev, $dst)
1137                unless $_dry_run;
1138
1139        $gs->fetch_all;
1140}
1141
1142sub cmd_find_rev {
1143        my $revision_or_hash = shift or die "SVN or git revision required ",
1144                                            "as a command-line argument\n";
1145        my $result;
1146        if ($revision_or_hash =~ /^r\d+$/) {
1147                my $head = shift;
1148                $head ||= 'HEAD';
1149                my @refs;
1150                my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1151                unless ($gs) {
1152                        die "Unable to determine upstream SVN information from ",
1153                            "$head history\n";
1154                }
1155                my $desired_revision = substr($revision_or_hash, 1);
1156                $result = $gs->rev_map_get($desired_revision, $uuid);
1157        } else {
1158                my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1159                $result = $rev;
1160        }
1161        print "$result\n" if $result;
1162}
1163
1164sub auto_create_empty_directories {
1165        my ($gs) = @_;
1166        my $var = eval { command_oneline('config', '--get', '--bool',
1167                                         "svn-remote.$gs->{repo_id}.automkdirs") };
1168        # By default, create empty directories by consulting the unhandled log,
1169        # but allow setting it to 'false' to skip it.
1170        return !($var && $var eq 'false');
1171}
1172
1173sub cmd_rebase {
1174        command_noisy(qw/update-index --refresh/);
1175        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1176        unless ($gs) {
1177                die "Unable to determine upstream SVN information from ",
1178                    "working tree history\n";
1179        }
1180        if ($_dry_run) {
1181                print "Remote Branch: " . $gs->refname . "\n";
1182                print "SVN URL: " . $url . "\n";
1183                return;
1184        }
1185        if (command(qw/diff-index HEAD --/)) {
1186                print STDERR "Cannot rebase with uncommited changes:\n";
1187                command_noisy('status');
1188                exit 1;
1189        }
1190        unless ($_local) {
1191                # rebase will checkout for us, so no need to do it explicitly
1192                $_no_checkout = 'true';
1193                $_fetch_all ? $gs->fetch_all : $gs->fetch;
1194        }
1195        command_noisy(rebase_cmd(), $gs->refname);
1196        if (auto_create_empty_directories($gs)) {
1197                $gs->mkemptydirs;
1198        }
1199}
1200
1201sub cmd_show_ignore {
1202        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1203        $gs ||= Git::SVN->new;
1204        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1205        $gs->prop_walk($gs->path, $r, sub {
1206                my ($gs, $path, $props) = @_;
1207                print STDOUT "\n# $path\n";
1208                my $s = $props->{'svn:ignore'} or return;
1209                $s =~ s/[\r\n]+/\n/g;
1210                $s =~ s/^\n+//;
1211                chomp $s;
1212                $s =~ s#^#$path#gm;
1213                print STDOUT "$s\n";
1214        });
1215}
1216
1217sub cmd_show_externals {
1218        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1219        $gs ||= Git::SVN->new;
1220        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1221        $gs->prop_walk($gs->path, $r, sub {
1222                my ($gs, $path, $props) = @_;
1223                print STDOUT "\n# $path\n";
1224                my $s = $props->{'svn:externals'} or return;
1225                $s =~ s/[\r\n]+/\n/g;
1226                chomp $s;
1227                $s =~ s#^#$path#gm;
1228                print STDOUT "$s\n";
1229        });
1230}
1231
1232sub cmd_create_ignore {
1233        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1234        $gs ||= Git::SVN->new;
1235        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1236        $gs->prop_walk($gs->path, $r, sub {
1237                my ($gs, $path, $props) = @_;
1238                # $path is of the form /path/to/dir/
1239                $path = '.' . $path;
1240                # SVN can have attributes on empty directories,
1241                # which git won't track
1242                mkpath([$path]) unless -d $path;
1243                my $ignore = $path . '.gitignore';
1244                my $s = $props->{'svn:ignore'} or return;
1245                open(GITIGNORE, '>', $ignore)
1246                  or fatal("Failed to open `$ignore' for writing: $!");
1247                $s =~ s/[\r\n]+/\n/g;
1248                $s =~ s/^\n+//;
1249                chomp $s;
1250                # Prefix all patterns so that the ignore doesn't apply
1251                # to sub-directories.
1252                $s =~ s#^#/#gm;
1253                print GITIGNORE "$s\n";
1254                close(GITIGNORE)
1255                  or fatal("Failed to close `$ignore': $!");
1256                command_noisy('add', '-f', $ignore);
1257        });
1258}
1259
1260sub cmd_mkdirs {
1261        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1262        $gs ||= Git::SVN->new;
1263        $gs->mkemptydirs($_revision);
1264}
1265
1266# get_svnprops(PATH)
1267# ------------------
1268# Helper for cmd_propget and cmd_proplist below.
1269sub get_svnprops {
1270        my $path = shift;
1271        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1272        $gs ||= Git::SVN->new;
1273
1274        # prefix THE PATH by the sub-directory from which the user
1275        # invoked us.
1276        $path = $cmd_dir_prefix . $path;
1277        fatal("No such file or directory: $path") unless -e $path;
1278        my $is_dir = -d $path ? 1 : 0;
1279        $path = join_paths($gs->{path}, $path);
1280
1281        # canonicalize the path (otherwise libsvn will abort or fail to
1282        # find the file)
1283        $path = canonicalize_path($path);
1284
1285        my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1286        my $props;
1287        if ($is_dir) {
1288                (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1289        }
1290        else {
1291                (undef, $props) = $gs->ra->get_file($path, $r, undef);
1292        }
1293        return $props;
1294}
1295
1296# cmd_propget (PROP, PATH)
1297# ------------------------
1298# Print the SVN property PROP for PATH.
1299sub cmd_propget {
1300        my ($prop, $path) = @_;
1301        $path = '.' if not defined $path;
1302        usage(1) if not defined $prop;
1303        my $props = get_svnprops($path);
1304        if (not defined $props->{$prop}) {
1305                fatal("`$path' does not have a `$prop' SVN property.");
1306        }
1307        print $props->{$prop} . "\n";
1308}
1309
1310# cmd_proplist (PATH)
1311# -------------------
1312# Print the list of SVN properties for PATH.
1313sub cmd_proplist {
1314        my $path = shift;
1315        $path = '.' if not defined $path;
1316        my $props = get_svnprops($path);
1317        print "Properties on '$path':\n";
1318        foreach (sort keys %{$props}) {
1319                print "  $_\n";
1320        }
1321}
1322
1323sub cmd_multi_init {
1324        my $url = shift;
1325        unless (defined $_trunk || @_branches || @_tags) {
1326                usage(1);
1327        }
1328
1329        $_prefix = '' unless defined $_prefix;
1330        if (defined $url) {
1331                $url = canonicalize_url($url);
1332                init_subdir(@_);
1333        }
1334        do_git_init_db();
1335        if (defined $_trunk) {
1336                $_trunk =~ s#^/+##;
1337                my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1338                # try both old-style and new-style lookups:
1339                my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1340                unless ($gs_trunk) {
1341                        my ($trunk_url, $trunk_path) =
1342                                              complete_svn_url($url, $_trunk);
1343                        $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1344                                                   undef, $trunk_ref);
1345                }
1346        }
1347        return unless @_branches || @_tags;
1348        my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1349        foreach my $path (@_branches) {
1350                complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1351        }
1352        foreach my $path (@_tags) {
1353                complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1354        }
1355}
1356
1357sub cmd_multi_fetch {
1358        $Git::SVN::no_reuse_existing = undef;
1359        my $remotes = Git::SVN::read_all_remotes();
1360        foreach my $repo_id (sort keys %$remotes) {
1361                if ($remotes->{$repo_id}->{url}) {
1362                        Git::SVN::fetch_all($repo_id, $remotes);
1363                }
1364        }
1365}
1366
1367# this command is special because it requires no metadata
1368sub cmd_commit_diff {
1369        my ($ta, $tb, $url) = @_;
1370        my $usage = "Usage: $0 commit-diff -r<revision> ".
1371                    "<tree-ish> <tree-ish> [<URL>]";
1372        fatal($usage) if (!defined $ta || !defined $tb);
1373        my $svn_path = '';
1374        if (!defined $url) {
1375                my $gs = eval { Git::SVN->new };
1376                if (!$gs) {
1377                        fatal("Needed URL or usable git-svn --id in ",
1378                              "the command-line\n", $usage);
1379                }
1380                $url = $gs->url;
1381                $svn_path = $gs->path;
1382        }
1383        unless (defined $_revision) {
1384                fatal("-r|--revision is a required argument\n", $usage);
1385        }
1386        if (defined $_message && defined $_file) {
1387                fatal("Both --message/-m and --file/-F specified ",
1388                      "for the commit message.\n",
1389                      "I have no idea what you mean");
1390        }
1391        if (defined $_file) {
1392                $_message = file_to_s($_file);
1393        } else {
1394                $_message ||= get_commit_entry($tb)->{log};
1395        }
1396        my $ra ||= Git::SVN::Ra->new($url);
1397        my $r = $_revision;
1398        if ($r eq 'HEAD') {
1399                $r = $ra->get_latest_revnum;
1400        } elsif ($r !~ /^\d+$/) {
1401                die "revision argument: $r not understood by git-svn\n";
1402        }
1403        my %ed_opts = ( r => $r,
1404                        log => $_message,
1405                        ra => $ra,
1406                        tree_a => $ta,
1407                        tree_b => $tb,
1408                        editor_cb => sub { print "Committed r$_[0]\n" },
1409                        svn_path => $svn_path );
1410        if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1411                print "No changes\n$ta == $tb\n";
1412        }
1413}
1414
1415
1416sub cmd_info {
1417        my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1418        my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1419        if (exists $_[1]) {
1420                die "Too many arguments specified\n";
1421        }
1422
1423        my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1424
1425        if (!$file_type && !$diff_status) {
1426                print STDERR "svn: '$path' is not under version control\n";
1427                exit 1;
1428        }
1429
1430        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1431        unless ($gs) {
1432                die "Unable to determine upstream SVN information from ",
1433                    "working tree history\n";
1434        }
1435
1436        # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1437        $path = "." if $path eq "";
1438
1439        my $full_url = canonicalize_url( $url . ($fullpath eq "" ? "" : "/$fullpath") );
1440
1441        if ($_url) {
1442                print "$full_url\n";
1443                return;
1444        }
1445
1446        my $result = "Path: $path\n";
1447        $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1448        $result .= "URL: $full_url\n";
1449
1450        eval {
1451                my $repos_root = $gs->repos_root;
1452                Git::SVN::remove_username($repos_root);
1453                $result .= "Repository Root: " . canonicalize_url($repos_root) . "\n";
1454        };
1455        if ($@) {
1456                $result .= "Repository Root: (offline)\n";
1457        }
1458        ::_req_svn();
1459        $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1460                (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
1461        $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1462
1463        $result .= "Node Kind: " .
1464                   ($file_type eq "dir" ? "directory" : "file") . "\n";
1465
1466        my $schedule = $diff_status eq "A"
1467                       ? "add"
1468                       : ($diff_status eq "D" ? "delete" : "normal");
1469        $result .= "Schedule: $schedule\n";
1470
1471        if ($diff_status eq "A") {
1472                print $result, "\n";
1473                return;
1474        }
1475
1476        my ($lc_author, $lc_rev, $lc_date_utc);
1477        my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1478        my $log = command_output_pipe(@args);
1479        my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1480        while (<$log>) {
1481                if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1482                        $lc_author = $1;
1483                        $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1484                } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
1485                        (undef, $lc_rev, undef) = ::extract_metadata($1);
1486                }
1487        }
1488        close $log;
1489
1490        Git::SVN::Log::set_local_timezone();
1491
1492        $result .= "Last Changed Author: $lc_author\n";
1493        $result .= "Last Changed Rev: $lc_rev\n";
1494        $result .= "Last Changed Date: " .
1495                   Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1496
1497        if ($file_type ne "dir") {
1498                my $text_last_updated_date =
1499                    ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1500                $result .=
1501                    "Text Last Updated: " .
1502                    Git::SVN::Log::format_svn_date($text_last_updated_date) .
1503                    "\n";
1504                my $checksum;
1505                if ($diff_status eq "D") {
1506                        my ($fh, $ctx) =
1507                            command_output_pipe(qw(cat-file blob), "HEAD:$path");
1508                        if ($file_type eq "link") {
1509                                my $file_name = <$fh>;
1510                                $checksum = md5sum("link $file_name");
1511                        } else {
1512                                $checksum = md5sum($fh);
1513                        }
1514                        command_close_pipe($fh, $ctx);
1515                } elsif ($file_type eq "link") {
1516                        my $file_name =
1517                            command(qw(cat-file blob), "HEAD:$path");
1518                        $checksum =
1519                            md5sum("link " . $file_name);
1520                } else {
1521                        open FILE, "<", $path or die $!;
1522                        $checksum = md5sum(\*FILE);
1523                        close FILE or die $!;
1524                }
1525                $result .= "Checksum: " . $checksum . "\n";
1526        }
1527
1528        print $result, "\n";
1529}
1530
1531sub cmd_reset {
1532        my $target = shift || $_revision or die "SVN revision required\n";
1533        $target = $1 if $target =~ /^r(\d+)$/;
1534        $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1535        my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1536        unless ($gs) {
1537                die "Unable to determine upstream SVN information from ".
1538                    "history\n";
1539        }
1540        my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1541        die "Cannot find SVN revision $target\n" unless defined($c);
1542        $gs->rev_map_set($r, $c, 'reset', $uuid);
1543        print "r$r = $c ($gs->{ref_id})\n";
1544}
1545
1546sub cmd_gc {
1547        if (!can_compress()) {
1548                warn "Compress::Zlib could not be found; unhandled.log " .
1549                     "files will not be compressed.\n";
1550        }
1551        find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1552}
1553
1554########################### utility functions #########################
1555
1556sub rebase_cmd {
1557        my @cmd = qw/rebase/;
1558        push @cmd, '-v' if $_verbose;
1559        push @cmd, qw/--merge/ if $_merge;
1560        push @cmd, "--strategy=$_strategy" if $_strategy;
1561        push @cmd, "--preserve-merges" if $_preserve_merges;
1562        @cmd;
1563}
1564
1565sub post_fetch_checkout {
1566        return if $_no_checkout;
1567        return if verify_ref('HEAD^0');
1568        my $gs = $Git::SVN::_head or return;
1569
1570        # look for "trunk" ref if it exists
1571        my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1572        my $fetch = $remote->{fetch};
1573        if ($fetch) {
1574                foreach my $p (keys %$fetch) {
1575                        basename($fetch->{$p}) eq 'trunk' or next;
1576                        $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1577                        last;
1578                }
1579        }
1580
1581        command_noisy(qw(update-ref HEAD), $gs->refname);
1582        return unless verify_ref('HEAD^0');
1583
1584        return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1585        my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1586        return if -f $index;
1587
1588        return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1589        return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1590        command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1591        print STDERR "Checked out HEAD:\n  ",
1592                     $gs->full_url, " r", $gs->last_rev, "\n";
1593        if (auto_create_empty_directories($gs)) {
1594                $gs->mkemptydirs($gs->last_rev);
1595        }
1596}
1597
1598sub complete_svn_url {
1599        my ($url, $path) = @_;
1600        $path =~ s#/+$##;
1601
1602        # If the path is not a URL...
1603        if ($path !~ m#^[a-z\+]+://#) {
1604                if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1605                        fatal("E: '$path' is not a complete URL ",
1606                              "and a separate URL is not specified");
1607                }
1608                return ($url, $path);
1609        }
1610        return ($path, '');
1611}
1612
1613sub complete_url_ls_init {
1614        my ($ra, $repo_path, $switch, $pfx) = @_;
1615        unless ($repo_path) {
1616                print STDERR "W: $switch not specified\n";
1617                return;
1618        }
1619        $repo_path =~ s#/+$##;
1620        if ($repo_path =~ m#^[a-z\+]+://#) {
1621                $ra = Git::SVN::Ra->new($repo_path);
1622                $repo_path = '';
1623        } else {
1624                $repo_path =~ s#^/+##;
1625                unless ($ra) {
1626                        fatal("E: '$repo_path' is not a complete URL ",
1627                              "and a separate URL is not specified");
1628                }
1629        }
1630        my $url = $ra->url;
1631        my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1632        my $k = "svn-remote.$gs->{repo_id}.url";
1633        my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1634        if ($orig_url && ($orig_url ne $gs->url)) {
1635                die "$k already set: $orig_url\n",
1636                    "wanted to set to: $gs->url\n";
1637        }
1638        command_oneline('config', $k, $gs->url) unless $orig_url;
1639
1640        my $remote_path = $gs->path . "/$repo_path";
1641        $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1642        $remote_path =~ s#/+#/#g;
1643        $remote_path =~ s#^/##g;
1644        $remote_path .= "/*" if $remote_path !~ /\*/;
1645        my ($n) = ($switch =~ /^--(\w+)/);
1646        if (length $pfx && $pfx !~ m#/$#) {
1647                die "--prefix='$pfx' must have a trailing slash '/'\n";
1648        }
1649        command_noisy('config',
1650                      '--add',
1651                      "svn-remote.$gs->{repo_id}.$n",
1652                      "$remote_path:refs/remotes/$pfx*" .
1653                        ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1654}
1655
1656sub verify_ref {
1657        my ($ref) = @_;
1658        eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1659                               { STDERR => 0 }); };
1660}
1661
1662sub get_tree_from_treeish {
1663        my ($treeish) = @_;
1664        # $treeish can be a symbolic ref, too:
1665        my $type = command_oneline(qw/cat-file -t/, $treeish);
1666        my $expected;
1667        while ($type eq 'tag') {
1668                ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1669        }
1670        if ($type eq 'commit') {
1671                $expected = (grep /^tree /, command(qw/cat-file commit/,
1672                                                    $treeish))[0];
1673                ($expected) = ($expected =~ /^tree ($sha1)$/o);
1674                die "Unable to get tree from $treeish\n" unless $expected;
1675        } elsif ($type eq 'tree') {
1676                $expected = $treeish;
1677        } else {
1678                die "$treeish is a $type, expected tree, tag or commit\n";
1679        }
1680        return $expected;
1681}
1682
1683sub get_commit_entry {
1684        my ($treeish) = shift;
1685        my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1686        my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1687        my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1688        open my $log_fh, '>', $commit_editmsg or croak $!;
1689
1690        my $type = command_oneline(qw/cat-file -t/, $treeish);
1691        if ($type eq 'commit' || $type eq 'tag') {
1692                my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1693                                                         $type, $treeish);
1694                my $in_msg = 0;
1695                my $author;
1696                my $saw_from = 0;
1697                my $msgbuf = "";
1698                while (<$msg_fh>) {
1699                        if (!$in_msg) {
1700                                $in_msg = 1 if (/^\s*$/);
1701                                $author = $1 if (/^author (.*>)/);
1702                        } elsif (/^git-svn-id: /) {
1703                                # skip this for now, we regenerate the
1704                                # correct one on re-fetch anyways
1705                                # TODO: set *:merge properties or like...
1706                        } else {
1707                                if (/^From:/ || /^Signed-off-by:/) {
1708                                        $saw_from = 1;
1709                                }
1710                                $msgbuf .= $_;
1711                        }
1712                }
1713                $msgbuf =~ s/\s+$//s;
1714                if ($Git::SVN::_add_author_from && defined($author)
1715                    && !$saw_from) {
1716                        $msgbuf .= "\n\nFrom: $author";
1717                }
1718                print $log_fh $msgbuf or croak $!;
1719                command_close_pipe($msg_fh, $ctx);
1720        }
1721        close $log_fh or croak $!;
1722
1723        if ($_edit || ($type eq 'tree')) {
1724                chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1725                system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1726        }
1727        rename $commit_editmsg, $commit_msg or croak $!;
1728        {
1729                require Encode;
1730                # SVN requires messages to be UTF-8 when entering the repo
1731                local $/;
1732                open $log_fh, '<', $commit_msg or croak $!;
1733                binmode $log_fh;
1734                chomp($log_entry{log} = <$log_fh>);
1735
1736                my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1737                my $msg = $log_entry{log};
1738
1739                eval { $msg = Encode::decode($enc, $msg, 1) };
1740                if ($@) {
1741                        die "Could not decode as $enc:\n", $msg,
1742                            "\nPerhaps you need to set i18n.commitencoding\n";
1743                }
1744
1745                eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1746                die "Could not encode as UTF-8:\n$msg\n" if $@;
1747
1748                $log_entry{log} = $msg;
1749
1750                close $log_fh or croak $!;
1751        }
1752        unlink $commit_msg;
1753        \%log_entry;
1754}
1755
1756sub s_to_file {
1757        my ($str, $file, $mode) = @_;
1758        open my $fd,'>',$file or croak $!;
1759        print $fd $str,"\n" or croak $!;
1760        close $fd or croak $!;
1761        chmod ($mode &~ umask, $file) if (defined $mode);
1762}
1763
1764sub file_to_s {
1765        my $file = shift;
1766        open my $fd,'<',$file or croak "$!: file: $file\n";
1767        local $/;
1768        my $ret = <$fd>;
1769        close $fd or croak $!;
1770        $ret =~ s/\s*$//s;
1771        return $ret;
1772}
1773
1774# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1775sub load_authors {
1776        open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1777        my $log = $cmd eq 'log';
1778        while (<$authors>) {
1779                chomp;
1780                next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1781                my ($user, $name, $email) = ($1, $2, $3);
1782                if ($log) {
1783                        $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1784                } else {
1785                        $users{$user} = [$name, $email];
1786                }
1787        }
1788        close $authors or croak $!;
1789}
1790
1791# convert GetOpt::Long specs for use by git-config
1792sub read_git_config {
1793        my $opts = shift;
1794        my @config_only;
1795        foreach my $o (keys %$opts) {
1796                # if we have mixedCase and a long option-only, then
1797                # it's a config-only variable that we don't need for
1798                # the command-line.
1799                push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1800                my $v = $opts->{$o};
1801                my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1802                $key =~ s/-//g;
1803                my $arg = 'git config';
1804                $arg .= ' --int' if ($o =~ /[:=]i$/);
1805                $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1806                if (ref $v eq 'ARRAY') {
1807                        chomp(my @tmp = `$arg --get-all svn.$key`);
1808                        @$v = @tmp if @tmp;
1809                } else {
1810                        chomp(my $tmp = `$arg --get svn.$key`);
1811                        if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1812                                $$v = $tmp;
1813                        }
1814                }
1815        }
1816        delete @$opts{@config_only} if @config_only;
1817}
1818
1819sub extract_metadata {
1820        my $id = shift or return (undef, undef, undef);
1821        my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1822                                                        \s([a-f\d\-]+)$/ix);
1823        if (!defined $rev || !$uuid || !$url) {
1824                # some of the original repositories I made had
1825                # identifiers like this:
1826                ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1827        }
1828        return ($url, $rev, $uuid);
1829}
1830
1831sub cmt_metadata {
1832        return extract_metadata((grep(/^git-svn-id: /,
1833                command(qw/cat-file commit/, shift)))[-1]);
1834}
1835
1836sub cmt_sha2rev_batch {
1837        my %s2r;
1838        my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1839        my $list = shift;
1840
1841        foreach my $sha (@{$list}) {
1842                my $first = 1;
1843                my $size = 0;
1844                print $out $sha, "\n";
1845
1846                while (my $line = <$in>) {
1847                        if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1848                                last;
1849                        } elsif ($first &&
1850                               $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1851                                $first = 0;
1852                                $size = $1;
1853                                next;
1854                        } elsif ($line =~ /^(git-svn-id: )/) {
1855                                my (undef, $rev, undef) =
1856                                                      extract_metadata($line);
1857                                $s2r{$sha} = $rev;
1858                        }
1859
1860                        $size -= length($line);
1861                        last if ($size == 0);
1862                }
1863        }
1864
1865        command_close_bidi_pipe($pid, $in, $out, $ctx);
1866
1867        return \%s2r;
1868}
1869
1870sub working_head_info {
1871        my ($head, $refs) = @_;
1872        my @args = qw/rev-list --first-parent --pretty=medium/;
1873        my ($fh, $ctx) = command_output_pipe(@args, $head);
1874        my $hash;
1875        my %max;
1876        while (<$fh>) {
1877                if ( m{^commit ($::sha1)$} ) {
1878                        unshift @$refs, $hash if $hash and $refs;
1879                        $hash = $1;
1880                        next;
1881                }
1882                next unless s{^\s*(git-svn-id:)}{$1};
1883                my ($url, $rev, $uuid) = extract_metadata($_);
1884                if (defined $url && defined $rev) {
1885                        next if $max{$url} and $max{$url} < $rev;
1886                        if (my $gs = Git::SVN->find_by_url($url)) {
1887                                my $c = $gs->rev_map_get($rev, $uuid);
1888                                if ($c && $c eq $hash) {
1889                                        close $fh; # break the pipe
1890                                        return ($url, $rev, $uuid, $gs);
1891                                } else {
1892                                        $max{$url} ||= $gs->rev_map_max;
1893                                }
1894                        }
1895                }
1896        }
1897        command_close_pipe($fh, $ctx);
1898        (undef, undef, undef, undef);
1899}
1900
1901sub read_commit_parents {
1902        my ($parents, $c) = @_;
1903        chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1904        $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1905        @{$parents->{$c}} = split(/ /, $p);
1906}
1907
1908sub linearize_history {
1909        my ($gs, $refs) = @_;
1910        my %parents;
1911        foreach my $c (@$refs) {
1912                read_commit_parents(\%parents, $c);
1913        }
1914
1915        my @linear_refs;
1916        my %skip = ();
1917        my $last_svn_commit = $gs->last_commit;
1918        foreach my $c (reverse @$refs) {
1919                next if $c eq $last_svn_commit;
1920                last if $skip{$c};
1921
1922                unshift @linear_refs, $c;
1923                $skip{$c} = 1;
1924
1925                # we only want the first parent to diff against for linear
1926                # history, we save the rest to inject when we finalize the
1927                # svn commit
1928                my $fp_a = verify_ref("$c~1");
1929                my $fp_b = shift @{$parents{$c}} if $parents{$c};
1930                if (!$fp_a || !$fp_b) {
1931                        die "Commit $c\n",
1932                            "has no parent commit, and therefore ",
1933                            "nothing to diff against.\n",
1934                            "You should be working from a repository ",
1935                            "originally created by git-svn\n";
1936                }
1937                if ($fp_a ne $fp_b) {
1938                        die "$c~1 = $fp_a, however parsing commit $c ",
1939                            "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1940                }
1941
1942                foreach my $p (@{$parents{$c}}) {
1943                        $skip{$p} = 1;
1944                }
1945        }
1946        (\@linear_refs, \%parents);
1947}
1948
1949sub find_file_type_and_diff_status {
1950        my ($path) = @_;
1951        return ('dir', '') if $path eq '';
1952
1953        my $diff_output =
1954            command_oneline(qw(diff --cached --name-status --), $path) || "";
1955        my $diff_status = (split(' ', $diff_output))[0] || "";
1956
1957        my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1958
1959        return (undef, undef) if !$diff_status && !$ls_tree;
1960
1961        if ($diff_status eq "A") {
1962                return ("link", $diff_status) if -l $path;
1963                return ("dir", $diff_status) if -d $path;
1964                return ("file", $diff_status);
1965        }
1966
1967        my $mode = (split(' ', $ls_tree))[0] || "";
1968
1969        return ("link", $diff_status) if $mode eq "120000";
1970        return ("dir", $diff_status) if $mode eq "040000";
1971        return ("file", $diff_status);
1972}
1973
1974sub md5sum {
1975        my $arg = shift;
1976        my $ref = ref $arg;
1977        my $md5 = Digest::MD5->new();
1978        if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1979                $md5->addfile($arg) or croak $!;
1980        } elsif ($ref eq 'SCALAR') {
1981                $md5->add($$arg) or croak $!;
1982        } elsif (!$ref) {
1983                $md5->add($arg) or croak $!;
1984        } else {
1985                fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1986        }
1987        return $md5->hexdigest();
1988}
1989
1990sub gc_directory {
1991        if (can_compress() && -f $_ && basename($_) eq "unhandled.log") {
1992                my $out_filename = $_ . ".gz";
1993                open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1994                binmode $in_fh;
1995                my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1996                                die "Unable to open $out_filename: $!\n";
1997
1998                my $res;
1999                while ($res = sysread($in_fh, my $str, 1024)) {
2000                        $gz->gzwrite($str) or
2001                                die "Unable to write: ".$gz->gzerror()."!\n";
2002                }
2003                unlink $_ or die "unlink $File::Find::name: $!\n";
2004        } elsif (-f $_ && basename($_) eq "index") {
2005                unlink $_ or die "unlink $_: $!\n";
2006        }
2007}
2008
2009__END__
2010
2011Data structures:
2012
2013
2014$remotes = { # returned by read_all_remotes()
2015        'svn' => {
2016                # svn-remote.svn.url=https://svn.musicpd.org
2017                url => 'https://svn.musicpd.org',
2018                # svn-remote.svn.fetch=mpd/trunk:trunk
2019                fetch => {
2020                        'mpd/trunk' => 'trunk',
2021                },
2022                # svn-remote.svn.tags=mpd/tags/*:tags/*
2023                tags => {
2024                        path => {
2025                                left => 'mpd/tags',
2026                                right => '',
2027                                regex => qr!mpd/tags/([^/]+)$!,
2028                                glob => 'tags/*',
2029                        },
2030                        ref => {
2031                                left => 'tags',
2032                                right => '',
2033                                regex => qr!tags/([^/]+)$!,
2034                                glob => 'tags/*',
2035                        },
2036                }
2037        }
2038};
2039
2040$log_entry hashref as returned by libsvn_log_entry()
2041{
2042        log => 'whitespace-formatted log entry
2043',                                              # trailing newline is preserved
2044        revision => '8',                        # integer
2045        date => '2004-02-24T17:01:44.108345Z',  # commit date
2046        author => 'committer name'
2047};
2048
2049
2050# this is generated by generate_diff();
2051@mods = array of diff-index line hashes, each element represents one line
2052        of diff-index output
2053
2054diff-index line ($m hash)
2055{
2056        mode_a => first column of diff-index output, no leading ':',
2057        mode_b => second column of diff-index output,
2058        sha1_b => sha1sum of the final blob,
2059        chg => change type [MCRADT],
2060        file_a => original file name of a file (iff chg is 'C' or 'R')
2061        file_b => new/current file name of a file (any chg)
2062}
2063;
2064
2065# retval of read_url_paths{,_all}();
2066$l_map = {
2067        # repository root url
2068        'https://svn.musicpd.org' => {
2069                # repository path               # GIT_SVN_ID
2070                'mpd/trunk'             =>      'trunk',
2071                'mpd/tags/0.11.5'       =>      'tags/0.11.5',
2072        },
2073}
2074
2075Notes:
2076        I don't trust the each() function on unless I created %hash myself
2077        because the internal iterator may not have started at base.