71a8b3b2e69a47a4f1919589058121ac576f247c
   1#!/usr/bin/env perl
   2use warnings;
   3use strict;
   4use vars qw/    $AUTHOR $VERSION
   5                $SVN_URL $SVN_INFO $SVN_WC
   6                $GIT_SVN_INDEX $GIT_SVN
   7                $GIT_DIR $REV_DIR/;
   8$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
   9$VERSION = '0.9.0';
  10$GIT_DIR = $ENV{GIT_DIR} || "$ENV{PWD}/.git";
  11$GIT_SVN = $ENV{GIT_SVN_ID} || 'git-svn';
  12$GIT_SVN_INDEX = "$GIT_DIR/$GIT_SVN/index";
  13$ENV{GIT_DIR} ||= $GIT_DIR;
  14$SVN_URL = undef;
  15$REV_DIR = "$GIT_DIR/$GIT_SVN/revs";
  16$SVN_WC = "$GIT_DIR/$GIT_SVN/tree";
  17
  18# make sure the svn binary gives consistent output between locales and TZs:
  19$ENV{TZ} = 'UTC';
  20$ENV{LC_ALL} = 'C';
  21
  22# If SVN:: library support is added, please make the dependencies
  23# optional and preserve the capability to use the command-line client.
  24# See what I do with XML::Simple to make the dependency optional.
  25use Carp qw/croak/;
  26use IO::File qw//;
  27use File::Basename qw/dirname basename/;
  28use File::Path qw/mkpath/;
  29use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
  30use File::Spec qw//;
  31my $sha1 = qr/[a-f\d]{40}/;
  32my $sha1_short = qr/[a-f\d]{6,40}/;
  33my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit);
  34
  35GetOptions(     'revision|r=s' => \$_revision,
  36                'no-ignore-externals' => \$_no_ignore_ext,
  37                'stdin|' => \$_stdin,
  38                'edit|e' => \$_edit,
  39                'rmdir' => \$_rmdir,
  40                'help|H|h' => \$_help,
  41                'no-stop-copy' => \$_no_stop_copy );
  42my %cmd = (
  43        fetch => [ \&fetch, "Download new revisions from SVN" ],
  44        init => [ \&init, "Initialize and fetch (import)"],
  45        commit => [ \&commit, "Commit git revisions to SVN" ],
  46        rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)" ],
  47        help => [ \&usage, "Show help" ],
  48);
  49my $cmd;
  50for (my $i = 0; $i < @ARGV; $i++) {
  51        if (defined $cmd{$ARGV[$i]}) {
  52                $cmd = $ARGV[$i];
  53                splice @ARGV, $i, 1;
  54                last;
  55        }
  56};
  57
  58# we may be called as git-svn-(command), or git-svn(command).
  59foreach (keys %cmd) {
  60        if (/git\-svn\-?($_)(?:\.\w+)?$/) {
  61                $cmd = $1;
  62                last;
  63        }
  64}
  65usage(0) if $_help;
  66usage(1) unless (defined $cmd);
  67svn_check_ignore_externals();
  68$cmd{$cmd}->[0]->(@ARGV);
  69exit 0;
  70
  71####################### primary functions ######################
  72sub usage {
  73        my $exit = shift || 0;
  74        my $fd = $exit ? \*STDERR : \*STDOUT;
  75        print $fd <<"";
  76git-svn - bidirectional operations between a single Subversion tree and git
  77Usage: $0 <command> [options] [arguments]\n
  78Available commands:
  79
  80        foreach (sort keys %cmd) {
  81                print $fd '  ',pack('A10',$_),$cmd{$_}->[1],"\n";
  82        }
  83        print $fd <<"";
  84\nGIT_SVN_ID may be set in the environment to an arbitrary identifier if
  85you're tracking multiple SVN branches/repositories in one git repository
  86and want to keep them separate.
  87
  88        exit $exit;
  89}
  90
  91sub rebuild {
  92        $SVN_URL = shift or undef;
  93        my $repo_uuid;
  94        my $newest_rev = 0;
  95
  96        my $pid = open(my $rev_list,'-|');
  97        defined $pid or croak $!;
  98        if ($pid == 0) {
  99                exec("git-rev-list","$GIT_SVN-HEAD") or croak $!;
 100        }
 101        my $first;
 102        while (<$rev_list>) {
 103                chomp;
 104                my $c = $_;
 105                croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
 106                my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
 107                next if (!@commit); # skip merges
 108                my $id = $commit[$#commit];
 109                my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
 110                                                \s([a-f\d\-]+)$/x);
 111                if (!$rev || !$uuid || !$url) {
 112                        # some of the original repositories I made had
 113                        # indentifiers like this:
 114                        ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
 115                                                        \@([a-f\d\-]+)/x);
 116                        if (!$rev || !$uuid) {
 117                                croak "Unable to extract revision or UUID from ",
 118                                        "$c, $id\n";
 119                        }
 120                }
 121                print "r$rev = $c\n";
 122                unless (defined $first) {
 123                        if (!$SVN_URL && !$url) {
 124                                croak "SVN repository location required: $url\n";
 125                        }
 126                        $SVN_URL ||= $url;
 127                        $repo_uuid = setup_git_svn();
 128                        $first = $rev;
 129                }
 130                if ($uuid ne $repo_uuid) {
 131                        croak "Repository UUIDs do not match!\ngot: $uuid\n",
 132                                                "expected: $repo_uuid\n";
 133                }
 134                assert_revision_eq_or_unknown($rev, $c);
 135                sys('git-update-ref',"$GIT_SVN/revs/$rev",$c);
 136                $newest_rev = $rev if ($rev > $newest_rev);
 137        }
 138        close $rev_list or croak $?;
 139        if (!chdir $SVN_WC) {
 140                my @svn_co = ('svn','co',"-r$first");
 141                push @svn_co, '--ignore-externals' unless $_no_ignore_ext;
 142                sys(@svn_co, $SVN_URL, $SVN_WC);
 143                chdir $SVN_WC or croak $!;
 144        }
 145
 146        $pid = fork;
 147        defined $pid or croak $!;
 148        if ($pid == 0) {
 149                my @svn_up = qw(svn up);
 150                push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
 151                sys(@svn_up,"-r$newest_rev");
 152                $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
 153                git_addremove();
 154                exec('git-write-tree');
 155        }
 156        waitpid $pid, 0;
 157}
 158
 159sub init {
 160        $SVN_URL = shift or croak "SVN repository location required\n";
 161        unless (-d $GIT_DIR) {
 162                sys('git-init-db');
 163        }
 164        setup_git_svn();
 165}
 166
 167sub fetch {
 168        my (@parents) = @_;
 169        $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
 170        my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
 171        unless ($_revision) {
 172                $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
 173        }
 174        push @log_args, "-r$_revision";
 175        push @log_args, '--stop-on-copy' unless $_no_stop_copy;
 176
 177        eval { require XML::Simple or croak $! };
 178        my $svn_log = $@ ? svn_log_raw(@log_args) : svn_log_xml(@log_args);
 179        @$svn_log = sort { $a->{revision} <=> $b->{revision} } @$svn_log;
 180
 181        my $base = shift @$svn_log or croak "No base revision!\n";
 182        my $last_commit = undef;
 183        unless (-d $SVN_WC) {
 184                my @svn_co = ('svn','co',"-r$base->{revision}");
 185                push @svn_co,'--ignore-externals' unless $_no_ignore_ext;
 186                sys(@svn_co, $SVN_URL, $SVN_WC);
 187                chdir $SVN_WC or croak $!;
 188                $last_commit = git_commit($base, @parents);
 189                unless (-f "$GIT_DIR/refs/heads/master") {
 190                        sys(qw(git-update-ref refs/heads/master),$last_commit);
 191                }
 192                assert_svn_wc_clean($base->{revision}, $last_commit);
 193        } else {
 194                chdir $SVN_WC or croak $!;
 195                $last_commit = file_to_s("$REV_DIR/$base->{revision}");
 196        }
 197        my @svn_up = qw(svn up);
 198        push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
 199        my $last_rev = $base->{revision};
 200        foreach my $log_msg (@$svn_log) {
 201                assert_svn_wc_clean($last_rev, $last_commit);
 202                $last_rev = $log_msg->{revision};
 203                sys(@svn_up,"-r$last_rev");
 204                $last_commit = git_commit($log_msg, $last_commit, @parents);
 205        }
 206        assert_svn_wc_clean($last_rev, $last_commit);
 207        return pop @$svn_log;
 208}
 209
 210sub commit {
 211        my (@commits) = @_;
 212        if ($_stdin || !@commits) {
 213                print "Reading from stdin...\n";
 214                @commits = ();
 215                while (<STDIN>) {
 216                        if (/^([a-f\d]{6,40})\b/) {
 217                                unshift @commits, $1;
 218                        }
 219                }
 220        }
 221        my @revs;
 222        foreach (@commits) {
 223                push @revs, (safe_qx('git-rev-parse',$_));
 224        }
 225        chomp @revs;
 226
 227        fetch();
 228        chdir $SVN_WC or croak $!;
 229        my $svn_current_rev =  svn_info('.')->{'Last Changed Rev'};
 230        foreach my $c (@revs) {
 231                print "Committing $c\n";
 232                svn_checkout_tree($svn_current_rev, $c);
 233                $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
 234        }
 235        print "Done committing ",scalar @revs," revisions to SVN\n";
 236
 237}
 238
 239########################### utility functions #########################
 240
 241sub setup_git_svn {
 242        defined $SVN_URL or croak "SVN repository location required\n";
 243        unless (-d $GIT_DIR) {
 244                croak "GIT_DIR=$GIT_DIR does not exist!\n";
 245        }
 246        mkpath(["$GIT_DIR/$GIT_SVN"]);
 247        mkpath(["$GIT_DIR/$GIT_SVN/info"]);
 248        mkpath([$REV_DIR]);
 249        s_to_file($SVN_URL,"$GIT_DIR/$GIT_SVN/info/url");
 250        my $uuid = svn_info($SVN_URL)->{'Repository UUID'} or
 251                                        croak "Repository UUID unreadable\n";
 252        s_to_file($uuid,"$GIT_DIR/$GIT_SVN/info/uuid");
 253
 254        open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
 255        print $fd '.svn',"\n";
 256        close $fd or croak $!;
 257        return $uuid;
 258}
 259
 260sub assert_svn_wc_clean {
 261        my ($svn_rev, $commit) = @_;
 262        croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
 263        croak "$commit is not a sha1!\n" unless ($commit =~ /^$sha1$/o);
 264        my $svn_info = svn_info('.');
 265        if ($svn_rev != $svn_info->{'Last Changed Rev'}) {
 266                croak "Expected r$svn_rev, got r",
 267                                $svn_info->{'Last Changed Rev'},"\n";
 268        }
 269        my @status = grep(!/^Performing status on external/,(`svn status`));
 270        @status = grep(!/^\s*$/,@status);
 271        if (scalar @status) {
 272                print STDERR "Tree ($SVN_WC) is not clean:\n";
 273                print STDERR $_ foreach @status;
 274                croak;
 275        }
 276        my ($tree_a) = grep(/^tree $sha1$/o,`git-cat-file commit $commit`);
 277        $tree_a =~ s/^tree //;
 278        chomp $tree_a;
 279        chomp(my $tree_b = `GIT_INDEX_FILE=$GIT_SVN_INDEX git-write-tree`);
 280        if ($tree_a ne $tree_b) {
 281                croak "$svn_rev != $commit, $tree_a != $tree_b\n";
 282        }
 283}
 284
 285sub parse_diff_tree {
 286        my $diff_fh = shift;
 287        local $/ = "\0";
 288        my $state = 'meta';
 289        my @mods;
 290        while (<$diff_fh>) {
 291                chomp $_; # this gets rid of the trailing "\0"
 292                print $_,"\n";
 293                if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
 294                                        $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
 295                        push @mods, {   mode_a => $1, mode_b => $2,
 296                                        sha1_b => $3, chg => $4 };
 297                        if ($4 =~ /^(?:C|R)$/) {
 298                                $state = 'file_a';
 299                        } else {
 300                                $state = 'file_b';
 301                        }
 302                } elsif ($state eq 'file_a') {
 303                        my $x = $mods[$#mods] or croak __LINE__,": Empty array\n";
 304                        if ($x->{chg} !~ /^(?:C|R)$/) {
 305                                croak __LINE__,": Error parsing $_, $x->{chg}\n";
 306                        }
 307                        $x->{file_a} = $_;
 308                        $state = 'file_b';
 309                } elsif ($state eq 'file_b') {
 310                        my $x = $mods[$#mods] or croak __LINE__,": Empty array\n";
 311                        if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
 312                                croak __LINE__,": Error parsing $_, $x->{chg}\n";
 313                        }
 314                        if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
 315                                croak __LINE__,": Error parsing $_, $x->{chg}\n";
 316                        }
 317                        $x->{file_b} = $_;
 318                        $state = 'meta';
 319                } else {
 320                        croak __LINE__,": Error parsing $_\n";
 321                }
 322        }
 323        close $diff_fh or croak $!;
 324        return \@mods;
 325}
 326
 327sub svn_check_prop_executable {
 328        my $m = shift;
 329        if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
 330                sys(qw(svn propset svn:executable 1), $m->{file_b});
 331        } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
 332                sys(qw(svn propdel svn:executable), $m->{file_b});
 333        }
 334}
 335
 336sub svn_ensure_parent_path {
 337        my $dir_b = dirname(shift);
 338        svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
 339        mkpath([$dir_b]) unless (-d $dir_b);
 340        sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
 341}
 342
 343sub svn_checkout_tree {
 344        my ($svn_rev, $commit) = @_;
 345        my $from = file_to_s("$REV_DIR/$svn_rev");
 346        assert_svn_wc_clean($svn_rev,$from);
 347        print "diff-tree '$from' '$commit'\n";
 348        my $pid = open my $diff_fh, '-|';
 349        defined $pid or croak $!;
 350        if ($pid == 0) {
 351                exec(qw(git-diff-tree -z -r -C), $from, $commit) or croak $!;
 352        }
 353        my $mods = parse_diff_tree($diff_fh);
 354        unless (@$mods) {
 355                # git can do empty commits, SVN doesn't allow it...
 356                return $svn_rev;
 357        }
 358        my %rm;
 359        foreach my $m (@$mods) {
 360                if ($m->{chg} eq 'C') {
 361                        svn_ensure_parent_path( $m->{file_b} );
 362                        sys(qw(svn cp),         $m->{file_a}, $m->{file_b});
 363                        blob_to_file(           $m->{sha1_b}, $m->{file_b});
 364                        svn_check_prop_executable($m);
 365                } elsif ($m->{chg} eq 'D') {
 366                        $rm{dirname $m->{file_b}}->{basename $m->{file_b}} = 1;
 367                        sys(qw(svn rm --force), $m->{file_b});
 368                } elsif ($m->{chg} eq 'R') {
 369                        svn_ensure_parent_path( $m->{file_b} );
 370                        sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
 371                        blob_to_file(           $m->{sha1_b}, $m->{file_b});
 372                        svn_check_prop_executable($m);
 373                        $rm{dirname $m->{file_a}}->{basename $m->{file_a}} = 1;
 374                } elsif ($m->{chg} eq 'M') {
 375                        if ($m->{mode_b} =~ /^120/ && $m->{mode_a} =~ /^120/) {
 376                                unlink $m->{file_b} or croak $!;
 377                                blob_to_symlink($m->{sha1_b}, $m->{file_b});
 378                        } else {
 379                                blob_to_file($m->{sha1_b}, $m->{file_b});
 380                        }
 381                        svn_check_prop_executable($m);
 382                } elsif ($m->{chg} eq 'T') {
 383                        sys(qw(svn rm --force),$m->{file_b});
 384                        if ($m->{mode_b} =~ /^120/ && $m->{mode_a} =~ /^100/) {
 385                                blob_to_symlink($m->{sha1_b}, $m->{file_b});
 386                        } else {
 387                                blob_to_file($m->{sha1_b}, $m->{file_b});
 388                        }
 389                        svn_check_prop_executable($m);
 390                        sys(qw(svn add --force), $m->{file_b});
 391                } elsif ($m->{chg} eq 'A') {
 392                        svn_ensure_parent_path( $m->{file_b} );
 393                        blob_to_file(           $m->{sha1_b}, $m->{file_b});
 394                        if ($m->{mode_b} =~ /755$/) {
 395                                chmod 0755, $m->{file_b};
 396                        }
 397                        sys(qw(svn add --force), $m->{file_b});
 398                } else {
 399                        croak "Invalid chg: $m->{chg}\n";
 400                }
 401        }
 402        if ($_rmdir) {
 403                my $old_index = $ENV{GIT_INDEX_FILE};
 404                $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
 405                foreach my $dir (keys %rm) {
 406                        my $files = $rm{$dir};
 407                        my @files;
 408                        foreach (safe_qx('svn','ls',$dir)) {
 409                                chomp;
 410                                push @files, $_ unless $files->{$_};
 411                        }
 412                        sys(qw(svn rm),$dir) unless @files;
 413                }
 414                if ($old_index) {
 415                        $ENV{GIT_INDEX_FILE} = $old_index;
 416                } else {
 417                        delete $ENV{GIT_INDEX_FILE};
 418                }
 419        }
 420}
 421
 422sub svn_commit_tree {
 423        my ($svn_rev, $commit) = @_;
 424        my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
 425        open my $msg, '>', $commit_msg  or croak $!;
 426
 427        chomp(my $type = `git-cat-file -t $commit`);
 428        if ($type eq 'commit') {
 429                my $pid = open my $msg_fh, '-|';
 430                defined $pid or croak $!;
 431
 432                if ($pid == 0) {
 433                        exec(qw(git-cat-file commit), $commit) or croak $!;
 434                }
 435                my $in_msg = 0;
 436                while (<$msg_fh>) {
 437                        if (!$in_msg) {
 438                                $in_msg = 1 if (/^\s*$/);
 439                        } else {
 440                                print $msg $_ or croak $!;
 441                        }
 442                }
 443                close $msg_fh or croak $!;
 444        }
 445        close $msg or croak $!;
 446
 447        if ($_edit || ($type eq 'tree')) {
 448                my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
 449                system($editor, $commit_msg);
 450        }
 451        my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
 452        my ($committed) = grep(/^Committed revision \d+\./,@ci_output);
 453        unlink $commit_msg;
 454        defined $committed or croak
 455                        "Commit output failed to parse committed revision!\n",
 456                        join("\n",@ci_output),"\n";
 457        my ($rev_committed) = ($committed =~ /^Committed revision (\d+)\./);
 458
 459        # resync immediately
 460        my @svn_up = (qw(svn up), "-r$svn_rev");
 461        push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
 462        sys(@svn_up);
 463        return fetch("$rev_committed=$commit")->{revision};
 464}
 465
 466sub svn_log_xml {
 467        my (@log_args) = @_;
 468        my $log_fh = IO::File->new_tmpfile or croak $!;
 469
 470        my $pid = fork;
 471        defined $pid or croak $!;
 472
 473        if ($pid == 0) {
 474                open STDOUT, '>&', $log_fh or croak $!;
 475                exec (qw(svn log --xml), @log_args) or croak $!
 476        }
 477
 478        waitpid $pid, 0;
 479        croak $? if $?;
 480
 481        seek $log_fh, 0, 0;
 482        my @svn_log;
 483        my $log = XML::Simple::XMLin( $log_fh,
 484                                ForceArray => ['path','revision','logentry'],
 485                                KeepRoot => 0,
 486                                KeyAttr => {    logentry => '+revision',
 487                                                paths => '+path' },
 488                        )->{logentry};
 489        foreach my $r (sort {$a <=> $b} keys %$log) {
 490                my $log_msg = $log->{$r};
 491                my ($Y,$m,$d,$H,$M,$S) = ($log_msg->{date} =~
 492                                        /(\d{4})\-(\d\d)\-(\d\d)T
 493                                         (\d\d)\:(\d\d)\:(\d\d)\.\d+Z$/x)
 494                                         or croak "Failed to parse date: ",
 495                                                 $log->{$r}->{date};
 496                $log_msg->{date} = "+0000 $Y-$m-$d $H:$M:$S";
 497
 498                # XML::Simple can't handle <msg></msg> as a string:
 499                if (ref $log_msg->{msg} eq 'HASH') {
 500                        $log_msg->{msg} = "\n";
 501                } else {
 502                        $log_msg->{msg} .= "\n";
 503                }
 504                push @svn_log, $log->{$r};
 505        }
 506        return \@svn_log;
 507}
 508
 509sub svn_log_raw {
 510        my (@log_args) = @_;
 511        my $pid = open my $log_fh,'-|';
 512        defined $pid or croak $!;
 513
 514        if ($pid == 0) {
 515                exec (qw(svn log), @log_args) or croak $!
 516        }
 517
 518        my @svn_log;
 519        my $state;
 520        while (<$log_fh>) {
 521                chomp;
 522                if (/^\-{72}$/) {
 523                        $state = 'rev';
 524
 525                        # if we have an empty log message, put something there:
 526                        if (@svn_log) {
 527                                $svn_log[$#svn_log]->{msg} ||= "\n";
 528                        }
 529                        next;
 530                }
 531                if ($state eq 'rev' && s/^r(\d+)\s*\|\s*//) {
 532                        my $rev = $1;
 533                        my ($author, $date) = split(/\s*\|\s*/, $_, 2);
 534                        my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
 535                                        /(\d{4})\-(\d\d)\-(\d\d)\s
 536                                         (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
 537                                         or croak "Failed to parse date: $date\n";
 538                        my %log_msg = ( revision => $rev,
 539                                        date => "$tz $Y-$m-$d $H:$M:$S",
 540                                        author => $author,
 541                                        msg => '' );
 542                        push @svn_log, \%log_msg;
 543                        $state = 'msg_start';
 544                        next;
 545                }
 546                # skip the first blank line of the message:
 547                if ($state eq 'msg_start' && /^$/) {
 548                        $state = 'msg';
 549                } elsif ($state eq 'msg') {
 550                        $svn_log[$#svn_log]->{msg} .= $_."\n";
 551                }
 552        }
 553        close $log_fh or croak $?;
 554        return \@svn_log;
 555}
 556
 557sub svn_info {
 558        my $url = shift || $SVN_URL;
 559
 560        my $pid = open my $info_fh, '-|';
 561        defined $pid or croak $!;
 562
 563        if ($pid == 0) {
 564                exec(qw(svn info),$url) or croak $!;
 565        }
 566
 567        my $ret = {};
 568        # only single-lines seem to exist in svn info output
 569        while (<$info_fh>) {
 570                chomp $_;
 571                if (m#^([^:]+)\s*:\s*(\S*)$#) {
 572                        $ret->{$1} = $2;
 573                        push @{$ret->{-order}}, $1;
 574                }
 575        }
 576        close $info_fh or croak $!;
 577        return $ret;
 578}
 579
 580sub sys { system(@_) == 0 or croak $? }
 581
 582sub git_addremove {
 583        system( "git-diff-files --name-only -z ".
 584                                " | git-update-index --remove -z --stdin; ".
 585                "git-ls-files -z --others ".
 586                        "'--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude'".
 587                                " | git-update-index --add -z --stdin; "
 588                ) == 0 or croak $?
 589}
 590
 591sub s_to_file {
 592        my ($str, $file, $mode) = @_;
 593        open my $fd,'>',$file or croak $!;
 594        print $fd $str,"\n" or croak $!;
 595        close $fd or croak $!;
 596        chmod ($mode &~ umask, $file) if (defined $mode);
 597}
 598
 599sub file_to_s {
 600        my $file = shift;
 601        open my $fd,'<',$file or croak "$!: file: $file\n";
 602        local $/;
 603        my $ret = <$fd>;
 604        close $fd or croak $!;
 605        $ret =~ s/\s*$//s;
 606        return $ret;
 607}
 608
 609sub assert_revision_unknown {
 610        my $revno = shift;
 611        if (-f "$REV_DIR/$revno") {
 612                croak "$REV_DIR/$revno already exists! ",
 613                                "Why are we refetching it?";
 614        }
 615}
 616
 617sub assert_revision_eq_or_unknown {
 618        my ($revno, $commit) = @_;
 619        if (-f "$REV_DIR/$revno") {
 620                my $current = file_to_s("$REV_DIR/$revno");
 621                if ($commit ne $current) {
 622                        croak "$REV_DIR/$revno already exists!\n",
 623                                "current: $current\nexpected: $commit\n";
 624                }
 625                return;
 626        }
 627}
 628
 629sub git_commit {
 630        my ($log_msg, @parents) = @_;
 631        assert_revision_unknown($log_msg->{revision});
 632        my $out_fh = IO::File->new_tmpfile or croak $!;
 633        my $info = svn_info('.');
 634        my $uuid = $info->{'Repository UUID'};
 635        defined $uuid or croak "Unable to get Repository UUID\n";
 636
 637        # commit parents can be conditionally bound to a particular
 638        # svn revision via: "svn_revno=commit_sha1", filter them out here:
 639        my @exec_parents;
 640        foreach my $p (@parents) {
 641                next unless defined $p;
 642                if ($p =~ /^(\d+)=($sha1_short)$/o) {
 643                        if ($1 == $log_msg->{revision}) {
 644                                push @exec_parents, $2;
 645                        }
 646                } else {
 647                        push @exec_parents, $p if $p =~ /$sha1_short/o;
 648                }
 649        }
 650
 651        my $pid = fork;
 652        defined $pid or croak $!;
 653        if ($pid == 0) {
 654                $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
 655                git_addremove();
 656                chomp(my $tree = `git-write-tree`);
 657                croak if $?;
 658                my $msg_fh = IO::File->new_tmpfile or croak $!;
 659                print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
 660                                        "$SVN_URL\@$log_msg->{revision}",
 661                                        " $uuid\n" or croak $!;
 662                $msg_fh->flush == 0 or croak $!;
 663                seek $msg_fh, 0, 0 or croak $!;
 664
 665                $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} =
 666                                                $log_msg->{author};
 667                $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
 668                                                $log_msg->{author}."\@$uuid";
 669                $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} =
 670                                                $log_msg->{date};
 671                my @exec = ('git-commit-tree',$tree);
 672                push @exec, '-p', $_  foreach @exec_parents;
 673                open STDIN, '<&', $msg_fh or croak $!;
 674                open STDOUT, '>&', $out_fh or croak $!;
 675                exec @exec or croak $!;
 676        }
 677        waitpid($pid,0);
 678        croak if $?;
 679
 680        $out_fh->flush == 0 or croak $!;
 681        seek $out_fh, 0, 0 or croak $!;
 682        chomp(my $commit = do { local $/; <$out_fh> });
 683        if ($commit !~ /^$sha1$/o) {
 684                croak "Failed to commit, invalid sha1: $commit\n";
 685        }
 686        my @update_ref = ('git-update-ref',"refs/heads/$GIT_SVN-HEAD",$commit);
 687        if (my $primary_parent = shift @exec_parents) {
 688                push @update_ref, $primary_parent;
 689        }
 690        sys(@update_ref);
 691        sys('git-update-ref',"$GIT_SVN/revs/$log_msg->{revision}",$commit);
 692        print "r$log_msg->{revision} = $commit\n";
 693        return $commit;
 694}
 695
 696sub blob_to_symlink {
 697        my ($blob, $link) = @_;
 698        defined $link or croak "\$link not defined!\n";
 699        croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
 700        my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
 701        symlink $dest, $link or croak $!;
 702}
 703
 704sub blob_to_file {
 705        my ($blob, $file) = @_;
 706        defined $file or croak "\$file not defined!\n";
 707        croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
 708        open my $blob_fh, '>', $file or croak "$!: $file\n";
 709        my $pid = fork;
 710        defined $pid or croak $!;
 711
 712        if ($pid == 0) {
 713                open STDOUT, '>&', $blob_fh or croak $!;
 714                exec('git-cat-file','blob',$blob);
 715        }
 716        waitpid $pid, 0;
 717        croak $? if $?;
 718
 719        close $blob_fh or croak $!;
 720}
 721
 722sub safe_qx {
 723        my $pid = open my $child, '-|';
 724        defined $pid or croak $!;
 725        if ($pid == 0) {
 726                exec(@_) or croak $?;
 727        }
 728        my @ret = (<$child>);
 729        close $child or croak $?;
 730        die $? if $?; # just in case close didn't error out
 731        return wantarray ? @ret : join('',@ret);
 732}
 733
 734sub svn_check_ignore_externals {
 735        return if $_no_ignore_ext;
 736        unless (grep /ignore-externals/,(safe_qx(qw(svn co -h)))) {
 737                print STDERR "W: Installed svn version does not support ",
 738                                "--ignore-externals\n";
 739                $_no_ignore_ext = 1;
 740        }
 741}
 742__END__
 743
 744Data structures:
 745
 746@svn_log = array of log_msg hashes
 747
 748$log_msg hash
 749{
 750        msg => 'whitespace-formatted log entry
 751',                                              # trailing newline is preserved
 752        revision => '8',                        # integer
 753        date => '2004-02-24T17:01:44.108345Z',  # commit date
 754        author => 'committer name'
 755};
 756
 757
 758@mods = array of diff-index line hashes, each element represents one line
 759        of diff-index output
 760
 761diff-index line ($m hash)
 762{
 763        mode_a => first column of diff-index output, no leading ':',
 764        mode_b => second column of diff-index output,
 765        sha1_b => sha1sum of the final blob,
 766        chg => change type [MCRAD],
 767        file_a => original file name of a file (iff chg is 'C' or 'R')
 768        file_b => new/current file name of a file (any chg)
 769}
 770;