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