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