svn import: make -s option actually optional
[git/dscho.git] / git-svnimport.perl
blob0462c31f7ec56ebc950112517480a9db73503013
1 #!/usr/bin/perl -w
3 # This tool is copyright (c) 2005, Matthias Urlichs.
4 # It is released under the Gnu Public License, version 2.
6 # The basic idea is to pull and analyze SVN changes.
8 # Checking out the files is done by a single long-running CVS connection
9 # / server process.
11 # The head revision is on branch "origin" by default.
12 # You can change that with the '-o' option.
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;
29 die "Need CVN:Core 1.2.1 or better" if $SVN::Core::VERSION lt "1.2.1";
31 $SIG{'PIPE'}="IGNORE";
32 $ENV{'TZ'}="UTC";
34 our($opt_h,$opt_o,$opt_v,$opt_u,$opt_C,$opt_i,$opt_m,$opt_M,$opt_t,$opt_T,$opt_b,$opt_s,$opt_l);
36 sub usage() {
37 print STDERR <<END;
38 Usage: ${\basename $0} # fetch/update GIT from CVS
39 [-o branch-for-HEAD] [-h] [-v] [-l max_num_changes]
40 [-C GIT_repository] [-t tagname] [-T trunkname] [-b branchname]
41 [-i] [-u] [-s start_chg] [-m] [-M regex] [SVN_URL]
42 END
43 exit(1);
46 getopts("b:C:hil:mM:o:s:t:T:uv") or usage();
47 usage if $opt_h;
49 my $tag_name = $opt_t || "tags";
50 my $trunk_name = $opt_T || "trunk";
51 my $branch_name = $opt_b || "branches";
53 @ARGV <= 1 or usage();
55 $opt_o ||= "origin";
56 $opt_s ||= 1;
57 $opt_l = 100 unless defined $opt_l;
58 my $git_tree = $opt_C;
59 $git_tree ||= ".";
61 my $cvs_tree;
62 if ($#ARGV == 0) {
63 $cvs_tree = $ARGV[0];
64 } elsif (-f 'CVS/Repository') {
65 open my $f, '<', 'CVS/Repository' or
66 die 'Failed to open CVS/Repository';
67 $cvs_tree = <$f>;
68 chomp $cvs_tree;
69 close $f;
70 } else {
71 usage();
74 our @mergerx = ();
75 if ($opt_m) {
76 @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
78 if ($opt_M) {
79 push (@mergerx, qr/$opt_M/);
82 select(STDERR); $|=1; select(STDOUT);
85 package SVNconn;
86 # Basic SVN connection.
87 # We're only interested in connecting and downloading, so ...
89 use File::Spec;
90 use File::Temp qw(tempfile);
91 use POSIX qw(strftime dup2);
93 sub new {
94 my($what,$repo) = @_;
95 $what=ref($what) if ref($what);
97 my $self = {};
98 $self->{'buffer'} = "";
99 bless($self,$what);
101 $repo =~ s#/+$##;
102 $self->{'fullrep'} = $repo;
103 $self->conn();
105 return $self;
108 sub conn {
109 my $self = shift;
110 my $repo = $self->{'fullrep'};
111 my $s = SVN::Ra->new($repo);
113 die "SVN connection to $repo: $!\n" unless defined $s;
114 $self->{'svn'} = $s;
115 $self->{'repo'} = $repo;
116 $self->{'maxrev'} = $s->get_latest_revnum();
119 sub file {
120 my($self,$path,$rev) = @_;
121 my $res;
123 my ($fh, $name) = tempfile('gitsvn.XXXXXX',
124 DIR => File::Spec->tmpdir(), UNLINK => 1);
126 print "... $rev $path ...\n" if $opt_v;
127 eval { $self->{'svn'}->get_file($path,$rev,$fh); };
128 if ($@ and $@ !~ /Attempted to get checksum/) {
129 # retry
130 $self->conn();
131 eval { $self->{'svn'}->get_file($path,$rev,$fh); };
133 return () if $@ and $@ !~ /Attempted to get checksum/;
134 die $@ if $@;
135 close ($fh);
137 return ($name, $res);
141 package main;
143 my $svn = SVNconn->new($cvs_tree);
146 sub pdate($) {
147 my($d) = @_;
148 $d =~ m#(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)#
149 or die "Unparseable date: $d\n";
150 my $y=$1; $y-=1900 if $y>1900;
151 return timegm($6||0,$5,$4,$3,$2-1,$y);
154 sub getwd() {
155 my $pwd = `pwd`;
156 chomp $pwd;
157 return $pwd;
161 sub get_headref($$) {
162 my $name = shift;
163 my $git_dir = shift;
164 my $sha;
166 if (open(C,"$git_dir/refs/heads/$name")) {
167 chomp($sha = <C>);
168 close(C);
169 length($sha) == 40
170 or die "Cannot get head id for $name ($sha): $!\n";
172 return $sha;
176 -d $git_tree
177 or mkdir($git_tree,0777)
178 or die "Could not create $git_tree: $!";
179 chdir($git_tree);
181 my $orig_branch = "";
182 my $forward_master = 0;
183 my %branches;
185 my $git_dir = $ENV{"GIT_DIR"} || ".git";
186 $git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
187 $ENV{"GIT_DIR"} = $git_dir;
188 my $orig_git_index;
189 $orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
190 my ($git_ih, $git_index) = tempfile('gitXXXXXX', SUFFIX => '.idx',
191 DIR => File::Spec->tmpdir());
192 close ($git_ih);
193 $ENV{GIT_INDEX_FILE} = $git_index;
194 my $maxnum = 0;
195 my $last_rev = "";
196 my $last_branch;
197 my $current_rev = $opt_s-1;
198 unless(-d $git_dir) {
199 system("git-init-db");
200 die "Cannot init the GIT db at $git_tree: $?\n" if $?;
201 system("git-read-tree");
202 die "Cannot init an empty tree: $?\n" if $?;
204 $last_branch = $opt_o;
205 $orig_branch = "";
206 } else {
207 -f "$git_dir/refs/heads/$opt_o"
208 or die "Branch '$opt_o' does not exist.\n".
209 "Either use the correct '-o branch' option,\n".
210 "or import to a new repository.\n";
212 -f "$git_dir/svn2git"
213 or die "'$git_dir/svn2git' does not exist.\n".
214 "You need that file for incremental imports.\n";
215 $last_branch = basename(readlink("$git_dir/HEAD"));
216 unless($last_branch) {
217 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
218 $last_branch = "master";
220 $orig_branch = $last_branch;
221 $last_rev = get_headref($orig_branch, $git_dir);
222 if (-f "$git_dir/SVN2GIT_HEAD") {
223 die <<EOM;
224 SVN2GIT_HEAD exists.
225 Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
226 You may need to run
228 git-read-tree -m -u SVN2GIT_HEAD HEAD
231 system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
233 $forward_master =
234 $opt_o ne 'master' && -f "$git_dir/refs/heads/master" &&
235 system('cmp', '-s', "$git_dir/refs/heads/master",
236 "$git_dir/refs/heads/$opt_o") == 0;
238 # populate index
239 system('git-read-tree', $last_rev);
240 die "read-tree failed: $?\n" if $?;
242 # Get the last import timestamps
243 open my $B,"<", "$git_dir/svn2git";
244 while(<$B>) {
245 chomp;
246 my($num,$branch,$ref) = split;
247 $branches{$branch}{$num} = $ref;
248 $branches{$branch}{"LAST"} = $ref;
249 $current_rev = $num if $current_rev < $num;
251 close($B);
253 -d $git_dir
254 or die "Could not create git subdir ($git_dir).\n";
256 open BRANCHES,">>", "$git_dir/svn2git";
259 ## cvsps output:
260 #---------------------
261 #PatchSet 314
262 #Date: 1999/09/18 13:03:59
263 #Author: wkoch
264 #Branch: STABLE-BRANCH-1-0
265 #Ancestor branch: HEAD
266 #Tag: (none)
267 #Log:
268 # See ChangeLog: Sat Sep 18 13:03:28 CEST 1999 Werner Koch
269 #Members:
270 # README:1.57->1.57.2.1
271 # VERSION:1.96->1.96.2.1
273 #---------------------
275 my $state = 0;
277 sub get_file($$$) {
278 my($rev,$branch,$path) = @_;
280 # revert split_path(), below
281 my $svnpath;
282 $path = "" if $path eq "/"; # this should not happen, but ...
283 if($branch eq "/") {
284 $svnpath = "/$trunk_name/$path";
285 } elsif($branch =~ m#^/#) {
286 $svnpath = "/$tag_name$branch/$path";
287 } else {
288 $svnpath = "/$branch_name/$branch/$path";
291 # now get it
292 my ($name, $res) = eval { $svn->file($svnpath,$rev); };
293 return () unless defined $name;
295 open my $F, '-|', "git-hash-object", "-w", $name
296 or die "Cannot create object: $!\n";
297 my $sha = <$F>;
298 chomp $sha;
299 close $F;
300 unlink $name;
301 my $mode = "0644"; # SV does not seem to store any file modes
302 return [$mode, $sha, $path];
305 sub split_path($$) {
306 my($rev,$path) = @_;
307 my $branch;
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 ()
319 $path = "/" if $path eq "";
320 return ($branch,$path);
323 sub commit {
324 my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
325 my($author_name,$author_email,$dest);
326 my(@old,@new);
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;
336 $date = pdate($date);
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;
349 $dest = $parent;
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
364 } else {
365 $parent = undef;
369 my $rev;
370 if($revision > $opt_s and 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;
377 chop $rev;
378 if(length($rev) != 40) {
379 print STDERR "$revision: cannot find commit '$parent'!\n";
380 return;
382 $rev = $branches{($parent eq $opt_o) ? "/" : $parent}{"LAST"};
383 if($revision != $opt_s and not $rev) {
384 print STDERR "$revision: do not know ancestor for '$parent'!\n";
385 return;
387 } else {
388 $rev = undef;
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;
398 # print H "$rev\n"
399 # or die "Could not write branch $branch: $!";
400 # close(H)
401 # or die "Could not write branch $branch: $!";
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;
413 my $cid;
414 if($tag and not %$changed_paths) {
415 $cid = $rev;
416 } else {
417 while(my($path,$action) = each %$changed_paths) {
418 if ($action->[0] eq "A") {
419 my $f = get_file($revision,$branch,$path);
420 push(@new,$f) if $f;
421 } elsif ($action->[0] eq "D") {
422 push(@old,$path);
423 } elsif ($action->[0] eq "M") {
424 my $f = get_file($revision,$branch,$path);
425 push(@new,$f) if $f;
426 } elsif ($action->[0] eq "R") {
427 # refer to a file/tree in an earlier commit
428 push(@old,$path); # remove any old stuff
430 # ... and add any new stuff
431 my($b,$p) = split_path($revision,$action->[1]);
432 open my $F,"-|","git-ls-tree","-r","-z", $branches{$b}{$action->[2]}, $p;
433 local $/ = '\0';
434 while(<$F>) {
435 chomp;
436 my($m,$p) = split(/\t/,$_,2);
437 my($mode,$type,$sha1) = split(/ /,$m);
438 next if $type ne "blob";
439 push(@new,[$mode,$sha1,$p]);
441 } else {
442 die "$revision: unknown action '".$action->[0]."' for $path\n";
446 if(@old) {
447 open my $F, "-|", "git-ls-files", "-z", @old or die $!;
448 @old = ();
449 local $/ = '\0';
450 while(<$F>) {
451 chomp;
452 push(@old,$_);
454 close($F);
456 while(@old) {
457 my @o2;
458 if(@old > 55) {
459 @o2 = splice(@old,0,50);
460 } else {
461 @o2 = @old;
462 @old = ();
464 system("git-update-index","--force-remove","--",@o2);
465 die "Cannot remove files: $?\n" if $?;
468 while(@new) {
469 my @n2;
470 if(@new > 12) {
471 @n2 = splice(@new,0,10);
472 } else {
473 @n2 = @new;
474 @new = ();
476 system("git-update-index","--add",
477 (map { ('--cacheinfo', @$_) } @n2));
478 die "Cannot add files: $?\n" if $?;
481 my $pid = open(C,"-|");
482 die "Cannot fork: $!" unless defined $pid;
483 unless($pid) {
484 exec("git-write-tree");
485 die "Cannot exec git-write-tree: $!\n";
487 chomp(my $tree = <C>);
488 length($tree) == 40
489 or die "Cannot get tree id ($tree): $!\n";
490 close(C)
491 or die "Error running git-write-tree: $?\n";
492 print "Tree ID $tree\n" if $opt_v;
494 my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
495 my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
496 $pid = fork();
497 die "Fork: $!\n" unless defined $pid;
498 unless($pid) {
499 $pr->writer();
500 $pw->reader();
501 open(OUT,">&STDOUT");
502 dup2($pw->fileno(),0);
503 dup2($pr->fileno(),1);
504 $pr->close();
505 $pw->close();
507 my @par = ();
508 @par = ("-p",$rev) if defined $rev;
510 # loose detection of merges
511 # based on the commit msg
512 foreach my $rx (@mergerx) {
513 if ($message =~ $rx) {
514 my $mparent = $1;
515 if ($mparent eq 'HEAD') { $mparent = $opt_o };
516 if ( -e "$git_dir/refs/heads/$mparent") {
517 $mparent = get_headref($mparent, $git_dir);
518 push @par, '-p', $mparent;
519 print OUT "Merge parent branch: $mparent\n" if $opt_v;
524 exec("env",
525 "GIT_AUTHOR_NAME=$author_name",
526 "GIT_AUTHOR_EMAIL=$author_email",
527 "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
528 "GIT_COMMITTER_NAME=$author_name",
529 "GIT_COMMITTER_EMAIL=$author_email",
530 "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
531 "git-commit-tree", $tree,@par);
532 die "Cannot exec git-commit-tree: $!\n";
534 $pw->writer();
535 $pr->reader();
537 $message =~ s/[\s\n]+\z//;
539 print $pw "$message\n"
540 or die "Error writing to git-commit-tree: $!\n";
541 $pw->close();
543 print "Committed change $revision:$branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
544 chomp($cid = <$pr>);
545 length($cid) == 40
546 or die "Cannot get commit id ($cid): $!\n";
547 print "Commit ID $cid\n" if $opt_v;
548 $pr->close();
550 waitpid($pid,0);
551 die "Error running git-commit-tree: $?\n" if $?;
554 if(not defined $dest) {
555 print "... no known parent\n" if $opt_v;
556 } elsif(not $tag) {
557 print "Writing to refs/heads/$dest\n" if $opt_v;
558 open(C,">$git_dir/refs/heads/$dest") and
559 print C ("$cid\n") and
560 close(C)
561 or die "Cannot write branch $dest for update: $!\n";
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
569 $dest =~ tr/_/\./ if $opt_u;
571 my $pid = open2($in, $out, 'git-mktag');
572 print $out ("object $cid\n".
573 "type commit\n".
574 "tag $dest\n".
575 "tagger $author_name <$author_email>\n") and
576 close($out)
577 or die "Cannot create tag object $dest: $!\n";
579 my $tagobj = <$in>;
580 chomp $tagobj;
582 if ( !close($in) or waitpid($pid, 0) != $pid or
583 $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
584 die "Cannot create tag object $dest: $!\n";
587 open(C,">$git_dir/refs/tags/$dest") and
588 print C ("$tagobj\n") and
589 close(C)
590 or die "Cannot create tag $branch: $!\n";
592 print "Created tag '$dest' on '$branch'\n" if $opt_v;
594 $branches{$branch}{"LAST"} = $cid;
595 $branches{$branch}{$revision} = $cid;
596 $last_rev = $cid;
597 print BRANCHES "$revision $branch $cid\n";
598 print "DONE: $revision $dest $cid\n" if $opt_v;
601 my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
602 sub _commit_all {
603 ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
604 my %p;
605 while(my($path,$action) = each %$changed_paths) {
606 $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev ];
608 $changed_paths = \%p;
611 sub commit_all {
612 my %done;
613 my @col;
614 my $pref;
615 my $branch;
617 while(my($path,$action) = each %$changed_paths) {
618 ($branch,$path) = split_path($revision,$path);
619 next if not defined $branch;
620 $done{$branch}{$path} = $action;
622 while(($branch,$changed_paths) = each %done) {
623 commit($branch, $changed_paths, $revision, $author, $date, $message);
627 while(++$current_rev <= $svn->{'maxrev'}) {
628 $svn->{'svn'}->get_log("/",$current_rev,$current_rev,$current_rev,1,1,\&_commit_all,"");
629 commit_all();
630 if($opt_l and not --$opt_l) {
631 print STDERR "Exiting due to a memory leak. Repeat, please.\n";
632 last;
637 unlink($git_index);
639 if (defined $orig_git_index) {
640 $ENV{GIT_INDEX_FILE} = $orig_git_index;
641 } else {
642 delete $ENV{GIT_INDEX_FILE};
645 # Now switch back to the branch we were in before all of this happened
646 if($orig_branch) {
647 print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
648 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
649 if $forward_master;
650 unless ($opt_i) {
651 system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
652 die "read-tree failed: $?\n" if $?;
654 } else {
655 $orig_branch = "master";
656 print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
657 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
658 unless -f "$git_dir/refs/heads/master";
659 unlink("$git_dir/HEAD");
660 symlink("refs/heads/$orig_branch","$git_dir/HEAD");
661 unless ($opt_i) {
662 system('git checkout');
663 die "checkout failed: $?\n" if $?;
666 unlink("$git_dir/SVN2GIT_HEAD");
667 close(BRANCHES);