Fix remote CVS import.
[git/git.git] / git-cvsimport-script
CommitLineData
a57a9493 1#!/usr/bin/perl -w
9718a00b 2
a57a9493
MU
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
16use strict;
17use warnings;
18use Getopt::Std;
19use File::Path qw(mkpath);
20use File::Basename qw(basename dirname);
21use Time::Local;
2a3e1a85
MU
22use IO::Socket;
23use IO::Pipe;
24use POSIX qw(strftime dup2);
a57a9493
MU
25
26$SIG{'PIPE'}="IGNORE";
27$ENV{'TZ'}="UTC";
28
2a3e1a85 29our($opt_h,$opt_o,$opt_v,$opt_d);
a57a9493
MU
30
31sub usage() {
32 print STDERR <<END;
2a3e1a85
MU
33Usage: ${\basename $0} # fetch/update GIT from CVS
34 [ -o branch-for-HEAD ] [ -h ] [ -v ] [ -d CVSROOT ]
35 CVS_module [ GIT_repository ]
a57a9493
MU
36END
37 exit(1);
38}
39
2a3e1a85 40getopts("hqvo:d:") or usage();
a57a9493
MU
41usage if $opt_h;
42
2a3e1a85 43@ARGV == 1 or @ARGV == 2 or usage();
a57a9493
MU
44
45my($cvs_tree, $git_tree) = @ARGV;
46
2a3e1a85
MU
47if($opt_d) {
48 $ENV{"CVSROOT"} = $opt_d;
49} elsif($ENV{"CVSROOT"}) {
50 $opt_d = $ENV{"CVSROOT"};
51} else {
52 die "CVSROOT needs to be set";
53}
54$opt_o ||= "origin";
55$git_tree ||= ".";
56
a57a9493
MU
57select(STDERR); $|=1; select(STDOUT);
58
59
60package CVSconn;
61# Basic CVS dialog.
2a3e1a85 62# We're only interested in connecting and downloading, so ...
a57a9493
MU
63
64sub new {
65 my($what,$repo,$subdir) = @_;
66 $what=ref($what) if ref($what);
67
68 my $self = {};
69 $self->{'buffer'} = "";
70 bless($self,$what);
71
72 $repo =~ s#/+$##;
73 $self->{'fullrep'} = $repo;
74 $self->conn();
75
76 $self->{'subdir'} = $subdir;
77 $self->{'lines'} = undef;
78
79 return $self;
80}
81
82sub conn {
83 my $self = shift;
84 my $repo = $self->{'fullrep'};
85 if($repo =~ s/^:pserver:(?:(.*?)(?::(.*?))?@)?([^:\/]*)(?::(\d*))?//) {
86 my($user,$pass,$serv,$port) = ($1,$2,$3,$4);
87 $user="anonymous" unless defined $user;
2a3e1a85 88 my $rr2 = "-";
a57a9493
MU
89 unless($port) {
90 $rr2 = ":pserver:$user\@$serv:$repo";
91 $port=2401;
92 }
93 my $rr = ":pserver:$user\@$serv:$port$repo";
94
95 unless($pass) {
96 open(H,$ENV{'HOME'}."/.cvspass") and do {
97 # :pserver:cvs@mea.tmt.tele.fi:/cvsroot/zmailer Ah<Z
98 while(<H>) {
99 chomp;
100 s/^\/\d+\s+//;
101 my ($w,$p) = split(/\s/,$_,2);
102 if($w eq $rr or $w eq $rr2) {
103 $pass = $p;
104 last;
105 }
106 }
107 };
108 }
109 $pass="A" unless $pass;
110
a57a9493
MU
111 my $s = IO::Socket::INET->new(PeerHost => $serv, PeerPort => $port);
112 die "Socket to $serv: $!\n" unless defined $s;
113 $s->write("BEGIN AUTH REQUEST\n$repo\n$user\n$pass\nEND AUTH REQUEST\n")
114 or die "Write to $serv: $!\n";
115 $s->flush();
116
117 my $rep = <$s>;
118
119 if($rep ne "I LOVE YOU\n") {
120 $rep="<unknown>" unless $rep;
121 die "AuthReply: $rep\n";
122 }
123 $self->{'socketo'} = $s;
124 $self->{'socketi'} = $s;
125 } else { # local: Fork off our own cvs server.
a57a9493
MU
126 my $pr = IO::Pipe->new();
127 my $pw = IO::Pipe->new();
128 my $pid = fork();
129 die "Fork: $!\n" unless defined $pid;
130 unless($pid) {
131 $pr->writer();
132 $pw->reader();
a57a9493
MU
133 dup2($pw->fileno(),0);
134 dup2($pr->fileno(),1);
135 $pr->close();
136 $pw->close();
137 exec("cvs","server");
138 }
139 $pw->writer();
140 $pr->reader();
141 $self->{'socketo'} = $pw;
142 $self->{'socketi'} = $pr;
143 }
144 $self->{'socketo'}->write("Root $repo\n");
145
146 # Trial and error says that this probably is the minimum set
147 $self->{'socketo'}->write("Valid-responses ok error Valid-requests Mode M Mbinary E F Checked-in Created Updated Merged Removed\n");
148
149 $self->{'socketo'}->write("valid-requests\n");
150 $self->{'socketo'}->flush();
151
152 chomp(my $rep=$self->readline());
153 if($rep !~ s/^Valid-requests\s*//) {
154 $rep="<unknown>" unless $rep;
155 die "Expected Valid-requests from server, but got: $rep\n";
156 }
157 chomp(my $res=$self->readline());
158 die "validReply: $res\n" if $res ne "ok";
159
160 $self->{'socketo'}->write("UseUnchanged\n") if $rep =~ /\bUseUnchanged\b/;
161 $self->{'repo'} = $repo;
162}
163
164sub readline {
165 my($self) = @_;
166 return $self->{'socketi'}->getline();
167}
168
169sub _file {
170 # Request a file with a given revision.
171 # Trial and error says this is a good way to do it. :-/
172 my($self,$fn,$rev) = @_;
173 $self->{'socketo'}->write("Argument -N\n") or return undef;
174 $self->{'socketo'}->write("Argument -P\n") or return undef;
175 # $self->{'socketo'}->write("Argument -ko\n") or return undef;
176 # -ko: Linus' version doesn't use it
177 $self->{'socketo'}->write("Argument -r\n") or return undef;
178 $self->{'socketo'}->write("Argument $rev\n") or return undef;
179 $self->{'socketo'}->write("Argument --\n") or return undef;
180 $self->{'socketo'}->write("Argument $self->{'subdir'}/$fn\n") or return undef;
181 $self->{'socketo'}->write("Directory .\n") or return undef;
182 $self->{'socketo'}->write("$self->{'repo'}\n") or return undef;
183 $self->{'socketo'}->write("Sticky T1.1\n") or return undef;
184 $self->{'socketo'}->write("co\n") or return undef;
185 $self->{'socketo'}->flush() or return undef;
186 $self->{'lines'} = 0;
187 return 1;
188}
189sub _line {
190 # Read a line from the server.
191 # ... except that 'line' may be an entire file. ;-)
192 my($self) = @_;
193 die "Not in lines" unless defined $self->{'lines'};
194
195 my $line;
196 my $res="";
197 while(defined($line = $self->readline())) {
198 # M U gnupg-cvs-rep/AUTHORS
199 # Updated gnupg-cvs-rep/
200 # /daten/src/rsync/gnupg-cvs-rep/AUTHORS
201 # /AUTHORS/1.1///T1.1
202 # u=rw,g=rw,o=rw
203 # 0
204 # ok
205
206 if($line =~ s/^(?:Created|Updated) //) {
207 $line = $self->readline(); # path
208 $line = $self->readline(); # Entries line
209 my $mode = $self->readline(); chomp $mode;
210 $self->{'mode'} = $mode;
211 defined (my $cnt = $self->readline())
212 or die "EOF from server after 'Changed'\n";
213 chomp $cnt;
214 die "Duh: Filesize $cnt" if $cnt !~ /^\d+$/;
215 $line="";
216 $res="";
217 while($cnt) {
218 my $buf;
219 my $num = $self->{'socketi'}->read($buf,$cnt);
220 die "Server: Filesize $cnt: $num: $!\n" if not defined $num or $num<=0;
221 $res .= $buf;
222 $cnt -= $num;
223 }
224 } elsif($line =~ s/^ //) {
225 $res .= $line;
226 } elsif($line =~ /^M\b/) {
227 # output, do nothing
228 } elsif($line =~ /^Mbinary\b/) {
229 my $cnt;
230 die "EOF from server after 'Mbinary'" unless defined ($cnt = $self->readline());
231 chomp $cnt;
232 die "Duh: Mbinary $cnt" if $cnt !~ /^\d+$/ or $cnt<1;
233 $line="";
234 while($cnt) {
235 my $buf;
236 my $num = $self->{'socketi'}->read($buf,$cnt);
237 die "S: Mbinary $cnt: $num: $!\n" if not defined $num or $num<=0;
238 $res .= $buf;
239 $cnt -= $num;
240 }
241 } else {
242 chomp $line;
243 if($line eq "ok") {
244 # print STDERR "S: ok (".length($res).")\n";
245 return $res;
246 } elsif($line =~ s/^E //) {
247 # print STDERR "S: $line\n";
248 } else {
249 die "Unknown: $line\n";
250 }
251 }
252 }
253}
254sub file {
255 my($self,$fn,$rev) = @_;
256 my $res;
257
258 if ($self->_file($fn,$rev)) {
259 $res = $self->_line();
260 return $res if defined $res;
261 }
262
263 # retry
264 $self->conn();
265 $self->_file($fn,$rev)
266 or die "No file command send\n";
267 $res = $self->_line();
268 die "No input: $fn $rev\n" unless defined $res;
269 return $res;
270}
271
272
273package main;
274
2a3e1a85 275my $cvs = CVSconn->new($opt_d, $cvs_tree);
a57a9493
MU
276
277
278sub pdate($) {
279 my($d) = @_;
280 m#(\d{2,4})/(\d\d)/(\d\d)\s(\d\d):(\d\d)(?::(\d\d))?#
281 or die "Unparseable date: $d\n";
282 my $y=$1; $y-=1900 if $y>1900;
283 return timegm($6||0,$5,$4,$3,$2-1,$y);
9718a00b
TM
284}
285
a57a9493
MU
286sub pmode($) {
287 my($mode) = @_;
288 my $m = 0;
289 my $mm = 0;
290 my $um = 0;
291 for my $x(split(//,$mode)) {
292 if($x eq ",") {
293 $m |= $mm&$um;
294 $mm = 0;
295 $um = 0;
296 } elsif($x eq "u") { $um |= 0700;
297 } elsif($x eq "g") { $um |= 0070;
298 } elsif($x eq "o") { $um |= 0007;
299 } elsif($x eq "r") { $mm |= 0444;
300 } elsif($x eq "w") { $mm |= 0222;
301 } elsif($x eq "x") { $mm |= 0111;
302 } elsif($x eq "=") { # do nothing
303 } else { die "Unknown mode: $mode\n";
304 }
305 }
306 $m |= $mm&$um;
307 return $m;
308}
d4f8b390 309
a57a9493 310my $tmpcv = "/var/cache/cvs";
d4f8b390 311
a57a9493
MU
312sub getwd() {
313 my $pwd = `pwd`;
314 chomp $pwd;
315 return $pwd;
d4f8b390
LT
316}
317
a57a9493
MU
318-d $git_tree
319 or mkdir($git_tree,0777)
320 or die "Could not create $git_tree: $!";
321chdir($git_tree);
d4f8b390 322
a57a9493
MU
323my $last_branch = "";
324my %branch_date;
325
326my $git_dir = $ENV{"GIT_DIR"} || ".git";
327$git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
328$ENV{"GIT_DIR"} = $git_dir;
329unless(-d $git_dir) {
330 system("git-init-db");
331 die "Cannot init the GIT db at $git_tree: $?\n" if $?;
332 system("git-read-tree");
333 die "Cannot init an empty tree: $?\n" if $?;
334
335 $last_branch = $opt_o;
336} else {
337 $last_branch = basename(readlink("$git_dir/HEAD"));
338 die "Cannot read the last branch name: $!\n" unless $last_branch;
339
340 # Get the last import timestamps
341 opendir(D,"$git_dir/refs/heads");
342 while(defined(my $head = readdir(D))) {
343 next if $head =~ /^\./;
344 open(F,"$git_dir/refs/heads/$head")
345 or die "Bad head branch: $head: $!\n";
346 chomp(my $ftag = <F>);
347 close(F);
348 open(F,"git-cat-file commit $ftag |");
349 while(<F>) {
350 next unless /^author\s.*\s(\d+)\s[-+]\d{4}$/;
351 $branch_date{$head} = $1;
352 last;
353 }
354 close(F);
355 }
356 closedir(D);
357}
358
359-d $git_dir
360 or die "Could not create git subdir ($git_dir).\n";
361
362my $pid = open(CVS,"-|");
363die "Cannot fork: $!\n" unless defined $pid;
364unless($pid) {
365 exec("cvsps","-A","--cvs-direct",$cvs_tree);
366 die "Could not start cvsps: $!\n";
367}
368
369
370## cvsps output:
371#---------------------
372#PatchSet 314
373#Date: 1999/09/18 13:03:59
374#Author: wkoch
375#Branch: STABLE-BRANCH-1-0
376#Ancestor branch: HEAD
377#Tag: (none)
378#Log:
379# See ChangeLog: Sat Sep 18 13:03:28 CEST 1999 Werner Koch
380#Members:
381# README:1.57->1.57.2.1
382# VERSION:1.96->1.96.2.1
383#
384#---------------------
385
386my $state = 0;
387
388my($patchset,$date,$author,$branch,$ancestor,$tag,$logmsg);
389my(@old,@new);
390my $commit = sub {
391 my $pid;
392 system("git-update-cache","--force-remove","--",@old) if @old;
393 die "Cannot remove files: $?\n" if $?;
394 system("git-update-cache","--add","--",@new) if @new;
395 die "Cannot add files: $?\n" if $?;
396
397 $pid = open(C,"-|");
398 die "Cannot fork: $!" unless defined $pid;
399 unless($pid) {
400 exec("git-write-tree");
401 die "Cannot exec git-write-tree: $!\n";
402 }
403 chomp(my $tree = <C>);
404 length($tree) == 40
405 or die "Cannot get tree id ($tree): $!\n";
406 close(C)
407 or die "Error running git-write-tree: $?\n";
408 print "Tree ID $tree\n" if $opt_v;
409
410 my $parent = "";
411 if(open(C,"$git_dir/refs/heads/$last_branch")) {
412 chomp($parent = <C>);
413 close(C);
414 length($parent) == 40
415 or die "Cannot get parent id ($parent): $!\n";
416 print "Parent ID $parent\n" if $opt_v;
417 }
418
2a3e1a85
MU
419 my $pr = IO::Pipe->new();
420 my $pw = IO::Pipe->new();
421 $pid = fork();
422 die "Fork: $!\n" unless defined $pid;
a57a9493 423 unless($pid) {
2a3e1a85
MU
424 $pr->writer();
425 $pw->reader();
426 dup2($pw->fileno(),0);
427 dup2($pr->fileno(),1);
428 $pr->close();
429 $pw->close();
430
a57a9493
MU
431 my @par = ();
432 @par = ("-p",$parent) if $parent;
433 exec("env",
434 "GIT_AUTHOR_NAME=$author",
435 "GIT_AUTHOR_EMAIL=$author",
436 "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
437 "GIT_COMMITTER_NAME=$author",
438 "GIT_COMMITTER_EMAIL=$author",
439 "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
440 "git-commit-tree", $tree,@par);
441 die "Cannot exec git-commit-tree: $!\n";
442 }
2a3e1a85
MU
443 $pw->writer();
444 $pr->reader();
445 print $pw $logmsg
a57a9493 446 or die "Error writing to git-commit-tree: $!\n";
2a3e1a85
MU
447 $pw->close();
448
a57a9493 449 print "Committed patch $patchset ($branch)\n" if $opt_v;
2a3e1a85 450 chomp(my $cid = <$pr>);
a57a9493
MU
451 length($cid) == 40
452 or die "Cannot get commit id ($cid): $!\n";
453 print "Commit ID $cid\n" if $opt_v;
2a3e1a85
MU
454 $pr->close();
455
456 waitpid($pid,0);
457 die "Error running git-commit-tree: $?\n" if $?;
a57a9493
MU
458
459 open(C,">$git_dir/refs/heads/$branch")
460 or die "Cannot open branch $branch for update: $!\n";
461 print C "$cid\n"
462 or die "Cannot write branch $branch for update: $!\n";
463 close(C)
464 or die "Cannot write branch $branch for update: $!\n";
465
466 if($tag) {
467 open(C,">$git_dir/refs/tags/$tag")
468 or die "Cannot create tag $tag: $!\n";
469 print C "$cid\n"
470 or die "Cannot write tag $branch: $!\n";
471 close(C)
472 or die "Cannot write tag $branch: $!\n";
473 print "Created tag '$tag' on '$branch'\n" if $opt_v;
474 }
475
476 @old = ();
477 @new = ();
478};
479
480while(<CVS>) {
481 chomp;
482 if($state == 0 and /^-+$/) {
483 $state = 1;
484 } elsif($state == 0) {
485 $state = 1;
486 redo;
487 } elsif(($state==0 or $state==1) and s/^PatchSet\s+//) {
488 $patchset = 0+$_;
489 $state=2;
490 } elsif($state == 2 and s/^Date:\s+//) {
491 $date = pdate($_);
492 unless($date) {
493 print STDERR "Could not parse date: $_\n";
494 $state=0;
495 next;
496 }
497 $state=3;
498 } elsif($state == 3 and s/^Author:\s+//) {
499 s/\s+$//;
500 $author = $_;
501 $state = 4;
502 } elsif($state == 4 and s/^Branch:\s+//) {
503 s/\s+$//;
504 $branch = $_;
505 $state = 5;
506 } elsif($state == 5 and s/^Ancestor branch:\s+//) {
507 s/\s+$//;
508 $ancestor = $_;
509 $ancestor = $opt_o if $ancestor == "HEAD";
510 $state = 6;
511 } elsif($state == 5) {
512 $ancestor = undef;
513 $state = 6;
514 redo;
515 } elsif($state == 6 and s/^Tag:\s+//) {
516 s/\s+$//;
517 if($_ eq "(none)") {
518 $tag = undef;
519 } else {
520 $tag = $_;
521 }
522 $state = 7;
523 } elsif($state == 7 and /^Log:/) {
524 $logmsg = "";
525 $state = 8;
526 } elsif($state == 8 and /^Members:/) {
527 $branch = $opt_o if $branch eq "HEAD";
528 if(defined $branch_date{$branch} and $branch_date{$branch} >= $date) {
529 # skip
530 print "skip patchset $patchset: $date before $branch_date{$branch}\n";
531 $state = 11;
532 next;
533 }
534 if($ancestor) {
535 if(-f "$git_dir/refs/heads/$branch") {
536 print STDERR "Branch $branch already exists!\n";
537 $state=11;
538 next;
539 }
540 unless(open(H,"$git_dir/refs/heads/$ancestor")) {
541 print STDERR "Branch $ancestor does not exist!\n";
542 $state=11;
543 next;
544 }
545 chomp(my $id = <H>);
546 close(H);
547 unless(open(H,"> $git_dir/refs/heads/$branch")) {
548 print STDERR "Could not create branch $branch: $!\n";
549 $state=11;
550 next;
551 }
552 print H "$id\n"
553 or die "Could not write branch $branch: $!";
554 close(H)
555 or die "Could not write branch $branch: $!";
556 }
557 if(($ancestor || $branch) ne $last_branch) {
2a3e1a85 558 print "Switching from $last_branch to $branch\n" if $opt_v;
a57a9493
MU
559 system("git-read-tree -m -u $last_branch $branch");
560 die "read-tree $branch failed at $branch: $?\n" if $?;
561 }
562 if($branch ne $last_branch) {
563 unlink("$git_dir/HEAD");
564 symlink("refs/heads/$branch","$git_dir/HEAD");
565 $last_branch = $branch;
566 }
567 $state = 9;
568 } elsif($state == 8) {
569 $logmsg .= "$_\n";
2a3e1a85 570 } elsif($state == 9 and /^\s+(\S+):(INITIAL|\d(?:\.\d+)+)->(\d(?:\.\d+)+)\s*$/) {
a57a9493 571# VERSION:1.96->1.96.2.1
2a3e1a85 572 my $init = ($2 eq "INITIAL");
a57a9493 573 my $fn = $1;
2a3e1a85
MU
574 my $data = $cvs->file($fn,$3);
575 print "".($init ? "New" : "Update")." $fn: ".length($data)." bytes.\n";
a57a9493
MU
576 mkpath(dirname($fn),$opt_v);
577 open(F,"> ./$fn")
578 or die "Cannot create '$fn': $!\n";
579 print F $data
580 or die "Cannot write to '$fn': $!\n";
581 close(F)
582 or die "Cannot write to '$fn': $!\n";
583 chmod(pmode($cvs->{'mode'}), $fn);
584 push(@new,$fn); # may be resurrected!
585 } elsif($state == 9 and /^\s+(\S+):\d(?:\.\d+)+->(\d(?:\.\d+)+)\(DEAD\)\s*$/) {
586 push(@old,$1);
587 } elsif($state == 9 and /^\s*$/) {
588 $state = 10;
589 } elsif(($state == 9 or $state == 10) and /^-+$/) {
590 &$commit();
591 $state = 1;
592 } elsif($state == 11 and /^-+$/) {
593 $state = 1;
594 } elsif(/^-+$/) { # end of unknown-line processing
595 $state = 1;
596 } elsif($state != 11) { # ignore stuff when skipping
597 print "* UNKNOWN LINE * $_\n";
598 }
599}
600&$commit() if $branch and $state != 11;
d4f8b390 601
a57a9493 602print "DONE\n" if $opt_v;