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