b880297e0c3fdb5778f66311f6eef89c6dd16ed7
   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 CVS connection
   9# / server process.
  10#
  11# The head revision is on branch "origin" by default.
  12# You can change that with the '-o' option.
  13
  14require v5.8.0; # for shell-safe open("-|",LIST)
  15use strict;
  16use warnings;
  17use Getopt::Std;
  18use File::Spec;
  19use File::Temp qw(tempfile);
  20use File::Path qw(mkpath);
  21use File::Basename qw(basename dirname);
  22use Time::Local;
  23use IO::Pipe;
  24use POSIX qw(strftime dup2);
  25use IPC::Open2;
  26use SVN::Core;
  27use SVN::Ra;
  28
  29die "Need CVN:COre 1.2.1 or better" if $SVN::Core::VERSION lt "1.2.1";
  30
  31$SIG{'PIPE'}="IGNORE";
  32$ENV{'TZ'}="UTC";
  33
  34our($opt_h,$opt_o,$opt_v,$opt_u,$opt_C,$opt_i,$opt_m,$opt_M,$opt_t,$opt_T,$opt_b,$opt_s,$opt_l);
  35
  36sub usage() {
  37        print STDERR <<END;
  38Usage: ${\basename $0}     # fetch/update GIT from CVS
  39       [-o branch-for-HEAD] [-h] [-v] [-l max_num_changes]
  40       [-C GIT_repository] [-t tagname] [-T trunkname] [-b branchname]
  41       [-i] [-u] [-s start_chg] [-m] [-M regex] [SVN_URL]
  42END
  43        exit(1);
  44}
  45
  46getopts("b:C:hil:mM:o:s:t:T:uv") or usage();
  47usage if $opt_h;
  48
  49my $tag_name = $opt_t || "tags";
  50my $trunk_name = $opt_T || "trunk";
  51my $branch_name = $opt_b || "branches";
  52
  53@ARGV <= 1 or usage();
  54
  55$opt_o ||= "origin";
  56$opt_l = 100 unless defined $opt_l;
  57my $git_tree = $opt_C;
  58$git_tree ||= ".";
  59
  60my $cvs_tree;
  61if ($#ARGV == 0) {
  62        $cvs_tree = $ARGV[0];
  63} elsif (-f 'CVS/Repository') {
  64        open my $f, '<', 'CVS/Repository' or 
  65            die 'Failed to open CVS/Repository';
  66        $cvs_tree = <$f>;
  67        chomp $cvs_tree;
  68        close $f;
  69} else {
  70        usage();
  71}
  72
  73our @mergerx = ();
  74if ($opt_m) {
  75        @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
  76}
  77if ($opt_M) {
  78        push (@mergerx, qr/$opt_M/);
  79}
  80
  81select(STDERR); $|=1; select(STDOUT);
  82
  83
  84package SVNconn;
  85# Basic SVN connection.
  86# We're only interested in connecting and downloading, so ...
  87
  88use File::Spec;
  89use File::Temp qw(tempfile);
  90use POSIX qw(strftime dup2);
  91
  92sub new {
  93        my($what,$repo) = @_;
  94        $what=ref($what) if ref($what);
  95
  96        my $self = {};
  97        $self->{'buffer'} = "";
  98        bless($self,$what);
  99
 100        $repo =~ s#/+$##;
 101        $self->{'fullrep'} = $repo;
 102        $self->conn();
 103
 104        return $self;
 105}
 106
 107sub conn {
 108        my $self = shift;
 109        my $repo = $self->{'fullrep'};
 110        my $s = SVN::Ra->new($repo);
 111
 112        die "SVN connection to $repo: $!\n" unless defined $s;
 113        $self->{'svn'} = $s;
 114        $self->{'repo'} = $repo;
 115        $self->{'maxrev'} = $s->get_latest_revnum();
 116}
 117
 118sub file {
 119        my($self,$path,$rev) = @_;
 120        my $res;
 121
 122        my ($fh, $name) = tempfile('gitsvn.XXXXXX', 
 123                    DIR => File::Spec->tmpdir(), UNLINK => 1);
 124
 125        print "... $rev $path ...\n" if $opt_v;
 126        eval { $self->{'svn'}->get_file($path,$rev,$fh); };
 127        if ($@ and $@ !~ /Attempted to get checksum/) {
 128            # retry
 129            $self->conn();
 130                eval { $self->{'svn'}->get_file($path,$rev,$fh); };
 131        };
 132        return () if $@ and $@ !~ /Attempted to get checksum/;
 133        die $@ if $@;
 134        close ($fh);
 135
 136        return ($name, $res);
 137}
 138
 139
 140package main;
 141
 142my $svn = SVNconn->new($cvs_tree);
 143
 144
 145sub pdate($) {
 146        my($d) = @_;
 147        $d =~ m#(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)#
 148                or die "Unparseable date: $d\n";
 149        my $y=$1; $y-=1900 if $y>1900;
 150        return timegm($6||0,$5,$4,$3,$2-1,$y);
 151}
 152
 153sub getwd() {
 154        my $pwd = `pwd`;
 155        chomp $pwd;
 156        return $pwd;
 157}
 158
 159
 160sub get_headref($$) {
 161    my $name    = shift;
 162    my $git_dir = shift; 
 163    my $sha;
 164    
 165    if (open(C,"$git_dir/refs/heads/$name")) {
 166        chomp($sha = <C>);
 167        close(C);
 168        length($sha) == 40
 169            or die "Cannot get head id for $name ($sha): $!\n";
 170    }
 171    return $sha;
 172}
 173
 174
 175-d $git_tree
 176        or mkdir($git_tree,0777)
 177        or die "Could not create $git_tree: $!";
 178chdir($git_tree);
 179
 180my $orig_branch = "";
 181my $forward_master = 0;
 182my %branches;
 183
 184my $git_dir = $ENV{"GIT_DIR"} || ".git";
 185$git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
 186$ENV{"GIT_DIR"} = $git_dir;
 187my $orig_git_index;
 188$orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
 189my ($git_ih, $git_index) = tempfile('gitXXXXXX', SUFFIX => '.idx',
 190                                    DIR => File::Spec->tmpdir());
 191close ($git_ih);
 192$ENV{GIT_INDEX_FILE} = $git_index;
 193my $maxnum = 0;
 194my $last_rev = "";
 195my $last_branch;
 196my $current_rev = $opt_s ? ($opt_s-1) : 0;
 197unless(-d $git_dir) {
 198        system("git-init-db");
 199        die "Cannot init the GIT db at $git_tree: $?\n" if $?;
 200        system("git-read-tree");
 201        die "Cannot init an empty tree: $?\n" if $?;
 202
 203        $last_branch = $opt_o;
 204        $orig_branch = "";
 205} else {
 206        -f "$git_dir/refs/heads/$opt_o"
 207                or die "Branch '$opt_o' does not exist.\n".
 208                       "Either use the correct '-o branch' option,\n".
 209                       "or import to a new repository.\n";
 210
 211        -f "$git_dir/svn2git"
 212                or die "'$git_dir/svn2git' does not exist.\n".
 213                       "You need that file for incremental imports.\n";
 214        $last_branch = basename(readlink("$git_dir/HEAD"));
 215        unless($last_branch) {
 216                warn "Cannot read the last branch name: $! -- assuming 'master'\n";
 217                $last_branch = "master";
 218        }
 219        $orig_branch = $last_branch;
 220        $last_rev = get_headref($orig_branch, $git_dir);
 221        if (-f "$git_dir/SVN2GIT_HEAD") {
 222                die <<EOM;
 223SVN2GIT_HEAD exists.
 224Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
 225You may need to run
 226
 227    git-read-tree -m -u SVN2GIT_HEAD HEAD
 228EOM
 229        }
 230        system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
 231
 232        $forward_master =
 233            $opt_o ne 'master' && -f "$git_dir/refs/heads/master" &&
 234            system('cmp', '-s', "$git_dir/refs/heads/master", 
 235                                "$git_dir/refs/heads/$opt_o") == 0;
 236
 237        # populate index
 238        system('git-read-tree', $last_rev);
 239        die "read-tree failed: $?\n" if $?;
 240
 241        # Get the last import timestamps
 242        open my $B,"<", "$git_dir/svn2git";
 243        while(<$B>) {
 244                chomp;
 245                my($num,$branch,$ref) = split;
 246                $branches{$branch}{$num} = $ref;
 247                $branches{$branch}{"LAST"} = $ref;
 248                $current_rev = $num if $current_rev < $num;
 249        }
 250        close($B);
 251}
 252-d $git_dir
 253        or die "Could not create git subdir ($git_dir).\n";
 254
 255open BRANCHES,">>", "$git_dir/svn2git";
 256
 257
 258## cvsps output:
 259#---------------------
 260#PatchSet 314
 261#Date: 1999/09/18 13:03:59
 262#Author: wkoch
 263#Branch: STABLE-BRANCH-1-0
 264#Ancestor branch: HEAD
 265#Tag: (none)
 266#Log:
 267#    See ChangeLog: Sat Sep 18 13:03:28 CEST 1999  Werner Koch
 268#Members:
 269#       README:1.57->1.57.2.1
 270#       VERSION:1.96->1.96.2.1
 271#
 272#---------------------
 273
 274my $state = 0;
 275
 276sub get_file($$$) {
 277        my($rev,$branch,$path) = @_;
 278
 279        # revert split_path(), below
 280        my $svnpath;
 281        $path = "" if $path eq "/"; # this should not happen, but ...
 282        if($branch eq "/") {
 283                $svnpath = "/$trunk_name/$path";
 284        } elsif($branch =~ m#^/#) {
 285                $svnpath = "/$tag_name$branch/$path";
 286        } else {
 287                $svnpath = "/$branch_name/$branch/$path";
 288        }
 289
 290        # now get it
 291        my ($name, $res) = eval { $svn->file($svnpath,$rev); };
 292        return () unless defined $name;
 293
 294        open my $F, '-|', "git-hash-object", "-w", $name
 295                or die "Cannot create object: $!\n";
 296        my $sha = <$F>;
 297        chomp $sha;
 298        close $F;
 299        my $mode = "0644"; # SV does not seem to store any file modes
 300        return [$mode, $sha, $path];
 301}
 302
 303sub split_path($$) {
 304        my($rev,$path) = @_;
 305        my $branch;
 306
 307        if($path =~ s#^/\Q$tag_name\E/([^/]+)/?##) {
 308                $branch = "/$1";
 309        } elsif($path =~ s#^/\Q$trunk_name\E/?##) {
 310                $branch = "/";
 311        } elsif($path =~ s#^/\Q$branch_name\E/([^/]+)/?##) {
 312                $branch = $1;
 313        } else {
 314                print STDERR "$rev: Unrecognized path: $path\n";
 315                return ()
 316        }
 317        $path = "/" if $path eq "";
 318        return ($branch,$path);
 319}
 320
 321sub commit {
 322        my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
 323        my($author_name,$author_email,$dest);
 324        my(@old,@new);
 325
 326        if (not defined $author) {
 327                $author_name = $author_email = "unknown";
 328        } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
 329                ($author_name, $author_email) = ($1, $2);
 330        } else {
 331                $author =~ s/^<(.*)>$/$1/;
 332                $author_name = $author_email = $author;
 333        }
 334        $date = pdate($date);
 335
 336        my $tag;
 337        my $parent;
 338        if($branch eq "/") { # trunk
 339                $parent = $opt_o;
 340        } elsif($branch =~ m#^/(.+)#) { # tag
 341                $tag = 1;
 342                $parent = $1;
 343        } else { # "normal" branch
 344                # nothing to do
 345                $parent = $branch;
 346        }
 347        $dest = $parent;
 348
 349        my $prev = $changed_paths->{"/"};
 350        if($prev and $prev->[0] eq "A") {
 351                delete $changed_paths->{"/"};
 352                my $oldpath = $prev->[1];
 353                my $rev;
 354                if(defined $oldpath) {
 355                        my $p;
 356                        ($parent,$p) = split_path($revision,$oldpath);
 357                        if($parent eq "/") {
 358                                $parent = $opt_o;
 359                        } else {
 360                                $parent =~ s#^/##; # if it's a tag
 361                        }
 362                } else {
 363                        $parent = undef;
 364                }
 365        }
 366
 367        my $rev;
 368        if($revision > $opt_s and defined $parent) {
 369                open(H,"git-rev-parse --verify $parent |");
 370                $rev = <H>;
 371                close(H) or do {
 372                        print STDERR "$revision: cannot find commit '$parent'!\n";
 373                        return;
 374                };
 375                chop $rev;
 376                if(length($rev) != 40) {
 377                        print STDERR "$revision: cannot find commit '$parent'!\n";
 378                        return;
 379                }
 380                $rev = $branches{($parent eq $opt_o) ? "/" : $parent}{"LAST"};
 381                if($revision != $opt_s and not $rev) {
 382                        print STDERR "$revision: do not know ancestor for '$parent'!\n";
 383                        return;
 384                }
 385        } else {
 386                $rev = undef;
 387        }
 388
 389#       if($prev and $prev->[0] eq "A") {
 390#               if(not $tag) {
 391#                       unless(open(H,"> $git_dir/refs/heads/$branch")) {
 392#                               print STDERR "$revision: Could not create branch $branch: $!\n";
 393#                               $state=11;
 394#                               next;
 395#                       }
 396#                       print H "$rev\n"
 397#                               or die "Could not write branch $branch: $!";
 398#                       close(H)
 399#                               or die "Could not write branch $branch: $!";
 400#               }
 401#       }
 402        if(not defined $rev) {
 403                unlink($git_index);
 404        } elsif ($rev ne $last_rev) {
 405                print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
 406                system("git-read-tree", $rev);
 407                die "read-tree failed for $rev: $?\n" if $?;
 408                $last_rev = $rev;
 409        }
 410
 411        my $cid;
 412        if($tag and not %$changed_paths) {
 413                $cid = $rev;
 414        } else {
 415                while(my($path,$action) = each %$changed_paths) {
 416                        if ($action->[0] eq "A") {
 417                                my $f = get_file($revision,$branch,$path);
 418                                push(@new,$f) if $f;
 419                        } elsif ($action->[0] eq "D") {
 420                                push(@old,$path);
 421                        } elsif ($action->[0] eq "M") {
 422                                my $f = get_file($revision,$branch,$path);
 423                                push(@new,$f) if $f;
 424                        } elsif ($action->[0] eq "R") {
 425                                # refer to a file/tree in an earlier commit
 426                                push(@old,$path); # remove any old stuff
 427
 428                                # ... and add any new stuff
 429                                my($b,$p) = split_path($revision,$action->[1]);
 430                                open my $F,"-|","git-ls-tree","-r","-z", $branches{$b}{$action->[2]}, $p;
 431                                local $/ = '\0';
 432                                while(<$F>) {
 433                                        chomp;
 434                                        my($m,$p) = split(/\t/,$_,2);
 435                                        my($mode,$type,$sha1) = split(/ /,$m);
 436                                        next if $type ne "blob";
 437                                        push(@new,[$mode,$sha1,$p]);
 438                                }
 439                        } else {
 440                                die "$revision: unknown action '".$action->[0]."' for $path\n";
 441                        }
 442                }
 443
 444                if(@old) {
 445                        open my $F, "-|", "git-ls-files", "-z", @old or die $!;
 446                        @old = ();
 447                        local $/ = '\0';
 448                        while(<$F>) {
 449                                chomp;
 450                                push(@old,$_);
 451                        }
 452                        close($F);
 453
 454                        while(@old) {
 455                                my @o2;
 456                                if(@old > 55) {
 457                                        @o2 = splice(@old,0,50);
 458                                } else {
 459                                        @o2 = @old;
 460                                        @old = ();
 461                                }
 462                                system("git-update-index","--force-remove","--",@o2);
 463                                die "Cannot remove files: $?\n" if $?;
 464                        }
 465                }
 466                while(@new) {
 467                        my @n2;
 468                        if(@new > 12) {
 469                                @n2 = splice(@new,0,10);
 470                        } else {
 471                                @n2 = @new;
 472                                @new = ();
 473                        }
 474                        system("git-update-index","--add",
 475                                (map { ('--cacheinfo', @$_) } @n2));
 476                        die "Cannot add files: $?\n" if $?;
 477                }
 478
 479                my $pid = open(C,"-|");
 480                die "Cannot fork: $!" unless defined $pid;
 481                unless($pid) {
 482                        exec("git-write-tree");
 483                        die "Cannot exec git-write-tree: $!\n";
 484                }
 485                chomp(my $tree = <C>);
 486                length($tree) == 40
 487                        or die "Cannot get tree id ($tree): $!\n";
 488                close(C)
 489                        or die "Error running git-write-tree: $?\n";
 490                print "Tree ID $tree\n" if $opt_v;
 491
 492                my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
 493                my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
 494                $pid = fork();
 495                die "Fork: $!\n" unless defined $pid;
 496                unless($pid) {
 497                        $pr->writer();
 498                        $pw->reader();
 499                        open(OUT,">&STDOUT");
 500                        dup2($pw->fileno(),0);
 501                        dup2($pr->fileno(),1);
 502                        $pr->close();
 503                        $pw->close();
 504
 505                        my @par = ();
 506                        @par = ("-p",$rev) if defined $rev;
 507
 508                        # loose detection of merges
 509                        # based on the commit msg
 510                        foreach my $rx (@mergerx) {
 511                                if ($message =~ $rx) {
 512                                        my $mparent = $1;
 513                                        if ($mparent eq 'HEAD') { $mparent = $opt_o };
 514                                        if ( -e "$git_dir/refs/heads/$mparent") {
 515                                                $mparent = get_headref($mparent, $git_dir);
 516                                                push @par, '-p', $mparent;
 517                                                print OUT "Merge parent branch: $mparent\n" if $opt_v;
 518                                        }
 519                                } 
 520                        }
 521
 522                        exec("env",
 523                                "GIT_AUTHOR_NAME=$author_name",
 524                                "GIT_AUTHOR_EMAIL=$author_email",
 525                                "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
 526                                "GIT_COMMITTER_NAME=$author_name",
 527                                "GIT_COMMITTER_EMAIL=$author_email",
 528                                "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
 529                                "git-commit-tree", $tree,@par);
 530                        die "Cannot exec git-commit-tree: $!\n";
 531                }
 532                $pw->writer();
 533                $pr->reader();
 534
 535                $message =~ s/[\s\n]+\z//;
 536
 537                print $pw "$message\n"
 538                        or die "Error writing to git-commit-tree: $!\n";
 539                $pw->close();
 540
 541                print "Committed change $revision:$branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
 542                chomp($cid = <$pr>);
 543                length($cid) == 40
 544                        or die "Cannot get commit id ($cid): $!\n";
 545                print "Commit ID $cid\n" if $opt_v;
 546                $pr->close();
 547
 548                waitpid($pid,0);
 549                die "Error running git-commit-tree: $?\n" if $?;
 550        }
 551
 552        if(not defined $dest) {
 553                print "... no known parent\n" if $opt_v;
 554        } elsif(not $tag) {
 555                print "Writing to refs/heads/$dest\n" if $opt_v;
 556                open(C,">$git_dir/refs/heads/$dest") and 
 557                print C ("$cid\n") and
 558                close(C)
 559                        or die "Cannot write branch $dest for update: $!\n";
 560        }
 561
 562        if($tag) {
 563                my($in, $out) = ('','');
 564                $last_rev = "-" if %$changed_paths;
 565                # the tag was 'complex', i.e. did not refer to a "real" revision
 566                
 567                $dest =~ tr/_/\./ if $opt_u;
 568
 569                my $pid = open2($in, $out, 'git-mktag');
 570                print $out ("object $cid\n".
 571                    "type commit\n".
 572                    "tag $dest\n".
 573                    "tagger $author_name <$author_email>\n") and
 574                close($out)
 575                    or die "Cannot create tag object $dest: $!\n";
 576
 577                my $tagobj = <$in>;
 578                chomp $tagobj;
 579
 580                if ( !close($in) or waitpid($pid, 0) != $pid or
 581                                $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
 582                        die "Cannot create tag object $dest: $!\n";
 583                }
 584
 585                open(C,">$git_dir/refs/tags/$dest") and
 586                print C ("$tagobj\n") and
 587                close(C)
 588                        or die "Cannot create tag $branch: $!\n";
 589
 590                print "Created tag '$dest' on '$branch'\n" if $opt_v;
 591        }
 592        $branches{$branch}{"LAST"} = $cid;
 593        $branches{$branch}{$revision} = $cid;
 594        $last_rev = $cid;
 595        print BRANCHES "$revision $branch $cid\n";
 596        print "DONE: $revision $dest $cid\n" if $opt_v;
 597}
 598
 599my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
 600sub _commit_all {
 601        ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
 602        my %p;
 603        while(my($path,$action) = each %$changed_paths) {
 604                $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev ];
 605        }
 606        $changed_paths = \%p;
 607}
 608
 609sub commit_all {
 610        my %done;
 611        my @col;
 612        my $pref;
 613        my $branch;
 614
 615        while(my($path,$action) = each %$changed_paths) {
 616                ($branch,$path) = split_path($revision,$path);
 617                next if not defined $branch;
 618                $done{$branch}{$path} = $action;
 619        }
 620        while(($branch,$changed_paths) = each %done) {
 621                commit($branch, $changed_paths, $revision, $author, $date, $message);
 622        }
 623}
 624
 625while(++$current_rev < $svn->{'maxrev'}) {
 626        $svn->{'svn'}->get_log("/",$current_rev,$current_rev,$current_rev,1,1,\&_commit_all,"");
 627        commit_all();
 628        if($opt_l and not --$opt_l) {
 629                print STDERR "Exiting due to a memory leak. Repeat, please.\n";
 630                last;
 631        }
 632}
 633
 634
 635unlink($git_index);
 636
 637if (defined $orig_git_index) {
 638        $ENV{GIT_INDEX_FILE} = $orig_git_index;
 639} else {
 640        delete $ENV{GIT_INDEX_FILE};
 641}
 642
 643# Now switch back to the branch we were in before all of this happened
 644if($orig_branch) {
 645        print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
 646        system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
 647                if $forward_master;
 648        unless ($opt_i) {
 649                system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
 650                die "read-tree failed: $?\n" if $?;
 651        }
 652} else {
 653        $orig_branch = "master";
 654        print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
 655        system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
 656                unless -f "$git_dir/refs/heads/master";
 657        unlink("$git_dir/HEAD");
 658        symlink("refs/heads/$orig_branch","$git_dir/HEAD");
 659        unless ($opt_i) {
 660                system('git checkout');
 661                die "checkout failed: $?\n" if $?;
 662        }
 663}
 664unlink("$git_dir/SVN2GIT_HEAD");
 665close(BRANCHES);