svn import: wrong file open mode
[git.git] / git-svnimport.perl
1 #!/usr/bin/perl -w
2
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 pull and analyze SVN changes.
7 #
8 # Checking out the files is done by a single long-running CVS connection
9 # / server process.
10 #
11 # The head revision is on branch "origin" by default.
12 # You can change that with the '-o' option.
13
14 require v5.8.0; # for shell-safe open("-|",LIST)
15 use strict;
16 use warnings;
17 use Getopt::Std;
18 use File::Spec;
19 use File::Temp qw(tempfile);
20 use File::Path qw(mkpath);
21 use File::Basename qw(basename dirname);
22 use Time::Local;
23 use IO::Pipe;
24 use POSIX qw(strftime dup2);
25 use IPC::Open2;
26 use SVN::Core;
27 use SVN::Ra;
28
29 die "Need CVN:COre 1.2.1 or better" if $SVN::Core::VERSION lt "1.2.1";
30
31 $SIG{'PIPE'}="IGNORE";
32 $ENV{'TZ'}="UTC";
33
34 our($opt_h,$opt_o,$opt_v,$opt_u,$opt_C,$opt_i,$opt_m,$opt_M,$opt_t,$opt_T,$opt_b);
35
36 sub usage() {
37         print STDERR <<END;
38 Usage: ${\basename $0}     # fetch/update GIT from CVS
39        [-o branch-for-HEAD] [-h] [-v]
40        [-C GIT_repository] [-t tagname] [-T trunkname] [-b branchname]
41        [-i] [-u] [-s subst] [-m] [-M regex] [SVN_URL]
42 END
43         exit(1);
44 }
45
46 getopts("b:C:hivmM:o:t:T:u") or usage();
47 usage if $opt_h;
48
49 my $tag_name = $opt_t || "tags";
50 my $trunk_name = $opt_T || "trunk";
51 my $branch_name = $opt_b || "branches";
52
53 @ARGV <= 1 or usage();
54
55 $opt_o ||= "origin";
56 my $git_tree = $opt_C;
57 $git_tree ||= ".";
58
59 my $cvs_tree;
60 if ($#ARGV == 0) {
61         $cvs_tree = $ARGV[0];
62 } elsif (-f 'CVS/Repository') {
63         open my $f, '<', 'CVS/Repository' or 
64             die 'Failed to open CVS/Repository';
65         $cvs_tree = <$f>;
66         chomp $cvs_tree;
67         close $f;
68 } else {
69         usage();
70 }
71
72 our @mergerx = ();
73 if ($opt_m) {
74         @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
75 }
76 if ($opt_M) {
77         push (@mergerx, qr/$opt_M/);
78 }
79
80 select(STDERR); $|=1; select(STDOUT);
81
82
83 package SVNconn;
84 # Basic SVN connection.
85 # We're only interested in connecting and downloading, so ...
86
87 use File::Spec;
88 use File::Temp qw(tempfile);
89 use POSIX qw(strftime dup2);
90
91 sub new {
92         my($what,$repo) = @_;
93         $what=ref($what) if ref($what);
94
95         my $self = {};
96         $self->{'buffer'} = "";
97         bless($self,$what);
98
99         $repo =~ s#/+$##;
100         $self->{'fullrep'} = $repo;
101         $self->conn();
102
103         return $self;
104 }
105
106 sub conn {
107         my $self = shift;
108         my $repo = $self->{'fullrep'};
109         my $s = SVN::Ra->new($repo);
110
111         die "SVN connection to $repo: $!\n" unless defined $s;
112         $self->{'svn'} = $s;
113         print STDERR "*** SVN *** $s ***\n";
114         $self->{'repo'} = $repo;
115         $self->{'maxrev'} = $s->get_latest_revnum();
116 }
117
118 sub file {
119         my($self,$path,$rev) = @_;
120         my $res;
121
122         my ($fh, $name) = tempfile('gitsvn.XXXXXX', 
123                     DIR => File::Spec->tmpdir(), UNLINK => 1);
124
125         print "... $rev $path ...\n" if $opt_v;
126         my $s = $self->{'svn'};
127         print STDERR "*** GET *** $s ***\n";
128         eval { $s->get_file($path,$rev,$fh); };
129         if ($@ and $@ !~ /Attempted to get checksum/) {
130             # retry
131             $self->conn();
132                 eval { $self->{'svn'}->get_file($path,$rev,$fh); };
133         };
134         return () if $@ and $@ !~ /Attempted to get checksum/;
135         die $@ if $@;
136         close ($fh);
137
138         return ($name, $res);
139 }
140
141
142 package main;
143
144 my $svn = SVNconn->new($cvs_tree);
145
146
147 sub pdate($) {
148         my($d) = @_;
149         $d =~ m#(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)#
150                 or die "Unparseable date: $d\n";
151         my $y=$1; $y-=1900 if $y>1900;
152         return timegm($6||0,$5,$4,$3,$2-1,$y);
153 }
154
155 sub getwd() {
156         my $pwd = `pwd`;
157         chomp $pwd;
158         return $pwd;
159 }
160
161
162 sub get_headref($$) {
163     my $name    = shift;
164     my $git_dir = shift; 
165     my $sha;
166     
167     if (open(C,"$git_dir/refs/heads/$name")) {
168         chomp($sha = <C>);
169         close(C);
170         length($sha) == 40
171             or die "Cannot get head id for $name ($sha): $!\n";
172     }
173     return $sha;
174 }
175
176
177 -d $git_tree
178         or mkdir($git_tree,0777)
179         or die "Could not create $git_tree: $!";
180 chdir($git_tree);
181
182 my $orig_branch = "";
183 my $forward_master = 0;
184 my %branches;
185
186 my $git_dir = $ENV{"GIT_DIR"} || ".git";
187 $git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
188 $ENV{"GIT_DIR"} = $git_dir;
189 my $orig_git_index;
190 $orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
191 my ($git_ih, $git_index) = tempfile('gitXXXXXX', SUFFIX => '.idx',
192                                     DIR => File::Spec->tmpdir());
193 close ($git_ih);
194 $ENV{GIT_INDEX_FILE} = $git_index;
195 my $maxnum = 0;
196 my $last_rev = "";
197 my $last_branch;
198 my $current_rev = 0;
199 unless(-d $git_dir) {
200         system("git-init-db");
201         die "Cannot init the GIT db at $git_tree: $?\n" if $?;
202         system("git-read-tree");
203         die "Cannot init an empty tree: $?\n" if $?;
204
205         $last_branch = $opt_o;
206         $orig_branch = "";
207 } else {
208         -f "$git_dir/refs/heads/$opt_o"
209                 or die "Branch '$opt_o' does not exist.\n".
210                        "Either use the correct '-o branch' option,\n".
211                        "or import to a new repository.\n";
212
213         -f "$git_dir/svn2git"
214                 or die "'$git_dir/svn2git' does not exist.\n".
215                        "You need that file for incremental imports.\n";
216         $last_branch = basename(readlink("$git_dir/HEAD"));
217         unless($last_branch) {
218                 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
219                 $last_branch = "master";
220         }
221         $orig_branch = $last_branch;
222         $last_rev = get_headref($orig_branch, $git_dir);
223         if (-f "$git_dir/SVN2GIT_HEAD") {
224                 die <<EOM;
225 SVN2GIT_HEAD exists.
226 Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
227 You may need to run
228
229     git-read-tree -m -u SVN2GIT_HEAD HEAD
230 EOM
231         }
232         system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
233
234         $forward_master =
235             $opt_o ne 'master' && -f "$git_dir/refs/heads/master" &&
236             system('cmp', '-s', "$git_dir/refs/heads/master", 
237                                 "$git_dir/refs/heads/$opt_o") == 0;
238
239         # populate index
240         system('git-read-tree', $last_rev);
241         die "read-tree failed: $?\n" if $?;
242
243         # Get the last import timestamps
244         open my $B,"<", "$git_dir/svn2git";
245         while(<$B>) {
246                 chomp;
247                 my($num,$branch,$ref) = split;
248                 $branches{$branch}{$num} = $ref;
249                 $branches{$branch}{"LAST"} = $ref;
250                 $current_rev = $num+1 if $current_rev < $num+1;
251         }
252         close($B);
253 }
254 -d $git_dir
255         or die "Could not create git subdir ($git_dir).\n";
256
257 open BRANCHES,">>", "$git_dir/svn2git";
258
259
260 ## cvsps output:
261 #---------------------
262 #PatchSet 314
263 #Date: 1999/09/18 13:03:59
264 #Author: wkoch
265 #Branch: STABLE-BRANCH-1-0
266 #Ancestor branch: HEAD
267 #Tag: (none)
268 #Log:
269 #    See ChangeLog: Sat Sep 18 13:03:28 CEST 1999  Werner Koch
270 #Members:
271 #       README:1.57->1.57.2.1
272 #       VERSION:1.96->1.96.2.1
273 #
274 #---------------------
275
276 my $state = 0;
277
278 sub get_file($$$) {
279         my($rev,$branch,$path) = @_;
280
281         # revert split_path(), below
282         my $svnpath;
283         $path = "" if $path eq "/"; # this should not happen, but ...
284         if($branch eq "/") {
285                 $svnpath = "/$trunk_name/$path";
286         } elsif($branch =~ m#^/#) {
287                 $svnpath = "/$tag_name$branch/$path";
288         } else {
289                 $svnpath = "/$branch_name/$branch/$path";
290         }
291
292         # now get it
293         my ($name, $res) = eval { $svn->file($svnpath,$rev); };
294         return () unless defined $name;
295
296         open my $F, '-|', "git-hash-object", "-w", $name
297                 or die "Cannot create object: $!\n";
298         my $sha = <$F>;
299         chomp $sha;
300         close $F;
301         my $mode = "0644"; # SV does not seem to store any file modes
302         return [$mode, $sha, $path];
303 }
304
305 sub split_path($$) {
306         my($rev,$path) = @_;
307         my $branch;
308
309         if($path =~ s#^/\Q$tag_name\E/([^/]+)/?##) {
310                 $branch = "/$1";
311         } elsif($path =~ s#^/\Q$trunk_name\E/?##) {
312                 $branch = "/";
313         } elsif($path =~ s#^/\Q$branch_name\E/([^/]+)/?##) {
314                 $branch = $1;
315         } else {
316                 print STDERR "$rev: Unrecognized path: $path\n";
317                 return ()
318         }
319         $path = "/" if $path eq "";
320         return ($branch,$path);
321 }
322
323 sub commit {
324         my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
325         my($author_name,$author_email,$dest);
326         my(@old,@new);
327
328         if (not defined $author) {
329                 $author_name = $author_email = "unknown";
330         } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
331                 ($author_name, $author_email) = ($1, $2);
332         } else {
333                 $author =~ s/^<(.*)>$/$1/;
334                 $author_name = $author_email = $author;
335         }
336         $date = pdate($date);
337
338         my $tag;
339         my $parent;
340         if($branch eq "/") { # trunk
341                 $parent = $opt_o;
342         } elsif($branch =~ m#^/(.+)#) { # tag
343                 $tag = 1;
344                 $parent = $1;
345         } else { # "normal" branch
346                 # nothing to do
347                 $parent = $branch;
348         }
349         $dest = $parent;
350
351         my $prev = $changed_paths->{"/"};
352         if($prev and $prev->[0] eq "A") {
353                 delete $changed_paths->{"/"};
354                 my $oldpath = $prev->[1];
355                 my $rev;
356                 if(defined $oldpath) {
357                         my $p;
358                         ($parent,$p) = split_path($revision,$oldpath);
359                         if($parent eq "/") {
360                                 $parent = $opt_o;
361                         } else {
362                                 $parent =~ s#^/##; # if it's a tag
363                         }
364                 } else {
365                         $parent = undef;
366                 }
367         }
368
369         my $rev;
370         if(defined $parent) {
371                 open(H,"git-rev-parse --verify $parent |");
372                 $rev = <H>;
373                 close(H) or do {
374                         print STDERR "$revision: cannot find commit '$parent'!\n";
375                         return;
376                 };
377                 chop $rev;
378                 if(length($rev) != 40) {
379                         print STDERR "$revision: cannot find commit '$parent'!\n";
380                         return;
381                 }
382                 $rev = $branches{($parent eq $opt_o) ? "/" : $parent}{"LAST"};
383                 if($revision != 1 and not $rev) {
384                         print STDERR "$revision: do not know ancestor for '$parent'!\n";
385                         return;
386                 }
387         } else {
388                 $rev = undef;
389         }
390
391 #       if($prev and $prev->[0] eq "A") {
392 #               if(not $tag) {
393 #                       unless(open(H,"> $git_dir/refs/heads/$branch")) {
394 #                               print STDERR "$revision: Could not create branch $branch: $!\n";
395 #                               $state=11;
396 #                               next;
397 #                       }
398 #                       print H "$rev\n"
399 #                               or die "Could not write branch $branch: $!";
400 #                       close(H)
401 #                               or die "Could not write branch $branch: $!";
402 #               }
403 #       }
404         if(not defined $rev) {
405                 unlink($git_index);
406         } elsif ($rev ne $last_rev) {
407                 print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
408                 system("git-read-tree", $rev);
409                 die "read-tree failed for $rev: $?\n" if $?;
410                 $last_rev = $rev;
411         }
412
413         while(my($path,$action) = each %$changed_paths) {
414                 if ($action->[0] eq "A") {
415                         my $f = get_file($revision,$branch,$path);
416                         push(@new,$f) if $f;
417                 } elsif ($action->[0] eq "D") {
418                         push(@old,$path);
419                 } elsif ($action->[0] eq "M") {
420                         my $f = get_file($revision,$branch,$path);
421                         push(@new,$f) if $f;
422                 } elsif ($action->[0] eq "R") {
423                         # refer to a file/tree in an earlier commit
424                         push(@old,$path); # remove any old stuff
425
426                         # ... and add any new stuff
427                         my($b,$p) = split_path($revision,$action->[1]);
428                         open my $F,"-|","git-ls-tree","-r","-z", $branches{$b}{$action->[2]}, $p;
429                         local $/ = '\0';
430                         while(<$F>) {
431                                 chomp;
432                                 my($m,$p) = split(/\t/,$_,2);
433                                 my($mode,$type,$sha1) = split(/ /,$m);
434                                 next if $type ne "blob";
435                                 push(@new,[$mode,$sha1,$p]);
436                         }
437                 } else {
438                         die "$revision: unknown action '".$action->[0]."' for $path\n";
439                 }
440         }
441
442         if(@old) {
443                 open my $F, "-|", "git-ls-files", "-z", @old or die $!;
444                 @old = ();
445                 local $/ = '\0';
446                 while(<$F>) {
447                         chomp;
448                         push(@old,$_);
449                 }
450                 close($F);
451
452                 while(@old) {
453                         my @o2;
454                         if(@old > 55) {
455                                 @o2 = splice(@old,0,50);
456                         } else {
457                                 @o2 = @old;
458                                 @old = ();
459                         }
460                         system("git-update-index","--force-remove","--",@o2);
461                         die "Cannot remove files: $?\n" if $?;
462                 }
463         }
464         while(@new) {
465                 my @n2;
466                 if(@new > 12) {
467                         @n2 = splice(@new,0,10);
468                 } else {
469                         @n2 = @new;
470                         @new = ();
471                 }
472                 system("git-update-index","--add",
473                         (map { ('--cacheinfo', @$_) } @n2));
474                 die "Cannot add files: $?\n" if $?;
475         }
476
477         my $pid = open(C,"-|");
478         die "Cannot fork: $!" unless defined $pid;
479         unless($pid) {
480                 exec("git-write-tree");
481                 die "Cannot exec git-write-tree: $!\n";
482         }
483         chomp(my $tree = <C>);
484         length($tree) == 40
485                 or die "Cannot get tree id ($tree): $!\n";
486         close(C)
487                 or die "Error running git-write-tree: $?\n";
488         print "Tree ID $tree\n" if $opt_v;
489
490         my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
491         my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
492         $pid = fork();
493         die "Fork: $!\n" unless defined $pid;
494         unless($pid) {
495                 $pr->writer();
496                 $pw->reader();
497                 open(OUT,">&STDOUT");
498                 dup2($pw->fileno(),0);
499                 dup2($pr->fileno(),1);
500                 $pr->close();
501                 $pw->close();
502
503                 my @par = ();
504                 @par = ("-p",$rev) if defined $rev;
505
506                 # loose detection of merges
507                 # based on the commit msg
508                 foreach my $rx (@mergerx) {
509                         if ($message =~ $rx) {
510                                 my $mparent = $1;
511                                 if ($mparent eq 'HEAD') { $mparent = $opt_o };
512                                 if ( -e "$git_dir/refs/heads/$mparent") {
513                                         $mparent = get_headref($mparent, $git_dir);
514                                         push @par, '-p', $mparent;
515                                         print OUT "Merge parent branch: $mparent\n" if $opt_v;
516                                 }
517                         } 
518                 }
519
520                 exec("env",
521                         "GIT_AUTHOR_NAME=$author_name",
522                         "GIT_AUTHOR_EMAIL=$author_email",
523                         "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
524                         "GIT_COMMITTER_NAME=$author_name",
525                         "GIT_COMMITTER_EMAIL=$author_email",
526                         "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
527                         "git-commit-tree", $tree,@par);
528                 die "Cannot exec git-commit-tree: $!\n";
529         }
530         $pw->writer();
531         $pr->reader();
532
533         $message =~ s/[\s\n]+\z//;
534
535         print $pw "$message\n"
536                 or die "Error writing to git-commit-tree: $!\n";
537         $pw->close();
538
539         print "Committed change $revision:$branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
540         chomp(my $cid = <$pr>);
541         length($cid) == 40
542                 or die "Cannot get commit id ($cid): $!\n";
543         print "Commit ID $cid\n" if $opt_v;
544         $pr->close();
545
546         waitpid($pid,0);
547         die "Error running git-commit-tree: $?\n" if $?;
548
549         if(defined $dest) {
550                 print "Writing to refs/heads/$dest\n" if $opt_v;
551                 open(C,">$git_dir/refs/heads/$dest") and 
552                 print C ("$cid\n") and
553                 close(C)
554                         or die "Cannot write branch $dest for update: $!\n";
555         } else {
556                 print "... no known parent\n" if $opt_v;
557         }
558         $branches{$branch}{"LAST"} = $cid;
559         $branches{$branch}{$revision} = $cid;
560         $last_rev = $cid;
561         print BRANCHES "$revision $branch $cid\n";
562         print "DONE: $revision $dest $cid\n" if $opt_v;
563
564         if($tag) {
565                 my($in, $out) = ('','');
566                 $last_rev = "-" if %$changed_paths;
567                 # the tag was 'complex', i.e. did not refer to a "real" revision
568                 
569                 $tag =~ tr/_/\./ if $opt_u;
570
571                 my $pid = open2($in, $out, 'git-mktag');
572                 print $out ("object $cid\n".
573                     "type commit\n".
574                     "tag $tag\n".
575                     "tagger $author_name <$author_email>\n") and
576                 close($out)
577                     or die "Cannot create tag object $tag: $!\n";
578
579                 my $tagobj = <$in>;
580                 chomp $tagobj;
581
582                 if ( !close($in) or waitpid($pid, 0) != $pid or
583                                 $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
584                         die "Cannot create tag object $tag: $!\n";
585                 }
586                 
587
588                 open(C,">$git_dir/refs/tags/$tag")
589                         or die "Cannot create tag $tag: $!\n";
590                 print C "$tagobj\n"
591                         or die "Cannot write tag $tag: $!\n";
592                 close(C)
593                         or die "Cannot write tag $tag: $!\n";
594
595                 print "Created tag '$tag' on '$branch'\n" if $opt_v;
596         }
597 }
598
599 my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
600 sub _commit_all {
601         ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
602         my %p;
603         while(my($path,$action) = each %$changed_paths) {
604                 $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev ];
605         }
606         $changed_paths = \%p;
607 }
608
609 sub commit_all {
610         my %done;
611         my @col;
612         my $pref;
613         my $branch;
614
615         while(my($path,$action) = each %$changed_paths) {
616                 ($branch,$path) = split_path($revision,$path);
617                 next if not defined $branch;
618                 $done{$branch}{$path} = $action;
619         }
620         while(($branch,$changed_paths) = each %done) {
621                 commit($branch, $changed_paths, $revision, $author, $date, $message);
622         }
623 }
624
625 while(++$current_rev < $svn->{'maxrev'}) {
626         $svn->{'svn'}->get_log("/",$current_rev,$current_rev,$current_rev,1,1,\&_commit_all,"");
627         commit_all();
628 }
629
630
631 unlink($git_index);
632
633 if (defined $orig_git_index) {
634         $ENV{GIT_INDEX_FILE} = $orig_git_index;
635 } else {
636         delete $ENV{GIT_INDEX_FILE};
637 }
638
639 # Now switch back to the branch we were in before all of this happened
640 if($orig_branch) {
641         print "DONE\n" if $opt_v;
642         system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
643                 if $forward_master;
644         unless ($opt_i) {
645                 system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
646                 die "read-tree failed: $?\n" if $?;
647         }
648 } else {
649         $orig_branch = "master";
650         print "DONE; creating $orig_branch branch\n" if $opt_v;
651         system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
652                 unless -f "$git_dir/refs/heads/master";
653         unlink("$git_dir/HEAD");
654         symlink("refs/heads/$orig_branch","$git_dir/HEAD");
655         unless ($opt_i) {
656                 system('git checkout');
657                 die "checkout failed: $?\n" if $?;
658         }
659 }
660 unlink("$git_dir/SVN2GIT_HEAD");
661 close(BRANCHES);