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