git-cvsimport.perlon commit Yank writing-back support from gitfakemmap. (f48000f)
   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);
  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);
  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_s,$opt_m,$opt_M);
  33
  34sub usage() {
  35        print STDERR <<END;
  36Usage: ${\basename $0}     # fetch/update GIT from CVS
  37       [-o branch-for-HEAD] [-h] [-v] [-d CVSROOT]
  38       [-p opts-for-cvsps] [-C GIT_repository] [-z fuzz]
  39       [-i] [-k] [-u] [-s subst] [-m] [-M regex] [CVS_module]
  40END
  41        exit(1);
  42}
  43
  44getopts("hivmkuo:d:p:C:z:s:M:") or usage();
  45usage if $opt_h;
  46
  47@ARGV <= 1 or usage();
  48
  49if($opt_d) {
  50        $ENV{"CVSROOT"} = $opt_d;
  51} elsif(-f 'CVS/Root') {
  52        open my $f, '<', 'CVS/Root' or die 'Failed to open CVS/Root';
  53        $opt_d = <$f>;
  54        chomp $opt_d;
  55        close $f;
  56        $ENV{"CVSROOT"} = $opt_d;
  57} elsif($ENV{"CVSROOT"}) {
  58        $opt_d = $ENV{"CVSROOT"};
  59} else {
  60        die "CVSROOT needs to be set";
  61}
  62$opt_o ||= "origin";
  63$opt_s ||= "-";
  64my $git_tree = $opt_C;
  65$git_tree ||= ".";
  66
  67my $cvs_tree;
  68if ($#ARGV == 0) {
  69        $cvs_tree = $ARGV[0];
  70} elsif (-f 'CVS/Repository') {
  71        open my $f, '<', 'CVS/Repository' or 
  72            die 'Failed to open CVS/Repository';
  73        $cvs_tree = <$f>;
  74        chomp $cvs_tree;
  75        close $f;
  76} else {
  77        usage();
  78}
  79
  80our @mergerx = ();
  81if ($opt_m) {
  82        @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
  83}
  84if ($opt_M) {
  85        push (@mergerx, qr/$opt_M/);
  86}
  87
  88select(STDERR); $|=1; select(STDOUT);
  89
  90
  91package CVSconn;
  92# Basic CVS dialog.
  93# We're only interested in connecting and downloading, so ...
  94
  95use File::Spec;
  96use File::Temp qw(tempfile);
  97use POSIX qw(strftime dup2);
  98
  99sub new {
 100        my($what,$repo,$subdir) = @_;
 101        $what=ref($what) if ref($what);
 102
 103        my $self = {};
 104        $self->{'buffer'} = "";
 105        bless($self,$what);
 106
 107        $repo =~ s#/+$##;
 108        $self->{'fullrep'} = $repo;
 109        $self->conn();
 110
 111        $self->{'subdir'} = $subdir;
 112        $self->{'lines'} = undef;
 113
 114        return $self;
 115}
 116
 117sub conn {
 118        my $self = shift;
 119        my $repo = $self->{'fullrep'};
 120        if($repo =~ s/^:pserver:(?:(.*?)(?::(.*?))?@)?([^:\/]*)(?::(\d*))?//) {
 121                my($user,$pass,$serv,$port) = ($1,$2,$3,$4);
 122                $user="anonymous" unless defined $user;
 123                my $rr2 = "-";
 124                unless($port) {
 125                        $rr2 = ":pserver:$user\@$serv:$repo";
 126                        $port=2401;
 127                }
 128                my $rr = ":pserver:$user\@$serv:$port$repo";
 129
 130                unless($pass) {
 131                        open(H,$ENV{'HOME'}."/.cvspass") and do {
 132                                # :pserver:cvs@mea.tmt.tele.fi:/cvsroot/zmailer Ah<Z
 133                                while(<H>) {
 134                                        chomp;
 135                                        s/^\/\d+\s+//;
 136                                        my ($w,$p) = split(/\s/,$_,2);
 137                                        if($w eq $rr or $w eq $rr2) {
 138                                                $pass = $p;
 139                                                last;
 140                                        }
 141                                }
 142                        };
 143                }
 144                $pass="A" unless $pass;
 145
 146                my $s = IO::Socket::INET->new(PeerHost => $serv, PeerPort => $port);
 147                die "Socket to $serv: $!\n" unless defined $s;
 148                $s->write("BEGIN AUTH REQUEST\n$repo\n$user\n$pass\nEND AUTH REQUEST\n")
 149                        or die "Write to $serv: $!\n";
 150                $s->flush();
 151
 152                my $rep = <$s>;
 153
 154                if($rep ne "I LOVE YOU\n") {
 155                        $rep="<unknown>" unless $rep;
 156                        die "AuthReply: $rep\n";
 157                }
 158                $self->{'socketo'} = $s;
 159                $self->{'socketi'} = $s;
 160        } else { # local or ext: Fork off our own cvs server.
 161                my $pr = IO::Pipe->new();
 162                my $pw = IO::Pipe->new();
 163                my $pid = fork();
 164                die "Fork: $!\n" unless defined $pid;
 165                my $cvs = 'cvs';
 166                $cvs = $ENV{CVS_SERVER} if exists $ENV{CVS_SERVER};
 167                my $rsh = 'rsh';
 168                $rsh = $ENV{CVS_RSH} if exists $ENV{CVS_RSH};
 169
 170                my @cvs = ($cvs, 'server');
 171                my ($local, $user, $host);
 172                $local = $repo =~ s/:local://;
 173                if (!$local) {
 174                    $repo =~ s/:ext://;
 175                    $local = !($repo =~ s/^(?:([^\@:]+)\@)?([^:]+)://);
 176                    ($user, $host) = ($1, $2);
 177                }
 178                if (!$local) {
 179                    if ($user) {
 180                        unshift @cvs, $rsh, '-l', $user, $host;
 181                    } else {
 182                        unshift @cvs, $rsh, $host;
 183                    }
 184                }
 185
 186                unless($pid) {
 187                        $pr->writer();
 188                        $pw->reader();
 189                        dup2($pw->fileno(),0);
 190                        dup2($pr->fileno(),1);
 191                        $pr->close();
 192                        $pw->close();
 193                        exec(@cvs);
 194                }
 195                $pw->writer();
 196                $pr->reader();
 197                $self->{'socketo'} = $pw;
 198                $self->{'socketi'} = $pr;
 199        }
 200        $self->{'socketo'}->write("Root $repo\n");
 201
 202        # Trial and error says that this probably is the minimum set
 203        $self->{'socketo'}->write("Valid-responses ok error Valid-requests Mode M Mbinary E Checked-in Created Updated Merged Removed\n");
 204
 205        $self->{'socketo'}->write("valid-requests\n");
 206        $self->{'socketo'}->flush();
 207
 208        chomp(my $rep=$self->readline());
 209        if($rep !~ s/^Valid-requests\s*//) {
 210                $rep="<unknown>" unless $rep;
 211                die "Expected Valid-requests from server, but got: $rep\n";
 212        }
 213        chomp(my $res=$self->readline());
 214        die "validReply: $res\n" if $res ne "ok";
 215
 216        $self->{'socketo'}->write("UseUnchanged\n") if $rep =~ /\bUseUnchanged\b/;
 217        $self->{'repo'} = $repo;
 218}
 219
 220sub readline {
 221        my($self) = @_;
 222        return $self->{'socketi'}->getline();
 223}
 224
 225sub _file {
 226        # Request a file with a given revision.
 227        # Trial and error says this is a good way to do it. :-/
 228        my($self,$fn,$rev) = @_;
 229        $self->{'socketo'}->write("Argument -N\n") or return undef;
 230        $self->{'socketo'}->write("Argument -P\n") or return undef;
 231        # -kk: Linus' version doesn't use it - defaults to off
 232        if ($opt_k) {
 233            $self->{'socketo'}->write("Argument -kk\n") or return undef;
 234        }
 235        $self->{'socketo'}->write("Argument -r\n") or return undef;
 236        $self->{'socketo'}->write("Argument $rev\n") or return undef;
 237        $self->{'socketo'}->write("Argument --\n") or return undef;
 238        $self->{'socketo'}->write("Argument $self->{'subdir'}/$fn\n") or return undef;
 239        $self->{'socketo'}->write("Directory .\n") or return undef;
 240        $self->{'socketo'}->write("$self->{'repo'}\n") or return undef;
 241        # $self->{'socketo'}->write("Sticky T1.0\n") or return undef;
 242        $self->{'socketo'}->write("co\n") or return undef;
 243        $self->{'socketo'}->flush() or return undef;
 244        $self->{'lines'} = 0;
 245        return 1;
 246}
 247sub _line {
 248        # Read a line from the server.
 249        # ... except that 'line' may be an entire file. ;-)
 250        my($self, $fh) = @_;
 251        die "Not in lines" unless defined $self->{'lines'};
 252
 253        my $line;
 254        my $res=0;
 255        while(defined($line = $self->readline())) {
 256                # M U gnupg-cvs-rep/AUTHORS
 257                # Updated gnupg-cvs-rep/
 258                # /daten/src/rsync/gnupg-cvs-rep/AUTHORS
 259                # /AUTHORS/1.1///T1.1
 260                # u=rw,g=rw,o=rw
 261                # 0
 262                # ok
 263
 264                if($line =~ s/^(?:Created|Updated) //) {
 265                        $line = $self->readline(); # path
 266                        $line = $self->readline(); # Entries line
 267                        my $mode = $self->readline(); chomp $mode;
 268                        $self->{'mode'} = $mode;
 269                        defined (my $cnt = $self->readline())
 270                                or die "EOF from server after 'Changed'\n";
 271                        chomp $cnt;
 272                        die "Duh: Filesize $cnt" if $cnt !~ /^\d+$/;
 273                        $line="";
 274                        $res=0;
 275                        while($cnt) {
 276                                my $buf;
 277                                my $num = $self->{'socketi'}->read($buf,$cnt);
 278                                die "Server: Filesize $cnt: $num: $!\n" if not defined $num or $num<=0;
 279                                print $fh $buf;
 280                                $res += $num;
 281                                $cnt -= $num;
 282                        }
 283                } elsif($line =~ s/^ //) {
 284                        print $fh $line;
 285                        $res += length($line);
 286                } elsif($line =~ /^M\b/) {
 287                        # output, do nothing
 288                } elsif($line =~ /^Mbinary\b/) {
 289                        my $cnt;
 290                        die "EOF from server after 'Mbinary'" unless defined ($cnt = $self->readline());
 291                        chomp $cnt;
 292                        die "Duh: Mbinary $cnt" if $cnt !~ /^\d+$/ or $cnt<1;
 293                        $line="";
 294                        while($cnt) {
 295                                my $buf;
 296                                my $num = $self->{'socketi'}->read($buf,$cnt);
 297                                die "S: Mbinary $cnt: $num: $!\n" if not defined $num or $num<=0;
 298                                print $fh $buf;
 299                                $res += $num;
 300                                $cnt -= $num;
 301                        }
 302                } else {
 303                        chomp $line;
 304                        if($line eq "ok") {
 305                                # print STDERR "S: ok (".length($res).")\n";
 306                                return $res;
 307                        } elsif($line =~ s/^E //) {
 308                                # print STDERR "S: $line\n";
 309                        } elsif($line =~ /^Remove-entry /i) {
 310                                $line = $self->readline(); # filename
 311                                $line = $self->readline(); # OK
 312                                chomp $line;
 313                                die "Unknown: $line" if $line ne "ok";
 314                                return -1;
 315                        } else {
 316                                die "Unknown: $line\n";
 317                        }
 318                }
 319        }
 320}
 321sub file {
 322        my($self,$fn,$rev) = @_;
 323        my $res;
 324
 325        my ($fh, $name) = tempfile('gitcvs.XXXXXX', 
 326                    DIR => File::Spec->tmpdir(), UNLINK => 1);
 327
 328        $self->_file($fn,$rev) and $res = $self->_line($fh);
 329
 330        if (!defined $res) {
 331            # retry
 332            $self->conn();
 333            $self->_file($fn,$rev)
 334                    or die "No file command send\n";
 335            $res = $self->_line($fh);
 336            die "No input: $fn $rev\n" unless defined $res;
 337        }
 338        close ($fh);
 339
 340        return ($name, $res);
 341}
 342
 343
 344package main;
 345
 346my $cvs = CVSconn->new($opt_d, $cvs_tree);
 347
 348
 349sub pdate($) {
 350        my($d) = @_;
 351        m#(\d{2,4})/(\d\d)/(\d\d)\s(\d\d):(\d\d)(?::(\d\d))?#
 352                or die "Unparseable date: $d\n";
 353        my $y=$1; $y-=1900 if $y>1900;
 354        return timegm($6||0,$5,$4,$3,$2-1,$y);
 355}
 356
 357sub pmode($) {
 358        my($mode) = @_;
 359        my $m = 0;
 360        my $mm = 0;
 361        my $um = 0;
 362        for my $x(split(//,$mode)) {
 363                if($x eq ",") {
 364                        $m |= $mm&$um;
 365                        $mm = 0;
 366                        $um = 0;
 367                } elsif($x eq "u") { $um |= 0700;
 368                } elsif($x eq "g") { $um |= 0070;
 369                } elsif($x eq "o") { $um |= 0007;
 370                } elsif($x eq "r") { $mm |= 0444;
 371                } elsif($x eq "w") { $mm |= 0222;
 372                } elsif($x eq "x") { $mm |= 0111;
 373                } elsif($x eq "=") { # do nothing
 374                } else { die "Unknown mode: $mode\n";
 375                }
 376        }
 377        $m |= $mm&$um;
 378        return $m;
 379}
 380
 381sub getwd() {
 382        my $pwd = `pwd`;
 383        chomp $pwd;
 384        return $pwd;
 385}
 386
 387
 388sub get_headref($$) {
 389    my $name    = shift;
 390    my $git_dir = shift; 
 391    my $sha;
 392    
 393    if (open(C,"$git_dir/refs/heads/$name")) {
 394        chomp($sha = <C>);
 395        close(C);
 396        length($sha) == 40
 397            or die "Cannot get head id for $name ($sha): $!\n";
 398    }
 399    return $sha;
 400}
 401
 402
 403-d $git_tree
 404        or mkdir($git_tree,0777)
 405        or die "Could not create $git_tree: $!";
 406chdir($git_tree);
 407
 408my $last_branch = "";
 409my $orig_branch = "";
 410my $forward_master = 0;
 411my %branch_date;
 412
 413my $git_dir = $ENV{"GIT_DIR"} || ".git";
 414$git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
 415$ENV{"GIT_DIR"} = $git_dir;
 416my $orig_git_index;
 417$orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
 418my ($git_ih, $git_index) = tempfile('gitXXXXXX', SUFFIX => '.idx',
 419                                    DIR => File::Spec->tmpdir());
 420close ($git_ih);
 421$ENV{GIT_INDEX_FILE} = $git_index;
 422unless(-d $git_dir) {
 423        system("git-init-db");
 424        die "Cannot init the GIT db at $git_tree: $?\n" if $?;
 425        system("git-read-tree");
 426        die "Cannot init an empty tree: $?\n" if $?;
 427
 428        $last_branch = $opt_o;
 429        $orig_branch = "";
 430} else {
 431        -f "$git_dir/refs/heads/$opt_o"
 432                or die "Branch '$opt_o' does not exist.\n".
 433                       "Either use the correct '-o branch' option,\n".
 434                       "or import to a new repository.\n";
 435
 436        $last_branch = basename(readlink("$git_dir/HEAD"));
 437        unless($last_branch) {
 438                warn "Cannot read the last branch name: $! -- assuming 'master'\n";
 439                $last_branch = "master";
 440        }
 441        $orig_branch = $last_branch;
 442        if (-f "$git_dir/CVS2GIT_HEAD") {
 443                die <<EOM;
 444CVS2GIT_HEAD exists.
 445Make sure your working directory corresponds to HEAD and remove CVS2GIT_HEAD.
 446You may need to run
 447
 448    git-read-tree -m -u CVS2GIT_HEAD HEAD
 449EOM
 450        }
 451        system('cp', "$git_dir/HEAD", "$git_dir/CVS2GIT_HEAD");
 452
 453        $forward_master =
 454            $opt_o ne 'master' && -f "$git_dir/refs/heads/master" &&
 455            system('cmp', '-s', "$git_dir/refs/heads/master", 
 456                                "$git_dir/refs/heads/$opt_o") == 0;
 457
 458        # populate index
 459        system('git-read-tree', $last_branch);
 460        die "read-tree failed: $?\n" if $?;
 461
 462        # Get the last import timestamps
 463        opendir(D,"$git_dir/refs/heads");
 464        while(defined(my $head = readdir(D))) {
 465                next if $head =~ /^\./;
 466                open(F,"$git_dir/refs/heads/$head")
 467                        or die "Bad head branch: $head: $!\n";
 468                chomp(my $ftag = <F>);
 469                close(F);
 470                open(F,"git-cat-file commit $ftag |");
 471                while(<F>) {
 472                        next unless /^author\s.*\s(\d+)\s[-+]\d{4}$/;
 473                        $branch_date{$head} = $1;
 474                        last;
 475                }
 476                close(F);
 477        }
 478        closedir(D);
 479}
 480
 481-d $git_dir
 482        or die "Could not create git subdir ($git_dir).\n";
 483
 484my $pid = open(CVS,"-|");
 485die "Cannot fork: $!\n" unless defined $pid;
 486unless($pid) {
 487        my @opt;
 488        @opt = split(/,/,$opt_p) if defined $opt_p;
 489        unshift @opt, '-z', $opt_z if defined $opt_z;
 490        exec("cvsps",@opt,"-u","-A","--cvs-direct",'--root',$opt_d,$cvs_tree);
 491        die "Could not start cvsps: $!\n";
 492}
 493
 494
 495## cvsps output:
 496#---------------------
 497#PatchSet 314
 498#Date: 1999/09/18 13:03:59
 499#Author: wkoch
 500#Branch: STABLE-BRANCH-1-0
 501#Ancestor branch: HEAD
 502#Tag: (none)
 503#Log:
 504#    See ChangeLog: Sat Sep 18 13:03:28 CEST 1999  Werner Koch
 505#Members:
 506#       README:1.57->1.57.2.1
 507#       VERSION:1.96->1.96.2.1
 508#
 509#---------------------
 510
 511my $state = 0;
 512
 513my($patchset,$date,$author_name,$author_email,$branch,$ancestor,$tag,$logmsg);
 514my(@old,@new);
 515my $commit = sub {
 516        my $pid;
 517        while(@old) {
 518                my @o2;
 519                if(@old > 55) {
 520                        @o2 = splice(@old,0,50);
 521                } else {
 522                        @o2 = @old;
 523                        @old = ();
 524                }
 525                system("git-update-index","--force-remove","--",@o2);
 526                die "Cannot remove files: $?\n" if $?;
 527        }
 528        while(@new) {
 529                my @n2;
 530                if(@new > 12) {
 531                        @n2 = splice(@new,0,10);
 532                } else {
 533                        @n2 = @new;
 534                        @new = ();
 535                }
 536                system("git-update-index","--add",
 537                        (map { ('--cacheinfo', @$_) } @n2));
 538                die "Cannot add files: $?\n" if $?;
 539        }
 540
 541        $pid = open(C,"-|");
 542        die "Cannot fork: $!" unless defined $pid;
 543        unless($pid) {
 544                exec("git-write-tree");
 545                die "Cannot exec git-write-tree: $!\n";
 546        }
 547        chomp(my $tree = <C>);
 548        length($tree) == 40
 549                or die "Cannot get tree id ($tree): $!\n";
 550        close(C)
 551                or die "Error running git-write-tree: $?\n";
 552        print "Tree ID $tree\n" if $opt_v;
 553
 554        my $parent = "";
 555        if(open(C,"$git_dir/refs/heads/$last_branch")) {
 556                chomp($parent = <C>);
 557                close(C);
 558                length($parent) == 40
 559                        or die "Cannot get parent id ($parent): $!\n";
 560                print "Parent ID $parent\n" if $opt_v;
 561        }
 562
 563        my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
 564        my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
 565        $pid = fork();
 566        die "Fork: $!\n" unless defined $pid;
 567        unless($pid) {
 568                $pr->writer();
 569                $pw->reader();
 570                dup2($pw->fileno(),0);
 571                dup2($pr->fileno(),1);
 572                $pr->close();
 573                $pw->close();
 574
 575                my @par = ();
 576                @par = ("-p",$parent) if $parent;
 577
 578                # loose detection of merges
 579                # based on the commit msg
 580                foreach my $rx (@mergerx) {
 581                        if ($logmsg =~ $rx) {
 582                                my $mparent = $1;
 583                                if ($mparent eq 'HEAD') { $mparent = $opt_o };
 584                                if ( -e "$git_dir/refs/heads/$mparent") {
 585                                        $mparent = get_headref($mparent, $git_dir);
 586                                        push @par, '-p', $mparent;
 587                                        # printing here breaks import # 
 588                                        # # print "Merge parent branch: $mparent\n" if $opt_v;
 589                                }
 590                        } 
 591                }
 592
 593                exec("env",
 594                        "GIT_AUTHOR_NAME=$author_name",
 595                        "GIT_AUTHOR_EMAIL=$author_email",
 596                        "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
 597                        "GIT_COMMITTER_NAME=$author_name",
 598                        "GIT_COMMITTER_EMAIL=$author_email",
 599                        "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
 600                        "git-commit-tree", $tree,@par);
 601                die "Cannot exec git-commit-tree: $!\n";
 602        }
 603        $pw->writer();
 604        $pr->reader();
 605
 606        # compatibility with git2cvs
 607        substr($logmsg,32767) = "" if length($logmsg) > 32767;
 608        $logmsg =~ s/[\s\n]+\z//;
 609
 610        print $pw "$logmsg\n"
 611                or die "Error writing to git-commit-tree: $!\n";
 612        $pw->close();
 613
 614        print "Committed patch $patchset ($branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
 615        chomp(my $cid = <$pr>);
 616        length($cid) == 40
 617                or die "Cannot get commit id ($cid): $!\n";
 618        print "Commit ID $cid\n" if $opt_v;
 619        $pr->close();
 620
 621        waitpid($pid,0);
 622        die "Error running git-commit-tree: $?\n" if $?;
 623
 624        open(C,">$git_dir/refs/heads/$branch")
 625                or die "Cannot open branch $branch for update: $!\n";
 626        print C "$cid\n"
 627                or die "Cannot write branch $branch for update: $!\n";
 628        close(C)
 629                or die "Cannot write branch $branch for update: $!\n";
 630
 631        if($tag) {
 632                my($in, $out) = ('','');
 633                my($xtag) = $tag;
 634                $xtag =~ s/\s+\*\*.*$//; # Remove stuff like ** INVALID ** and ** FUNKY **
 635                $xtag =~ tr/_/\./ if ( $opt_u );
 636                
 637                my $pid = open2($in, $out, 'git-mktag');
 638                print $out "object $cid\n".
 639                    "type commit\n".
 640                    "tag $xtag\n".
 641                    "tagger $author_name <$author_email>\n"
 642                    or die "Cannot create tag object $xtag: $!\n";
 643                close($out)
 644                    or die "Cannot create tag object $xtag: $!\n";
 645
 646                my $tagobj = <$in>;
 647                chomp $tagobj;
 648
 649                if ( !close($in) or waitpid($pid, 0) != $pid or
 650                     $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
 651                    die "Cannot create tag object $xtag: $!\n";
 652                }
 653                
 654
 655                open(C,">$git_dir/refs/tags/$xtag")
 656                        or die "Cannot create tag $xtag: $!\n";
 657                print C "$tagobj\n"
 658                        or die "Cannot write tag $xtag: $!\n";
 659                close(C)
 660                        or die "Cannot write tag $xtag: $!\n";
 661
 662                print "Created tag '$xtag' on '$branch'\n" if $opt_v;
 663        }
 664};
 665
 666while(<CVS>) {
 667        chomp;
 668        if($state == 0 and /^-+$/) {
 669                $state = 1;
 670        } elsif($state == 0) {
 671                $state = 1;
 672                redo;
 673        } elsif(($state==0 or $state==1) and s/^PatchSet\s+//) {
 674                $patchset = 0+$_;
 675                $state=2;
 676        } elsif($state == 2 and s/^Date:\s+//) {
 677                $date = pdate($_);
 678                unless($date) {
 679                        print STDERR "Could not parse date: $_\n";
 680                        $state=0;
 681                        next;
 682                }
 683                $state=3;
 684        } elsif($state == 3 and s/^Author:\s+//) {
 685                s/\s+$//;
 686                if (/^(.*?)\s+<(.*)>/) {
 687                    ($author_name, $author_email) = ($1, $2);
 688                } else {
 689                    $author_name = $author_email = $_;
 690                }
 691                $state = 4;
 692        } elsif($state == 4 and s/^Branch:\s+//) {
 693                s/\s+$//;
 694                s/[\/]/$opt_s/g;
 695                $branch = $_;
 696                $state = 5;
 697        } elsif($state == 5 and s/^Ancestor branch:\s+//) {
 698                s/\s+$//;
 699                $ancestor = $_;
 700                $ancestor = $opt_o if $ancestor eq "HEAD";
 701                $state = 6;
 702        } elsif($state == 5) {
 703                $ancestor = undef;
 704                $state = 6;
 705                redo;
 706        } elsif($state == 6 and s/^Tag:\s+//) {
 707                s/\s+$//;
 708                if($_ eq "(none)") {
 709                        $tag = undef;
 710                } else {
 711                        $tag = $_;
 712                }
 713                $state = 7;
 714        } elsif($state == 7 and /^Log:/) {
 715                $logmsg = "";
 716                $state = 8;
 717        } elsif($state == 8 and /^Members:/) {
 718                $branch = $opt_o if $branch eq "HEAD";
 719                if(defined $branch_date{$branch} and $branch_date{$branch} >= $date) {
 720                        # skip
 721                        print "skip patchset $patchset: $date before $branch_date{$branch}\n" if $opt_v;
 722                        $state = 11;
 723                        next;
 724                }
 725                if($ancestor) {
 726                        if(-f "$git_dir/refs/heads/$branch") {
 727                                print STDERR "Branch $branch already exists!\n";
 728                                $state=11;
 729                                next;
 730                        }
 731                        unless(open(H,"$git_dir/refs/heads/$ancestor")) {
 732                                print STDERR "Branch $ancestor does not exist!\n";
 733                                $state=11;
 734                                next;
 735                        }
 736                        chomp(my $id = <H>);
 737                        close(H);
 738                        unless(open(H,"> $git_dir/refs/heads/$branch")) {
 739                                print STDERR "Could not create branch $branch: $!\n";
 740                                $state=11;
 741                                next;
 742                        }
 743                        print H "$id\n"
 744                                or die "Could not write branch $branch: $!";
 745                        close(H)
 746                                or die "Could not write branch $branch: $!";
 747                }
 748                if(($ancestor || $branch) ne $last_branch) {
 749                        print "Switching from $last_branch to $branch\n" if $opt_v;
 750                        system("git-read-tree", $branch);
 751                        die "read-tree failed: $?\n" if $?;
 752                }
 753                $last_branch = $branch if $branch ne $last_branch;
 754                $state = 9;
 755        } elsif($state == 8) {
 756                $logmsg .= "$_\n";
 757        } elsif($state == 9 and /^\s+(.+?):(INITIAL|\d+(?:\.\d+)+)->(\d+(?:\.\d+)+)\s*$/) {
 758#       VERSION:1.96->1.96.2.1
 759                my $init = ($2 eq "INITIAL");
 760                my $fn = $1;
 761                my $rev = $3;
 762                $fn =~ s#^/+##;
 763                my ($tmpname, $size) = $cvs->file($fn,$rev);
 764                if($size == -1) {
 765                        push(@old,$fn);
 766                        print "Drop $fn\n" if $opt_v;
 767                } else {
 768                        print "".($init ? "New" : "Update")." $fn: $size bytes\n" if $opt_v;
 769                        open my $F, '-|', "git-hash-object -w $tmpname"
 770                                or die "Cannot create object: $!\n";
 771                        my $sha = <$F>;
 772                        chomp $sha;
 773                        close $F;
 774                        my $mode = pmode($cvs->{'mode'});
 775                        push(@new,[$mode, $sha, $fn]); # may be resurrected!
 776                }
 777                unlink($tmpname);
 778        } elsif($state == 9 and /^\s+(.+?):\d+(?:\.\d+)+->(\d+(?:\.\d+)+)\(DEAD\)\s*$/) {
 779                my $fn = $1;
 780                $fn =~ s#^/+##;
 781                push(@old,$fn);
 782                print "Delete $fn\n" if $opt_v;
 783        } elsif($state == 9 and /^\s*$/) {
 784                $state = 10;
 785        } elsif(($state == 9 or $state == 10) and /^-+$/) {
 786                &$commit();
 787                $state = 1;
 788        } elsif($state == 11 and /^-+$/) {
 789                $state = 1;
 790        } elsif(/^-+$/) { # end of unknown-line processing
 791                $state = 1;
 792        } elsif($state != 11) { # ignore stuff when skipping
 793                print "* UNKNOWN LINE * $_\n";
 794        }
 795}
 796&$commit() if $branch and $state != 11;
 797
 798unlink($git_index);
 799
 800if (defined $orig_git_index) {
 801        $ENV{GIT_INDEX_FILE} = $orig_git_index;
 802} else {
 803        delete $ENV{GIT_INDEX_FILE};
 804}
 805
 806# Now switch back to the branch we were in before all of this happened
 807if($orig_branch) {
 808        print "DONE\n" if $opt_v;
 809        system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
 810                if $forward_master;
 811        unless ($opt_i) {
 812                system('git-read-tree', '-m', '-u', 'CVS2GIT_HEAD', 'HEAD');
 813                die "read-tree failed: $?\n" if $?;
 814        }
 815} else {
 816        $orig_branch = "master";
 817        print "DONE; creating $orig_branch branch\n" if $opt_v;
 818        system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
 819                unless -f "$git_dir/refs/heads/master";
 820        unlink("$git_dir/HEAD");
 821        symlink("refs/heads/$orig_branch","$git_dir/HEAD");
 822        unless ($opt_i) {
 823                system('git checkout');
 824                die "checkout failed: $?\n" if $?;
 825        }
 826}
 827unlink("$git_dir/CVS2GIT_HEAD");