git-cvsimport.perlon commit Documentation/git-svn: clarify dcommit, rebase vs pull/merge (2eff142)
   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 aggregate CVS check-ins into related changes.
   7# Fortunately, "cvsps" does that for us; all we have to do is to parse
   8# its output.
   9#
  10# Checking out the files is done by a single long-running CVS connection
  11# / server process.
  12#
  13# The head revision is on branch "origin" by default.
  14# You can change that with the '-o' option.
  15
  16use strict;
  17use warnings;
  18use Getopt::Std;
  19use File::Spec;
  20use File::Temp qw(tempfile tmpnam);
  21use File::Path qw(mkpath);
  22use File::Basename qw(basename dirname);
  23use Time::Local;
  24use IO::Socket;
  25use IO::Pipe;
  26use POSIX qw(strftime dup2 ENOENT);
  27use IPC::Open2;
  28
  29$SIG{'PIPE'}="IGNORE";
  30$ENV{'TZ'}="UTC";
  31
  32our ($opt_h,$opt_o,$opt_v,$opt_k,$opt_u,$opt_d,$opt_p,$opt_C,$opt_z,$opt_i,$opt_P, $opt_s,$opt_m,$opt_M,$opt_A,$opt_S,$opt_L);
  33my (%conv_author_name, %conv_author_email);
  34
  35sub usage() {
  36        print STDERR <<END;
  37Usage: ${\basename $0}     # fetch/update GIT from CVS
  38       [-o branch-for-HEAD] [-h] [-v] [-d CVSROOT] [-A author-conv-file]
  39       [-p opts-for-cvsps] [-C GIT_repository] [-z fuzz] [-i] [-k] [-u]
  40       [-s subst] [-m] [-M regex] [-S regex] [CVS_module]
  41END
  42        exit(1);
  43}
  44
  45sub read_author_info($) {
  46        my ($file) = @_;
  47        my $user;
  48        open my $f, '<', "$file" or die("Failed to open $file: $!\n");
  49
  50        while (<$f>) {
  51                # Expected format is this:
  52                #   exon=Andreas Ericsson <ae@op5.se>
  53                if (m/^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/) {
  54                        $user = $1;
  55                        $conv_author_name{$user} = $2;
  56                        $conv_author_email{$user} = $3;
  57                }
  58                # However, we also read from CVSROOT/users format
  59                # to ease migration.
  60                elsif (/^(\w+):(['"]?)(.+?)\2\s*$/) {
  61                        my $mapped;
  62                        ($user, $mapped) = ($1, $3);
  63                        if ($mapped =~ /^\s*(.*?)\s*<(.*)>\s*$/) {
  64                                $conv_author_name{$user} = $1;
  65                                $conv_author_email{$user} = $2;
  66                        }
  67                        elsif ($mapped =~ /^<?(.*)>?$/) {
  68                                $conv_author_name{$user} = $user;
  69                                $conv_author_email{$user} = $1;
  70                        }
  71                }
  72                # NEEDSWORK: Maybe warn on unrecognized lines?
  73        }
  74        close ($f);
  75}
  76
  77sub write_author_info($) {
  78        my ($file) = @_;
  79        open my $f, '>', $file or
  80          die("Failed to open $file for writing: $!");
  81
  82        foreach (keys %conv_author_name) {
  83                print $f "$_=$conv_author_name{$_} <$conv_author_email{$_}>\n";
  84        }
  85        close ($f);
  86}
  87
  88getopts("hivmkuo:d:p:C:z:s:M:P:A:S:L:") or usage();
  89usage if $opt_h;
  90
  91@ARGV <= 1 or usage();
  92
  93if ($opt_d) {
  94        $ENV{"CVSROOT"} = $opt_d;
  95} elsif (-f 'CVS/Root') {
  96        open my $f, '<', 'CVS/Root' or die 'Failed to open CVS/Root';
  97        $opt_d = <$f>;
  98        chomp $opt_d;
  99        close $f;
 100        $ENV{"CVSROOT"} = $opt_d;
 101} elsif ($ENV{"CVSROOT"}) {
 102        $opt_d = $ENV{"CVSROOT"};
 103} else {
 104        die "CVSROOT needs to be set";
 105}
 106$opt_o ||= "origin";
 107$opt_s ||= "-";
 108my $git_tree = $opt_C;
 109$git_tree ||= ".";
 110
 111my $cvs_tree;
 112if ($#ARGV == 0) {
 113        $cvs_tree = $ARGV[0];
 114} elsif (-f 'CVS/Repository') {
 115        open my $f, '<', 'CVS/Repository' or 
 116            die 'Failed to open CVS/Repository';
 117        $cvs_tree = <$f>;
 118        chomp $cvs_tree;
 119        close $f;
 120} else {
 121        usage();
 122}
 123
 124our @mergerx = ();
 125if ($opt_m) {
 126        @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
 127}
 128if ($opt_M) {
 129        push (@mergerx, qr/$opt_M/);
 130}
 131
 132select(STDERR); $|=1; select(STDOUT);
 133
 134
 135package CVSconn;
 136# Basic CVS dialog.
 137# We're only interested in connecting and downloading, so ...
 138
 139use File::Spec;
 140use File::Temp qw(tempfile);
 141use POSIX qw(strftime dup2);
 142
 143sub new {
 144        my ($what,$repo,$subdir) = @_;
 145        $what=ref($what) if ref($what);
 146
 147        my $self = {};
 148        $self->{'buffer'} = "";
 149        bless($self,$what);
 150
 151        $repo =~ s#/+$##;
 152        $self->{'fullrep'} = $repo;
 153        $self->conn();
 154
 155        $self->{'subdir'} = $subdir;
 156        $self->{'lines'} = undef;
 157
 158        return $self;
 159}
 160
 161sub conn {
 162        my $self = shift;
 163        my $repo = $self->{'fullrep'};
 164        if ($repo =~ s/^:pserver(?:([^:]*)):(?:(.*?)(?::(.*?))?@)?([^:\/]*)(?::(\d*))?//) {
 165                my ($param,$user,$pass,$serv,$port) = ($1,$2,$3,$4,$5);
 166
 167                my ($proxyhost,$proxyport);
 168                if ($param && ($param =~ m/proxy=([^;]+)/)) {
 169                        $proxyhost = $1;
 170                        # Default proxyport, if not specified, is 8080.
 171                        $proxyport = 8080;
 172                        if ($ENV{"CVS_PROXY_PORT"}) {
 173                                $proxyport = $ENV{"CVS_PROXY_PORT"};
 174                        }
 175                        if ($param =~ m/proxyport=([^;]+)/) {
 176                                $proxyport = $1;
 177                        }
 178                }
 179
 180                $user="anonymous" unless defined $user;
 181                my $rr2 = "-";
 182                unless ($port) {
 183                        $rr2 = ":pserver:$user\@$serv:$repo";
 184                        $port=2401;
 185                }
 186                my $rr = ":pserver:$user\@$serv:$port$repo";
 187
 188                unless ($pass) {
 189                        open(H,$ENV{'HOME'}."/.cvspass") and do {
 190                                # :pserver:cvs@mea.tmt.tele.fi:/cvsroot/zmailer Ah<Z
 191                                while (<H>) {
 192                                        chomp;
 193                                        s/^\/\d+\s+//;
 194                                        my ($w,$p) = split(/\s/,$_,2);
 195                                        if ($w eq $rr or $w eq $rr2) {
 196                                                $pass = $p;
 197                                                last;
 198                                        }
 199                                }
 200                        };
 201                }
 202                $pass="A" unless $pass;
 203
 204                my ($s, $rep);
 205                if ($proxyhost) {
 206
 207                        # Use a HTTP Proxy. Only works for HTTP proxies that
 208                        # don't require user authentication
 209                        #
 210                        # See: http://www.ietf.org/rfc/rfc2817.txt
 211
 212                        $s = IO::Socket::INET->new(PeerHost => $proxyhost, PeerPort => $proxyport);
 213                        die "Socket to $proxyhost: $!\n" unless defined $s;
 214                        $s->write("CONNECT $serv:$port HTTP/1.1\r\nHost: $serv:$port\r\n\r\n")
 215                                or die "Write to $proxyhost: $!\n";
 216                        $s->flush();
 217
 218                        $rep = <$s>;
 219
 220                        # The answer should look like 'HTTP/1.x 2yy ....'
 221                        if (!($rep =~ m#^HTTP/1\.. 2[0-9][0-9]#)) {
 222                                die "Proxy connect: $rep\n";
 223                        }
 224                        # Skip up to the empty line of the proxy server output
 225                        # including the response headers.
 226                        while ($rep = <$s>) {
 227                                last if (!defined $rep ||
 228                                         $rep eq "\n" ||
 229                                         $rep eq "\r\n");
 230                        }
 231                } else {
 232                        $s = IO::Socket::INET->new(PeerHost => $serv, PeerPort => $port);
 233                        die "Socket to $serv: $!\n" unless defined $s;
 234                }
 235
 236                $s->write("BEGIN AUTH REQUEST\n$repo\n$user\n$pass\nEND AUTH REQUEST\n")
 237                        or die "Write to $serv: $!\n";
 238                $s->flush();
 239
 240                $rep = <$s>;
 241
 242                if ($rep ne "I LOVE YOU\n") {
 243                        $rep="<unknown>" unless $rep;
 244                        die "AuthReply: $rep\n";
 245                }
 246                $self->{'socketo'} = $s;
 247                $self->{'socketi'} = $s;
 248        } else { # local or ext: Fork off our own cvs server.
 249                my $pr = IO::Pipe->new();
 250                my $pw = IO::Pipe->new();
 251                my $pid = fork();
 252                die "Fork: $!\n" unless defined $pid;
 253                my $cvs = 'cvs';
 254                $cvs = $ENV{CVS_SERVER} if exists $ENV{CVS_SERVER};
 255                my $rsh = 'rsh';
 256                $rsh = $ENV{CVS_RSH} if exists $ENV{CVS_RSH};
 257
 258                my @cvs = ($cvs, 'server');
 259                my ($local, $user, $host);
 260                $local = $repo =~ s/:local://;
 261                if (!$local) {
 262                    $repo =~ s/:ext://;
 263                    $local = !($repo =~ s/^(?:([^\@:]+)\@)?([^:]+)://);
 264                    ($user, $host) = ($1, $2);
 265                }
 266                if (!$local) {
 267                    if ($user) {
 268                        unshift @cvs, $rsh, '-l', $user, $host;
 269                    } else {
 270                        unshift @cvs, $rsh, $host;
 271                    }
 272                }
 273
 274                unless ($pid) {
 275                        $pr->writer();
 276                        $pw->reader();
 277                        dup2($pw->fileno(),0);
 278                        dup2($pr->fileno(),1);
 279                        $pr->close();
 280                        $pw->close();
 281                        exec(@cvs);
 282                }
 283                $pw->writer();
 284                $pr->reader();
 285                $self->{'socketo'} = $pw;
 286                $self->{'socketi'} = $pr;
 287        }
 288        $self->{'socketo'}->write("Root $repo\n");
 289
 290        # Trial and error says that this probably is the minimum set
 291        $self->{'socketo'}->write("Valid-responses ok error Valid-requests Mode M Mbinary E Checked-in Created Updated Merged Removed\n");
 292
 293        $self->{'socketo'}->write("valid-requests\n");
 294        $self->{'socketo'}->flush();
 295
 296        chomp(my $rep=$self->readline());
 297        if ($rep !~ s/^Valid-requests\s*//) {
 298                $rep="<unknown>" unless $rep;
 299                die "Expected Valid-requests from server, but got: $rep\n";
 300        }
 301        chomp(my $res=$self->readline());
 302        die "validReply: $res\n" if $res ne "ok";
 303
 304        $self->{'socketo'}->write("UseUnchanged\n") if $rep =~ /\bUseUnchanged\b/;
 305        $self->{'repo'} = $repo;
 306}
 307
 308sub readline {
 309        my ($self) = @_;
 310        return $self->{'socketi'}->getline();
 311}
 312
 313sub _file {
 314        # Request a file with a given revision.
 315        # Trial and error says this is a good way to do it. :-/
 316        my ($self,$fn,$rev) = @_;
 317        $self->{'socketo'}->write("Argument -N\n") or return undef;
 318        $self->{'socketo'}->write("Argument -P\n") or return undef;
 319        # -kk: Linus' version doesn't use it - defaults to off
 320        if ($opt_k) {
 321            $self->{'socketo'}->write("Argument -kk\n") or return undef;
 322        }
 323        $self->{'socketo'}->write("Argument -r\n") or return undef;
 324        $self->{'socketo'}->write("Argument $rev\n") or return undef;
 325        $self->{'socketo'}->write("Argument --\n") or return undef;
 326        $self->{'socketo'}->write("Argument $self->{'subdir'}/$fn\n") or return undef;
 327        $self->{'socketo'}->write("Directory .\n") or return undef;
 328        $self->{'socketo'}->write("$self->{'repo'}\n") or return undef;
 329        # $self->{'socketo'}->write("Sticky T1.0\n") or return undef;
 330        $self->{'socketo'}->write("co\n") or return undef;
 331        $self->{'socketo'}->flush() or return undef;
 332        $self->{'lines'} = 0;
 333        return 1;
 334}
 335sub _line {
 336        # Read a line from the server.
 337        # ... except that 'line' may be an entire file. ;-)
 338        my ($self, $fh) = @_;
 339        die "Not in lines" unless defined $self->{'lines'};
 340
 341        my $line;
 342        my $res=0;
 343        while (defined($line = $self->readline())) {
 344                # M U gnupg-cvs-rep/AUTHORS
 345                # Updated gnupg-cvs-rep/
 346                # /daten/src/rsync/gnupg-cvs-rep/AUTHORS
 347                # /AUTHORS/1.1///T1.1
 348                # u=rw,g=rw,o=rw
 349                # 0
 350                # ok
 351
 352                if ($line =~ s/^(?:Created|Updated) //) {
 353                        $line = $self->readline(); # path
 354                        $line = $self->readline(); # Entries line
 355                        my $mode = $self->readline(); chomp $mode;
 356                        $self->{'mode'} = $mode;
 357                        defined (my $cnt = $self->readline())
 358                                or die "EOF from server after 'Changed'\n";
 359                        chomp $cnt;
 360                        die "Duh: Filesize $cnt" if $cnt !~ /^\d+$/;
 361                        $line="";
 362                        $res = $self->_fetchfile($fh, $cnt);
 363                } elsif ($line =~ s/^ //) {
 364                        print $fh $line;
 365                        $res += length($line);
 366                } elsif ($line =~ /^M\b/) {
 367                        # output, do nothing
 368                } elsif ($line =~ /^Mbinary\b/) {
 369                        my $cnt;
 370                        die "EOF from server after 'Mbinary'" unless defined ($cnt = $self->readline());
 371                        chomp $cnt;
 372                        die "Duh: Mbinary $cnt" if $cnt !~ /^\d+$/ or $cnt<1;
 373                        $line="";
 374                        $res += $self->_fetchfile($fh, $cnt);
 375                } else {
 376                        chomp $line;
 377                        if ($line eq "ok") {
 378                                # print STDERR "S: ok (".length($res).")\n";
 379                                return $res;
 380                        } elsif ($line =~ s/^E //) {
 381                                # print STDERR "S: $line\n";
 382                        } elsif ($line =~ /^(Remove-entry|Removed) /i) {
 383                                $line = $self->readline(); # filename
 384                                $line = $self->readline(); # OK
 385                                chomp $line;
 386                                die "Unknown: $line" if $line ne "ok";
 387                                return -1;
 388                        } else {
 389                                die "Unknown: $line\n";
 390                        }
 391                }
 392        }
 393        return undef;
 394}
 395sub file {
 396        my ($self,$fn,$rev) = @_;
 397        my $res;
 398
 399        my ($fh, $name) = tempfile('gitcvs.XXXXXX', 
 400                    DIR => File::Spec->tmpdir(), UNLINK => 1);
 401
 402        $self->_file($fn,$rev) and $res = $self->_line($fh);
 403
 404        if (!defined $res) {
 405            print STDERR "Server has gone away while fetching $fn $rev, retrying...\n";
 406            truncate $fh, 0;
 407            $self->conn();
 408            $self->_file($fn,$rev) or die "No file command send";
 409            $res = $self->_line($fh);
 410            die "Retry failed" unless defined $res;
 411        }
 412        close ($fh);
 413
 414        return ($name, $res);
 415}
 416sub _fetchfile {
 417        my ($self, $fh, $cnt) = @_;
 418        my $res = 0;
 419        my $bufsize = 1024 * 1024;
 420        while ($cnt) {
 421            if ($bufsize > $cnt) {
 422                $bufsize = $cnt;
 423            }
 424            my $buf;
 425            my $num = $self->{'socketi'}->read($buf,$bufsize);
 426            die "Server: Filesize $cnt: $num: $!\n" if not defined $num or $num<=0;
 427            print $fh $buf;
 428            $res += $num;
 429            $cnt -= $num;
 430        }
 431        return $res;
 432}
 433
 434
 435package main;
 436
 437my $cvs = CVSconn->new($opt_d, $cvs_tree);
 438
 439
 440sub pdate($) {
 441        my ($d) = @_;
 442        m#(\d{2,4})/(\d\d)/(\d\d)\s(\d\d):(\d\d)(?::(\d\d))?#
 443                or die "Unparseable date: $d\n";
 444        my $y=$1; $y-=1900 if $y>1900;
 445        return timegm($6||0,$5,$4,$3,$2-1,$y);
 446}
 447
 448sub pmode($) {
 449        my ($mode) = @_;
 450        my $m = 0;
 451        my $mm = 0;
 452        my $um = 0;
 453        for my $x(split(//,$mode)) {
 454                if ($x eq ",") {
 455                        $m |= $mm&$um;
 456                        $mm = 0;
 457                        $um = 0;
 458                } elsif ($x eq "u") { $um |= 0700;
 459                } elsif ($x eq "g") { $um |= 0070;
 460                } elsif ($x eq "o") { $um |= 0007;
 461                } elsif ($x eq "r") { $mm |= 0444;
 462                } elsif ($x eq "w") { $mm |= 0222;
 463                } elsif ($x eq "x") { $mm |= 0111;
 464                } elsif ($x eq "=") { # do nothing
 465                } else { die "Unknown mode: $mode\n";
 466                }
 467        }
 468        $m |= $mm&$um;
 469        return $m;
 470}
 471
 472sub getwd() {
 473        my $pwd = `pwd`;
 474        chomp $pwd;
 475        return $pwd;
 476}
 477
 478sub is_sha1 {
 479        my $s = shift;
 480        return $s =~ /^[a-f0-9]{40}$/;
 481}
 482
 483sub get_headref ($$) {
 484    my $name    = shift;
 485    my $git_dir = shift; 
 486    
 487    my $f = "$git_dir/refs/heads/$name";
 488    if (open(my $fh, $f)) {
 489            chomp(my $r = <$fh>);
 490            is_sha1($r) or die "Cannot get head id for $name ($r): $!";
 491            return $r;
 492    }
 493    die "unable to open $f: $!" unless $! == POSIX::ENOENT;
 494    return undef;
 495}
 496
 497-d $git_tree
 498        or mkdir($git_tree,0777)
 499        or die "Could not create $git_tree: $!";
 500chdir($git_tree);
 501
 502my $last_branch = "";
 503my $orig_branch = "";
 504my %branch_date;
 505my $tip_at_start = undef;
 506
 507my $git_dir = $ENV{"GIT_DIR"} || ".git";
 508$git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
 509$ENV{"GIT_DIR"} = $git_dir;
 510my $orig_git_index;
 511$orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
 512
 513my %index; # holds filenames of one index per branch
 514
 515unless (-d $git_dir) {
 516        system("git-init-db");
 517        die "Cannot init the GIT db at $git_tree: $?\n" if $?;
 518        system("git-read-tree");
 519        die "Cannot init an empty tree: $?\n" if $?;
 520
 521        $last_branch = $opt_o;
 522        $orig_branch = "";
 523} else {
 524        -f "$git_dir/refs/heads/$opt_o"
 525                or die "Branch '$opt_o' does not exist.\n".
 526                       "Either use the correct '-o branch' option,\n".
 527                       "or import to a new repository.\n";
 528
 529        open(F, "git-symbolic-ref HEAD |") or
 530                die "Cannot run git-symbolic-ref: $!\n";
 531        chomp ($last_branch = <F>);
 532        $last_branch = basename($last_branch);
 533        close(F);
 534        unless ($last_branch) {
 535                warn "Cannot read the last branch name: $! -- assuming 'master'\n";
 536                $last_branch = "master";
 537        }
 538        $orig_branch = $last_branch;
 539        $tip_at_start = `git-rev-parse --verify HEAD`;
 540
 541        # Get the last import timestamps
 542        my $fmt = '($ref, $author) = (%(refname), %(author));';
 543        open(H, "git-for-each-ref --perl --format='$fmt' refs/heads |") or
 544                die "Cannot run git-for-each-ref: $!\n";
 545        while (defined(my $entry = <H>)) {
 546                my ($ref, $author);
 547                eval($entry) || die "cannot eval refs list: $@";
 548                my ($head) = ($ref =~ m|^refs/heads/(.*)|);
 549                $author =~ /^.*\s(\d+)\s[-+]\d{4}$/;
 550                $branch_date{$head} = $1;
 551        }
 552        close(H);
 553}
 554
 555-d $git_dir
 556        or die "Could not create git subdir ($git_dir).\n";
 557
 558# now we read (and possibly save) author-info as well
 559-f "$git_dir/cvs-authors" and
 560  read_author_info("$git_dir/cvs-authors");
 561if ($opt_A) {
 562        read_author_info($opt_A);
 563        write_author_info("$git_dir/cvs-authors");
 564}
 565
 566
 567#
 568# run cvsps into a file unless we are getting
 569# it passed as a file via $opt_P
 570#
 571unless ($opt_P) {
 572        print "Running cvsps...\n" if $opt_v;
 573        my $pid = open(CVSPS,"-|");
 574        die "Cannot fork: $!\n" unless defined $pid;
 575        unless ($pid) {
 576                my @opt;
 577                @opt = split(/,/,$opt_p) if defined $opt_p;
 578                unshift @opt, '-z', $opt_z if defined $opt_z;
 579                unshift @opt, '-q'         unless defined $opt_v;
 580                unless (defined($opt_p) && $opt_p =~ m/--no-cvs-direct/) {
 581                        push @opt, '--cvs-direct';
 582                }
 583                exec("cvsps","--norc",@opt,"-u","-A",'--root',$opt_d,$cvs_tree);
 584                die "Could not start cvsps: $!\n";
 585        }
 586        my ($cvspsfh, $cvspsfile) = tempfile('gitXXXXXX', SUFFIX => '.cvsps',
 587                                             DIR => File::Spec->tmpdir());
 588        while (<CVSPS>) {
 589            print $cvspsfh $_;
 590        }
 591        close CVSPS;
 592        close $cvspsfh;
 593        $opt_P = $cvspsfile;
 594}
 595
 596
 597open(CVS, "<$opt_P") or die $!;
 598
 599## cvsps output:
 600#---------------------
 601#PatchSet 314
 602#Date: 1999/09/18 13:03:59
 603#Author: wkoch
 604#Branch: STABLE-BRANCH-1-0
 605#Ancestor branch: HEAD
 606#Tag: (none)
 607#Log:
 608#    See ChangeLog: Sat Sep 18 13:03:28 CEST 1999  Werner Koch
 609#Members:
 610#       README:1.57->1.57.2.1
 611#       VERSION:1.96->1.96.2.1
 612#
 613#---------------------
 614
 615my $state = 0;
 616
 617sub update_index (\@\@) {
 618        my $old = shift;
 619        my $new = shift;
 620        open(my $fh, '|-', qw(git-update-index -z --index-info))
 621                or die "unable to open git-update-index: $!";
 622        print $fh
 623                (map { "0 0000000000000000000000000000000000000000\t$_\0" }
 624                        @$old),
 625                (map { '100' . sprintf('%o', $_->[0]) . " $_->[1]\t$_->[2]\0" }
 626                        @$new)
 627                or die "unable to write to git-update-index: $!";
 628        close $fh
 629                or die "unable to write to git-update-index: $!";
 630        $? and die "git-update-index reported error: $?";
 631}
 632
 633sub write_tree () {
 634        open(my $fh, '-|', qw(git-write-tree))
 635                or die "unable to open git-write-tree: $!";
 636        chomp(my $tree = <$fh>);
 637        is_sha1($tree)
 638                or die "Cannot get tree id ($tree): $!";
 639        close($fh)
 640                or die "Error running git-write-tree: $?\n";
 641        print "Tree ID $tree\n" if $opt_v;
 642        return $tree;
 643}
 644
 645my ($patchset,$date,$author_name,$author_email,$branch,$ancestor,$tag,$logmsg);
 646my (@old,@new,@skipped,%ignorebranch);
 647
 648# commits that cvsps cannot place anywhere...
 649$ignorebranch{'#CVSPS_NO_BRANCH'} = 1;
 650
 651sub commit {
 652        if ($branch eq $opt_o && !$index{branch} && !get_headref($branch, $git_dir)) {
 653            # looks like an initial commit
 654            # use the index primed by git-init-db
 655            $ENV{GIT_INDEX_FILE} = '.git/index';
 656            $index{$branch} = '.git/index';
 657        } else {
 658            # use an index per branch to speed up
 659            # imports of projects with many branches
 660            unless ($index{$branch}) {
 661                $index{$branch} = tmpnam();
 662                $ENV{GIT_INDEX_FILE} = $index{$branch};
 663                if ($ancestor) {
 664                    system("git-read-tree", $ancestor);
 665                } else {
 666                    system("git-read-tree", $branch);
 667                }
 668                die "read-tree failed: $?\n" if $?;
 669            }
 670        }
 671        $ENV{GIT_INDEX_FILE} = $index{$branch};
 672
 673        update_index(@old, @new);
 674        @old = @new = ();
 675        my $tree = write_tree();
 676        my $parent = get_headref($last_branch, $git_dir);
 677        print "Parent ID " . ($parent ? $parent : "(empty)") . "\n" if $opt_v;
 678
 679        my @commit_args;
 680        push @commit_args, ("-p", $parent) if $parent;
 681
 682        # loose detection of merges
 683        # based on the commit msg
 684        foreach my $rx (@mergerx) {
 685                next unless $logmsg =~ $rx && $1;
 686                my $mparent = $1 eq 'HEAD' ? $opt_o : $1;
 687                if (my $sha1 = get_headref($mparent, $git_dir)) {
 688                        push @commit_args, '-p', $mparent;
 689                        print "Merge parent branch: $mparent\n" if $opt_v;
 690                }
 691        }
 692
 693        my $commit_date = strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date));
 694        $ENV{GIT_AUTHOR_NAME} = $author_name;
 695        $ENV{GIT_AUTHOR_EMAIL} = $author_email;
 696        $ENV{GIT_AUTHOR_DATE} = $commit_date;
 697        $ENV{GIT_COMMITTER_NAME} = $author_name;
 698        $ENV{GIT_COMMITTER_EMAIL} = $author_email;
 699        $ENV{GIT_COMMITTER_DATE} = $commit_date;
 700        my $pid = open2(my $commit_read, my $commit_write,
 701                'git-commit-tree', $tree, @commit_args);
 702
 703        # compatibility with git2cvs
 704        substr($logmsg,32767) = "" if length($logmsg) > 32767;
 705        $logmsg =~ s/[\s\n]+\z//;
 706
 707        if (@skipped) {
 708            $logmsg .= "\n\n\nSKIPPED:\n\t";
 709            $logmsg .= join("\n\t", @skipped) . "\n";
 710            @skipped = ();
 711        }
 712
 713        print($commit_write "$logmsg\n") && close($commit_write)
 714                or die "Error writing to git-commit-tree: $!\n";
 715
 716        print "Committed patch $patchset ($branch $commit_date)\n" if $opt_v;
 717        chomp(my $cid = <$commit_read>);
 718        is_sha1($cid) or die "Cannot get commit id ($cid): $!\n";
 719        print "Commit ID $cid\n" if $opt_v;
 720        close($commit_read);
 721
 722        waitpid($pid,0);
 723        die "Error running git-commit-tree: $?\n" if $?;
 724
 725        system("git-update-ref refs/heads/$branch $cid") == 0
 726                or die "Cannot write branch $branch for update: $!\n";
 727
 728        if ($tag) {
 729                my ($in, $out) = ('','');
 730                my ($xtag) = $tag;
 731                $xtag =~ s/\s+\*\*.*$//; # Remove stuff like ** INVALID ** and ** FUNKY **
 732                $xtag =~ tr/_/\./ if ( $opt_u );
 733                $xtag =~ s/[\/]/$opt_s/g;
 734                
 735                my $pid = open2($in, $out, 'git-mktag');
 736                print $out "object $cid\n".
 737                    "type commit\n".
 738                    "tag $xtag\n".
 739                    "tagger $author_name <$author_email>\n"
 740                    or die "Cannot create tag object $xtag: $!\n";
 741                close($out)
 742                    or die "Cannot create tag object $xtag: $!\n";
 743
 744                my $tagobj = <$in>;
 745                chomp $tagobj;
 746
 747                if ( !close($in) or waitpid($pid, 0) != $pid or
 748                     $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
 749                    die "Cannot create tag object $xtag: $!\n";
 750                }
 751                
 752
 753                open(C,">$git_dir/refs/tags/$xtag")
 754                        or die "Cannot create tag $xtag: $!\n";
 755                print C "$tagobj\n"
 756                        or die "Cannot write tag $xtag: $!\n";
 757                close(C)
 758                        or die "Cannot write tag $xtag: $!\n";
 759
 760                print "Created tag '$xtag' on '$branch'\n" if $opt_v;
 761        }
 762};
 763
 764my $commitcount = 1;
 765while (<CVS>) {
 766        chomp;
 767        if ($state == 0 and /^-+$/) {
 768                $state = 1;
 769        } elsif ($state == 0) {
 770                $state = 1;
 771                redo;
 772        } elsif (($state==0 or $state==1) and s/^PatchSet\s+//) {
 773                $patchset = 0+$_;
 774                $state=2;
 775        } elsif ($state == 2 and s/^Date:\s+//) {
 776                $date = pdate($_);
 777                unless ($date) {
 778                        print STDERR "Could not parse date: $_\n";
 779                        $state=0;
 780                        next;
 781                }
 782                $state=3;
 783        } elsif ($state == 3 and s/^Author:\s+//) {
 784                s/\s+$//;
 785                if (/^(.*?)\s+<(.*)>/) {
 786                    ($author_name, $author_email) = ($1, $2);
 787                } elsif ($conv_author_name{$_}) {
 788                        $author_name = $conv_author_name{$_};
 789                        $author_email = $conv_author_email{$_};
 790                } else {
 791                    $author_name = $author_email = $_;
 792                }
 793                $state = 4;
 794        } elsif ($state == 4 and s/^Branch:\s+//) {
 795                s/\s+$//;
 796                s/[\/]/$opt_s/g;
 797                $branch = $_;
 798                $state = 5;
 799        } elsif ($state == 5 and s/^Ancestor branch:\s+//) {
 800                s/\s+$//;
 801                $ancestor = $_;
 802                $ancestor = $opt_o if $ancestor eq "HEAD";
 803                $state = 6;
 804        } elsif ($state == 5) {
 805                $ancestor = undef;
 806                $state = 6;
 807                redo;
 808        } elsif ($state == 6 and s/^Tag:\s+//) {
 809                s/\s+$//;
 810                if ($_ eq "(none)") {
 811                        $tag = undef;
 812                } else {
 813                        $tag = $_;
 814                }
 815                $state = 7;
 816        } elsif ($state == 7 and /^Log:/) {
 817                $logmsg = "";
 818                $state = 8;
 819        } elsif ($state == 8 and /^Members:/) {
 820                $branch = $opt_o if $branch eq "HEAD";
 821                if (defined $branch_date{$branch} and $branch_date{$branch} >= $date) {
 822                        # skip
 823                        print "skip patchset $patchset: $date before $branch_date{$branch}\n" if $opt_v;
 824                        $state = 11;
 825                        next;
 826                }
 827                if (exists $ignorebranch{$branch}) {
 828                        print STDERR "Skipping $branch\n";
 829                        $state = 11;
 830                        next;
 831                }
 832                if ($ancestor) {
 833                        if ($ancestor eq $branch) {
 834                                print STDERR "Branch $branch erroneously stems from itself -- changed ancestor to $opt_o\n";
 835                                $ancestor = $opt_o;
 836                        }
 837                        if (-f "$git_dir/refs/heads/$branch") {
 838                                print STDERR "Branch $branch already exists!\n";
 839                                $state=11;
 840                                next;
 841                        }
 842                        unless (open(H,"$git_dir/refs/heads/$ancestor")) {
 843                                print STDERR "Branch $ancestor does not exist!\n";
 844                                $ignorebranch{$branch} = 1;
 845                                $state=11;
 846                                next;
 847                        }
 848                        chomp(my $id = <H>);
 849                        close(H);
 850                        unless (open(H,"> $git_dir/refs/heads/$branch")) {
 851                                print STDERR "Could not create branch $branch: $!\n";
 852                                $ignorebranch{$branch} = 1;
 853                                $state=11;
 854                                next;
 855                        }
 856                        print H "$id\n"
 857                                or die "Could not write branch $branch: $!";
 858                        close(H)
 859                                or die "Could not write branch $branch: $!";
 860                }
 861                $last_branch = $branch if $branch ne $last_branch;
 862                $state = 9;
 863        } elsif ($state == 8) {
 864                $logmsg .= "$_\n";
 865        } elsif ($state == 9 and /^\s+(.+?):(INITIAL|\d+(?:\.\d+)+)->(\d+(?:\.\d+)+)\s*$/) {
 866#       VERSION:1.96->1.96.2.1
 867                my $init = ($2 eq "INITIAL");
 868                my $fn = $1;
 869                my $rev = $3;
 870                $fn =~ s#^/+##;
 871                if ($opt_S && $fn =~ m/$opt_S/) {
 872                    print "SKIPPING $fn v $rev\n";
 873                    push(@skipped, $fn);
 874                    next;
 875                }
 876                print "Fetching $fn   v $rev\n" if $opt_v;
 877                my ($tmpname, $size) = $cvs->file($fn,$rev);
 878                if ($size == -1) {
 879                        push(@old,$fn);
 880                        print "Drop $fn\n" if $opt_v;
 881                } else {
 882                        print "".($init ? "New" : "Update")." $fn: $size bytes\n" if $opt_v;
 883                        my $pid = open(my $F, '-|');
 884                        die $! unless defined $pid;
 885                        if (!$pid) {
 886                            exec("git-hash-object", "-w", $tmpname)
 887                                or die "Cannot create object: $!\n";
 888                        }
 889                        my $sha = <$F>;
 890                        chomp $sha;
 891                        close $F;
 892                        my $mode = pmode($cvs->{'mode'});
 893                        push(@new,[$mode, $sha, $fn]); # may be resurrected!
 894                }
 895                unlink($tmpname);
 896        } elsif ($state == 9 and /^\s+(.+?):\d+(?:\.\d+)+->(\d+(?:\.\d+)+)\(DEAD\)\s*$/) {
 897                my $fn = $1;
 898                $fn =~ s#^/+##;
 899                push(@old,$fn);
 900                print "Delete $fn\n" if $opt_v;
 901        } elsif ($state == 9 and /^\s*$/) {
 902                $state = 10;
 903        } elsif (($state == 9 or $state == 10) and /^-+$/) {
 904                $commitcount++;
 905                if ($opt_L && $commitcount > $opt_L) {
 906                        last;
 907                }
 908                commit();
 909                if (($commitcount & 1023) == 0) {
 910                        system("git repack -a -d");
 911                }
 912                $state = 1;
 913        } elsif ($state == 11 and /^-+$/) {
 914                $state = 1;
 915        } elsif (/^-+$/) { # end of unknown-line processing
 916                $state = 1;
 917        } elsif ($state != 11) { # ignore stuff when skipping
 918                print "* UNKNOWN LINE * $_\n";
 919        }
 920}
 921commit() if $branch and $state != 11;
 922
 923# The heuristic of repacking every 1024 commits can leave a
 924# lot of unpacked data.  If there is more than 1MB worth of
 925# not-packed objects, repack once more.
 926my $line = `git-count-objects`;
 927if ($line =~ /^(\d+) objects, (\d+) kilobytes$/) {
 928  my ($n_objects, $kb) = ($1, $2);
 929  1024 < $kb
 930    and system("git repack -a -d");
 931}
 932
 933foreach my $git_index (values %index) {
 934    if ($git_index ne '.git/index') {
 935        unlink($git_index);
 936    }
 937}
 938
 939if (defined $orig_git_index) {
 940        $ENV{GIT_INDEX_FILE} = $orig_git_index;
 941} else {
 942        delete $ENV{GIT_INDEX_FILE};
 943}
 944
 945# Now switch back to the branch we were in before all of this happened
 946if ($orig_branch) {
 947        print "DONE.\n" if $opt_v;
 948        if ($opt_i) {
 949                exit 0;
 950        }
 951        my $tip_at_end = `git-rev-parse --verify HEAD`;
 952        if ($tip_at_start ne $tip_at_end) {
 953                for ($tip_at_start, $tip_at_end) { chomp; }
 954                print "Fetched into the current branch.\n" if $opt_v;
 955                system(qw(git-read-tree -u -m),
 956                       $tip_at_start, $tip_at_end);
 957                die "Fast-forward update failed: $?\n" if $?;
 958        }
 959        else {
 960                system(qw(git-merge cvsimport HEAD), "refs/heads/$opt_o");
 961                die "Could not merge $opt_o into the current branch.\n" if $?;
 962        }
 963} else {
 964        $orig_branch = "master";
 965        print "DONE; creating $orig_branch branch\n" if $opt_v;
 966        system("git-update-ref", "refs/heads/master", "refs/heads/$opt_o")
 967                unless -f "$git_dir/refs/heads/master";
 968        system('git-update-ref', 'HEAD', "$orig_branch");
 969        unless ($opt_i) {
 970                system('git checkout');
 971                die "checkout failed: $?\n" if $?;
 972        }
 973}