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