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