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