git-svn: fix log command to avoid infinite loop on long commit messages
[git/jnareb-git.git] / git-cvsimport.perl
blobac74bc51b3197d06f13f588d6916400ac3e6fcf0
1 #!/usr/bin/perl -w
3 # This tool is copyright (c) 2005, Matthias Urlichs.
4 # It is released under the Gnu Public License, version 2.
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.
10 # Checking out the files is done by a single long-running CVS connection
11 # / server process.
13 # The head revision is on branch "origin" by default.
14 # You can change that with the '-o' option.
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;
29 $SIG{'PIPE'}="IGNORE";
30 $ENV{'TZ'}="UTC";
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, $opt_a);
33 my (%conv_author_name, %conv_author_email);
35 sub usage(;$) {
36 my $msg = shift;
37 print(STDERR "Error: $msg\n") if $msg;
38 print STDERR <<END;
39 Usage: ${\basename $0} # fetch/update GIT from CVS
40 [-o branch-for-HEAD] [-h] [-v] [-d CVSROOT] [-A author-conv-file]
41 [-p opts-for-cvsps] [-P file] [-C GIT_repository] [-z fuzz] [-i] [-k]
42 [-u] [-s subst] [-a] [-m] [-M regex] [-S regex] [-L commitlimit]
43 [CVS_module]
44 END
45 exit(1);
48 sub read_author_info($) {
49 my ($file) = @_;
50 my $user;
51 open my $f, '<', "$file" or die("Failed to open $file: $!\n");
53 while (<$f>) {
54 # Expected format is this:
55 # exon=Andreas Ericsson <ae@op5.se>
56 if (m/^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/) {
57 $user = $1;
58 $conv_author_name{$user} = $2;
59 $conv_author_email{$user} = $3;
61 # However, we also read from CVSROOT/users format
62 # to ease migration.
63 elsif (/^(\w+):(['"]?)(.+?)\2\s*$/) {
64 my $mapped;
65 ($user, $mapped) = ($1, $3);
66 if ($mapped =~ /^\s*(.*?)\s*<(.*)>\s*$/) {
67 $conv_author_name{$user} = $1;
68 $conv_author_email{$user} = $2;
70 elsif ($mapped =~ /^<?(.*)>?$/) {
71 $conv_author_name{$user} = $user;
72 $conv_author_email{$user} = $1;
75 # NEEDSWORK: Maybe warn on unrecognized lines?
77 close ($f);
80 sub write_author_info($) {
81 my ($file) = @_;
82 open my $f, '>', $file or
83 die("Failed to open $file for writing: $!");
85 foreach (keys %conv_author_name) {
86 print $f "$_=$conv_author_name{$_} <$conv_author_email{$_}>\n";
88 close ($f);
91 # convert getopts specs for use by git-repo-config
92 sub read_repo_config {
93 # Split the string between characters, unless there is a ':'
94 # So "abc:de" becomes ["a", "b", "c:", "d", "e"]
95 my @opts = split(/ *(?!:)/, shift);
96 foreach my $o (@opts) {
97 my $key = $o;
98 $key =~ s/://g;
99 my $arg = 'git-repo-config';
100 $arg .= ' --bool' if ($o !~ /:$/);
102 chomp(my $tmp = `$arg --get cvsimport.$key`);
103 if ($tmp && !($arg =~ /--bool/ && $tmp eq 'false')) {
104 no strict 'refs';
105 my $opt_name = "opt_" . $key;
106 if (!$$opt_name) {
107 $$opt_name = $tmp;
111 if (@ARGV == 0) {
112 chomp(my $module = `git-repo-config --get cvsimport.module`);
113 push(@ARGV, $module);
117 my $opts = "haivmkuo:d:p:C:z:s:M:P:A:S:L:";
118 read_repo_config($opts);
119 getopts($opts) or usage();
120 usage if $opt_h;
122 @ARGV <= 1 or usage("You can't specify more than one CVS module");
124 if ($opt_d) {
125 $ENV{"CVSROOT"} = $opt_d;
126 } elsif (-f 'CVS/Root') {
127 open my $f, '<', 'CVS/Root' or die 'Failed to open CVS/Root';
128 $opt_d = <$f>;
129 chomp $opt_d;
130 close $f;
131 $ENV{"CVSROOT"} = $opt_d;
132 } elsif ($ENV{"CVSROOT"}) {
133 $opt_d = $ENV{"CVSROOT"};
134 } else {
135 usage("CVSROOT needs to be set");
137 $opt_o ||= "origin";
138 $opt_s ||= "-";
139 $opt_a ||= 0;
141 my $git_tree = $opt_C;
142 $git_tree ||= ".";
144 my $cvs_tree;
145 if ($#ARGV == 0) {
146 $cvs_tree = $ARGV[0];
147 } elsif (-f 'CVS/Repository') {
148 open my $f, '<', 'CVS/Repository' or
149 die 'Failed to open CVS/Repository';
150 $cvs_tree = <$f>;
151 chomp $cvs_tree;
152 close $f;
153 } else {
154 usage("CVS module has to be specified");
157 our @mergerx = ();
158 if ($opt_m) {
159 @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
161 if ($opt_M) {
162 push (@mergerx, qr/$opt_M/);
165 # Remember UTC of our starting time
166 # we'll want to avoid importing commits
167 # that are too recent
168 our $starttime = time();
170 select(STDERR); $|=1; select(STDOUT);
173 package CVSconn;
174 # Basic CVS dialog.
175 # We're only interested in connecting and downloading, so ...
177 use File::Spec;
178 use File::Temp qw(tempfile);
179 use POSIX qw(strftime dup2);
181 sub new {
182 my ($what,$repo,$subdir) = @_;
183 $what=ref($what) if ref($what);
185 my $self = {};
186 $self->{'buffer'} = "";
187 bless($self,$what);
189 $repo =~ s#/+$##;
190 $self->{'fullrep'} = $repo;
191 $self->conn();
193 $self->{'subdir'} = $subdir;
194 $self->{'lines'} = undef;
196 return $self;
199 sub conn {
200 my $self = shift;
201 my $repo = $self->{'fullrep'};
202 if ($repo =~ s/^:pserver(?:([^:]*)):(?:(.*?)(?::(.*?))?@)?([^:\/]*)(?::(\d*))?//) {
203 my ($param,$user,$pass,$serv,$port) = ($1,$2,$3,$4,$5);
205 my ($proxyhost,$proxyport);
206 if ($param && ($param =~ m/proxy=([^;]+)/)) {
207 $proxyhost = $1;
208 # Default proxyport, if not specified, is 8080.
209 $proxyport = 8080;
210 if ($ENV{"CVS_PROXY_PORT"}) {
211 $proxyport = $ENV{"CVS_PROXY_PORT"};
213 if ($param =~ m/proxyport=([^;]+)/) {
214 $proxyport = $1;
218 $user="anonymous" unless defined $user;
219 my $rr2 = "-";
220 unless ($port) {
221 $rr2 = ":pserver:$user\@$serv:$repo";
222 $port=2401;
224 my $rr = ":pserver:$user\@$serv:$port$repo";
226 unless ($pass) {
227 open(H,$ENV{'HOME'}."/.cvspass") and do {
228 # :pserver:cvs@mea.tmt.tele.fi:/cvsroot/zmailer Ah<Z
229 while (<H>) {
230 chomp;
231 s/^\/\d+\s+//;
232 my ($w,$p) = split(/\s/,$_,2);
233 if ($w eq $rr or $w eq $rr2) {
234 $pass = $p;
235 last;
240 $pass="A" unless $pass;
242 my ($s, $rep);
243 if ($proxyhost) {
245 # Use a HTTP Proxy. Only works for HTTP proxies that
246 # don't require user authentication
248 # See: http://www.ietf.org/rfc/rfc2817.txt
250 $s = IO::Socket::INET->new(PeerHost => $proxyhost, PeerPort => $proxyport);
251 die "Socket to $proxyhost: $!\n" unless defined $s;
252 $s->write("CONNECT $serv:$port HTTP/1.1\r\nHost: $serv:$port\r\n\r\n")
253 or die "Write to $proxyhost: $!\n";
254 $s->flush();
256 $rep = <$s>;
258 # The answer should look like 'HTTP/1.x 2yy ....'
259 if (!($rep =~ m#^HTTP/1\.. 2[0-9][0-9]#)) {
260 die "Proxy connect: $rep\n";
262 # Skip up to the empty line of the proxy server output
263 # including the response headers.
264 while ($rep = <$s>) {
265 last if (!defined $rep ||
266 $rep eq "\n" ||
267 $rep eq "\r\n");
269 } else {
270 $s = IO::Socket::INET->new(PeerHost => $serv, PeerPort => $port);
271 die "Socket to $serv: $!\n" unless defined $s;
274 $s->write("BEGIN AUTH REQUEST\n$repo\n$user\n$pass\nEND AUTH REQUEST\n")
275 or die "Write to $serv: $!\n";
276 $s->flush();
278 $rep = <$s>;
280 if ($rep ne "I LOVE YOU\n") {
281 $rep="<unknown>" unless $rep;
282 die "AuthReply: $rep\n";
284 $self->{'socketo'} = $s;
285 $self->{'socketi'} = $s;
286 } else { # local or ext: Fork off our own cvs server.
287 my $pr = IO::Pipe->new();
288 my $pw = IO::Pipe->new();
289 my $pid = fork();
290 die "Fork: $!\n" unless defined $pid;
291 my $cvs = 'cvs';
292 $cvs = $ENV{CVS_SERVER} if exists $ENV{CVS_SERVER};
293 my $rsh = 'rsh';
294 $rsh = $ENV{CVS_RSH} if exists $ENV{CVS_RSH};
296 my @cvs = ($cvs, 'server');
297 my ($local, $user, $host);
298 $local = $repo =~ s/:local://;
299 if (!$local) {
300 $repo =~ s/:ext://;
301 $local = !($repo =~ s/^(?:([^\@:]+)\@)?([^:]+)://);
302 ($user, $host) = ($1, $2);
304 if (!$local) {
305 if ($user) {
306 unshift @cvs, $rsh, '-l', $user, $host;
307 } else {
308 unshift @cvs, $rsh, $host;
312 unless ($pid) {
313 $pr->writer();
314 $pw->reader();
315 dup2($pw->fileno(),0);
316 dup2($pr->fileno(),1);
317 $pr->close();
318 $pw->close();
319 exec(@cvs);
321 $pw->writer();
322 $pr->reader();
323 $self->{'socketo'} = $pw;
324 $self->{'socketi'} = $pr;
326 $self->{'socketo'}->write("Root $repo\n");
328 # Trial and error says that this probably is the minimum set
329 $self->{'socketo'}->write("Valid-responses ok error Valid-requests Mode M Mbinary E Checked-in Created Updated Merged Removed\n");
331 $self->{'socketo'}->write("valid-requests\n");
332 $self->{'socketo'}->flush();
334 chomp(my $rep=$self->readline());
335 if ($rep !~ s/^Valid-requests\s*//) {
336 $rep="<unknown>" unless $rep;
337 die "Expected Valid-requests from server, but got: $rep\n";
339 chomp(my $res=$self->readline());
340 die "validReply: $res\n" if $res ne "ok";
342 $self->{'socketo'}->write("UseUnchanged\n") if $rep =~ /\bUseUnchanged\b/;
343 $self->{'repo'} = $repo;
346 sub readline {
347 my ($self) = @_;
348 return $self->{'socketi'}->getline();
351 sub _file {
352 # Request a file with a given revision.
353 # Trial and error says this is a good way to do it. :-/
354 my ($self,$fn,$rev) = @_;
355 $self->{'socketo'}->write("Argument -N\n") or return undef;
356 $self->{'socketo'}->write("Argument -P\n") or return undef;
357 # -kk: Linus' version doesn't use it - defaults to off
358 if ($opt_k) {
359 $self->{'socketo'}->write("Argument -kk\n") or return undef;
361 $self->{'socketo'}->write("Argument -r\n") or return undef;
362 $self->{'socketo'}->write("Argument $rev\n") or return undef;
363 $self->{'socketo'}->write("Argument --\n") or return undef;
364 $self->{'socketo'}->write("Argument $self->{'subdir'}/$fn\n") or return undef;
365 $self->{'socketo'}->write("Directory .\n") or return undef;
366 $self->{'socketo'}->write("$self->{'repo'}\n") or return undef;
367 # $self->{'socketo'}->write("Sticky T1.0\n") or return undef;
368 $self->{'socketo'}->write("co\n") or return undef;
369 $self->{'socketo'}->flush() or return undef;
370 $self->{'lines'} = 0;
371 return 1;
373 sub _line {
374 # Read a line from the server.
375 # ... except that 'line' may be an entire file. ;-)
376 my ($self, $fh) = @_;
377 die "Not in lines" unless defined $self->{'lines'};
379 my $line;
380 my $res=0;
381 while (defined($line = $self->readline())) {
382 # M U gnupg-cvs-rep/AUTHORS
383 # Updated gnupg-cvs-rep/
384 # /daten/src/rsync/gnupg-cvs-rep/AUTHORS
385 # /AUTHORS/1.1///T1.1
386 # u=rw,g=rw,o=rw
388 # ok
390 if ($line =~ s/^(?:Created|Updated) //) {
391 $line = $self->readline(); # path
392 $line = $self->readline(); # Entries line
393 my $mode = $self->readline(); chomp $mode;
394 $self->{'mode'} = $mode;
395 defined (my $cnt = $self->readline())
396 or die "EOF from server after 'Changed'\n";
397 chomp $cnt;
398 die "Duh: Filesize $cnt" if $cnt !~ /^\d+$/;
399 $line="";
400 $res = $self->_fetchfile($fh, $cnt);
401 } elsif ($line =~ s/^ //) {
402 print $fh $line;
403 $res += length($line);
404 } elsif ($line =~ /^M\b/) {
405 # output, do nothing
406 } elsif ($line =~ /^Mbinary\b/) {
407 my $cnt;
408 die "EOF from server after 'Mbinary'" unless defined ($cnt = $self->readline());
409 chomp $cnt;
410 die "Duh: Mbinary $cnt" if $cnt !~ /^\d+$/ or $cnt<1;
411 $line="";
412 $res += $self->_fetchfile($fh, $cnt);
413 } else {
414 chomp $line;
415 if ($line eq "ok") {
416 # print STDERR "S: ok (".length($res).")\n";
417 return $res;
418 } elsif ($line =~ s/^E //) {
419 # print STDERR "S: $line\n";
420 } elsif ($line =~ /^(Remove-entry|Removed) /i) {
421 $line = $self->readline(); # filename
422 $line = $self->readline(); # OK
423 chomp $line;
424 die "Unknown: $line" if $line ne "ok";
425 return -1;
426 } else {
427 die "Unknown: $line\n";
431 return undef;
433 sub file {
434 my ($self,$fn,$rev) = @_;
435 my $res;
437 my ($fh, $name) = tempfile('gitcvs.XXXXXX',
438 DIR => File::Spec->tmpdir(), UNLINK => 1);
440 $self->_file($fn,$rev) and $res = $self->_line($fh);
442 if (!defined $res) {
443 print STDERR "Server has gone away while fetching $fn $rev, retrying...\n";
444 truncate $fh, 0;
445 $self->conn();
446 $self->_file($fn,$rev) or die "No file command send";
447 $res = $self->_line($fh);
448 die "Retry failed" unless defined $res;
450 close ($fh);
452 return ($name, $res);
454 sub _fetchfile {
455 my ($self, $fh, $cnt) = @_;
456 my $res = 0;
457 my $bufsize = 1024 * 1024;
458 while ($cnt) {
459 if ($bufsize > $cnt) {
460 $bufsize = $cnt;
462 my $buf;
463 my $num = $self->{'socketi'}->read($buf,$bufsize);
464 die "Server: Filesize $cnt: $num: $!\n" if not defined $num or $num<=0;
465 print $fh $buf;
466 $res += $num;
467 $cnt -= $num;
469 return $res;
473 package main;
475 my $cvs = CVSconn->new($opt_d, $cvs_tree);
478 sub pdate($) {
479 my ($d) = @_;
480 m#(\d{2,4})/(\d\d)/(\d\d)\s(\d\d):(\d\d)(?::(\d\d))?#
481 or die "Unparseable date: $d\n";
482 my $y=$1; $y-=1900 if $y>1900;
483 return timegm($6||0,$5,$4,$3,$2-1,$y);
486 sub pmode($) {
487 my ($mode) = @_;
488 my $m = 0;
489 my $mm = 0;
490 my $um = 0;
491 for my $x(split(//,$mode)) {
492 if ($x eq ",") {
493 $m |= $mm&$um;
494 $mm = 0;
495 $um = 0;
496 } elsif ($x eq "u") { $um |= 0700;
497 } elsif ($x eq "g") { $um |= 0070;
498 } elsif ($x eq "o") { $um |= 0007;
499 } elsif ($x eq "r") { $mm |= 0444;
500 } elsif ($x eq "w") { $mm |= 0222;
501 } elsif ($x eq "x") { $mm |= 0111;
502 } elsif ($x eq "=") { # do nothing
503 } else { die "Unknown mode: $mode\n";
506 $m |= $mm&$um;
507 return $m;
510 sub getwd() {
511 my $pwd = `pwd`;
512 chomp $pwd;
513 return $pwd;
516 sub is_sha1 {
517 my $s = shift;
518 return $s =~ /^[a-f0-9]{40}$/;
521 sub get_headref ($$) {
522 my $name = shift;
523 my $git_dir = shift;
525 my $f = "$git_dir/refs/heads/$name";
526 if (open(my $fh, $f)) {
527 chomp(my $r = <$fh>);
528 is_sha1($r) or die "Cannot get head id for $name ($r): $!";
529 return $r;
531 die "unable to open $f: $!" unless $! == POSIX::ENOENT;
532 return undef;
535 -d $git_tree
536 or mkdir($git_tree,0777)
537 or die "Could not create $git_tree: $!";
538 chdir($git_tree);
540 my $last_branch = "";
541 my $orig_branch = "";
542 my %branch_date;
543 my $tip_at_start = undef;
545 my $git_dir = $ENV{"GIT_DIR"} || ".git";
546 $git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
547 $ENV{"GIT_DIR"} = $git_dir;
548 my $orig_git_index;
549 $orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
551 my %index; # holds filenames of one index per branch
553 unless (-d $git_dir) {
554 system("git-init");
555 die "Cannot init the GIT db at $git_tree: $?\n" if $?;
556 system("git-read-tree");
557 die "Cannot init an empty tree: $?\n" if $?;
559 $last_branch = $opt_o;
560 $orig_branch = "";
561 } else {
562 -f "$git_dir/refs/heads/$opt_o"
563 or die "Branch '$opt_o' does not exist.\n".
564 "Either use the correct '-o branch' option,\n".
565 "or import to a new repository.\n";
567 open(F, "git-symbolic-ref HEAD |") or
568 die "Cannot run git-symbolic-ref: $!\n";
569 chomp ($last_branch = <F>);
570 $last_branch = basename($last_branch);
571 close(F);
572 unless ($last_branch) {
573 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
574 $last_branch = "master";
576 $orig_branch = $last_branch;
577 $tip_at_start = `git-rev-parse --verify HEAD`;
579 # Get the last import timestamps
580 my $fmt = '($ref, $author) = (%(refname), %(author));';
581 open(H, "git-for-each-ref --perl --format='$fmt' refs/heads |") or
582 die "Cannot run git-for-each-ref: $!\n";
583 while (defined(my $entry = <H>)) {
584 my ($ref, $author);
585 eval($entry) || die "cannot eval refs list: $@";
586 my ($head) = ($ref =~ m|^refs/heads/(.*)|);
587 $author =~ /^.*\s(\d+)\s[-+]\d{4}$/;
588 $branch_date{$head} = $1;
590 close(H);
593 -d $git_dir
594 or die "Could not create git subdir ($git_dir).\n";
596 # now we read (and possibly save) author-info as well
597 -f "$git_dir/cvs-authors" and
598 read_author_info("$git_dir/cvs-authors");
599 if ($opt_A) {
600 read_author_info($opt_A);
601 write_author_info("$git_dir/cvs-authors");
606 # run cvsps into a file unless we are getting
607 # it passed as a file via $opt_P
609 my $cvspsfile;
610 unless ($opt_P) {
611 print "Running cvsps...\n" if $opt_v;
612 my $pid = open(CVSPS,"-|");
613 my $cvspsfh;
614 die "Cannot fork: $!\n" unless defined $pid;
615 unless ($pid) {
616 my @opt;
617 @opt = split(/,/,$opt_p) if defined $opt_p;
618 unshift @opt, '-z', $opt_z if defined $opt_z;
619 unshift @opt, '-q' unless defined $opt_v;
620 unless (defined($opt_p) && $opt_p =~ m/--no-cvs-direct/) {
621 push @opt, '--cvs-direct';
623 exec("cvsps","--norc",@opt,"-u","-A",'--root',$opt_d,$cvs_tree);
624 die "Could not start cvsps: $!\n";
626 ($cvspsfh, $cvspsfile) = tempfile('gitXXXXXX', SUFFIX => '.cvsps',
627 DIR => File::Spec->tmpdir());
628 while (<CVSPS>) {
629 print $cvspsfh $_;
631 close CVSPS;
632 close $cvspsfh;
633 } else {
634 $cvspsfile = $opt_P;
637 open(CVS, "<$cvspsfile") or die $!;
639 ## cvsps output:
640 #---------------------
641 #PatchSet 314
642 #Date: 1999/09/18 13:03:59
643 #Author: wkoch
644 #Branch: STABLE-BRANCH-1-0
645 #Ancestor branch: HEAD
646 #Tag: (none)
647 #Log:
648 # See ChangeLog: Sat Sep 18 13:03:28 CEST 1999 Werner Koch
649 #Members:
650 # README:1.57->1.57.2.1
651 # VERSION:1.96->1.96.2.1
653 #---------------------
655 my $state = 0;
657 sub update_index (\@\@) {
658 my $old = shift;
659 my $new = shift;
660 open(my $fh, '|-', qw(git-update-index -z --index-info))
661 or die "unable to open git-update-index: $!";
662 print $fh
663 (map { "0 0000000000000000000000000000000000000000\t$_\0" }
664 @$old),
665 (map { '100' . sprintf('%o', $_->[0]) . " $_->[1]\t$_->[2]\0" }
666 @$new)
667 or die "unable to write to git-update-index: $!";
668 close $fh
669 or die "unable to write to git-update-index: $!";
670 $? and die "git-update-index reported error: $?";
673 sub write_tree () {
674 open(my $fh, '-|', qw(git-write-tree))
675 or die "unable to open git-write-tree: $!";
676 chomp(my $tree = <$fh>);
677 is_sha1($tree)
678 or die "Cannot get tree id ($tree): $!";
679 close($fh)
680 or die "Error running git-write-tree: $?\n";
681 print "Tree ID $tree\n" if $opt_v;
682 return $tree;
685 my ($patchset,$date,$author_name,$author_email,$branch,$ancestor,$tag,$logmsg);
686 my (@old,@new,@skipped,%ignorebranch);
688 # commits that cvsps cannot place anywhere...
689 $ignorebranch{'#CVSPS_NO_BRANCH'} = 1;
691 sub commit {
692 if ($branch eq $opt_o && !$index{branch} && !get_headref($branch, $git_dir)) {
693 # looks like an initial commit
694 # use the index primed by git-init
695 $ENV{GIT_INDEX_FILE} = '.git/index';
696 $index{$branch} = '.git/index';
697 } else {
698 # use an index per branch to speed up
699 # imports of projects with many branches
700 unless ($index{$branch}) {
701 $index{$branch} = tmpnam();
702 $ENV{GIT_INDEX_FILE} = $index{$branch};
703 if ($ancestor) {
704 system("git-read-tree", $ancestor);
705 } else {
706 system("git-read-tree", $branch);
708 die "read-tree failed: $?\n" if $?;
711 $ENV{GIT_INDEX_FILE} = $index{$branch};
713 update_index(@old, @new);
714 @old = @new = ();
715 my $tree = write_tree();
716 my $parent = get_headref($last_branch, $git_dir);
717 print "Parent ID " . ($parent ? $parent : "(empty)") . "\n" if $opt_v;
719 my @commit_args;
720 push @commit_args, ("-p", $parent) if $parent;
722 # loose detection of merges
723 # based on the commit msg
724 foreach my $rx (@mergerx) {
725 next unless $logmsg =~ $rx && $1;
726 my $mparent = $1 eq 'HEAD' ? $opt_o : $1;
727 if (my $sha1 = get_headref($mparent, $git_dir)) {
728 push @commit_args, '-p', $mparent;
729 print "Merge parent branch: $mparent\n" if $opt_v;
733 my $commit_date = strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date));
734 $ENV{GIT_AUTHOR_NAME} = $author_name;
735 $ENV{GIT_AUTHOR_EMAIL} = $author_email;
736 $ENV{GIT_AUTHOR_DATE} = $commit_date;
737 $ENV{GIT_COMMITTER_NAME} = $author_name;
738 $ENV{GIT_COMMITTER_EMAIL} = $author_email;
739 $ENV{GIT_COMMITTER_DATE} = $commit_date;
740 my $pid = open2(my $commit_read, my $commit_write,
741 'git-commit-tree', $tree, @commit_args);
743 # compatibility with git2cvs
744 substr($logmsg,32767) = "" if length($logmsg) > 32767;
745 $logmsg =~ s/[\s\n]+\z//;
747 if (@skipped) {
748 $logmsg .= "\n\n\nSKIPPED:\n\t";
749 $logmsg .= join("\n\t", @skipped) . "\n";
750 @skipped = ();
753 print($commit_write "$logmsg\n") && close($commit_write)
754 or die "Error writing to git-commit-tree: $!\n";
756 print "Committed patch $patchset ($branch $commit_date)\n" if $opt_v;
757 chomp(my $cid = <$commit_read>);
758 is_sha1($cid) or die "Cannot get commit id ($cid): $!\n";
759 print "Commit ID $cid\n" if $opt_v;
760 close($commit_read);
762 waitpid($pid,0);
763 die "Error running git-commit-tree: $?\n" if $?;
765 system("git-update-ref refs/heads/$branch $cid") == 0
766 or die "Cannot write branch $branch for update: $!\n";
768 if ($tag) {
769 my ($in, $out) = ('','');
770 my ($xtag) = $tag;
771 $xtag =~ s/\s+\*\*.*$//; # Remove stuff like ** INVALID ** and ** FUNKY **
772 $xtag =~ tr/_/\./ if ( $opt_u );
773 $xtag =~ s/[\/]/$opt_s/g;
775 my $pid = open2($in, $out, 'git-mktag');
776 print $out "object $cid\n".
777 "type commit\n".
778 "tag $xtag\n".
779 "tagger $author_name <$author_email>\n"
780 or die "Cannot create tag object $xtag: $!\n";
781 close($out)
782 or die "Cannot create tag object $xtag: $!\n";
784 my $tagobj = <$in>;
785 chomp $tagobj;
787 if ( !close($in) or waitpid($pid, 0) != $pid or
788 $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
789 die "Cannot create tag object $xtag: $!\n";
793 open(C,">$git_dir/refs/tags/$xtag")
794 or die "Cannot create tag $xtag: $!\n";
795 print C "$tagobj\n"
796 or die "Cannot write tag $xtag: $!\n";
797 close(C)
798 or die "Cannot write tag $xtag: $!\n";
800 print "Created tag '$xtag' on '$branch'\n" if $opt_v;
804 my $commitcount = 1;
805 while (<CVS>) {
806 chomp;
807 if ($state == 0 and /^-+$/) {
808 $state = 1;
809 } elsif ($state == 0) {
810 $state = 1;
811 redo;
812 } elsif (($state==0 or $state==1) and s/^PatchSet\s+//) {
813 $patchset = 0+$_;
814 $state=2;
815 } elsif ($state == 2 and s/^Date:\s+//) {
816 $date = pdate($_);
817 unless ($date) {
818 print STDERR "Could not parse date: $_\n";
819 $state=0;
820 next;
822 $state=3;
823 } elsif ($state == 3 and s/^Author:\s+//) {
824 s/\s+$//;
825 if (/^(.*?)\s+<(.*)>/) {
826 ($author_name, $author_email) = ($1, $2);
827 } elsif ($conv_author_name{$_}) {
828 $author_name = $conv_author_name{$_};
829 $author_email = $conv_author_email{$_};
830 } else {
831 $author_name = $author_email = $_;
833 $state = 4;
834 } elsif ($state == 4 and s/^Branch:\s+//) {
835 s/\s+$//;
836 s/[\/]/$opt_s/g;
837 $branch = $_;
838 $state = 5;
839 } elsif ($state == 5 and s/^Ancestor branch:\s+//) {
840 s/\s+$//;
841 $ancestor = $_;
842 $ancestor = $opt_o if $ancestor eq "HEAD";
843 $state = 6;
844 } elsif ($state == 5) {
845 $ancestor = undef;
846 $state = 6;
847 redo;
848 } elsif ($state == 6 and s/^Tag:\s+//) {
849 s/\s+$//;
850 if ($_ eq "(none)") {
851 $tag = undef;
852 } else {
853 $tag = $_;
855 $state = 7;
856 } elsif ($state == 7 and /^Log:/) {
857 $logmsg = "";
858 $state = 8;
859 } elsif ($state == 8 and /^Members:/) {
860 $branch = $opt_o if $branch eq "HEAD";
861 if (defined $branch_date{$branch} and $branch_date{$branch} >= $date) {
862 # skip
863 print "skip patchset $patchset: $date before $branch_date{$branch}\n" if $opt_v;
864 $state = 11;
865 next;
867 if (!$opt_a && $starttime - 300 - (defined $opt_z ? $opt_z : 300) <= $date) {
868 # skip if the commit is too recent
869 # that the cvsps default fuzz is 300s, we give ourselves another
870 # 300s just in case -- this also prevents skipping commits
871 # due to server clock drift
872 print "skip patchset $patchset: $date too recent\n" if $opt_v;
873 $state = 11;
874 next;
876 if (exists $ignorebranch{$branch}) {
877 print STDERR "Skipping $branch\n";
878 $state = 11;
879 next;
881 if ($ancestor) {
882 if ($ancestor eq $branch) {
883 print STDERR "Branch $branch erroneously stems from itself -- changed ancestor to $opt_o\n";
884 $ancestor = $opt_o;
886 if (-f "$git_dir/refs/heads/$branch") {
887 print STDERR "Branch $branch already exists!\n";
888 $state=11;
889 next;
891 unless (open(H,"$git_dir/refs/heads/$ancestor")) {
892 print STDERR "Branch $ancestor does not exist!\n";
893 $ignorebranch{$branch} = 1;
894 $state=11;
895 next;
897 chomp(my $id = <H>);
898 close(H);
899 unless (open(H,"> $git_dir/refs/heads/$branch")) {
900 print STDERR "Could not create branch $branch: $!\n";
901 $ignorebranch{$branch} = 1;
902 $state=11;
903 next;
905 print H "$id\n"
906 or die "Could not write branch $branch: $!";
907 close(H)
908 or die "Could not write branch $branch: $!";
910 $last_branch = $branch if $branch ne $last_branch;
911 $state = 9;
912 } elsif ($state == 8) {
913 $logmsg .= "$_\n";
914 } elsif ($state == 9 and /^\s+(.+?):(INITIAL|\d+(?:\.\d+)+)->(\d+(?:\.\d+)+)\s*$/) {
915 # VERSION:1.96->1.96.2.1
916 my $init = ($2 eq "INITIAL");
917 my $fn = $1;
918 my $rev = $3;
919 $fn =~ s#^/+##;
920 if ($opt_S && $fn =~ m/$opt_S/) {
921 print "SKIPPING $fn v $rev\n";
922 push(@skipped, $fn);
923 next;
925 print "Fetching $fn v $rev\n" if $opt_v;
926 my ($tmpname, $size) = $cvs->file($fn,$rev);
927 if ($size == -1) {
928 push(@old,$fn);
929 print "Drop $fn\n" if $opt_v;
930 } else {
931 print "".($init ? "New" : "Update")." $fn: $size bytes\n" if $opt_v;
932 my $pid = open(my $F, '-|');
933 die $! unless defined $pid;
934 if (!$pid) {
935 exec("git-hash-object", "-w", $tmpname)
936 or die "Cannot create object: $!\n";
938 my $sha = <$F>;
939 chomp $sha;
940 close $F;
941 my $mode = pmode($cvs->{'mode'});
942 push(@new,[$mode, $sha, $fn]); # may be resurrected!
944 unlink($tmpname);
945 } elsif ($state == 9 and /^\s+(.+?):\d+(?:\.\d+)+->(\d+(?:\.\d+)+)\(DEAD\)\s*$/) {
946 my $fn = $1;
947 $fn =~ s#^/+##;
948 push(@old,$fn);
949 print "Delete $fn\n" if $opt_v;
950 } elsif ($state == 9 and /^\s*$/) {
951 $state = 10;
952 } elsif (($state == 9 or $state == 10) and /^-+$/) {
953 $commitcount++;
954 if ($opt_L && $commitcount > $opt_L) {
955 last;
957 commit();
958 if (($commitcount & 1023) == 0) {
959 system("git repack -a -d");
961 $state = 1;
962 } elsif ($state == 11 and /^-+$/) {
963 $state = 1;
964 } elsif (/^-+$/) { # end of unknown-line processing
965 $state = 1;
966 } elsif ($state != 11) { # ignore stuff when skipping
967 print "* UNKNOWN LINE * $_\n";
970 commit() if $branch and $state != 11;
972 unless ($opt_P) {
973 unlink($cvspsfile);
976 # The heuristic of repacking every 1024 commits can leave a
977 # lot of unpacked data. If there is more than 1MB worth of
978 # not-packed objects, repack once more.
979 my $line = `git-count-objects`;
980 if ($line =~ /^(\d+) objects, (\d+) kilobytes$/) {
981 my ($n_objects, $kb) = ($1, $2);
982 1024 < $kb
983 and system("git repack -a -d");
986 foreach my $git_index (values %index) {
987 if ($git_index ne '.git/index') {
988 unlink($git_index);
992 if (defined $orig_git_index) {
993 $ENV{GIT_INDEX_FILE} = $orig_git_index;
994 } else {
995 delete $ENV{GIT_INDEX_FILE};
998 # Now switch back to the branch we were in before all of this happened
999 if ($orig_branch) {
1000 print "DONE.\n" if $opt_v;
1001 if ($opt_i) {
1002 exit 0;
1004 my $tip_at_end = `git-rev-parse --verify HEAD`;
1005 if ($tip_at_start ne $tip_at_end) {
1006 for ($tip_at_start, $tip_at_end) { chomp; }
1007 print "Fetched into the current branch.\n" if $opt_v;
1008 system(qw(git-read-tree -u -m),
1009 $tip_at_start, $tip_at_end);
1010 die "Fast-forward update failed: $?\n" if $?;
1012 else {
1013 system(qw(git-merge cvsimport HEAD), "refs/heads/$opt_o");
1014 die "Could not merge $opt_o into the current branch.\n" if $?;
1016 } else {
1017 $orig_branch = "master";
1018 print "DONE; creating $orig_branch branch\n" if $opt_v;
1019 system("git-update-ref", "refs/heads/master", "refs/heads/$opt_o")
1020 unless -f "$git_dir/refs/heads/master";
1021 system('git-update-ref', 'HEAD', "$orig_branch");
1022 unless ($opt_i) {
1023 system('git checkout');
1024 die "checkout failed: $?\n" if $?;