THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1184 lines
31KB

  1. #!/usr/bin/perl
  2. # This tool is copyright (c) 2005, Matthias Urlichs.
  3. # It is released under the Gnu Public License, version 2.
  4. #
  5. # The basic idea is to aggregate CVS check-ins into related changes.
  6. # Fortunately, "cvsps" does that for us; all we have to do is to parse
  7. # its output.
  8. #
  9. # Checking out the files is done by a single long-running CVS connection
  10. # / server process.
  11. #
  12. # The head revision is on branch "origin" by default.
  13. # You can change that with the '-o' option.
  14. use 5.008;
  15. use strict;
  16. use warnings;
  17. use Getopt::Long;
  18. use File::Spec;
  19. use File::Temp qw(tempfile tmpnam);
  20. use File::Path qw(mkpath);
  21. use File::Basename qw(basename dirname);
  22. use Time::Local;
  23. use IO::Socket;
  24. use IO::Pipe;
  25. use POSIX qw(strftime tzset dup2 ENOENT);
  26. use IPC::Open2;
  27. use Git qw(get_tz_offset);
  28. $SIG{'PIPE'}="IGNORE";
  29. set_timezone('UTC');
  30. 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, $opt_r, $opt_R);
  31. my (%conv_author_name, %conv_author_email, %conv_author_tz);
  32. sub usage(;$) {
  33. my $msg = shift;
  34. print(STDERR "Error: $msg\n") if $msg;
  35. print STDERR <<END;
  36. usage: git cvsimport # fetch/update GIT from CVS
  37. [-o branch-for-HEAD] [-h] [-v] [-d CVSROOT] [-A author-conv-file]
  38. [-p opts-for-cvsps] [-P file] [-C GIT_repository] [-z fuzz] [-i] [-k]
  39. [-u] [-s subst] [-a] [-m] [-M regex] [-S regex] [-L commitlimit]
  40. [-r remote] [-R] [CVS_module]
  41. END
  42. exit(1);
  43. }
  44. sub read_author_info($) {
  45. my ($file) = @_;
  46. my $user;
  47. open my $f, '<', "$file" or die("Failed to open $file: $!\n");
  48. while (<$f>) {
  49. # Expected format is this:
  50. # exon=Andreas Ericsson <ae@op5.se>
  51. if (m/^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/) {
  52. $user = $1;
  53. $conv_author_name{$user} = $2;
  54. $conv_author_email{$user} = $3;
  55. }
  56. # or with an optional timezone:
  57. # spawn=Simon Pawn <spawn@frog-pond.org> America/Chicago
  58. elsif (m/^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*(\S+?)\s*$/) {
  59. $user = $1;
  60. $conv_author_name{$user} = $2;
  61. $conv_author_email{$user} = $3;
  62. $conv_author_tz{$user} = $4;
  63. }
  64. # However, we also read from CVSROOT/users format
  65. # to ease migration.
  66. elsif (/^(\w+):(['"]?)(.+?)\2\s*$/) {
  67. my $mapped;
  68. ($user, $mapped) = ($1, $3);
  69. if ($mapped =~ /^\s*(.*?)\s*<(.*)>\s*$/) {
  70. $conv_author_name{$user} = $1;
  71. $conv_author_email{$user} = $2;
  72. }
  73. elsif ($mapped =~ /^<?(.*)>?$/) {
  74. $conv_author_name{$user} = $user;
  75. $conv_author_email{$user} = $1;
  76. }
  77. }
  78. # NEEDSWORK: Maybe warn on unrecognized lines?
  79. }
  80. close ($f);
  81. }
  82. sub write_author_info($) {
  83. my ($file) = @_;
  84. open my $f, '>', $file or
  85. die("Failed to open $file for writing: $!");
  86. foreach (keys %conv_author_name) {
  87. print $f "$_=$conv_author_name{$_} <$conv_author_email{$_}>";
  88. print $f " $conv_author_tz{$_}" if ($conv_author_tz{$_});
  89. print $f "\n";
  90. }
  91. close ($f);
  92. }
  93. # Versions of perl before 5.10.0 may not automatically check $TZ each
  94. # time localtime is run (most platforms will do so only the first time).
  95. # We can work around this by using tzset() to update the internal
  96. # variable whenever we change the environment.
  97. sub set_timezone {
  98. $ENV{TZ} = shift;
  99. tzset();
  100. }
  101. # convert getopts specs for use by git config
  102. my %longmap = (
  103. 'A:' => 'authors-file',
  104. 'M:' => 'merge-regex',
  105. 'P:' => undef,
  106. 'R' => 'track-revisions',
  107. 'S:' => 'ignore-paths',
  108. );
  109. sub read_repo_config {
  110. # Split the string between characters, unless there is a ':'
  111. # So "abc:de" becomes ["a", "b", "c:", "d", "e"]
  112. my @opts = split(/ *(?!:)/, shift);
  113. foreach my $o (@opts) {
  114. my $key = $o;
  115. $key =~ s/://g;
  116. my $arg = 'git config';
  117. $arg .= ' --bool' if ($o !~ /:$/);
  118. my $ckey = $key;
  119. if (exists $longmap{$o}) {
  120. # An uppercase option like -R cannot be
  121. # expressed in the configuration, as the
  122. # variable names are downcased.
  123. $ckey = $longmap{$o};
  124. next if (! defined $ckey);
  125. $ckey =~ s/-//g;
  126. }
  127. chomp(my $tmp = `$arg --get cvsimport.$ckey`);
  128. if ($tmp && !($arg =~ /--bool/ && $tmp eq 'false')) {
  129. no strict 'refs';
  130. my $opt_name = "opt_" . $key;
  131. if (!$$opt_name) {
  132. $$opt_name = $tmp;
  133. }
  134. }
  135. }
  136. }
  137. my $opts = "haivmkuo:d:p:r:C:z:s:M:P:A:S:L:R";
  138. read_repo_config($opts);
  139. Getopt::Long::Configure( 'no_ignore_case', 'bundling' );
  140. # turn the Getopt::Std specification in a Getopt::Long one,
  141. # with support for multiple -M options
  142. GetOptions( map { s/:/=s/; /M/ ? "$_\@" : $_ } split( /(?!:)/, $opts ) )
  143. or usage();
  144. usage if $opt_h;
  145. if (@ARGV == 0) {
  146. chomp(my $module = `git config --get cvsimport.module`);
  147. push(@ARGV, $module) if $? == 0;
  148. }
  149. @ARGV <= 1 or usage("You can't specify more than one CVS module");
  150. if ($opt_d) {
  151. $ENV{"CVSROOT"} = $opt_d;
  152. } elsif (-f 'CVS/Root') {
  153. open my $f, '<', 'CVS/Root' or die 'Failed to open CVS/Root';
  154. $opt_d = <$f>;
  155. chomp $opt_d;
  156. close $f;
  157. $ENV{"CVSROOT"} = $opt_d;
  158. } elsif ($ENV{"CVSROOT"}) {
  159. $opt_d = $ENV{"CVSROOT"};
  160. } else {
  161. usage("CVSROOT needs to be set");
  162. }
  163. $opt_s ||= "-";
  164. $opt_a ||= 0;
  165. my $git_tree = $opt_C;
  166. $git_tree ||= ".";
  167. my $remote;
  168. if (defined $opt_r) {
  169. $remote = 'refs/remotes/' . $opt_r;
  170. $opt_o ||= "master";
  171. } else {
  172. $opt_o ||= "origin";
  173. $remote = 'refs/heads';
  174. }
  175. my $cvs_tree;
  176. if ($#ARGV == 0) {
  177. $cvs_tree = $ARGV[0];
  178. } elsif (-f 'CVS/Repository') {
  179. open my $f, '<', 'CVS/Repository' or
  180. die 'Failed to open CVS/Repository';
  181. $cvs_tree = <$f>;
  182. chomp $cvs_tree;
  183. close $f;
  184. } else {
  185. usage("CVS module has to be specified");
  186. }
  187. our @mergerx = ();
  188. if ($opt_m) {
  189. @mergerx = ( qr/\b(?:from|of|merge|merging|merged) ([-\w]+)/i );
  190. }
  191. if (@opt_M) {
  192. push (@mergerx, map { qr/$_/ } @opt_M);
  193. }
  194. # Remember UTC of our starting time
  195. # we'll want to avoid importing commits
  196. # that are too recent
  197. our $starttime = time();
  198. select(STDERR); $|=1; select(STDOUT);
  199. package CVSconn;
  200. # Basic CVS dialog.
  201. # We're only interested in connecting and downloading, so ...
  202. use File::Spec;
  203. use File::Temp qw(tempfile);
  204. use POSIX qw(strftime dup2);
  205. sub new {
  206. my ($what,$repo,$subdir) = @_;
  207. $what=ref($what) if ref($what);
  208. my $self = {};
  209. $self->{'buffer'} = "";
  210. bless($self,$what);
  211. $repo =~ s#/+$##;
  212. $self->{'fullrep'} = $repo;
  213. $self->conn();
  214. $self->{'subdir'} = $subdir;
  215. $self->{'lines'} = undef;
  216. return $self;
  217. }
  218. sub find_password_entry {
  219. my ($cvspass, @cvsroot) = @_;
  220. my ($file, $delim) = @$cvspass;
  221. my $pass;
  222. local ($_);
  223. if (open(my $fh, $file)) {
  224. # :pserver:cvs@mea.tmt.tele.fi:/cvsroot/zmailer Ah<Z
  225. CVSPASSFILE:
  226. while (<$fh>) {
  227. chomp;
  228. s/^\/\d+\s+//;
  229. my ($w, $p) = split($delim,$_,2);
  230. for my $cvsroot (@cvsroot) {
  231. if ($w eq $cvsroot) {
  232. $pass = $p;
  233. last CVSPASSFILE;
  234. }
  235. }
  236. }
  237. close($fh);
  238. }
  239. return $pass;
  240. }
  241. sub conn {
  242. my $self = shift;
  243. my $repo = $self->{'fullrep'};
  244. if ($repo =~ s/^:pserver(?:([^:]*)):(?:(.*?)(?::(.*?))?@)?([^:\/]*)(?::(\d*))?//) {
  245. my ($param,$user,$pass,$serv,$port) = ($1,$2,$3,$4,$5);
  246. my ($proxyhost,$proxyport);
  247. if ($param && ($param =~ m/proxy=([^;]+)/)) {
  248. $proxyhost = $1;
  249. # Default proxyport, if not specified, is 8080.
  250. $proxyport = 8080;
  251. if ($ENV{"CVS_PROXY_PORT"}) {
  252. $proxyport = $ENV{"CVS_PROXY_PORT"};
  253. }
  254. if ($param =~ m/proxyport=([^;]+)/) {
  255. $proxyport = $1;
  256. }
  257. }
  258. $repo ||= '/';
  259. # if username is not explicit in CVSROOT, then use current user, as cvs would
  260. $user=(getlogin() || $ENV{'LOGNAME'} || $ENV{'USER'} || "anonymous") unless $user;
  261. my $rr2 = "-";
  262. unless ($port) {
  263. $rr2 = ":pserver:$user\@$serv:$repo";
  264. $port=2401;
  265. }
  266. my $rr = ":pserver:$user\@$serv:$port$repo";
  267. if ($pass) {
  268. $pass = $self->_scramble($pass);
  269. } else {
  270. my @cvspass = ([$ENV{'HOME'}."/.cvspass", qr/\s/],
  271. [$ENV{'HOME'}."/.cvs/cvspass", qr/=/]);
  272. my @loc = ();
  273. foreach my $cvspass (@cvspass) {
  274. my $p = find_password_entry($cvspass, $rr, $rr2);
  275. if ($p) {
  276. push @loc, $cvspass->[0];
  277. $pass = $p;
  278. }
  279. }
  280. if (1 < @loc) {
  281. die("Multiple cvs password files have ".
  282. "entries for CVSROOT $opt_d: @loc");
  283. } elsif (!$pass) {
  284. $pass = "A";
  285. }
  286. }
  287. my ($s, $rep);
  288. if ($proxyhost) {
  289. # Use a HTTP Proxy. Only works for HTTP proxies that
  290. # don't require user authentication
  291. #
  292. # See: http://www.ietf.org/rfc/rfc2817.txt
  293. $s = IO::Socket::INET->new(PeerHost => $proxyhost, PeerPort => $proxyport);
  294. die "Socket to $proxyhost: $!\n" unless defined $s;
  295. $s->write("CONNECT $serv:$port HTTP/1.1\r\nHost: $serv:$port\r\n\r\n")
  296. or die "Write to $proxyhost: $!\n";
  297. $s->flush();
  298. $rep = <$s>;
  299. # The answer should look like 'HTTP/1.x 2yy ....'
  300. if (!($rep =~ m#^HTTP/1\.. 2[0-9][0-9]#)) {
  301. die "Proxy connect: $rep\n";
  302. }
  303. # Skip up to the empty line of the proxy server output
  304. # including the response headers.
  305. while ($rep = <$s>) {
  306. last if (!defined $rep ||
  307. $rep eq "\n" ||
  308. $rep eq "\r\n");
  309. }
  310. } else {
  311. $s = IO::Socket::INET->new(PeerHost => $serv, PeerPort => $port);
  312. die "Socket to $serv: $!\n" unless defined $s;
  313. }
  314. $s->write("BEGIN AUTH REQUEST\n$repo\n$user\n$pass\nEND AUTH REQUEST\n")
  315. or die "Write to $serv: $!\n";
  316. $s->flush();
  317. $rep = <$s>;
  318. if ($rep ne "I LOVE YOU\n") {
  319. $rep="<unknown>" unless $rep;
  320. die "AuthReply: $rep\n";
  321. }
  322. $self->{'socketo'} = $s;
  323. $self->{'socketi'} = $s;
  324. } else { # local or ext: Fork off our own cvs server.
  325. my $pr = IO::Pipe->new();
  326. my $pw = IO::Pipe->new();
  327. my $pid = fork();
  328. die "Fork: $!\n" unless defined $pid;
  329. my $cvs = 'cvs';
  330. $cvs = $ENV{CVS_SERVER} if exists $ENV{CVS_SERVER};
  331. my $rsh = 'rsh';
  332. $rsh = $ENV{CVS_RSH} if exists $ENV{CVS_RSH};
  333. my @cvs = ($cvs, 'server');
  334. my ($local, $user, $host);
  335. $local = $repo =~ s/:local://;
  336. if (!$local) {
  337. $repo =~ s/:ext://;
  338. $local = !($repo =~ s/^(?:([^\@:]+)\@)?([^:]+)://);
  339. ($user, $host) = ($1, $2);
  340. }
  341. if (!$local) {
  342. if ($user) {
  343. unshift @cvs, $rsh, '-l', $user, $host;
  344. } else {
  345. unshift @cvs, $rsh, $host;
  346. }
  347. }
  348. unless ($pid) {
  349. $pr->writer();
  350. $pw->reader();
  351. dup2($pw->fileno(),0);
  352. dup2($pr->fileno(),1);
  353. $pr->close();
  354. $pw->close();
  355. exec(@cvs);
  356. }
  357. $pw->writer();
  358. $pr->reader();
  359. $self->{'socketo'} = $pw;
  360. $self->{'socketi'} = $pr;
  361. }
  362. $self->{'socketo'}->write("Root $repo\n");
  363. # Trial and error says that this probably is the minimum set
  364. $self->{'socketo'}->write("Valid-responses ok error Valid-requests Mode M Mbinary E Checked-in Created Updated Merged Removed\n");
  365. $self->{'socketo'}->write("valid-requests\n");
  366. $self->{'socketo'}->flush();
  367. my $rep=$self->readline();
  368. die "Failed to read from server" unless defined $rep;
  369. chomp($rep);
  370. if ($rep !~ s/^Valid-requests\s*//) {
  371. $rep="<unknown>" unless $rep;
  372. die "Expected Valid-requests from server, but got: $rep\n";
  373. }
  374. chomp(my $res=$self->readline());
  375. die "validReply: $res\n" if $res ne "ok";
  376. $self->{'socketo'}->write("UseUnchanged\n") if $rep =~ /\bUseUnchanged\b/;
  377. $self->{'repo'} = $repo;
  378. }
  379. sub readline {
  380. my ($self) = @_;
  381. return $self->{'socketi'}->getline();
  382. }
  383. sub _file {
  384. # Request a file with a given revision.
  385. # Trial and error says this is a good way to do it. :-/
  386. my ($self,$fn,$rev) = @_;
  387. $self->{'socketo'}->write("Argument -N\n") or return undef;
  388. $self->{'socketo'}->write("Argument -P\n") or return undef;
  389. # -kk: Linus' version doesn't use it - defaults to off
  390. if ($opt_k) {
  391. $self->{'socketo'}->write("Argument -kk\n") or return undef;
  392. }
  393. $self->{'socketo'}->write("Argument -r\n") or return undef;
  394. $self->{'socketo'}->write("Argument $rev\n") or return undef;
  395. $self->{'socketo'}->write("Argument --\n") or return undef;
  396. $self->{'socketo'}->write("Argument $self->{'subdir'}/$fn\n") or return undef;
  397. $self->{'socketo'}->write("Directory .\n") or return undef;
  398. $self->{'socketo'}->write("$self->{'repo'}\n") or return undef;
  399. # $self->{'socketo'}->write("Sticky T1.0\n") or return undef;
  400. $self->{'socketo'}->write("co\n") or return undef;
  401. $self->{'socketo'}->flush() or return undef;
  402. $self->{'lines'} = 0;
  403. return 1;
  404. }
  405. sub _line {
  406. # Read a line from the server.
  407. # ... except that 'line' may be an entire file. ;-)
  408. my ($self, $fh) = @_;
  409. die "Not in lines" unless defined $self->{'lines'};
  410. my $line;
  411. my $res=0;
  412. while (defined($line = $self->readline())) {
  413. # M U gnupg-cvs-rep/AUTHORS
  414. # Updated gnupg-cvs-rep/
  415. # /daten/src/rsync/gnupg-cvs-rep/AUTHORS
  416. # /AUTHORS/1.1///T1.1
  417. # u=rw,g=rw,o=rw
  418. # 0
  419. # ok
  420. if ($line =~ s/^(?:Created|Updated) //) {
  421. $line = $self->readline(); # path
  422. $line = $self->readline(); # Entries line
  423. my $mode = $self->readline(); chomp $mode;
  424. $self->{'mode'} = $mode;
  425. defined (my $cnt = $self->readline())
  426. or die "EOF from server after 'Changed'\n";
  427. chomp $cnt;
  428. die "Duh: Filesize $cnt" if $cnt !~ /^\d+$/;
  429. $line="";
  430. $res = $self->_fetchfile($fh, $cnt);
  431. } elsif ($line =~ s/^ //) {
  432. print $fh $line;
  433. $res += length($line);
  434. } elsif ($line =~ /^M\b/) {
  435. # output, do nothing
  436. } elsif ($line =~ /^Mbinary\b/) {
  437. my $cnt;
  438. die "EOF from server after 'Mbinary'" unless defined ($cnt = $self->readline());
  439. chomp $cnt;
  440. die "Duh: Mbinary $cnt" if $cnt !~ /^\d+$/ or $cnt<1;
  441. $line="";
  442. $res += $self->_fetchfile($fh, $cnt);
  443. } else {
  444. chomp $line;
  445. if ($line eq "ok") {
  446. # print STDERR "S: ok (".length($res).")\n";
  447. return $res;
  448. } elsif ($line =~ s/^E //) {
  449. # print STDERR "S: $line\n";
  450. } elsif ($line =~ /^(Remove-entry|Removed) /i) {
  451. $line = $self->readline(); # filename
  452. $line = $self->readline(); # OK
  453. chomp $line;
  454. die "Unknown: $line" if $line ne "ok";
  455. return -1;
  456. } else {
  457. die "Unknown: $line\n";
  458. }
  459. }
  460. }
  461. return undef;
  462. }
  463. sub file {
  464. my ($self,$fn,$rev) = @_;
  465. my $res;
  466. my ($fh, $name) = tempfile('gitcvs.XXXXXX',
  467. DIR => File::Spec->tmpdir(), UNLINK => 1);
  468. $self->_file($fn,$rev) and $res = $self->_line($fh);
  469. if (!defined $res) {
  470. print STDERR "Server has gone away while fetching $fn $rev, retrying...\n";
  471. truncate $fh, 0;
  472. $self->conn();
  473. $self->_file($fn,$rev) or die "No file command send";
  474. $res = $self->_line($fh);
  475. die "Retry failed" unless defined $res;
  476. }
  477. close ($fh);
  478. return ($name, $res);
  479. }
  480. sub _fetchfile {
  481. my ($self, $fh, $cnt) = @_;
  482. my $res = 0;
  483. my $bufsize = 1024 * 1024;
  484. while ($cnt) {
  485. if ($bufsize > $cnt) {
  486. $bufsize = $cnt;
  487. }
  488. my $buf;
  489. my $num = $self->{'socketi'}->read($buf,$bufsize);
  490. die "Server: Filesize $cnt: $num: $!\n" if not defined $num or $num<=0;
  491. print $fh $buf;
  492. $res += $num;
  493. $cnt -= $num;
  494. }
  495. return $res;
  496. }
  497. sub _scramble {
  498. my ($self, $pass) = @_;
  499. my $scrambled = "A";
  500. return $scrambled unless $pass;
  501. my $pass_len = length($pass);
  502. my @pass_arr = split("", $pass);
  503. my $i;
  504. # from cvs/src/scramble.c
  505. my @shifts = (
  506. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  507. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
  508. 114,120, 53, 79, 96,109, 72,108, 70, 64, 76, 67,116, 74, 68, 87,
  509. 111, 52, 75,119, 49, 34, 82, 81, 95, 65,112, 86,118,110,122,105,
  510. 41, 57, 83, 43, 46,102, 40, 89, 38,103, 45, 50, 42,123, 91, 35,
  511. 125, 55, 54, 66,124,126, 59, 47, 92, 71,115, 78, 88,107,106, 56,
  512. 36,121,117,104,101,100, 69, 73, 99, 63, 94, 93, 39, 37, 61, 48,
  513. 58,113, 32, 90, 44, 98, 60, 51, 33, 97, 62, 77, 84, 80, 85,223,
  514. 225,216,187,166,229,189,222,188,141,249,148,200,184,136,248,190,
  515. 199,170,181,204,138,232,218,183,255,234,220,247,213,203,226,193,
  516. 174,172,228,252,217,201,131,230,197,211,145,238,161,179,160,212,
  517. 207,221,254,173,202,146,224,151,140,196,205,130,135,133,143,246,
  518. 192,159,244,239,185,168,215,144,139,165,180,157,147,186,214,176,
  519. 227,231,219,169,175,156,206,198,129,164,150,210,154,177,134,127,
  520. 182,128,158,208,162,132,167,209,149,241,153,251,237,236,171,195,
  521. 243,233,253,240,194,250,191,155,142,137,245,235,163,242,178,152
  522. );
  523. for ($i = 0; $i < $pass_len; $i++) {
  524. $scrambled .= pack("C", $shifts[ord($pass_arr[$i])]);
  525. }
  526. return $scrambled;
  527. }
  528. package main;
  529. my $cvs = CVSconn->new($opt_d, $cvs_tree);
  530. sub pdate($) {
  531. my ($d) = @_;
  532. m#(\d{2,4})/(\d\d)/(\d\d)\s(\d\d):(\d\d)(?::(\d\d))?#
  533. or die "Unparseable date: $d\n";
  534. my $y=$1;
  535. $y+=100 if $y<70;
  536. $y+=1900 if $y<1000;
  537. return timegm($6||0,$5,$4,$3,$2-1,$y);
  538. }
  539. sub pmode($) {
  540. my ($mode) = @_;
  541. my $m = 0;
  542. my $mm = 0;
  543. my $um = 0;
  544. for my $x(split(//,$mode)) {
  545. if ($x eq ",") {
  546. $m |= $mm&$um;
  547. $mm = 0;
  548. $um = 0;
  549. } elsif ($x eq "u") { $um |= 0700;
  550. } elsif ($x eq "g") { $um |= 0070;
  551. } elsif ($x eq "o") { $um |= 0007;
  552. } elsif ($x eq "r") { $mm |= 0444;
  553. } elsif ($x eq "w") { $mm |= 0222;
  554. } elsif ($x eq "x") { $mm |= 0111;
  555. } elsif ($x eq "=") { # do nothing
  556. } else { die "Unknown mode: $mode\n";
  557. }
  558. }
  559. $m |= $mm&$um;
  560. return $m;
  561. }
  562. sub getwd() {
  563. my $pwd = `pwd`;
  564. chomp $pwd;
  565. return $pwd;
  566. }
  567. sub is_sha1 {
  568. my $s = shift;
  569. return $s =~ /^[a-f0-9]{40}$/;
  570. }
  571. sub get_headref ($) {
  572. my $name = shift;
  573. $name =~ s/'/'\\''/g;
  574. my $r = `git rev-parse --verify '$name' 2>/dev/null`;
  575. return undef unless $? == 0;
  576. chomp $r;
  577. return $r;
  578. }
  579. my $user_filename_prepend = '';
  580. sub munge_user_filename {
  581. my $name = shift;
  582. return File::Spec->file_name_is_absolute($name) ?
  583. $name :
  584. $user_filename_prepend . $name;
  585. }
  586. -d $git_tree
  587. or mkdir($git_tree,0777)
  588. or die "Could not create $git_tree: $!";
  589. if ($git_tree ne '.') {
  590. $user_filename_prepend = getwd() . '/';
  591. chdir($git_tree);
  592. }
  593. my $last_branch = "";
  594. my $orig_branch = "";
  595. my %branch_date;
  596. my $tip_at_start = undef;
  597. my $git_dir = $ENV{"GIT_DIR"} || ".git";
  598. $git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
  599. $ENV{"GIT_DIR"} = $git_dir;
  600. my $orig_git_index;
  601. $orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
  602. my %index; # holds filenames of one index per branch
  603. unless (-d $git_dir) {
  604. system(qw(git init));
  605. die "Cannot init the GIT db at $git_tree: $?\n" if $?;
  606. system(qw(git read-tree --empty));
  607. die "Cannot init an empty tree: $?\n" if $?;
  608. $last_branch = $opt_o;
  609. $orig_branch = "";
  610. } else {
  611. open(F, "-|", qw(git symbolic-ref HEAD)) or
  612. die "Cannot run git symbolic-ref: $!\n";
  613. chomp ($last_branch = <F>);
  614. $last_branch = basename($last_branch);
  615. close(F);
  616. unless ($last_branch) {
  617. warn "Cannot read the last branch name: $! -- assuming 'master'\n";
  618. $last_branch = "master";
  619. }
  620. $orig_branch = $last_branch;
  621. $tip_at_start = `git rev-parse --verify HEAD`;
  622. # Get the last import timestamps
  623. my $fmt = '($ref, $author) = (%(refname), %(author));';
  624. my @cmd = ('git', 'for-each-ref', '--perl', "--format=$fmt", $remote);
  625. open(H, "-|", @cmd) or die "Cannot run git for-each-ref: $!\n";
  626. while (defined(my $entry = <H>)) {
  627. my ($ref, $author);
  628. eval($entry) || die "cannot eval refs list: $@";
  629. my ($head) = ($ref =~ m|^$remote/(.*)|);
  630. $author =~ /^.*\s(\d+)\s[-+]\d{4}$/;
  631. $branch_date{$head} = $1;
  632. }
  633. close(H);
  634. if (!exists $branch_date{$opt_o}) {
  635. die "Branch '$opt_o' does not exist.\n".
  636. "Either use the correct '-o branch' option,\n".
  637. "or import to a new repository.\n";
  638. }
  639. }
  640. -d $git_dir
  641. or die "Could not create git subdir ($git_dir).\n";
  642. # now we read (and possibly save) author-info as well
  643. -f "$git_dir/cvs-authors" and
  644. read_author_info("$git_dir/cvs-authors");
  645. if ($opt_A) {
  646. read_author_info(munge_user_filename($opt_A));
  647. write_author_info("$git_dir/cvs-authors");
  648. }
  649. # open .git/cvs-revisions, if requested
  650. open my $revision_map, '>>', "$git_dir/cvs-revisions"
  651. or die "Can't open $git_dir/cvs-revisions for appending: $!\n"
  652. if defined $opt_R;
  653. #
  654. # run cvsps into a file unless we are getting
  655. # it passed as a file via $opt_P
  656. #
  657. my $cvspsfile;
  658. unless ($opt_P) {
  659. print "Running cvsps...\n" if $opt_v;
  660. my $pid = open(CVSPS,"-|");
  661. my $cvspsfh;
  662. die "Cannot fork: $!\n" unless defined $pid;
  663. unless ($pid) {
  664. my @opt;
  665. @opt = split(/,/,$opt_p) if defined $opt_p;
  666. unshift @opt, '-z', $opt_z if defined $opt_z;
  667. unshift @opt, '-q' unless defined $opt_v;
  668. unless (defined($opt_p) && $opt_p =~ m/--no-cvs-direct/) {
  669. push @opt, '--cvs-direct';
  670. }
  671. exec("cvsps","--norc",@opt,"-u","-A",'--root',$opt_d,$cvs_tree);
  672. die "Could not start cvsps: $!\n";
  673. }
  674. ($cvspsfh, $cvspsfile) = tempfile('gitXXXXXX', SUFFIX => '.cvsps',
  675. DIR => File::Spec->tmpdir());
  676. while (<CVSPS>) {
  677. print $cvspsfh $_;
  678. }
  679. close CVSPS;
  680. $? == 0 or die "git cvsimport: fatal: cvsps reported error\n";
  681. close $cvspsfh;
  682. } else {
  683. $cvspsfile = munge_user_filename($opt_P);
  684. }
  685. open(CVS, "<$cvspsfile") or die $!;
  686. ## cvsps output:
  687. #---------------------
  688. #PatchSet 314
  689. #Date: 1999/09/18 13:03:59
  690. #Author: wkoch
  691. #Branch: STABLE-BRANCH-1-0
  692. #Ancestor branch: HEAD
  693. #Tag: (none)
  694. #Log:
  695. # See ChangeLog: Sat Sep 18 13:03:28 CEST 1999 Werner Koch
  696. #Members:
  697. # README:1.57->1.57.2.1
  698. # VERSION:1.96->1.96.2.1
  699. #
  700. #---------------------
  701. my $state = 0;
  702. sub update_index (\@\@) {
  703. my $old = shift;
  704. my $new = shift;
  705. open(my $fh, '|-', qw(git update-index -z --index-info))
  706. or die "unable to open git update-index: $!";
  707. print $fh
  708. (map { "0 0000000000000000000000000000000000000000\t$_\0" }
  709. @$old),
  710. (map { '100' . sprintf('%o', $_->[0]) . " $_->[1]\t$_->[2]\0" }
  711. @$new)
  712. or die "unable to write to git update-index: $!";
  713. close $fh
  714. or die "unable to write to git update-index: $!";
  715. $? and die "git update-index reported error: $?";
  716. }
  717. sub write_tree () {
  718. open(my $fh, '-|', qw(git write-tree))
  719. or die "unable to open git write-tree: $!";
  720. chomp(my $tree = <$fh>);
  721. is_sha1($tree)
  722. or die "Cannot get tree id ($tree): $!";
  723. close($fh)
  724. or die "Error running git write-tree: $?\n";
  725. print "Tree ID $tree\n" if $opt_v;
  726. return $tree;
  727. }
  728. my ($patchset,$date,$author_name,$author_email,$author_tz,$branch,$ancestor,$tag,$logmsg);
  729. my (@old,@new,@skipped,%ignorebranch,@commit_revisions);
  730. # commits that cvsps cannot place anywhere...
  731. $ignorebranch{'#CVSPS_NO_BRANCH'} = 1;
  732. sub commit {
  733. if ($branch eq $opt_o && !$index{branch} &&
  734. !get_headref("$remote/$branch")) {
  735. # looks like an initial commit
  736. # use the index primed by git init
  737. $ENV{GIT_INDEX_FILE} = "$git_dir/index";
  738. $index{$branch} = "$git_dir/index";
  739. } else {
  740. # use an index per branch to speed up
  741. # imports of projects with many branches
  742. unless ($index{$branch}) {
  743. $index{$branch} = tmpnam();
  744. $ENV{GIT_INDEX_FILE} = $index{$branch};
  745. if ($ancestor) {
  746. system("git", "read-tree", "$remote/$ancestor");
  747. } else {
  748. system("git", "read-tree", "$remote/$branch");
  749. }
  750. die "read-tree failed: $?\n" if $?;
  751. }
  752. }
  753. $ENV{GIT_INDEX_FILE} = $index{$branch};
  754. update_index(@old, @new);
  755. @old = @new = ();
  756. my $tree = write_tree();
  757. my $parent = get_headref("$remote/$last_branch");
  758. print "Parent ID " . ($parent ? $parent : "(empty)") . "\n" if $opt_v;
  759. my @commit_args;
  760. push @commit_args, ("-p", $parent) if $parent;
  761. # loose detection of merges
  762. # based on the commit msg
  763. foreach my $rx (@mergerx) {
  764. next unless $logmsg =~ $rx && $1;
  765. my $mparent = $1 eq 'HEAD' ? $opt_o : $1;
  766. if (my $sha1 = get_headref("$remote/$mparent")) {
  767. push @commit_args, '-p', "$remote/$mparent";
  768. print "Merge parent branch: $mparent\n" if $opt_v;
  769. }
  770. }
  771. set_timezone($author_tz);
  772. # $date is in the seconds since epoch format
  773. my $tz_offset = get_tz_offset($date);
  774. my $commit_date = "$date $tz_offset";
  775. set_timezone('UTC');
  776. $ENV{GIT_AUTHOR_NAME} = $author_name;
  777. $ENV{GIT_AUTHOR_EMAIL} = $author_email;
  778. $ENV{GIT_AUTHOR_DATE} = $commit_date;
  779. $ENV{GIT_COMMITTER_NAME} = $author_name;
  780. $ENV{GIT_COMMITTER_EMAIL} = $author_email;
  781. $ENV{GIT_COMMITTER_DATE} = $commit_date;
  782. my $pid = open2(my $commit_read, my $commit_write,
  783. 'git', 'commit-tree', $tree, @commit_args);
  784. # compatibility with git2cvs
  785. substr($logmsg,32767) = "" if length($logmsg) > 32767;
  786. $logmsg =~ s/[\s\n]+\z//;
  787. if (@skipped) {
  788. $logmsg .= "\n\n\nSKIPPED:\n\t";
  789. $logmsg .= join("\n\t", @skipped) . "\n";
  790. @skipped = ();
  791. }
  792. print($commit_write "$logmsg\n") && close($commit_write)
  793. or die "Error writing to git commit-tree: $!\n";
  794. print "Committed patch $patchset ($branch $commit_date)\n" if $opt_v;
  795. chomp(my $cid = <$commit_read>);
  796. is_sha1($cid) or die "Cannot get commit id ($cid): $!\n";
  797. print "Commit ID $cid\n" if $opt_v;
  798. close($commit_read);
  799. waitpid($pid,0);
  800. die "Error running git commit-tree: $?\n" if $?;
  801. system('git' , 'update-ref', "$remote/$branch", $cid) == 0
  802. or die "Cannot write branch $branch for update: $!\n";
  803. if ($revision_map) {
  804. print $revision_map "@$_ $cid\n" for @commit_revisions;
  805. }
  806. @commit_revisions = ();
  807. if ($tag) {
  808. my ($xtag) = $tag;
  809. $xtag =~ s/\s+\*\*.*$//; # Remove stuff like ** INVALID ** and ** FUNKY **
  810. $xtag =~ tr/_/\./ if ( $opt_u );
  811. $xtag =~ s/[\/]/$opt_s/g;
  812. # See refs.c for these rules.
  813. # Tag cannot contain bad chars. (See bad_ref_char in refs.c.)
  814. $xtag =~ s/[ ~\^:\\\*\?\[]//g;
  815. # Other bad strings for tags:
  816. # (See check_refname_component in refs.c.)
  817. 1 while $xtag =~ s/
  818. (?: \.\. # Tag cannot contain '..'.
  819. | \@\{ # Tag cannot contain '@{'.
  820. | ^ - # Tag cannot begin with '-'.
  821. | \.lock $ # Tag cannot end with '.lock'.
  822. | ^ \. # Tag cannot begin...
  823. | \. $ # ...or end with '.'
  824. )//xg;
  825. # Tag cannot be empty.
  826. if ($xtag eq '') {
  827. warn("warning: ignoring tag '$tag'",
  828. " with invalid tagname\n");
  829. return;
  830. }
  831. if (system('git' , 'tag', '-f', $xtag, $cid) != 0) {
  832. # We did our best to sanitize the tag, but still failed
  833. # for whatever reason. Bail out, and give the user
  834. # enough information to understand if/how we should
  835. # improve the translation in the future.
  836. if ($tag ne $xtag) {
  837. print "Translated '$tag' tag to '$xtag'\n";
  838. }
  839. die "Cannot create tag $xtag: $!\n";
  840. }
  841. print "Created tag '$xtag' on '$branch'\n" if $opt_v;
  842. }
  843. };
  844. my $commitcount = 1;
  845. while (<CVS>) {
  846. chomp;
  847. if ($state == 0 and /^-+$/) {
  848. $state = 1;
  849. } elsif ($state == 0) {
  850. $state = 1;
  851. redo;
  852. } elsif (($state==0 or $state==1) and s/^PatchSet\s+//) {
  853. $patchset = 0+$_;
  854. $state=2;
  855. } elsif ($state == 2 and s/^Date:\s+//) {
  856. $date = pdate($_);
  857. unless ($date) {
  858. print STDERR "Could not parse date: $_\n";
  859. $state=0;
  860. next;
  861. }
  862. $state=3;
  863. } elsif ($state == 3 and s/^Author:\s+//) {
  864. $author_tz = "UTC";
  865. s/\s+$//;
  866. if (/^(.*?)\s+<(.*)>/) {
  867. ($author_name, $author_email) = ($1, $2);
  868. } elsif ($conv_author_name{$_}) {
  869. $author_name = $conv_author_name{$_};
  870. $author_email = $conv_author_email{$_};
  871. $author_tz = $conv_author_tz{$_} if ($conv_author_tz{$_});
  872. } else {
  873. $author_name = $author_email = $_;
  874. }
  875. $state = 4;
  876. } elsif ($state == 4 and s/^Branch:\s+//) {
  877. s/\s+$//;
  878. tr/_/\./ if ( $opt_u );
  879. s/[\/]/$opt_s/g;
  880. $branch = $_;
  881. $state = 5;
  882. } elsif ($state == 5 and s/^Ancestor branch:\s+//) {
  883. s/\s+$//;
  884. $ancestor = $_;
  885. $ancestor = $opt_o if $ancestor eq "HEAD";
  886. $state = 6;
  887. } elsif ($state == 5) {
  888. $ancestor = undef;
  889. $state = 6;
  890. redo;
  891. } elsif ($state == 6 and s/^Tag:\s+//) {
  892. s/\s+$//;
  893. if ($_ eq "(none)") {
  894. $tag = undef;
  895. } else {
  896. $tag = $_;
  897. }
  898. $state = 7;
  899. } elsif ($state == 7 and /^Log:/) {
  900. $logmsg = "";
  901. $state = 8;
  902. } elsif ($state == 8 and /^Members:/) {
  903. $branch = $opt_o if $branch eq "HEAD";
  904. if (defined $branch_date{$branch} and $branch_date{$branch} >= $date) {
  905. # skip
  906. print "skip patchset $patchset: $date before $branch_date{$branch}\n" if $opt_v;
  907. $state = 11;
  908. next;
  909. }
  910. if (!$opt_a && $starttime - 300 - (defined $opt_z ? $opt_z : 300) <= $date) {
  911. # skip if the commit is too recent
  912. # given that the cvsps default fuzz is 300s, we give ourselves another
  913. # 300s just in case -- this also prevents skipping commits
  914. # due to server clock drift
  915. print "skip patchset $patchset: $date too recent\n" if $opt_v;
  916. $state = 11;
  917. next;
  918. }
  919. if (exists $ignorebranch{$branch}) {
  920. print STDERR "Skipping $branch\n";
  921. $state = 11;
  922. next;
  923. }
  924. if ($ancestor) {
  925. if ($ancestor eq $branch) {
  926. print STDERR "Branch $branch erroneously stems from itself -- changed ancestor to $opt_o\n";
  927. $ancestor = $opt_o;
  928. }
  929. if (defined get_headref("$remote/$branch")) {
  930. print STDERR "Branch $branch already exists!\n";
  931. $state=11;
  932. next;
  933. }
  934. my $id = get_headref("$remote/$ancestor");
  935. if (!$id) {
  936. print STDERR "Branch $ancestor does not exist!\n";
  937. $ignorebranch{$branch} = 1;
  938. $state=11;
  939. next;
  940. }
  941. system(qw(git update-ref -m cvsimport),
  942. "$remote/$branch", $id);
  943. if($? != 0) {
  944. print STDERR "Could not create branch $branch\n";
  945. $ignorebranch{$branch} = 1;
  946. $state=11;
  947. next;
  948. }
  949. }
  950. $last_branch = $branch if $branch ne $last_branch;
  951. $state = 9;
  952. } elsif ($state == 8) {
  953. $logmsg .= "$_\n";
  954. } elsif ($state == 9 and /^\s+(.+?):(INITIAL|\d+(?:\.\d+)+)->(\d+(?:\.\d+)+)\s*$/) {
  955. # VERSION:1.96->1.96.2.1
  956. my $init = ($2 eq "INITIAL");
  957. my $fn = $1;
  958. my $rev = $3;
  959. $fn =~ s#^/+##;
  960. if ($opt_S && $fn =~ m/$opt_S/) {
  961. print "SKIPPING $fn v $rev\n";
  962. push(@skipped, $fn);
  963. next;
  964. }
  965. push @commit_revisions, [$fn, $rev];
  966. print "Fetching $fn v $rev\n" if $opt_v;
  967. my ($tmpname, $size) = $cvs->file($fn,$rev);
  968. if ($size == -1) {
  969. push(@old,$fn);
  970. print "Drop $fn\n" if $opt_v;
  971. } else {
  972. print "".($init ? "New" : "Update")." $fn: $size bytes\n" if $opt_v;
  973. my $pid = open(my $F, '-|');
  974. die $! unless defined $pid;
  975. if (!$pid) {
  976. exec("git", "hash-object", "-w", $tmpname)
  977. or die "Cannot create object: $!\n";
  978. }
  979. my $sha = <$F>;
  980. chomp $sha;
  981. close $F;
  982. my $mode = pmode($cvs->{'mode'});
  983. push(@new,[$mode, $sha, $fn]); # may be resurrected!
  984. }
  985. unlink($tmpname);
  986. } elsif ($state == 9 and /^\s+(.+?):\d+(?:\.\d+)+->(\d+(?:\.\d+)+)\(DEAD\)\s*$/) {
  987. my $fn = $1;
  988. my $rev = $2;
  989. $fn =~ s#^/+##;
  990. push @commit_revisions, [$fn, $rev];
  991. push(@old,$fn);
  992. print "Delete $fn\n" if $opt_v;
  993. } elsif ($state == 9 and /^\s*$/) {
  994. $state = 10;
  995. } elsif (($state == 9 or $state == 10) and /^-+$/) {
  996. $commitcount++;
  997. if ($opt_L && $commitcount > $opt_L) {
  998. last;
  999. }
  1000. commit();
  1001. if (($commitcount & 1023) == 0) {
  1002. system(qw(git repack -a -d));
  1003. }
  1004. $state = 1;
  1005. } elsif ($state == 11 and /^-+$/) {
  1006. $state = 1;
  1007. } elsif (/^-+$/) { # end of unknown-line processing
  1008. $state = 1;
  1009. } elsif ($state != 11) { # ignore stuff when skipping
  1010. print STDERR "* UNKNOWN LINE * $_\n";
  1011. }
  1012. }
  1013. commit() if $branch and $state != 11;
  1014. unless ($opt_P) {
  1015. unlink($cvspsfile);
  1016. }
  1017. # The heuristic of repacking every 1024 commits can leave a
  1018. # lot of unpacked data. If there is more than 1MB worth of
  1019. # not-packed objects, repack once more.
  1020. my $line = `git count-objects`;
  1021. if ($line =~ /^(\d+) objects, (\d+) kilobytes$/) {
  1022. my ($n_objects, $kb) = ($1, $2);
  1023. 1024 < $kb
  1024. and system(qw(git repack -a -d));
  1025. }
  1026. foreach my $git_index (values %index) {
  1027. if ($git_index ne "$git_dir/index") {
  1028. unlink($git_index);
  1029. }
  1030. }
  1031. if (defined $orig_git_index) {
  1032. $ENV{GIT_INDEX_FILE} = $orig_git_index;
  1033. } else {
  1034. delete $ENV{GIT_INDEX_FILE};
  1035. }
  1036. # Now switch back to the branch we were in before all of this happened
  1037. if ($orig_branch) {
  1038. print "DONE.\n" if $opt_v;
  1039. if ($opt_i) {
  1040. exit 0;
  1041. }
  1042. my $tip_at_end = `git rev-parse --verify HEAD`;
  1043. if ($tip_at_start ne $tip_at_end) {
  1044. for ($tip_at_start, $tip_at_end) { chomp; }
  1045. print "Fetched into the current branch.\n" if $opt_v;
  1046. system(qw(git read-tree -u -m),
  1047. $tip_at_start, $tip_at_end);
  1048. die "Fast-forward update failed: $?\n" if $?;
  1049. }
  1050. else {
  1051. system(qw(git merge -m cvsimport), "$remote/$opt_o");
  1052. die "Could not merge $opt_o into the current branch.\n" if $?;
  1053. }
  1054. } else {
  1055. $orig_branch = "master";
  1056. print "DONE; creating $orig_branch branch\n" if $opt_v;
  1057. system("git", "update-ref", "refs/heads/master", "$remote/$opt_o")
  1058. unless defined get_headref('refs/heads/master');
  1059. system("git", "symbolic-ref", "$remote/HEAD", "$remote/$opt_o")
  1060. if ($opt_r && $opt_o ne 'HEAD');
  1061. system('git', 'update-ref', 'HEAD', "$orig_branch");
  1062. unless ($opt_i) {
  1063. system(qw(git checkout -f));
  1064. die "checkout failed: $?\n" if $?;
  1065. }
  1066. }