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
10 # Checking out the files is done by a single long-running CVS connection
13 # The head revision is on branch "origin" by default.
14 # You can change that with the '-o' option.
20 use File::Temp qw(tempfile);
21 use File::Path qw(mkpath);
22 use File::Basename qw(basename dirname);
26 use POSIX qw(strftime dup2);
29 $SIG{'PIPE'}="IGNORE";
32 our($opt_h,$opt_o,$opt_v,$opt_k,$opt_u,$opt_d,$opt_p,$opt_C,$opt_z,$opt_i,$opt_P, $opt_s,$opt_m,$opt_M,$opt_A,$opt_S);
33 my (%conv_author_name, %conv_author_email);
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]
45 sub read_author_info($) {
48 open my $f, '<', "$file" or die("Failed to open $file: $!\n");
51 # Expected format is this:
52 # exon=Andreas Ericsson <ae@op5.se>
53 if (m/^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/) {
55 $conv_author_name{$user} = $2;
56 $conv_author_email{$user} = $3;
58 # However, we also read from CVSROOT/users format
60 elsif (/^(\w+):(['"]?)(.+?)\2\s*$/) {
62 ($user, $mapped) = ($1, $3);
63 if ($mapped =~ /^\s*(.*?)\s*<(.*)>\s*$/) {
64 $conv_author_name{$user} = $1;
65 $conv_author_email{$user} = $2;
67 elsif ($mapped =~ /^<?(.*)>?$/) {
68 $conv_author_name{$user} = $user;
69 $conv_author_email{$user} = $1;
72 # NEEDSWORK: Maybe warn on unrecognized lines?
77 sub write_author_info($) {
79 open my $f, '>', $file or
80 die("Failed to open $file for writing: $!");
82 foreach (keys %conv_author_name) {
83 print $f "$_=$conv_author_name{$_} <$conv_author_email{$_}>\n";
88 getopts("hivmkuo:d:p:C:z:s:M:P:A:S:") or usage();
91 @ARGV <= 1 or usage();
94 $ENV{"CVSROOT"} = $opt_d;
95 } elsif(-f 'CVS/Root') {
96 open my $f, '<', 'CVS/Root' or die 'Failed to open CVS/Root';
100 $ENV{"CVSROOT"} = $opt_d;
101 } elsif($ENV{"CVSROOT"}) {
102 $opt_d = $ENV{"CVSROOT"};
104 die "CVSROOT needs to be set";
108 my $git_tree = $opt_C;
113 $cvs_tree = $ARGV[0];
114 } elsif (-f 'CVS/Repository') {
115 open my $f, '<', 'CVS/Repository' or
116 die 'Failed to open CVS/Repository';
126 @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
129 push (@mergerx, qr/$opt_M/);
132 select(STDERR); $|=1; select(STDOUT);
137 # We're only interested in connecting and downloading, so ...
140 use File::Temp qw(tempfile);
141 use POSIX qw(strftime dup2);
144 my($what,$repo,$subdir) = @_;
145 $what=ref($what) if ref($what);
148 $self->{'buffer'} = "";
152 $self->{'fullrep'} = $repo;
155 $self->{'subdir'} = $subdir;
156 $self->{'lines'} = undef;
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;
169 $rr2 = ":pserver:$user\@$serv:$repo";
172 my $rr = ":pserver:$user\@$serv:$port$repo";
175 open(H,$ENV{'HOME'}."/.cvspass") and do {
176 # :pserver:cvs@mea.tmt.tele.fi:/cvsroot/zmailer Ah<Z
180 my ($w,$p) = split(/\s/,$_,2);
181 if($w eq $rr or $w eq $rr2) {
188 $pass="A" unless $pass;
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";
198 if($rep ne "I LOVE YOU\n") {
199 $rep="<unknown>" unless $rep;
200 die "AuthReply: $rep\n";
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();
208 die "Fork: $!\n" unless defined $pid;
210 $cvs = $ENV{CVS_SERVER} if exists $ENV{CVS_SERVER};
212 $rsh = $ENV{CVS_RSH} if exists $ENV{CVS_RSH};
214 my @cvs = ($cvs, 'server');
215 my ($local, $user, $host);
216 $local = $repo =~ s/:local://;
219 $local = !($repo =~ s/^(?:([^\@:]+)\@)?([^:]+)://);
220 ($user, $host) = ($1, $2);
224 unshift @cvs, $rsh, '-l', $user, $host;
226 unshift @cvs, $rsh, $host;
233 dup2($pw->fileno(),0);
234 dup2($pr->fileno(),1);
241 $self->{'socketo'} = $pw;
242 $self->{'socketi'} = $pr;
244 $self->{'socketo'}->write("Root $repo\n");
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");
249 $self->{'socketo'}->write("valid-requests\n");
250 $self->{'socketo'}->flush();
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";
257 chomp(my $res=$self->readline());
258 die "validReply: $res\n" if $res ne "ok";
260 $self->{'socketo'}->write("UseUnchanged\n") if $rep =~ /\bUseUnchanged\b/;
261 $self->{'repo'} = $repo;
266 return $self->{'socketi'}->getline();
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
277 $self->{'socketo'}->write("Argument -kk\n") or return undef;
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;
292 # Read a line from the server.
293 # ... except that 'line' may be an entire file. ;-)
295 die "Not in lines" unless defined $self->{'lines'};
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
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";
316 die "Duh: Filesize $cnt" if $cnt !~ /^\d+$/;
321 my $num = $self->{'socketi'}->read($buf,$cnt);
322 die "Server: Filesize $cnt: $num: $!\n" if not defined $num or $num<=0;
327 } elsif($line =~ s/^ //) {
329 $res += length($line);
330 } elsif($line =~ /^M\b/) {
332 } elsif($line =~ /^Mbinary\b/) {
334 die "EOF from server after 'Mbinary'" unless defined ($cnt = $self->readline());
336 die "Duh: Mbinary $cnt" if $cnt !~ /^\d+$/ or $cnt<1;
340 my $num = $self->{'socketi'}->read($buf,$cnt);
341 die "S: Mbinary $cnt: $num: $!\n" if not defined $num or $num<=0;
349 # print STDERR "S: ok (".length($res).")\n";
351 } elsif($line =~ s/^E //) {
352 # print STDERR "S: $line\n";
353 } elsif($line =~ /^Remove-entry /i) {
354 $line = $self->readline(); # filename
355 $line = $self->readline(); # OK
357 die "Unknown: $line" if $line ne "ok";
360 die "Unknown: $line\n";
367 my($self,$fn,$rev) = @_;
370 my ($fh, $name) = tempfile('gitcvs.XXXXXX',
371 DIR => File::Spec->tmpdir(), UNLINK => 1);
373 $self->_file($fn,$rev) and $res = $self->_line($fh);
376 print STDERR "Server has gone away while fetching $fn $rev, retrying...\n";
379 $self->_file($fn,$rev) or die "No file command send";
380 $res = $self->_line($fh);
381 die "Retry failed" unless defined $res;
385 return ($name, $res);
391 my $cvs = CVSconn->new($opt_d, $cvs_tree);
396 m#(\d{2,4})/(\d\d)/(\d\d)\s(\d\d):(\d\d)(?::(\d\d))?#
397 or die "Unparseable date: $d\n";
398 my $y=$1; $y-=1900 if $y>1900;
399 return timegm($6||0,$5,$4,$3,$2-1,$y);
407 for my $x(split(//,$mode)) {
412 } elsif($x eq "u") { $um |= 0700;
413 } elsif($x eq "g") { $um |= 0070;
414 } elsif($x eq "o") { $um |= 0007;
415 } elsif($x eq "r") { $mm |= 0444;
416 } elsif($x eq "w") { $mm |= 0222;
417 } elsif($x eq "x") { $mm |= 0111;
418 } elsif($x eq "=") { # do nothing
419 } else { die "Unknown mode: $mode\n";
433 sub get_headref($$) {
438 if (open(C,"$git_dir/refs/heads/$name")) {
442 or die "Cannot get head id for $name ($sha): $!\n";
449 or mkdir($git_tree,0777)
450 or die "Could not create $git_tree: $!";
453 my $last_branch = "";
454 my $orig_branch = "";
455 my $forward_master = 0;
458 my $git_dir = $ENV{"GIT_DIR"} || ".git";
459 $git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
460 $ENV{"GIT_DIR"} = $git_dir;
462 $orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
463 my ($git_ih, $git_index) = tempfile('gitXXXXXX', SUFFIX => '.idx',
464 DIR => File::Spec->tmpdir());
466 $ENV{GIT_INDEX_FILE} = $git_index;
467 unless(-d $git_dir) {
468 system("git-init-db");
469 die "Cannot init the GIT db at $git_tree: $?\n" if $?;
470 system("git-read-tree");
471 die "Cannot init an empty tree: $?\n" if $?;
473 $last_branch = $opt_o;
476 -f "$git_dir/refs/heads/$opt_o"
477 or die "Branch '$opt_o' does not exist.\n".
478 "Either use the correct '-o branch' option,\n".
479 "or import to a new repository.\n";
481 open(F, "git-symbolic-ref HEAD |") or
482 die "Cannot run git-symbolic-ref: $!\n";
483 chomp ($last_branch = <F>);
484 $last_branch = basename($last_branch);
486 unless($last_branch) {
487 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
488 $last_branch = "master";
490 $orig_branch = $last_branch;
491 if (-f "$git_dir/CVS2GIT_HEAD") {
494 Make sure your working directory corresponds to HEAD and remove CVS2GIT_HEAD.
497 git read-tree -m -u CVS2GIT_HEAD HEAD
500 system('cp', "$git_dir/HEAD", "$git_dir/CVS2GIT_HEAD");
503 $opt_o ne 'master' && -f "$git_dir/refs/heads/master" &&
504 system('cmp', '-s', "$git_dir/refs/heads/master",
505 "$git_dir/refs/heads/$opt_o") == 0;
508 system('git-read-tree', $last_branch);
509 die "read-tree failed: $?\n" if $?;
511 # Get the last import timestamps
512 opendir(D,"$git_dir/refs/heads");
513 while(defined(my $head = readdir(D))) {
514 next if $head =~ /^\./;
515 open(F,"$git_dir/refs/heads/$head")
516 or die "Bad head branch: $head: $!\n";
517 chomp(my $ftag = <F>);
519 open(F,"git-cat-file commit $ftag |");
521 next unless /^author\s.*\s(\d+)\s[-+]\d{4}$/;
522 $branch_date{$head} = $1;
531 or die "Could not create git subdir ($git_dir).\n";
533 # now we read (and possibly save) author-info as well
534 -f "$git_dir/cvs-authors" and
535 read_author_info("$git_dir/cvs-authors");
537 read_author_info($opt_A);
538 write_author_info("$git_dir/cvs-authors");
541 my $pid = open(CVS,"-|");
542 die "Cannot fork: $!\n" unless defined $pid;
545 @opt = split(/,/,$opt_p) if defined $opt_p;
546 unshift @opt, '-z', $opt_z if defined $opt_z;
547 unshift @opt, '-q' unless defined $opt_v;
548 unless (defined($opt_p) && $opt_p =~ m/--no-cvs-direct/) {
549 push @opt, '--cvs-direct';
554 exec("cvsps","--norc",@opt,"-u","-A",'--root',$opt_d,$cvs_tree);
555 die "Could not start cvsps: $!\n";
561 #---------------------
563 #Date: 1999/09/18 13:03:59
565 #Branch: STABLE-BRANCH-1-0
566 #Ancestor branch: HEAD
569 # See ChangeLog: Sat Sep 18 13:03:28 CEST 1999 Werner Koch
571 # README:1.57->1.57.2.1
572 # VERSION:1.96->1.96.2.1
574 #---------------------
578 my($patchset,$date,$author_name,$author_email,$branch,$ancestor,$tag,$logmsg);
579 my(@old,@new,@skipped);
585 @o2 = splice(@old,0,50);
590 system("git-update-index","--force-remove","--",@o2);
591 die "Cannot remove files: $?\n" if $?;
596 @n2 = splice(@new,0,10);
601 system("git-update-index","--add",
602 (map { ('--cacheinfo', @$_) } @n2));
603 die "Cannot add files: $?\n" if $?;
607 die "Cannot fork: $!" unless defined $pid;
609 exec("git-write-tree");
610 die "Cannot exec git-write-tree: $!\n";
612 chomp(my $tree = <C>);
614 or die "Cannot get tree id ($tree): $!\n";
616 or die "Error running git-write-tree: $?\n";
617 print "Tree ID $tree\n" if $opt_v;
620 if(open(C,"$git_dir/refs/heads/$last_branch")) {
621 chomp($parent = <C>);
623 length($parent) == 40
624 or die "Cannot get parent id ($parent): $!\n";
625 print "Parent ID $parent\n" if $opt_v;
628 my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
629 my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
631 die "Fork: $!\n" unless defined $pid;
635 open(OUT,">&STDOUT");
636 dup2($pw->fileno(),0);
637 dup2($pr->fileno(),1);
642 @par = ("-p",$parent) if $parent;
644 # loose detection of merges
645 # based on the commit msg
646 foreach my $rx (@mergerx) {
647 if ($logmsg =~ $rx) {
649 if ($mparent eq 'HEAD') { $mparent = $opt_o };
650 if ( -e "$git_dir/refs/heads/$mparent") {
651 $mparent = get_headref($mparent, $git_dir);
652 push @par, '-p', $mparent;
653 print OUT "Merge parent branch: $mparent\n" if $opt_v;
659 "GIT_AUTHOR_NAME=$author_name",
660 "GIT_AUTHOR_EMAIL=$author_email",
661 "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
662 "GIT_COMMITTER_NAME=$author_name",
663 "GIT_COMMITTER_EMAIL=$author_email",
664 "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
665 "git-commit-tree", $tree,@par);
666 die "Cannot exec git-commit-tree: $!\n";
671 # compatibility with git2cvs
672 substr($logmsg,32767) = "" if length($logmsg) > 32767;
673 $logmsg =~ s/[\s\n]+\z//;
676 $logmsg .= "\n\n\nSKIPPED:\n\t";
677 $logmsg .= join("\n\t", @skipped) . "\n";
680 print $pw "$logmsg\n"
681 or die "Error writing to git-commit-tree: $!\n";
684 print "Committed patch $patchset ($branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
685 chomp(my $cid = <$pr>);
687 or die "Cannot get commit id ($cid): $!\n";
688 print "Commit ID $cid\n" if $opt_v;
692 die "Error running git-commit-tree: $?\n" if $?;
694 open(C,">$git_dir/refs/heads/$branch")
695 or die "Cannot open branch $branch for update: $!\n";
697 or die "Cannot write branch $branch for update: $!\n";
699 or die "Cannot write branch $branch for update: $!\n";
702 my($in, $out) = ('','');
704 $xtag =~ s/\s+\*\*.*$//; # Remove stuff like ** INVALID ** and ** FUNKY **
705 $xtag =~ tr/_/\./ if ( $opt_u );
706 $xtag =~ s/[\/]/$opt_s/g;
708 my $pid = open2($in, $out, 'git-mktag');
709 print $out "object $cid\n".
712 "tagger $author_name <$author_email>\n"
713 or die "Cannot create tag object $xtag: $!\n";
715 or die "Cannot create tag object $xtag: $!\n";
720 if ( !close($in) or waitpid($pid, 0) != $pid or
721 $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
722 die "Cannot create tag object $xtag: $!\n";
726 open(C,">$git_dir/refs/tags/$xtag")
727 or die "Cannot create tag $xtag: $!\n";
729 or die "Cannot write tag $xtag: $!\n";
731 or die "Cannot write tag $xtag: $!\n";
733 print "Created tag '$xtag' on '$branch'\n" if $opt_v;
739 if($state == 0 and /^-+$/) {
741 } elsif($state == 0) {
744 } elsif(($state==0 or $state==1) and s/^PatchSet\s+//) {
747 } elsif($state == 2 and s/^Date:\s+//) {
750 print STDERR "Could not parse date: $_\n";
755 } elsif($state == 3 and s/^Author:\s+//) {
757 if (/^(.*?)\s+<(.*)>/) {
758 ($author_name, $author_email) = ($1, $2);
759 } elsif ($conv_author_name{$_}) {
760 $author_name = $conv_author_name{$_};
761 $author_email = $conv_author_email{$_};
763 $author_name = $author_email = $_;
766 } elsif($state == 4 and s/^Branch:\s+//) {
771 } elsif($state == 5 and s/^Ancestor branch:\s+//) {
774 $ancestor = $opt_o if $ancestor eq "HEAD";
776 } elsif($state == 5) {
780 } elsif($state == 6 and s/^Tag:\s+//) {
788 } elsif($state == 7 and /^Log:/) {
791 } elsif($state == 8 and /^Members:/) {
792 $branch = $opt_o if $branch eq "HEAD";
793 if(defined $branch_date{$branch} and $branch_date{$branch} >= $date) {
795 print "skip patchset $patchset: $date before $branch_date{$branch}\n" if $opt_v;
800 if(-f "$git_dir/refs/heads/$branch") {
801 print STDERR "Branch $branch already exists!\n";
805 unless(open(H,"$git_dir/refs/heads/$ancestor")) {
806 print STDERR "Branch $ancestor does not exist!\n";
812 unless(open(H,"> $git_dir/refs/heads/$branch")) {
813 print STDERR "Could not create branch $branch: $!\n";
818 or die "Could not write branch $branch: $!";
820 or die "Could not write branch $branch: $!";
822 if(($ancestor || $branch) ne $last_branch) {
823 print "Switching from $last_branch to $branch\n" if $opt_v;
824 system("git-read-tree", $branch);
825 die "read-tree failed: $?\n" if $?;
827 $last_branch = $branch if $branch ne $last_branch;
829 } elsif($state == 8) {
831 } elsif($state == 9 and /^\s+(.+?):(INITIAL|\d+(?:\.\d+)+)->(\d+(?:\.\d+)+)\s*$/) {
832 # VERSION:1.96->1.96.2.1
833 my $init = ($2 eq "INITIAL");
837 if ($opt_S && $fn =~ m/$opt_S/) {
838 print "SKIPPING $fn v $rev\n";
842 print "Fetching $fn v $rev\n" if $opt_v;
843 my ($tmpname, $size) = $cvs->file($fn,$rev);
846 print "Drop $fn\n" if $opt_v;
848 print "".($init ? "New" : "Update")." $fn: $size bytes\n" if $opt_v;
849 open my $F, '-|', "git-hash-object -w $tmpname"
850 or die "Cannot create object: $!\n";
854 my $mode = pmode($cvs->{'mode'});
855 push(@new,[$mode, $sha, $fn]); # may be resurrected!
858 } elsif($state == 9 and /^\s+(.+?):\d+(?:\.\d+)+->(\d+(?:\.\d+)+)\(DEAD\)\s*$/) {
862 print "Delete $fn\n" if $opt_v;
863 } elsif($state == 9 and /^\s*$/) {
865 } elsif(($state == 9 or $state == 10) and /^-+$/) {
868 } elsif($state == 11 and /^-+$/) {
870 } elsif(/^-+$/) { # end of unknown-line processing
872 } elsif($state != 11) { # ignore stuff when skipping
873 print "* UNKNOWN LINE * $_\n";
876 &$commit() if $branch and $state != 11;
880 if (defined $orig_git_index) {
881 $ENV{GIT_INDEX_FILE} = $orig_git_index;
883 delete $ENV{GIT_INDEX_FILE};
886 # Now switch back to the branch we were in before all of this happened
888 print "DONE\n" if $opt_v;
889 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
892 system('git-read-tree', '-m', '-u', 'CVS2GIT_HEAD', 'HEAD');
893 die "read-tree failed: $?\n" if $?;
896 $orig_branch = "master";
897 print "DONE; creating $orig_branch branch\n" if $opt_v;
898 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
899 unless -f "$git_dir/refs/heads/master";
900 system('git-update-ref', 'HEAD', "$orig_branch");
902 system('git checkout');
903 die "checkout failed: $?\n" if $?;
906 unlink("$git_dir/CVS2GIT_HEAD");