git-svnimport.perlon commit git-svnimport symlink support (08ddd4f)
   1#!/usr/bin/perl -w
   2
   3# This tool is copyright (c) 2005, Matthias Urlichs.
   4# It is released under the Gnu Public License, version 2.
   5#
   6# The basic idea is to pull and analyze SVN changes.
   7#
   8# Checking out the files is done by a single long-running SVN connection.
   9#
  10# The head revision is on branch "origin" by default.
  11# You can change that with the '-o' option.
  12
  13use strict;
  14use warnings;
  15use Getopt::Std;
  16use File::Copy;
  17use File::Spec;
  18use File::Temp qw(tempfile);
  19use File::Path qw(mkpath);
  20use File::Basename qw(basename dirname);
  21use Time::Local;
  22use IO::Pipe;
  23use POSIX qw(strftime dup2);
  24use IPC::Open2;
  25use SVN::Core;
  26use SVN::Ra;
  27
  28die "Need SVN:Core 1.2.1 or better" if $SVN::Core::VERSION lt "1.2.1";
  29
  30$SIG{'PIPE'}="IGNORE";
  31$ENV{'TZ'}="UTC";
  32
  33our($opt_h,$opt_o,$opt_v,$opt_u,$opt_C,$opt_i,$opt_m,$opt_M,$opt_t,$opt_T,
  34    $opt_b,$opt_r,$opt_I,$opt_A,$opt_s,$opt_l,$opt_d,$opt_D);
  35
  36sub usage() {
  37        print STDERR <<END;
  38Usage: ${\basename $0}     # fetch/update GIT from SVN
  39       [-o branch-for-HEAD] [-h] [-v] [-l max_rev]
  40       [-C GIT_repository] [-t tagname] [-T trunkname] [-b branchname]
  41       [-d|-D] [-i] [-u] [-r] [-I ignorefilename] [-s start_chg]
  42       [-m] [-M regex] [-A author_file] [SVN_URL]
  43END
  44        exit(1);
  45}
  46
  47getopts("A:b:C:dDhiI:l:mM:o:rs:t:T:uv") or usage();
  48usage if $opt_h;
  49
  50my $tag_name = $opt_t || "tags";
  51my $trunk_name = $opt_T || "trunk";
  52my $branch_name = $opt_b || "branches";
  53
  54@ARGV == 1 or @ARGV == 2 or usage();
  55
  56$opt_o ||= "origin";
  57$opt_s ||= 1;
  58my $git_tree = $opt_C;
  59$git_tree ||= ".";
  60
  61my $svn_url = $ARGV[0];
  62my $svn_dir = $ARGV[1];
  63
  64our @mergerx = ();
  65if ($opt_m) {
  66        @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
  67}
  68if ($opt_M) {
  69        push (@mergerx, qr/$opt_M/);
  70}
  71
  72# Absolutize filename now, since we will have chdir'ed by the time we
  73# get around to opening it.
  74$opt_A = File::Spec->rel2abs($opt_A) if $opt_A;
  75
  76our %users = ();
  77our $users_file = undef;
  78sub read_users($) {
  79        $users_file = File::Spec->rel2abs(@_);
  80        die "Cannot open $users_file\n" unless -f $users_file;
  81        open(my $authors,$users_file);
  82        while(<$authors>) {
  83                chomp;
  84                next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
  85                (my $user,my $name,my $email) = ($1,$2,$3);
  86                $users{$user} = [$name,$email];
  87        }
  88        close($authors);
  89}
  90
  91select(STDERR); $|=1; select(STDOUT);
  92
  93
  94package SVNconn;
  95# Basic SVN connection.
  96# We're only interested in connecting and downloading, so ...
  97
  98use File::Spec;
  99use File::Temp qw(tempfile);
 100use POSIX qw(strftime dup2);
 101use Fcntl qw(SEEK_SET);
 102
 103sub new {
 104        my($what,$repo) = @_;
 105        $what=ref($what) if ref($what);
 106
 107        my $self = {};
 108        $self->{'buffer'} = "";
 109        bless($self,$what);
 110
 111        $repo =~ s#/+$##;
 112        $self->{'fullrep'} = $repo;
 113        $self->conn();
 114
 115        return $self;
 116}
 117
 118sub conn {
 119        my $self = shift;
 120        my $repo = $self->{'fullrep'};
 121        my $auth = SVN::Core::auth_open ([SVN::Client::get_simple_provider,
 122                          SVN::Client::get_ssl_server_trust_file_provider,
 123                          SVN::Client::get_username_provider]);
 124        my $s = SVN::Ra->new(url => $repo, auth => $auth);
 125        die "SVN connection to $repo: $!\n" unless defined $s;
 126        $self->{'svn'} = $s;
 127        $self->{'repo'} = $repo;
 128        $self->{'maxrev'} = $s->get_latest_revnum();
 129}
 130
 131sub file {
 132        my($self,$path,$rev) = @_;
 133
 134        my ($fh, $name) = tempfile('gitsvn.XXXXXX',
 135                    DIR => File::Spec->tmpdir(), UNLINK => 1);
 136
 137        print "... $rev $path ...\n" if $opt_v;
 138        my (undef, $properties);
 139        eval { (undef, $properties)
 140                   = $self->{'svn'}->get_file($path,$rev,$fh); };
 141        if($@) {
 142                return undef if $@ =~ /Attempted to get checksum/;
 143                die $@;
 144        }
 145        my $mode;
 146        if (exists $properties->{'svn:executable'}) {
 147                $mode = '100755';
 148        } elsif (exists $properties->{'svn:special'}) {
 149                my ($special_content, $filesize);
 150                $filesize = tell $fh;
 151                seek $fh, 0, SEEK_SET;
 152                read $fh, $special_content, $filesize;
 153                if ($special_content =~ s/^link //) {
 154                        $mode = '120000';
 155                        seek $fh, 0, SEEK_SET;
 156                        truncate $fh, 0;
 157                        print $fh $special_content;
 158                } else {
 159                        die "unexpected svn:special file encountered";
 160                }
 161        } else {
 162                $mode = '100644';
 163        }
 164        close ($fh);
 165
 166        return ($name, $mode);
 167}
 168
 169sub ignore {
 170        my($self,$path,$rev) = @_;
 171
 172        print "... $rev $path ...\n" if $opt_v;
 173        my (undef,undef,$properties)
 174            = $self->{'svn'}->get_dir($path,$rev,undef);
 175        if (exists $properties->{'svn:ignore'}) {
 176                my ($fh, $name) = tempfile('gitsvn.XXXXXX',
 177                                           DIR => File::Spec->tmpdir(),
 178                                           UNLINK => 1);
 179                print $fh $properties->{'svn:ignore'};
 180                close($fh);
 181                return $name;
 182        } else {
 183                return undef;
 184        }
 185}
 186
 187package main;
 188use URI;
 189
 190our $svn = $svn_url;
 191$svn .= "/$svn_dir" if defined $svn_dir;
 192my $svn2 = SVNconn->new($svn);
 193$svn = SVNconn->new($svn);
 194
 195my $lwp_ua;
 196if($opt_d or $opt_D) {
 197        $svn_url = URI->new($svn_url)->canonical;
 198        if($opt_D) {
 199                $svn_dir =~ s#/*$#/#;
 200        } else {
 201                $svn_dir = "";
 202        }
 203        if ($svn_url->scheme eq "http") {
 204                use LWP::UserAgent;
 205                $lwp_ua = LWP::UserAgent->new(keep_alive => 1, requests_redirectable => []);
 206        } else {
 207                print STDERR "Warning: not HTTP; turning off direct file access\n";
 208                $opt_d=0;
 209        }
 210}
 211
 212sub pdate($) {
 213        my($d) = @_;
 214        $d =~ m#(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)#
 215                or die "Unparseable date: $d\n";
 216        my $y=$1; $y-=1900 if $y>1900;
 217        return timegm($6||0,$5,$4,$3,$2-1,$y);
 218}
 219
 220sub getwd() {
 221        my $pwd = `pwd`;
 222        chomp $pwd;
 223        return $pwd;
 224}
 225
 226
 227sub get_headref($$) {
 228    my $name    = shift;
 229    my $git_dir = shift;
 230    my $sha;
 231
 232    if (open(C,"$git_dir/refs/heads/$name")) {
 233        chomp($sha = <C>);
 234        close(C);
 235        length($sha) == 40
 236            or die "Cannot get head id for $name ($sha): $!\n";
 237    }
 238    return $sha;
 239}
 240
 241
 242-d $git_tree
 243        or mkdir($git_tree,0777)
 244        or die "Could not create $git_tree: $!";
 245chdir($git_tree);
 246
 247my $orig_branch = "";
 248my $forward_master = 0;
 249my %branches;
 250
 251my $git_dir = $ENV{"GIT_DIR"} || ".git";
 252$git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
 253$ENV{"GIT_DIR"} = $git_dir;
 254my $orig_git_index;
 255$orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
 256my ($git_ih, $git_index) = tempfile('gitXXXXXX', SUFFIX => '.idx',
 257                                    DIR => File::Spec->tmpdir());
 258close ($git_ih);
 259$ENV{GIT_INDEX_FILE} = $git_index;
 260my $maxnum = 0;
 261my $last_rev = "";
 262my $last_branch;
 263my $current_rev = $opt_s || 1;
 264unless(-d $git_dir) {
 265        system("git-init-db");
 266        die "Cannot init the GIT db at $git_tree: $?\n" if $?;
 267        system("git-read-tree");
 268        die "Cannot init an empty tree: $?\n" if $?;
 269
 270        $last_branch = $opt_o;
 271        $orig_branch = "";
 272} else {
 273        -f "$git_dir/refs/heads/$opt_o"
 274                or die "Branch '$opt_o' does not exist.\n".
 275                       "Either use the correct '-o branch' option,\n".
 276                       "or import to a new repository.\n";
 277
 278        -f "$git_dir/svn2git"
 279                or die "'$git_dir/svn2git' does not exist.\n".
 280                       "You need that file for incremental imports.\n";
 281        open(F, "git-symbolic-ref HEAD |") or
 282                die "Cannot run git-symbolic-ref: $!\n";
 283        chomp ($last_branch = <F>);
 284        $last_branch = basename($last_branch);
 285        close(F);
 286        unless($last_branch) {
 287                warn "Cannot read the last branch name: $! -- assuming 'master'\n";
 288                $last_branch = "master";
 289        }
 290        $orig_branch = $last_branch;
 291        $last_rev = get_headref($orig_branch, $git_dir);
 292        if (-f "$git_dir/SVN2GIT_HEAD") {
 293                die <<EOM;
 294SVN2GIT_HEAD exists.
 295Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
 296You may need to run
 297
 298    git-read-tree -m -u SVN2GIT_HEAD HEAD
 299EOM
 300        }
 301        system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
 302
 303        $forward_master =
 304            $opt_o ne 'master' && -f "$git_dir/refs/heads/master" &&
 305            system('cmp', '-s', "$git_dir/refs/heads/master",
 306                                "$git_dir/refs/heads/$opt_o") == 0;
 307
 308        # populate index
 309        system('git-read-tree', $last_rev);
 310        die "read-tree failed: $?\n" if $?;
 311
 312        # Get the last import timestamps
 313        open my $B,"<", "$git_dir/svn2git";
 314        while(<$B>) {
 315                chomp;
 316                my($num,$branch,$ref) = split;
 317                $branches{$branch}{$num} = $ref;
 318                $branches{$branch}{"LAST"} = $ref;
 319                $current_rev = $num+1 if $current_rev <= $num;
 320        }
 321        close($B);
 322}
 323-d $git_dir
 324        or die "Could not create git subdir ($git_dir).\n";
 325
 326my $default_authors = "$git_dir/svn-authors";
 327if ($opt_A) {
 328        read_users($opt_A);
 329        copy($opt_A,$default_authors) or die "Copy failed: $!";
 330} else {
 331        read_users($default_authors) if -f $default_authors;
 332}
 333
 334open BRANCHES,">>", "$git_dir/svn2git";
 335
 336sub node_kind($$$) {
 337        my ($branch, $path, $revision) = @_;
 338        my $pool=SVN::Pool->new;
 339        my $kind = $svn->{'svn'}->check_path(revert_split_path($branch,$path),$revision,$pool);
 340        $pool->clear;
 341        return $kind;
 342}
 343
 344sub revert_split_path($$) {
 345        my($branch,$path) = @_;
 346
 347        my $svnpath;
 348        $path = "" if $path eq "/"; # this should not happen, but ...
 349        if($branch eq "/") {
 350                $svnpath = "$trunk_name/$path";
 351        } elsif($branch =~ m#^/#) {
 352                $svnpath = "$tag_name$branch/$path";
 353        } else {
 354                $svnpath = "$branch_name/$branch/$path";
 355        }
 356
 357        $svnpath =~ s#/+$##;
 358        return $svnpath;
 359}
 360
 361sub get_file($$$) {
 362        my($rev,$branch,$path) = @_;
 363
 364        my $svnpath = revert_split_path($branch,$path);
 365
 366        # now get it
 367        my ($name,$mode);
 368        if($opt_d) {
 369                my($req,$res);
 370
 371                # /svn/!svn/bc/2/django/trunk/django-docs/build.py
 372                my $url=$svn_url->clone();
 373                $url->path($url->path."/!svn/bc/$rev/$svn_dir$svnpath");
 374                print "... $path...\n" if $opt_v;
 375                $req = HTTP::Request->new(GET => $url);
 376                $res = $lwp_ua->request($req);
 377                if ($res->is_success) {
 378                        my $fh;
 379                        ($fh, $name) = tempfile('gitsvn.XXXXXX',
 380                        DIR => File::Spec->tmpdir(), UNLINK => 1);
 381                        print $fh $res->content;
 382                        close($fh) or die "Could not write $name: $!\n";
 383                } else {
 384                        return undef if $res->code == 301; # directory?
 385                        die $res->status_line." at $url\n";
 386                }
 387                $mode = '0644'; # can't obtain mode via direct http request?
 388        } else {
 389                ($name,$mode) = $svn->file("$svnpath",$rev);
 390                return undef unless defined $name;
 391        }
 392
 393        my $pid = open(my $F, '-|');
 394        die $! unless defined $pid;
 395        if (!$pid) {
 396            exec("git-hash-object", "-w", $name)
 397                or die "Cannot create object: $!\n";
 398        }
 399        my $sha = <$F>;
 400        chomp $sha;
 401        close $F;
 402        unlink $name;
 403        return [$mode, $sha, $path];
 404}
 405
 406sub get_ignore($$$$$) {
 407        my($new,$old,$rev,$branch,$path) = @_;
 408
 409        return unless $opt_I;
 410        my $svnpath = revert_split_path($branch,$path);
 411        my $name = $svn->ignore("$svnpath",$rev);
 412        if ($path eq '/') {
 413                $path = $opt_I;
 414        } else {
 415                $path = File::Spec->catfile($path,$opt_I);
 416        }
 417        if (defined $name) {
 418                my $pid = open(my $F, '-|');
 419                die $! unless defined $pid;
 420                if (!$pid) {
 421                        exec("git-hash-object", "-w", $name)
 422                            or die "Cannot create object: $!\n";
 423                }
 424                my $sha = <$F>;
 425                chomp $sha;
 426                close $F;
 427                unlink $name;
 428                push(@$new,['0644',$sha,$path]);
 429        } else {
 430                push(@$old,$path);
 431        }
 432}
 433
 434sub split_path($$) {
 435        my($rev,$path) = @_;
 436        my $branch;
 437
 438        if($path =~ s#^/\Q$tag_name\E/([^/]+)/?##) {
 439                $branch = "/$1";
 440        } elsif($path =~ s#^/\Q$trunk_name\E/?##) {
 441                $branch = "/";
 442        } elsif($path =~ s#^/\Q$branch_name\E/([^/]+)/?##) {
 443                $branch = $1;
 444        } else {
 445                my %no_error = (
 446                        "/" => 1,
 447                        "/$tag_name" => 1,
 448                        "/$branch_name" => 1
 449                );
 450                print STDERR "$rev: Unrecognized path: $path\n" unless (defined $no_error{$path});
 451                return ()
 452        }
 453        $path = "/" if $path eq "";
 454        return ($branch,$path);
 455}
 456
 457sub branch_rev($$) {
 458
 459        my ($srcbranch,$uptorev) = @_;
 460
 461        my $bbranches = $branches{$srcbranch};
 462        my @revs = reverse sort { ($a eq 'LAST' ? 0 : $a) <=> ($b eq 'LAST' ? 0 : $b) } keys %$bbranches;
 463        my $therev;
 464        foreach my $arev(@revs) {
 465                next if  ($arev eq 'LAST');
 466                if ($arev <= $uptorev) {
 467                        $therev = $arev;
 468                        last;
 469                }
 470        }
 471        return $therev;
 472}
 473
 474sub copy_path($$$$$$$$) {
 475        # Somebody copied a whole subdirectory.
 476        # We need to find the index entries from the old version which the
 477        # SVN log entry points to, and add them to the new place.
 478
 479        my($newrev,$newbranch,$path,$oldpath,$rev,$node_kind,$new,$parents) = @_;
 480
 481        my($srcbranch,$srcpath) = split_path($rev,$oldpath);
 482        unless(defined $srcbranch) {
 483                print "Path not found when copying from $oldpath @ $rev\n";
 484                return;
 485        }
 486        my $therev = branch_rev($srcbranch, $rev);
 487        my $gitrev = $branches{$srcbranch}{$therev};
 488        unless($gitrev) {
 489                print STDERR "$newrev:$newbranch: could not find $oldpath \@ $rev\n";
 490                return;
 491        }
 492        if ($srcbranch ne $newbranch) {
 493                push(@$parents, $branches{$srcbranch}{'LAST'});
 494        }
 495        print "$newrev:$newbranch:$path: copying from $srcbranch:$srcpath @ $rev\n" if $opt_v;
 496        if ($node_kind eq $SVN::Node::dir) {
 497                        $srcpath =~ s#/*$#/#;
 498        }
 499        
 500        my $pid = open my $f,'-|';
 501        die $! unless defined $pid;
 502        if (!$pid) {
 503                exec("git-ls-tree","-r","-z",$gitrev,$srcpath)
 504                        or die $!;
 505        }
 506        local $/ = "\0";
 507        while(<$f>) {
 508                chomp;
 509                my($m,$p) = split(/\t/,$_,2);
 510                my($mode,$type,$sha1) = split(/ /,$m);
 511                next if $type ne "blob";
 512                if ($node_kind eq $SVN::Node::dir) {
 513                        $p = $path . substr($p,length($srcpath)-1);
 514                } else {
 515                        $p = $path;
 516                }
 517                push(@$new,[$mode,$sha1,$p]);   
 518        }
 519        close($f) or
 520                print STDERR "$newrev:$newbranch: could not list files in $oldpath \@ $rev\n";
 521}
 522
 523sub commit {
 524        my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
 525        my($author_name,$author_email,$dest);
 526        my(@old,@new,@parents);
 527
 528        if (not defined $author) {
 529                $author_name = $author_email = "unknown";
 530        } elsif (defined $users_file) {
 531                die "User $author is not listed in $users_file\n"
 532                    unless exists $users{$author};
 533                ($author_name,$author_email) = @{$users{$author}};
 534        } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
 535                ($author_name, $author_email) = ($1, $2);
 536        } else {
 537                $author =~ s/^<(.*)>$/$1/;
 538                $author_name = $author_email = $author;
 539        }
 540        $date = pdate($date);
 541
 542        my $tag;
 543        my $parent;
 544        if($branch eq "/") { # trunk
 545                $parent = $opt_o;
 546        } elsif($branch =~ m#^/(.+)#) { # tag
 547                $tag = 1;
 548                $parent = $1;
 549        } else { # "normal" branch
 550                # nothing to do
 551                $parent = $branch;
 552        }
 553        $dest = $parent;
 554
 555        my $prev = $changed_paths->{"/"};
 556        if($prev and $prev->[0] eq "A") {
 557                delete $changed_paths->{"/"};
 558                my $oldpath = $prev->[1];
 559                my $rev;
 560                if(defined $oldpath) {
 561                        my $p;
 562                        ($parent,$p) = split_path($revision,$oldpath);
 563                        if($parent eq "/") {
 564                                $parent = $opt_o;
 565                        } else {
 566                                $parent =~ s#^/##; # if it's a tag
 567                        }
 568                } else {
 569                        $parent = undef;
 570                }
 571        }
 572
 573        my $rev;
 574        if($revision > $opt_s and defined $parent) {
 575                open(H,"git-rev-parse --verify $parent |");
 576                $rev = <H>;
 577                close(H) or do {
 578                        print STDERR "$revision: cannot find commit '$parent'!\n";
 579                        return;
 580                };
 581                chop $rev;
 582                if(length($rev) != 40) {
 583                        print STDERR "$revision: cannot find commit '$parent'!\n";
 584                        return;
 585                }
 586                $rev = $branches{($parent eq $opt_o) ? "/" : $parent}{"LAST"};
 587                if($revision != $opt_s and not $rev) {
 588                        print STDERR "$revision: do not know ancestor for '$parent'!\n";
 589                        return;
 590                }
 591        } else {
 592                $rev = undef;
 593        }
 594
 595#       if($prev and $prev->[0] eq "A") {
 596#               if(not $tag) {
 597#                       unless(open(H,"> $git_dir/refs/heads/$branch")) {
 598#                               print STDERR "$revision: Could not create branch $branch: $!\n";
 599#                               $state=11;
 600#                               next;
 601#                       }
 602#                       print H "$rev\n"
 603#                               or die "Could not write branch $branch: $!";
 604#                       close(H)
 605#                               or die "Could not write branch $branch: $!";
 606#               }
 607#       }
 608        if(not defined $rev) {
 609                unlink($git_index);
 610        } elsif ($rev ne $last_rev) {
 611                print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
 612                system("git-read-tree", $rev);
 613                die "read-tree failed for $rev: $?\n" if $?;
 614                $last_rev = $rev;
 615        }
 616
 617        push (@parents, $rev) if defined $rev;
 618
 619        my $cid;
 620        if($tag and not %$changed_paths) {
 621                $cid = $rev;
 622        } else {
 623                my @paths = sort keys %$changed_paths;
 624                foreach my $path(@paths) {
 625                        my $action = $changed_paths->{$path};
 626
 627                        if ($action->[0] eq "R") {
 628                                # refer to a file/tree in an earlier commit
 629                                push(@old,$path); # remove any old stuff
 630                        }
 631                        if(($action->[0] eq "A") || ($action->[0] eq "R")) {
 632                                my $node_kind = node_kind($branch,$path,$revision);
 633                                if ($node_kind eq $SVN::Node::file) {
 634                                        my $f = get_file($revision,$branch,$path);
 635                                        if ($f) {
 636                                                push(@new,$f) if $f;
 637                                        } else {
 638                                                my $opath = $action->[3];
 639                                                print STDERR "$revision: $branch: could not fetch '$opath'\n";
 640                                        }
 641                                } elsif ($node_kind eq $SVN::Node::dir) {
 642                                        if($action->[1]) {
 643                                                copy_path($revision, $branch,
 644                                                          $path, $action->[1],
 645                                                          $action->[2], $node_kind,
 646                                                          \@new, \@parents);
 647                                        } else {
 648                                                get_ignore(\@new, \@old, $revision,
 649                                                           $branch, $path);
 650                                        }
 651                                }
 652                        } elsif ($action->[0] eq "D") {
 653                                push(@old,$path);
 654                        } elsif ($action->[0] eq "M") {
 655                                my $node_kind = node_kind($branch,$path,$revision);
 656                                if ($node_kind eq $SVN::Node::file) {
 657                                        my $f = get_file($revision,$branch,$path);
 658                                        push(@new,$f) if $f;
 659                                } elsif ($node_kind eq $SVN::Node::dir) {
 660                                        get_ignore(\@new, \@old, $revision,
 661                                                   $branch,$path);
 662                                }
 663                        } else {
 664                                die "$revision: unknown action '".$action->[0]."' for $path\n";
 665                        }
 666                }
 667
 668                while(@old) {
 669                        my @o1;
 670                        if(@old > 55) {
 671                                @o1 = splice(@old,0,50);
 672                        } else {
 673                                @o1 = @old;
 674                                @old = ();
 675                        }
 676                        my $pid = open my $F, "-|";
 677                        die "$!" unless defined $pid;
 678                        if (!$pid) {
 679                                exec("git-ls-files", "-z", @o1) or die $!;
 680                        }
 681                        @o1 = ();
 682                        local $/ = "\0";
 683                        while(<$F>) {
 684                                chomp;
 685                                push(@o1,$_);
 686                        }
 687                        close($F);
 688
 689                        while(@o1) {
 690                                my @o2;
 691                                if(@o1 > 55) {
 692                                        @o2 = splice(@o1,0,50);
 693                                } else {
 694                                        @o2 = @o1;
 695                                        @o1 = ();
 696                                }
 697                                system("git-update-index","--force-remove","--",@o2);
 698                                die "Cannot remove files: $?\n" if $?;
 699                        }
 700                }
 701                while(@new) {
 702                        my @n2;
 703                        if(@new > 12) {
 704                                @n2 = splice(@new,0,10);
 705                        } else {
 706                                @n2 = @new;
 707                                @new = ();
 708                        }
 709                        system("git-update-index","--add",
 710                                (map { ('--cacheinfo', @$_) } @n2));
 711                        die "Cannot add files: $?\n" if $?;
 712                }
 713
 714                my $pid = open(C,"-|");
 715                die "Cannot fork: $!" unless defined $pid;
 716                unless($pid) {
 717                        exec("git-write-tree");
 718                        die "Cannot exec git-write-tree: $!\n";
 719                }
 720                chomp(my $tree = <C>);
 721                length($tree) == 40
 722                        or die "Cannot get tree id ($tree): $!\n";
 723                close(C)
 724                        or die "Error running git-write-tree: $?\n";
 725                print "Tree ID $tree\n" if $opt_v;
 726
 727                my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
 728                my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
 729                $pid = fork();
 730                die "Fork: $!\n" unless defined $pid;
 731                unless($pid) {
 732                        $pr->writer();
 733                        $pw->reader();
 734                        open(OUT,">&STDOUT");
 735                        dup2($pw->fileno(),0);
 736                        dup2($pr->fileno(),1);
 737                        $pr->close();
 738                        $pw->close();
 739
 740                        my @par = ();
 741
 742                        # loose detection of merges
 743                        # based on the commit msg
 744                        foreach my $rx (@mergerx) {
 745                                if ($message =~ $rx) {
 746                                        my $mparent = $1;
 747                                        if ($mparent eq 'HEAD') { $mparent = $opt_o };
 748                                        if ( -e "$git_dir/refs/heads/$mparent") {
 749                                                $mparent = get_headref($mparent, $git_dir);
 750                                                push (@parents, $mparent);
 751                                                print OUT "Merge parent branch: $mparent\n" if $opt_v;
 752                                        }
 753                                }
 754                        }
 755                        my %seen_parents = ();
 756                        my @unique_parents = grep { ! $seen_parents{$_} ++ } @parents;
 757                        foreach my $bparent (@unique_parents) {
 758                                push @par, '-p', $bparent;
 759                                print OUT "Merge parent branch: $bparent\n" if $opt_v;
 760                        }
 761
 762                        exec("env",
 763                                "GIT_AUTHOR_NAME=$author_name",
 764                                "GIT_AUTHOR_EMAIL=$author_email",
 765                                "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
 766                                "GIT_COMMITTER_NAME=$author_name",
 767                                "GIT_COMMITTER_EMAIL=$author_email",
 768                                "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
 769                                "git-commit-tree", $tree,@par);
 770                        die "Cannot exec git-commit-tree: $!\n";
 771                }
 772                $pw->writer();
 773                $pr->reader();
 774
 775                $message =~ s/[\s\n]+\z//;
 776                $message = "r$revision: $message" if $opt_r;
 777
 778                print $pw "$message\n"
 779                        or die "Error writing to git-commit-tree: $!\n";
 780                $pw->close();
 781
 782                print "Committed change $revision:$branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
 783                chomp($cid = <$pr>);
 784                length($cid) == 40
 785                        or die "Cannot get commit id ($cid): $!\n";
 786                print "Commit ID $cid\n" if $opt_v;
 787                $pr->close();
 788
 789                waitpid($pid,0);
 790                die "Error running git-commit-tree: $?\n" if $?;
 791        }
 792
 793        if (not defined $cid) {
 794                $cid = $branches{"/"}{"LAST"};
 795        }
 796
 797        if(not defined $dest) {
 798                print "... no known parent\n" if $opt_v;
 799        } elsif(not $tag) {
 800                print "Writing to refs/heads/$dest\n" if $opt_v;
 801                open(C,">$git_dir/refs/heads/$dest") and
 802                print C ("$cid\n") and
 803                close(C)
 804                        or die "Cannot write branch $dest for update: $!\n";
 805        }
 806
 807        if($tag) {
 808                my($in, $out) = ('','');
 809                $last_rev = "-" if %$changed_paths;
 810                # the tag was 'complex', i.e. did not refer to a "real" revision
 811
 812                $dest =~ tr/_/\./ if $opt_u;
 813                $branch = $dest;
 814
 815                my $pid = open2($in, $out, 'git-mktag');
 816                print $out ("object $cid\n".
 817                    "type commit\n".
 818                    "tag $dest\n".
 819                    "tagger $author_name <$author_email>\n") and
 820                close($out)
 821                    or die "Cannot create tag object $dest: $!\n";
 822
 823                my $tagobj = <$in>;
 824                chomp $tagobj;
 825
 826                if ( !close($in) or waitpid($pid, 0) != $pid or
 827                                $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
 828                        die "Cannot create tag object $dest: $!\n";
 829                }
 830
 831                open(C,">$git_dir/refs/tags/$dest") and
 832                print C ("$tagobj\n") and
 833                close(C)
 834                        or die "Cannot create tag $branch: $!\n";
 835
 836                print "Created tag '$dest' on '$branch'\n" if $opt_v;
 837        }
 838        $branches{$branch}{"LAST"} = $cid;
 839        $branches{$branch}{$revision} = $cid;
 840        $last_rev = $cid;
 841        print BRANCHES "$revision $branch $cid\n";
 842        print "DONE: $revision $dest $cid\n" if $opt_v;
 843}
 844
 845sub commit_all {
 846        # Recursive use of the SVN connection does not work
 847        local $svn = $svn2;
 848
 849        my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
 850        my %p;
 851        while(my($path,$action) = each %$changed_paths) {
 852                $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev, $path ];
 853        }
 854        $changed_paths = \%p;
 855
 856        my %done;
 857        my @col;
 858        my $pref;
 859        my $branch;
 860
 861        while(my($path,$action) = each %$changed_paths) {
 862                ($branch,$path) = split_path($revision,$path);
 863                next if not defined $branch;
 864                $done{$branch}{$path} = $action;
 865        }
 866        while(($branch,$changed_paths) = each %done) {
 867                commit($branch, $changed_paths, $revision, $author, $date, $message);
 868        }
 869}
 870
 871$opt_l = $svn->{'maxrev'} if not defined $opt_l or $opt_l > $svn->{'maxrev'};
 872
 873if ($opt_l < $current_rev) {
 874    print "Up to date: no new revisions to fetch!\n" if $opt_v;
 875    unlink("$git_dir/SVN2GIT_HEAD");
 876    exit;
 877}
 878
 879print "Fetching from $current_rev to $opt_l ...\n" if $opt_v;
 880
 881my $pool=SVN::Pool->new;
 882$svn->{'svn'}->get_log("/",$current_rev,$opt_l,0,1,1,\&commit_all,$pool);
 883$pool->clear;
 884
 885
 886unlink($git_index);
 887
 888if (defined $orig_git_index) {
 889        $ENV{GIT_INDEX_FILE} = $orig_git_index;
 890} else {
 891        delete $ENV{GIT_INDEX_FILE};
 892}
 893
 894# Now switch back to the branch we were in before all of this happened
 895if($orig_branch) {
 896        print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
 897        system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
 898                if $forward_master;
 899        unless ($opt_i) {
 900                system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
 901                die "read-tree failed: $?\n" if $?;
 902        }
 903} else {
 904        $orig_branch = "master";
 905        print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
 906        system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
 907                unless -f "$git_dir/refs/heads/master";
 908        system('git-update-ref', 'HEAD', "$orig_branch");
 909        unless ($opt_i) {
 910                system('git checkout');
 911                die "checkout failed: $?\n" if $?;
 912        }
 913}
 914unlink("$git_dir/SVN2GIT_HEAD");
 915close(BRANCHES);