d4b9323694e115a8005d464c1518a1880f47ccc8
   1#!/usr/bin/env perl
   2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
   3# License: GPL v2 or later
   4use warnings;
   5use strict;
   6use vars qw/    $AUTHOR $VERSION
   7                $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
   8                $GIT_SVN_INDEX $GIT_SVN
   9                $GIT_DIR $REV_DIR/;
  10$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
  11$VERSION = '1.1.0-pre';
  12
  13use Cwd qw/abs_path/;
  14$GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
  15$ENV{GIT_DIR} = $GIT_DIR;
  16
  17my $LC_ALL = $ENV{LC_ALL};
  18# make sure the svn binary gives consistent output between locales and TZs:
  19$ENV{TZ} = 'UTC';
  20$ENV{LC_ALL} = 'C';
  21
  22# If SVN:: library support is added, please make the dependencies
  23# optional and preserve the capability to use the command-line client.
  24# use eval { require SVN::... } to make it lazy load
  25# We don't use any modules not in the standard Perl distribution:
  26use Carp qw/croak/;
  27use IO::File qw//;
  28use File::Basename qw/dirname basename/;
  29use File::Path qw/mkpath/;
  30use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
  31use File::Spec qw//;
  32use POSIX qw/strftime/;
  33my $sha1 = qr/[a-f\d]{40}/;
  34my $sha1_short = qr/[a-f\d]{4,40}/;
  35my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
  36        $_find_copies_harder, $_l, $_cp_similarity,
  37        $_version, $_upgrade, $_authors, $_branch_all_refs);
  38my (@_branch_from, %tree_map, %users);
  39my ($_svn_co_url_revs, $_svn_pg_peg_revs);
  40
  41my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
  42                'branch|b=s' => \@_branch_from,
  43                'branch-all-refs|B' => \$_branch_all_refs,
  44                'authors-file|A=s' => \$_authors );
  45
  46# yes, 'native' sets "\n".  Patches to fix this for non-*nix systems welcome:
  47my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
  48
  49my %cmd = (
  50        fetch => [ \&fetch, "Download new revisions from SVN",
  51                        { 'revision|r=s' => \$_revision, %fc_opts } ],
  52        init => [ \&init, "Initialize a repo for tracking" .
  53                          " (requires URL argument)", { } ],
  54        commit => [ \&commit, "Commit git revisions to SVN",
  55                        {       'stdin|' => \$_stdin,
  56                                'edit|e' => \$_edit,
  57                                'rmdir' => \$_rmdir,
  58                                'find-copies-harder' => \$_find_copies_harder,
  59                                'l=i' => \$_l,
  60                                'copy-similarity|C=i'=> \$_cp_similarity,
  61                                %fc_opts,
  62                        } ],
  63        'show-ignore' => [ \&show_ignore, "Show svn:ignore listings", { } ],
  64        rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
  65                        { 'no-ignore-externals' => \$_no_ignore_ext,
  66                          'upgrade' => \$_upgrade } ],
  67);
  68my $cmd;
  69for (my $i = 0; $i < @ARGV; $i++) {
  70        if (defined $cmd{$ARGV[$i]}) {
  71                $cmd = $ARGV[$i];
  72                splice @ARGV, $i, 1;
  73                last;
  74        }
  75};
  76
  77my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
  78
  79# convert GetOpt::Long specs for use by git-repo-config
  80foreach my $o (keys %opts) {
  81        my $v = $opts{$o};
  82        my ($key) = ($o =~ /^([a-z\-]+)/);
  83        $key =~ s/-//g;
  84        my $arg = 'git-repo-config';
  85        $arg .= ' --int' if ($o =~ /=i$/);
  86        $arg .= ' --bool' if ($o !~ /=[sfi]$/);
  87        if (ref $v eq 'ARRAY') {
  88                chomp(my @tmp = `$arg --get-all svn.$key`);
  89                @$v = @tmp if @tmp;
  90        } else {
  91                chomp(my $tmp = `$arg --get svn.$key`);
  92                if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
  93                        $$v = $tmp;
  94                }
  95        }
  96}
  97
  98GetOptions(%opts, 'help|H|h' => \$_help,
  99                'version|V' => \$_version,
 100                'id|i=s' => \$GIT_SVN) or exit 1;
 101
 102$GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
 103$GIT_SVN_INDEX = "$GIT_DIR/$GIT_SVN/index";
 104$SVN_URL = undef;
 105$REV_DIR = "$GIT_DIR/$GIT_SVN/revs";
 106$SVN_WC = "$GIT_DIR/$GIT_SVN/tree";
 107
 108usage(0) if $_help;
 109version() if $_version;
 110usage(1) unless defined $cmd;
 111load_authors() if $_authors;
 112load_all_refs() if $_branch_all_refs;
 113svn_compat_check();
 114$cmd{$cmd}->[0]->(@ARGV);
 115exit 0;
 116
 117####################### primary functions ######################
 118sub usage {
 119        my $exit = shift || 0;
 120        my $fd = $exit ? \*STDERR : \*STDOUT;
 121        print $fd <<"";
 122git-svn - bidirectional operations between a single Subversion tree and git
 123Usage: $0 <command> [options] [arguments]\n
 124
 125        print $fd "Available commands:\n" unless $cmd;
 126
 127        foreach (sort keys %cmd) {
 128                next if $cmd && $cmd ne $_;
 129                print $fd '  ',pack('A13',$_),$cmd{$_}->[1],"\n";
 130                foreach (keys %{$cmd{$_}->[2]}) {
 131                        # prints out arguments as they should be passed:
 132                        my $x = s#=s$## ? '<arg>' : s#=i$## ? '<num>' : '';
 133                        print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
 134                                                        "--$_" : "-$_" }
 135                                                split /\|/,$_)," $x\n";
 136                }
 137        }
 138        print $fd <<"";
 139\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
 140arbitrary identifier if you're tracking multiple SVN branches/repositories in
 141one git repository and want to keep them separate.  See git-svn(1) for more
 142information.
 143
 144        exit $exit;
 145}
 146
 147sub version {
 148        print "git-svn version $VERSION\n";
 149        exit 0;
 150}
 151
 152sub rebuild {
 153        $SVN_URL = shift or undef;
 154        my $newest_rev = 0;
 155        if ($_upgrade) {
 156                sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
 157        } else {
 158                check_upgrade_needed();
 159        }
 160
 161        my $pid = open(my $rev_list,'-|');
 162        defined $pid or croak $!;
 163        if ($pid == 0) {
 164                exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
 165        }
 166        my $latest;
 167        while (<$rev_list>) {
 168                chomp;
 169                my $c = $_;
 170                croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
 171                my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
 172                next if (!@commit); # skip merges
 173                my $id = $commit[$#commit];
 174                my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
 175                                                \s([a-f\d\-]+)$/x);
 176                if (!$rev || !$uuid || !$url) {
 177                        # some of the original repositories I made had
 178                        # indentifiers like this:
 179                        ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
 180                                                        \@([a-f\d\-]+)/x);
 181                        if (!$rev || !$uuid) {
 182                                croak "Unable to extract revision or UUID from ",
 183                                        "$c, $id\n";
 184                        }
 185                }
 186
 187                # if we merged or otherwise started elsewhere, this is
 188                # how we break out of it
 189                next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
 190                next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
 191
 192                print "r$rev = $c\n";
 193                unless (defined $latest) {
 194                        if (!$SVN_URL && !$url) {
 195                                croak "SVN repository location required: $url\n";
 196                        }
 197                        $SVN_URL ||= $url;
 198                        $SVN_UUID ||= $uuid;
 199                        setup_git_svn();
 200                        $latest = $rev;
 201                }
 202                assert_revision_eq_or_unknown($rev, $c);
 203                sys('git-update-ref',"$GIT_SVN/revs/$rev",$c);
 204                $newest_rev = $rev if ($rev > $newest_rev);
 205        }
 206        close $rev_list or croak $?;
 207        if (!chdir $SVN_WC) {
 208                svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
 209                chdir $SVN_WC or croak $!;
 210        }
 211
 212        $pid = fork;
 213        defined $pid or croak $!;
 214        if ($pid == 0) {
 215                my @svn_up = qw(svn up);
 216                push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
 217                sys(@svn_up,"-r$newest_rev");
 218                $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
 219                index_changes();
 220                exec('git-write-tree');
 221        }
 222        waitpid $pid, 0;
 223
 224        if ($_upgrade) {
 225                print STDERR <<"";
 226Keeping deprecated refs/head/$GIT_SVN-HEAD for now.  Please remove it
 227when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
 228
 229        }
 230}
 231
 232sub init {
 233        $SVN_URL = shift or die "SVN repository location required " .
 234                                "as a command-line argument\n";
 235        unless (-d $GIT_DIR) {
 236                sys('git-init-db');
 237        }
 238        setup_git_svn();
 239}
 240
 241sub fetch {
 242        my (@parents) = @_;
 243        check_upgrade_needed();
 244        $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
 245        my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
 246        unless ($_revision) {
 247                $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
 248        }
 249        push @log_args, "-r$_revision";
 250        push @log_args, '--stop-on-copy' unless $_no_stop_copy;
 251
 252        my $svn_log = svn_log_raw(@log_args);
 253
 254        my $base = next_log_entry($svn_log) or croak "No base revision!\n";
 255        my $last_commit = undef;
 256        unless (-d $SVN_WC) {
 257                svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
 258                chdir $SVN_WC or croak $!;
 259                read_uuid();
 260                $last_commit = git_commit($base, @parents);
 261                assert_tree($last_commit);
 262        } else {
 263                chdir $SVN_WC or croak $!;
 264                read_uuid();
 265                $last_commit = file_to_s("$REV_DIR/$base->{revision}");
 266        }
 267        my @svn_up = qw(svn up);
 268        push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
 269        my $last = $base;
 270        while (my $log_msg = next_log_entry($svn_log)) {
 271                assert_tree($last_commit);
 272                if ($last->{revision} >= $log_msg->{revision}) {
 273                        croak "Out of order: last >= current: ",
 274                                "$last->{revision} >= $log_msg->{revision}\n";
 275                }
 276                # Revert is needed for cases like:
 277                # https://svn.musicpd.org/Jamming/trunk (r166:167), but
 278                # I can't seem to reproduce something like that on a test...
 279                sys(qw/svn revert -R ./);
 280                assert_svn_wc_clean($last->{revision});
 281                sys(@svn_up,"-r$log_msg->{revision}");
 282                $last_commit = git_commit($log_msg, $last_commit, @parents);
 283                $last = $log_msg;
 284        }
 285        unless (-e "$GIT_DIR/refs/heads/master") {
 286                sys(qw(git-update-ref refs/heads/master),$last_commit);
 287        }
 288        return $last;
 289}
 290
 291sub commit {
 292        my (@commits) = @_;
 293        check_upgrade_needed();
 294        if ($_stdin || !@commits) {
 295                print "Reading from stdin...\n";
 296                @commits = ();
 297                while (<STDIN>) {
 298                        if (/\b($sha1_short)\b/o) {
 299                                unshift @commits, $1;
 300                        }
 301                }
 302        }
 303        my @revs;
 304        foreach my $c (@commits) {
 305                chomp(my @tmp = safe_qx('git-rev-parse',$c));
 306                if (scalar @tmp == 1) {
 307                        push @revs, $tmp[0];
 308                } elsif (scalar @tmp > 1) {
 309                        push @revs, reverse (safe_qx('git-rev-list',@tmp));
 310                } else {
 311                        die "Failed to rev-parse $c\n";
 312                }
 313        }
 314        chomp @revs;
 315
 316        chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
 317        my $info = svn_info('.');
 318        my $fetched = fetch();
 319        if ($info->{Revision} != $fetched->{revision}) {
 320                print STDERR "There are new revisions that were fetched ",
 321                                "and need to be merged (or acknowledged) ",
 322                                "before committing.\n";
 323                exit 1;
 324        }
 325        $info = svn_info('.');
 326        read_uuid($info);
 327        my $svn_current_rev =  $info->{'Last Changed Rev'};
 328        foreach my $c (@revs) {
 329                my $mods = svn_checkout_tree($svn_current_rev, $c);
 330                if (scalar @$mods == 0) {
 331                        print "Skipping, no changes detected\n";
 332                        next;
 333                }
 334                $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
 335        }
 336        print "Done committing ",scalar @revs," revisions to SVN\n";
 337}
 338
 339sub show_ignore {
 340        require File::Find or die $!;
 341        my $exclude_file = "$GIT_DIR/info/exclude";
 342        open my $fh, '<', $exclude_file or croak $!;
 343        chomp(my @excludes = (<$fh>));
 344        close $fh or croak $!;
 345
 346        $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
 347        chdir $SVN_WC or croak $!;
 348        my %ign;
 349        File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
 350                s#^\./##;
 351                @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
 352                }}, no_chdir=>1},'.');
 353
 354        print "\n# /\n";
 355        foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
 356        delete $ign{'.'};
 357        foreach my $i (sort keys %ign) {
 358                print "\n# ",$i,"\n";
 359                foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
 360        }
 361}
 362
 363########################### utility functions #########################
 364
 365sub read_uuid {
 366        return if $SVN_UUID;
 367        my $info = shift || svn_info('.');
 368        $SVN_UUID = $info->{'Repository UUID'} or
 369                                        croak "Repository UUID unreadable\n";
 370        s_to_file($SVN_UUID,"$GIT_DIR/$GIT_SVN/info/uuid");
 371}
 372
 373sub setup_git_svn {
 374        defined $SVN_URL or croak "SVN repository location required\n";
 375        unless (-d $GIT_DIR) {
 376                croak "GIT_DIR=$GIT_DIR does not exist!\n";
 377        }
 378        mkpath(["$GIT_DIR/$GIT_SVN"]);
 379        mkpath(["$GIT_DIR/$GIT_SVN/info"]);
 380        mkpath([$REV_DIR]);
 381        s_to_file($SVN_URL,"$GIT_DIR/$GIT_SVN/info/url");
 382
 383        open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
 384        print $fd '.svn',"\n";
 385        close $fd or croak $!;
 386}
 387
 388sub assert_svn_wc_clean {
 389        my ($svn_rev) = @_;
 390        croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
 391        my $lcr = svn_info('.')->{'Last Changed Rev'};
 392        if ($svn_rev != $lcr) {
 393                print STDERR "Checking for copy-tree ... ";
 394                my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
 395                                                "-r$lcr:$svn_rev")));
 396                if (@diff) {
 397                        croak "Nope!  Expected r$svn_rev, got r$lcr\n";
 398                } else {
 399                        print STDERR "OK!\n";
 400                }
 401        }
 402        my @status = grep(!/^Performing status on external/,(`svn status`));
 403        @status = grep(!/^\s*$/,@status);
 404        if (scalar @status) {
 405                print STDERR "Tree ($SVN_WC) is not clean:\n";
 406                print STDERR $_ foreach @status;
 407                croak;
 408        }
 409}
 410
 411sub assert_tree {
 412        my ($treeish) = @_;
 413        croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
 414        chomp(my $type = `git-cat-file -t $treeish`);
 415        my $expected;
 416        while ($type eq 'tag') {
 417                chomp(($treeish, $type) = `git-cat-file tag $treeish`);
 418        }
 419        if ($type eq 'commit') {
 420                $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
 421                ($expected) = ($expected =~ /^tree ($sha1)$/);
 422                die "Unable to get tree from $treeish\n" unless $expected;
 423        } elsif ($type eq 'tree') {
 424                $expected = $treeish;
 425        } else {
 426                die "$treeish is a $type, expected tree, tag or commit\n";
 427        }
 428
 429        my $old_index = $ENV{GIT_INDEX_FILE};
 430        my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
 431        if (-e $tmpindex) {
 432                unlink $tmpindex or croak $!;
 433        }
 434        $ENV{GIT_INDEX_FILE} = $tmpindex;
 435        index_changes(1);
 436        chomp(my $tree = `git-write-tree`);
 437        if ($old_index) {
 438                $ENV{GIT_INDEX_FILE} = $old_index;
 439        } else {
 440                delete $ENV{GIT_INDEX_FILE};
 441        }
 442        if ($tree ne $expected) {
 443                croak "Tree mismatch, Got: $tree, Expected: $expected\n";
 444        }
 445        unlink $tmpindex;
 446}
 447
 448sub parse_diff_tree {
 449        my $diff_fh = shift;
 450        local $/ = "\0";
 451        my $state = 'meta';
 452        my @mods;
 453        while (<$diff_fh>) {
 454                chomp $_; # this gets rid of the trailing "\0"
 455                if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
 456                                        $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
 457                        push @mods, {   mode_a => $1, mode_b => $2,
 458                                        sha1_b => $3, chg => $4 };
 459                        if ($4 =~ /^(?:C|R)$/) {
 460                                $state = 'file_a';
 461                        } else {
 462                                $state = 'file_b';
 463                        }
 464                } elsif ($state eq 'file_a') {
 465                        my $x = $mods[$#mods] or croak "Empty array\n";
 466                        if ($x->{chg} !~ /^(?:C|R)$/) {
 467                                croak "Error parsing $_, $x->{chg}\n";
 468                        }
 469                        $x->{file_a} = $_;
 470                        $state = 'file_b';
 471                } elsif ($state eq 'file_b') {
 472                        my $x = $mods[$#mods] or croak "Empty array\n";
 473                        if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
 474                                croak "Error parsing $_, $x->{chg}\n";
 475                        }
 476                        if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
 477                                croak "Error parsing $_, $x->{chg}\n";
 478                        }
 479                        $x->{file_b} = $_;
 480                        $state = 'meta';
 481                } else {
 482                        croak "Error parsing $_\n";
 483                }
 484        }
 485        close $diff_fh or croak $!;
 486
 487        return \@mods;
 488}
 489
 490sub svn_check_prop_executable {
 491        my $m = shift;
 492        return if -l $m->{file_b};
 493        if ($m->{mode_b} =~ /755$/) {
 494                chmod((0755 &~ umask),$m->{file_b}) or croak $!;
 495                if ($m->{mode_a} !~ /755$/) {
 496                        sys(qw(svn propset svn:executable 1), $m->{file_b});
 497                }
 498                -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
 499        } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
 500                sys(qw(svn propdel svn:executable), $m->{file_b});
 501                chmod((0644 &~ umask),$m->{file_b}) or croak $!;
 502                -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
 503        }
 504}
 505
 506sub svn_ensure_parent_path {
 507        my $dir_b = dirname(shift);
 508        svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
 509        mkpath([$dir_b]) unless (-d $dir_b);
 510        sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
 511}
 512
 513sub precommit_check {
 514        my $mods = shift;
 515        my (%rm_file, %rmdir_check, %added_check);
 516
 517        my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
 518        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
 519                if ($m->{chg} eq 'R') {
 520                        if (-d $m->{file_b}) {
 521                                err_dir_to_file("$m->{file_a} => $m->{file_b}");
 522                        }
 523                        # dir/$file => dir/file/$file
 524                        my $dirname = dirname($m->{file_b});
 525                        while ($dirname ne File::Spec->curdir) {
 526                                if ($dirname ne $m->{file_a}) {
 527                                        $dirname = dirname($dirname);
 528                                        next;
 529                                }
 530                                err_file_to_dir("$m->{file_a} => $m->{file_b}");
 531                        }
 532                        # baz/zzz => baz (baz is a file)
 533                        $dirname = dirname($m->{file_a});
 534                        while ($dirname ne File::Spec->curdir) {
 535                                if ($dirname ne $m->{file_b}) {
 536                                        $dirname = dirname($dirname);
 537                                        next;
 538                                }
 539                                err_dir_to_file("$m->{file_a} => $m->{file_b}");
 540                        }
 541                }
 542                if ($m->{chg} =~ /^(D|R)$/) {
 543                        my $t = $1 eq 'D' ? 'file_b' : 'file_a';
 544                        $rm_file{ $m->{$t} } = 1;
 545                        my $dirname = dirname( $m->{$t} );
 546                        my $basename = basename( $m->{$t} );
 547                        $rmdir_check{$dirname}->{$basename} = 1;
 548                } elsif ($m->{chg} =~ /^(?:A|C)$/) {
 549                        if (-d $m->{file_b}) {
 550                                err_dir_to_file($m->{file_b});
 551                        }
 552                        my $dirname = dirname( $m->{file_b} );
 553                        my $basename = basename( $m->{file_b} );
 554                        $added_check{$dirname}->{$basename} = 1;
 555                        while ($dirname ne File::Spec->curdir) {
 556                                if ($rm_file{$dirname}) {
 557                                        err_file_to_dir($m->{file_b});
 558                                }
 559                                $dirname = dirname $dirname;
 560                        }
 561                }
 562        }
 563        return (\%rmdir_check, \%added_check);
 564
 565        sub err_dir_to_file {
 566                my $file = shift;
 567                print STDERR "Node change from directory to file ",
 568                                "is not supported by Subversion: ",$file,"\n";
 569                exit 1;
 570        }
 571        sub err_file_to_dir {
 572                my $file = shift;
 573                print STDERR "Node change from file to directory ",
 574                                "is not supported by Subversion: ",$file,"\n";
 575                exit 1;
 576        }
 577}
 578
 579sub svn_checkout_tree {
 580        my ($svn_rev, $treeish) = @_;
 581        my $from = file_to_s("$REV_DIR/$svn_rev");
 582        assert_tree($from);
 583        print "diff-tree $from $treeish\n";
 584        my $pid = open my $diff_fh, '-|';
 585        defined $pid or croak $!;
 586        if ($pid == 0) {
 587                my @diff_tree = qw(git-diff-tree -z -r);
 588                if ($_cp_similarity) {
 589                        push @diff_tree, "-C$_cp_similarity";
 590                } else {
 591                        push @diff_tree, '-C';
 592                }
 593                push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
 594                push @diff_tree, "-l$_l" if defined $_l;
 595                exec(@diff_tree, $from, $treeish) or croak $!;
 596        }
 597        my $mods = parse_diff_tree($diff_fh);
 598        unless (@$mods) {
 599                # git can do empty commits, but SVN doesn't allow it...
 600                return $mods;
 601        }
 602        my ($rm, $add) = precommit_check($mods);
 603
 604        my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
 605        foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
 606                if ($m->{chg} eq 'C') {
 607                        svn_ensure_parent_path( $m->{file_b} );
 608                        sys(qw(svn cp),         $m->{file_a}, $m->{file_b});
 609                        apply_mod_line_blob($m);
 610                        svn_check_prop_executable($m);
 611                } elsif ($m->{chg} eq 'D') {
 612                        sys(qw(svn rm --force), $m->{file_b});
 613                } elsif ($m->{chg} eq 'R') {
 614                        svn_ensure_parent_path( $m->{file_b} );
 615                        sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
 616                        apply_mod_line_blob($m);
 617                        svn_check_prop_executable($m);
 618                } elsif ($m->{chg} eq 'M') {
 619                        apply_mod_line_blob($m);
 620                        svn_check_prop_executable($m);
 621                } elsif ($m->{chg} eq 'T') {
 622                        sys(qw(svn rm --force),$m->{file_b});
 623                        apply_mod_line_blob($m);
 624                        sys(qw(svn add --force), $m->{file_b});
 625                        svn_check_prop_executable($m);
 626                } elsif ($m->{chg} eq 'A') {
 627                        svn_ensure_parent_path( $m->{file_b} );
 628                        apply_mod_line_blob($m);
 629                        sys(qw(svn add --force), $m->{file_b});
 630                        svn_check_prop_executable($m);
 631                } else {
 632                        croak "Invalid chg: $m->{chg}\n";
 633                }
 634        }
 635
 636        assert_tree($treeish);
 637        if ($_rmdir) { # remove empty directories
 638                handle_rmdir($rm, $add);
 639        }
 640        assert_tree($treeish);
 641        return $mods;
 642}
 643
 644# svn ls doesn't work with respect to the current working tree, but what's
 645# in the repository.  There's not even an option for it... *sigh*
 646# (added files don't show up and removed files remain in the ls listing)
 647sub svn_ls_current {
 648        my ($dir, $rm, $add) = @_;
 649        chomp(my @ls = safe_qx('svn','ls',$dir));
 650        my @ret = ();
 651        foreach (@ls) {
 652                s#/$##; # trailing slashes are evil
 653                push @ret, $_ unless $rm->{$dir}->{$_};
 654        }
 655        if (exists $add->{$dir}) {
 656                push @ret, keys %{$add->{$dir}};
 657        }
 658        return \@ret;
 659}
 660
 661sub handle_rmdir {
 662        my ($rm, $add) = @_;
 663
 664        foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
 665                my $ls = svn_ls_current($dir, $rm, $add);
 666                next if (scalar @$ls);
 667                sys(qw(svn rm --force),$dir);
 668
 669                my $dn = dirname $dir;
 670                $rm->{ $dn }->{ basename $dir } = 1;
 671                $ls = svn_ls_current($dn, $rm, $add);
 672                while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
 673                        sys(qw(svn rm --force),$dn);
 674                        $dir = basename $dn;
 675                        $dn = dirname $dn;
 676                        $rm->{ $dn }->{ $dir } = 1;
 677                        $ls = svn_ls_current($dn, $rm, $add);
 678                }
 679        }
 680}
 681
 682sub svn_commit_tree {
 683        my ($svn_rev, $commit) = @_;
 684        my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
 685        my %log_msg = ( msg => '' );
 686        open my $msg, '>', $commit_msg or croak $!;
 687
 688        chomp(my $type = `git-cat-file -t $commit`);
 689        if ($type eq 'commit') {
 690                my $pid = open my $msg_fh, '-|';
 691                defined $pid or croak $!;
 692
 693                if ($pid == 0) {
 694                        exec(qw(git-cat-file commit), $commit) or croak $!;
 695                }
 696                my $in_msg = 0;
 697                while (<$msg_fh>) {
 698                        if (!$in_msg) {
 699                                $in_msg = 1 if (/^\s*$/);
 700                        } elsif (/^git-svn-id: /) {
 701                                # skip this, we regenerate the correct one
 702                                # on re-fetch anyways
 703                        } else {
 704                                print $msg $_ or croak $!;
 705                        }
 706                }
 707                close $msg_fh or croak $!;
 708        }
 709        close $msg or croak $!;
 710
 711        if ($_edit || ($type eq 'tree')) {
 712                my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
 713                system($editor, $commit_msg);
 714        }
 715
 716        # file_to_s removes all trailing newlines, so just use chomp() here:
 717        open $msg, '<', $commit_msg or croak $!;
 718        { local $/; chomp($log_msg{msg} = <$msg>); }
 719        close $msg or croak $!;
 720
 721        my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
 722        print "Committing $commit: $oneline\n";
 723
 724        if (defined $LC_ALL) {
 725                $ENV{LC_ALL} = $LC_ALL;
 726        } else {
 727                delete $ENV{LC_ALL};
 728        }
 729        my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
 730        $ENV{LC_ALL} = 'C';
 731        unlink $commit_msg;
 732        my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
 733        if (!defined $committed) {
 734                my $out = join("\n",@ci_output);
 735                print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
 736                                $out, "\n\nAssuming English locale...";
 737                ($committed) = ($out =~ /^Committed revision \d+\./sm);
 738                defined $committed or die " FAILED!\n",
 739                        "Commit output failed to parse committed revision!\n",
 740                print STDERR " OK\n";
 741        }
 742
 743        my @svn_up = qw(svn up);
 744        push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
 745        if ($committed == ($svn_rev + 1)) {
 746                push @svn_up, "-r$committed";
 747                sys(@svn_up);
 748                my $info = svn_info('.');
 749                my $date = $info->{'Last Changed Date'} or die "Missing date\n";
 750                if ($info->{'Last Changed Rev'} != $committed) {
 751                        croak "$info->{'Last Changed Rev'} != $committed\n"
 752                }
 753                my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
 754                                        /(\d{4})\-(\d\d)\-(\d\d)\s
 755                                         (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
 756                                         or croak "Failed to parse date: $date\n";
 757                $log_msg{date} = "$tz $Y-$m-$d $H:$M:$S";
 758                $log_msg{author} = $info->{'Last Changed Author'};
 759                $log_msg{revision} = $committed;
 760                $log_msg{msg} .= "\n";
 761                my $parent = file_to_s("$REV_DIR/$svn_rev");
 762                git_commit(\%log_msg, $parent, $commit);
 763                return $committed;
 764        }
 765        # resync immediately
 766        push @svn_up, "-r$svn_rev";
 767        sys(@svn_up);
 768        return fetch("$committed=$commit")->{revision};
 769}
 770
 771# read the entire log into a temporary file (which is removed ASAP)
 772# and store the file handle + parser state
 773sub svn_log_raw {
 774        my (@log_args) = @_;
 775        my $log_fh = IO::File->new_tmpfile or croak $!;
 776        my $pid = fork;
 777        defined $pid or croak $!;
 778        if (!$pid) {
 779                open STDOUT, '>&', $log_fh or croak $!;
 780                exec (qw(svn log), @log_args) or croak $!
 781        }
 782        waitpid $pid, 0;
 783        croak if $?;
 784        seek $log_fh, 0, 0 or croak $!;
 785        return { state => 'sep', fh => $log_fh };
 786}
 787
 788sub next_log_entry {
 789        my $log = shift; # retval of svn_log_raw()
 790        my $ret = undef;
 791        my $fh = $log->{fh};
 792
 793        while (<$fh>) {
 794                chomp;
 795                if (/^\-{72}$/) {
 796                        if ($log->{state} eq 'msg') {
 797                                if ($ret->{lines}) {
 798                                        $ret->{msg} .= $_."\n";
 799                                        unless(--$ret->{lines}) {
 800                                                $log->{state} = 'sep';
 801                                        }
 802                                } else {
 803                                        croak "Log parse error at: $_\n",
 804                                                $ret->{revision},
 805                                                "\n";
 806                                }
 807                                next;
 808                        }
 809                        if ($log->{state} ne 'sep') {
 810                                croak "Log parse error at: $_\n",
 811                                        "state: $log->{state}\n",
 812                                        $ret->{revision},
 813                                        "\n";
 814                        }
 815                        $log->{state} = 'rev';
 816
 817                        # if we have an empty log message, put something there:
 818                        if ($ret) {
 819                                $ret->{msg} ||= "\n";
 820                                delete $ret->{lines};
 821                                return $ret;
 822                        }
 823                        next;
 824                }
 825                if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
 826                        my $rev = $1;
 827                        my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
 828                        ($lines) = ($lines =~ /(\d+)/);
 829                        my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
 830                                        /(\d{4})\-(\d\d)\-(\d\d)\s
 831                                         (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
 832                                         or croak "Failed to parse date: $date\n";
 833                        $ret = {        revision => $rev,
 834                                        date => "$tz $Y-$m-$d $H:$M:$S",
 835                                        author => $author,
 836                                        lines => $lines,
 837                                        msg => '' };
 838                        if (defined $_authors && ! defined $users{$author}) {
 839                                die "Author: $author not defined in ",
 840                                                "$_authors file\n";
 841                        }
 842                        $log->{state} = 'msg_start';
 843                        next;
 844                }
 845                # skip the first blank line of the message:
 846                if ($log->{state} eq 'msg_start' && /^$/) {
 847                        $log->{state} = 'msg';
 848                } elsif ($log->{state} eq 'msg') {
 849                        if ($ret->{lines}) {
 850                                $ret->{msg} .= $_."\n";
 851                                unless (--$ret->{lines}) {
 852                                        $log->{state} = 'sep';
 853                                }
 854                        } else {
 855                                croak "Log parse error at: $_\n",
 856                                        $ret->{revision},"\n";
 857                        }
 858                }
 859        }
 860        return $ret;
 861}
 862
 863sub svn_info {
 864        my $url = shift || $SVN_URL;
 865
 866        my $pid = open my $info_fh, '-|';
 867        defined $pid or croak $!;
 868
 869        if ($pid == 0) {
 870                exec(qw(svn info),$url) or croak $!;
 871        }
 872
 873        my $ret = {};
 874        # only single-lines seem to exist in svn info output
 875        while (<$info_fh>) {
 876                chomp $_;
 877                if (m#^([^:]+)\s*:\s*(\S.*)$#) {
 878                        $ret->{$1} = $2;
 879                        push @{$ret->{-order}}, $1;
 880                }
 881        }
 882        close $info_fh or croak $!;
 883        return $ret;
 884}
 885
 886sub sys { system(@_) == 0 or croak $? }
 887
 888sub eol_cp {
 889        my ($from, $to) = @_;
 890        my $es = svn_propget_base('svn:eol-style', $to);
 891        open my $rfd, '<', $from or croak $!;
 892        binmode $rfd or croak $!;
 893        open my $wfd, '>', $to or croak $!;
 894        binmode $wfd or croak $!;
 895
 896        my $eol = $EOL{$es} or undef;
 897        my $buf;
 898        use bytes;
 899        while (1) {
 900                my ($r, $w, $t);
 901                defined($r = sysread($rfd, $buf, 4096)) or croak $!;
 902                return unless $r;
 903                if ($eol) {
 904                        if ($buf =~ /\015$/) {
 905                                my $c;
 906                                defined($r = sysread($rfd,$c,1)) or croak $!;
 907                                $buf .= $c if $r > 0;
 908                        }
 909                        $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
 910                        $r = length($buf);
 911                }
 912                for ($w = 0; $w < $r; $w += $t) {
 913                        $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
 914                }
 915        }
 916        no bytes;
 917}
 918
 919sub do_update_index {
 920        my ($z_cmd, $cmd, $no_text_base) = @_;
 921
 922        my $z = open my $p, '-|';
 923        defined $z or croak $!;
 924        unless ($z) { exec @$z_cmd or croak $! }
 925
 926        my $pid = open my $ui, '|-';
 927        defined $pid or croak $!;
 928        unless ($pid) {
 929                exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
 930        }
 931        local $/ = "\0";
 932        while (my $x = <$p>) {
 933                chomp $x;
 934                if (!$no_text_base && lstat $x && ! -l _ &&
 935                                svn_propget_base('svn:keywords', $x)) {
 936                        my $mode = -x _ ? 0755 : 0644;
 937                        my ($v,$d,$f) = File::Spec->splitpath($x);
 938                        my $tb = File::Spec->catfile($d, '.svn', 'tmp',
 939                                                'text-base',"$f.svn-base");
 940                        $tb =~ s#^/##;
 941                        unless (-f $tb) {
 942                                $tb = File::Spec->catfile($d, '.svn',
 943                                                'text-base',"$f.svn-base");
 944                                $tb =~ s#^/##;
 945                        }
 946                        unlink $x or croak $!;
 947                        eol_cp($tb, $x);
 948                        chmod(($mode &~ umask), $x) or croak $!;
 949                }
 950                print $ui $x,"\0";
 951        }
 952        close $ui or croak $!;
 953}
 954
 955sub index_changes {
 956        my $no_text_base = shift;
 957        do_update_index([qw/git-diff-files --name-only -z/],
 958                        'remove',
 959                        $no_text_base);
 960        do_update_index([qw/git-ls-files -z --others/,
 961                              "--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude"],
 962                        'add',
 963                        $no_text_base);
 964}
 965
 966sub s_to_file {
 967        my ($str, $file, $mode) = @_;
 968        open my $fd,'>',$file or croak $!;
 969        print $fd $str,"\n" or croak $!;
 970        close $fd or croak $!;
 971        chmod ($mode &~ umask, $file) if (defined $mode);
 972}
 973
 974sub file_to_s {
 975        my $file = shift;
 976        open my $fd,'<',$file or croak "$!: file: $file\n";
 977        local $/;
 978        my $ret = <$fd>;
 979        close $fd or croak $!;
 980        $ret =~ s/\s*$//s;
 981        return $ret;
 982}
 983
 984sub assert_revision_unknown {
 985        my $revno = shift;
 986        if (-f "$REV_DIR/$revno") {
 987                croak "$REV_DIR/$revno already exists! ",
 988                                "Why are we refetching it?";
 989        }
 990}
 991
 992sub trees_eq {
 993        my ($x, $y) = @_;
 994        my @x = safe_qx('git-cat-file','commit',$x);
 995        my @y = safe_qx('git-cat-file','commit',$y);
 996        if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
 997                                || $y[0] !~ /^tree $sha1\n$/) {
 998                print STDERR "Trees not equal: $y[0] != $x[0]\n";
 999                return 0
1000        }
1001        return 1;
1002}
1003
1004sub assert_revision_eq_or_unknown {
1005        my ($revno, $commit) = @_;
1006        if (-f "$REV_DIR/$revno") {
1007                my $current = file_to_s("$REV_DIR/$revno");
1008                if (($commit ne $current) && !trees_eq($commit, $current)) {
1009                        croak "$REV_DIR/$revno already exists!\n",
1010                                "current: $current\nexpected: $commit\n";
1011                }
1012                return;
1013        }
1014}
1015
1016sub git_commit {
1017        my ($log_msg, @parents) = @_;
1018        assert_revision_unknown($log_msg->{revision});
1019        my $out_fh = IO::File->new_tmpfile or croak $!;
1020
1021        map_tree_joins() if (@_branch_from && !%tree_map);
1022
1023        # commit parents can be conditionally bound to a particular
1024        # svn revision via: "svn_revno=commit_sha1", filter them out here:
1025        my @exec_parents;
1026        foreach my $p (@parents) {
1027                next unless defined $p;
1028                if ($p =~ /^(\d+)=($sha1_short)$/o) {
1029                        if ($1 == $log_msg->{revision}) {
1030                                push @exec_parents, $2;
1031                        }
1032                } else {
1033                        push @exec_parents, $p if $p =~ /$sha1_short/o;
1034                }
1035        }
1036
1037        my $pid = fork;
1038        defined $pid or croak $!;
1039        if ($pid == 0) {
1040                $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
1041                index_changes();
1042                chomp(my $tree = `git-write-tree`);
1043                croak if $?;
1044                if (exists $tree_map{$tree}) {
1045                        my %seen_parent = map { $_ => 1 } @exec_parents;
1046                        foreach (@{$tree_map{$tree}}) {
1047                                # MAXPARENT is defined to 16 in commit-tree.c:
1048                                if ($seen_parent{$_} || @exec_parents > 16) {
1049                                        next;
1050                                }
1051                                push @exec_parents, $_;
1052                                $seen_parent{$_} = 1;
1053                        }
1054                }
1055                my $msg_fh = IO::File->new_tmpfile or croak $!;
1056                print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1057                                        "$SVN_URL\@$log_msg->{revision}",
1058                                        " $SVN_UUID\n" or croak $!;
1059                $msg_fh->flush == 0 or croak $!;
1060                seek $msg_fh, 0, 0 or croak $!;
1061
1062                set_commit_env($log_msg);
1063
1064                my @exec = ('git-commit-tree',$tree);
1065                push @exec, '-p', $_  foreach @exec_parents;
1066                open STDIN, '<&', $msg_fh or croak $!;
1067                open STDOUT, '>&', $out_fh or croak $!;
1068                exec @exec or croak $!;
1069        }
1070        waitpid($pid,0);
1071        croak if $?;
1072
1073        $out_fh->flush == 0 or croak $!;
1074        seek $out_fh, 0, 0 or croak $!;
1075        chomp(my $commit = do { local $/; <$out_fh> });
1076        if ($commit !~ /^$sha1$/o) {
1077                croak "Failed to commit, invalid sha1: $commit\n";
1078        }
1079        my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1080        if (my $primary_parent = shift @exec_parents) {
1081                $pid = fork;
1082                defined $pid or croak $!;
1083                if (!$pid) {
1084                        close STDERR;
1085                        close STDOUT;
1086                        exec 'git-rev-parse','--verify',
1087                                                "refs/remotes/$GIT_SVN^0";
1088                }
1089                waitpid $pid, 0;
1090                push @update_ref, $primary_parent unless $?;
1091        }
1092        sys(@update_ref);
1093        sys('git-update-ref',"$GIT_SVN/revs/$log_msg->{revision}",$commit);
1094        print "r$log_msg->{revision} = $commit\n";
1095        return $commit;
1096}
1097
1098sub set_commit_env {
1099        my ($log_msg) = @_;
1100        my $author = $log_msg->{author};
1101        my ($name,$email) = defined $users{$author} ?  @{$users{$author}}
1102                                : ($author,"$author\@$SVN_UUID");
1103        $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1104        $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1105        $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1106}
1107
1108sub apply_mod_line_blob {
1109        my $m = shift;
1110        if ($m->{mode_b} =~ /^120/) {
1111                blob_to_symlink($m->{sha1_b}, $m->{file_b});
1112        } else {
1113                blob_to_file($m->{sha1_b}, $m->{file_b});
1114        }
1115}
1116
1117sub blob_to_symlink {
1118        my ($blob, $link) = @_;
1119        defined $link or croak "\$link not defined!\n";
1120        croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1121        if (-l $link || -f _) {
1122                unlink $link or croak $!;
1123        }
1124
1125        my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1126        symlink $dest, $link or croak $!;
1127}
1128
1129sub blob_to_file {
1130        my ($blob, $file) = @_;
1131        defined $file or croak "\$file not defined!\n";
1132        croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1133        if (-l $file || -f _) {
1134                unlink $file or croak $!;
1135        }
1136
1137        open my $blob_fh, '>', $file or croak "$!: $file\n";
1138        my $pid = fork;
1139        defined $pid or croak $!;
1140
1141        if ($pid == 0) {
1142                open STDOUT, '>&', $blob_fh or croak $!;
1143                exec('git-cat-file','blob',$blob);
1144        }
1145        waitpid $pid, 0;
1146        croak $? if $?;
1147
1148        close $blob_fh or croak $!;
1149}
1150
1151sub safe_qx {
1152        my $pid = open my $child, '-|';
1153        defined $pid or croak $!;
1154        if ($pid == 0) {
1155                exec(@_) or croak $?;
1156        }
1157        my @ret = (<$child>);
1158        close $child or croak $?;
1159        die $? if $?; # just in case close didn't error out
1160        return wantarray ? @ret : join('',@ret);
1161}
1162
1163sub svn_compat_check {
1164        my @co_help = safe_qx(qw(svn co -h));
1165        unless (grep /ignore-externals/,@co_help) {
1166                print STDERR "W: Installed svn version does not support ",
1167                                "--ignore-externals\n";
1168                $_no_ignore_ext = 1;
1169        }
1170        if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1171                $_svn_co_url_revs = 1;
1172        }
1173        if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1174                $_svn_pg_peg_revs = 1;
1175        }
1176
1177        # I really, really hope nobody hits this...
1178        unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1179                print STDERR <<'';
1180W: The installed svn version does not support the --stop-on-copy flag in
1181   the log command.
1182   Lets hope the directory you're tracking is not a branch or tag
1183   and was never moved within the repository...
1184
1185                $_no_stop_copy = 1;
1186        }
1187}
1188
1189# *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1190# (and they won't honor URL@<rev> without -r<rev>, too!)
1191sub svn_cmd_checkout {
1192        my ($url, $rev, $dir) = @_;
1193        my @cmd = ('svn','co', "-r$rev");
1194        push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1195        $url .= "\@$rev" if $_svn_co_url_revs;
1196        sys(@cmd, $url, $dir);
1197}
1198
1199sub check_upgrade_needed {
1200        my $old = eval {
1201                my $pid = open my $child, '-|';
1202                defined $pid or croak $!;
1203                if ($pid == 0) {
1204                        close STDERR;
1205                        exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $?;
1206                }
1207                my @ret = (<$child>);
1208                close $child or croak $?;
1209                die $? if $?; # just in case close didn't error out
1210                return wantarray ? @ret : join('',@ret);
1211        };
1212        return unless $old;
1213        my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1214        if ($@ || !$head) {
1215                print STDERR "Please run: $0 rebuild --upgrade\n";
1216                exit 1;
1217        }
1218}
1219
1220# fills %tree_map with a reverse mapping of trees to commits.  Useful
1221# for finding parents to commit on.
1222sub map_tree_joins {
1223        my %seen;
1224        foreach my $br (@_branch_from) {
1225                my $pid = open my $pipe, '-|';
1226                defined $pid or croak $!;
1227                if ($pid == 0) {
1228                        exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1229                                                                or croak $?;
1230                }
1231                while (<$pipe>) {
1232                        if (/^commit ($sha1)$/o) {
1233                                my $commit = $1;
1234
1235                                # if we've seen a commit,
1236                                # we've seen its parents
1237                                last if $seen{$commit};
1238                                my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1239                                unless (defined $tree) {
1240                                        die "Failed to parse commit $commit\n";
1241                                }
1242                                push @{$tree_map{$tree}}, $commit;
1243                                $seen{$commit} = 1;
1244                        }
1245                }
1246                close $pipe; # we could be breaking the pipe early
1247        }
1248}
1249
1250sub load_all_refs {
1251        if (@_branch_from) {
1252                print STDERR '--branch|-b parameters are ignored when ',
1253                        "--branch-all-refs|-B is passed\n";
1254        }
1255
1256        # don't worry about rev-list on non-commit objects/tags,
1257        # it shouldn't blow up if a ref is a blob or tree...
1258        chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1259}
1260
1261# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1262sub load_authors {
1263        open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1264        while (<$authors>) {
1265                chomp;
1266                next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1267                my ($user, $name, $email) = ($1, $2, $3);
1268                $users{$user} = [$name, $email];
1269        }
1270        close $authors or croak $!;
1271}
1272
1273sub svn_propget_base {
1274        my ($p, $f) = @_;
1275        $f .= '@BASE' if $_svn_pg_peg_revs;
1276        return safe_qx(qw/svn propget/, $p, $f);
1277}
1278
1279__END__
1280
1281Data structures:
1282
1283$svn_log hashref (as returned by svn_log_raw)
1284{
1285        fh => file handle of the log file,
1286        state => state of the log file parser (sep/msg/rev/msg_start...)
1287}
1288
1289$log_msg hashref as returned by next_log_entry($svn_log)
1290{
1291        msg => 'whitespace-formatted log entry
1292',                                              # trailing newline is preserved
1293        revision => '8',                        # integer
1294        date => '2004-02-24T17:01:44.108345Z',  # commit date
1295        author => 'committer name'
1296};
1297
1298
1299@mods = array of diff-index line hashes, each element represents one line
1300        of diff-index output
1301
1302diff-index line ($m hash)
1303{
1304        mode_a => first column of diff-index output, no leading ':',
1305        mode_b => second column of diff-index output,
1306        sha1_b => sha1sum of the final blob,
1307        chg => change type [MCRADT],
1308        file_a => original file name of a file (iff chg is 'C' or 'R')
1309        file_b => new/current file name of a file (any chg)
1310}
1311;