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