]> asedeno.scripts.mit.edu Git - git.git/blob - git-cvsimport.perl
cvsimport: setup indexes correctly for ancestors and incremental imports
[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 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 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 = $self->_fetchfile($fh, $cnt);
319                 } elsif($line =~ s/^ //) {
320                         print $fh $line;
321                         $res += length($line);
322                 } elsif($line =~ /^M\b/) {
323                         # output, do nothing
324                 } elsif($line =~ /^Mbinary\b/) {
325                         my $cnt;
326                         die "EOF from server after 'Mbinary'" unless defined ($cnt = $self->readline());
327                         chomp $cnt;
328                         die "Duh: Mbinary $cnt" if $cnt !~ /^\d+$/ or $cnt<1;
329                         $line="";
330                         $res += $self->_fetchfile($fh, $cnt);
331                 } else {
332                         chomp $line;
333                         if($line eq "ok") {
334                                 # print STDERR "S: ok (".length($res).")\n";
335                                 return $res;
336                         } elsif($line =~ s/^E //) {
337                                 # print STDERR "S: $line\n";
338                         } elsif($line =~ /^(Remove-entry|Removed) /i) {
339                                 $line = $self->readline(); # filename
340                                 $line = $self->readline(); # OK
341                                 chomp $line;
342                                 die "Unknown: $line" if $line ne "ok";
343                                 return -1;
344                         } else {
345                                 die "Unknown: $line\n";
346                         }
347                 }
348         }
349         return undef;
350 }
351 sub file {
352         my($self,$fn,$rev) = @_;
353         my $res;
354
355         my ($fh, $name) = tempfile('gitcvs.XXXXXX', 
356                     DIR => File::Spec->tmpdir(), UNLINK => 1);
357
358         $self->_file($fn,$rev) and $res = $self->_line($fh);
359
360         if (!defined $res) {
361             print STDERR "Server has gone away while fetching $fn $rev, retrying...\n";
362             truncate $fh, 0;
363             $self->conn();
364             $self->_file($fn,$rev) or die "No file command send";
365             $res = $self->_line($fh);
366             die "Retry failed" unless defined $res;
367         }
368         close ($fh);
369
370         return ($name, $res);
371 }
372 sub _fetchfile {
373         my ($self, $fh, $cnt) = @_;
374         my $res = 0;
375         my $bufsize = 1024 * 1024;
376         while($cnt) {
377             if ($bufsize > $cnt) {
378                 $bufsize = $cnt;
379             }
380             my $buf;
381             my $num = $self->{'socketi'}->read($buf,$bufsize);
382             die "Server: Filesize $cnt: $num: $!\n" if not defined $num or $num<=0;
383             print $fh $buf;
384             $res += $num;
385             $cnt -= $num;
386         }
387         return $res;
388 }
389
390
391 package main;
392
393 my $cvs = CVSconn->new($opt_d, $cvs_tree);
394
395
396 sub pdate($) {
397         my($d) = @_;
398         m#(\d{2,4})/(\d\d)/(\d\d)\s(\d\d):(\d\d)(?::(\d\d))?#
399                 or die "Unparseable date: $d\n";
400         my $y=$1; $y-=1900 if $y>1900;
401         return timegm($6||0,$5,$4,$3,$2-1,$y);
402 }
403
404 sub pmode($) {
405         my($mode) = @_;
406         my $m = 0;
407         my $mm = 0;
408         my $um = 0;
409         for my $x(split(//,$mode)) {
410                 if($x eq ",") {
411                         $m |= $mm&$um;
412                         $mm = 0;
413                         $um = 0;
414                 } elsif($x eq "u") { $um |= 0700;
415                 } elsif($x eq "g") { $um |= 0070;
416                 } elsif($x eq "o") { $um |= 0007;
417                 } elsif($x eq "r") { $mm |= 0444;
418                 } elsif($x eq "w") { $mm |= 0222;
419                 } elsif($x eq "x") { $mm |= 0111;
420                 } elsif($x eq "=") { # do nothing
421                 } else { die "Unknown mode: $mode\n";
422                 }
423         }
424         $m |= $mm&$um;
425         return $m;
426 }
427
428 sub getwd() {
429         my $pwd = `pwd`;
430         chomp $pwd;
431         return $pwd;
432 }
433
434 sub is_sha1 {
435         my $s = shift;
436         return $s =~ /^[a-f0-9]{40}$/;
437 }
438
439 sub get_headref ($$) {
440     my $name    = shift;
441     my $git_dir = shift; 
442     
443     my $f = "$git_dir/refs/heads/$name";
444     if(open(my $fh, $f)) {
445             chomp(my $r = <$fh>);
446             is_sha1($r) or die "Cannot get head id for $name ($r): $!";
447             return $r;
448     }
449     die "unable to open $f: $!" unless $! == POSIX::ENOENT;
450     return undef;
451 }
452
453 -d $git_tree
454         or mkdir($git_tree,0777)
455         or die "Could not create $git_tree: $!";
456 chdir($git_tree);
457
458 my $last_branch = "";
459 my $orig_branch = "";
460 my %branch_date;
461 my $tip_at_start = undef;
462
463 my $git_dir = $ENV{"GIT_DIR"} || ".git";
464 $git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
465 $ENV{"GIT_DIR"} = $git_dir;
466 my $orig_git_index;
467 $orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
468
469 my %index; # holds filenames of one index per branch
470 $index{$opt_o} = tmpnam();
471
472 $ENV{GIT_INDEX_FILE} = $index{$opt_o};
473 unless(-d $git_dir) {
474         system("git-init-db");
475         die "Cannot init the GIT db at $git_tree: $?\n" if $?;
476         system("git-read-tree");
477         die "Cannot init an empty tree: $?\n" if $?;
478
479         $last_branch = $opt_o;
480         $orig_branch = "";
481 } else {
482         -f "$git_dir/refs/heads/$opt_o"
483                 or die "Branch '$opt_o' does not exist.\n".
484                        "Either use the correct '-o branch' option,\n".
485                        "or import to a new repository.\n";
486
487         open(F, "git-symbolic-ref HEAD |") or
488                 die "Cannot run git-symbolic-ref: $!\n";
489         chomp ($last_branch = <F>);
490         $last_branch = basename($last_branch);
491         close(F);
492         unless($last_branch) {
493                 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
494                 $last_branch = "master";
495         }
496         $orig_branch = $last_branch;
497         $tip_at_start = `git-rev-parse --verify HEAD`;
498
499         # populate index
500         unless ($index{$last_branch}) {
501             $index{$last_branch} = tmpnam();
502         }
503         $ENV{GIT_INDEX_FILE} = $index{$last_branch};
504         system('git-read-tree', $last_branch);
505         die "read-tree failed: $?\n" if $?;
506
507         # Get the last import timestamps
508         opendir(D,"$git_dir/refs/heads");
509         while(defined(my $head = readdir(D))) {
510                 next if $head =~ /^\./;
511                 open(F,"$git_dir/refs/heads/$head")
512                         or die "Bad head branch: $head: $!\n";
513                 chomp(my $ftag = <F>);
514                 close(F);
515                 open(F,"git-cat-file commit $ftag |");
516                 while(<F>) {
517                         next unless /^author\s.*\s(\d+)\s[-+]\d{4}$/;
518                         $branch_date{$head} = $1;
519                         last;
520                 }
521                 close(F);
522         }
523         closedir(D);
524 }
525
526 -d $git_dir
527         or die "Could not create git subdir ($git_dir).\n";
528
529 # now we read (and possibly save) author-info as well
530 -f "$git_dir/cvs-authors" and
531   read_author_info("$git_dir/cvs-authors");
532 if ($opt_A) {
533         read_author_info($opt_A);
534         write_author_info("$git_dir/cvs-authors");
535 }
536
537
538 #
539 # run cvsps into a file unless we are getting
540 # it passed as a file via $opt_P
541 #
542 unless ($opt_P) {
543         print "Running cvsps...\n" if $opt_v;
544         my $pid = open(CVSPS,"-|");
545         die "Cannot fork: $!\n" unless defined $pid;
546         unless($pid) {
547                 my @opt;
548                 @opt = split(/,/,$opt_p) if defined $opt_p;
549                 unshift @opt, '-z', $opt_z if defined $opt_z;
550                 unshift @opt, '-q'         unless defined $opt_v;
551                 unless (defined($opt_p) && $opt_p =~ m/--no-cvs-direct/) {
552                         push @opt, '--cvs-direct';
553                 }
554                 exec("cvsps","--norc",@opt,"-u","-A",'--root',$opt_d,$cvs_tree);
555                 die "Could not start cvsps: $!\n";
556         }
557         my ($cvspsfh, $cvspsfile) = tempfile('gitXXXXXX', SUFFIX => '.cvsps',
558                                              DIR => File::Spec->tmpdir());
559         while (<CVSPS>) {
560             print $cvspsfh $_;
561         }
562         close CVSPS;
563         close $cvspsfh;
564         $opt_P = $cvspsfile;
565 }
566
567
568 open(CVS, "<$opt_P") or die $!;
569
570 ## cvsps output:
571 #---------------------
572 #PatchSet 314
573 #Date: 1999/09/18 13:03:59
574 #Author: wkoch
575 #Branch: STABLE-BRANCH-1-0
576 #Ancestor branch: HEAD
577 #Tag: (none)
578 #Log:
579 #    See ChangeLog: Sat Sep 18 13:03:28 CEST 1999  Werner Koch
580 #Members:
581 #       README:1.57->1.57.2.1
582 #       VERSION:1.96->1.96.2.1
583 #
584 #---------------------
585
586 my $state = 0;
587
588 sub update_index (\@\@) {
589         my $old = shift;
590         my $new = shift;
591         open(my $fh, '|-', qw(git-update-index -z --index-info))
592                 or die "unable to open git-update-index: $!";
593         print $fh
594                 (map { "0 0000000000000000000000000000000000000000\t$_\0" }
595                         @$old),
596                 (map { '100' . sprintf('%o', $_->[0]) . " $_->[1]\t$_->[2]\0" }
597                         @$new)
598                 or die "unable to write to git-update-index: $!";
599         close $fh
600                 or die "unable to write to git-update-index: $!";
601         $? and die "git-update-index reported error: $?";
602 }
603
604 sub write_tree () {
605         open(my $fh, '-|', qw(git-write-tree))
606                 or die "unable to open git-write-tree: $!";
607         chomp(my $tree = <$fh>);
608         is_sha1($tree)
609                 or die "Cannot get tree id ($tree): $!";
610         close($fh)
611                 or die "Error running git-write-tree: $?\n";
612         print "Tree ID $tree\n" if $opt_v;
613         return $tree;
614 }
615
616 my($patchset,$date,$author_name,$author_email,$branch,$ancestor,$tag,$logmsg);
617 my(@old,@new,@skipped,%ignorebranch);
618
619 # commits that cvsps cannot place anywhere...
620 $ignorebranch{'#CVSPS_NO_BRANCH'} = 1;
621
622 sub commit {
623         update_index(@old, @new);
624         @old = @new = ();
625         my $tree = write_tree();
626         my $parent = get_headref($last_branch, $git_dir);
627         print "Parent ID " . ($parent ? $parent : "(empty)") . "\n" if $opt_v;
628
629         my @commit_args;
630         push @commit_args, ("-p", $parent) if $parent;
631
632         # loose detection of merges
633         # based on the commit msg
634         foreach my $rx (@mergerx) {
635                 next unless $logmsg =~ $rx && $1;
636                 my $mparent = $1 eq 'HEAD' ? $opt_o : $1;
637                 if(my $sha1 = get_headref($mparent, $git_dir)) {
638                         push @commit_args, '-p', $mparent;
639                         print "Merge parent branch: $mparent\n" if $opt_v;
640                 }
641         }
642
643         my $commit_date = strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date));
644         $ENV{GIT_AUTHOR_NAME} = $author_name;
645         $ENV{GIT_AUTHOR_EMAIL} = $author_email;
646         $ENV{GIT_AUTHOR_DATE} = $commit_date;
647         $ENV{GIT_COMMITTER_NAME} = $author_name;
648         $ENV{GIT_COMMITTER_EMAIL} = $author_email;
649         $ENV{GIT_COMMITTER_DATE} = $commit_date;
650         my $pid = open2(my $commit_read, my $commit_write,
651                 'git-commit-tree', $tree, @commit_args);
652
653         # compatibility with git2cvs
654         substr($logmsg,32767) = "" if length($logmsg) > 32767;
655         $logmsg =~ s/[\s\n]+\z//;
656
657         if (@skipped) {
658             $logmsg .= "\n\n\nSKIPPED:\n\t";
659             $logmsg .= join("\n\t", @skipped) . "\n";
660             @skipped = ();
661         }
662
663         print($commit_write "$logmsg\n") && close($commit_write)
664                 or die "Error writing to git-commit-tree: $!\n";
665
666         print "Committed patch $patchset ($branch $commit_date)\n" if $opt_v;
667         chomp(my $cid = <$commit_read>);
668         is_sha1($cid) or die "Cannot get commit id ($cid): $!\n";
669         print "Commit ID $cid\n" if $opt_v;
670         close($commit_read);
671
672         waitpid($pid,0);
673         die "Error running git-commit-tree: $?\n" if $?;
674
675         system("git-update-ref refs/heads/$branch $cid") == 0
676                 or die "Cannot write branch $branch for update: $!\n";
677
678         if($tag) {
679                 my($in, $out) = ('','');
680                 my($xtag) = $tag;
681                 $xtag =~ s/\s+\*\*.*$//; # Remove stuff like ** INVALID ** and ** FUNKY **
682                 $xtag =~ tr/_/\./ if ( $opt_u );
683                 $xtag =~ s/[\/]/$opt_s/g;
684                 
685                 my $pid = open2($in, $out, 'git-mktag');
686                 print $out "object $cid\n".
687                     "type commit\n".
688                     "tag $xtag\n".
689                     "tagger $author_name <$author_email>\n"
690                     or die "Cannot create tag object $xtag: $!\n";
691                 close($out)
692                     or die "Cannot create tag object $xtag: $!\n";
693
694                 my $tagobj = <$in>;
695                 chomp $tagobj;
696
697                 if ( !close($in) or waitpid($pid, 0) != $pid or
698                      $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
699                     die "Cannot create tag object $xtag: $!\n";
700                 }
701                 
702
703                 open(C,">$git_dir/refs/tags/$xtag")
704                         or die "Cannot create tag $xtag: $!\n";
705                 print C "$tagobj\n"
706                         or die "Cannot write tag $xtag: $!\n";
707                 close(C)
708                         or die "Cannot write tag $xtag: $!\n";
709
710                 print "Created tag '$xtag' on '$branch'\n" if $opt_v;
711         }
712 };
713
714 my $commitcount = 1;
715 while(<CVS>) {
716         chomp;
717         if($state == 0 and /^-+$/) {
718                 $state = 1;
719         } elsif($state == 0) {
720                 $state = 1;
721                 redo;
722         } elsif(($state==0 or $state==1) and s/^PatchSet\s+//) {
723                 $patchset = 0+$_;
724                 $state=2;
725         } elsif($state == 2 and s/^Date:\s+//) {
726                 $date = pdate($_);
727                 unless($date) {
728                         print STDERR "Could not parse date: $_\n";
729                         $state=0;
730                         next;
731                 }
732                 $state=3;
733         } elsif($state == 3 and s/^Author:\s+//) {
734                 s/\s+$//;
735                 if (/^(.*?)\s+<(.*)>/) {
736                     ($author_name, $author_email) = ($1, $2);
737                 } elsif ($conv_author_name{$_}) {
738                         $author_name = $conv_author_name{$_};
739                         $author_email = $conv_author_email{$_};
740                 } else {
741                     $author_name = $author_email = $_;
742                 }
743                 $state = 4;
744         } elsif($state == 4 and s/^Branch:\s+//) {
745                 s/\s+$//;
746                 s/[\/]/$opt_s/g;
747                 $branch = $_;
748                 $state = 5;
749         } elsif($state == 5 and s/^Ancestor branch:\s+//) {
750                 s/\s+$//;
751                 $ancestor = $_;
752                 $ancestor = $opt_o if $ancestor eq "HEAD";
753                 $state = 6;
754         } elsif($state == 5) {
755                 $ancestor = undef;
756                 $state = 6;
757                 redo;
758         } elsif($state == 6 and s/^Tag:\s+//) {
759                 s/\s+$//;
760                 if($_ eq "(none)") {
761                         $tag = undef;
762                 } else {
763                         $tag = $_;
764                 }
765                 $state = 7;
766         } elsif($state == 7 and /^Log:/) {
767                 $logmsg = "";
768                 $state = 8;
769         } elsif($state == 8 and /^Members:/) {
770                 $branch = $opt_o if $branch eq "HEAD";
771                 if(defined $branch_date{$branch} and $branch_date{$branch} >= $date) {
772                         # skip
773                         print "skip patchset $patchset: $date before $branch_date{$branch}\n" if $opt_v;
774                         $state = 11;
775                         next;
776                 }
777                 if (exists $ignorebranch{$branch}) {
778                         print STDERR "Skipping $branch\n";
779                         $state = 11;
780                         next;
781                 }
782                 if($ancestor) {
783                         if($ancestor eq $branch) {
784                                 print STDERR "Branch $branch erroneously stems from itself -- changed ancestor to $opt_o\n";
785                                 $ancestor = $opt_o;
786                         }
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                                 $ignorebranch{$branch} = 1;
795                                 $state=11;
796                                 next;
797                         }
798                         chomp(my $id = <H>);
799                         close(H);
800                         unless(open(H,"> $git_dir/refs/heads/$branch")) {
801                                 print STDERR "Could not create branch $branch: $!\n";
802                                 $ignorebranch{$branch} = 1;
803                                 $state=11;
804                                 next;
805                         }
806                         print H "$id\n"
807                                 or die "Could not write branch $branch: $!";
808                         close(H)
809                                 or die "Could not write branch $branch: $!";
810                 }
811                 if(($ancestor || $branch) ne $last_branch) {
812                         print "Switching from $last_branch to $branch\n" if $opt_v;
813                         unless ($index{$branch}) {
814                             $index{$branch} = tmpnam();
815                             $ENV{GIT_INDEX_FILE} = $index{$branch};
816                         }
817                         if ($ancestor) {
818                             system("git-read-tree", $ancestor);
819                             die "read-tree failed: $?\n" if $?;
820                         } else {
821                             unless ($index{$branch}) {
822                                 $index{$branch} = tmpnam();
823                                 $ENV{GIT_INDEX_FILE} = $index{$branch};
824                                 system("git-read-tree", $branch);
825                                 die "read-tree failed: $?\n" if $?;
826                             }
827                         }
828                 } else {
829                         # just in case
830                         unless ($index{$branch}) {
831                             $index{$branch} = tmpnam();
832                             $ENV{GIT_INDEX_FILE} = $index{$branch};
833                             system("git-read-tree", $branch);
834                             die "read-tree failed: $?\n" if $?;
835                         }
836                 }
837                 $last_branch = $branch if $branch ne $last_branch;
838                 $state = 9;
839         } elsif($state == 8) {
840                 $logmsg .= "$_\n";
841         } elsif($state == 9 and /^\s+(.+?):(INITIAL|\d+(?:\.\d+)+)->(\d+(?:\.\d+)+)\s*$/) {
842 #       VERSION:1.96->1.96.2.1
843                 my $init = ($2 eq "INITIAL");
844                 my $fn = $1;
845                 my $rev = $3;
846                 $fn =~ s#^/+##;
847                 if ($opt_S && $fn =~ m/$opt_S/) {
848                     print "SKIPPING $fn v $rev\n";
849                     push(@skipped, $fn);
850                     next;
851                 }
852                 print "Fetching $fn   v $rev\n" if $opt_v;
853                 my ($tmpname, $size) = $cvs->file($fn,$rev);
854                 if($size == -1) {
855                         push(@old,$fn);
856                         print "Drop $fn\n" if $opt_v;
857                 } else {
858                         print "".($init ? "New" : "Update")." $fn: $size bytes\n" if $opt_v;
859                         my $pid = open(my $F, '-|');
860                         die $! unless defined $pid;
861                         if (!$pid) {
862                             exec("git-hash-object", "-w", $tmpname)
863                                 or die "Cannot create object: $!\n";
864                         }
865                         my $sha = <$F>;
866                         chomp $sha;
867                         close $F;
868                         my $mode = pmode($cvs->{'mode'});
869                         push(@new,[$mode, $sha, $fn]); # may be resurrected!
870                 }
871                 unlink($tmpname);
872         } elsif($state == 9 and /^\s+(.+?):\d+(?:\.\d+)+->(\d+(?:\.\d+)+)\(DEAD\)\s*$/) {
873                 my $fn = $1;
874                 $fn =~ s#^/+##;
875                 push(@old,$fn);
876                 print "Delete $fn\n" if $opt_v;
877         } elsif($state == 9 and /^\s*$/) {
878                 $state = 10;
879         } elsif(($state == 9 or $state == 10) and /^-+$/) {
880                 $commitcount++;
881                 if ($opt_L && $commitcount > $opt_L) {
882                         last;
883                 }
884                 commit();
885                 if (($commitcount & 1023) == 0) {
886                         system("git repack -a -d");
887                 }
888                 $state = 1;
889         } elsif($state == 11 and /^-+$/) {
890                 $state = 1;
891         } elsif(/^-+$/) { # end of unknown-line processing
892                 $state = 1;
893         } elsif($state != 11) { # ignore stuff when skipping
894                 print "* UNKNOWN LINE * $_\n";
895         }
896 }
897 commit() if $branch and $state != 11;
898
899 foreach my $git_index (values %index) {
900     unlink($git_index);
901 }
902
903 if (defined $orig_git_index) {
904         $ENV{GIT_INDEX_FILE} = $orig_git_index;
905 } else {
906         delete $ENV{GIT_INDEX_FILE};
907 }
908
909 # Now switch back to the branch we were in before all of this happened
910 if($orig_branch) {
911         print "DONE.\n" if $opt_v;
912         if ($opt_i) {
913                 exit 0;
914         }
915         my $tip_at_end = `git-rev-parse --verify HEAD`;
916         if ($tip_at_start ne $tip_at_end) {
917                 for ($tip_at_start, $tip_at_end) { chomp; }
918                 print "Fetched into the current branch.\n" if $opt_v;
919                 system(qw(git-read-tree -u -m),
920                        $tip_at_start, $tip_at_end);
921                 die "Fast-forward update failed: $?\n" if $?;
922         }
923         else {
924                 system(qw(git-merge cvsimport HEAD), "refs/heads/$opt_o");
925                 die "Could not merge $opt_o into the current branch.\n" if $?;
926         }
927 } else {
928         $orig_branch = "master";
929         print "DONE; creating $orig_branch branch\n" if $opt_v;
930         system("git-update-ref", "refs/heads/master", "refs/heads/$opt_o")
931                 unless -f "$git_dir/refs/heads/master";
932         system('git-update-ref', 'HEAD', "$orig_branch");
933         unless ($opt_i) {
934                 system('git checkout');
935                 die "checkout failed: $?\n" if $?;
936         }
937 }