Merge branch 'maint-1.5.1' into maint
[git/git.git] / git-cvsimport.perl
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;
79ee456c 19use File::Spec;
7ccd9009 20use File::Temp qw(tempfile tmpnam);
a57a9493
MU
21use File::Path qw(mkpath);
22use File::Basename qw(basename dirname);
23use Time::Local;
2a3e1a85
MU
24use IO::Socket;
25use IO::Pipe;
e49289df 26use POSIX qw(strftime dup2 ENOENT);
0d821d4d 27use IPC::Open2;
a57a9493
MU
28
29$SIG{'PIPE'}="IGNORE";
30$ENV{'TZ'}="UTC";
31
ded9f400 32our ($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);
ffd97f3a 33my (%conv_author_name, %conv_author_email);
a57a9493 34
7bf77644
FL
35sub usage(;$) {
36 my $msg = shift;
37 print(STDERR "Error: $msg\n") if $msg;
a57a9493 38 print STDERR <<END;
2a3e1a85 39Usage: ${\basename $0} # fetch/update GIT from CVS
ffd97f3a 40 [-o branch-for-HEAD] [-h] [-v] [-d CVSROOT] [-A author-conv-file]
edbe4466
FL
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]
a57a9493
MU
44END
45 exit(1);
46}
47
ffd97f3a
AE
48sub read_author_info($) {
49 my ($file) = @_;
50 my $user;
51 open my $f, '<', "$file" or die("Failed to open $file: $!\n");
52
53 while (<$f>) {
8cd16211 54 # Expected format is this:
ffd97f3a 55 # exon=Andreas Ericsson <ae@op5.se>
8cd16211 56 if (m/^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/) {
ffd97f3a 57 $user = $1;
8cd16211
JH
58 $conv_author_name{$user} = $2;
59 $conv_author_email{$user} = $3;
ffd97f3a 60 }
8cd16211
JH
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;
69 }
70 elsif ($mapped =~ /^<?(.*)>?$/) {
71 $conv_author_name{$user} = $user;
72 $conv_author_email{$user} = $1;
73 }
74 }
75 # NEEDSWORK: Maybe warn on unrecognized lines?
ffd97f3a
AE
76 }
77 close ($f);
78}
79
80sub write_author_info($) {
81 my ($file) = @_;
82 open my $f, '>', $file or
83 die("Failed to open $file for writing: $!");
84
85 foreach (keys %conv_author_name) {
8cd16211 86 print $f "$_=$conv_author_name{$_} <$conv_author_email{$_}>\n";
ffd97f3a
AE
87 }
88 close ($f);
89}
90
ed35dece
JB
91# convert getopts specs for use by git-repo-config
92sub 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 !~ /:$/);
101
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;
108 }
109 }
110 }
111 if (@ARGV == 0) {
112 chomp(my $module = `git-repo-config --get cvsimport.module`);
113 push(@ARGV, $module);
114 }
115}
116
117my $opts = "haivmkuo:d:p:C:z:s:M:P:A:S:L:";
118read_repo_config($opts);
119getopts($opts) or usage();
a57a9493
MU
120usage if $opt_h;
121
7bf77644 122@ARGV <= 1 or usage("You can't specify more than one CVS module");
a57a9493 123
86d11cf2 124if ($opt_d) {
2a3e1a85 125 $ENV{"CVSROOT"} = $opt_d;
86d11cf2 126} elsif (-f 'CVS/Root') {
f9714a4a
SV
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;
86d11cf2 132} elsif ($ENV{"CVSROOT"}) {
2a3e1a85
MU
133 $opt_d = $ENV{"CVSROOT"};
134} else {
7bf77644 135 usage("CVSROOT needs to be set");
2a3e1a85
MU
136}
137$opt_o ||= "origin";
fbfd60d6 138$opt_s ||= "-";
ded9f400
ML
139$opt_a ||= 0;
140
f9714a4a 141my $git_tree = $opt_C;
2a3e1a85
MU
142$git_tree ||= ".";
143
f9714a4a
SV
144my $cvs_tree;
145if ($#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;
db4b6582 152 close $f;
f9714a4a 153} else {
7bf77644 154 usage("CVS module has to be specified");
f9714a4a
SV
155}
156
db4b6582
ML
157our @mergerx = ();
158if ($opt_m) {
159 @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
160}
161if ($opt_M) {
162 push (@mergerx, qr/$opt_M/);
163}
164
6211988f
ML
165# Remember UTC of our starting time
166# we'll want to avoid importing commits
167# that are too recent
168our $starttime = time();
169
a57a9493
MU
170select(STDERR); $|=1; select(STDOUT);
171
172
173package CVSconn;
174# Basic CVS dialog.
2a3e1a85 175# We're only interested in connecting and downloading, so ...
a57a9493 176
2eb6d82e
SV
177use File::Spec;
178use File::Temp qw(tempfile);
f65ae603
MU
179use POSIX qw(strftime dup2);
180
a57a9493 181sub new {
86d11cf2 182 my ($what,$repo,$subdir) = @_;
a57a9493
MU
183 $what=ref($what) if ref($what);
184
185 my $self = {};
186 $self->{'buffer'} = "";
187 bless($self,$what);
188
189 $repo =~ s#/+$##;
190 $self->{'fullrep'} = $repo;
191 $self->conn();
192
193 $self->{'subdir'} = $subdir;
194 $self->{'lines'} = undef;
195
196 return $self;
197}
198
199sub conn {
200 my $self = shift;
201 my $repo = $self->{'fullrep'};
86d11cf2
JH
202 if ($repo =~ s/^:pserver(?:([^:]*)):(?:(.*?)(?::(.*?))?@)?([^:\/]*)(?::(\d*))?//) {
203 my ($param,$user,$pass,$serv,$port) = ($1,$2,$3,$4,$5);
73bcf533 204
86d11cf2
JH
205 my ($proxyhost,$proxyport);
206 if ($param && ($param =~ m/proxy=([^;]+)/)) {
73bcf533
IA
207 $proxyhost = $1;
208 # Default proxyport, if not specified, is 8080.
209 $proxyport = 8080;
86d11cf2 210 if ($ENV{"CVS_PROXY_PORT"}) {
73bcf533
IA
211 $proxyport = $ENV{"CVS_PROXY_PORT"};
212 }
86d11cf2 213 if ($param =~ m/proxyport=([^;]+)/) {
73bcf533
IA
214 $proxyport = $1;
215 }
216 }
217
a57a9493 218 $user="anonymous" unless defined $user;
2a3e1a85 219 my $rr2 = "-";
86d11cf2 220 unless ($port) {
a57a9493
MU
221 $rr2 = ":pserver:$user\@$serv:$repo";
222 $port=2401;
223 }
224 my $rr = ":pserver:$user\@$serv:$port$repo";
225
86d11cf2 226 unless ($pass) {
a57a9493
MU
227 open(H,$ENV{'HOME'}."/.cvspass") and do {
228 # :pserver:cvs@mea.tmt.tele.fi:/cvsroot/zmailer Ah<Z
86d11cf2 229 while (<H>) {
a57a9493
MU
230 chomp;
231 s/^\/\d+\s+//;
232 my ($w,$p) = split(/\s/,$_,2);
86d11cf2 233 if ($w eq $rr or $w eq $rr2) {
a57a9493
MU
234 $pass = $p;
235 last;
236 }
237 }
238 };
239 }
240 $pass="A" unless $pass;
241
73bcf533 242 my ($s, $rep);
86d11cf2 243 if ($proxyhost) {
73bcf533
IA
244
245 # Use a HTTP Proxy. Only works for HTTP proxies that
246 # don't require user authentication
247 #
248 # See: http://www.ietf.org/rfc/rfc2817.txt
249
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();
255
256 $rep = <$s>;
257
258 # The answer should look like 'HTTP/1.x 2yy ....'
86d11cf2 259 if (!($rep =~ m#^HTTP/1\.. 2[0-9][0-9]#)) {
73bcf533
IA
260 die "Proxy connect: $rep\n";
261 }
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");
268 }
269 } else {
270 $s = IO::Socket::INET->new(PeerHost => $serv, PeerPort => $port);
271 die "Socket to $serv: $!\n" unless defined $s;
272 }
273
a57a9493
MU
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();
277
73bcf533 278 $rep = <$s>;
a57a9493 279
86d11cf2 280 if ($rep ne "I LOVE YOU\n") {
a57a9493
MU
281 $rep="<unknown>" unless $rep;
282 die "AuthReply: $rep\n";
283 }
284 $self->{'socketo'} = $s;
285 $self->{'socketi'} = $s;
34155390 286 } else { # local or ext: Fork off our own cvs server.
a57a9493
MU
287 my $pr = IO::Pipe->new();
288 my $pw = IO::Pipe->new();
289 my $pid = fork();
290 die "Fork: $!\n" unless defined $pid;
8d0ea311
SV
291 my $cvs = 'cvs';
292 $cvs = $ENV{CVS_SERVER} if exists $ENV{CVS_SERVER};
34155390
SV
293 my $rsh = 'rsh';
294 $rsh = $ENV{CVS_RSH} if exists $ENV{CVS_RSH};
295
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);
303 }
304 if (!$local) {
305 if ($user) {
306 unshift @cvs, $rsh, '-l', $user, $host;
307 } else {
308 unshift @cvs, $rsh, $host;
309 }
310 }
311
86d11cf2 312 unless ($pid) {
a57a9493
MU
313 $pr->writer();
314 $pw->reader();
a57a9493
MU
315 dup2($pw->fileno(),0);
316 dup2($pr->fileno(),1);
317 $pr->close();
318 $pw->close();
34155390 319 exec(@cvs);
a57a9493
MU
320 }
321 $pw->writer();
322 $pr->reader();
323 $self->{'socketo'} = $pw;
324 $self->{'socketi'} = $pr;
325 }
326 $self->{'socketo'}->write("Root $repo\n");
327
328 # Trial and error says that this probably is the minimum set
b0921331 329 $self->{'socketo'}->write("Valid-responses ok error Valid-requests Mode M Mbinary E Checked-in Created Updated Merged Removed\n");
a57a9493
MU
330
331 $self->{'socketo'}->write("valid-requests\n");
332 $self->{'socketo'}->flush();
333
334 chomp(my $rep=$self->readline());
86d11cf2 335 if ($rep !~ s/^Valid-requests\s*//) {
a57a9493
MU
336 $rep="<unknown>" unless $rep;
337 die "Expected Valid-requests from server, but got: $rep\n";
338 }
339 chomp(my $res=$self->readline());
340 die "validReply: $res\n" if $res ne "ok";
341
342 $self->{'socketo'}->write("UseUnchanged\n") if $rep =~ /\bUseUnchanged\b/;
343 $self->{'repo'} = $repo;
344}
345
346sub readline {
86d11cf2 347 my ($self) = @_;
a57a9493
MU
348 return $self->{'socketi'}->getline();
349}
350
351sub _file {
352 # Request a file with a given revision.
353 # Trial and error says this is a good way to do it. :-/
86d11cf2 354 my ($self,$fn,$rev) = @_;
a57a9493
MU
355 $self->{'socketo'}->write("Argument -N\n") or return undef;
356 $self->{'socketo'}->write("Argument -P\n") or return undef;
abe05822
ML
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;
360 }
a57a9493
MU
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;
4f7c0caa 367 # $self->{'socketo'}->write("Sticky T1.0\n") or return undef;
a57a9493
MU
368 $self->{'socketo'}->write("co\n") or return undef;
369 $self->{'socketo'}->flush() or return undef;
370 $self->{'lines'} = 0;
371 return 1;
372}
373sub _line {
374 # Read a line from the server.
375 # ... except that 'line' may be an entire file. ;-)
86d11cf2 376 my ($self, $fh) = @_;
a57a9493
MU
377 die "Not in lines" unless defined $self->{'lines'};
378
379 my $line;
2eb6d82e 380 my $res=0;
86d11cf2 381 while (defined($line = $self->readline())) {
a57a9493
MU
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
387 # 0
388 # ok
389
86d11cf2 390 if ($line =~ s/^(?:Created|Updated) //) {
a57a9493
MU
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="";
55cad842 400 $res = $self->_fetchfile($fh, $cnt);
86d11cf2 401 } elsif ($line =~ s/^ //) {
2eb6d82e
SV
402 print $fh $line;
403 $res += length($line);
86d11cf2 404 } elsif ($line =~ /^M\b/) {
a57a9493 405 # output, do nothing
86d11cf2 406 } elsif ($line =~ /^Mbinary\b/) {
a57a9493
MU
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="";
55cad842 412 $res += $self->_fetchfile($fh, $cnt);
a57a9493
MU
413 } else {
414 chomp $line;
86d11cf2 415 if ($line eq "ok") {
a57a9493
MU
416 # print STDERR "S: ok (".length($res).")\n";
417 return $res;
86d11cf2 418 } elsif ($line =~ s/^E //) {
a57a9493 419 # print STDERR "S: $line\n";
86d11cf2 420 } elsif ($line =~ /^(Remove-entry|Removed) /i) {
8b8840e0
MU
421 $line = $self->readline(); # filename
422 $line = $self->readline(); # OK
423 chomp $line;
424 die "Unknown: $line" if $line ne "ok";
425 return -1;
a57a9493
MU
426 } else {
427 die "Unknown: $line\n";
428 }
429 }
430 }
39ba7d54 431 return undef;
a57a9493
MU
432}
433sub file {
86d11cf2 434 my ($self,$fn,$rev) = @_;
a57a9493
MU
435 my $res;
436
2eb6d82e
SV
437 my ($fh, $name) = tempfile('gitcvs.XXXXXX',
438 DIR => File::Spec->tmpdir(), UNLINK => 1);
439
440 $self->_file($fn,$rev) and $res = $self->_line($fh);
441
442 if (!defined $res) {
39ba7d54
MM
443 print STDERR "Server has gone away while fetching $fn $rev, retrying...\n";
444 truncate $fh, 0;
2eb6d82e 445 $self->conn();
39ba7d54 446 $self->_file($fn,$rev) or die "No file command send";
2eb6d82e 447 $res = $self->_line($fh);
39ba7d54 448 die "Retry failed" unless defined $res;
a57a9493 449 }
c619ad51 450 close ($fh);
a57a9493 451
2eb6d82e 452 return ($name, $res);
a57a9493 453}
55cad842
ML
454sub _fetchfile {
455 my ($self, $fh, $cnt) = @_;
61efa5e3 456 my $res = 0;
55cad842 457 my $bufsize = 1024 * 1024;
86d11cf2 458 while ($cnt) {
55cad842
ML
459 if ($bufsize > $cnt) {
460 $bufsize = $cnt;
461 }
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;
468 }
469 return $res;
470}
a57a9493
MU
471
472
473package main;
474
2a3e1a85 475my $cvs = CVSconn->new($opt_d, $cvs_tree);
a57a9493
MU
476
477
478sub pdate($) {
86d11cf2 479 my ($d) = @_;
a57a9493
MU
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);
9718a00b
TM
484}
485
a57a9493 486sub pmode($) {
86d11cf2 487 my ($mode) = @_;
a57a9493
MU
488 my $m = 0;
489 my $mm = 0;
490 my $um = 0;
491 for my $x(split(//,$mode)) {
86d11cf2 492 if ($x eq ",") {
a57a9493
MU
493 $m |= $mm&$um;
494 $mm = 0;
495 $um = 0;
86d11cf2
JH
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
a57a9493
MU
503 } else { die "Unknown mode: $mode\n";
504 }
505 }
506 $m |= $mm&$um;
507 return $m;
508}
d4f8b390 509
a57a9493
MU
510sub getwd() {
511 my $pwd = `pwd`;
512 chomp $pwd;
513 return $pwd;
d4f8b390
LT
514}
515
e73aefe4
JK
516sub is_sha1 {
517 my $s = shift;
518 return $s =~ /^[a-f0-9]{40}$/;
519}
db4b6582 520
e73aefe4 521sub get_headref ($$) {
db4b6582
ML
522 my $name = shift;
523 my $git_dir = shift;
db4b6582 524
e73aefe4 525 my $f = "$git_dir/refs/heads/$name";
86d11cf2 526 if (open(my $fh, $f)) {
e73aefe4
JK
527 chomp(my $r = <$fh>);
528 is_sha1($r) or die "Cannot get head id for $name ($r): $!";
529 return $r;
db4b6582 530 }
e73aefe4
JK
531 die "unable to open $f: $!" unless $! == POSIX::ENOENT;
532 return undef;
db4b6582
ML
533}
534
a57a9493
MU
535-d $git_tree
536 or mkdir($git_tree,0777)
537 or die "Could not create $git_tree: $!";
538chdir($git_tree);
d4f8b390 539
a57a9493 540my $last_branch = "";
46541669 541my $orig_branch = "";
a57a9493 542my %branch_date;
8a5f2eac 543my $tip_at_start = undef;
a57a9493
MU
544
545my $git_dir = $ENV{"GIT_DIR"} || ".git";
546$git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
547$ENV{"GIT_DIR"} = $git_dir;
79ee456c
SV
548my $orig_git_index;
549$orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
8f732649
ML
550
551my %index; # holds filenames of one index per branch
061303f0 552
86d11cf2 553unless (-d $git_dir) {
5c94f87e 554 system("git-init");
a57a9493
MU
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 $?;
558
559 $last_branch = $opt_o;
46541669 560 $orig_branch = "";
a57a9493 561} else {
866d1310 562 -f "$git_dir/refs/heads/$opt_o"
4c24e089
MU
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";
566
8366a10a
PR
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);
86d11cf2 572 unless ($last_branch) {
46541669
MU
573 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
574 $last_branch = "master";
575 }
576 $orig_branch = $last_branch;
8a5f2eac 577 $tip_at_start = `git-rev-parse --verify HEAD`;
a57a9493
MU
578
579 # Get the last import timestamps
1f24c587
AW
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";
86d11cf2 583 while (defined(my $entry = <H>)) {
1f24c587
AW
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;
a57a9493 589 }
1f24c587 590 close(H);
a57a9493
MU
591}
592
593-d $git_dir
594 or die "Could not create git subdir ($git_dir).\n";
595
ffd97f3a
AE
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");
599if ($opt_A) {
600 read_author_info($opt_A);
601 write_author_info("$git_dir/cvs-authors");
602}
603
2f57c697
ML
604
605#
606# run cvsps into a file unless we are getting
607# it passed as a file via $opt_P
608#
4083c2fc 609my $cvspsfile;
2f57c697
ML
610unless ($opt_P) {
611 print "Running cvsps...\n" if $opt_v;
612 my $pid = open(CVSPS,"-|");
4083c2fc 613 my $cvspsfh;
2f57c697 614 die "Cannot fork: $!\n" unless defined $pid;
86d11cf2 615 unless ($pid) {
2f57c697
ML
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';
622 }
623 exec("cvsps","--norc",@opt,"-u","-A",'--root',$opt_d,$cvs_tree);
624 die "Could not start cvsps: $!\n";
df73e9c6 625 }
4083c2fc
ML
626 ($cvspsfh, $cvspsfile) = tempfile('gitXXXXXX', SUFFIX => '.cvsps',
627 DIR => File::Spec->tmpdir());
2f57c697
ML
628 while (<CVSPS>) {
629 print $cvspsfh $_;
211dcac6 630 }
2f57c697
ML
631 close CVSPS;
632 close $cvspsfh;
4083c2fc
ML
633} else {
634 $cvspsfile = $opt_P;
a57a9493
MU
635}
636
4083c2fc 637open(CVS, "<$cvspsfile") or die $!;
2f57c697 638
a57a9493
MU
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
652#
653#---------------------
654
655my $state = 0;
656
e73aefe4
JK
657sub update_index (\@\@) {
658 my $old = shift;
659 my $new = shift;
6a1871e1
JK
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" }
e73aefe4 664 @$old),
6a1871e1 665 (map { '100' . sprintf('%o', $_->[0]) . " $_->[1]\t$_->[2]\0" }
e73aefe4 666 @$new)
6a1871e1
JK
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: $?";
e73aefe4 671}
a57a9493 672
e73aefe4
JK
673sub 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)
a57a9493
MU
680 or die "Error running git-write-tree: $?\n";
681 print "Tree ID $tree\n" if $opt_v;
e73aefe4
JK
682 return $tree;
683}
a57a9493 684
86d11cf2
JH
685my ($patchset,$date,$author_name,$author_email,$branch,$ancestor,$tag,$logmsg);
686my (@old,@new,@skipped,%ignorebranch);
71b08148
ML
687
688# commits that cvsps cannot place anywhere...
689$ignorebranch{'#CVSPS_NO_BRANCH'} = 1;
690
e73aefe4 691sub commit {
c5f448b0
ML
692 if ($branch eq $opt_o && !$index{branch} && !get_headref($branch, $git_dir)) {
693 # looks like an initial commit
5c94f87e 694 # use the index primed by git-init
c5f448b0
ML
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);
707 }
708 die "read-tree failed: $?\n" if $?;
709 }
710 }
711 $ENV{GIT_INDEX_FILE} = $index{$branch};
712
e73aefe4
JK
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;
718
719 my @commit_args;
720 push @commit_args, ("-p", $parent) if $parent;
721
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;
86d11cf2 727 if (my $sha1 = get_headref($mparent, $git_dir)) {
e73aefe4
JK
728 push @commit_args, '-p', $mparent;
729 print "Merge parent branch: $mparent\n" if $opt_v;
db4b6582 730 }
a57a9493 731 }
e73aefe4
JK
732
733 my $commit_date = strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date));
62bf0d96
JK
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;
e73aefe4 740 my $pid = open2(my $commit_read, my $commit_write,
e73aefe4 741 'git-commit-tree', $tree, @commit_args);
e371046b
MU
742
743 # compatibility with git2cvs
744 substr($logmsg,32767) = "" if length($logmsg) > 32767;
745 $logmsg =~ s/[\s\n]+\z//;
746
5179c8a5
ML
747 if (@skipped) {
748 $logmsg .= "\n\n\nSKIPPED:\n\t";
749 $logmsg .= join("\n\t", @skipped) . "\n";
f396f01f 750 @skipped = ();
5179c8a5
ML
751 }
752
e73aefe4 753 print($commit_write "$logmsg\n") && close($commit_write)
a57a9493 754 or die "Error writing to git-commit-tree: $!\n";
2a3e1a85 755
e73aefe4
JK
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";
a57a9493 759 print "Commit ID $cid\n" if $opt_v;
e73aefe4 760 close($commit_read);
2a3e1a85
MU
761
762 waitpid($pid,0);
763 die "Error running git-commit-tree: $?\n" if $?;
a57a9493 764
42277bc8 765 system("git-update-ref refs/heads/$branch $cid") == 0
a57a9493
MU
766 or die "Cannot write branch $branch for update: $!\n";
767
86d11cf2
JH
768 if ($tag) {
769 my ($in, $out) = ('','');
770 my ($xtag) = $tag;
0d821d4d
PA
771 $xtag =~ s/\s+\*\*.*$//; # Remove stuff like ** INVALID ** and ** FUNKY **
772 $xtag =~ tr/_/\./ if ( $opt_u );
34c99da2 773 $xtag =~ s/[\/]/$opt_s/g;
0d821d4d
PA
774
775 my $pid = open2($in, $out, 'git-mktag');
776 print $out "object $cid\n".
777 "type commit\n".
778 "tag $xtag\n".
94c23343 779 "tagger $author_name <$author_email>\n"
0d821d4d
PA
780 or die "Cannot create tag object $xtag: $!\n";
781 close($out)
782 or die "Cannot create tag object $xtag: $!\n";
783
784 my $tagobj = <$in>;
785 chomp $tagobj;
786
787 if ( !close($in) or waitpid($pid, 0) != $pid or
788 $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
789 die "Cannot create tag object $xtag: $!\n";
790 }
791
792
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";
a57a9493 797 close(C)
0d821d4d
PA
798 or die "Cannot write tag $xtag: $!\n";
799
800 print "Created tag '$xtag' on '$branch'\n" if $opt_v;
a57a9493 801 }
a57a9493
MU
802};
803
06918348 804my $commitcount = 1;
86d11cf2 805while (<CVS>) {
a57a9493 806 chomp;
86d11cf2 807 if ($state == 0 and /^-+$/) {
a57a9493 808 $state = 1;
86d11cf2 809 } elsif ($state == 0) {
a57a9493
MU
810 $state = 1;
811 redo;
86d11cf2 812 } elsif (($state==0 or $state==1) and s/^PatchSet\s+//) {
a57a9493
MU
813 $patchset = 0+$_;
814 $state=2;
86d11cf2 815 } elsif ($state == 2 and s/^Date:\s+//) {
a57a9493 816 $date = pdate($_);
86d11cf2 817 unless ($date) {
a57a9493
MU
818 print STDERR "Could not parse date: $_\n";
819 $state=0;
820 next;
821 }
822 $state=3;
86d11cf2 823 } elsif ($state == 3 and s/^Author:\s+//) {
a57a9493 824 s/\s+$//;
94c23343
JH
825 if (/^(.*?)\s+<(.*)>/) {
826 ($author_name, $author_email) = ($1, $2);
ffd97f3a
AE
827 } elsif ($conv_author_name{$_}) {
828 $author_name = $conv_author_name{$_};
829 $author_email = $conv_author_email{$_};
94c23343
JH
830 } else {
831 $author_name = $author_email = $_;
832 }
a57a9493 833 $state = 4;
86d11cf2 834 } elsif ($state == 4 and s/^Branch:\s+//) {
a57a9493 835 s/\s+$//;
fbfd60d6 836 s/[\/]/$opt_s/g;
a57a9493
MU
837 $branch = $_;
838 $state = 5;
86d11cf2 839 } elsif ($state == 5 and s/^Ancestor branch:\s+//) {
a57a9493
MU
840 s/\s+$//;
841 $ancestor = $_;
0fa2824f 842 $ancestor = $opt_o if $ancestor eq "HEAD";
a57a9493 843 $state = 6;
86d11cf2 844 } elsif ($state == 5) {
a57a9493
MU
845 $ancestor = undef;
846 $state = 6;
847 redo;
86d11cf2 848 } elsif ($state == 6 and s/^Tag:\s+//) {
a57a9493 849 s/\s+$//;
86d11cf2 850 if ($_ eq "(none)") {
a57a9493
MU
851 $tag = undef;
852 } else {
853 $tag = $_;
854 }
855 $state = 7;
86d11cf2 856 } elsif ($state == 7 and /^Log:/) {
a57a9493
MU
857 $logmsg = "";
858 $state = 8;
86d11cf2 859 } elsif ($state == 8 and /^Members:/) {
a57a9493 860 $branch = $opt_o if $branch eq "HEAD";
86d11cf2 861 if (defined $branch_date{$branch} and $branch_date{$branch} >= $date) {
a57a9493 862 # skip
9da07f34 863 print "skip patchset $patchset: $date before $branch_date{$branch}\n" if $opt_v;
a57a9493
MU
864 $state = 11;
865 next;
866 }
ded9f400 867 if (!$opt_a && $starttime - 300 - (defined $opt_z ? $opt_z : 300) <= $date) {
6211988f
ML
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;
875 }
71b08148
ML
876 if (exists $ignorebranch{$branch}) {
877 print STDERR "Skipping $branch\n";
878 $state = 11;
879 next;
880 }
86d11cf2
JH
881 if ($ancestor) {
882 if ($ancestor eq $branch) {
71b08148
ML
883 print STDERR "Branch $branch erroneously stems from itself -- changed ancestor to $opt_o\n";
884 $ancestor = $opt_o;
885 }
86d11cf2 886 if (-f "$git_dir/refs/heads/$branch") {
a57a9493
MU
887 print STDERR "Branch $branch already exists!\n";
888 $state=11;
889 next;
890 }
86d11cf2 891 unless (open(H,"$git_dir/refs/heads/$ancestor")) {
a57a9493 892 print STDERR "Branch $ancestor does not exist!\n";
71b08148 893 $ignorebranch{$branch} = 1;
a57a9493
MU
894 $state=11;
895 next;
896 }
897 chomp(my $id = <H>);
898 close(H);
86d11cf2 899 unless (open(H,"> $git_dir/refs/heads/$branch")) {
a57a9493 900 print STDERR "Could not create branch $branch: $!\n";
71b08148 901 $ignorebranch{$branch} = 1;
a57a9493
MU
902 $state=11;
903 next;
904 }
905 print H "$id\n"
906 or die "Could not write branch $branch: $!";
907 close(H)
908 or die "Could not write branch $branch: $!";
909 }
46e63efc 910 $last_branch = $branch if $branch ne $last_branch;
a57a9493 911 $state = 9;
86d11cf2 912 } elsif ($state == 8) {
a57a9493 913 $logmsg .= "$_\n";
86d11cf2 914 } elsif ($state == 9 and /^\s+(.+?):(INITIAL|\d+(?:\.\d+)+)->(\d+(?:\.\d+)+)\s*$/) {
a57a9493 915# VERSION:1.96->1.96.2.1
2a3e1a85 916 my $init = ($2 eq "INITIAL");
a57a9493 917 my $fn = $1;
f65ae603
MU
918 my $rev = $3;
919 $fn =~ s#^/+##;
5179c8a5
ML
920 if ($opt_S && $fn =~ m/$opt_S/) {
921 print "SKIPPING $fn v $rev\n";
922 push(@skipped, $fn);
923 next;
924 }
925 print "Fetching $fn v $rev\n" if $opt_v;
2eb6d82e 926 my ($tmpname, $size) = $cvs->file($fn,$rev);
86d11cf2 927 if ($size == -1) {
8b8840e0
MU
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;
dd27478f
JH
932 my $pid = open(my $F, '-|');
933 die $! unless defined $pid;
934 if (!$pid) {
935 exec("git-hash-object", "-w", $tmpname)
8b8840e0 936 or die "Cannot create object: $!\n";
dd27478f 937 }
8b8840e0
MU
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!
943 }
2eb6d82e 944 unlink($tmpname);
86d11cf2 945 } elsif ($state == 9 and /^\s+(.+?):\d+(?:\.\d+)+->(\d+(?:\.\d+)+)\(DEAD\)\s*$/) {
f65ae603
MU
946 my $fn = $1;
947 $fn =~ s#^/+##;
948 push(@old,$fn);
8b8840e0 949 print "Delete $fn\n" if $opt_v;
86d11cf2 950 } elsif ($state == 9 and /^\s*$/) {
a57a9493 951 $state = 10;
86d11cf2 952 } elsif (($state == 9 or $state == 10) and /^-+$/) {
4adcea99
LT
953 $commitcount++;
954 if ($opt_L && $commitcount > $opt_L) {
06918348
ML
955 last;
956 }
c4b16f8d 957 commit();
4adcea99
LT
958 if (($commitcount & 1023) == 0) {
959 system("git repack -a -d");
960 }
a57a9493 961 $state = 1;
86d11cf2 962 } elsif ($state == 11 and /^-+$/) {
a57a9493 963 $state = 1;
86d11cf2 964 } elsif (/^-+$/) { # end of unknown-line processing
a57a9493 965 $state = 1;
86d11cf2 966 } elsif ($state != 11) { # ignore stuff when skipping
a57a9493
MU
967 print "* UNKNOWN LINE * $_\n";
968 }
969}
c4b16f8d 970commit() if $branch and $state != 11;
d4f8b390 971
4083c2fc
ML
972unless ($opt_P) {
973 unlink($cvspsfile);
974}
975
efe4abd1
JM
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.
979my $line = `git-count-objects`;
980if ($line =~ /^(\d+) objects, (\d+) kilobytes$/) {
981 my ($n_objects, $kb) = ($1, $2);
982 1024 < $kb
983 and system("git repack -a -d");
984}
985
8f732649 986foreach my $git_index (values %index) {
c5f448b0
ML
987 if ($git_index ne '.git/index') {
988 unlink($git_index);
989 }
8f732649 990}
79ee456c 991
210569f9
SV
992if (defined $orig_git_index) {
993 $ENV{GIT_INDEX_FILE} = $orig_git_index;
994} else {
995 delete $ENV{GIT_INDEX_FILE};
996}
997
46541669 998# Now switch back to the branch we were in before all of this happened
86d11cf2 999if ($orig_branch) {
8a5f2eac
JH
1000 print "DONE.\n" if $opt_v;
1001 if ($opt_i) {
1002 exit 0;
1003 }
1004 my $tip_at_end = `git-rev-parse --verify HEAD`;
1005 if ($tip_at_start ne $tip_at_end) {
cb9594e2 1006 for ($tip_at_start, $tip_at_end) { chomp; }
8a5f2eac
JH
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 $?;
1011 }
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 $?;
1015 }
46541669
MU
1016} else {
1017 $orig_branch = "master";
1018 print "DONE; creating $orig_branch branch\n" if $opt_v;
a541211e 1019 system("git-update-ref", "refs/heads/master", "refs/heads/$opt_o")
46541669 1020 unless -f "$git_dir/refs/heads/master";
8366a10a 1021 system('git-update-ref', 'HEAD', "$orig_branch");
c1c774e7
SV
1022 unless ($opt_i) {
1023 system('git checkout');
1024 die "checkout failed: $?\n" if $?;
1025 }
46541669 1026}