svn import: typo fix
[git.git] / git-svnimport.perl
blob821f51f105903c5241dcf8a55092dc6ed3fc76b3
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_l = 100 unless defined $opt_l;
57 my $git_tree = $opt_C;
58 $git_tree ||= ".";
60 my $cvs_tree;
61 if ($#ARGV == 0) {
62 $cvs_tree = $ARGV[0];
63 } elsif (-f 'CVS/Repository') {
64 open my $f, '<', 'CVS/Repository' or
65 die 'Failed to open CVS/Repository';
66 $cvs_tree = <$f>;
67 chomp $cvs_tree;
68 close $f;
69 } else {
70 usage();
73 our @mergerx = ();
74 if ($opt_m) {
75 @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
77 if ($opt_M) {
78 push (@mergerx, qr/$opt_M/);
81 select(STDERR); $|=1; select(STDOUT);
84 package SVNconn;
85 # Basic SVN connection.
86 # We're only interested in connecting and downloading, so ...
88 use File::Spec;
89 use File::Temp qw(tempfile);
90 use POSIX qw(strftime dup2);
92 sub new {
93 my($what,$repo) = @_;
94 $what=ref($what) if ref($what);
96 my $self = {};
97 $self->{'buffer'} = "";
98 bless($self,$what);
100 $repo =~ s#/+$##;
101 $self->{'fullrep'} = $repo;
102 $self->conn();
104 return $self;
107 sub conn {
108 my $self = shift;
109 my $repo = $self->{'fullrep'};
110 my $s = SVN::Ra->new($repo);
112 die "SVN connection to $repo: $!\n" unless defined $s;
113 $self->{'svn'} = $s;
114 $self->{'repo'} = $repo;
115 $self->{'maxrev'} = $s->get_latest_revnum();
118 sub file {
119 my($self,$path,$rev) = @_;
120 my $res;
122 my ($fh, $name) = tempfile('gitsvn.XXXXXX',
123 DIR => File::Spec->tmpdir(), UNLINK => 1);
125 print "... $rev $path ...\n" if $opt_v;
126 eval { $self->{'svn'}->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); };
132 return () if $@ and $@ !~ /Attempted to get checksum/;
133 die $@ if $@;
134 close ($fh);
136 return ($name, $res);
140 package main;
142 my $svn = SVNconn->new($cvs_tree);
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);
153 sub getwd() {
154 my $pwd = `pwd`;
155 chomp $pwd;
156 return $pwd;
160 sub get_headref($$) {
161 my $name = shift;
162 my $git_dir = shift;
163 my $sha;
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";
171 return $sha;
175 -d $git_tree
176 or mkdir($git_tree,0777)
177 or die "Could not create $git_tree: $!";
178 chdir($git_tree);
180 my $orig_branch = "";
181 my $forward_master = 0;
182 my %branches;
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 = $opt_s ? ($opt_s-1) : 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 $?;
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";
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";
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
227 git-read-tree -m -u SVN2GIT_HEAD HEAD
230 system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
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;
237 # populate index
238 system('git-read-tree', $last_rev);
239 die "read-tree failed: $?\n" if $?;
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 if $current_rev < $num;
250 close($B);
252 -d $git_dir
253 or die "Could not create git subdir ($git_dir).\n";
255 open BRANCHES,">>", "$git_dir/svn2git";
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
272 #---------------------
274 my $state = 0;
276 sub get_file($$$) {
277 my($rev,$branch,$path) = @_;
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";
290 # now get it
291 my ($name, $res) = eval { $svn->file($svnpath,$rev); };
292 return () unless defined $name;
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 unlink $name;
300 my $mode = "0644"; # SV does not seem to store any file modes
301 return [$mode, $sha, $path];
304 sub split_path($$) {
305 my($rev,$path) = @_;
306 my $branch;
308 if($path =~ s#^/\Q$tag_name\E/([^/]+)/?##) {
309 $branch = "/$1";
310 } elsif($path =~ s#^/\Q$trunk_name\E/?##) {
311 $branch = "/";
312 } elsif($path =~ s#^/\Q$branch_name\E/([^/]+)/?##) {
313 $branch = $1;
314 } else {
315 print STDERR "$rev: Unrecognized path: $path\n";
316 return ()
318 $path = "/" if $path eq "";
319 return ($branch,$path);
322 sub commit {
323 my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
324 my($author_name,$author_email,$dest);
325 my(@old,@new);
327 if (not defined $author) {
328 $author_name = $author_email = "unknown";
329 } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
330 ($author_name, $author_email) = ($1, $2);
331 } else {
332 $author =~ s/^<(.*)>$/$1/;
333 $author_name = $author_email = $author;
335 $date = pdate($date);
337 my $tag;
338 my $parent;
339 if($branch eq "/") { # trunk
340 $parent = $opt_o;
341 } elsif($branch =~ m#^/(.+)#) { # tag
342 $tag = 1;
343 $parent = $1;
344 } else { # "normal" branch
345 # nothing to do
346 $parent = $branch;
348 $dest = $parent;
350 my $prev = $changed_paths->{"/"};
351 if($prev and $prev->[0] eq "A") {
352 delete $changed_paths->{"/"};
353 my $oldpath = $prev->[1];
354 my $rev;
355 if(defined $oldpath) {
356 my $p;
357 ($parent,$p) = split_path($revision,$oldpath);
358 if($parent eq "/") {
359 $parent = $opt_o;
360 } else {
361 $parent =~ s#^/##; # if it's a tag
363 } else {
364 $parent = undef;
368 my $rev;
369 if($revision > $opt_s and defined $parent) {
370 open(H,"git-rev-parse --verify $parent |");
371 $rev = <H>;
372 close(H) or do {
373 print STDERR "$revision: cannot find commit '$parent'!\n";
374 return;
376 chop $rev;
377 if(length($rev) != 40) {
378 print STDERR "$revision: cannot find commit '$parent'!\n";
379 return;
381 $rev = $branches{($parent eq $opt_o) ? "/" : $parent}{"LAST"};
382 if($revision != $opt_s and not $rev) {
383 print STDERR "$revision: do not know ancestor for '$parent'!\n";
384 return;
386 } else {
387 $rev = undef;
390 # if($prev and $prev->[0] eq "A") {
391 # if(not $tag) {
392 # unless(open(H,"> $git_dir/refs/heads/$branch")) {
393 # print STDERR "$revision: Could not create branch $branch: $!\n";
394 # $state=11;
395 # next;
397 # print H "$rev\n"
398 # or die "Could not write branch $branch: $!";
399 # close(H)
400 # or die "Could not write branch $branch: $!";
403 if(not defined $rev) {
404 unlink($git_index);
405 } elsif ($rev ne $last_rev) {
406 print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
407 system("git-read-tree", $rev);
408 die "read-tree failed for $rev: $?\n" if $?;
409 $last_rev = $rev;
412 my $cid;
413 if($tag and not %$changed_paths) {
414 $cid = $rev;
415 } else {
416 while(my($path,$action) = each %$changed_paths) {
417 if ($action->[0] eq "A") {
418 my $f = get_file($revision,$branch,$path);
419 push(@new,$f) if $f;
420 } elsif ($action->[0] eq "D") {
421 push(@old,$path);
422 } elsif ($action->[0] eq "M") {
423 my $f = get_file($revision,$branch,$path);
424 push(@new,$f) if $f;
425 } elsif ($action->[0] eq "R") {
426 # refer to a file/tree in an earlier commit
427 push(@old,$path); # remove any old stuff
429 # ... and add any new stuff
430 my($b,$p) = split_path($revision,$action->[1]);
431 open my $F,"-|","git-ls-tree","-r","-z", $branches{$b}{$action->[2]}, $p;
432 local $/ = '\0';
433 while(<$F>) {
434 chomp;
435 my($m,$p) = split(/\t/,$_,2);
436 my($mode,$type,$sha1) = split(/ /,$m);
437 next if $type ne "blob";
438 push(@new,[$mode,$sha1,$p]);
440 } else {
441 die "$revision: unknown action '".$action->[0]."' for $path\n";
445 if(@old) {
446 open my $F, "-|", "git-ls-files", "-z", @old or die $!;
447 @old = ();
448 local $/ = '\0';
449 while(<$F>) {
450 chomp;
451 push(@old,$_);
453 close($F);
455 while(@old) {
456 my @o2;
457 if(@old > 55) {
458 @o2 = splice(@old,0,50);
459 } else {
460 @o2 = @old;
461 @old = ();
463 system("git-update-index","--force-remove","--",@o2);
464 die "Cannot remove files: $?\n" if $?;
467 while(@new) {
468 my @n2;
469 if(@new > 12) {
470 @n2 = splice(@new,0,10);
471 } else {
472 @n2 = @new;
473 @new = ();
475 system("git-update-index","--add",
476 (map { ('--cacheinfo', @$_) } @n2));
477 die "Cannot add files: $?\n" if $?;
480 my $pid = open(C,"-|");
481 die "Cannot fork: $!" unless defined $pid;
482 unless($pid) {
483 exec("git-write-tree");
484 die "Cannot exec git-write-tree: $!\n";
486 chomp(my $tree = <C>);
487 length($tree) == 40
488 or die "Cannot get tree id ($tree): $!\n";
489 close(C)
490 or die "Error running git-write-tree: $?\n";
491 print "Tree ID $tree\n" if $opt_v;
493 my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
494 my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
495 $pid = fork();
496 die "Fork: $!\n" unless defined $pid;
497 unless($pid) {
498 $pr->writer();
499 $pw->reader();
500 open(OUT,">&STDOUT");
501 dup2($pw->fileno(),0);
502 dup2($pr->fileno(),1);
503 $pr->close();
504 $pw->close();
506 my @par = ();
507 @par = ("-p",$rev) if defined $rev;
509 # loose detection of merges
510 # based on the commit msg
511 foreach my $rx (@mergerx) {
512 if ($message =~ $rx) {
513 my $mparent = $1;
514 if ($mparent eq 'HEAD') { $mparent = $opt_o };
515 if ( -e "$git_dir/refs/heads/$mparent") {
516 $mparent = get_headref($mparent, $git_dir);
517 push @par, '-p', $mparent;
518 print OUT "Merge parent branch: $mparent\n" if $opt_v;
523 exec("env",
524 "GIT_AUTHOR_NAME=$author_name",
525 "GIT_AUTHOR_EMAIL=$author_email",
526 "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
527 "GIT_COMMITTER_NAME=$author_name",
528 "GIT_COMMITTER_EMAIL=$author_email",
529 "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
530 "git-commit-tree", $tree,@par);
531 die "Cannot exec git-commit-tree: $!\n";
533 $pw->writer();
534 $pr->reader();
536 $message =~ s/[\s\n]+\z//;
538 print $pw "$message\n"
539 or die "Error writing to git-commit-tree: $!\n";
540 $pw->close();
542 print "Committed change $revision:$branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
543 chomp($cid = <$pr>);
544 length($cid) == 40
545 or die "Cannot get commit id ($cid): $!\n";
546 print "Commit ID $cid\n" if $opt_v;
547 $pr->close();
549 waitpid($pid,0);
550 die "Error running git-commit-tree: $?\n" if $?;
553 if(not defined $dest) {
554 print "... no known parent\n" if $opt_v;
555 } elsif(not $tag) {
556 print "Writing to refs/heads/$dest\n" if $opt_v;
557 open(C,">$git_dir/refs/heads/$dest") and
558 print C ("$cid\n") and
559 close(C)
560 or die "Cannot write branch $dest for update: $!\n";
563 if($tag) {
564 my($in, $out) = ('','');
565 $last_rev = "-" if %$changed_paths;
566 # the tag was 'complex', i.e. did not refer to a "real" revision
568 $dest =~ tr/_/\./ if $opt_u;
570 my $pid = open2($in, $out, 'git-mktag');
571 print $out ("object $cid\n".
572 "type commit\n".
573 "tag $dest\n".
574 "tagger $author_name <$author_email>\n") and
575 close($out)
576 or die "Cannot create tag object $dest: $!\n";
578 my $tagobj = <$in>;
579 chomp $tagobj;
581 if ( !close($in) or waitpid($pid, 0) != $pid or
582 $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
583 die "Cannot create tag object $dest: $!\n";
586 open(C,">$git_dir/refs/tags/$dest") and
587 print C ("$tagobj\n") and
588 close(C)
589 or die "Cannot create tag $branch: $!\n";
591 print "Created tag '$dest' on '$branch'\n" if $opt_v;
593 $branches{$branch}{"LAST"} = $cid;
594 $branches{$branch}{$revision} = $cid;
595 $last_rev = $cid;
596 print BRANCHES "$revision $branch $cid\n";
597 print "DONE: $revision $dest $cid\n" if $opt_v;
600 my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
601 sub _commit_all {
602 ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
603 my %p;
604 while(my($path,$action) = each %$changed_paths) {
605 $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev ];
607 $changed_paths = \%p;
610 sub commit_all {
611 my %done;
612 my @col;
613 my $pref;
614 my $branch;
616 while(my($path,$action) = each %$changed_paths) {
617 ($branch,$path) = split_path($revision,$path);
618 next if not defined $branch;
619 $done{$branch}{$path} = $action;
621 while(($branch,$changed_paths) = each %done) {
622 commit($branch, $changed_paths, $revision, $author, $date, $message);
626 while(++$current_rev <= $svn->{'maxrev'}) {
627 $svn->{'svn'}->get_log("/",$current_rev,$current_rev,$current_rev,1,1,\&_commit_all,"");
628 commit_all();
629 if($opt_l and not --$opt_l) {
630 print STDERR "Exiting due to a memory leak. Repeat, please.\n";
631 last;
636 unlink($git_index);
638 if (defined $orig_git_index) {
639 $ENV{GIT_INDEX_FILE} = $orig_git_index;
640 } else {
641 delete $ENV{GIT_INDEX_FILE};
644 # Now switch back to the branch we were in before all of this happened
645 if($orig_branch) {
646 print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
647 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
648 if $forward_master;
649 unless ($opt_i) {
650 system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
651 die "read-tree failed: $?\n" if $?;
653 } else {
654 $orig_branch = "master";
655 print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
656 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
657 unless -f "$git_dir/refs/heads/master";
658 unlink("$git_dir/HEAD");
659 symlink("refs/heads/$orig_branch","$git_dir/HEAD");
660 unless ($opt_i) {
661 system('git checkout');
662 die "checkout failed: $?\n" if $?;
665 unlink("$git_dir/SVN2GIT_HEAD");
666 close(BRANCHES);