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